text
stringlengths
54
60.6k
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "Downloads.h" /* system headers */ #include <map> /* common implementation headers */ #include "network.h" #include "Address.h" #include "AccessList.h" #include "CacheManager.h" #include "BzMaterial.h" #include "URLManager.h" #include "AnsiCodes.h" #include "TextureManager.h" /* local implementation headers */ #include "playing.h" #include "HUDDialogStack.h" // FIXME - someone write a better explanation static const char DownloadContent[] = "#\n" "# This file controls the access to servers for downloads.\n" "# Patterns are attempted in order against both the hostname\n" "# and ip. The first matching pattern sets the state. If no\n" "# patterns are matched, then the server is authorized. There\n" "# are four types of matches:\n" "#\n" "# simple globbing (* and ?)\n" "# allow\n" "# deny\n" "#\n" "# regular expressions\n" "# allow_regex\n" "# deny_regex\n" "#\n" "\n" "#\n" "# To authorize all servers, remove the last 3 lines.\n" "#\n" "\n" "allow *.bzflag.bz\n" "allow *.bzflag.org\n" "deny *\n"; static AccessList DownloadAccessList("DownloadAccess.txt", DownloadContent); /******************************************************************************/ #ifdef HAVE_CURL /******************************************************************************/ // Function Prototypes static void printAuthNotice(); static void setHudMessage(const std::string& msg); static bool getFileTime(const std::string& url, time_t& t); static bool getAndCacheURL(const std::string& url); static bool authorizedServer(const std::string& hostname); static bool checkAuthorizations(BzMaterialManager::TextureSet& set); void Downloads::doDownloads() { CACHEMGR.loadIndex(); CACHEMGR.limitCacheSize(); DownloadAccessList.reload(); BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, false /* ignore referencing */); const bool doDownloads = BZDB.isTrue("doDownloads"); const bool updateDownloads = BZDB.isTrue("updateDownloads"); // check hosts' access permissions bool authNotice = checkAuthorizations(set); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { // use the cache? CacheManager::CacheRecord oldrec; if (CACHEMGR.findURL(texUrl, oldrec)) { time_t filetime = 0; if (doDownloads && updateDownloads) { getFileTime(texUrl, filetime); } if (filetime <= oldrec.date) { // use the cached file MATERIALMGR.setTextureLocal(texUrl, oldrec.name); continue; } } // bail here if we can't download if (!doDownloads) { MATERIALMGR.setTextureLocal(texUrl, ""); std::string msg = ColorStrings[GreyColor]; msg += "not downloading: " + texUrl; addMessage(NULL, msg); continue; } // download and cache the URL if (getAndCacheURL(texUrl)) { const std::string localname = CACHEMGR.getLocalName(texUrl); MATERIALMGR.setTextureLocal(texUrl, localname); } else { MATERIALMGR.setTextureLocal(texUrl, ""); } } } if (authNotice) { printAuthNotice(); } CACHEMGR.saveIndex(); return; } bool Downloads::updateDownloads(bool& rebuild) { CACHEMGR.loadIndex(); CACHEMGR.limitCacheSize(); DownloadAccessList.reload(); BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, true /* only referenced materials */); TextureManager& TEXMGR = TextureManager::instance(); rebuild = false; bool updated = false; // check hosts' access permissions bool authNotice = checkAuthorizations(set); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { // use the cache or update? CacheManager::CacheRecord oldrec; if (CACHEMGR.findURL(texUrl, oldrec)) { time_t filetime; getFileTime(texUrl, filetime); if (filetime <= oldrec.date) { // keep using the cached file MATERIALMGR.setTextureLocal(texUrl, oldrec.name); if (!TEXMGR.isLoaded(oldrec.name)) { rebuild = true; } continue; } } // download the file and update the cache if (getAndCacheURL(texUrl)) { updated = true; const std::string localname = CACHEMGR.getLocalName(texUrl); if (!TEXMGR.isLoaded(localname)) { rebuild = true; } else { TEXMGR.reloadTextureImage(localname); // reload with the new image } MATERIALMGR.setTextureLocal(texUrl, localname); // if it wasn't cached } } } if (authNotice) { printAuthNotice(); } CACHEMGR.saveIndex(); return updated; } void Downloads::removeTextures() { BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, false /* ignore referencing */); TextureManager& TEXMGR = TextureManager::instance(); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { const std::string& localname = CACHEMGR.getLocalName(texUrl); if (TEXMGR.isLoaded(localname)) { TEXMGR.removeTexture(localname); } } } return; } static void printAuthNotice() { std::string msg = ColorStrings[WhiteColor]; msg += "NOTE: "; msg += ColorStrings[GreyColor]; msg += "download access is controlled by "; msg += ColorStrings[YellowColor]; msg += DownloadAccessList.getFileName(); addMessage(NULL, msg); return; } static bool getFileTime(const std::string& url, time_t& t) { setHudMessage("Update DNS check..."); URLManager& URLMGR = URLManager::instance(); if (URLMGR.getURLHeader(url)) { URLMGR.getFileTime(t); return true; } else { t = 0; return false; } setHudMessage(""); } static bool getAndCacheURL(const std::string& url) { bool result = false; setHudMessage("Download DNS check..."); URLManager& URLMGR = URLManager::instance(); URLMGR.setProgressFunc(curlProgressFunc, NULL); std::string msg = ColorStrings[GreyColor]; msg += "downloading: " + url; addMessage(NULL, msg); void* urlData; unsigned int urlSize; if (URLMGR.getURL(url, &urlData, urlSize)) { time_t filetime; URLMGR.getFileTime(filetime); // CACHEMGR generates name, usedDate, and key CacheManager::CacheRecord rec; rec.url = url; rec.size = urlSize; rec.date = filetime; CACHEMGR.addFile(rec, urlData); free(urlData); result = true; } else { std::string msg = ColorStrings[RedColor] + "failure: "; msg += URLMGR.getErrorString(); addMessage(NULL, msg); result = false; } URLMGR.setProgressFunc(NULL, NULL); setHudMessage(""); return result; } static bool authorizedServer(const std::string& hostname) { setHudMessage("Access DNS check..."); Address address(hostname); // get the address (BLOCKING) std::string ip = address.getDotNotation(); setHudMessage(""); // make the list of strings to check std::vector<std::string> nameAndIp; if (hostname.size() > 0) { nameAndIp.push_back(hostname); } if (ip.size() > 0) { nameAndIp.push_back(ip); } return DownloadAccessList.authorized(nameAndIp); } static bool parseHostname(const std::string& url, std::string& hostname) { std::string protocol, path, ip; int port; if (BzfNetwork::parseURL(url, protocol, hostname, port, path)) { if ((protocol == "http") || (protocol == "ftp")) { return true; } } return false; } static bool checkAuthorizations(BzMaterialManager::TextureSet& set) { // avoid the DNS lookup if (DownloadAccessList.alwaysAuthorized()) { return false; } bool hostFailed = false; BzMaterialManager::TextureSet::iterator set_it; std::map<std::string, bool> hostAccess; std::map<std::string, bool>::iterator host_it; // get the list of hosts to check for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& url = *set_it; std::string hostname; if (parseHostname(url, hostname)) { hostAccess[hostname] = true; } } // check the hosts for (host_it = hostAccess.begin(); host_it != hostAccess.end(); host_it++) { const std::string& host = host_it->first; host_it->second = authorizedServer(host); } // clear any unauthorized urls set_it = set.begin(); while (set_it != set.end()) { BzMaterialManager::TextureSet::iterator next_it = set_it; next_it++; const std::string& url = *set_it; std::string hostname; if (parseHostname(url, hostname) && !hostAccess[hostname]) { hostFailed = true; // remove the url MATERIALMGR.setTextureLocal(url, ""); set.erase(set_it); // send a message std::string msg = ColorStrings[RedColor]; msg += "local denial: "; msg += ColorStrings[GreyColor]; msg += url; addMessage(NULL, msg); } set_it = next_it; } return hostFailed; } static void setHudMessage(const std::string& msg) { HUDDialogStack::get()->setFailedMessage(msg.c_str()); drawFrame(0.0f); return; } /******************************************************************************/ #else // ! HAVE_CURL /******************************************************************************/ void Downloads::doDownloads() { bool needWarning = false; BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, false /* ignore referencing */); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { needWarning = true; // one time warning std::string msg = ColorStrings[GreyColor]; msg += "not downloading: " + texUrl; addMessage(NULL, msg); // avoid future warnings MATERIALMGR.setTextureLocal(texUrl, ""); } } if (needWarning && BZDB.isTrue("doDownloads")) { std::string msg = ColorStrings[RedColor]; msg += "Downloads are not available for clients without libcurl"; addMessage(NULL, msg); msg = ColorStrings[YellowColor]; msg += "To disable this message, disable [Automatic Downloads] in"; addMessage(NULL, msg); msg = ColorStrings[YellowColor]; msg += "Options -> Cache Options, or get a client with libcurl"; addMessage(NULL, msg); } return; } bool Downloads::updateDownloads(bool& /*rebuild*/) { std::string msg = ColorStrings[RedColor]; msg += "Downloads are not available for clients without libcurl"; addMessage(NULL, msg); return false; } void Downloads::removeTextures() { return; } /******************************************************************************/ #endif // HAVE_CURL /******************************************************************************/ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>crash catch by dtr<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "Downloads.h" /* system headers */ #include <map> /* common implementation headers */ #include "network.h" #include "Address.h" #include "AccessList.h" #include "CacheManager.h" #include "BzMaterial.h" #include "URLManager.h" #include "AnsiCodes.h" #include "TextureManager.h" /* local implementation headers */ #include "playing.h" #include "HUDDialogStack.h" // FIXME - someone write a better explanation static const char DownloadContent[] = "#\n" "# This file controls the access to servers for downloads.\n" "# Patterns are attempted in order against both the hostname\n" "# and ip. The first matching pattern sets the state. If no\n" "# patterns are matched, then the server is authorized. There\n" "# are four types of matches:\n" "#\n" "# simple globbing (* and ?)\n" "# allow\n" "# deny\n" "#\n" "# regular expressions\n" "# allow_regex\n" "# deny_regex\n" "#\n" "\n" "#\n" "# To authorize all servers, remove the last 3 lines.\n" "#\n" "\n" "allow *.bzflag.bz\n" "allow *.bzflag.org\n" "deny *\n"; static AccessList DownloadAccessList("DownloadAccess.txt", DownloadContent); /******************************************************************************/ #ifdef HAVE_CURL /******************************************************************************/ // Function Prototypes static void printAuthNotice(); static void setHudMessage(const std::string& msg); static bool getFileTime(const std::string& url, time_t& t); static bool getAndCacheURL(const std::string& url); static bool authorizedServer(const std::string& hostname); static bool checkAuthorizations(BzMaterialManager::TextureSet& set); void Downloads::doDownloads() { CACHEMGR.loadIndex(); CACHEMGR.limitCacheSize(); DownloadAccessList.reload(); BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, false /* ignore referencing */); const bool doDownloads = BZDB.isTrue("doDownloads"); const bool updateDownloads = BZDB.isTrue("updateDownloads"); // check hosts' access permissions bool authNotice = checkAuthorizations(set); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { // use the cache? CacheManager::CacheRecord oldrec; if (CACHEMGR.findURL(texUrl, oldrec)) { time_t filetime = 0; if (doDownloads && updateDownloads) { getFileTime(texUrl, filetime); } if (filetime <= oldrec.date) { // use the cached file MATERIALMGR.setTextureLocal(texUrl, oldrec.name); continue; } } // bail here if we can't download if (!doDownloads) { MATERIALMGR.setTextureLocal(texUrl, ""); std::string msg = ColorStrings[GreyColor]; msg += "not downloading: " + texUrl; addMessage(NULL, msg); continue; } // download and cache the URL if (getAndCacheURL(texUrl)) { const std::string localname = CACHEMGR.getLocalName(texUrl); MATERIALMGR.setTextureLocal(texUrl, localname); } else { MATERIALMGR.setTextureLocal(texUrl, ""); } } } if (authNotice) { printAuthNotice(); } CACHEMGR.saveIndex(); return; } bool Downloads::updateDownloads(bool& rebuild) { CACHEMGR.loadIndex(); CACHEMGR.limitCacheSize(); DownloadAccessList.reload(); BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, true /* only referenced materials */); TextureManager& TEXMGR = TextureManager::instance(); rebuild = false; bool updated = false; // check hosts' access permissions bool authNotice = checkAuthorizations(set); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { // use the cache or update? CacheManager::CacheRecord oldrec; if (CACHEMGR.findURL(texUrl, oldrec)) { time_t filetime; getFileTime(texUrl, filetime); if (filetime <= oldrec.date) { // keep using the cached file MATERIALMGR.setTextureLocal(texUrl, oldrec.name); if (!TEXMGR.isLoaded(oldrec.name)) { rebuild = true; } continue; } } // download the file and update the cache if (getAndCacheURL(texUrl)) { updated = true; const std::string localname = CACHEMGR.getLocalName(texUrl); if (!TEXMGR.isLoaded(localname)) { rebuild = true; } else { TEXMGR.reloadTextureImage(localname); // reload with the new image } MATERIALMGR.setTextureLocal(texUrl, localname); // if it wasn't cached } } } if (authNotice) { printAuthNotice(); } CACHEMGR.saveIndex(); return updated; } void Downloads::removeTextures() { BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, false /* ignore referencing */); TextureManager& TEXMGR = TextureManager::instance(); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { const std::string& localname = CACHEMGR.getLocalName(texUrl); if (TEXMGR.isLoaded(localname)) { TEXMGR.removeTexture(localname); } } } return; } static void printAuthNotice() { std::string msg = ColorStrings[WhiteColor]; msg += "NOTE: "; msg += ColorStrings[GreyColor]; msg += "download access is controlled by "; msg += ColorStrings[YellowColor]; msg += DownloadAccessList.getFileName(); addMessage(NULL, msg); return; } static bool getFileTime(const std::string& url, time_t& t) { setHudMessage("Update DNS check..."); URLManager& URLMGR = URLManager::instance(); if (URLMGR.getURLHeader(url)) { URLMGR.getFileTime(t); return true; } else { t = 0; return false; } setHudMessage(""); } static bool getAndCacheURL(const std::string& url) { bool result = false; setHudMessage("Download DNS check..."); URLManager& URLMGR = URLManager::instance(); URLMGR.setProgressFunc(curlProgressFunc, NULL); std::string msg = ColorStrings[GreyColor]; msg += "downloading: " + url; addMessage(NULL, msg); void* urlData; unsigned int urlSize; if (URLMGR.getURL(url, &urlData, urlSize)) { time_t filetime; URLMGR.getFileTime(filetime); // CACHEMGR generates name, usedDate, and key CacheManager::CacheRecord rec; rec.url = url; rec.size = urlSize; rec.date = filetime; CACHEMGR.addFile(rec, urlData); free(urlData); result = true; } else { std::string msg = ColorStrings[RedColor] + "failure: "; msg += URLMGR.getErrorString(); addMessage(NULL, msg); result = false; } URLMGR.setProgressFunc(NULL, NULL); setHudMessage(""); return result; } static bool authorizedServer(const std::string& hostname) { setHudMessage("Access DNS check..."); Address address(hostname); // get the address (BLOCKING) std::string ip = address.getDotNotation(); setHudMessage(""); // make the list of strings to check std::vector<std::string> nameAndIp; if (hostname.size() > 0) { nameAndIp.push_back(hostname); } if (ip.size() > 0) { nameAndIp.push_back(ip); } return DownloadAccessList.authorized(nameAndIp); } static bool parseHostname(const std::string& url, std::string& hostname) { std::string protocol, path, ip; int port; if (BzfNetwork::parseURL(url, protocol, hostname, port, path)) { if ((protocol == "http") || (protocol == "ftp")) { return true; } } return false; } static bool checkAuthorizations(BzMaterialManager::TextureSet& set) { // avoid the DNS lookup if (DownloadAccessList.alwaysAuthorized()) { return false; } bool hostFailed = false; BzMaterialManager::TextureSet::iterator set_it; std::map<std::string, bool> hostAccess; std::map<std::string, bool>::iterator host_it; // get the list of hosts to check for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& url = *set_it; std::string hostname; if (parseHostname(url, hostname)) { hostAccess[hostname] = true; } } // check the hosts for (host_it = hostAccess.begin(); host_it != hostAccess.end(); host_it++) { const std::string& host = host_it->first; host_it->second = authorizedServer(host); } // clear any unauthorized urls set_it = set.begin(); while (set_it != set.end()) { BzMaterialManager::TextureSet::iterator next_it = set_it; next_it++; const std::string& url = *set_it; std::string hostname; if (parseHostname(url, hostname) && !hostAccess[hostname]) { hostFailed = true; // send a message std::string msg = ColorStrings[RedColor]; msg += "local denial: "; msg += ColorStrings[GreyColor]; msg += url; addMessage(NULL, msg); // remove the url MATERIALMGR.setTextureLocal(url, ""); set.erase(set_it); } set_it = next_it; } return hostFailed; } static void setHudMessage(const std::string& msg) { HUDDialogStack::get()->setFailedMessage(msg.c_str()); drawFrame(0.0f); return; } /******************************************************************************/ #else // ! HAVE_CURL /******************************************************************************/ void Downloads::doDownloads() { bool needWarning = false; BzMaterialManager::TextureSet set; BzMaterialManager::TextureSet::iterator set_it; MATERIALMGR.makeTextureList(set, false /* ignore referencing */); for (set_it = set.begin(); set_it != set.end(); set_it++) { const std::string& texUrl = set_it->c_str(); if (CACHEMGR.isCacheFileType(texUrl)) { needWarning = true; // one time warning std::string msg = ColorStrings[GreyColor]; msg += "not downloading: " + texUrl; addMessage(NULL, msg); // avoid future warnings MATERIALMGR.setTextureLocal(texUrl, ""); } } if (needWarning && BZDB.isTrue("doDownloads")) { std::string msg = ColorStrings[RedColor]; msg += "Downloads are not available for clients without libcurl"; addMessage(NULL, msg); msg = ColorStrings[YellowColor]; msg += "To disable this message, disable [Automatic Downloads] in"; addMessage(NULL, msg); msg = ColorStrings[YellowColor]; msg += "Options -> Cache Options, or get a client with libcurl"; addMessage(NULL, msg); } return; } bool Downloads::updateDownloads(bool& /*rebuild*/) { std::string msg = ColorStrings[RedColor]; msg += "Downloads are not available for clients without libcurl"; addMessage(NULL, msg); return false; } void Downloads::removeTextures() { return; } /******************************************************************************/ #endif // HAVE_CURL /******************************************************************************/ // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/** @file * * @ingroup foundationLibrary * * @brief 2-dimensional matrix of compound values with N elements each. * * @authors Timothy Place & Nathan Wolek * * @copyright Copyright © 2011-2012, Timothy Place & Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTMatrix.h" #include "TTEnvironment.h" #include "TTBase.h" #define thisTTClass TTMatrix #define thisTTClassName "matrix" #define thisTTClassTags "matrix" TT_OBJECT_CONSTRUCTOR, mData(NULL), mRowCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mColumnCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mElementCount(1), mComponentCount(1), mComponentStride(1), mDataCount(0), mType(kTypeUInt8), mTypeSizeInBytes(1), mDataSize(0), mDataIsLocallyOwned(YES) { addAttributeWithGetterAndSetter(Dimensions, kTypeInt32); // mDimensions deprecated, we should delete this too // NW: had trouble removing it in Oct 2012 // we can keep setDimensions() & getDimensions() addAttributeWithSetter(RowCount, kTypeInt32); addAttributeWithSetter(ColumnCount, kTypeInt32); addAttributeWithGetterAndSetter(Type, kTypeUInt8); // necessary so that public interface uses symbols // internally we use TTDataType addAttributeWithSetter(ElementCount, kTypeInt16); addMessage(clear); addMessageWithArguments(fill); addMessageWithArguments(get); addMessageWithArguments(set); // TODO: getLockedPointer -- returns a pointer to the data, locks the matrix mutex // TODO: releaseLockedPointer -- releases the matrix mutex // TODO: the above two items mean we need a TTMutex member resize(); } TTMatrix::~TTMatrix() { if (mDataIsLocallyOwned) delete[] mData; // TODO: only do this if the refcount for the data is down to zero! } TTErr TTMatrix::resize() { mComponentCount = mRowCount * mColumnCount; mDataCount = mComponentCount * mElementCount; mDataSize = mDataCount * mTypeSizeInBytes; mComponentStride = mTypeSizeInBytes * mElementCount; if (mDataIsLocallyOwned) { // TODO: currently, we are not preserving memory when resizing. Should we try to preserve the previous memory contents? // TODO: thread protection delete[] mData; mData = new TTByte[mDataSize]; } if (mDataSize && mData) { return kTTErrNone; } else { return kTTErrAllocFailed; } } TTBoolean TTMatrix::setRowCountWithoutResize(TTRowID aNewRowCount) { if (aNewRowCount > 0) { mRowCount = aNewRowCount; return true; } else { return false; } } TTBoolean TTMatrix::setColumnCountWithoutResize(TTColumnID aNewColumnCount) { if (aNewColumnCount > 0) { mColumnCount = aNewColumnCount; return true; } else { return false; } } TTBoolean TTMatrix::setElementCountWithoutResize(TTElementID aNewElementCount) { if (aNewElementCount > 0) { mElementCount = aNewElementCount; return true; } else { return false; } } TTBoolean TTMatrix::setTypeWithoutResize(TTDataType aNewType) { if (ttDataTypeInfo[aNewType]->isNumerical) { mType = aNewType; mTypeAsDataInfo = TTDataInfo::getInfoForType(aNewType); mTypeAsSymbol = &(mTypeAsDataInfo->name); mTypeSizeInBytes = (mTypeAsDataInfo->bitdepth / 8); return true; } else { return false; } } TTErr TTMatrix::setRowCount(const TTValue& aNewRowCount) { TTRowID aNewRowCountInt = aNewRowCount; if (setRowCountWithoutResize(aNewRowCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setColumnCount(const TTValue& aNewColumnCount) { TTColumnID aNewColumnCountInt = aNewColumnCount; if (setColumnCountWithoutResize(aNewColumnCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setElementCount(const TTValue& newElementCount) { TTElementID aNewElementCountInt = newElementCount; if (setElementCountWithoutResize(aNewElementCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setType(const TTValue& aType) { TTSymbol aNewTypeAsSymbol = aType; TTDataType aNewDataType = TTDataInfo::matchSymbolToDataType(aNewTypeAsSymbol); if (setTypeWithoutResize(aNewDataType)) { mTypeAsSymbol = aNewTypeAsSymbol; // TODO: dereferencing TTDataInfo->name not working, so this is temp solution // after if{} because we should not change unless resize() will occur return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setDimensions(const TTValue& someNewDimensions) { TTRowID aNewRowCount = 1; TTColumnID aNewColumnCount = 1; TTUInt8 size = someNewDimensions.getSize(); // needed to support old calls with 1 or 2 dimensions if (size > 0) { someNewDimensions.get(0, aNewRowCount); } if (size > 1) { someNewDimensions.get(1, aNewColumnCount); } if (this->setRowCountWithoutResize(aNewRowCount) && this->setColumnCountWithoutResize(aNewColumnCount)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::getType(TTValue& returnedType) const { returnedType = mTypeAsSymbol; return kTTErrNone; } TTErr TTMatrix::getDimensions(TTValue& returnedDimensions) const { returnedDimensions.setSize(2); returnedDimensions.set(0, TTUInt32(mRowCount)); // compile fails if we don't cast mRowCount here returnedDimensions.set(1, TTUInt32(mColumnCount)); // compile fails if we don't cast mColumnCount here return kTTErrNone; } TTErr TTMatrix::clear() { memset(mData, 0, mDataSize); return kTTErrNone; } TTErr TTMatrix::fill(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTBytePtr fillValue = new TTByte[mComponentStride]; // TODO: here we have this ugly switch again... if (mType == kTypeUInt8) anInputValue.getArray((TTUInt8*)fillValue, mElementCount); else if (mType == kTypeInt32) anInputValue.getArray((TTInt32*)fillValue, mElementCount); else if (mType == kTypeFloat32) anInputValue.getArray((TTFloat32*)fillValue, mElementCount); else if (mType == kTypeFloat64) anInputValue.getArray((TTFloat64*)fillValue, mElementCount); for (TTUInt32 i=0; i<mDataSize; i += mComponentStride) memcpy(mData+i, fillValue, mComponentStride); delete[] fillValue; return kTTErrNone; } /* To find the index in the matrix: 1D Matrix: index = x 2D Matrix: index = dim_0 y + x 3D Matrix: index = dim_0 dim_1 z + dim_0 y + x etc. */ // args passed-in should be the 2 coordinates // args returned will be the value(s) at those coordinates TTErr TTMatrix::get(const TTValue& anInputValue, TTValue &anOutputValue) const { TTUInt16 dimensionCount = anInputValue.getSize(); if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; TTInt32 i, j; anInputValue.get(0, i); anInputValue.get(1, j); TTUInt32 index = INDEX_OF_COMPONENT_FIRSTBYTE(i, j); // TODO: there is no bounds checking here anOutputValue.clear(); // TODO: here we have this ugly switch again... // Maybe we could just have duplicate pointers of different types in our class, and then we could access them more cleanly? if (mType == kTypeUInt8) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTUInt8*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeInt32) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTInt32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat32) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat64) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat64*)(mData+(index+e*mTypeSizeInBytes))); } return kTTErrNone; } // args passed-in should be the coordinates plus the value // therefore anInputValue requires (2 + mElementCount) items TTErr TTMatrix::set(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTValue theValue; TTUInt16 dimensionCount = anInputValue.getSize() - mElementCount; if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; theValue.copyFrom(anInputValue, dimensionCount); TTInt32 i, j; anInputValue.get(0, i); anInputValue.get(1, j); TTUInt32 index = INDEX_OF_COMPONENT_FIRSTBYTE(i, j); // TODO: there is no bounds checking here if (mType == kTypeUInt8) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTUInt8*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeInt32) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTInt32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat32) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat64) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat64*)(mData+(index+e*mTypeSizeInBytes))); } return kTTErrNone; } TTBoolean TTMatrix::allAttributesMatch(const TTMatrix& anotherMatrix) const { // TODO: should/could this be inlined? if (mType == anotherMatrix.mType && mElementCount == anotherMatrix.mElementCount && mRowCount == anotherMatrix.mRowCount && mColumnCount == anotherMatrix.mColumnCount) { return true; } else { return false; } } TTErr TTMatrix::copy(const TTMatrix& source, TTMatrix& dest) { // TODO: could this be rethought as an iterator? dest.adaptTo(source); memcpy(dest.mData, source.mData, source.mDataSize); return kTTErrNone; } TTErr TTMatrix::adaptTo(const TTMatrix& anotherMatrix) { // TODO: what should we do if anotherMatrix is not locally owned? // It would be nice to re-dimension the data, but we can't re-alloc / resize the number of bytes... // NW: don't understand above comment, previous set attribute methods *were* calling resize() if (setRowCountWithoutResize(anotherMatrix.mRowCount) && setColumnCountWithoutResize(anotherMatrix.mColumnCount) && setElementCountWithoutResize(anotherMatrix.mElementCount) && setTypeWithoutResize(anotherMatrix.mType)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::iterate(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator) { if(C->adaptTo(A) == kTTErrNone) { int stride = A->mTypeSizeInBytes; int size = A->mDataSize; for (int k=0; k<size; k+=stride) (*iterator)(C->mData+k, A->mData+k, B->mData+k); return kTTErrNone; } else { return kTTErrGeneric; } } TTErr TTMatrix::iterateWhenAllAttributesMatch(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator) { if (A->allAttributesMatch(B)) { return iterate(C,A,B,iterator); } else { return kTTErrGeneric; } } <commit_msg>TTMatrix:set() & get() now include boundary checking<commit_after>/** @file * * @ingroup foundationLibrary * * @brief 2-dimensional matrix of compound values with N elements each. * * @authors Timothy Place & Nathan Wolek * * @copyright Copyright © 2011-2012, Timothy Place & Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTMatrix.h" #include "TTEnvironment.h" #include "TTBase.h" #define thisTTClass TTMatrix #define thisTTClassName "matrix" #define thisTTClassTags "matrix" TT_OBJECT_CONSTRUCTOR, mData(NULL), mRowCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mColumnCount(1), // initialize to a 1x1 matrix by default (maybe we should be using the args?) mElementCount(1), mComponentCount(1), mComponentStride(1), mDataCount(0), mType(kTypeUInt8), mTypeSizeInBytes(1), mDataSize(0), mDataIsLocallyOwned(YES) { addAttributeWithGetterAndSetter(Dimensions, kTypeInt32); // TODO: mDimensions deprecated, we should delete this too // NW: had trouble removing it in Oct 2012 // we should keep setDimensions() & getDimensions() methods addAttributeWithSetter(RowCount, kTypeInt32); addAttributeWithSetter(ColumnCount, kTypeInt32); addAttributeWithGetterAndSetter(Type, kTypeUInt8); // necessary so that public interface uses symbols // internally we use TTDataType addAttributeWithSetter(ElementCount, kTypeInt16); addMessage(clear); addMessageWithArguments(fill); addMessageWithArguments(get); addMessageWithArguments(set); // TODO: getLockedPointer -- returns a pointer to the data, locks the matrix mutex // TODO: releaseLockedPointer -- releases the matrix mutex // TODO: the above two items mean we need a TTMutex member resize(); } TTMatrix::~TTMatrix() { if (mDataIsLocallyOwned) delete[] mData; // TODO: only do this if the refcount for the data is down to zero! } TTErr TTMatrix::resize() { mComponentCount = mRowCount * mColumnCount; mDataCount = mComponentCount * mElementCount; mDataSize = mDataCount * mTypeSizeInBytes; mComponentStride = mTypeSizeInBytes * mElementCount; if (mDataIsLocallyOwned) { // TODO: currently, we are not preserving memory when resizing. Should we try to preserve the previous memory contents? // TODO: thread protection delete[] mData; mData = new TTByte[mDataSize]; } if (mDataSize && mData) { return kTTErrNone; } else { return kTTErrAllocFailed; } } TTBoolean TTMatrix::setRowCountWithoutResize(TTRowID aNewRowCount) { if (aNewRowCount > 0) { mRowCount = aNewRowCount; return true; } else { return false; } } TTBoolean TTMatrix::setColumnCountWithoutResize(TTColumnID aNewColumnCount) { if (aNewColumnCount > 0) { mColumnCount = aNewColumnCount; return true; } else { return false; } } TTBoolean TTMatrix::setElementCountWithoutResize(TTElementID aNewElementCount) { if (aNewElementCount > 0) { mElementCount = aNewElementCount; return true; } else { return false; } } TTBoolean TTMatrix::setTypeWithoutResize(TTDataType aNewType) { if (ttDataTypeInfo[aNewType]->isNumerical) { mType = aNewType; mTypeAsDataInfo = TTDataInfo::getInfoForType(aNewType); mTypeAsSymbol = &(mTypeAsDataInfo->name); mTypeSizeInBytes = (mTypeAsDataInfo->bitdepth / 8); return true; } else { return false; } } TTErr TTMatrix::setRowCount(const TTValue& aNewRowCount) { TTRowID aNewRowCountInt = aNewRowCount; if (setRowCountWithoutResize(aNewRowCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setColumnCount(const TTValue& aNewColumnCount) { TTColumnID aNewColumnCountInt = aNewColumnCount; if (setColumnCountWithoutResize(aNewColumnCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setElementCount(const TTValue& newElementCount) { TTElementID aNewElementCountInt = newElementCount; if (setElementCountWithoutResize(aNewElementCountInt)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setType(const TTValue& aType) { TTSymbol aNewTypeAsSymbol = aType; TTDataType aNewDataType = TTDataInfo::matchSymbolToDataType(aNewTypeAsSymbol); if (setTypeWithoutResize(aNewDataType)) { mTypeAsSymbol = aNewTypeAsSymbol; // TODO: dereferencing TTDataInfo->name not working, so this is temp solution // after if{} because we should not change unless resize() will occur return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::setDimensions(const TTValue& someNewDimensions) { TTRowID aNewRowCount = 1; TTColumnID aNewColumnCount = 1; TTUInt8 size = someNewDimensions.getSize(); // needed to support old calls with 1 or 2 dimensions if (size > 0) { someNewDimensions.get(0, aNewRowCount); } if (size > 1) { someNewDimensions.get(1, aNewColumnCount); } if (this->setRowCountWithoutResize(aNewRowCount) && this->setColumnCountWithoutResize(aNewColumnCount)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::getType(TTValue& returnedType) const { returnedType = mTypeAsSymbol; return kTTErrNone; } TTErr TTMatrix::getDimensions(TTValue& returnedDimensions) const { returnedDimensions.setSize(2); returnedDimensions.set(0, TTUInt32(mRowCount)); // compile fails if we don't cast mRowCount here returnedDimensions.set(1, TTUInt32(mColumnCount)); // compile fails if we don't cast mColumnCount here return kTTErrNone; } TTErr TTMatrix::clear() { memset(mData, 0, mDataSize); return kTTErrNone; } TTErr TTMatrix::fill(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTBytePtr fillValue = new TTByte[mComponentStride]; // TODO: here we have this ugly switch again... if (mType == kTypeUInt8) anInputValue.getArray((TTUInt8*)fillValue, mElementCount); else if (mType == kTypeInt32) anInputValue.getArray((TTInt32*)fillValue, mElementCount); else if (mType == kTypeFloat32) anInputValue.getArray((TTFloat32*)fillValue, mElementCount); else if (mType == kTypeFloat64) anInputValue.getArray((TTFloat64*)fillValue, mElementCount); for (TTUInt32 i=0; i<mDataSize; i += mComponentStride) memcpy(mData+i, fillValue, mComponentStride); delete[] fillValue; return kTTErrNone; } /* To find the index in the matrix: 1D Matrix: index = x 2D Matrix: index = dim_0 y + x 3D Matrix: index = dim_0 dim_1 z + dim_0 y + x etc. */ // args passed-in should be the 2 coordinates // args returned will be the value(s) at those coordinates TTErr TTMatrix::get(const TTValue& anInputValue, TTValue &anOutputValue) const { TTUInt16 dimensionCount = anInputValue.getSize(); if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; TTInt32 i, j; anInputValue.get(0, i); anInputValue.get(1, j); TTBoolean weAreNotInBounds = makeInBounds(i,j); if (weAreNotInBounds) return kTTErrOutOfBounds; // TODO: for now we throw an error when out of bounds. wrapping could be option in future version. TTUInt32 index = INDEX_OF_COMPONENT_FIRSTBYTE(i, j); anOutputValue.clear(); // TODO: here we have this ugly switch again... // Maybe we could just have duplicate pointers of different types in our class, and then we could access them more cleanly? if (mType == kTypeUInt8) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTUInt8*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeInt32) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTInt32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat32) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat64) { for (int e=0; e<mElementCount; e++) anOutputValue.append((TTFloat64*)(mData+(index+e*mTypeSizeInBytes))); } return kTTErrNone; } // args passed-in should be the coordinates plus the value // therefore anInputValue requires (2 + mElementCount) items TTErr TTMatrix::set(const TTValue& anInputValue, TTValue &anUnusedOutputValue) { TTValue theValue; TTUInt16 dimensionCount = anInputValue.getSize() - mElementCount; if (dimensionCount != 2) // 2 dimensions only return kTTErrWrongNumValues; theValue.copyFrom(anInputValue, dimensionCount); TTInt32 i, j; anInputValue.get(0, i); anInputValue.get(1, j); TTBoolean weAreNotInBounds = makeInBounds(i,j); if (weAreNotInBounds) return kTTErrOutOfBounds; // TODO: for now we throw an error when out of bounds. wrapping could be option in future version. TTUInt32 index = INDEX_OF_COMPONENT_FIRSTBYTE(i, j); if (mType == kTypeUInt8) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTUInt8*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeInt32) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTInt32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat32) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat32*)(mData+(index+e*mTypeSizeInBytes))); } else if (mType == kTypeFloat64) { for (int e=0; e<mElementCount; e++) anInputValue.get(e+dimensionCount, *(TTFloat64*)(mData+(index+e*mTypeSizeInBytes))); } return kTTErrNone; } TTBoolean TTMatrix::allAttributesMatch(const TTMatrix& anotherMatrix) const { // TODO: should/could this be inlined? if (mType == anotherMatrix.mType && mElementCount == anotherMatrix.mElementCount && mRowCount == anotherMatrix.mRowCount && mColumnCount == anotherMatrix.mColumnCount) { return true; } else { return false; } } TTErr TTMatrix::copy(const TTMatrix& source, TTMatrix& dest) { // TODO: could this be rethought as an iterator? dest.adaptTo(source); memcpy(dest.mData, source.mData, source.mDataSize); return kTTErrNone; } TTErr TTMatrix::adaptTo(const TTMatrix& anotherMatrix) { // TODO: what should we do if anotherMatrix is not locally owned? // It would be nice to re-dimension the data, but we can't re-alloc / resize the number of bytes... // NW: don't understand above comment, previous set attribute methods *were* calling resize() if (setRowCountWithoutResize(anotherMatrix.mRowCount) && setColumnCountWithoutResize(anotherMatrix.mColumnCount) && setElementCountWithoutResize(anotherMatrix.mElementCount) && setTypeWithoutResize(anotherMatrix.mType)) { return resize(); } else { return kTTErrInvalidValue; } } TTErr TTMatrix::iterate(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator) { if(C->adaptTo(A) == kTTErrNone) { int stride = A->mTypeSizeInBytes; int size = A->mDataSize; for (int k=0; k<size; k+=stride) (*iterator)(C->mData+k, A->mData+k, B->mData+k); return kTTErrNone; } else { return kTTErrGeneric; } } TTErr TTMatrix::iterateWhenAllAttributesMatch(TTMatrix* C, const TTMatrix* A, const TTMatrix* B, TTMatrixIterator iterator) { if (A->allAttributesMatch(B)) { return iterate(C,A,B,iterator); } else { return kTTErrGeneric; } } <|endoftext|>
<commit_before>// @(#)root/tree:$Name: $:$Id: TLeaf.cxx,v 1.11 2003/12/19 07:55:25 brun Exp $ // Author: Rene Brun 12/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf describes individual elements of a TBranch // // See TBranch structure in TTree. // ////////////////////////////////////////////////////////////////////////// #include "TLeaf.h" #include "TBranch.h" #include "TTree.h" #include "TVirtualPad.h" #include "TBrowser.h" #include <ctype.h> R__EXTERN TTree *gTree; R__EXTERN TBranch *gBranch; ClassImp(TLeaf) //______________________________________________________________________________ TLeaf::TLeaf(): TNamed() { //*-*-*-*-*-*Default constructor for Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fLen = 0; //fBranch = 0; fBranch = gBranch; fLeafCount = 0; fNdata = 0; fOffset = 0; } //______________________________________________________________________________ TLeaf::TLeaf(const char *name, const char *) :TNamed(name,name) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============= // // See the TTree and TBranch constructors for explanation of parameters. fBranch = 0; fIsRange = 0; fIsUnsigned = 0; fLenType = 4; fNdata = 0; fOffset = 0; fLeafCount = GetLeafCounter(fLen); if (fLen == -1) { MakeZombie(); return; } if (fLeafCount || strchr(name,'[')) { char newname[64]; strcpy(newname,name); char *bracket = strchr(newname,'['); *bracket = 0; SetName(newname); } fBranch = gBranch; } //______________________________________________________________________________ TLeaf::~TLeaf() { //*-*-*-*-*-*Default destructor for a Leaf*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== // if (fBranch) fBranch->GetListOfLeaves().Remove(this); if (!fBranch) return; TTree *tree = fBranch->GetTree(); fBranch = 0; if (!tree) return; tree->GetListOfLeaves()->Remove(this); } //______________________________________________________________________________ void TLeaf::Browse(TBrowser *b) { char name[64]; if (strchr(GetName(),'.')) { fBranch->GetTree()->Draw(GetName(), b ? b->GetDrawOption() : ""); } else { sprintf(name,"%s.%s",fBranch->GetName(),GetName()); fBranch->GetTree()->Draw(name, "", b ? b->GetDrawOption() : ""); } if (gPad) gPad->Update(); } //______________________________________________________________________________ void TLeaf::FillBasket(TBuffer &) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================= } //______________________________________________________________________________ TLeaf *TLeaf::GetLeafCounter(Int_t &countval) const { //*-*-*-*-*-*-*Return Pointer to counter of referenced Leaf*-*-*-*-*-*-*-* //*-* ============================================ // // If leaf name has the forme var[nelem], where nelem is alphanumeric, then // If nelem is a leaf name, return countval = 1 and the pointer to // the leaf named nelem. // If leaf name has the forme var[nelem], where nelem is a digit, then // return countval = nelem and a null pointer. // Otherwise return countval=0 and a null pointer. // countval = 1; const char *name = GetTitle(); char *bleft = (char*)strchr(name,'['); if (!bleft) return 0; bleft++; Int_t nch = strlen(bleft); char *countname = new char[nch+1]; strcpy(countname,bleft); char *bright = (char*)strchr(countname,']'); if (!bright) { delete [] countname; return 0;} char *bleft2 = (char*)strchr(countname,'['); *bright = 0; nch = strlen(countname); //*-* Now search a branch name with a leave name = countname // We search for the leaf in the ListOfLeaves from the TTree. We can in principle // access the TTree by calling fBranch()->GetTree(), but fBranch is not set if this // method is called from the TLeaf constructor. In that case, use global pointer // gTree. // Also, if fBranch is set, but fBranch->GetTree() returns NULL, use gTree. TTree* pTree = fBranch ? fBranch->GetTree() : gTree; if (!pTree) pTree = gTree; TLeaf *leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname); Int_t i; if (leaf) { countval = 1; leaf->SetRange(); if (bleft2) { sscanf(bleft2,"[%d]",&i); countval *= i; } bleft = bleft2; while(bleft) { bleft2++; bleft = (char*)strchr(bleft2,'['); if (!bleft) break; sscanf(bleft,"[%d]",&i); countval *= i; bleft2 = bleft; } delete [] countname; return leaf; } //*-* not found in a branch/leaf. Is it a numerical value? for (i=0;i<nch;i++) { if (!isdigit(countname[i])) { delete [] countname; countval = -1; return 0; } } sscanf(countname,"%d",&countval); if (bleft2) { sscanf(bleft2,"[%d]",&i); countval *= i; } bleft = bleft2; while(bleft) { bleft2++; bleft = (char*)strchr(bleft2,'['); if (!bleft) break; sscanf(bleft,"[%d]",&i); countval *= i; bleft2 = bleft; } //*/ delete [] countname; return 0; } //______________________________________________________________________________ Int_t TLeaf::GetLen() const { //*-*-*-*-*-*-*-*-*Return the number of effective elements of this leaf*-*-*-* //*-* ==================================================== Int_t len; if (fLeafCount) { len = Int_t(fLeafCount->GetValue()); if (len > fLeafCount->GetMaximum()) { printf("ERROR leaf:%s, len=%d and max=%d\n",GetName(),len,fLeafCount->GetMaximum()); len = fLeafCount->GetMaximum(); } return len*fLen; } else { return fLen; } } //______________________________________________________________________________ Int_t TLeaf::ResetAddress(void *add, Bool_t destructor) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ // // This function is called by all TLeafX::SetAddress Int_t todelete = 0; if (TestBit(kNewValue)) todelete = 1; if (destructor) return todelete; if (fLeafCount) fNdata = fLen*(fLeafCount->GetMaximum() + 1); else fNdata = fLen; ResetBit(kNewValue); if (!add) SetBit(kNewValue); return todelete; } //_______________________________________________________________________ void TLeaf::SetLeafCount(TLeaf *leaf) { if (IsZombie() && fLen==-1 && leaf) { // The constructor noted that it could not find the // leafcount. Now that we did find it, let's remove // the side-effects ResetBit(kZombie); fLen = 1; } fLeafCount=leaf; } //_______________________________________________________________________ void TLeaf::Streamer(TBuffer &b) { //*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================================= if (b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = b.ReadVersion(&R__s, &R__c); if (R__v > 1) { TLeaf::Class()->ReadBuffer(b, this, R__v, R__s, R__c); } else { //====process old versions before automatic schema evolution TNamed::Streamer(b); b >> fLen; b >> fLenType; b >> fOffset; b >> fIsRange; b >> fIsUnsigned; b >> fLeafCount; b.CheckByteCount(R__s, R__c, TLeaf::IsA()); //====end of old versions } if (fLen == 0) fLen = 1; ResetBit(kNewValue); SetAddress(); } else { TLeaf::Class()->WriteBuffer(b,this); } } <commit_msg>Improve TLeaf::GetLeafCounter such that a class with a dynamic array with the size declared in the comment field with [size] will work when the class is the top level branch of a Tree and the branch name has "." as last character.<commit_after>// @(#)root/tree:$Name: $:$Id: TLeaf.cxx,v 1.12 2004/06/22 15:36:42 brun Exp $ // Author: Rene Brun 12/01/96 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf describes individual elements of a TBranch // // See TBranch structure in TTree. // ////////////////////////////////////////////////////////////////////////// #include "TLeaf.h" #include "TBranch.h" #include "TTree.h" #include "TVirtualPad.h" #include "TBrowser.h" #include <ctype.h> R__EXTERN TTree *gTree; R__EXTERN TBranch *gBranch; ClassImp(TLeaf) //______________________________________________________________________________ TLeaf::TLeaf(): TNamed() { //*-*-*-*-*-*Default constructor for Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fLen = 0; //fBranch = 0; fBranch = gBranch; fLeafCount = 0; fNdata = 0; fOffset = 0; } //______________________________________________________________________________ TLeaf::TLeaf(const char *name, const char *) :TNamed(name,name) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============= // // See the TTree and TBranch constructors for explanation of parameters. fBranch = 0; fIsRange = 0; fIsUnsigned = 0; fLenType = 4; fNdata = 0; fOffset = 0; fLeafCount = GetLeafCounter(fLen); if (fLen == -1) { MakeZombie(); return; } if (fLeafCount || strchr(name,'[')) { char newname[64]; strcpy(newname,name); char *bracket = strchr(newname,'['); *bracket = 0; SetName(newname); } fBranch = gBranch; } //______________________________________________________________________________ TLeaf::~TLeaf() { //*-*-*-*-*-*Default destructor for a Leaf*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== // if (fBranch) fBranch->GetListOfLeaves().Remove(this); if (!fBranch) return; TTree *tree = fBranch->GetTree(); fBranch = 0; if (!tree) return; tree->GetListOfLeaves()->Remove(this); } //______________________________________________________________________________ void TLeaf::Browse(TBrowser *b) { char name[64]; if (strchr(GetName(),'.')) { fBranch->GetTree()->Draw(GetName(), b ? b->GetDrawOption() : ""); } else { sprintf(name,"%s.%s",fBranch->GetName(),GetName()); fBranch->GetTree()->Draw(name, "", b ? b->GetDrawOption() : ""); } if (gPad) gPad->Update(); } //______________________________________________________________________________ void TLeaf::FillBasket(TBuffer &) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================= } //______________________________________________________________________________ TLeaf *TLeaf::GetLeafCounter(Int_t &countval) const { //*-*-*-*-*-*-*Return Pointer to counter of referenced Leaf*-*-*-*-*-*-*-* //*-* ============================================ // // If leaf name has the forme var[nelem], where nelem is alphanumeric, then // If nelem is a leaf name, return countval = 1 and the pointer to // the leaf named nelem. // If leaf name has the forme var[nelem], where nelem is a digit, then // return countval = nelem and a null pointer. // Otherwise return countval=0 and a null pointer. // countval = 1; const char *name = GetTitle(); char *bleft = (char*)strchr(name,'['); if (!bleft) return 0; bleft++; Int_t nch = strlen(bleft); char *countname = new char[nch+1]; strcpy(countname,bleft); char *bright = (char*)strchr(countname,']'); if (!bright) { delete [] countname; return 0;} char *bleft2 = (char*)strchr(countname,'['); *bright = 0; nch = strlen(countname); //*-* Now search a branch name with a leave name = countname // We search for the leaf in the ListOfLeaves from the TTree. We can in principle // access the TTree by calling fBranch()->GetTree(), but fBranch is not set if this // method is called from the TLeaf constructor. In that case, use global pointer // gTree. // Also, if fBranch is set, but fBranch->GetTree() returns NULL, use gTree. TTree* pTree = fBranch ? fBranch->GetTree() : gTree; if (!pTree) pTree = gTree; TLeaf *leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname); //if not found, make one more trial in case the leaf name has a "." if (!leaf && strchr(GetName(),'.')) { char *withdot = new char[1000]; strcpy(withdot,GetName()); char *lastdot = strrchr(withdot,'.'); strcpy(lastdot,countname); leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname); delete [] withdot; } Int_t i; if (leaf) { countval = 1; leaf->SetRange(); if (bleft2) { sscanf(bleft2,"[%d]",&i); countval *= i; } bleft = bleft2; while(bleft) { bleft2++; bleft = (char*)strchr(bleft2,'['); if (!bleft) break; sscanf(bleft,"[%d]",&i); countval *= i; bleft2 = bleft; } delete [] countname; return leaf; } //*-* not found in a branch/leaf. Is it a numerical value? for (i=0;i<nch;i++) { if (!isdigit(countname[i])) { delete [] countname; countval = -1; return 0; } } sscanf(countname,"%d",&countval); if (bleft2) { sscanf(bleft2,"[%d]",&i); countval *= i; } bleft = bleft2; while(bleft) { bleft2++; bleft = (char*)strchr(bleft2,'['); if (!bleft) break; sscanf(bleft,"[%d]",&i); countval *= i; bleft2 = bleft; } //*/ delete [] countname; return 0; } //______________________________________________________________________________ Int_t TLeaf::GetLen() const { //*-*-*-*-*-*-*-*-*Return the number of effective elements of this leaf*-*-*-* //*-* ==================================================== Int_t len; if (fLeafCount) { len = Int_t(fLeafCount->GetValue()); if (len > fLeafCount->GetMaximum()) { printf("ERROR leaf:%s, len=%d and max=%d\n",GetName(),len,fLeafCount->GetMaximum()); len = fLeafCount->GetMaximum(); } return len*fLen; } else { return fLen; } } //______________________________________________________________________________ Int_t TLeaf::ResetAddress(void *add, Bool_t destructor) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ // // This function is called by all TLeafX::SetAddress Int_t todelete = 0; if (TestBit(kNewValue)) todelete = 1; if (destructor) return todelete; if (fLeafCount) fNdata = fLen*(fLeafCount->GetMaximum() + 1); else fNdata = fLen; ResetBit(kNewValue); if (!add) SetBit(kNewValue); return todelete; } //_______________________________________________________________________ void TLeaf::SetLeafCount(TLeaf *leaf) { if (IsZombie() && fLen==-1 && leaf) { // The constructor noted that it could not find the // leafcount. Now that we did find it, let's remove // the side-effects ResetBit(kZombie); fLen = 1; } fLeafCount=leaf; } //_______________________________________________________________________ void TLeaf::Streamer(TBuffer &b) { //*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================================= if (b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = b.ReadVersion(&R__s, &R__c); if (R__v > 1) { TLeaf::Class()->ReadBuffer(b, this, R__v, R__s, R__c); } else { //====process old versions before automatic schema evolution TNamed::Streamer(b); b >> fLen; b >> fLenType; b >> fOffset; b >> fIsRange; b >> fIsUnsigned; b >> fLeafCount; b.CheckByteCount(R__s, R__c, TLeaf::IsA()); //====end of old versions } if (fLen == 0) fLen = 1; ResetBit(kNewValue); SetAddress(); } else { TLeaf::Class()->WriteBuffer(b,this); } } <|endoftext|>
<commit_before>#include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/UniformVectorRV.h> #include <queso/StatisticalInverseProblem.h> #include <queso/VectorSet.h> #include <queso/GaussianProcessEmulator.h> #include <cstdio> // Read in data files void readExpData(const std::vector<QUESO::GslVector *> & experimentScenarios, const std::vector<QUESO::GslVector *> & experimentOutputs) { FILE * fp_in = fopen("gp/scalar/ctf_dat.txt", "r"); unsigned int i = 0; double pressure; while (fscanf(fp_in, "%lf\n", &pressure) != EOF) { (*(experimentOutputs[i]))[0] = pressure; i++; } fclose(fp_in); } void readSimData(const std::vector<QUESO::GslVector *> & simulationScenarios, const std::vector<QUESO::GslVector *> & simulationParameters, const std::vector<QUESO::GslVector *> & simulationOutputs) { FILE * fp_in = fopen("gp/scalar/dakota_pstudy.dat", "r"); unsigned int i, id, size = 512; double k_tmasl, k_tmoml, k_tnrgl, k_xkwlx, k_cd, pressure; char line[size]; // First line is a header, so we ignore it fgets(line, size, fp_in); i = 0; while (fscanf(fp_in, "%d %lf %lf %lf %lf %lf %lf\n", &id, &k_tmasl, &k_tmoml, &k_tnrgl, &k_xkwlx, &k_cd, &pressure) != EOF) { (*(simulationScenarios[i]))[0] = 0.5; (*(simulationParameters[i]))[0] = k_tmasl; (*(simulationParameters[i]))[1] = k_tmoml; (*(simulationParameters[i]))[2] = k_tnrgl; (*(simulationParameters[i]))[3] = k_xkwlx; (*(simulationParameters[i]))[4] = k_cd; (*(simulationOutputs[i]))[0] = pressure; i++; } fclose(fp_in); } int main(int argc, char ** argv) { // Step 0: Set up some variables unsigned int numExperiments = 10; // Number of experiments unsigned int numUncertainVars = 5; // Number of things to calibrate unsigned int numSimulations = 50; // Number of simulations unsigned int numConfigVars = 1; // Dimension of configuration space unsigned int numEta = 1; // Number of responses the model is returning unsigned int experimentSize = 1; // Size of each experiment MPI_Init(&argc, &argv); // Step 1: Set up QUESO environment QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL); // Step 2: Set up prior for calibration parameters QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "param_", numUncertainVars, NULL); QUESO::GslVector paramMins(paramSpace.zeroVector()); paramMins.cwSet(0.0); QUESO::GslVector paramMaxs(paramSpace.zeroVector()); paramMaxs.cwSet(1.0); QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_", paramSpace, paramMins, paramMaxs); QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_", paramDomain); // Step 3: Instantiate the 'scenario' and 'output' spaces for simulation QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> configSpace(env, "scenario_", numConfigVars, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> nEtaSpace(env, "output_", numEta, NULL); // Step 4: Instantiate the 'output' space for the experiments QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> experimentSpace(env, "experimentspace_", experimentSize, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> totalExperimentSpace(env, "experimentspace_", experimentSize * numExperiments, NULL); // Step 5: Instantiate the Gaussian process emulator object // // Regarding simulation scenario input values, QUESO should standardise them // so that they exist inside a hypercube. // // Regarding simulation output data, QUESO should transform it so that the // mean is zero and the variance is one. // // Regarding experimental scenario input values, QUESO should standardize // them so that they exist inside a hypercube. // // Regarding experimental data, QUESO should transformed it so that it has // zero mean and variance one. // GaussianProcessEmulator stores all the information about our simulation // data and experimental data. It also stores default information about the // hyperparameter distributions. QUESO::GaussianProcessFactory<QUESO::GslVector, QUESO::GslMatrix> gpFactory("gp_", priorRv, configSpace, paramSpace, nEtaSpace, experimentSpace, numSimulations, numExperiments); // std::vector containing all the points in scenario space where we have // simulations std::vector<QUESO::GslVector *> simulationScenarios(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in parameter space where we have // simulations std::vector<QUESO::GslVector *> paramVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the simulation output data std::vector<QUESO::GslVector *> outputVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in scenario space where we have // experiments std::vector<QUESO::GslVector *> experimentScenarios(numExperiments, (QUESO::GslVector *) NULL); // std::vector containing all the experimental output data std::vector<QUESO::GslVector *> experimentVecs(numExperiments, (QUESO::GslVector *) NULL); // The experimental output data observation error covariance matrix QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector()); // Instantiate each of the simulation points/outputs for (unsigned int i = 0; i < numSimulations; i++) { simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}^*' in paper paramVecs [i] = new QUESO::GslVector(paramSpace.zeroVector()); // 't_{i+1}^*' in paper outputVecs [i] = new QUESO::GslVector(nEtaSpace.zeroVector()); // 'eta_{i+1}' in paper } for (unsigned int i = 0; i < numExperiments; i++) { experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}' in paper experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector()); } readExpData(experimentScenarios, experimentVecs); readSimData(simulationScenarios, paramVecs, outputVecs); for (unsigned int i = 0; i < 5; i++) { experimentMat(i, i) = 0.075 * 0.075; } // Add simulation and experimental data gpFactory.addSimulations(simulationScenarios, paramVecs, outputVecs); gpFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat); QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> postRv( "post_", gpFactory.prior().imageSet().vectorSpace()); QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("", NULL, gpFactory, postRv); QUESO::GslVector paramInitials( gpFactory.prior().imageSet().vectorSpace().zeroVector()); // Initial condition of the chain for (unsigned int i = 0; i < paramInitials.sizeLocal(); i++) { paramInitials[i] = 0.5; } QUESO::GslMatrix proposalCovMatrix( gpFactory.prior().imageSet().vectorSpace().zeroVector()); for (unsigned int i = 0; i < proposalCovMatrix.numRowsLocal(); i++) { proposalCovMatrix(i, i) = 0.01; } std::cout << "got here 25" << std::endl; ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix); std::cout << "got here 26" << std::endl; MPI_Finalize(); std::cout << "got here 27" << std::endl; return 0; } <commit_msg>Fixing up some parameters for gp example<commit_after>#include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/UniformVectorRV.h> #include <queso/StatisticalInverseProblem.h> #include <queso/VectorSet.h> #include <queso/GaussianProcessEmulator.h> #include <cstdio> // Read in data files void readExpData(const std::vector<QUESO::GslVector *> & experimentScenarios, const std::vector<QUESO::GslVector *> & experimentOutputs) { FILE * fp_in = fopen("gp/scalar/ctf_dat.txt", "r"); unsigned int i = 0; double pressure; while (fscanf(fp_in, "%lf\n", &pressure) != EOF) { (*(experimentOutputs[i]))[0] = pressure; i++; } fclose(fp_in); } void readSimData(const std::vector<QUESO::GslVector *> & simulationScenarios, const std::vector<QUESO::GslVector *> & simulationParameters, const std::vector<QUESO::GslVector *> & simulationOutputs) { FILE * fp_in = fopen("gp/scalar/dakota_pstudy.dat", "r"); unsigned int i, id, size = 512; double k_tmasl, k_tmoml, k_tnrgl, k_xkwlx, k_cd, pressure; char line[size]; // First line is a header, so we ignore it fgets(line, size, fp_in); i = 0; while (fscanf(fp_in, "%d %lf %lf %lf %lf %lf %lf\n", &id, &k_tmasl, &k_tmoml, &k_tnrgl, &k_xkwlx, &k_cd, &pressure) != EOF) { (*(simulationScenarios[i]))[0] = 0.5; (*(simulationParameters[i]))[0] = k_tmasl; (*(simulationParameters[i]))[1] = k_tmoml; (*(simulationParameters[i]))[2] = k_tnrgl; (*(simulationParameters[i]))[3] = k_xkwlx; (*(simulationParameters[i]))[4] = k_cd; (*(simulationOutputs[i]))[0] = pressure; i++; } fclose(fp_in); } int main(int argc, char ** argv) { // Step 0: Set up some variables unsigned int numExperiments = 10; // Number of experiments unsigned int numUncertainVars = 5; // Number of things to calibrate unsigned int numSimulations = 50; // Number of simulations unsigned int numConfigVars = 1; // Dimension of configuration space unsigned int numEta = 1; // Number of responses the model is returning unsigned int experimentSize = 1; // Size of each experiment MPI_Init(&argc, &argv); // Step 1: Set up QUESO environment QUESO::FullEnvironment env(MPI_COMM_WORLD, argv[1], "", NULL); // Step 2: Set up prior for calibration parameters QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> paramSpace(env, "param_", numUncertainVars, NULL); // Parameter (theta) bounds: // upper_bounds 1.05 1.1 1.1 1.1 1.1 // lower_bounds 0.95 0.9 0.9 0.9 0.9 // descriptors 'k_tmasl' 'k_xkle' 'k_xkwew' 'k_xkwlx' 'k_cd' QUESO::GslVector paramMins(paramSpace.zeroVector()); QUESO::GslVector paramMaxs(paramSpace.zeroVector()); paramMins.cwSet(0.9); paramMaxs.cwSet(1.1); paramMins[0] = 0.95; paramMaxs[0] = 1.05; QUESO::BoxSubset<QUESO::GslVector, QUESO::GslMatrix> paramDomain("param_", paramSpace, paramMins, paramMaxs); QUESO::UniformVectorRV<QUESO::GslVector, QUESO::GslMatrix> priorRv("prior_", paramDomain); // Step 3: Instantiate the 'scenario' and 'output' spaces for simulation QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> configSpace(env, "scenario_", numConfigVars, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> nEtaSpace(env, "output_", numEta, NULL); // Step 4: Instantiate the 'output' space for the experiments QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> experimentSpace(env, "experimentspace_", experimentSize, NULL); QUESO::VectorSpace<QUESO::GslVector, QUESO::GslMatrix> totalExperimentSpace(env, "experimentspace_", experimentSize * numExperiments, NULL); // Step 5: Instantiate the Gaussian process emulator object // // Regarding simulation scenario input values, QUESO should standardise them // so that they exist inside a hypercube. // // Regarding simulation output data, QUESO should transform it so that the // mean is zero and the variance is one. // // Regarding experimental scenario input values, QUESO should standardize // them so that they exist inside a hypercube. // // Regarding experimental data, QUESO should transformed it so that it has // zero mean and variance one. // GaussianProcessEmulator stores all the information about our simulation // data and experimental data. It also stores default information about the // hyperparameter distributions. QUESO::GaussianProcessFactory<QUESO::GslVector, QUESO::GslMatrix> gpFactory("gp_", priorRv, configSpace, paramSpace, nEtaSpace, experimentSpace, numSimulations, numExperiments); // std::vector containing all the points in scenario space where we have // simulations std::vector<QUESO::GslVector *> simulationScenarios(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in parameter space where we have // simulations std::vector<QUESO::GslVector *> paramVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the simulation output data std::vector<QUESO::GslVector *> outputVecs(numSimulations, (QUESO::GslVector *) NULL); // std::vector containing all the points in scenario space where we have // experiments std::vector<QUESO::GslVector *> experimentScenarios(numExperiments, (QUESO::GslVector *) NULL); // std::vector containing all the experimental output data std::vector<QUESO::GslVector *> experimentVecs(numExperiments, (QUESO::GslVector *) NULL); // The experimental output data observation error covariance matrix QUESO::GslMatrix experimentMat(totalExperimentSpace.zeroVector()); // Instantiate each of the simulation points/outputs for (unsigned int i = 0; i < numSimulations; i++) { simulationScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}^*' in paper paramVecs [i] = new QUESO::GslVector(paramSpace.zeroVector()); // 't_{i+1}^*' in paper outputVecs [i] = new QUESO::GslVector(nEtaSpace.zeroVector()); // 'eta_{i+1}' in paper } for (unsigned int i = 0; i < numExperiments; i++) { experimentScenarios[i] = new QUESO::GslVector(configSpace.zeroVector()); // 'x_{i+1}' in paper experimentVecs[i] = new QUESO::GslVector(experimentSpace.zeroVector()); } readExpData(experimentScenarios, experimentVecs); readSimData(simulationScenarios, paramVecs, outputVecs); for (unsigned int i = 0; i < numExperiments; i++) { experimentMat(i, i) = 0.025 * 0.025; } // Add simulation and experimental data gpFactory.addSimulations(simulationScenarios, paramVecs, outputVecs); gpFactory.addExperiments(experimentScenarios, experimentVecs, &experimentMat); QUESO::GenericVectorRV<QUESO::GslVector, QUESO::GslMatrix> postRv( "post_", gpFactory.prior().imageSet().vectorSpace()); QUESO::StatisticalInverseProblem<QUESO::GslVector, QUESO::GslMatrix> ip("", NULL, gpFactory, postRv); QUESO::GslVector paramInitials( gpFactory.prior().imageSet().vectorSpace().zeroVector()); // Initial condition of the chain for (unsigned int i = 0; i < paramInitials.sizeLocal(); i++) { paramInitials[i] = 0.95; } QUESO::GslMatrix proposalCovMatrix( gpFactory.prior().imageSet().vectorSpace().zeroVector()); for (unsigned int i = 0; i < proposalCovMatrix.numRowsLocal(); i++) { proposalCovMatrix(i, i) = 0.01; } std::cout << "got here 25" << std::endl; ip.solveWithBayesMetropolisHastings(NULL, paramInitials, &proposalCovMatrix); std::cout << "got here 26" << std::endl; MPI_Finalize(); std::cout << "got here 27" << std::endl; return 0; } <|endoftext|>
<commit_before>/** Copyright (c) 2016, Philip Deegan. 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 Philip Deegan 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 _KUL_DB_HPP_ #define _KUL_DB_HPP_ #include <vector> #include <sstream> #include "kul/map.hpp" #include "kul/except.hpp" #include "kul/db/def.hpp" namespace kul{ namespace db{ class Exception : public kul::Exception{ public: Exception(const char*f, const uint16_t& l, std::string s) : kul::Exception(f, l, s){} }; } class ORM; class DB{ protected: const std::string n; DB(const std::string& n = "") : n(n){} friend class kul::ORM; public: virtual std::string exec_return(const std::string& sql) throw(db::Exception) = 0; virtual void exec(const std::string& s) throw(db::Exception) = 0; }; namespace orm{ template <class T> class AObject{ private: bool n = 1; kul::hash::set::String di; kul::hash::map::S2S fs; template <class R> friend std::ostream& operator<<(std::ostream&, const AObject<R>&); protected: const std::string& field(const std::string& s) const{ if(!fs.count(s)) KEXCEPTION("ORM error, no field: " + s); return (*fs.find(s)).second; } template<class R> const R field(const std::string& s) const{ std::stringstream ss(field(s)); R r; ss >> r; return r; } public: const std::string& created() const { return (*fs.find(_KUL_DB_CREATED_COL_)).second; } const std::string& updated() const { return (*fs.find(_KUL_DB_UPDATED_COL_)).second; } template<class V = std::string> AObject<T>& set(const std::string& s, const V& v){ std::stringstream ss; ss << v; fs.insert(s, ss.str()); di.insert(s); return *this; } const std::string& operator[](const std::string& s) const{ return field(s); } template<class R> R get(const std::string& s) const{ return this->template field<R>(s); } friend class kul::ORM; }; template <class T> std::ostream& operator<<(std::ostream &s, const kul::orm::AObject<T>& o); } class ORM{ protected: DB& db; virtual void populate(const std::string& s, std::vector<kul::hash::map::S2S>& vals) = 0; template <class T> std::string table(){ return db.n.size() ? (db.n+"."+T::TABLE()) : T::TABLE(); } template <class T> void update(orm::AObject<T>& o){ if(o.di.size() == 0) return; std::time_t now = std::time(0); std::stringstream ss; ss << "UPDATE " << table<T>() << " SET "; for(const auto& d : o.di) ss << d << "='" << o.fs[d] << "',"; ss << " updated = " << now; ss << " WHERE id = '" << o.fs[_KUL_DB_ID_COL_] << "'"; db.exec(ss.str()); o.set(_KUL_DB_UPDATED_COL_, now); o.di.clear(); } template <class T> void insert(orm::AObject<T>& o){ std::time_t now = std::time(0); std::string nsw = std::to_string(now); std::stringstream ss; ss << "INSERT INTO " << table<T>() << "("; for(const auto& p : o.fs) ss << p.first << ", "; ss << _KUL_DB_CREATED_COL_ << " ," << _KUL_DB_UPDATED_COL_ << ") VALUES("; for(const auto& p : o.fs) ss << "'" << p.second << "', "; ss << now << ", " << now << ") RETURNING " << _KUL_DB_ID_COL_; o.fs.insert(_KUL_DB_ID_COL_ , db.exec_return(ss.str())); o.fs.insert(_KUL_DB_CREATED_COL_, nsw); o.fs.insert(_KUL_DB_UPDATED_COL_, nsw); o.n = 0; o.di.clear(); } public: ORM(DB& db) : db(db){} template <class T> void commit(orm::AObject<T>& o){ if(o.n) insert(o); else update(o); } template <class T> void remove(const orm::AObject<T>& o){ std::stringstream ss; ss << "DELETE FROM " << table<T>() << " t WHERE t." << _KUL_DB_ID_COL_ << " = '" << o[_KUL_DB_ID_COL_] << "'"; db.exec(ss.str()); } template <class T> void remove(const std::string& w){ std::stringstream ss; ss << "DELETE FROM " << table<T>() << " t WHERE t." << w; db.exec(ss.str()); } template <class T> void get(std::vector<T>& ts, const std::string& w = "", const uint16_t& l = 100, const uint16_t& o = 0, const std::string& g = ""){ std::stringstream ss; ss << "SELECT * FROM " << table<T>() << " t "; if(!w.empty()) ss << " WHERE " << w; ss << " LIMIT " << l << " OFFSET " << o; if(!g.empty()) ss << " GROUP BY " << g; for(auto& t : ts) t.n = 0; std::vector<kul::hash::map::S2S> vals; populate(ss.str(), vals); for(const auto& v : vals){ T t; for(const auto& m : v) t.fs.insert(m.first, m.second); ts.push_back(t); } } template <class T, class V = std::string> T by(const std::string& c, const V& v) throw(db::Exception) { std::vector<T> ts; std::stringstream ss, id; id << v; ss << "t." << c << " = '" << v << "'"; get(ts, ss.str(), 2, 0); if(ts.size() == 0) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" does not exist"); if(ts.size() > 1) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" is a duplicate"); return ts[0]; } template <class T> T id(const _KUL_DB_ID_TYPE_& id) throw(db::Exception) { return by<T, _KUL_DB_ID_TYPE_>(_KUL_DB_ID_COL_, id); } }; } template <class T> std::ostream& kul::orm::operator<<(std::ostream &s, const kul::orm::AObject<T>& o){ std::stringstream ss; for(const auto& p : o.fs) ss << p.first << " : " << p.second << std::endl; return s << ss.str(); } #endif /* _KUL_DB_HPP_ */ <commit_msg>set update order<commit_after>/** Copyright (c) 2016, Philip Deegan. 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 Philip Deegan 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 _KUL_DB_HPP_ #define _KUL_DB_HPP_ #include <vector> #include <sstream> #include "kul/map.hpp" #include "kul/except.hpp" #include "kul/db/def.hpp" namespace kul{ namespace db{ class Exception : public kul::Exception{ public: Exception(const char*f, const uint16_t& l, std::string s) : kul::Exception(f, l, s){} }; } class ORM; class DB{ protected: const std::string n; DB(const std::string& n = "") : n(n){} friend class kul::ORM; public: virtual std::string exec_return(const std::string& sql) throw(db::Exception) = 0; virtual void exec(const std::string& s) throw(db::Exception) = 0; }; namespace orm{ template <class T> class AObject{ private: bool n = 1; kul::hash::set::String di; kul::hash::map::S2S fs; template <class R> friend std::ostream& operator<<(std::ostream&, const AObject<R>&); protected: const std::string& field(const std::string& s) const{ if(!fs.count(s)) KEXCEPTION("ORM error, no field: " + s); return (*fs.find(s)).second; } template<class R> const R field(const std::string& s) const{ std::stringstream ss(field(s)); R r; ss >> r; return r; } public: const std::string& created() const { return (*fs.find(_KUL_DB_CREATED_COL_)).second; } const std::string& updated() const { return (*fs.find(_KUL_DB_UPDATED_COL_)).second; } template<class V = std::string> AObject<T>& set(const std::string& s, const V& v){ std::stringstream ss; ss << v; fs.insert(s, ss.str()); di.insert(s); return *this; } const std::string& operator[](const std::string& s) const{ return field(s); } template<class R> R get(const std::string& s) const{ return this->template field<R>(s); } friend class kul::ORM; }; template <class T> std::ostream& operator<<(std::ostream &s, const kul::orm::AObject<T>& o); } class ORM{ protected: DB& db; virtual void populate(const std::string& s, std::vector<kul::hash::map::S2S>& vals) = 0; template <class T> std::string table(){ return db.n.size() ? (db.n+"."+T::TABLE()) : T::TABLE(); } template <class T> void update(orm::AObject<T>& o){ if(o.di.size() == 0) return; std::time_t now = std::time(0); o.set(_KUL_DB_UPDATED_COL_, now); std::stringstream ss; ss << "UPDATE " << table<T>() << " SET "; for(const auto& d : o.di) ss << d << "='" << o.fs[d] << "',"; ss << " updated = " << now; ss << " WHERE " << _KUL_DB_ID_COL_ << " = '" << o.fs[_KUL_DB_ID_COL_] << "'"; db.exec(ss.str()); o.di.clear(); } template <class T> void insert(orm::AObject<T>& o){ std::time_t now = std::time(0); std::string nsw = std::to_string(now); std::stringstream ss; ss << "INSERT INTO " << table<T>() << "("; for(const auto& p : o.fs) ss << p.first << ", "; ss << _KUL_DB_CREATED_COL_ << " ," << _KUL_DB_UPDATED_COL_ << ") VALUES("; for(const auto& p : o.fs) ss << "'" << p.second << "', "; ss << now << ", " << now << ") RETURNING " << _KUL_DB_ID_COL_; o.fs.insert(_KUL_DB_ID_COL_ , db.exec_return(ss.str())); o.fs.insert(_KUL_DB_CREATED_COL_, nsw); o.fs.insert(_KUL_DB_UPDATED_COL_, nsw); o.n = 0; o.di.clear(); } public: ORM(DB& db) : db(db){} template <class T> void commit(orm::AObject<T>& o){ if(o.n) insert(o); else update(o); } template <class T> void remove(const orm::AObject<T>& o){ std::stringstream ss; ss << "DELETE FROM " << table<T>() << " t WHERE t." << _KUL_DB_ID_COL_ << " = '" << o[_KUL_DB_ID_COL_] << "'"; db.exec(ss.str()); } template <class T> void remove(const std::string& w){ std::stringstream ss; ss << "DELETE FROM " << table<T>() << " t WHERE t." << w; db.exec(ss.str()); } template <class T> void get(std::vector<T>& ts, const std::string& w = "", const uint16_t& l = 100, const uint16_t& o = 0, const std::string& g = ""){ std::stringstream ss; ss << "SELECT * FROM " << table<T>() << " t "; if(!w.empty()) ss << " WHERE " << w; ss << " LIMIT " << l << " OFFSET " << o; if(!g.empty()) ss << " GROUP BY " << g; std::vector<kul::hash::map::S2S> vals; populate(ss.str(), vals); for(const auto& v : vals){ T t; for(const auto& m : v) t.fs.insert(m.first, m.second); t.n = 0; ts.push_back(t); } } template <class T, class V = std::string> T by(const std::string& c, const V& v) throw(db::Exception) { std::vector<T> ts; std::stringstream ss, id; id << v; ss << "t." << c << " = '" << v << "'"; get(ts, ss.str(), 2, 0); if(ts.size() == 0) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" does not exist"); if(ts.size() > 1) KEXCEPT(db::Exception, "Table("+table<T>()+") : "+ _KUL_DB_ID_COL_ +":"+ id.str() +" is a duplicate"); return ts[0]; } template <class T> T id(const _KUL_DB_ID_TYPE_& id) throw(db::Exception) { return by<T, _KUL_DB_ID_TYPE_>(_KUL_DB_ID_COL_, id); } }; } template <class T> std::ostream& kul::orm::operator<<(std::ostream &s, const kul::orm::AObject<T>& o){ std::stringstream ss; for(const auto& p : o.fs) ss << p.first << " : " << p.second << std::endl; return s << ss.str(); } #endif /* _KUL_DB_HPP_ */ <|endoftext|>
<commit_before>/* Copyright (c) 2016 Cornell University * * 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 "MemServerIndication.h" #include "MainIndication.h" #include "MainRequest.h" #include "GeneratedTypes.h" #include "lutils.h" #include "lpcap.h" #define DATA_WIDTH 128 static MainRequestProxy *device = 0; void device_writePacketData(uint64_t* data, uint8_t* mask, int sop, int eop) { device->writePacketData(data, mask, sop, eop); } class MainIndication : public MainIndicationWrapper { public: virtual void read_version_rsp(uint32_t a) { fprintf(stderr, "version %x\n", a); } MainIndication(unsigned int id): MainIndicationWrapper(id) {} }; class MemServerIndication : public MemServerIndicationWrapper { public: virtual void error(uint32_t code, uint32_t sglId, uint64_t offset, uint64_t extra) { fprintf(stderr, "memServer Indication.error=%d\n", code); } virtual void addrResponse ( const uint64_t physAddr ) { fprintf(stderr, "phyaddr=%lx\n", physAddr); } virtual void reportStateDbg ( const DmaDbgRec rec ) { fprintf(stderr, "rec\n"); } virtual void reportMemoryTraffic ( const uint64_t words ) { fprintf(stderr, "words %lx\n", words); } MemServerIndication(unsigned int id) : MemServerIndicationWrapper(id) {} }; void usage (const char *program_name) { printf("%s: p4fpga tester\n" "usage: %s [OPTIONS] \n", program_name, program_name); printf("\nOther options:\n" " -p, --parser=FILE demo parsing pcap log\n" ); } static void parse_options(int argc, char *argv[], char **pcap_file, struct arg_info* info) { int c, option_index; static struct option long_options [] = { {"help", no_argument, 0, 'h'}, {"pcap", required_argument, 0, 'p'}, {0, 0, 0, 0} }; static std::string short_options (long_options_to_short_options(long_options)); for (;;) { c = getopt_long(argc, argv, short_options.c_str(), long_options, &option_index); if (c == -1) break; switch (c) { case 'h': usage(get_exe_name(argv[0])); break; case 'p': *pcap_file = optarg; break; default: break; } } } int main(int argc, char **argv) { char *pcap_file=NULL; struct pcap_trace_info pcap_info = {0, 0}; MainIndication echoindication(IfcNames_MainIndicationH2S); device = new MainRequestProxy(IfcNames_MainRequestS2H); parse_options(argc, argv, &pcap_file, 0); device->set_verbosity(4); device->read_version(); if (pcap_file) { fprintf(stderr, "Attempts to read pcap file %s\n", pcap_file); load_pcap_file(pcap_file, &pcap_info); } sleep(3); return 0; } <commit_msg>modified main for l2forwarding<commit_after>/* Copyright (c) 2016 Cornell University * * 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 "MemServerIndication.h" #include "MainIndication.h" #include "MainRequest.h" #include "GeneratedTypes.h" #include "lutils.h" #include "lpcap.h" #include <pcap.h> #include <pthread.h> #define DATA_WIDTH 128 #define MAXBYTES2CAPTURE 2048 #define BUFFSIZE 4096 static MainRequestProxy *device = 0; char* pktbuf=NULL; char* p=NULL; int size = 0; static bool tosend = false; void device_writePacketData(uint64_t* data, uint8_t* mask, int sop, int eop) { device->writePacketData(data, mask, sop, eop); } class MainIndication : public MainIndicationWrapper { public: virtual void read_version_rsp(uint32_t a) { fprintf(stderr, "version %x\n", a); } virtual void readPacketData(const uint64_t data, const uint8_t mask, const uint8_t sop, const uint8_t eop) { //fprintf(stderr, "Rdata %016lx, mask %02x, sop %x eop %x\n", data, mask, sop, eop); if (sop == 1) { pktbuf = (char *) malloc(4096); p = pktbuf; } memcpy(p, &data, 8); int bits = (mask * 01001001001ULL & 042104210421ULL) % 017; p += bits; size += bits; if (eop == 1) { tosend = true; } } MainIndication(unsigned int id): MainIndicationWrapper(id) {} }; class MemServerIndication : public MemServerIndicationWrapper { public: virtual void error(uint32_t code, uint32_t sglId, uint64_t offset, uint64_t extra) { fprintf(stderr, "memServer Indication.error=%d\n", code); } virtual void addrResponse ( const uint64_t physAddr ) { fprintf(stderr, "phyaddr=%lx\n", physAddr); } virtual void reportStateDbg ( const DmaDbgRec rec ) { fprintf(stderr, "rec\n"); } virtual void reportMemoryTraffic ( const uint64_t words ) { fprintf(stderr, "words %lx\n", words); } MemServerIndication(unsigned int id) : MemServerIndicationWrapper(id) {} }; void usage (const char *program_name) { printf("%s: p4fpga tester\n" "usage: %s [OPTIONS] \n", program_name, program_name); printf("\nOther options:\n" " -p, --parser=FILE pcap trace to run\n" " -I, --intf=interface listen on interface\n" ); } static void parse_options(int argc, char *argv[], char **pcap_file, char **intf, char **outf, struct arg_info* info) { int c, option_index; static struct option long_options [] = { {"help", no_argument, 0, 'h'}, {"pcap", required_argument, 0, 'p'}, {"intf", required_argument, 0, 'I'}, {"outf", required_argument, 0, 'O'}, {0, 0, 0, 0} }; static std::string short_options (long_options_to_short_options(long_options)); for (;;) { c = getopt_long(argc, argv, short_options.c_str(), long_options, &option_index); if (c == -1) break; switch (c) { case 'h': usage(get_exe_name(argv[0])); break; case 'p': *pcap_file = optarg; break; case 'I': fprintf(stderr, "%s", optarg); *intf = optarg; break; case 'O': fprintf(stderr, "%s", optarg); *outf = optarg; break; default: break; } } } /* processPacket(): Callback function called by pcap_loop() everytime a packet */ /* arrives to the network card. This function prints the captured raw data in */ /* hexadecimal. */ void processPacket(u_char *arg, const struct pcap_pkthdr* pkthdr, const u_char * packet){ int *counter = (int *)arg; printf("Packet Count: %d\n", ++(*counter)); printf("Received Packet Size: %d\n", pkthdr->len); // mem_copy(packet, pkthdr->len); return; } void *captureThread(void * pcapt) { pcap_t * pt; int count=0; pt = (pcap_t *)pcapt; pcap_loop(pt, -1, processPacket, (u_char*)&count); /* should not be reached */ pcap_close(pt); return NULL; } void *sendThread(void *pcapt) { pcap_t *pt; pt = (pcap_t *)pcapt; while (1) { if (tosend) { fprintf(stderr, "inject packet %d\n", size); pcap_inject(pt, pktbuf, size); tosend = false; size = 0; } usleep(100); } return NULL; } int main(int argc, char **argv) { char *pcap_file=NULL; pcap_t *handle = NULL, *handle2=NULL; pthread_t t_cap, t_snd; char errbuf[PCAP_ERRBUF_SIZE], *intf=NULL, *outf=NULL; memset(errbuf,0,PCAP_ERRBUF_SIZE); struct pcap_trace_info pcap_info = {0, 0}; MainIndication echoindication(IfcNames_MainIndicationH2S); device = new MainRequestProxy(IfcNames_MainRequestS2H); parse_options(argc, argv, &pcap_file, &intf, &outf, 0); device->set_verbosity(4); device->read_version(); device->forward_tbl_add_entry(0x3417EB96BF1C,0x200); device->forward_tbl_add_entry(0x01005E002002,0x200); if (intf) { printf("Opening device %s\n", intf); /* Open device in promiscuous mode */ if ((handle = pcap_open_live(intf, MAXBYTES2CAPTURE, 0, 512, errbuf)) == NULL){ fprintf(stderr, "ERROR: %s\n", errbuf); exit(1); } pthread_create(&t_cap, NULL, captureThread, (void*)handle); if (outf) { printf("Opening device %s\n", outf); if ((handle2 = pcap_open_live(outf, MAXBYTES2CAPTURE, 0, 512, errbuf)) == NULL) { fprintf(stderr, "ERROR: %s\n", errbuf); exit(1); } pthread_create(&t_snd, NULL, sendThread, (void*)handle2); } pthread_join(t_cap, NULL); pthread_join(t_snd, NULL); /* Loop forever & call processPacket() for every received packet */ //if (pcap_loop(pt, -1, processPacket, (u_char *)&count) == -1){ // fprintf(stderr, "ERROR: %s\n", pcap_geterr(pt) ); // exit(1); //} } if (pcap_file) { fprintf(stderr, "Attempts to read pcap file %s\n", pcap_file); load_pcap_file(pcap_file, &pcap_info); } sleep(3); return 0; } <|endoftext|>
<commit_before>#include "curltools.h" #include "json_spirit.h" #include <boost/thread.hpp> #include <iostream> #include <openssl/ssl.h> boost::once_flag init_openssl_once_flag = BOOST_ONCE_INIT; boost::once_flag init_curl_global_once_flag = BOOST_ONCE_INIT; boost::mutex curl_global_init_lock; class CurlCleaner { CURL* curl_obj_to_clean; public: CurlCleaner(CURL* Curl_obj_to_clean) : curl_obj_to_clean(Curl_obj_to_clean) {} ~CurlCleaner() { curl_easy_cleanup(curl_obj_to_clean); } }; size_t cURLTools::CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::deque<char>* s) { size_t newLength = size * nmemb; size_t oldLength = s->size(); try { s->resize(oldLength + newLength); } catch (std::bad_alloc& e) { std::stringstream msg; msg << "Error allocating memory: " << e.what() << std::endl; printf("%s", msg.str().c_str()); return 0; } std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength); return size * nmemb; } size_t cURLTools::CurlRead_CallbackFunc_StdString(void* dest, size_t /*size*/, size_t /*nmemb*/, void* userp) { std::string* from = (std::string*)userp; std::string* to = (std::string*)dest; std::copy(from->begin(), from->end(), std::back_inserter(*to)); return 0; /* no more data left to deliver */ } size_t cURLTools::CurlWrite_CallbackFunc_File(void* contents, size_t size, size_t nmemb, boost::filesystem::fstream* fs) { size_t newLength = size * nmemb; fs->write(reinterpret_cast<char*>(contents), newLength); return size * nmemb; } int cURLTools::CurlProgress_CallbackFunc(void*, double TotalToDownload, double NowDownloaded, double /*TotalToUpload*/, double /*NowUploaded*/) { std::clog << "Download progress: " << ToString(NowDownloaded) << " / " << ToString(TotalToDownload) << std::endl; return CURLE_OK; } int cURLTools::CurlAtomicProgress_CallbackFunc(void* number, double TotalToDownload, double NowDownloaded, double /*TotalToUpload*/, double /*NowUploaded*/) { std::atomic<float>* progress = reinterpret_cast<std::atomic<float>*>(number); float val = 0; if (TotalToDownload > 0.) { val = static_cast<float>(100. * NowDownloaded / TotalToDownload); if (val < 0.0001) { val = 0; } } progress->store(val, std::memory_order_relaxed); return CURLE_OK; } void cURLTools::CurlGlobalInit_ThreadSafe() { boost::lock_guard<boost::mutex> lg(curl_global_init_lock); curl_global_init(CURL_GLOBAL_DEFAULT); } void cURLTools::GetLargeFileFromHTTPS(const std::string& URL, long ConnectionTimeout, const boost::filesystem::path& targetPath, std::atomic<float>& progress) { #if OPENSSL_VERSION_NUMBER < 0x10100000L boost::call_once(init_openssl_once_flag, SSL_library_init); #else boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL)); #endif CURL* curl; CURLcode res; boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe); curl = curl_easy_init(); boost::filesystem::fstream outputStream(targetPath, std::ios::out | std::ios::binary); if (curl) { CurlCleaner cleaner(curl); curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // verify ssl peer curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); // verify ssl hostname curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_File); curl_easy_setopt(curl, CURLOPT_USERAGENT, "Dark Secret Ninja/1.0"); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outputStream); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlAtomicProgress_CallbackFunc); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &progress); // curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); //verbose output curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) { std::string errorMsg(curl_easy_strerror(res)); throw std::runtime_error(std::string(errorMsg).c_str()); } else { long http_response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code); if (http_response_code != 200) { throw std::runtime_error("Error retrieving data with https protocol from URL \"" + URL + "\", error code: " + ToString(http_response_code) + ". Probably the URL is invalid."); } } /* always cleanup */ // This is replaced by a smart cleaning object with the destructor (CurlCleaner) // curl_easy_cleanup(curl); } } std::string cURLTools::GetFileFromHTTPS(const std::string& URL, long ConnectionTimeout, bool IncludeProgressBar) { #if OPENSSL_VERSION_NUMBER < 0x10100000L boost::call_once(init_openssl_once_flag, SSL_library_init); #else boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL)); #endif CURL* curl; CURLcode res; boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe); curl = curl_easy_init(); std::deque<char> s; if (curl) { CurlCleaner cleaner(curl); curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // verify ssl peer curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); // verify ssl hostname curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString); curl_easy_setopt(curl, CURLOPT_USERAGENT, "Dark Secret Ninja/1.0"); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); if (IncludeProgressBar) { curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlProgress_CallbackFunc); } else { curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true); } // curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); //verbose output curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) { std::string errorMsg(curl_easy_strerror(res)); throw std::runtime_error(std::string(errorMsg).c_str()); } else { long http_response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code); if (http_response_code != 200) { throw std::runtime_error("Error retrieving data with https protocol from URL \"" + URL + "\", error code: " + ToString(http_response_code) + ". Probably the URL is invalid."); } } /* always cleanup */ // This is replaced by a smart cleaning object with the destructor (CurlCleaner) // curl_easy_cleanup(curl); } std::string fileStr(s.begin(), s.end()); return fileStr; } std::string cURLTools::PostJsonToHTTPS(const std::string& URL, long ConnectionTimeout, const std::string& readdata, bool chunked) { #if OPENSSL_VERSION_NUMBER < 0x10100000L boost::call_once(init_openssl_once_flag, SSL_library_init); #else boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL)); #endif CURL* curl; CURLcode res; boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe); /* get a curl handle */ curl = curl_easy_init(); std::deque<char> writedata; if (curl) { CurlCleaner cleaner(curl); struct curl_slist* headers = NULL; /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); // curl_easy_setopt(curl, CURLOPT_READDATA, &readdata); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &writedata); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // verify ssl peer curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); // verify ssl hostname curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(curl, CURLOPT_READFUNCTION, CurlRead_CallbackFunc_StdString); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString); /* Now specify the POST data */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, readdata.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1); headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "charsets: utf-8"); // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); // verbose output curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout); if (chunked) { headers = curl_slist_append(headers, "Transfer-Encoding: chunked"); /* use curl_slist_free_all() after the *perform() call to free this list again */ } else { /* Set the expected POST size. If you want to POST large amounts of data, consider CURLOPT_POSTFIELDSIZE_LARGE */ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (curl_off_t)readdata.size()); } /* Using POST with HTTP 1.1 implies the use of a "Expect: 100-continue" header. You can disable this header with CURLOPT_HTTPHEADER as usual. NOTE: if you want chunked transfer too, you need to combine these two since you can only set one list of headers with CURLOPT_HTTPHEADER. */ /* A less good option would be to enforce HTTP 1.0, but that might also have other implications. */ const bool disable_expect = false; if (disable_expect) { headers = curl_slist_append(headers, "Expect:"); /* use curl_slist_free_all() after the *perform() call to free this list again */ } res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) { std::string errorMsg(curl_easy_strerror(res)); throw std::runtime_error(std::string(errorMsg).c_str()); } else { long http_response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code); if (http_response_code != 200) { json_spirit::Value errorData; if (json_spirit::read(std::string(writedata.begin(), writedata.end()), errorData)) { json_spirit::Value errorMsg; errorMsg = json_spirit::find_value(errorData.get_obj(), "message"); throw std::runtime_error("Failed to create transaction with error: " + errorMsg.get_str()); } else { throw std::runtime_error("Error posting data with https protocol from URL \"" + URL + "\", error code: " + ToString(http_response_code) + ". Probably the URL is invalid. Could not retrieve more " "information on the error."); } } } /* always cleanup */ // This is replaced by a smart cleaning object with the destructor (CurlCleaner) // curl_easy_cleanup(curl); } std::string fileStr(writedata.begin(), writedata.end()); return fileStr; } <commit_msg>More logging on curl.<commit_after>#include "curltools.h" #include "json_spirit.h" #include <boost/thread.hpp> #include <iostream> #include <openssl/ssl.h> boost::once_flag init_openssl_once_flag = BOOST_ONCE_INIT; boost::once_flag init_curl_global_once_flag = BOOST_ONCE_INIT; boost::mutex curl_global_init_lock; class CurlCleaner { CURL* curl_obj_to_clean; public: CurlCleaner(CURL* Curl_obj_to_clean) : curl_obj_to_clean(Curl_obj_to_clean) {} ~CurlCleaner() { curl_easy_cleanup(curl_obj_to_clean); } }; size_t cURLTools::CurlWrite_CallbackFunc_StdString(void* contents, size_t size, size_t nmemb, std::deque<char>* s) { size_t newLength = size * nmemb; size_t oldLength = s->size(); try { s->resize(oldLength + newLength); } catch (std::bad_alloc& e) { std::stringstream msg; msg << "Error allocating memory: " << e.what() << std::endl; printf("%s", msg.str().c_str()); return 0; } std::copy((char*)contents, (char*)contents + newLength, s->begin() + oldLength); return size * nmemb; } size_t cURLTools::CurlRead_CallbackFunc_StdString(void* dest, size_t /*size*/, size_t /*nmemb*/, void* userp) { std::string* from = (std::string*)userp; std::string* to = (std::string*)dest; std::copy(from->begin(), from->end(), std::back_inserter(*to)); return 0; /* no more data left to deliver */ } size_t cURLTools::CurlWrite_CallbackFunc_File(void* contents, size_t size, size_t nmemb, boost::filesystem::fstream* fs) { size_t newLength = size * nmemb; fs->write(reinterpret_cast<char*>(contents), newLength); return size * nmemb; } int cURLTools::CurlProgress_CallbackFunc(void*, double TotalToDownload, double NowDownloaded, double /*TotalToUpload*/, double /*NowUploaded*/) { std::clog << "Download progress: " << ToString(NowDownloaded) << " / " << ToString(TotalToDownload) << std::endl; return CURLE_OK; } int cURLTools::CurlAtomicProgress_CallbackFunc(void* number, double TotalToDownload, double NowDownloaded, double /*TotalToUpload*/, double /*NowUploaded*/) { std::atomic<float>* progress = reinterpret_cast<std::atomic<float>*>(number); float val = 0; if (TotalToDownload > 0.) { val = static_cast<float>(100. * NowDownloaded / TotalToDownload); if (val < 0.0001) { val = 0; } } progress->store(val, std::memory_order_relaxed); return CURLE_OK; } void cURLTools::CurlGlobalInit_ThreadSafe() { boost::lock_guard<boost::mutex> lg(curl_global_init_lock); curl_global_init(CURL_GLOBAL_DEFAULT); } void cURLTools::GetLargeFileFromHTTPS(const std::string& URL, long ConnectionTimeout, const boost::filesystem::path& targetPath, std::atomic<float>& progress) { #if OPENSSL_VERSION_NUMBER < 0x10100000L boost::call_once(init_openssl_once_flag, SSL_library_init); #else boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL)); #endif CURL* curl; CURLcode res; boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe); curl = curl_easy_init(); boost::filesystem::fstream outputStream(targetPath, std::ios::out | std::ios::binary); if (curl) { CurlCleaner cleaner(curl); curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // verify ssl peer curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); // verify ssl hostname curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_File); curl_easy_setopt(curl, CURLOPT_USERAGENT, "Dark Secret Ninja/1.0"); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outputStream); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlAtomicProgress_CallbackFunc); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &progress); // curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); //verbose output curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) { std::string errorMsg(curl_easy_strerror(res)); printf("Curl error: %s", errorMsg.c_str()); throw std::runtime_error(std::string(errorMsg).c_str()); } else { long http_response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code); if (http_response_code != 200) { std::string errorMsg("Error retrieving data with https protocol from URL \"" + URL + "\", error code: " + ToString(http_response_code) + ". Probably the URL is invalid."); printf("Curl http code error: %s", errorMsg.c_str()); throw std::runtime_error(errorMsg); } } /* always cleanup */ // This is replaced by a smart cleaning object with the destructor (CurlCleaner) // curl_easy_cleanup(curl); } } std::string cURLTools::GetFileFromHTTPS(const std::string& URL, long ConnectionTimeout, bool IncludeProgressBar) { #if OPENSSL_VERSION_NUMBER < 0x10100000L boost::call_once(init_openssl_once_flag, SSL_library_init); #else boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL)); #endif CURL* curl; CURLcode res; boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe); curl = curl_easy_init(); std::deque<char> s; if (curl) { CurlCleaner cleaner(curl); curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // verify ssl peer curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); // verify ssl hostname curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString); curl_easy_setopt(curl, CURLOPT_USERAGENT, "Dark Secret Ninja/1.0"); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); if (IncludeProgressBar) { curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, CurlProgress_CallbackFunc); } else { curl_easy_setopt(curl, CURLOPT_NOPROGRESS, true); } // curl_easy_setopt (curl, CURLOPT_VERBOSE, 1L); //verbose output curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) { std::string errorMsg(curl_easy_strerror(res)); throw std::runtime_error(std::string(errorMsg).c_str()); } else { long http_response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code); if (http_response_code != 200) { throw std::runtime_error("Error retrieving data with https protocol from URL \"" + URL + "\", error code: " + ToString(http_response_code) + ". Probably the URL is invalid."); } } /* always cleanup */ // This is replaced by a smart cleaning object with the destructor (CurlCleaner) // curl_easy_cleanup(curl); } std::string fileStr(s.begin(), s.end()); return fileStr; } std::string cURLTools::PostJsonToHTTPS(const std::string& URL, long ConnectionTimeout, const std::string& readdata, bool chunked) { #if OPENSSL_VERSION_NUMBER < 0x10100000L boost::call_once(init_openssl_once_flag, SSL_library_init); #else boost::call_once(init_openssl_once_flag, OPENSSL_init_ssl, 0, static_cast<const ossl_init_settings_st*>(NULL)); #endif CURL* curl; CURLcode res; boost::call_once(init_curl_global_once_flag, CurlGlobalInit_ThreadSafe); /* get a curl handle */ curl = curl_easy_init(); std::deque<char> writedata; if (curl) { CurlCleaner cleaner(curl); struct curl_slist* headers = NULL; /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, URL.c_str()); // curl_easy_setopt(curl, CURLOPT_READDATA, &readdata); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &writedata); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); // verify ssl peer curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); // verify ssl hostname curl_easy_setopt(curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); curl_easy_setopt(curl, CURLOPT_READFUNCTION, CurlRead_CallbackFunc_StdString); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString); /* Now specify the POST data */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, readdata.c_str()); curl_easy_setopt(curl, CURLOPT_POST, 1); headers = curl_slist_append(headers, "Content-Type: application/json"); headers = curl_slist_append(headers, "charsets: utf-8"); // curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); // verbose output curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, ConnectionTimeout); if (chunked) { headers = curl_slist_append(headers, "Transfer-Encoding: chunked"); /* use curl_slist_free_all() after the *perform() call to free this list again */ } else { /* Set the expected POST size. If you want to POST large amounts of data, consider CURLOPT_POSTFIELDSIZE_LARGE */ curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (curl_off_t)readdata.size()); } /* Using POST with HTTP 1.1 implies the use of a "Expect: 100-continue" header. You can disable this header with CURLOPT_HTTPHEADER as usual. NOTE: if you want chunked transfer too, you need to combine these two since you can only set one list of headers with CURLOPT_HTTPHEADER. */ /* A less good option would be to enforce HTTP 1.0, but that might also have other implications. */ const bool disable_expect = false; if (disable_expect) { headers = curl_slist_append(headers, "Expect:"); /* use curl_slist_free_all() after the *perform() call to free this list again */ } res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if (res != CURLE_OK) { std::string errorMsg(curl_easy_strerror(res)); throw std::runtime_error(std::string(errorMsg).c_str()); } else { long http_response_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_response_code); if (http_response_code != 200) { json_spirit::Value errorData; if (json_spirit::read(std::string(writedata.begin(), writedata.end()), errorData)) { json_spirit::Value errorMsg; errorMsg = json_spirit::find_value(errorData.get_obj(), "message"); throw std::runtime_error("Failed to create transaction with error: " + errorMsg.get_str()); } else { throw std::runtime_error("Error posting data with https protocol from URL \"" + URL + "\", error code: " + ToString(http_response_code) + ". Probably the URL is invalid. Could not retrieve more " "information on the error."); } } } /* always cleanup */ // This is replaced by a smart cleaning object with the destructor (CurlCleaner) // curl_easy_cleanup(curl); } std::string fileStr(writedata.begin(), writedata.end()); return fileStr; } <|endoftext|>
<commit_before>#ifndef CTOOL_EXTRACT #define CTOOL_EXTRACT #include "ToolBase.hpp" #include <stdio.h> #if _WIN32 #include <conio.h> #else #include <termios.h> #endif class ToolExtract final : public ToolBase { HECL::Database::IDataSpec::ExtractPassInfo m_einfo; struct SpecExtractPass { const HECL::Database::DataSpecEntry* m_entry; std::unique_ptr<HECL::Database::IDataSpec> m_instance; SpecExtractPass(const HECL::Database::DataSpecEntry* entry, HECL::Database::IDataSpec* instance) : m_entry(entry), m_instance(instance) {} SpecExtractPass(const SpecExtractPass& other) = delete; SpecExtractPass(SpecExtractPass&& other) = default; }; std::vector<SpecExtractPass> m_specPasses; std::vector<HECL::Database::IDataSpec::ExtractReport> m_reps; std::unique_ptr<HECL::Database::Project> m_fallbackProj; HECL::Database::Project* m_useProj; public: ToolExtract(const ToolPassInfo& info) : ToolBase(info) { if (!m_info.args.size()) LogModule.report(LogVisor::FatalError, "hecl extract needs a source path as its first argument"); if (!info.project) { /* Get name from input file and init project there */ HECL::SystemString baseFile = info.args.front(); size_t slashPos = baseFile.rfind(_S('/')); if (slashPos == HECL::SystemString::npos) slashPos = baseFile.rfind(_S('\\')); if (slashPos != HECL::SystemString::npos) baseFile.assign(baseFile.begin() + slashPos + 1, baseFile.end()); size_t dotPos = baseFile.rfind(_S('.')); if (dotPos != HECL::SystemString::npos) baseFile.assign(baseFile.begin(), baseFile.begin() + dotPos); if (baseFile.empty()) LogModule.report(LogVisor::FatalError, "hecl extract must be ran within a project directory"); size_t ErrorRef = LogVisor::ErrorCount; HECL::SystemString rootDir = info.cwd + baseFile; HECL::ProjectRootPath newProjRoot(rootDir); newProjRoot.makeDir(); m_fallbackProj.reset(new HECL::Database::Project(newProjRoot)); if (LogVisor::ErrorCount > ErrorRef) LogModule.report(LogVisor::FatalError, "unable to init project at '%s'", rootDir.c_str()); LogModule.report(LogVisor::Info, _S("initialized project at '%s/.hecl'"), rootDir.c_str()); m_useProj = m_fallbackProj.get(); } else m_useProj = info.project; m_einfo.srcpath = m_info.args.front(); m_einfo.extractArgs.reserve(info.args.size() - 1); m_einfo.force = info.force; std::list<HECL::SystemString>::const_iterator it=info.args.begin(); ++it; for (;it != info.args.end(); ++it) m_einfo.extractArgs.push_back(*it); for (const HECL::Database::DataSpecEntry* entry : HECL::Database::DATA_SPEC_REGISTRY) { HECL::Database::IDataSpec* ds = entry->m_factory(*m_useProj, HECL::Database::TOOL_EXTRACT); if (ds) { if (ds->canExtract(m_einfo, m_reps)) m_specPasses.emplace_back(entry, ds); else delete ds; } } } static void Help(HelpOutput& help) { help.secHead(_S("NAME")); help.beginWrap(); help.wrap(_S("hecl-extract - Extract objects from supported package/image formats\n")); help.endWrap(); help.secHead(_S("SYNOPSIS")); help.beginWrap(); help.wrap(_S("hecl extract <packagefile> [<subnode>...]\n")); help.endWrap(); help.secHead(_S("DESCRIPTION")); help.beginWrap(); help.wrap(_S("This command recursively extracts all or part of a dataspec-supported ") _S("package format. Each object is decoded to a working format and added to the project.\n\n")); help.endWrap(); help.secHead(_S("OPTIONS")); help.optionHead(_S("<packagefile>[/<subnode>...]"), _S("input file")); help.beginWrap(); help.wrap(_S("Specifies the package file or disc image to source data from. ") _S("An optional subnode specifies a named hierarchical-node specific ") _S("to the game architecture (levels/areas).")); help.endWrap(); } HECL::SystemString toolName() const {return _S("extract");} static void _recursivePrint(int level, HECL::Database::IDataSpec::ExtractReport& rep) { for (int l=0 ; l<level ; ++l) HECL::Printf(_S(" ")); if (XTERM_COLOR) HECL::Printf(_S("" BOLD "%s" NORMAL ""), rep.name.c_str()); else HECL::Printf(_S("%s"), rep.name.c_str()); if (rep.desc.size()) HECL::Printf(_S(" [%s]"), rep.desc.c_str()); HECL::Printf(_S("\n")); for (HECL::Database::IDataSpec::ExtractReport& child : rep.childOpts) _recursivePrint(level + 1, child); } int run() { if (m_specPasses.empty()) { if (XTERM_COLOR) HECL::Printf(_S("" RED BOLD "NOTHING TO EXTRACT" NORMAL "\n")); else HECL::Printf(_S("NOTHING TO EXTRACT\n")); return -1; } if (XTERM_COLOR) HECL::Printf(_S("" GREEN BOLD "ABOUT TO EXTRACT:" NORMAL "\n")); else HECL::Printf(_S("ABOUT TO EXTRACT:\n")); for (HECL::Database::IDataSpec::ExtractReport& rep : m_reps) { _recursivePrint(0, rep); HECL::Printf(_S("\n")); } if (XTERM_COLOR) HECL::Printf(_S("\n" BLUE BOLD "Continue?" NORMAL " (Y/n) ")); else HECL::Printf(_S("\nContinue? (Y/n) ")); int ch; #ifndef _WIN32 struct termios tioOld, tioNew; tcgetattr(0, &tioOld); tioNew = tioOld; tioNew.c_lflag &= ~ICANON; tcsetattr(0, TCSANOW, &tioNew); while ((ch = getchar())) #else while ((ch = getch())) #endif { if (ch == 'n' || ch == 'N') return 0; if (ch == 'y' || ch == 'Y' || ch == '\r' || ch == '\n') break; } #ifndef _WIN32 tcsetattr(0, TCSANOW, &tioOld); #endif HECL::Printf(_S("\n")); for (SpecExtractPass& ds : m_specPasses) { if (XTERM_COLOR) HECL::Printf(_S("" MAGENTA BOLD "Using DataSpec %s:" NORMAL "\n"), ds.m_entry->m_name); else HECL::Printf(_S("Using DataSpec %s:\n"), ds.m_entry->m_name); int lineIdx = 0; ds.m_instance->doExtract(m_einfo, [&lineIdx](const HECL::SystemChar* message, const HECL::SystemChar* submessage, int lidx, float factor) { int iFactor = factor * 100.0; if (XTERM_COLOR) HECL::Printf(_S("" HIDE_CURSOR "")); if (lidx > lineIdx) { HECL::Printf(_S("\n ")); lineIdx = lidx; } else HECL::Printf(_S(" ")); int width = HECL::ConsoleWidth(); int half = width / 2 - 2; if (!message) message = _S(""); size_t messageLen = HECL::StrLen(message); if (!submessage) submessage = _S(""); size_t submessageLen = HECL::StrLen(submessage); if (half - messageLen < submessageLen-2) submessageLen = 0; if (submessageLen) { if (messageLen > half-submessageLen-1) HECL::Printf(_S("%.*s... "), half-int(submessageLen)-4, message); else { HECL::Printf(_S("%s"), message); for (int i=half-messageLen-submessageLen-1 ; i>=0 ; --i) HECL::Printf(_S(" ")); HECL::Printf(_S("%s "), submessage); } } else { if (messageLen > half) HECL::Printf(_S("%.*s... "), half-3, message); else { HECL::Printf(_S("%s"), message); for (int i=half-messageLen ; i>=0 ; --i) HECL::Printf(_S(" ")); } } if (XTERM_COLOR) { size_t blocks = half - 7; size_t filled = blocks * factor; size_t rem = blocks - filled; HECL::Printf(_S("" BOLD "%3d%% ["), iFactor); for (int b=0 ; b<filled ; ++b) HECL::Printf(_S("#")); for (int b=0 ; b<rem ; ++b) HECL::Printf(_S("-")); HECL::Printf(_S("]" NORMAL "")); } else { size_t blocks = half - 7; size_t filled = blocks * factor; size_t rem = blocks - filled; HECL::Printf(_S("%3d%% ["), iFactor); for (int b=0 ; b<filled ; ++b) HECL::Printf(_S("#")); for (int b=0 ; b<rem ; ++b) HECL::Printf(_S("-")); HECL::Printf(_S("]")); } HECL::Printf(_S("\r")); if (XTERM_COLOR) HECL::Printf(_S("" SHOW_CURSOR "")); fflush(stdout); }); HECL::Printf(_S("\n\n")); } return 0; } }; #endif // CTOOL_EXTRACT <commit_msg>clamped progress factor<commit_after>#ifndef CTOOL_EXTRACT #define CTOOL_EXTRACT #include "ToolBase.hpp" #include <stdio.h> #if _WIN32 #include <conio.h> #else #include <termios.h> #endif class ToolExtract final : public ToolBase { HECL::Database::IDataSpec::ExtractPassInfo m_einfo; struct SpecExtractPass { const HECL::Database::DataSpecEntry* m_entry; std::unique_ptr<HECL::Database::IDataSpec> m_instance; SpecExtractPass(const HECL::Database::DataSpecEntry* entry, HECL::Database::IDataSpec* instance) : m_entry(entry), m_instance(instance) {} SpecExtractPass(const SpecExtractPass& other) = delete; SpecExtractPass(SpecExtractPass&& other) = default; }; std::vector<SpecExtractPass> m_specPasses; std::vector<HECL::Database::IDataSpec::ExtractReport> m_reps; std::unique_ptr<HECL::Database::Project> m_fallbackProj; HECL::Database::Project* m_useProj; public: ToolExtract(const ToolPassInfo& info) : ToolBase(info) { if (!m_info.args.size()) LogModule.report(LogVisor::FatalError, "hecl extract needs a source path as its first argument"); if (!info.project) { /* Get name from input file and init project there */ HECL::SystemString baseFile = info.args.front(); size_t slashPos = baseFile.rfind(_S('/')); if (slashPos == HECL::SystemString::npos) slashPos = baseFile.rfind(_S('\\')); if (slashPos != HECL::SystemString::npos) baseFile.assign(baseFile.begin() + slashPos + 1, baseFile.end()); size_t dotPos = baseFile.rfind(_S('.')); if (dotPos != HECL::SystemString::npos) baseFile.assign(baseFile.begin(), baseFile.begin() + dotPos); if (baseFile.empty()) LogModule.report(LogVisor::FatalError, "hecl extract must be ran within a project directory"); size_t ErrorRef = LogVisor::ErrorCount; HECL::SystemString rootDir = info.cwd + baseFile; HECL::ProjectRootPath newProjRoot(rootDir); newProjRoot.makeDir(); m_fallbackProj.reset(new HECL::Database::Project(newProjRoot)); if (LogVisor::ErrorCount > ErrorRef) LogModule.report(LogVisor::FatalError, "unable to init project at '%s'", rootDir.c_str()); LogModule.report(LogVisor::Info, _S("initialized project at '%s/.hecl'"), rootDir.c_str()); m_useProj = m_fallbackProj.get(); } else m_useProj = info.project; m_einfo.srcpath = m_info.args.front(); m_einfo.extractArgs.reserve(info.args.size() - 1); m_einfo.force = info.force; std::list<HECL::SystemString>::const_iterator it=info.args.begin(); ++it; for (;it != info.args.end(); ++it) m_einfo.extractArgs.push_back(*it); for (const HECL::Database::DataSpecEntry* entry : HECL::Database::DATA_SPEC_REGISTRY) { HECL::Database::IDataSpec* ds = entry->m_factory(*m_useProj, HECL::Database::TOOL_EXTRACT); if (ds) { if (ds->canExtract(m_einfo, m_reps)) m_specPasses.emplace_back(entry, ds); else delete ds; } } } static void Help(HelpOutput& help) { help.secHead(_S("NAME")); help.beginWrap(); help.wrap(_S("hecl-extract - Extract objects from supported package/image formats\n")); help.endWrap(); help.secHead(_S("SYNOPSIS")); help.beginWrap(); help.wrap(_S("hecl extract <packagefile> [<subnode>...]\n")); help.endWrap(); help.secHead(_S("DESCRIPTION")); help.beginWrap(); help.wrap(_S("This command recursively extracts all or part of a dataspec-supported ") _S("package format. Each object is decoded to a working format and added to the project.\n\n")); help.endWrap(); help.secHead(_S("OPTIONS")); help.optionHead(_S("<packagefile>[/<subnode>...]"), _S("input file")); help.beginWrap(); help.wrap(_S("Specifies the package file or disc image to source data from. ") _S("An optional subnode specifies a named hierarchical-node specific ") _S("to the game architecture (levels/areas).")); help.endWrap(); } HECL::SystemString toolName() const {return _S("extract");} static void _recursivePrint(int level, HECL::Database::IDataSpec::ExtractReport& rep) { for (int l=0 ; l<level ; ++l) HECL::Printf(_S(" ")); if (XTERM_COLOR) HECL::Printf(_S("" BOLD "%s" NORMAL ""), rep.name.c_str()); else HECL::Printf(_S("%s"), rep.name.c_str()); if (rep.desc.size()) HECL::Printf(_S(" [%s]"), rep.desc.c_str()); HECL::Printf(_S("\n")); for (HECL::Database::IDataSpec::ExtractReport& child : rep.childOpts) _recursivePrint(level + 1, child); } int run() { if (m_specPasses.empty()) { if (XTERM_COLOR) HECL::Printf(_S("" RED BOLD "NOTHING TO EXTRACT" NORMAL "\n")); else HECL::Printf(_S("NOTHING TO EXTRACT\n")); return -1; } if (XTERM_COLOR) HECL::Printf(_S("" GREEN BOLD "ABOUT TO EXTRACT:" NORMAL "\n")); else HECL::Printf(_S("ABOUT TO EXTRACT:\n")); for (HECL::Database::IDataSpec::ExtractReport& rep : m_reps) { _recursivePrint(0, rep); HECL::Printf(_S("\n")); } if (XTERM_COLOR) HECL::Printf(_S("\n" BLUE BOLD "Continue?" NORMAL " (Y/n) ")); else HECL::Printf(_S("\nContinue? (Y/n) ")); int ch; #ifndef _WIN32 struct termios tioOld, tioNew; tcgetattr(0, &tioOld); tioNew = tioOld; tioNew.c_lflag &= ~ICANON; tcsetattr(0, TCSANOW, &tioNew); while ((ch = getchar())) #else while ((ch = getch())) #endif { if (ch == 'n' || ch == 'N') return 0; if (ch == 'y' || ch == 'Y' || ch == '\r' || ch == '\n') break; } #ifndef _WIN32 tcsetattr(0, TCSANOW, &tioOld); #endif HECL::Printf(_S("\n")); for (SpecExtractPass& ds : m_specPasses) { if (XTERM_COLOR) HECL::Printf(_S("" MAGENTA BOLD "Using DataSpec %s:" NORMAL "\n"), ds.m_entry->m_name); else HECL::Printf(_S("Using DataSpec %s:\n"), ds.m_entry->m_name); int lineIdx = 0; ds.m_instance->doExtract(m_einfo, [&lineIdx](const HECL::SystemChar* message, const HECL::SystemChar* submessage, int lidx, float factor) { factor = std::max(0.0f, std::min(1.0f, factor)); int iFactor = factor * 100.0; if (XTERM_COLOR) HECL::Printf(_S("" HIDE_CURSOR "")); if (lidx > lineIdx) { HECL::Printf(_S("\n ")); lineIdx = lidx; } else HECL::Printf(_S(" ")); int width = HECL::ConsoleWidth(); int half = width / 2 - 2; if (!message) message = _S(""); size_t messageLen = HECL::StrLen(message); if (!submessage) submessage = _S(""); size_t submessageLen = HECL::StrLen(submessage); if (half - messageLen < submessageLen-2) submessageLen = 0; if (submessageLen) { if (messageLen > half-submessageLen-1) HECL::Printf(_S("%.*s... "), half-int(submessageLen)-4, message); else { HECL::Printf(_S("%s"), message); for (int i=half-messageLen-submessageLen-1 ; i>=0 ; --i) HECL::Printf(_S(" ")); HECL::Printf(_S("%s "), submessage); } } else { if (messageLen > half) HECL::Printf(_S("%.*s... "), half-3, message); else { HECL::Printf(_S("%s"), message); for (int i=half-messageLen ; i>=0 ; --i) HECL::Printf(_S(" ")); } } if (XTERM_COLOR) { size_t blocks = half - 7; size_t filled = blocks * factor; size_t rem = blocks - filled; HECL::Printf(_S("" BOLD "%3d%% ["), iFactor); for (int b=0 ; b<filled ; ++b) HECL::Printf(_S("#")); for (int b=0 ; b<rem ; ++b) HECL::Printf(_S("-")); HECL::Printf(_S("]" NORMAL "")); } else { size_t blocks = half - 7; size_t filled = blocks * factor; size_t rem = blocks - filled; HECL::Printf(_S("%3d%% ["), iFactor); for (int b=0 ; b<filled ; ++b) HECL::Printf(_S("#")); for (int b=0 ; b<rem ; ++b) HECL::Printf(_S("-")); HECL::Printf(_S("]")); } HECL::Printf(_S("\r")); if (XTERM_COLOR) HECL::Printf(_S("" SHOW_CURSOR "")); fflush(stdout); }); HECL::Printf(_S("\n\n")); } return 0; } }; #endif // CTOOL_EXTRACT <|endoftext|>
<commit_before>//===-- PPCInstPrinter.cpp - Convert PPC MCInst to assembly syntax --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class prints an PPC MCInst to a .s file. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "PPCInstPrinter.h" #include "MCTargetDesc/PPCMCTargetDesc.h" #include "MCTargetDesc/PPCPredicates.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #include "PPCGenAsmWriter.inc" void PPCInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const { OS << getRegisterName(RegNo); } void PPCInstPrinter::printInst(const MCInst *MI, raw_ostream &O, StringRef Annot) { // Check for slwi/srwi mnemonics. if (MI->getOpcode() == PPC::RLWINM) { unsigned char SH = MI->getOperand(2).getImm(); unsigned char MB = MI->getOperand(3).getImm(); unsigned char ME = MI->getOperand(4).getImm(); bool useSubstituteMnemonic = false; if (SH <= 31 && MB == 0 && ME == (31-SH)) { O << "\tslwi "; useSubstituteMnemonic = true; } if (SH <= 31 && MB == (32-SH) && ME == 31) { O << "\tsrwi "; useSubstituteMnemonic = true; SH = 32-SH; } if (useSubstituteMnemonic) { printOperand(MI, 0, O); O << ", "; printOperand(MI, 1, O); O << ", " << (unsigned int)SH; printAnnotation(O, Annot); return; } } if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) && MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) { O << "\tmr "; printOperand(MI, 0, O); O << ", "; printOperand(MI, 1, O); printAnnotation(O, Annot); return; } if (MI->getOpcode() == PPC::RLDICR) { unsigned char SH = MI->getOperand(2).getImm(); unsigned char ME = MI->getOperand(3).getImm(); // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH if (63-SH == ME) { O << "\tsldi "; printOperand(MI, 0, O); O << ", "; printOperand(MI, 1, O); O << ", " << (unsigned int)SH; printAnnotation(O, Annot); return; } } printInstruction(MI, O); printAnnotation(O, Annot); } void PPCInstPrinter::printPredicateOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O, const char *Modifier) { unsigned Code = MI->getOperand(OpNo).getImm(); if (StringRef(Modifier) == "cc") { switch ((PPC::Predicate)Code) { case PPC::PRED_LT_MINUS: case PPC::PRED_LT_PLUS: case PPC::PRED_LT: O << "lt"; return; case PPC::PRED_LE_MINUS: case PPC::PRED_LE_PLUS: case PPC::PRED_LE: O << "le"; return; case PPC::PRED_EQ_MINUS: case PPC::PRED_EQ_PLUS: case PPC::PRED_EQ: O << "eq"; return; case PPC::PRED_GE_MINUS: case PPC::PRED_GE_PLUS: case PPC::PRED_GE: O << "ge"; return; case PPC::PRED_GT_MINUS: case PPC::PRED_GT_PLUS: case PPC::PRED_GT: O << "gt"; return; case PPC::PRED_NE_MINUS: case PPC::PRED_NE_PLUS: case PPC::PRED_NE: O << "ne"; return; case PPC::PRED_UN_MINUS: case PPC::PRED_UN_PLUS: case PPC::PRED_UN: O << "un"; return; case PPC::PRED_NU_MINUS: case PPC::PRED_NU_PLUS: case PPC::PRED_NU: O << "nu"; return; default: llvm_unreachable("Invalid predicate code"); } } if (StringRef(Modifier) == "pm") { switch ((PPC::Predicate)Code) { case PPC::PRED_LT: case PPC::PRED_LE: case PPC::PRED_EQ: case PPC::PRED_GE: case PPC::PRED_GT: case PPC::PRED_NE: case PPC::PRED_UN: case PPC::PRED_NU: return; case PPC::PRED_LT_MINUS: case PPC::PRED_LE_MINUS: case PPC::PRED_EQ_MINUS: case PPC::PRED_GE_MINUS: case PPC::PRED_GT_MINUS: case PPC::PRED_NE_MINUS: case PPC::PRED_UN_MINUS: case PPC::PRED_NU_MINUS: O << "-"; return; case PPC::PRED_LT_PLUS: case PPC::PRED_LE_PLUS: case PPC::PRED_EQ_PLUS: case PPC::PRED_GE_PLUS: case PPC::PRED_GT_PLUS: case PPC::PRED_NE_PLUS: case PPC::PRED_UN_PLUS: case PPC::PRED_NU_PLUS: O << "+"; return; default: llvm_unreachable("Invalid predicate code"); } } assert(StringRef(Modifier) == "reg" && "Need to specify 'cc', 'pm' or 'reg' as predicate op modifier!"); printOperand(MI, OpNo+1, O); } void PPCInstPrinter::printS5ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { int Value = MI->getOperand(OpNo).getImm(); Value = SignExtend32<5>(Value); O << (int)Value; } void PPCInstPrinter::printU5ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { unsigned int Value = MI->getOperand(OpNo).getImm(); assert(Value <= 31 && "Invalid u5imm argument!"); O << (unsigned int)Value; } void PPCInstPrinter::printU6ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { unsigned int Value = MI->getOperand(OpNo).getImm(); assert(Value <= 63 && "Invalid u6imm argument!"); O << (unsigned int)Value; } void PPCInstPrinter::printS16ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { if (MI->getOperand(OpNo).isImm()) O << (short)MI->getOperand(OpNo).getImm(); else printOperand(MI, OpNo, O); } void PPCInstPrinter::printU16ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { O << (unsigned short)MI->getOperand(OpNo).getImm(); } void PPCInstPrinter::printBranchOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { if (!MI->getOperand(OpNo).isImm()) return printOperand(MI, OpNo, O); // Branches can take an immediate operand. This is used by the branch // selection pass to print .+8, an eight byte displacement from the PC. O << ".+"; printAbsBranchOperand(MI, OpNo, O); } void PPCInstPrinter::printAbsBranchOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { if (!MI->getOperand(OpNo).isImm()) return printOperand(MI, OpNo, O); O << (int)MI->getOperand(OpNo).getImm()*4; } void PPCInstPrinter::printcrbitm(const MCInst *MI, unsigned OpNo, raw_ostream &O) { unsigned CCReg = MI->getOperand(OpNo).getReg(); unsigned RegNo; switch (CCReg) { default: llvm_unreachable("Unknown CR register"); case PPC::CR0: RegNo = 0; break; case PPC::CR1: RegNo = 1; break; case PPC::CR2: RegNo = 2; break; case PPC::CR3: RegNo = 3; break; case PPC::CR4: RegNo = 4; break; case PPC::CR5: RegNo = 5; break; case PPC::CR6: RegNo = 6; break; case PPC::CR7: RegNo = 7; break; } O << (0x80 >> RegNo); } void PPCInstPrinter::printMemRegImm(const MCInst *MI, unsigned OpNo, raw_ostream &O) { printS16ImmOperand(MI, OpNo, O); O << '('; if (MI->getOperand(OpNo+1).getReg() == PPC::R0) O << "0"; else printOperand(MI, OpNo+1, O); O << ')'; } void PPCInstPrinter::printMemRegReg(const MCInst *MI, unsigned OpNo, raw_ostream &O) { // When used as the base register, r0 reads constant zero rather than // the value contained in the register. For this reason, the darwin // assembler requires that we print r0 as 0 (no r) when used as the base. if (MI->getOperand(OpNo).getReg() == PPC::R0) O << "0"; else printOperand(MI, OpNo, O); O << ", "; printOperand(MI, OpNo+1, O); } /// stripRegisterPrefix - This method strips the character prefix from a /// register name so that only the number is left. Used by for linux asm. static const char *stripRegisterPrefix(const char *RegName) { switch (RegName[0]) { case 'r': case 'f': case 'v': return RegName + 1; case 'c': if (RegName[1] == 'r') return RegName + 2; } return RegName; } void PPCInstPrinter::printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { const MCOperand &Op = MI->getOperand(OpNo); if (Op.isReg()) { const char *RegName = getRegisterName(Op.getReg()); // The linux and AIX assembler does not take register prefixes. if (!isDarwinSyntax()) RegName = stripRegisterPrefix(RegName); O << RegName; return; } if (Op.isImm()) { O << Op.getImm(); return; } assert(Op.isExpr() && "unknown operand kind in printOperand"); O << *Op.getExpr(); } <commit_msg>PPC: Remove default case from fully covered switch.<commit_after>//===-- PPCInstPrinter.cpp - Convert PPC MCInst to assembly syntax --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class prints an PPC MCInst to a .s file. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "PPCInstPrinter.h" #include "MCTargetDesc/PPCMCTargetDesc.h" #include "MCTargetDesc/PPCPredicates.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #include "PPCGenAsmWriter.inc" void PPCInstPrinter::printRegName(raw_ostream &OS, unsigned RegNo) const { OS << getRegisterName(RegNo); } void PPCInstPrinter::printInst(const MCInst *MI, raw_ostream &O, StringRef Annot) { // Check for slwi/srwi mnemonics. if (MI->getOpcode() == PPC::RLWINM) { unsigned char SH = MI->getOperand(2).getImm(); unsigned char MB = MI->getOperand(3).getImm(); unsigned char ME = MI->getOperand(4).getImm(); bool useSubstituteMnemonic = false; if (SH <= 31 && MB == 0 && ME == (31-SH)) { O << "\tslwi "; useSubstituteMnemonic = true; } if (SH <= 31 && MB == (32-SH) && ME == 31) { O << "\tsrwi "; useSubstituteMnemonic = true; SH = 32-SH; } if (useSubstituteMnemonic) { printOperand(MI, 0, O); O << ", "; printOperand(MI, 1, O); O << ", " << (unsigned int)SH; printAnnotation(O, Annot); return; } } if ((MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) && MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) { O << "\tmr "; printOperand(MI, 0, O); O << ", "; printOperand(MI, 1, O); printAnnotation(O, Annot); return; } if (MI->getOpcode() == PPC::RLDICR) { unsigned char SH = MI->getOperand(2).getImm(); unsigned char ME = MI->getOperand(3).getImm(); // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH if (63-SH == ME) { O << "\tsldi "; printOperand(MI, 0, O); O << ", "; printOperand(MI, 1, O); O << ", " << (unsigned int)SH; printAnnotation(O, Annot); return; } } printInstruction(MI, O); printAnnotation(O, Annot); } void PPCInstPrinter::printPredicateOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O, const char *Modifier) { unsigned Code = MI->getOperand(OpNo).getImm(); if (StringRef(Modifier) == "cc") { switch ((PPC::Predicate)Code) { case PPC::PRED_LT_MINUS: case PPC::PRED_LT_PLUS: case PPC::PRED_LT: O << "lt"; return; case PPC::PRED_LE_MINUS: case PPC::PRED_LE_PLUS: case PPC::PRED_LE: O << "le"; return; case PPC::PRED_EQ_MINUS: case PPC::PRED_EQ_PLUS: case PPC::PRED_EQ: O << "eq"; return; case PPC::PRED_GE_MINUS: case PPC::PRED_GE_PLUS: case PPC::PRED_GE: O << "ge"; return; case PPC::PRED_GT_MINUS: case PPC::PRED_GT_PLUS: case PPC::PRED_GT: O << "gt"; return; case PPC::PRED_NE_MINUS: case PPC::PRED_NE_PLUS: case PPC::PRED_NE: O << "ne"; return; case PPC::PRED_UN_MINUS: case PPC::PRED_UN_PLUS: case PPC::PRED_UN: O << "un"; return; case PPC::PRED_NU_MINUS: case PPC::PRED_NU_PLUS: case PPC::PRED_NU: O << "nu"; return; } llvm_unreachable("Invalid predicate code"); } if (StringRef(Modifier) == "pm") { switch ((PPC::Predicate)Code) { case PPC::PRED_LT: case PPC::PRED_LE: case PPC::PRED_EQ: case PPC::PRED_GE: case PPC::PRED_GT: case PPC::PRED_NE: case PPC::PRED_UN: case PPC::PRED_NU: return; case PPC::PRED_LT_MINUS: case PPC::PRED_LE_MINUS: case PPC::PRED_EQ_MINUS: case PPC::PRED_GE_MINUS: case PPC::PRED_GT_MINUS: case PPC::PRED_NE_MINUS: case PPC::PRED_UN_MINUS: case PPC::PRED_NU_MINUS: O << "-"; return; case PPC::PRED_LT_PLUS: case PPC::PRED_LE_PLUS: case PPC::PRED_EQ_PLUS: case PPC::PRED_GE_PLUS: case PPC::PRED_GT_PLUS: case PPC::PRED_NE_PLUS: case PPC::PRED_UN_PLUS: case PPC::PRED_NU_PLUS: O << "+"; return; } llvm_unreachable("Invalid predicate code"); } assert(StringRef(Modifier) == "reg" && "Need to specify 'cc', 'pm' or 'reg' as predicate op modifier!"); printOperand(MI, OpNo+1, O); } void PPCInstPrinter::printS5ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { int Value = MI->getOperand(OpNo).getImm(); Value = SignExtend32<5>(Value); O << (int)Value; } void PPCInstPrinter::printU5ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { unsigned int Value = MI->getOperand(OpNo).getImm(); assert(Value <= 31 && "Invalid u5imm argument!"); O << (unsigned int)Value; } void PPCInstPrinter::printU6ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { unsigned int Value = MI->getOperand(OpNo).getImm(); assert(Value <= 63 && "Invalid u6imm argument!"); O << (unsigned int)Value; } void PPCInstPrinter::printS16ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { if (MI->getOperand(OpNo).isImm()) O << (short)MI->getOperand(OpNo).getImm(); else printOperand(MI, OpNo, O); } void PPCInstPrinter::printU16ImmOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { O << (unsigned short)MI->getOperand(OpNo).getImm(); } void PPCInstPrinter::printBranchOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { if (!MI->getOperand(OpNo).isImm()) return printOperand(MI, OpNo, O); // Branches can take an immediate operand. This is used by the branch // selection pass to print .+8, an eight byte displacement from the PC. O << ".+"; printAbsBranchOperand(MI, OpNo, O); } void PPCInstPrinter::printAbsBranchOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { if (!MI->getOperand(OpNo).isImm()) return printOperand(MI, OpNo, O); O << (int)MI->getOperand(OpNo).getImm()*4; } void PPCInstPrinter::printcrbitm(const MCInst *MI, unsigned OpNo, raw_ostream &O) { unsigned CCReg = MI->getOperand(OpNo).getReg(); unsigned RegNo; switch (CCReg) { default: llvm_unreachable("Unknown CR register"); case PPC::CR0: RegNo = 0; break; case PPC::CR1: RegNo = 1; break; case PPC::CR2: RegNo = 2; break; case PPC::CR3: RegNo = 3; break; case PPC::CR4: RegNo = 4; break; case PPC::CR5: RegNo = 5; break; case PPC::CR6: RegNo = 6; break; case PPC::CR7: RegNo = 7; break; } O << (0x80 >> RegNo); } void PPCInstPrinter::printMemRegImm(const MCInst *MI, unsigned OpNo, raw_ostream &O) { printS16ImmOperand(MI, OpNo, O); O << '('; if (MI->getOperand(OpNo+1).getReg() == PPC::R0) O << "0"; else printOperand(MI, OpNo+1, O); O << ')'; } void PPCInstPrinter::printMemRegReg(const MCInst *MI, unsigned OpNo, raw_ostream &O) { // When used as the base register, r0 reads constant zero rather than // the value contained in the register. For this reason, the darwin // assembler requires that we print r0 as 0 (no r) when used as the base. if (MI->getOperand(OpNo).getReg() == PPC::R0) O << "0"; else printOperand(MI, OpNo, O); O << ", "; printOperand(MI, OpNo+1, O); } /// stripRegisterPrefix - This method strips the character prefix from a /// register name so that only the number is left. Used by for linux asm. static const char *stripRegisterPrefix(const char *RegName) { switch (RegName[0]) { case 'r': case 'f': case 'v': return RegName + 1; case 'c': if (RegName[1] == 'r') return RegName + 2; } return RegName; } void PPCInstPrinter::printOperand(const MCInst *MI, unsigned OpNo, raw_ostream &O) { const MCOperand &Op = MI->getOperand(OpNo); if (Op.isReg()) { const char *RegName = getRegisterName(Op.getReg()); // The linux and AIX assembler does not take register prefixes. if (!isDarwinSyntax()) RegName = stripRegisterPrefix(RegName); O << RegName; return; } if (Op.isImm()) { O << Op.getImm(); return; } assert(Op.isExpr() && "unknown operand kind in printOperand"); O << *Op.getExpr(); } <|endoftext|>
<commit_before>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "Base.h" #include "Event.h" #include <event2/thread.h> #include <event2/event.h> #include <cbang/Exception.h> using namespace cb::Event; using namespace cb; bool Base::_threadsEnabled = false; Base::Base(bool withThreads) { if (withThreads) enableThreads(); base = event_base_new(); if (!base) THROW("Failed to create event base"); } Base::~Base() {if (base) event_base_free(base);} void Base::initPriority(int num) { if (event_base_priority_init(base, num)) THROW("Failed to init event base priority"); } int Base::getNumPriorities() const { return event_base_get_npriorities(base); } SmartPointer<cb::Event::Event> Base::newEvent(callback_t cb, unsigned flags) {return newEvent(-1, cb, flags);} SmartPointer<cb::Event::Event> Base::newEvent(socket_t fd, callback_t cb, unsigned flags) { return new Event(*this, fd, cb, flags); } SmartPointer<cb::Event::Event> Base::newSignal(int signal, callback_t cb, unsigned flags) { return newEvent((socket_t)signal, cb, flags | EV_SIGNAL); } void Base::dispatch() {if (event_base_dispatch(base)) THROW("Dispatch failed");} void Base::loop() {if (event_base_loop(base, 0)) THROW("Loop failed");} void Base::loopOnce() { if (event_base_loop(base, EVLOOP_ONCE)) THROW("Loop once failed"); } bool Base::loopNonBlock() { int ret = event_base_loop(base, EVLOOP_NONBLOCK); if (ret == -1) THROW("Loop nonblock failed"); return ret == 0; } void Base::loopBreak() { if (event_base_loopbreak(base)) THROW("Loop break failed"); } void Base::loopContinue() { if (event_base_loopcontinue(base)) THROW("Loop break failed"); } void Base::loopExit() { if (event_base_loopexit(base, 0)) THROW("Loop exit failed"); } void Base::enableThreads() { if (_threadsEnabled) return; #if EVTHREAD_USE_PTHREADS_IMPLEMENTED if (evthread_use_pthreads()) THROW("Failed to enable libevent thread support"); #elif EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED if (evthread_use_windows_threads()) THROW("Failed to enable libevent thread support"); #else THROW("libevent not built with thread support"); #endif _threadsEnabled = true; } <commit_msg>Fix for Windows<commit_after>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2019, Cauldron Development LLC Copyright (c) 2003-2017, Stanford University All rights reserved. The C! 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. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "Base.h" #include "Event.h" #include <event2/thread.h> #include <event2/event.h> #include <cbang/Exception.h> #include <cbang/socket/Socket.h> using namespace cb::Event; using namespace cb; bool Base::_threadsEnabled = false; Base::Base(bool withThreads) { Socket::initialize(); // Windows needs this if (withThreads) enableThreads(); base = event_base_new(); if (!base) THROW("Failed to create event base"); } Base::~Base() {if (base) event_base_free(base);} void Base::initPriority(int num) { if (event_base_priority_init(base, num)) THROW("Failed to init event base priority"); } int Base::getNumPriorities() const { return event_base_get_npriorities(base); } SmartPointer<cb::Event::Event> Base::newEvent(callback_t cb, unsigned flags) {return newEvent(-1, cb, flags);} SmartPointer<cb::Event::Event> Base::newEvent(socket_t fd, callback_t cb, unsigned flags) { return new Event(*this, fd, cb, flags); } SmartPointer<cb::Event::Event> Base::newSignal(int signal, callback_t cb, unsigned flags) { return newEvent((socket_t)signal, cb, flags | EV_SIGNAL); } void Base::dispatch() {if (event_base_dispatch(base)) THROW("Dispatch failed");} void Base::loop() {if (event_base_loop(base, 0)) THROW("Loop failed");} void Base::loopOnce() { if (event_base_loop(base, EVLOOP_ONCE)) THROW("Loop once failed"); } bool Base::loopNonBlock() { int ret = event_base_loop(base, EVLOOP_NONBLOCK); if (ret == -1) THROW("Loop nonblock failed"); return ret == 0; } void Base::loopBreak() { if (event_base_loopbreak(base)) THROW("Loop break failed"); } void Base::loopContinue() { if (event_base_loopcontinue(base)) THROW("Loop break failed"); } void Base::loopExit() { if (event_base_loopexit(base, 0)) THROW("Loop exit failed"); } void Base::enableThreads() { if (_threadsEnabled) return; #if EVTHREAD_USE_PTHREADS_IMPLEMENTED if (evthread_use_pthreads()) THROW("Failed to enable libevent thread support"); #elif EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED if (evthread_use_windows_threads()) THROW("Failed to enable libevent thread support"); #else THROW("libevent not built with thread support"); #endif _threadsEnabled = true; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "RocInc.h" volatile sig_atomic_t g_quitSetter = 0; void SignalHandleFunction(int f_sig) { signal(f_sig, SignalHandleFunction); g_quitSetter = 1; } int main(int argc, char *argv[]) { signal(SIGINT, SignalHandleFunction); signal(SIGTERM, SignalHandleFunction); #ifdef SIGBREAK signal(SIGBREAK, SignalHandleFunction); #endif #ifdef _WIN32 EnableScrollBar(GetConsoleWindow(), SB_BOTH, ESB_DISABLE_BOTH); HANDLE l_handle = GetStdHandle(STD_INPUT_HANDLE); DWORD l_handleMode; GetConsoleMode(l_handle, &l_handleMode); SetConsoleMode(l_handle, l_handleMode & ~ENABLE_QUICK_EDIT_MODE); #endif ROC::Core *l_core = ROC::Core::Init(); pugi::xml_document *l_meta = new pugi::xml_document(); if(l_meta->load_file("server_scripts/meta.xml")) { pugi::xml_node l_metaRoot = l_meta->child("meta"); if(l_metaRoot) { unsigned int l_counter = 0U; for(pugi::xml_node l_node = l_metaRoot.child("script"); l_node; l_node = l_node.next_sibling("script")) { pugi::xml_attribute l_attrib = l_node.attribute("src"); if(l_attrib) { std::string l_path("server_scripts/"); l_path.append(l_attrib.as_string()); l_core->GetLuaManager()->OpenFile(l_path); } else { std::string l_text("Unable to find attribute 'src' at 'script' subnodes with ID "); l_text.append(std::to_string(l_counter)); l_text.append(" in 'server_scripts/meta.xml'"); l_core->GetLogManager()->Log(l_text); } l_counter++; } if(!l_counter) { std::string l_text("Unable to find any 'script' subnode in 'server_scripts/meta.xml'"); l_core->GetLogManager()->Log(l_text); } } else { std::string l_text("Unable to find root node 'meta' in 'server_scripts/meta.xml'."); l_core->GetLogManager()->Log(l_text); } } else { std::string l_text("Unable to find 'server_scripts/meta.xml'."); l_core->GetLogManager()->Log(l_text); } delete l_meta; ROC::LuaArguments *l_emptyArgs = new ROC::LuaArguments(); l_core->GetLuaManager()->GetEventManager()->CallEvent(ROC::EventType::ServerStart, l_emptyArgs); while(!g_quitSetter) l_core->DoPulse(); l_core->GetLuaManager()->GetEventManager()->CallEvent(ROC::EventType::ServerStop, l_emptyArgs); delete l_emptyArgs; ROC::Core::Terminate(); return EXIT_SUCCESS; } <commit_msg>Minor fixes [53]<commit_after>#include "stdafx.h" #include "RocInc.h" volatile sig_atomic_t g_quitSetter = 0; void SignalHandleFunction(int f_sig) { signal(f_sig, SignalHandleFunction); g_quitSetter = 1; } int main(int argc, char *argv[]) { signal(SIGINT, SignalHandleFunction); signal(SIGTERM, SignalHandleFunction); #ifdef SIGBREAK signal(SIGBREAK, SignalHandleFunction); #endif #ifdef _WIN32 EnableScrollBar(GetConsoleWindow(), SB_BOTH, ESB_DISABLE_BOTH); HANDLE l_handle = GetStdHandle(STD_INPUT_HANDLE); DWORD l_handleMode; GetConsoleMode(l_handle, &l_handleMode); SetConsoleMode(l_handle, l_handleMode & ~ENABLE_QUICK_EDIT_MODE); l_handle = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO l_sbInfo; GetConsoleScreenBufferInfo(l_handle, &l_sbInfo); l_sbInfo.dwSize.Y = l_sbInfo.srWindow.Bottom + 1; SetConsoleWindowInfo(l_handle, TRUE, &l_sbInfo.srWindow); SetConsoleScreenBufferSize(l_handle, l_sbInfo.dwSize); #endif ROC::Core *l_core = ROC::Core::Init(); pugi::xml_document *l_meta = new pugi::xml_document(); if(l_meta->load_file("server_scripts/meta.xml")) { pugi::xml_node l_metaRoot = l_meta->child("meta"); if(l_metaRoot) { unsigned int l_counter = 0U; for(pugi::xml_node l_node = l_metaRoot.child("script"); l_node; l_node = l_node.next_sibling("script")) { pugi::xml_attribute l_attrib = l_node.attribute("src"); if(l_attrib) { std::string l_path("server_scripts/"); l_path.append(l_attrib.as_string()); l_core->GetLuaManager()->OpenFile(l_path); } else { std::string l_text("Unable to find attribute 'src' at 'script' subnodes with ID "); l_text.append(std::to_string(l_counter)); l_text.append(" in 'server_scripts/meta.xml'"); l_core->GetLogManager()->Log(l_text); } l_counter++; } if(!l_counter) { std::string l_text("Unable to find any 'script' subnode in 'server_scripts/meta.xml'"); l_core->GetLogManager()->Log(l_text); } } else { std::string l_text("Unable to find root node 'meta' in 'server_scripts/meta.xml'."); l_core->GetLogManager()->Log(l_text); } } else { std::string l_text("Unable to find 'server_scripts/meta.xml'."); l_core->GetLogManager()->Log(l_text); } delete l_meta; ROC::LuaArguments *l_emptyArgs = new ROC::LuaArguments(); l_core->GetLuaManager()->GetEventManager()->CallEvent(ROC::EventType::ServerStart, l_emptyArgs); while(!g_quitSetter) l_core->DoPulse(); l_core->GetLuaManager()->GetEventManager()->CallEvent(ROC::EventType::ServerStop, l_emptyArgs); delete l_emptyArgs; ROC::Core::Terminate(); return EXIT_SUCCESS; } <|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 "tp_ErrorBars.hxx" #include "ResId.hxx" #include "TabPages.hrc" #include "TabPageNotifiable.hxx" using namespace ::com::sun::star; //............................................................................. namespace chart { //............................................................................. ErrorBarsTabPage::ErrorBarsTabPage( Window* pParent, const SfxItemSet& rInAttrs ) : SfxTabPage( pParent, SchResId( TP_YERRORBAR ), rInAttrs ), m_aErrorBarResources( this, // the parent is the tab control, of which the parent is the dialog dynamic_cast< Dialog * >( pParent->GetParent() ), rInAttrs, /* bNoneAvailable = */ false ) { FreeResource(); } ErrorBarsTabPage::~ErrorBarsTabPage() { } SfxTabPage* ErrorBarsTabPage::Create( Window* pParent, const SfxItemSet& rOutAttrs ) { return new ErrorBarsTabPage( pParent, rOutAttrs ); } sal_Bool ErrorBarsTabPage::FillItemSet( SfxItemSet& rOutAttrs ) { return m_aErrorBarResources.FillItemSet( rOutAttrs ); } void ErrorBarsTabPage::Reset( const SfxItemSet& rInAttrs ) { m_aErrorBarResources.Reset( rInAttrs ); } void ErrorBarsTabPage::DataChanged( const DataChangedEvent& rDCEvt ) { SfxTabPage::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) m_aErrorBarResources.FillValueSets(); } void ErrorBarsTabPage::SetAxisMinorStepWidthForErrorBarDecimals( double fMinorStepWidth ) { m_aErrorBarResources.SetAxisMinorStepWidthForErrorBarDecimals( fMinorStepWidth ); } void ErrorBarsTabPage::SetErrorBarType( ErrorBarResources::tErrorBarType eNewType ) { m_aErrorBarResources.SetErrorBarType( eNewType ); } void ErrorBarsTabPage::SetChartDocumentForRangeChoosing( const uno::Reference< chart2::XChartDocument > & xChartDocument ) { m_aErrorBarResources.SetChartDocumentForRangeChoosing( xChartDocument ); } //............................................................................. } //namespace chart //............................................................................. /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>we need to use GetParentDialog nowadays, fdo#60253<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 "tp_ErrorBars.hxx" #include "ResId.hxx" #include "TabPages.hrc" #include "TabPageNotifiable.hxx" using namespace ::com::sun::star; //............................................................................. namespace chart { //............................................................................. ErrorBarsTabPage::ErrorBarsTabPage( Window* pParent, const SfxItemSet& rInAttrs ) : SfxTabPage( pParent, SchResId( TP_YERRORBAR ), rInAttrs ), m_aErrorBarResources( this, // the parent is the tab control, of which the parent is the dialog dynamic_cast< Dialog * >( pParent->GetParentDialog() ), rInAttrs, /* bNoneAvailable = */ false ) { FreeResource(); } ErrorBarsTabPage::~ErrorBarsTabPage() { } SfxTabPage* ErrorBarsTabPage::Create( Window* pParent, const SfxItemSet& rOutAttrs ) { return new ErrorBarsTabPage( pParent, rOutAttrs ); } sal_Bool ErrorBarsTabPage::FillItemSet( SfxItemSet& rOutAttrs ) { return m_aErrorBarResources.FillItemSet( rOutAttrs ); } void ErrorBarsTabPage::Reset( const SfxItemSet& rInAttrs ) { m_aErrorBarResources.Reset( rInAttrs ); } void ErrorBarsTabPage::DataChanged( const DataChangedEvent& rDCEvt ) { SfxTabPage::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) m_aErrorBarResources.FillValueSets(); } void ErrorBarsTabPage::SetAxisMinorStepWidthForErrorBarDecimals( double fMinorStepWidth ) { m_aErrorBarResources.SetAxisMinorStepWidthForErrorBarDecimals( fMinorStepWidth ); } void ErrorBarsTabPage::SetErrorBarType( ErrorBarResources::tErrorBarType eNewType ) { m_aErrorBarResources.SetErrorBarType( eNewType ); } void ErrorBarsTabPage::SetChartDocumentForRangeChoosing( const uno::Reference< chart2::XChartDocument > & xChartDocument ) { m_aErrorBarResources.SetChartDocumentForRangeChoosing( xChartDocument ); } //............................................................................. } //namespace chart //............................................................................. /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>hide a WaE... should be fixed properly when the issue is understood<commit_after><|endoftext|>
<commit_before>#ifndef GNR_FORWARDERREF_HPP # define GNR_FORWARDERREF_HPP # pragma once // std::memcpy #include <cstring> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail::fwdref { template <typename, bool> class fwdref_impl2; template <typename R, typename ...A, bool E> class fwdref_impl2<R (A...), E> { protected: R (*stub_)(void*, A&&...) noexcept(E) {}; void* store_; template <typename F> static constexpr auto is_invocable() noexcept { return std::is_invocable_r_v<R, F, A...>; } public: using result_type = R; public: R operator()(A... args) const noexcept(E) { //assert(stub_); return stub_(store_, std::forward<A>(args)...); } template <typename F, typename = std::enable_if_t< std::is_invocable_r_v<R, F, A...> > > void assign(F&& f) noexcept { using functor_type = std::decay_t<F>; store_ = &f; stub_ = [](void* const ptr, A&&... args) noexcept(E) -> R { return std::invoke(*static_cast<functor_type*>(ptr), std::forward<A>(args)...); }; } }; template <typename> class fwdref_impl; template <typename R, typename ...A> class fwdref_impl<R (A...)> : public fwdref_impl2<R (A...), false> { }; template <typename R, typename ...A> class fwdref_impl<R (A...) noexcept> : public fwdref_impl2<R (A...), true> { }; } template <typename A> class fwdref : public detail::fwdref::fwdref_impl<A> { using inherited_t = detail::fwdref::fwdref_impl<A>; public: fwdref() = default; fwdref(fwdref const&) = default; fwdref(fwdref&&) = default; template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, fwdref> && inherited_t::template is_invocable<F>() > > fwdref(F&& f) noexcept(noexcept(inherited_t::assign(std::forward<F>(f)))) { inherited_t::assign(std::forward<F>(f)); } fwdref& operator=(fwdref const&) = default; fwdref& operator=(fwdref&&) = default; template <typename F> fwdref& operator=(F&& f) noexcept( noexcept(inherited_t::assign(std::forward<F>(f)))) { static_assert(inherited_t::template is_invocable<F>()); inherited_t::assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return inherited_t::stub_; } bool operator==(std::nullptr_t) noexcept { return *this; } bool operator!=(std::nullptr_t) noexcept { return !operator==(nullptr); } void assign(std::nullptr_t) noexcept { reset(); } void reset() noexcept { inherited_t::stub_ = {}; } void swap(fwdref& other) noexcept { std::swap(*this, other); } void swap(fwdref&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() const noexcept { return reinterpret_cast<T*>(inherited_t::store_); } }; } #endif // GNR_FORWARDER_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_FORWARDERREF_HPP # define GNR_FORWARDERREF_HPP # pragma once // std::memcpy #include <cstring> #include <functional> #include <type_traits> #include <utility> namespace gnr { namespace detail::fwdref { template <typename, bool> class fwdref_impl2; template <typename R, typename ...A, bool E> class fwdref_impl2<R (A...), E> { protected: R (*stub_)(void*, A&&...) noexcept(E) {}; void* store_; template <typename F> static constexpr auto is_invocable() noexcept { return std::is_invocable_r_v<R, F, A...>; } public: using result_type = R; public: R operator()(A... args) const noexcept(E) { //assert(stub_); return stub_(store_, std::forward<A>(args)...); } template <typename F, typename = std::enable_if_t< std::is_invocable_r_v<R, F, A...> > > void assign(F&& f) noexcept { using functor_type = std::decay_t<F>; stub_ = [](void* const ptr, A&&... args) noexcept(E) -> R { return std::invoke(*static_cast<functor_type*>(ptr), std::forward<A>(args)...); }; store_ = &f; } }; template <typename> class fwdref_impl; template <typename R, typename ...A> class fwdref_impl<R (A...)> : public fwdref_impl2<R (A...), false> { }; template <typename R, typename ...A> class fwdref_impl<R (A...) noexcept> : public fwdref_impl2<R (A...), true> { }; } template <typename A> class fwdref : public detail::fwdref::fwdref_impl<A> { using inherited_t = detail::fwdref::fwdref_impl<A>; public: fwdref() = default; fwdref(fwdref const&) = default; fwdref(fwdref&&) = default; template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, fwdref> && inherited_t::template is_invocable<F>() > > fwdref(F&& f) noexcept(noexcept(inherited_t::assign(std::forward<F>(f)))) { inherited_t::assign(std::forward<F>(f)); } fwdref& operator=(fwdref const&) = default; fwdref& operator=(fwdref&&) = default; template <typename F> fwdref& operator=(F&& f) noexcept( noexcept(inherited_t::assign(std::forward<F>(f)))) { static_assert(inherited_t::template is_invocable<F>()); inherited_t::assign(std::forward<F>(f)); return *this; } explicit operator bool() const noexcept { return inherited_t::stub_; } bool operator==(std::nullptr_t) noexcept { return *this; } bool operator!=(std::nullptr_t) noexcept { return !operator==(nullptr); } void assign(std::nullptr_t) noexcept { reset(); } void reset() noexcept { inherited_t::stub_ = {}; } void swap(fwdref& other) noexcept { std::swap(*this, other); } void swap(fwdref&& other) noexcept { std::swap(*this, std::move(other)); } template <typename T> auto target() const noexcept { return reinterpret_cast<T*>(inherited_t::store_); } }; } #endif // GNR_FORWARDER_HPP <|endoftext|>
<commit_before>/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.1 $ | | Classes: | SoMaterial | | Author(s) : Paul S. Strauss | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/elements/SoGLLazyElement.h> #include <Inventor/elements/SoOverrideElement.h> #include <Inventor/nodes/SoMaterial.h> SO_NODE_SOURCE(SoMaterial); //////////////////////////////////////////////////////////////////////// // // Description: // Constructor // // Use: public SoMaterial::SoMaterial() // //////////////////////////////////////////////////////////////////////// { SO_NODE_CONSTRUCTOR(SoMaterial); SO_NODE_ADD_FIELD(ambientColor, (SoLazyElement::getDefaultAmbient())); SO_NODE_ADD_FIELD(diffuseColor, (SoLazyElement::getDefaultDiffuse())); SO_NODE_ADD_FIELD(specularColor,(SoLazyElement::getDefaultSpecular())); SO_NODE_ADD_FIELD(emissiveColor,(SoLazyElement::getDefaultEmissive())); SO_NODE_ADD_FIELD(shininess, (SoLazyElement::getDefaultShininess())); SO_NODE_ADD_FIELD(transparency, (SoLazyElement::getDefaultTransparency())); isBuiltIn = TRUE; colorPacker = new SoColorPacker; } //////////////////////////////////////////////////////////////////////// // // Description: // This initializes the SoMaterial class. // // Use: internal void SoMaterial::initClass() // //////////////////////////////////////////////////////////////////////// { SO__NODE_INIT_CLASS(SoMaterial, "Material", SoNode); // Enable elements: SO_ENABLE(SoCallbackAction, SoLazyElement); SO_ENABLE(SoGLRenderAction, SoGLLazyElement); } //////////////////////////////////////////////////////////////////////// // // Description: // Destructor (necessary since inline destructor is too complex) // // Use: private SoMaterial::~SoMaterial() // //////////////////////////////////////////////////////////////////////// { delete colorPacker; } //////////////////////////////////////////////////////////////////////// // // Description: // Performs accumulation of state for actions. // // Use: extender void SoMaterial::doAction(SoAction *action) // //////////////////////////////////////////////////////////////////////// { SoState *state = action->getState(); register uint32_t bitmask = 0; // Set all non-ignored components if (! ambientColor.isIgnored() && ambientColor.getNum() > 0 && ! SoOverrideElement::getAmbientColorOverride(state)) { if (isOverride()) { SoOverrideElement::setAmbientColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::AMBIENT_MASK; } if (! diffuseColor.isIgnored() && diffuseColor.getNum() > 0 && ! SoOverrideElement::getDiffuseColorOverride(state)) { if (isOverride()) { SoOverrideElement::setDiffuseColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::DIFFUSE_MASK; } if (! transparency.isIgnored() && transparency.getNum() > 0 && ! SoOverrideElement::getTransparencyOverride(state)) { if (isOverride()) { SoOverrideElement::setTransparencyOverride(state, this, TRUE); } bitmask |= SoLazyElement::TRANSPARENCY_MASK; } if (! specularColor.isIgnored() && specularColor.getNum() > 0 && ! SoOverrideElement::getSpecularColorOverride(state)) { if (isOverride()) { SoOverrideElement::setSpecularColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::SPECULAR_MASK; } if (! emissiveColor.isIgnored() && emissiveColor.getNum() > 0 && ! SoOverrideElement::getEmissiveColorOverride(state)) { if (isOverride()) { SoOverrideElement::setEmissiveColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::EMISSIVE_MASK; } if (! shininess.isIgnored() && shininess.getNum() > 0 && ! SoOverrideElement::getShininessOverride(state)) { if (isOverride()) { SoOverrideElement::setShininessOverride(state, this, TRUE); } bitmask |= SoLazyElement::SHININESS_MASK; } SoLazyElement::setMaterials(state, this, bitmask, colorPacker, diffuseColor, transparency, ambientColor, emissiveColor, specularColor, shininess); } //////////////////////////////////////////////////////////////////////// // // Description: // Method for callback action // // Use: extender void SoMaterial::callback(SoCallbackAction *action) // //////////////////////////////////////////////////////////////////////// { SoMaterial::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Method for GL rendering // // Use: extender void SoMaterial::GLRender(SoGLRenderAction *action) // //////////////////////////////////////////////////////////////////////// { SoMaterial::doAction(action); // If there's only one color, we might as well send it now. This // prevents cache dependencies in some cases that were // specifically optimized for Inventor 2.0. if (diffuseColor.getNum() == 1 && !diffuseColor.isIgnored()) SoGLLazyElement::sendAllMaterial(action->getState()); } <commit_msg>Fix for Bug 360177: setOverride not working for transparency property.<commit_after>/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * 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. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ /* * Copyright (C) 1990,91 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.2 $ | | Classes: | SoMaterial | | Author(s) : Paul S. Strauss | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/elements/SoGLLazyElement.h> #include <Inventor/elements/SoOverrideElement.h> #include <Inventor/nodes/SoMaterial.h> SO_NODE_SOURCE(SoMaterial); //////////////////////////////////////////////////////////////////////// // // Description: // Constructor // // Use: public SoMaterial::SoMaterial() // //////////////////////////////////////////////////////////////////////// { SO_NODE_CONSTRUCTOR(SoMaterial); SO_NODE_ADD_FIELD(ambientColor, (SoLazyElement::getDefaultAmbient())); SO_NODE_ADD_FIELD(diffuseColor, (SoLazyElement::getDefaultDiffuse())); SO_NODE_ADD_FIELD(specularColor,(SoLazyElement::getDefaultSpecular())); SO_NODE_ADD_FIELD(emissiveColor,(SoLazyElement::getDefaultEmissive())); SO_NODE_ADD_FIELD(shininess, (SoLazyElement::getDefaultShininess())); SO_NODE_ADD_FIELD(transparency, (SoLazyElement::getDefaultTransparency())); isBuiltIn = TRUE; colorPacker = new SoColorPacker; } //////////////////////////////////////////////////////////////////////// // // Description: // This initializes the SoMaterial class. // // Use: internal void SoMaterial::initClass() // //////////////////////////////////////////////////////////////////////// { SO__NODE_INIT_CLASS(SoMaterial, "Material", SoNode); // Enable elements: SO_ENABLE(SoCallbackAction, SoLazyElement); SO_ENABLE(SoGLRenderAction, SoGLLazyElement); } //////////////////////////////////////////////////////////////////////// // // Description: // Destructor (necessary since inline destructor is too complex) // // Use: private SoMaterial::~SoMaterial() // //////////////////////////////////////////////////////////////////////// { delete colorPacker; } //////////////////////////////////////////////////////////////////////// // // Description: // Performs accumulation of state for actions. // // Use: extender void SoMaterial::doAction(SoAction *action) // //////////////////////////////////////////////////////////////////////// { SoState *state = action->getState(); register uint32_t bitmask = 0; // Set all non-ignored components if (! ambientColor.isIgnored() && ambientColor.getNum() > 0 && ! SoOverrideElement::getAmbientColorOverride(state)) { if (isOverride()) { SoOverrideElement::setAmbientColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::AMBIENT_MASK; } if (! diffuseColor.isIgnored() && diffuseColor.getNum() > 0 && ! SoOverrideElement::getDiffuseColorOverride(state)) { if (isOverride()) { SoOverrideElement::setDiffuseColorOverride(state, this, TRUE); // Diffuse color and transparency share override state if (! transparency.isIgnored() && transparency.getNum() > 0) bitmask |= SoLazyElement::TRANSPARENCY_MASK; } bitmask |= SoLazyElement::DIFFUSE_MASK; } if (! transparency.isIgnored() && transparency.getNum() > 0 && ! SoOverrideElement::getTransparencyOverride(state)) { if (isOverride()) { SoOverrideElement::setTransparencyOverride(state, this, TRUE); // Diffuse color and transparency share override state if (! diffuseColor.isIgnored() && diffuseColor.getNum() > 0) bitmask |= SoLazyElement::DIFFUSE_MASK; } bitmask |= SoLazyElement::TRANSPARENCY_MASK; } if (! specularColor.isIgnored() && specularColor.getNum() > 0 && ! SoOverrideElement::getSpecularColorOverride(state)) { if (isOverride()) { SoOverrideElement::setSpecularColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::SPECULAR_MASK; } if (! emissiveColor.isIgnored() && emissiveColor.getNum() > 0 && ! SoOverrideElement::getEmissiveColorOverride(state)) { if (isOverride()) { SoOverrideElement::setEmissiveColorOverride(state, this, TRUE); } bitmask |= SoLazyElement::EMISSIVE_MASK; } if (! shininess.isIgnored() && shininess.getNum() > 0 && ! SoOverrideElement::getShininessOverride(state)) { if (isOverride()) { SoOverrideElement::setShininessOverride(state, this, TRUE); } bitmask |= SoLazyElement::SHININESS_MASK; } SoLazyElement::setMaterials(state, this, bitmask, colorPacker, diffuseColor, transparency, ambientColor, emissiveColor, specularColor, shininess); } //////////////////////////////////////////////////////////////////////// // // Description: // Method for callback action // // Use: extender void SoMaterial::callback(SoCallbackAction *action) // //////////////////////////////////////////////////////////////////////// { SoMaterial::doAction(action); } //////////////////////////////////////////////////////////////////////// // // Description: // Method for GL rendering // // Use: extender void SoMaterial::GLRender(SoGLRenderAction *action) // //////////////////////////////////////////////////////////////////////// { SoMaterial::doAction(action); // If there's only one color, we might as well send it now. This // prevents cache dependencies in some cases that were // specifically optimized for Inventor 2.0. if (diffuseColor.getNum() == 1 && !diffuseColor.isIgnored()) SoGLLazyElement::sendAllMaterial(action->getState()); } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Christopher Gilbert <christopher.john.gilbert@gmail.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 "options.hpp" #include <nanomsgpp/nanomsgpp.hpp> #include <chrono> #include <cstring> #include <iostream> #include <stdexcept> #include <string> #include <thread> using namespace client; using namespace std; namespace nn = nanomsgpp; void configure_socket(nn::socket& socket, const options& ops) { socket.set_option(NN_SOL_SOCKET, nn::socket_option::send_timeout, ops.send_timeout * 1000); socket.set_option(NN_SOL_SOCKET, nn::socket_option::receive_timeout, ops.recv_timeout); if (ops.get_type() == nn::socket_type::subscribe) { for (auto& subscription : ops.subscribe) { socket.set_option(NN_SUB, nn::socket_option::sub_subscribe, subscription); } } } void connect_socket(nn::socket& socket, const options& ops) { for (auto& addr : ops.bind) { socket.bind(addr); } for (auto& addr : ops.connect) { socket.connect(addr); } } void print_message_part(char* buf, int buflen, const options& ops) { switch (ops.get_format()) { case echo_format::none: return; case echo_format::raw: fwrite (buf, 1, buflen, stdout); break; case echo_format::ascii: for (; buflen > 0; --buflen, ++buf) { if (isprint (*buf)) { fputc (*buf, stdout); } else { fputc ('.', stdout); } } fputc ('\n', stdout); break; case echo_format::quoted: fputc ('"', stdout); for (; buflen > 0; --buflen, ++buf) { switch (*buf) { case '\n': fprintf (stdout, "\\n"); break; case '\r': fprintf (stdout, "\\r"); break; case '\\': case '\"': fprintf (stdout, "\\%c", *buf); break; default: if (isprint (*buf)) { fputc (*buf, stdout); } else { fprintf (stdout, "\\x%02x", (unsigned char)*buf); } } } fprintf (stdout, "\"\n"); break; case echo_format::msgpack: if (buflen < 256) { fputc ('\xc4', stdout); fputc (buflen, stdout); fwrite (buf, 1, buflen, stdout); } else if (buflen < 65536) { fputc ('\xc5', stdout); fputc (buflen >> 8, stdout); fputc (buflen & 0xff, stdout); fwrite (buf, 1, buflen, stdout); } else { fputc ('\xc6', stdout); fputc (buflen >> 24, stdout); fputc ((buflen >> 16) & 0xff, stdout); fputc ((buflen >> 8) & 0xff, stdout); fputc (buflen & 0xff, stdout); fwrite (buf, 1, buflen, stdout); } break; } fflush (stdout); } void print_message(std::unique_ptr<nn::message>& msg, const options& ops) { for (auto& part : *msg) { char *buf = part.as<char>(); int buflen = std::strlen(buf); print_message_part(buf, buflen, ops); } } void send_loop(nn::socket& socket, const options& ops) { std::string data = ops.get_data(); while (true) { try { nn::message m; m << data; socket.sendmsg(std::move(m)); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { cerr << "Message not sent (EAGAIN)" << endl; } else { throw (e); } } if (ops.interval >= 0) { std::this_thread::sleep_for(std::chrono::seconds(ops.interval)); } else { break; } } } void recv_loop(nn::socket& socket, const options& ops) { while (true) { try { std::unique_ptr<nn::message> m = socket.recvmsg(1); print_message(m, ops); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { continue; } else if (e.error() == ETIMEDOUT || e.error() == EFSM) { return; } else { throw (e); } } } } void rw_loop(nn::socket& socket, const options& ops) { std::string data = ops.get_data(); while (true) { try { nn::message m; m << data; socket.sendmsg(std::move(m)); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { cerr << "Message not sent (EAGAIN)" << endl; } else { throw (e); } } if (ops.interval < 0) { recv_loop(socket, ops); } while (true) { try { std::unique_ptr<nn::message> m = socket.recvmsg(1); print_message(m, ops); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { continue; } else if (e.error() == ETIMEDOUT || e.error() == EFSM) { std::this_thread::sleep_for(std::chrono::seconds(ops.interval)); } } } } } void resp_loop(nn::socket& socket, const options& ops) { std::string data = ops.get_data(); while (true) { try { std::unique_ptr<nn::message> m = socket.recvmsg(1); print_message(m, ops); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { continue; } else { throw (e); } } try { nn::message m; m << data; socket.sendmsg(std::move(m)); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { cerr << "Message not sent (EAGAIN)" << endl; } else { throw (e); } } } } int main(int argc, char const* argv[]) { options const ops = process_command_line(argc, argv); if (ops.show_version) { cout << "nanomsgpp version 0.1.0" << endl; return EXIT_FAILURE; } if (ops.show_usage || ops.show_help) { show_usage(cout); if (ops.show_help) { cout << endl << show_help(cout); } return EXIT_FAILURE; } try { nn::socket socket(nn::socket_domain::sp, ops.get_type()); configure_socket(socket, ops); connect_socket(socket, ops); if (ops.delay != -1) { std::this_thread::sleep_for(std::chrono::seconds(ops.delay)); } switch (ops.get_type()) { case nn::socket_type::publish: case nn::socket_type::push: send_loop(socket, ops); break; case nn::socket_type::subscribe: case nn::socket_type::pull: recv_loop(socket, ops); break; case nn::socket_type::bus: case nn::socket_type::pair: if (!ops.get_data().empty()) { rw_loop(socket, ops); } else { recv_loop(socket, ops); } break; case nn::socket_type::surveyor: case nn::socket_type::request: rw_loop(socket, ops); break; case nn::socket_type::reply: case nn::socket_type::respondent: if (!ops.get_data().empty()) { resp_loop(socket, ops); } else { recv_loop(socket, ops); } break; } } catch (std::invalid_argument &e) { cerr << e.what() << endl; return EXIT_FAILURE; } catch (nn::internal_exception &e) { cerr << e.reason() << endl; return EXIT_FAILURE; } catch (...) { cerr << "Unknown exception" << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Fixed compilation error on OS-X<commit_after>/* * Copyright (C) 2014 Christopher Gilbert <christopher.john.gilbert@gmail.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 "options.hpp" #include <nanomsgpp/nanomsgpp.hpp> #include <chrono> #include <cstring> #include <iostream> #include <stdexcept> #include <string> #include <thread> using namespace client; using namespace std; namespace nn = nanomsgpp; void configure_socket(nn::socket& socket, const options& ops) { socket.set_option(NN_SOL_SOCKET, nn::socket_option::send_timeout, ops.send_timeout * 1000); socket.set_option(NN_SOL_SOCKET, nn::socket_option::receive_timeout, ops.recv_timeout); if (ops.get_type() == nn::socket_type::subscribe) { for (auto& subscription : ops.subscribe) { socket.set_option(NN_SUB, nn::socket_option::sub_subscribe, subscription); } } } void connect_socket(nn::socket& socket, const options& ops) { for (auto& addr : ops.bind) { socket.bind(addr); } for (auto& addr : ops.connect) { socket.connect(addr); } } void print_message_part(char* buf, int buflen, const options& ops) { switch (ops.get_format()) { case echo_format::none: return; case echo_format::raw: fwrite (buf, 1, buflen, stdout); break; case echo_format::ascii: for (; buflen > 0; --buflen, ++buf) { if (isprint (*buf)) { fputc (*buf, stdout); } else { fputc ('.', stdout); } } fputc ('\n', stdout); break; case echo_format::quoted: fputc ('"', stdout); for (; buflen > 0; --buflen, ++buf) { switch (*buf) { case '\n': fprintf (stdout, "\\n"); break; case '\r': fprintf (stdout, "\\r"); break; case '\\': case '\"': fprintf (stdout, "\\%c", *buf); break; default: if (isprint (*buf)) { fputc (*buf, stdout); } else { fprintf (stdout, "\\x%02x", (unsigned char)*buf); } } } fprintf (stdout, "\"\n"); break; case echo_format::msgpack: if (buflen < 256) { fputc ('\xc4', stdout); fputc (buflen, stdout); fwrite (buf, 1, buflen, stdout); } else if (buflen < 65536) { fputc ('\xc5', stdout); fputc (buflen >> 8, stdout); fputc (buflen & 0xff, stdout); fwrite (buf, 1, buflen, stdout); } else { fputc ('\xc6', stdout); fputc (buflen >> 24, stdout); fputc ((buflen >> 16) & 0xff, stdout); fputc ((buflen >> 8) & 0xff, stdout); fputc (buflen & 0xff, stdout); fwrite (buf, 1, buflen, stdout); } break; } fflush (stdout); } void print_message(std::unique_ptr<nn::message>& msg, const options& ops) { for (auto& part : *msg) { char *buf = part.as<char>(); int buflen = std::strlen(buf); print_message_part(buf, buflen, ops); } } void send_loop(nn::socket& socket, const options& ops) { std::string data = ops.get_data(); while (true) { try { nn::message m; m << data; socket.sendmsg(std::move(m)); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { cerr << "Message not sent (EAGAIN)" << endl; } else { throw (e); } } if (ops.interval >= 0) { std::this_thread::sleep_for(std::chrono::seconds(ops.interval)); } else { break; } } } void recv_loop(nn::socket& socket, const options& ops) { while (true) { try { std::unique_ptr<nn::message> m = socket.recvmsg(1); print_message(m, ops); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { continue; } else if (e.error() == ETIMEDOUT || e.error() == EFSM) { return; } else { throw (e); } } } } void rw_loop(nn::socket& socket, const options& ops) { std::string data = ops.get_data(); while (true) { try { nn::message m; m << data; socket.sendmsg(std::move(m)); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { cerr << "Message not sent (EAGAIN)" << endl; } else { throw (e); } } if (ops.interval < 0) { recv_loop(socket, ops); } while (true) { try { std::unique_ptr<nn::message> m = socket.recvmsg(1); print_message(m, ops); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { continue; } else if (e.error() == ETIMEDOUT || e.error() == EFSM) { std::this_thread::sleep_for(std::chrono::seconds(ops.interval)); } } } } } void resp_loop(nn::socket& socket, const options& ops) { std::string data = ops.get_data(); while (true) { try { std::unique_ptr<nn::message> m = socket.recvmsg(1); print_message(m, ops); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { continue; } else { throw (e); } } try { nn::message m; m << data; socket.sendmsg(std::move(m)); } catch (nn::internal_exception &e) { if (e.error() == EAGAIN) { cerr << "Message not sent (EAGAIN)" << endl; } else { throw (e); } } } } int main(int argc, char const* argv[]) { options const ops = process_command_line(argc, argv); if (ops.show_version) { cout << "nanomsgpp version 0.1.0" << endl; return EXIT_FAILURE; } if (ops.show_usage || ops.show_help) { show_usage(cout); if (ops.show_help) { cout << endl; show_help(cout); } return EXIT_FAILURE; } try { nn::socket socket(nn::socket_domain::sp, ops.get_type()); configure_socket(socket, ops); connect_socket(socket, ops); if (ops.delay != -1) { std::this_thread::sleep_for(std::chrono::seconds(ops.delay)); } switch (ops.get_type()) { case nn::socket_type::publish: case nn::socket_type::push: send_loop(socket, ops); break; case nn::socket_type::subscribe: case nn::socket_type::pull: recv_loop(socket, ops); break; case nn::socket_type::bus: case nn::socket_type::pair: if (!ops.get_data().empty()) { rw_loop(socket, ops); } else { recv_loop(socket, ops); } break; case nn::socket_type::surveyor: case nn::socket_type::request: rw_loop(socket, ops); break; case nn::socket_type::reply: case nn::socket_type::respondent: if (!ops.get_data().empty()) { resp_loop(socket, ops); } else { recv_loop(socket, ops); } break; } } catch (std::invalid_argument &e) { cerr << e.what() << endl; return EXIT_FAILURE; } catch (nn::internal_exception &e) { cerr << e.reason() << endl; return EXIT_FAILURE; } catch (...) { cerr << "Unknown exception" << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>Fix namespace to ultimately compile on Mac BUG=none TEST=none Review URL: http://codereview.chromium.org/115924<commit_after><|endoftext|>
<commit_before>#pragma once #include <cstdint> namespace cu { template <typename T> struct IntTraits; namespace detail { template <std::size_t nBits_, bool isSigned_> struct IntTraitsImpl { static constexpr std::size_t nBits = nBits_; static constexpr bool isSigned = isSigned_; }; } template <> struct IntTraits<std:: int8_t> : detail::IntTraitsImpl< 8, true> {}; template <> struct IntTraits<std:: int16_t> : detail::IntTraitsImpl<16, true> {}; template <> struct IntTraits<std:: int32_t> : detail::IntTraitsImpl<32, true> {}; template <> struct IntTraits<std:: int64_t> : detail::IntTraitsImpl<64, true> {}; template <> struct IntTraits<std:: uint8_t> : detail::IntTraitsImpl< 8,false> {}; template <> struct IntTraits<std::uint16_t> : detail::IntTraitsImpl<16,false> {}; template <> struct IntTraits<std::uint32_t> : detail::IntTraitsImpl<32,false> {}; template <> struct IntTraits<std::uint64_t> : detail::IntTraitsImpl<64,false> {}; namespace detail { template <std::size_t nBits, bool isSigned> struct BuildInIntImpl; template <typename T> struct TypeTrait { using type = T; }; template <> struct BuildInIntImpl< 8, true> : TypeTrait<std:: int8_t> {}; template <> struct BuildInIntImpl<16, true> : TypeTrait<std:: int16_t> {}; template <> struct BuildInIntImpl<32, true> : TypeTrait<std:: int32_t> {}; template <> struct BuildInIntImpl<64, true> : TypeTrait<std:: int64_t> {}; template <> struct BuildInIntImpl< 8,false> : TypeTrait<std:: uint8_t> {}; template <> struct BuildInIntImpl<16,false> : TypeTrait<std::uint16_t> {}; template <> struct BuildInIntImpl<32,false> : TypeTrait<std::uint32_t> {}; template <> struct BuildInIntImpl<64,false> : TypeTrait<std::uint64_t> {}; } template <std::size_t nBits, bool isSigned = true> using BuildInInt = typename detail::BuildInIntImpl<nBits,isSigned>::type; } // namespace cu <commit_msg>Added DoubleSizeInt<T> to int_traits.hpp.<commit_after>#pragma once #include <cstdint> namespace cu { template <typename T> struct IntTraits; namespace detail { template <std::size_t nBits_, bool isSigned_> struct IntTraitsImpl { static constexpr std::size_t nBits = nBits_; static constexpr bool isSigned = isSigned_; }; } template <> struct IntTraits<std:: int8_t> : detail::IntTraitsImpl< 8, true> {}; template <> struct IntTraits<std:: int16_t> : detail::IntTraitsImpl<16, true> {}; template <> struct IntTraits<std:: int32_t> : detail::IntTraitsImpl<32, true> {}; template <> struct IntTraits<std:: int64_t> : detail::IntTraitsImpl<64, true> {}; template <> struct IntTraits<std:: uint8_t> : detail::IntTraitsImpl< 8,false> {}; template <> struct IntTraits<std::uint16_t> : detail::IntTraitsImpl<16,false> {}; template <> struct IntTraits<std::uint32_t> : detail::IntTraitsImpl<32,false> {}; template <> struct IntTraits<std::uint64_t> : detail::IntTraitsImpl<64,false> {}; namespace detail { template <std::size_t nBits, bool isSigned> struct BuildInIntImpl; template <typename T> struct TypeTrait { using type = T; }; template <> struct BuildInIntImpl< 8, true> : TypeTrait<std:: int8_t> {}; template <> struct BuildInIntImpl<16, true> : TypeTrait<std:: int16_t> {}; template <> struct BuildInIntImpl<32, true> : TypeTrait<std:: int32_t> {}; template <> struct BuildInIntImpl<64, true> : TypeTrait<std:: int64_t> {}; template <> struct BuildInIntImpl< 8,false> : TypeTrait<std:: uint8_t> {}; template <> struct BuildInIntImpl<16,false> : TypeTrait<std::uint16_t> {}; template <> struct BuildInIntImpl<32,false> : TypeTrait<std::uint32_t> {}; template <> struct BuildInIntImpl<64,false> : TypeTrait<std::uint64_t> {}; } template <std::size_t nBits, bool isSigned = true> using BuildInInt = typename detail::BuildInIntImpl<nBits,isSigned>::type; template <typename IntT> using DoubleSizeInt = BuildInInt<IntTraits<IntT>::nBits*2,IntTraits<IntT>::isSigned>; } // namespace cu <|endoftext|>
<commit_before><commit_msg>Apply style guideline for variable names for browser action container.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/basictypes.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_reg_util_win.h" #include "base/time/time.h" #include "base/win/registry.h" #include "chrome/installer/gcapi/gcapi.h" #include "chrome/installer/gcapi/gcapi_omaha_experiment.h" #include "chrome/installer/gcapi/gcapi_reactivation.h" #include "chrome/installer/util/google_update_constants.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; using base::win::RegKey; namespace { const wchar_t kExperimentLabels[] = L"experiment_labels"; const wchar_t* kExperimentAppGuids[] = { L"{4DC8B4CA-1BDA-483e-B5FA-D3C12E15B62D}", L"{8A69D345-D564-463C-AFF1-A69D9E530F96}", }; } class GCAPIReactivationTest : public ::testing::Test { protected: void SetUp() { // Override keys - this is undone during destruction. std::wstring hkcu_override = base::StringPrintf( L"hkcu_override\\%ls", ASCIIToWide(base::GenerateGUID())); override_manager_.OverrideRegistry(HKEY_CURRENT_USER, hkcu_override); std::wstring hklm_override = base::StringPrintf( L"hklm_override\\%ls", ASCIIToWide(base::GenerateGUID())); override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE, hklm_override); } bool SetChromeInstallMarker(HKEY hive) { // Create the client state keys in the right places. std::wstring reg_path(google_update::kRegPathClients); reg_path += L"\\"; reg_path += google_update::kChromeUpgradeCode; RegKey client_state(hive, reg_path.c_str(), KEY_CREATE_SUB_KEY | KEY_SET_VALUE); return (client_state.Valid() && client_state.WriteValue( google_update::kRegVersionField, L"1.2.3.4") == ERROR_SUCCESS); } bool SetLastRunTime(HKEY hive, int64 last_run_time) { return SetLastRunTimeString(hive, base::Int64ToString16(last_run_time)); } bool SetLastRunTimeString(HKEY hive, const string16& last_run_time_string) { const wchar_t* base_path = (hive == HKEY_LOCAL_MACHINE) ? google_update::kRegPathClientStateMedium : google_update::kRegPathClientState; std::wstring path(base_path); path += L"\\"; path += google_update::kChromeUpgradeCode; RegKey client_state(hive, path.c_str(), KEY_SET_VALUE); return (client_state.Valid() && client_state.WriteValue( google_update::kRegLastRunTimeField, last_run_time_string.c_str()) == ERROR_SUCCESS); } bool HasExperimentLabels(HKEY hive) { int label_count = 0; for (int i = 0; i < arraysize(kExperimentAppGuids); ++i) { string16 client_state_path(google_update::kRegPathClientState); client_state_path += L"\\"; client_state_path += kExperimentAppGuids[i]; RegKey client_state_key(hive, client_state_path.c_str(), KEY_QUERY_VALUE); if (client_state_key.Valid() && client_state_key.HasValue(kExperimentLabels)) { label_count++; } } return label_count == arraysize(kExperimentAppGuids); } std::wstring GetReactivationString(HKEY hive) { const wchar_t* base_path = (hive == HKEY_LOCAL_MACHINE) ? google_update::kRegPathClientStateMedium : google_update::kRegPathClientState; std::wstring path(base_path); path += L"\\"; path += google_update::kChromeUpgradeCode; RegKey client_state(hive, path.c_str(), KEY_QUERY_VALUE); if (client_state.Valid()) { std::wstring actual_brand; if (client_state.ReadValue(google_update::kRegRLZReactivationBrandField, &actual_brand) == ERROR_SUCCESS) { return actual_brand; } } return L"ERROR"; } private: registry_util::RegistryOverrideManager override_manager_; }; TEST_F(GCAPIReactivationTest, CheckSetReactivationBrandCode) { EXPECT_TRUE(SetReactivationBrandCode(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); EXPECT_TRUE(HasBeenReactivated()); } TEST_F(GCAPIReactivationTest, CanOfferReactivation_Basic) { DWORD error; // We're not installed yet. Make sure CanOfferReactivation fails. EXPECT_FALSE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_NOTINSTALLED, error); // Now pretend to be installed. CanOfferReactivation should pass. EXPECT_TRUE(SetChromeInstallMarker(HKEY_CURRENT_USER)); EXPECT_TRUE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); // Now set a recent last_run value. CanOfferReactivation should fail again. Time hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(20); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_FALSE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_NOTDORMANT, error); // Now set a last_run value that exceeds the threshold. hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(kReactivationMinDaysDormant); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_TRUE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); // Test some invalid inputs EXPECT_FALSE(CanOfferReactivation(NULL, GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_INVALID_INPUT, error); // One more valid one EXPECT_TRUE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); // Check that the previous brands check works: EXPECT_TRUE(SetReactivationBrandCode(L"GOOGOO", GCAPI_INVOKED_STANDARD_SHELL)); EXPECT_FALSE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_ALREADY_REACTIVATED, error); } TEST_F(GCAPIReactivationTest, Reactivation_Flow) { DWORD error; // Set us up as a candidate for reactivation. EXPECT_TRUE(SetChromeInstallMarker(HKEY_CURRENT_USER)); Time hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(kReactivationMinDaysDormant); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_TRUE(ReactivateChrome(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); // Make sure we can't reactivate again: EXPECT_FALSE(ReactivateChrome(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_ALREADY_REACTIVATED, error); // Should not be able to reactivate under other brands: EXPECT_FALSE(ReactivateChrome(L"MAMA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); // Validate that previous_brands are rejected: EXPECT_FALSE(ReactivateChrome(L"PFFT", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_ALREADY_REACTIVATED, error); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); } TEST_F(GCAPIReactivationTest, ExperimentLabelCheck) { DWORD error; // Set us up as a candidate for reactivation. EXPECT_TRUE(SetChromeInstallMarker(HKEY_CURRENT_USER)); Time hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(kReactivationMinDaysDormant); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_TRUE(ReactivateChrome(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); EXPECT_TRUE(HasExperimentLabels(HKEY_CURRENT_USER)); } <commit_msg>Fix GCAPIReactivationTest.ExperimentLabelCheck<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/basictypes.h" #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/test/test_reg_util_win.h" #include "base/time/time.h" #include "base/win/registry.h" #include "chrome/installer/gcapi/gcapi.h" #include "chrome/installer/gcapi/gcapi_omaha_experiment.h" #include "chrome/installer/gcapi/gcapi_reactivation.h" #include "chrome/installer/util/google_update_constants.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; using base::win::RegKey; class GCAPIReactivationTest : public ::testing::Test { protected: void SetUp() { // Override keys - this is undone during destruction. std::wstring hkcu_override = base::StringPrintf( L"hkcu_override\\%ls", ASCIIToWide(base::GenerateGUID())); override_manager_.OverrideRegistry(HKEY_CURRENT_USER, hkcu_override); std::wstring hklm_override = base::StringPrintf( L"hklm_override\\%ls", ASCIIToWide(base::GenerateGUID())); override_manager_.OverrideRegistry(HKEY_LOCAL_MACHINE, hklm_override); } bool SetChromeInstallMarker(HKEY hive) { // Create the client state keys in the right places. std::wstring reg_path(google_update::kRegPathClients); reg_path += L"\\"; reg_path += google_update::kChromeUpgradeCode; RegKey client_state(hive, reg_path.c_str(), KEY_CREATE_SUB_KEY | KEY_SET_VALUE); return (client_state.Valid() && client_state.WriteValue( google_update::kRegVersionField, L"1.2.3.4") == ERROR_SUCCESS); } bool SetLastRunTime(HKEY hive, int64 last_run_time) { return SetLastRunTimeString(hive, base::Int64ToString16(last_run_time)); } bool SetLastRunTimeString(HKEY hive, const string16& last_run_time_string) { const wchar_t* base_path = (hive == HKEY_LOCAL_MACHINE) ? google_update::kRegPathClientStateMedium : google_update::kRegPathClientState; std::wstring path(base_path); path += L"\\"; path += google_update::kChromeUpgradeCode; RegKey client_state(hive, path.c_str(), KEY_SET_VALUE); return (client_state.Valid() && client_state.WriteValue( google_update::kRegLastRunTimeField, last_run_time_string.c_str()) == ERROR_SUCCESS); } bool HasExperimentLabels(HKEY hive) { string16 client_state_path(google_update::kRegPathClientState); client_state_path.push_back(L'\\'); client_state_path.append(google_update::kChromeUpgradeCode); RegKey client_state_key(hive, client_state_path.c_str(), KEY_QUERY_VALUE); return client_state_key.Valid() && client_state_key.HasValue(google_update::kExperimentLabels); } std::wstring GetReactivationString(HKEY hive) { const wchar_t* base_path = (hive == HKEY_LOCAL_MACHINE) ? google_update::kRegPathClientStateMedium : google_update::kRegPathClientState; std::wstring path(base_path); path += L"\\"; path += google_update::kChromeUpgradeCode; RegKey client_state(hive, path.c_str(), KEY_QUERY_VALUE); if (client_state.Valid()) { std::wstring actual_brand; if (client_state.ReadValue(google_update::kRegRLZReactivationBrandField, &actual_brand) == ERROR_SUCCESS) { return actual_brand; } } return L"ERROR"; } private: registry_util::RegistryOverrideManager override_manager_; }; TEST_F(GCAPIReactivationTest, CheckSetReactivationBrandCode) { EXPECT_TRUE(SetReactivationBrandCode(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); EXPECT_TRUE(HasBeenReactivated()); } TEST_F(GCAPIReactivationTest, CanOfferReactivation_Basic) { DWORD error; // We're not installed yet. Make sure CanOfferReactivation fails. EXPECT_FALSE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_NOTINSTALLED, error); // Now pretend to be installed. CanOfferReactivation should pass. EXPECT_TRUE(SetChromeInstallMarker(HKEY_CURRENT_USER)); EXPECT_TRUE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); // Now set a recent last_run value. CanOfferReactivation should fail again. Time hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(20); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_FALSE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_NOTDORMANT, error); // Now set a last_run value that exceeds the threshold. hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(kReactivationMinDaysDormant); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_TRUE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); // Test some invalid inputs EXPECT_FALSE(CanOfferReactivation(NULL, GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_INVALID_INPUT, error); // One more valid one EXPECT_TRUE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); // Check that the previous brands check works: EXPECT_TRUE(SetReactivationBrandCode(L"GOOGOO", GCAPI_INVOKED_STANDARD_SHELL)); EXPECT_FALSE(CanOfferReactivation(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_ALREADY_REACTIVATED, error); } TEST_F(GCAPIReactivationTest, Reactivation_Flow) { DWORD error; // Set us up as a candidate for reactivation. EXPECT_TRUE(SetChromeInstallMarker(HKEY_CURRENT_USER)); Time hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(kReactivationMinDaysDormant); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_TRUE(ReactivateChrome(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); // Make sure we can't reactivate again: EXPECT_FALSE(ReactivateChrome(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_ALREADY_REACTIVATED, error); // Should not be able to reactivate under other brands: EXPECT_FALSE(ReactivateChrome(L"MAMA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); // Validate that previous_brands are rejected: EXPECT_FALSE(ReactivateChrome(L"PFFT", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(REACTIVATE_ERROR_ALREADY_REACTIVATED, error); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); } TEST_F(GCAPIReactivationTest, ExperimentLabelCheck) { DWORD error; // Set us up as a candidate for reactivation. EXPECT_TRUE(SetChromeInstallMarker(HKEY_CURRENT_USER)); Time hkcu_last_run = Time::NowFromSystemTime() - TimeDelta::FromDays(kReactivationMinDaysDormant); EXPECT_TRUE(SetLastRunTime(HKEY_CURRENT_USER, hkcu_last_run.ToInternalValue())); EXPECT_TRUE(ReactivateChrome(L"GAGA", GCAPI_INVOKED_STANDARD_SHELL, &error)); EXPECT_EQ(L"GAGA", GetReactivationString(HKEY_CURRENT_USER)); EXPECT_TRUE(HasExperimentLabels(HKEY_CURRENT_USER)); } <|endoftext|>
<commit_before>#include "attribute_provider.hpp" #include "../base/assert.hpp" #ifdef DEBUG #define INIT_CHECK_INFO(x) m_checkInfo = vector<bool>((vector<bool>::size_type)(x), false); #define CHECK_STREAMS CheckStreams() #define INIT_STREAM(x) InitCheckStream((x)) #else #include "../../base/macros.hpp" #define INIT_CHECK_INFO(x) UNUSED_VALUE((x)) #define CHECK_STREAMS #define INIT_STREAM(x) UNUSED_VALUE((x)) #endif AttributeProvider::AttributeProvider(uint8_t streamCount, uint16_t vertexCount) : m_vertexCount(vertexCount) { m_streams.resize(streamCount); INIT_CHECK_INFO(streamCount); } /// interface for batcher bool AttributeProvider::IsDataExists() const { CHECK_STREAMS; return m_vertexCount > 0; } uint16_t AttributeProvider::GetVertexCount() const { return m_vertexCount; } uint8_t AttributeProvider::GetStreamCount() const { return m_streams.size(); } const void * AttributeProvider::GetRawPointer(uint8_t streamIndex) { ASSERT_LESS(streamIndex, GetStreamCount(), ()); CHECK_STREAMS; return m_streams[streamIndex].m_data.GetRaw(); } const BindingInfo & AttributeProvider::GetBindingInfo(uint8_t streamIndex) const { ASSERT_LESS(streamIndex, GetStreamCount(), ()); CHECK_STREAMS; return m_streams[streamIndex].m_binding; } void AttributeProvider::Advance(uint16_t vertexCount) { ASSERT_LESS_OR_EQUAL(vertexCount, m_vertexCount, ()); CHECK_STREAMS; for (size_t i = 0; i < GetStreamCount(); ++i) { const BindingInfo & info = m_streams[i].m_binding; uint32_t offset = vertexCount * info.GetElementSize(); void * rawPointer = m_streams[i].m_data.GetRaw(); m_streams[i].m_data = MakeStackRefPointer((void *)(((uint8_t *)rawPointer) + offset)); } m_vertexCount -= vertexCount; } void AttributeProvider::InitStream(uint8_t streamIndex, const BindingInfo &bindingInfo, RefPointer<void> data) { ASSERT_LESS(streamIndex, GetStreamCount(), ()); AttributeStream s; s.m_binding = bindingInfo; s.m_data = data; m_streams[streamIndex] = s; INIT_STREAM(streamIndex); } #ifdef DEBUG void AttributeProvider::CheckStreams() const { ASSERT(std::find(m_checkInfo.begin(), m_checkInfo.end(), false) == m_checkInfo.end(), ("Not all streams initialized")); } void AttributeProvider::InitCheckStream(uint8_t streamIndex) { m_checkInfo[streamIndex] = true; } #endif <commit_msg>[drape] if we streams on "after end" memory, we don't create new stack pointer. New pointer can intersect with correct pointer of other object that also registered in pointer tracker<commit_after>#include "attribute_provider.hpp" #include "../base/assert.hpp" #ifdef DEBUG #define INIT_CHECK_INFO(x) m_checkInfo = vector<bool>((vector<bool>::size_type)(x), false); #define CHECK_STREAMS CheckStreams() #define INIT_STREAM(x) InitCheckStream((x)) #else #include "../../base/macros.hpp" #define INIT_CHECK_INFO(x) UNUSED_VALUE((x)) #define CHECK_STREAMS #define INIT_STREAM(x) UNUSED_VALUE((x)) #endif AttributeProvider::AttributeProvider(uint8_t streamCount, uint16_t vertexCount) : m_vertexCount(vertexCount) { m_streams.resize(streamCount); INIT_CHECK_INFO(streamCount); } /// interface for batcher bool AttributeProvider::IsDataExists() const { CHECK_STREAMS; return m_vertexCount > 0; } uint16_t AttributeProvider::GetVertexCount() const { return m_vertexCount; } uint8_t AttributeProvider::GetStreamCount() const { return m_streams.size(); } const void * AttributeProvider::GetRawPointer(uint8_t streamIndex) { ASSERT_LESS(streamIndex, GetStreamCount(), ()); CHECK_STREAMS; return m_streams[streamIndex].m_data.GetRaw(); } const BindingInfo & AttributeProvider::GetBindingInfo(uint8_t streamIndex) const { ASSERT_LESS(streamIndex, GetStreamCount(), ()); CHECK_STREAMS; return m_streams[streamIndex].m_binding; } void AttributeProvider::Advance(uint16_t vertexCount) { ASSERT_LESS_OR_EQUAL(vertexCount, m_vertexCount, ()); CHECK_STREAMS; if (m_vertexCount != vertexCount) { for (size_t i = 0; i < GetStreamCount(); ++i) { const BindingInfo & info = m_streams[i].m_binding; uint32_t offset = vertexCount * info.GetElementSize(); void * rawPointer = m_streams[i].m_data.GetRaw(); m_streams[i].m_data = MakeStackRefPointer((void *)(((uint8_t *)rawPointer) + offset)); } } m_vertexCount -= vertexCount; } void AttributeProvider::InitStream(uint8_t streamIndex, const BindingInfo &bindingInfo, RefPointer<void> data) { ASSERT_LESS(streamIndex, GetStreamCount(), ()); AttributeStream s; s.m_binding = bindingInfo; s.m_data = data; m_streams[streamIndex] = s; INIT_STREAM(streamIndex); } #ifdef DEBUG void AttributeProvider::CheckStreams() const { ASSERT(std::find(m_checkInfo.begin(), m_checkInfo.end(), false) == m_checkInfo.end(), ("Not all streams initialized")); } void AttributeProvider::InitCheckStream(uint8_t streamIndex) { m_checkInfo[streamIndex] = true; } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDicer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkDicer.h" #include "vtkMath.h" // Description: // Create object with 5000 points per piece. vtkDicer::vtkDicer() { this->NumberOfPointsPerPiece = 5000; this->NumberOfPieces = 0; } void vtkDicer::BuildTree(vtkIdList *ptIds, vtkOBBNode *OBBptr) { int i, numPts=ptIds->GetNumberOfIds(); int ptId; static vtkOBBTree OBB; vtkDataSet *input=(vtkDataSet *)this->Input; float size[3]; // // Gather all the points into a single list // for ( this->PointsList->Reset(), i=0; i < numPts; i++ ) { ptId = ptIds->GetId(i); this->PointsList->InsertNextPoint(input->GetPoint(ptId)); } // // Now compute the OBB // OBB.ComputeOBB(this->PointsList, OBBptr->Corner, OBBptr->Axes[0], OBBptr->Axes[1], OBBptr->Axes[2], size); // // Check whether to continue recursing; if so, create two children and // assign cells to appropriate child. // if ( numPts > this->NumberOfPointsPerPiece ) { vtkOBBNode *LHnode= new vtkOBBNode; vtkOBBNode *RHnode= new vtkOBBNode; OBBptr->Kids = new vtkOBBNode *[2]; OBBptr->Kids[0] = LHnode; OBBptr->Kids[1] = RHnode; vtkIdList *LHlist = vtkIdList::New(); LHlist->Allocate(numPts/2); vtkIdList *RHlist = vtkIdList::New(); RHlist->Allocate(numPts/2); LHnode->Parent = OBBptr; RHnode->Parent = OBBptr; float n[3], p[3], *x, val; //split the longest axis down the middle for (i=0; i < 3; i++) //compute split point { p[i] = OBBptr->Corner[i] + OBBptr->Axes[0][i]/2.0 + OBBptr->Axes[1][i]/2.0 + OBBptr->Axes[2][i]/2.0; } // compute split normal for (i=0 ; i < 3; i++) n[i] = OBBptr->Axes[0][i]; vtkMath::Normalize(n); //traverse cells, assigning to appropriate child list as necessary for ( i=0; i < numPts; i++ ) { ptId = ptIds->GetId(i); x = input->GetPoint(ptId); val = n[0]*(x[0]-p[0]) + n[1]*(x[1]-p[1]) + n[2]*(x[2]-p[2]); if ( val < 0.0 ) { LHlist->InsertNextId(ptId); } else { RHlist->InsertNextId(ptId); } }//for all points delete ptIds; //don't need to keep anymore this->BuildTree(LHlist, LHnode); this->BuildTree(RHlist, RHnode); }//if should build tree else //terminate recursion { ptIds->Squeeze(); OBBptr->Cells = ptIds; } } // Current implementation uses an OBBTree to split up the dataset. void vtkDicer::Execute() { int ptId, numPts; vtkIdList *ptIds; vtkScalars *groupIds; vtkOBBNode *root; vtkDataSet *input=(vtkDataSet *)this->Input; vtkDataSet *output=(vtkDataSet *)this->Output; vtkDebugMacro(<<"Dicing object"); if ( (numPts = input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"No data to dice!"); return; } // // Create list of points // this->PointsList = vtkPoints::New(); this->PointsList->Allocate(numPts); ptIds = vtkIdList::New(); ptIds->SetNumberOfIds(numPts); for ( ptId=0; ptId < numPts; ptId++ ) { ptIds->SetId(ptId,ptId); } root = new vtkOBBNode; this->BuildTree(ptIds,root); // // Generate scalar values // this->PointsList->Delete(); this->PointsList = NULL; groupIds = vtkScalars::New(VTK_SHORT,1); groupIds->SetNumberOfScalars(numPts); this->NumberOfPieces = 0; this->MarkPoints(root,groupIds); this->DeleteTree(root); delete root; vtkDebugMacro(<<"Created " << this->NumberOfPieces << " pieces"); // // Update self // output->GetPointData()->CopyScalarsOff(); output->GetPointData()->PassData(input->GetPointData()); output->GetPointData()->SetScalars(groupIds); groupIds->Delete(); } void vtkDicer::MarkPoints(vtkOBBNode *OBBptr, vtkScalars *groupIds) { if ( OBBptr->Kids == NULL ) //leaf OBB { vtkIdList *ptIds; int i, ptId, numIds; ptIds = OBBptr->Cells; if ( (numIds=ptIds->GetNumberOfIds()) > 0 ) { for ( i=0; i < numIds; i++ ) { ptId = ptIds->GetId(i); groupIds->SetScalar(ptId,this->NumberOfPieces); } this->NumberOfPieces++; }//if any points in this leaf OBB } else { this->MarkPoints(OBBptr->Kids[0],groupIds); this->MarkPoints(OBBptr->Kids[1],groupIds); } } void vtkDicer::DeleteTree(vtkOBBNode *OBBptr) { if ( OBBptr->Kids != NULL ) { this->DeleteTree(OBBptr->Kids[0]); this->DeleteTree(OBBptr->Kids[1]); delete OBBptr->Kids[0]; delete OBBptr->Kids[1]; delete [] OBBptr->Kids; } } void vtkDicer::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToDataSetFilter::PrintSelf(os,indent); os << indent << "Number of Points per Piece: " << this->NumberOfPointsPerPiece << "\n";; os << indent << "Number of Pieces: " << this->NumberOfPieces << "\n";; } <commit_msg>ERR: was double freeing OBBptr->Kids<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDicer.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkDicer.h" #include "vtkMath.h" // Description: // Create object with 5000 points per piece. vtkDicer::vtkDicer() { this->NumberOfPointsPerPiece = 5000; this->NumberOfPieces = 0; } void vtkDicer::BuildTree(vtkIdList *ptIds, vtkOBBNode *OBBptr) { int i, numPts=ptIds->GetNumberOfIds(); int ptId; static vtkOBBTree OBB; vtkDataSet *input=(vtkDataSet *)this->Input; float size[3]; // // Gather all the points into a single list // for ( this->PointsList->Reset(), i=0; i < numPts; i++ ) { ptId = ptIds->GetId(i); this->PointsList->InsertNextPoint(input->GetPoint(ptId)); } // // Now compute the OBB // OBB.ComputeOBB(this->PointsList, OBBptr->Corner, OBBptr->Axes[0], OBBptr->Axes[1], OBBptr->Axes[2], size); // // Check whether to continue recursing; if so, create two children and // assign cells to appropriate child. // if ( numPts > this->NumberOfPointsPerPiece ) { vtkOBBNode *LHnode= new vtkOBBNode; vtkOBBNode *RHnode= new vtkOBBNode; OBBptr->Kids = new vtkOBBNode *[2]; OBBptr->Kids[0] = LHnode; OBBptr->Kids[1] = RHnode; vtkIdList *LHlist = vtkIdList::New(); LHlist->Allocate(numPts/2); vtkIdList *RHlist = vtkIdList::New(); RHlist->Allocate(numPts/2); LHnode->Parent = OBBptr; RHnode->Parent = OBBptr; float n[3], p[3], *x, val; //split the longest axis down the middle for (i=0; i < 3; i++) //compute split point { p[i] = OBBptr->Corner[i] + OBBptr->Axes[0][i]/2.0 + OBBptr->Axes[1][i]/2.0 + OBBptr->Axes[2][i]/2.0; } // compute split normal for (i=0 ; i < 3; i++) n[i] = OBBptr->Axes[0][i]; vtkMath::Normalize(n); //traverse cells, assigning to appropriate child list as necessary for ( i=0; i < numPts; i++ ) { ptId = ptIds->GetId(i); x = input->GetPoint(ptId); val = n[0]*(x[0]-p[0]) + n[1]*(x[1]-p[1]) + n[2]*(x[2]-p[2]); if ( val < 0.0 ) { LHlist->InsertNextId(ptId); } else { RHlist->InsertNextId(ptId); } }//for all points delete ptIds; //don't need to keep anymore this->BuildTree(LHlist, LHnode); this->BuildTree(RHlist, RHnode); }//if should build tree else //terminate recursion { ptIds->Squeeze(); OBBptr->Cells = ptIds; } } // Current implementation uses an OBBTree to split up the dataset. void vtkDicer::Execute() { int ptId, numPts; vtkIdList *ptIds; vtkScalars *groupIds; vtkOBBNode *root; vtkDataSet *input=(vtkDataSet *)this->Input; vtkDataSet *output=(vtkDataSet *)this->Output; vtkDebugMacro(<<"Dicing object"); if ( (numPts = input->GetNumberOfPoints()) < 1 ) { vtkErrorMacro(<<"No data to dice!"); return; } // // Create list of points // this->PointsList = vtkPoints::New(); this->PointsList->Allocate(numPts); ptIds = vtkIdList::New(); ptIds->SetNumberOfIds(numPts); for ( ptId=0; ptId < numPts; ptId++ ) { ptIds->SetId(ptId,ptId); } root = new vtkOBBNode; this->BuildTree(ptIds,root); // // Generate scalar values // this->PointsList->Delete(); this->PointsList = NULL; groupIds = vtkScalars::New(VTK_SHORT,1); groupIds->SetNumberOfScalars(numPts); this->NumberOfPieces = 0; this->MarkPoints(root,groupIds); this->DeleteTree(root); delete root; vtkDebugMacro(<<"Created " << this->NumberOfPieces << " pieces"); // // Update self // output->GetPointData()->CopyScalarsOff(); output->GetPointData()->PassData(input->GetPointData()); output->GetPointData()->SetScalars(groupIds); groupIds->Delete(); } void vtkDicer::MarkPoints(vtkOBBNode *OBBptr, vtkScalars *groupIds) { if ( OBBptr->Kids == NULL ) //leaf OBB { vtkIdList *ptIds; int i, ptId, numIds; ptIds = OBBptr->Cells; if ( (numIds=ptIds->GetNumberOfIds()) > 0 ) { for ( i=0; i < numIds; i++ ) { ptId = ptIds->GetId(i); groupIds->SetScalar(ptId,this->NumberOfPieces); } this->NumberOfPieces++; }//if any points in this leaf OBB } else { this->MarkPoints(OBBptr->Kids[0],groupIds); this->MarkPoints(OBBptr->Kids[1],groupIds); } } void vtkDicer::DeleteTree(vtkOBBNode *OBBptr) { if ( OBBptr->Kids != NULL ) { this->DeleteTree(OBBptr->Kids[0]); this->DeleteTree(OBBptr->Kids[1]); delete OBBptr->Kids[0]; delete OBBptr->Kids[1]; } } void vtkDicer::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToDataSetFilter::PrintSelf(os,indent); os << indent << "Number of Points per Piece: " << this->NumberOfPointsPerPiece << "\n";; os << indent << "Number of Pieces: " << this->NumberOfPieces << "\n";; } <|endoftext|>
<commit_before>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2016, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_TABLES_H_ #define LUWRA_TABLES_H_ #include "common.hpp" #include "types.hpp" #include "auxiliary.hpp" LUWRA_NS_BEGIN namespace internal { // This represents a "path" which will be resolved lazily. It is useful for chained table // access. An access like 'table.field1.field2' would be represented similar to // `Path<Path<Table, std::string>, std::string> table {{table, "field1"}, "field"}`. template <typename P, typename K> struct Path { P parent; K key; // Read the value to which this path points to. template <typename V> inline V read(State* state) const { luwra::push(state, *this); V value = luwra::read<V>(state, -1); lua_pop(state, 1); return value; } // Change the value to which this path points to. template <typename V> inline void write(State* state, V&& value) const { size_t pushedParents = luwra::push(state, parent); if (pushedParents > 1) lua_pop(state, static_cast<int>(pushedParents - 1)); size_t pushedKeys = luwra::push(state, key); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); size_t pushedValues = luwra::push(state, std::forward<V>(value)); if (pushedValues > 1) lua_pop(state, static_cast<int>(pushedValues - 1)); lua_rawset(state, -3); lua_pop(state, 1); } }; } template <typename P, typename K> struct Value<internal::Path<P, K>> { // Push the value to which the path points onto the stack. static inline size_t push(State* state, const internal::Path<P, K>& accessor) { size_t pushedParents = luwra::push(state, accessor.parent); if (pushedParents > 1) lua_pop(state, static_cast<int>(pushedParents - 1)); size_t pushedKeys = luwra::push(state, accessor.key); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); lua_rawget(state, -2); lua_remove(state, -2); return 1; } }; namespace internal { template <typename A> struct TableAccessor { State* state; A accessor; template <typename V> inline V read() const && { return accessor.template read<V>(state); } template <typename V> inline operator V() const && { return accessor.template read<V>(state); } template <typename V> inline const TableAccessor&& write(V&& value) const && { accessor.write(state, std::forward<V>(value)); return std::move(*this); } template <typename V> inline const TableAccessor&& operator =(V&& value) const && { accessor.write(state, std::forward<V>(value)); return std::move(*this); } template <typename K> inline TableAccessor<Path<A, K>> access(K&& subkey) const && { return TableAccessor<Path<A, K>> { state, Path<A, K> { accessor, std::forward<K>(subkey) } }; } template <typename K> inline TableAccessor<Path<A, K>> operator [](K&& subkey) const && { return TableAccessor<Path<A, K>> { state, Path<A, K> { accessor, std::forward<K>(subkey) } }; } }; } template <typename A> struct Value<internal::TableAccessor<A>> { static inline size_t push(State* state, internal::TableAccessor<A>& ta) { return luwra::push(state, ta.accessor); } }; struct Table { Reference ref; Table(const Reference& ref): ref(ref) {} Table(State* state, int index): ref(state, index, true) { luaL_checktype(state, index, LUA_TTABLE); } Table(State* state): Table(state, (lua_newtable(state), -1)) { lua_pop(state, 1); } Table(State* state, const MemberMap& fields): Table(state, (luwra::push(state, fields), -1)) { lua_pop(state, 1); } template <typename K> inline internal::TableAccessor<internal::Path<const Reference&, K>> access(K&& key) const { return internal::TableAccessor<internal::Path<const Reference&, K>> { ref.impl->state, internal::Path<const Reference&, K> { ref, std::forward<K>(key) } }; } template <typename K> inline internal::TableAccessor<internal::Path<const Reference&, K>> operator [](K&& key) const { return internal::TableAccessor<internal::Path<const Reference&, K>> { ref.impl->state, internal::Path<const Reference&, K> { ref, std::forward<K>(key) } }; } inline void update(const MemberMap& fields) const { State* state = ref.impl->state; push(state, ref); setFields(state, -1, fields); lua_pop(state, 1); } template <typename K> inline bool has(K&& key) const { State* state = ref.impl->state; push(state, ref); size_t pushedKeys = push(state, std::forward<K>(key)); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); lua_rawget(state, -2); bool isNil = lua_isnil(state, -1); lua_pop(state, 2); return !isNil; } template <typename V, typename K> inline void set(K&& key, V&& value) const { State* state = ref.impl->state; push(state, ref); size_t pushedKeys = push(state, std::forward<K>(key)); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); size_t pushedValues = push(state, std::forward<V>(value)); if (pushedValues > 1) lua_pop(state, static_cast<int>(pushedValues - 1)); lua_rawset(state, -3); lua_pop(state, 1); } template <typename V, typename K> inline V get(K&& key) const { State* state = ref.impl->state; push(state, ref); size_t pushedKeys = push(state, std::forward<K>(key)); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); lua_rawget(state, -2); V ret = read<V>(state, -1); lua_pop(state, 2); return ret; } }; /** * See [Table](@ref Table). */ template <> struct Value<Table> { static inline Table read(State* state, int index) { return {state, index}; } static inline size_t push(State* state, const Table& value) { return value.ref.impl->push(state); } }; /** * Retrieve the table containing all global values. * \param state Lua state * \returns Reference to the globals table. */ static inline Table getGlobalsTable(State* state) { #if LUA_VERSION_NUM <= 501 return {{state, internal::referenceValue(state, LUA_GLOBALSINDEX), false}}; #else return {{state, LUA_RIDX_GLOBALS, false}}; #endif } LUWRA_NS_END #endif <commit_msg>Beautify template parameter names<commit_after>/* Luwra * Minimal-overhead Lua wrapper for C++ * * Copyright (C) 2016, Ole Krüger <ole@vprsm.de> */ #ifndef LUWRA_TABLES_H_ #define LUWRA_TABLES_H_ #include "common.hpp" #include "types.hpp" #include "auxiliary.hpp" LUWRA_NS_BEGIN namespace internal { // This represents a "path" which will be resolved lazily. It is useful for chained table // access. An access like 'table.field1.field2' would be represented similar to // `Path<Path<Table, std::string>, std::string> table {{table, "field1"}, "field"}`. template <typename Parent, typename Key> struct Path { Parent parent; Key key; // Read the value to which this path points to. template <typename V> inline V read(State* state) const { luwra::push(state, *this); V value = luwra::read<V>(state, -1); lua_pop(state, 1); return value; } // Change the value to which this path points to. template <typename V> inline void write(State* state, V&& value) const { size_t pushedParents = luwra::push(state, parent); if (pushedParents > 1) lua_pop(state, static_cast<int>(pushedParents - 1)); size_t pushedKeys = luwra::push(state, key); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); size_t pushedValues = luwra::push(state, std::forward<V>(value)); if (pushedValues > 1) lua_pop(state, static_cast<int>(pushedValues - 1)); lua_rawset(state, -3); lua_pop(state, 1); } }; } template <typename Parent, typename Key> struct Value<internal::Path<Parent, Key>> { // Push the value to which the path points onto the stack. static inline size_t push(State* state, const internal::Path<Parent, Key>& accessor) { size_t pushedParents = luwra::push(state, accessor.parent); if (pushedParents > 1) lua_pop(state, static_cast<int>(pushedParents - 1)); size_t pushedKeys = luwra::push(state, accessor.key); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); lua_rawget(state, -2); lua_remove(state, -2); return 1; } }; namespace internal { template <typename Accessor> struct TableAccessor { State* state; Accessor accessor; template <typename Type> inline Type read() const && { return accessor.template read<Type>(state); } template <typename Type> inline operator Type() const && { return accessor.template read<Type>(state); } template <typename Type> inline const TableAccessor&& write(Type&& value) const && { accessor.write(state, std::forward<Type>(value)); return std::move(*this); } template <typename Type> inline const TableAccessor&& operator =(Type&& value) const && { accessor.write(state, std::forward<Type>(value)); return std::move(*this); } template <typename Key> inline TableAccessor<Path<Accessor, Key>> access(Key&& subkey) const && { return TableAccessor<Path<Accessor, Key>> { state, Path<Accessor, Key> { accessor, std::forward<Key>(subkey) } }; } template <typename Key> inline TableAccessor<Path<Accessor, Key>> operator [](Key&& subkey) const && { return TableAccessor<Path<Accessor, Key>> { state, Path<Accessor, Key> { accessor, std::forward<Key>(subkey) } }; } }; } template <typename Accessor> struct Value<internal::TableAccessor<Accessor>> { static inline size_t push(State* state, internal::TableAccessor<Accessor>& ta) { return luwra::push(state, ta.accessor); } }; struct Table { Reference ref; Table(const Reference& ref): ref(ref) {} Table(State* state, int index): ref(state, index, true) { luaL_checktype(state, index, LUA_TTABLE); } Table(State* state): Table(state, (lua_newtable(state), -1)) { lua_pop(state, 1); } Table(State* state, const MemberMap& fields): Table(state, (luwra::push(state, fields), -1)) { lua_pop(state, 1); } template <typename Key> inline internal::TableAccessor<internal::Path<const Reference&, Key>> access(Key&& key) const { return internal::TableAccessor<internal::Path<const Reference&, Key>> { ref.impl->state, internal::Path<const Reference&, Key> { ref, std::forward<Key>(key) } }; } template <typename Key> inline internal::TableAccessor<internal::Path<const Reference&, Key>> operator [](Key&& key) const { return internal::TableAccessor<internal::Path<const Reference&, Key>> { ref.impl->state, internal::Path<const Reference&, Key> { ref, std::forward<Key>(key) } }; } inline void update(const MemberMap& fields) const { State* state = ref.impl->state; push(state, ref); setFields(state, -1, fields); lua_pop(state, 1); } template <typename Key> inline bool has(Key&& key) const { State* state = ref.impl->state; push(state, ref); size_t pushedKeys = push(state, std::forward<Key>(key)); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); lua_rawget(state, -2); bool isNil = lua_isnil(state, -1); lua_pop(state, 2); return !isNil; } template <typename Type, typename Key> inline void set(Key&& key, Type&& value) const { State* state = ref.impl->state; push(state, ref); size_t pushedKeys = push(state, std::forward<Key>(key)); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); size_t pushedValues = push(state, std::forward<Type>(value)); if (pushedValues > 1) lua_pop(state, static_cast<int>(pushedValues - 1)); lua_rawset(state, -3); lua_pop(state, 1); } template <typename Type, typename Key> inline Type get(Key&& key) const { State* state = ref.impl->state; push(state, ref); size_t pushedKeys = push(state, std::forward<Key>(key)); if (pushedKeys > 1) lua_pop(state, static_cast<int>(pushedKeys - 1)); lua_rawget(state, -2); Type ret = read<Type>(state, -1); lua_pop(state, 2); return ret; } }; /** * See [Table](@ref Table). */ template <> struct Value<Table> { static inline Table read(State* state, int index) { return {state, index}; } static inline size_t push(State* state, const Table& value) { return value.ref.impl->push(state); } }; /** * Retrieve the table containing all global values. * \param state Lua state * \returns Reference to the globals table. */ static inline Table getGlobalsTable(State* state) { #if LUA_VERSION_NUM <= 501 return {{state, internal::referenceValue(state, LUA_GLOBALSINDEX), false}}; #else return {{state, LUA_RIDX_GLOBALS, false}}; #endif } LUWRA_NS_END #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <iostream> #include <string> #include <algorithm> using namespace std; #define N 20010 int n, m, ans, cnt; int s[N], e[N], c[N], fa[N], rank[N], x[N]; int find(int v) { if (fa[v] == v) return v; else { int temp = fa[v]; fa[v] = find(fa[v]); rank[v] = rank[v] ^ rank[temp]; return fa[v]; } } bool check(int u, int v, int r) { int fu = find(u); int fv = find(v); // printf("u=%d fu=%d v=%d fv=%d\n", u, fu, v, fv); for (int i = 1; i <= cnt; i++) { // printf("fa[%d]=%d rank[%d]=%d\n",i, fa[i], i, rank[i]); } if (fu == fv) { return (rank[u]^rank[v]) == r; } return true; } void merge(int u, int v, int r) { int fu = find(u); int fv = find(v); if (fu > fv) { fa[fu] = fv; rank[fu] = rank[u]^rank[v]^r; } else { fa[fv] = fu; rank[fv] = rank[u]^rank[v]^r; } } int bs(int start, int end, int item) { int l = start; int r = end; while(l < r) { int mid = (l+r) >> 1; if (x[mid] == item) return mid; else if (x[mid] < item) l = mid+1; else r = mid; } return -1; } int main () { cin >> n >> m; string op; cnt = 0; ans = 0; ::memset(c, 0, sizeof(c)); ::memset(x, 0, sizeof(x)); for (int i = 0; i < m; i++) { cin >> s[i] >> e[i] >> op; x[cnt++] = s[i]; x[cnt++] = e[i]+1; if (op[0] == 'o') c[i] = 1; } sort(x, x+cnt); cnt = unique(x, x+cnt)-x; for (int i = 0; i < N; i++) { fa[i] = i; rank[i] = 0; } // for (int i = 0; i < cnt; i++) { // printf("%d ", x[i]); // } // printf("\n"); for (int i = 0; i < m; i++) { int u = bs(0, cnt, s[i]) + 1; int v = bs(0, cnt, e[i]+1) + 1; // printf("s=%d e=%d u=%d v=%d rel=%d\n",s[i], e[i]+1, u, v, c[i]); if (!check(u, v, c[i])) { break; } merge(u, v, c[i]); ans++; } printf("%d\n", ans); return 0; } <commit_msg>add tag for poj 1733<commit_after>//Tag: search disjoint set with weight //tips: //1. 带权并查集 //2. 当输入数据规模较大时,可以进行离散化,选用新的下标代替原先的数据段 //3. 当算法正确,但是TLE时,可查看输入数据规模限制是否为百万级别以上,如是的话,使用scanf取代cin,可以解决问题。 #include <stdio.h> #include <string.h> #include <iostream> #include <string> #include <algorithm> using namespace std; #define N 20010 int n, m, ans, cnt; int s[N], e[N], c[N], fa[N], rank[N], x[N]; int find(int v) { if (fa[v] == v) return v; else { int temp = fa[v]; fa[v] = find(fa[v]); rank[v] = rank[v] ^ rank[temp]; return fa[v]; } } bool check(int u, int v, int r) { int fu = find(u); int fv = find(v); // printf("u=%d fu=%d v=%d fv=%d\n", u, fu, v, fv); for (int i = 1; i <= cnt; i++) { // printf("fa[%d]=%d rank[%d]=%d\n",i, fa[i], i, rank[i]); } if (fu == fv) { return (rank[u]^rank[v]) == r; } return true; } void merge(int u, int v, int r) { int fu = find(u); int fv = find(v); if (fu > fv) { fa[fu] = fv; rank[fu] = rank[u]^rank[v]^r; } else { fa[fv] = fu; rank[fv] = rank[u]^rank[v]^r; } } int bs(int start, int end, int item) { int l = start; int r = end; while(l < r) { int mid = (l+r) >> 1; if (x[mid] == item) return mid; else if (x[mid] < item) l = mid+1; else r = mid; } return -1; } int main () { cin >> n >> m; string op; cnt = 0; ans = 0; ::memset(c, 0, sizeof(c)); ::memset(x, 0, sizeof(x)); for (int i = 0; i < m; i++) { cin >> s[i] >> e[i] >> op; x[cnt++] = s[i]; x[cnt++] = e[i]+1; if (op[0] == 'o') c[i] = 1; } sort(x, x+cnt); cnt = unique(x, x+cnt)-x; for (int i = 0; i < N; i++) { fa[i] = i; rank[i] = 0; } // for (int i = 0; i < cnt; i++) { // printf("%d ", x[i]); // } // printf("\n"); for (int i = 0; i < m; i++) { int u = bs(0, cnt, s[i]) + 1; int v = bs(0, cnt, e[i]+1) + 1; // printf("s=%d e=%d u=%d v=%d rel=%d\n",s[i], e[i]+1, u, v, c[i]); if (!check(u, v, c[i])) { break; } merge(u, v, c[i]); ans++; } printf("%d\n", ans); return 0; } <|endoftext|>
<commit_before><commit_msg>Tests for `Species::bind_to_new_parent`.<commit_after><|endoftext|>
<commit_before>// Copyright 2014 the V8 project 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 "src/compiler/pipeline.h" #include "src/base/platform/elapsed-timer.h" #include "src/compiler/ast-graph-builder.h" #include "src/compiler/change-lowering.h" #include "src/compiler/code-generator.h" #include "src/compiler/graph-replay.h" #include "src/compiler/graph-visualizer.h" #include "src/compiler/instruction.h" #include "src/compiler/instruction-selector.h" #include "src/compiler/js-context-specialization.h" #include "src/compiler/js-generic-lowering.h" #include "src/compiler/js-inlining.h" #include "src/compiler/js-typed-lowering.h" #include "src/compiler/machine-operator-reducer.h" #include "src/compiler/phi-reducer.h" #include "src/compiler/register-allocator.h" #include "src/compiler/schedule.h" #include "src/compiler/scheduler.h" #include "src/compiler/simplified-lowering.h" #include "src/compiler/simplified-operator-reducer.h" #include "src/compiler/typer.h" #include "src/compiler/value-numbering-reducer.h" #include "src/compiler/verifier.h" #include "src/hydrogen.h" #include "src/ostreams.h" #include "src/utils.h" namespace v8 { namespace internal { namespace compiler { class PhaseStats { public: enum PhaseKind { CREATE_GRAPH, OPTIMIZATION, CODEGEN }; PhaseStats(CompilationInfo* info, PhaseKind kind, const char* name) : info_(info), kind_(kind), name_(name), size_(info->zone()->allocation_size()) { if (FLAG_turbo_stats) { timer_.Start(); } } ~PhaseStats() { if (FLAG_turbo_stats) { base::TimeDelta delta = timer_.Elapsed(); size_t bytes = info_->zone()->allocation_size() - size_; HStatistics* stats = info_->isolate()->GetTStatistics(); stats->SaveTiming(name_, delta, static_cast<int>(bytes)); switch (kind_) { case CREATE_GRAPH: stats->IncrementCreateGraph(delta); break; case OPTIMIZATION: stats->IncrementOptimizeGraph(delta); break; case CODEGEN: stats->IncrementGenerateCode(delta); break; } } } private: CompilationInfo* info_; PhaseKind kind_; const char* name_; size_t size_; base::ElapsedTimer timer_; }; static inline bool VerifyGraphs() { #ifdef DEBUG return true; #else return FLAG_turbo_verify; #endif } void Pipeline::VerifyAndPrintGraph(Graph* graph, const char* phase) { if (FLAG_trace_turbo) { char buffer[256]; Vector<char> filename(buffer, sizeof(buffer)); if (!info_->shared_info().is_null()) { SmartArrayPointer<char> functionname = info_->shared_info()->DebugName()->ToCString(); if (strlen(functionname.get()) > 0) { SNPrintF(filename, "turbo-%s-%s", functionname.get(), phase); } else { SNPrintF(filename, "turbo-%p-%s", static_cast<void*>(info_), phase); } } else { SNPrintF(filename, "turbo-none-%s", phase); } std::replace(filename.start(), filename.start() + filename.length(), ' ', '_'); char dot_buffer[256]; Vector<char> dot_filename(dot_buffer, sizeof(dot_buffer)); SNPrintF(dot_filename, "%s.dot", filename.start()); FILE* dot_file = base::OS::FOpen(dot_filename.start(), "w+"); OFStream dot_of(dot_file); dot_of << AsDOT(*graph); fclose(dot_file); char json_buffer[256]; Vector<char> json_filename(json_buffer, sizeof(json_buffer)); SNPrintF(json_filename, "%s.json", filename.start()); FILE* json_file = base::OS::FOpen(json_filename.start(), "w+"); OFStream json_of(json_file); json_of << AsJSON(*graph); fclose(json_file); OFStream os(stdout); os << "-- " << phase << " graph printed to file " << filename.start() << "\n"; } if (VerifyGraphs()) Verifier::Run(graph); } class AstGraphBuilderWithPositions : public AstGraphBuilder { public: explicit AstGraphBuilderWithPositions(CompilationInfo* info, JSGraph* jsgraph, SourcePositionTable* source_positions) : AstGraphBuilder(info, jsgraph), source_positions_(source_positions) {} bool CreateGraph() { SourcePositionTable::Scope pos(source_positions_, SourcePosition::Unknown()); return AstGraphBuilder::CreateGraph(); } #define DEF_VISIT(type) \ virtual void Visit##type(type* node) OVERRIDE { \ SourcePositionTable::Scope pos(source_positions_, \ SourcePosition(node->position())); \ AstGraphBuilder::Visit##type(node); \ } AST_NODE_LIST(DEF_VISIT) #undef DEF_VISIT private: SourcePositionTable* source_positions_; }; static void TraceSchedule(Schedule* schedule) { if (!FLAG_trace_turbo) return; OFStream os(stdout); os << "-- Schedule --------------------------------------\n" << *schedule; } Handle<Code> Pipeline::GenerateCode() { if (info()->function()->dont_optimize_reason() == kTryCatchStatement || info()->function()->dont_optimize_reason() == kTryFinallyStatement || // TODO(turbofan): Make ES6 for-of work and remove this bailout. info()->function()->dont_optimize_reason() == kForOfStatement || // TODO(turbofan): Make super work and remove this bailout. info()->function()->dont_optimize_reason() == kSuperReference || // TODO(turbofan): Make OSR work and remove this bailout. info()->is_osr()) { return Handle<Code>::null(); } if (FLAG_turbo_stats) isolate()->GetTStatistics()->Initialize(info_); if (FLAG_trace_turbo) { OFStream os(stdout); os << "---------------------------------------------------\n" << "Begin compiling method " << info()->function()->debug_name()->ToCString().get() << " using Turbofan" << endl; } // Build the graph. Graph graph(zone()); SourcePositionTable source_positions(&graph); source_positions.AddDecorator(); // TODO(turbofan): there is no need to type anything during initial graph // construction. This is currently only needed for the node cache, which the // typer could sweep over later. Typer typer(zone()); MachineOperatorBuilder machine; CommonOperatorBuilder common(zone()); JSOperatorBuilder javascript(zone()); JSGraph jsgraph(&graph, &common, &javascript, &typer, &machine); Node* context_node; { PhaseStats graph_builder_stats(info(), PhaseStats::CREATE_GRAPH, "graph builder"); AstGraphBuilderWithPositions graph_builder(info(), &jsgraph, &source_positions); graph_builder.CreateGraph(); context_node = graph_builder.GetFunctionContext(); } { PhaseStats phi_reducer_stats(info(), PhaseStats::CREATE_GRAPH, "phi reduction"); PhiReducer phi_reducer; GraphReducer graph_reducer(&graph); graph_reducer.AddReducer(&phi_reducer); graph_reducer.ReduceGraph(); // TODO(mstarzinger): Running reducer once ought to be enough for everyone. graph_reducer.ReduceGraph(); graph_reducer.ReduceGraph(); } VerifyAndPrintGraph(&graph, "Initial untyped"); if (info()->is_context_specializing()) { SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); // Specialize the code to the context as aggressively as possible. JSContextSpecializer spec(info(), &jsgraph, context_node); spec.SpecializeToContext(); VerifyAndPrintGraph(&graph, "Context specialized"); } if (info()->is_inlining_enabled()) { SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); JSInliner inliner(info(), &jsgraph); inliner.Inline(); VerifyAndPrintGraph(&graph, "Inlined"); } // Print a replay of the initial graph. if (FLAG_print_turbo_replay) { GraphReplayPrinter::PrintReplay(&graph); } if (info()->is_typing_enabled()) { { // Type the graph. PhaseStats typer_stats(info(), PhaseStats::CREATE_GRAPH, "typer"); typer.Run(&graph, info()->context()); VerifyAndPrintGraph(&graph, "Typed"); } // All new nodes must be typed. typer.DecorateGraph(&graph); { // Lower JSOperators where we can determine types. PhaseStats lowering_stats(info(), PhaseStats::CREATE_GRAPH, "typed lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); JSTypedLowering lowering(&jsgraph); GraphReducer graph_reducer(&graph); graph_reducer.AddReducer(&lowering); graph_reducer.ReduceGraph(); VerifyAndPrintGraph(&graph, "Lowered typed"); } { // Lower simplified operators and insert changes. PhaseStats lowering_stats(info(), PhaseStats::CREATE_GRAPH, "simplified lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); SimplifiedLowering lowering(&jsgraph); lowering.LowerAllNodes(); VerifyAndPrintGraph(&graph, "Lowered simplified"); } { // Lower changes that have been inserted before. PhaseStats lowering_stats(info(), PhaseStats::OPTIMIZATION, "change lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); Linkage linkage(info()); // TODO(turbofan): Value numbering disabled for now. // ValueNumberingReducer vn_reducer(zone()); SimplifiedOperatorReducer simple_reducer(&jsgraph); ChangeLowering lowering(&jsgraph, &linkage); MachineOperatorReducer mach_reducer(&jsgraph); GraphReducer graph_reducer(&graph); // TODO(titzer): Figure out if we should run all reducers at once here. // graph_reducer.AddReducer(&vn_reducer); graph_reducer.AddReducer(&simple_reducer); graph_reducer.AddReducer(&lowering); graph_reducer.AddReducer(&mach_reducer); graph_reducer.ReduceGraph(); VerifyAndPrintGraph(&graph, "Lowered changes"); } } Handle<Code> code = Handle<Code>::null(); if (SupportedTarget()) { { // Lower any remaining generic JSOperators. PhaseStats lowering_stats(info(), PhaseStats::CREATE_GRAPH, "generic lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); JSGenericLowering lowering(info(), &jsgraph); GraphReducer graph_reducer(&graph); graph_reducer.AddReducer(&lowering); graph_reducer.ReduceGraph(); VerifyAndPrintGraph(&graph, "Lowered generic"); } { // Compute a schedule. Schedule* schedule = ComputeSchedule(&graph); // Generate optimized code. PhaseStats codegen_stats(info(), PhaseStats::CODEGEN, "codegen"); Linkage linkage(info()); code = GenerateCode(&linkage, &graph, schedule, &source_positions); info()->SetCode(code); } // Print optimized code. v8::internal::CodeGenerator::PrintCode(code, info()); } if (FLAG_trace_turbo) { OFStream os(stdout); os << "--------------------------------------------------\n" << "Finished compiling method " << info()->function()->debug_name()->ToCString().get() << " using Turbofan" << endl; } return code; } Schedule* Pipeline::ComputeSchedule(Graph* graph) { PhaseStats schedule_stats(info(), PhaseStats::CODEGEN, "scheduling"); Schedule* schedule = Scheduler::ComputeSchedule(graph); TraceSchedule(schedule); if (VerifyGraphs()) ScheduleVerifier::Run(schedule); return schedule; } Handle<Code> Pipeline::GenerateCodeForMachineGraph(Linkage* linkage, Graph* graph, Schedule* schedule) { CHECK(SupportedBackend()); if (schedule == NULL) { VerifyAndPrintGraph(graph, "Machine"); schedule = ComputeSchedule(graph); } TraceSchedule(schedule); SourcePositionTable source_positions(graph); Handle<Code> code = GenerateCode(linkage, graph, schedule, &source_positions); #if ENABLE_DISASSEMBLER if (!code.is_null() && FLAG_print_opt_code) { CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer()); OFStream os(tracing_scope.file()); code->Disassemble("test code", os); } #endif return code; } Handle<Code> Pipeline::GenerateCode(Linkage* linkage, Graph* graph, Schedule* schedule, SourcePositionTable* source_positions) { DCHECK_NOT_NULL(graph); DCHECK_NOT_NULL(linkage); DCHECK_NOT_NULL(schedule); CHECK(SupportedBackend()); InstructionSequence sequence(linkage, graph, schedule); // Select and schedule instructions covering the scheduled graph. { InstructionSelector selector(&sequence, source_positions); selector.SelectInstructions(); } if (FLAG_trace_turbo) { OFStream os(stdout); os << "----- Instruction sequence before register allocation -----\n" << sequence; } // Allocate registers. { int node_count = graph->NodeCount(); if (node_count > UnallocatedOperand::kMaxVirtualRegisters) { linkage->info()->AbortOptimization(kNotEnoughVirtualRegistersForValues); return Handle<Code>::null(); } RegisterAllocator allocator(&sequence); if (!allocator.Allocate()) { linkage->info()->AbortOptimization(kNotEnoughVirtualRegistersRegalloc); return Handle<Code>::null(); } } if (FLAG_trace_turbo) { OFStream os(stdout); os << "----- Instruction sequence after register allocation -----\n" << sequence; } // Generate native sequence. CodeGenerator generator(&sequence); return generator.GenerateCode(); } void Pipeline::SetUp() { InstructionOperand::SetUpCaches(); } void Pipeline::TearDown() { InstructionOperand::TearDownCaches(); } } // namespace compiler } // namespace internal } // namespace v8 <commit_msg>Correct bailout from TurboFan for unsupported targets.<commit_after>// Copyright 2014 the V8 project 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 "src/compiler/pipeline.h" #include "src/base/platform/elapsed-timer.h" #include "src/compiler/ast-graph-builder.h" #include "src/compiler/change-lowering.h" #include "src/compiler/code-generator.h" #include "src/compiler/graph-replay.h" #include "src/compiler/graph-visualizer.h" #include "src/compiler/instruction.h" #include "src/compiler/instruction-selector.h" #include "src/compiler/js-context-specialization.h" #include "src/compiler/js-generic-lowering.h" #include "src/compiler/js-inlining.h" #include "src/compiler/js-typed-lowering.h" #include "src/compiler/machine-operator-reducer.h" #include "src/compiler/phi-reducer.h" #include "src/compiler/register-allocator.h" #include "src/compiler/schedule.h" #include "src/compiler/scheduler.h" #include "src/compiler/simplified-lowering.h" #include "src/compiler/simplified-operator-reducer.h" #include "src/compiler/typer.h" #include "src/compiler/value-numbering-reducer.h" #include "src/compiler/verifier.h" #include "src/hydrogen.h" #include "src/ostreams.h" #include "src/utils.h" namespace v8 { namespace internal { namespace compiler { class PhaseStats { public: enum PhaseKind { CREATE_GRAPH, OPTIMIZATION, CODEGEN }; PhaseStats(CompilationInfo* info, PhaseKind kind, const char* name) : info_(info), kind_(kind), name_(name), size_(info->zone()->allocation_size()) { if (FLAG_turbo_stats) { timer_.Start(); } } ~PhaseStats() { if (FLAG_turbo_stats) { base::TimeDelta delta = timer_.Elapsed(); size_t bytes = info_->zone()->allocation_size() - size_; HStatistics* stats = info_->isolate()->GetTStatistics(); stats->SaveTiming(name_, delta, static_cast<int>(bytes)); switch (kind_) { case CREATE_GRAPH: stats->IncrementCreateGraph(delta); break; case OPTIMIZATION: stats->IncrementOptimizeGraph(delta); break; case CODEGEN: stats->IncrementGenerateCode(delta); break; } } } private: CompilationInfo* info_; PhaseKind kind_; const char* name_; size_t size_; base::ElapsedTimer timer_; }; static inline bool VerifyGraphs() { #ifdef DEBUG return true; #else return FLAG_turbo_verify; #endif } void Pipeline::VerifyAndPrintGraph(Graph* graph, const char* phase) { if (FLAG_trace_turbo) { char buffer[256]; Vector<char> filename(buffer, sizeof(buffer)); if (!info_->shared_info().is_null()) { SmartArrayPointer<char> functionname = info_->shared_info()->DebugName()->ToCString(); if (strlen(functionname.get()) > 0) { SNPrintF(filename, "turbo-%s-%s", functionname.get(), phase); } else { SNPrintF(filename, "turbo-%p-%s", static_cast<void*>(info_), phase); } } else { SNPrintF(filename, "turbo-none-%s", phase); } std::replace(filename.start(), filename.start() + filename.length(), ' ', '_'); char dot_buffer[256]; Vector<char> dot_filename(dot_buffer, sizeof(dot_buffer)); SNPrintF(dot_filename, "%s.dot", filename.start()); FILE* dot_file = base::OS::FOpen(dot_filename.start(), "w+"); OFStream dot_of(dot_file); dot_of << AsDOT(*graph); fclose(dot_file); char json_buffer[256]; Vector<char> json_filename(json_buffer, sizeof(json_buffer)); SNPrintF(json_filename, "%s.json", filename.start()); FILE* json_file = base::OS::FOpen(json_filename.start(), "w+"); OFStream json_of(json_file); json_of << AsJSON(*graph); fclose(json_file); OFStream os(stdout); os << "-- " << phase << " graph printed to file " << filename.start() << "\n"; } if (VerifyGraphs()) Verifier::Run(graph); } class AstGraphBuilderWithPositions : public AstGraphBuilder { public: explicit AstGraphBuilderWithPositions(CompilationInfo* info, JSGraph* jsgraph, SourcePositionTable* source_positions) : AstGraphBuilder(info, jsgraph), source_positions_(source_positions) {} bool CreateGraph() { SourcePositionTable::Scope pos(source_positions_, SourcePosition::Unknown()); return AstGraphBuilder::CreateGraph(); } #define DEF_VISIT(type) \ virtual void Visit##type(type* node) OVERRIDE { \ SourcePositionTable::Scope pos(source_positions_, \ SourcePosition(node->position())); \ AstGraphBuilder::Visit##type(node); \ } AST_NODE_LIST(DEF_VISIT) #undef DEF_VISIT private: SourcePositionTable* source_positions_; }; static void TraceSchedule(Schedule* schedule) { if (!FLAG_trace_turbo) return; OFStream os(stdout); os << "-- Schedule --------------------------------------\n" << *schedule; } Handle<Code> Pipeline::GenerateCode() { if (info()->function()->dont_optimize_reason() == kTryCatchStatement || info()->function()->dont_optimize_reason() == kTryFinallyStatement || // TODO(turbofan): Make ES6 for-of work and remove this bailout. info()->function()->dont_optimize_reason() == kForOfStatement || // TODO(turbofan): Make super work and remove this bailout. info()->function()->dont_optimize_reason() == kSuperReference || // TODO(turbofan): Make OSR work and remove this bailout. info()->is_osr()) { return Handle<Code>::null(); } if (FLAG_turbo_stats) isolate()->GetTStatistics()->Initialize(info_); if (FLAG_trace_turbo) { OFStream os(stdout); os << "---------------------------------------------------\n" << "Begin compiling method " << info()->function()->debug_name()->ToCString().get() << " using Turbofan" << endl; } // Build the graph. Graph graph(zone()); SourcePositionTable source_positions(&graph); source_positions.AddDecorator(); // TODO(turbofan): there is no need to type anything during initial graph // construction. This is currently only needed for the node cache, which the // typer could sweep over later. Typer typer(zone()); MachineOperatorBuilder machine; CommonOperatorBuilder common(zone()); JSOperatorBuilder javascript(zone()); JSGraph jsgraph(&graph, &common, &javascript, &typer, &machine); Node* context_node; { PhaseStats graph_builder_stats(info(), PhaseStats::CREATE_GRAPH, "graph builder"); AstGraphBuilderWithPositions graph_builder(info(), &jsgraph, &source_positions); graph_builder.CreateGraph(); context_node = graph_builder.GetFunctionContext(); } { PhaseStats phi_reducer_stats(info(), PhaseStats::CREATE_GRAPH, "phi reduction"); PhiReducer phi_reducer; GraphReducer graph_reducer(&graph); graph_reducer.AddReducer(&phi_reducer); graph_reducer.ReduceGraph(); // TODO(mstarzinger): Running reducer once ought to be enough for everyone. graph_reducer.ReduceGraph(); graph_reducer.ReduceGraph(); } VerifyAndPrintGraph(&graph, "Initial untyped"); if (info()->is_context_specializing()) { SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); // Specialize the code to the context as aggressively as possible. JSContextSpecializer spec(info(), &jsgraph, context_node); spec.SpecializeToContext(); VerifyAndPrintGraph(&graph, "Context specialized"); } if (info()->is_inlining_enabled()) { SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); JSInliner inliner(info(), &jsgraph); inliner.Inline(); VerifyAndPrintGraph(&graph, "Inlined"); } // Print a replay of the initial graph. if (FLAG_print_turbo_replay) { GraphReplayPrinter::PrintReplay(&graph); } // Bailout here in case target architecture is not supported. if (!SupportedTarget()) return Handle<Code>::null(); if (info()->is_typing_enabled()) { { // Type the graph. PhaseStats typer_stats(info(), PhaseStats::CREATE_GRAPH, "typer"); typer.Run(&graph, info()->context()); VerifyAndPrintGraph(&graph, "Typed"); } // All new nodes must be typed. typer.DecorateGraph(&graph); { // Lower JSOperators where we can determine types. PhaseStats lowering_stats(info(), PhaseStats::CREATE_GRAPH, "typed lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); JSTypedLowering lowering(&jsgraph); GraphReducer graph_reducer(&graph); graph_reducer.AddReducer(&lowering); graph_reducer.ReduceGraph(); VerifyAndPrintGraph(&graph, "Lowered typed"); } { // Lower simplified operators and insert changes. PhaseStats lowering_stats(info(), PhaseStats::CREATE_GRAPH, "simplified lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); SimplifiedLowering lowering(&jsgraph); lowering.LowerAllNodes(); VerifyAndPrintGraph(&graph, "Lowered simplified"); } { // Lower changes that have been inserted before. PhaseStats lowering_stats(info(), PhaseStats::OPTIMIZATION, "change lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); Linkage linkage(info()); // TODO(turbofan): Value numbering disabled for now. // ValueNumberingReducer vn_reducer(zone()); SimplifiedOperatorReducer simple_reducer(&jsgraph); ChangeLowering lowering(&jsgraph, &linkage); MachineOperatorReducer mach_reducer(&jsgraph); GraphReducer graph_reducer(&graph); // TODO(titzer): Figure out if we should run all reducers at once here. // graph_reducer.AddReducer(&vn_reducer); graph_reducer.AddReducer(&simple_reducer); graph_reducer.AddReducer(&lowering); graph_reducer.AddReducer(&mach_reducer); graph_reducer.ReduceGraph(); VerifyAndPrintGraph(&graph, "Lowered changes"); } } { // Lower any remaining generic JSOperators. PhaseStats lowering_stats(info(), PhaseStats::CREATE_GRAPH, "generic lowering"); SourcePositionTable::Scope pos(&source_positions, SourcePosition::Unknown()); JSGenericLowering lowering(info(), &jsgraph); GraphReducer graph_reducer(&graph); graph_reducer.AddReducer(&lowering); graph_reducer.ReduceGraph(); VerifyAndPrintGraph(&graph, "Lowered generic"); } Handle<Code> code = Handle<Code>::null(); { // Compute a schedule. Schedule* schedule = ComputeSchedule(&graph); // Generate optimized code. PhaseStats codegen_stats(info(), PhaseStats::CODEGEN, "codegen"); Linkage linkage(info()); code = GenerateCode(&linkage, &graph, schedule, &source_positions); info()->SetCode(code); } // Print optimized code. v8::internal::CodeGenerator::PrintCode(code, info()); if (FLAG_trace_turbo) { OFStream os(stdout); os << "--------------------------------------------------\n" << "Finished compiling method " << info()->function()->debug_name()->ToCString().get() << " using Turbofan" << endl; } return code; } Schedule* Pipeline::ComputeSchedule(Graph* graph) { PhaseStats schedule_stats(info(), PhaseStats::CODEGEN, "scheduling"); Schedule* schedule = Scheduler::ComputeSchedule(graph); TraceSchedule(schedule); if (VerifyGraphs()) ScheduleVerifier::Run(schedule); return schedule; } Handle<Code> Pipeline::GenerateCodeForMachineGraph(Linkage* linkage, Graph* graph, Schedule* schedule) { CHECK(SupportedBackend()); if (schedule == NULL) { VerifyAndPrintGraph(graph, "Machine"); schedule = ComputeSchedule(graph); } TraceSchedule(schedule); SourcePositionTable source_positions(graph); Handle<Code> code = GenerateCode(linkage, graph, schedule, &source_positions); #if ENABLE_DISASSEMBLER if (!code.is_null() && FLAG_print_opt_code) { CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer()); OFStream os(tracing_scope.file()); code->Disassemble("test code", os); } #endif return code; } Handle<Code> Pipeline::GenerateCode(Linkage* linkage, Graph* graph, Schedule* schedule, SourcePositionTable* source_positions) { DCHECK_NOT_NULL(graph); DCHECK_NOT_NULL(linkage); DCHECK_NOT_NULL(schedule); CHECK(SupportedBackend()); InstructionSequence sequence(linkage, graph, schedule); // Select and schedule instructions covering the scheduled graph. { InstructionSelector selector(&sequence, source_positions); selector.SelectInstructions(); } if (FLAG_trace_turbo) { OFStream os(stdout); os << "----- Instruction sequence before register allocation -----\n" << sequence; } // Allocate registers. { int node_count = graph->NodeCount(); if (node_count > UnallocatedOperand::kMaxVirtualRegisters) { linkage->info()->AbortOptimization(kNotEnoughVirtualRegistersForValues); return Handle<Code>::null(); } RegisterAllocator allocator(&sequence); if (!allocator.Allocate()) { linkage->info()->AbortOptimization(kNotEnoughVirtualRegistersRegalloc); return Handle<Code>::null(); } } if (FLAG_trace_turbo) { OFStream os(stdout); os << "----- Instruction sequence after register allocation -----\n" << sequence; } // Generate native sequence. CodeGenerator generator(&sequence); return generator.GenerateCode(); } void Pipeline::SetUp() { InstructionOperand::SetUpCaches(); } void Pipeline::TearDown() { InstructionOperand::TearDownCaches(); } } // namespace compiler } // namespace internal } // namespace v8 <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. 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. * */ #pragma once #define GRAPHENE_SYMBOL "CORE" #define GRAPHENE_ADDRESS_PREFIX "GPH" #define GRAPHENE_MIN_ACCOUNT_NAME_LENGTH 3 #define GRAPHENE_MAX_ACCOUNT_NAME_LENGTH 63 #define GRAPHENE_MIN_ASSET_SYMBOL_LENGTH 3 #define GRAPHENE_MAX_ASSET_SYMBOL_LENGTH 16 #define GRAPHENE_MAX_SHARE_SUPPLY int64_t(1000000000000000ll) #define GRAPHENE_MAX_PAY_RATE 10000 /* 100% */ #define GRAPHENE_MAX_SIG_CHECK_DEPTH 2 /** * Don't allow the committee_members to publish a limit that would * make the network unable to operate. */ #define GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT 1024 #define GRAPHENE_MIN_BLOCK_INTERVAL 1 /* seconds */ #define GRAPHENE_MAX_BLOCK_INTERVAL 30 /* seconds */ #define GRAPHENE_DEFAULT_BLOCK_INTERVAL 5 /* seconds */ #define GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE 2048 #define GRAPHENE_DEFAULT_MAX_BLOCK_SIZE (GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE*GRAPHENE_DEFAULT_BLOCK_INTERVAL*200000) #define GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day #define GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day #define GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS 3 // number of slots to skip for maintenance interval #define GRAPHENE_MIN_UNDO_HISTORY 10 #define GRAPHENE_MAX_UNDO_HISTORY 10000 #define GRAPHENE_MIN_BLOCK_SIZE_LIMIT (GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block #define GRAPHENE_MIN_TRANSACTION_EXPIRATION_LIMIT (GRAPHENE_MAX_BLOCK_INTERVAL * 5) // 5 transactions per block #define GRAPHENE_BLOCKCHAIN_PRECISION uint64_t( 100000 ) #define GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS 5 #define GRAPHENE_DEFAULT_TRANSFER_FEE (1*GRAPHENE_BLOCKCHAIN_PRECISION) #define GRAPHENE_MAX_INSTANCE_ID (uint64_t(-1)>>16) /** percentage fields are fixed point with a denominator of 10,000 */ #define GRAPHENE_100_PERCENT 10000 #define GRAPHENE_1_PERCENT (GRAPHENE_100_PERCENT/100) /** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */ #define GRAPHENE_MAX_MARKET_FEE_PERCENT GRAPHENE_100_PERCENT #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY (60*60*24) ///< 1 day #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET 0 ///< 1% #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME (20* GRAPHENE_1_PERCENT) ///< 20% #define GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME (60*60*24) ///< 1 day #define GRAPHENE_MAX_FEED_PRODUCERS 200 #define GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP 10 #define GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10 #define GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS 10 /** * These ratios are fixed point numbers with a denominator of GRAPHENE_COLLATERAL_RATIO_DENOM, the * minimum maitenance collateral is therefore 1.001x and the default * maintenance ratio is 1.75x */ ///@{ #define GRAPHENE_COLLATERAL_RATIO_DENOM 1000 #define GRAPHENE_MIN_COLLATERAL_RATIO 1001 ///< lower than this could result in divide by 0 #define GRAPHENE_MAX_COLLATERAL_RATIO 32000 ///< higher than this is unnecessary and may exceed int16 storage #define GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 ///< Call when collateral only pays off 175% the debt #define GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO 1500 ///< Stop calling when collateral only pays off 150% of the debt ///@} #define GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24) #define GRAPHENE_DEFAULT_MIN_WITNESS_COUNT (11) #define GRAPHENE_DEFAULT_MIN_COMMITTEE_MEMBER_COUNT (11) #define GRAPHENE_DEFAULT_MAX_WITNESSES (1001) // SHOULD BE ODD #define GRAPHENE_DEFAULT_MAX_COMMITTEE (1001) // SHOULD BE ODD #define GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks #define GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks #define GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE (30*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_MAX_BULK_DISCOUNT_PERCENT (50*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN ( GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(1000) ) #define GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MAX ( GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN*int64_t(100) ) #define GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC (60*60*24*365) ///< 1 year #define GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD (GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(100)) #define GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT) #define GRAPHENE_WITNESS_PAY_PERCENT_PRECISION (1000000000) #define GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE 1 #define GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD GRAPHENE_BLOCKCHAIN_PRECISION * 100; #define GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE 1000 #define GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS 4 #define GRAPHENE_MAX_WORKER_NAME_LENGTH 63 #define GRAPHENE_MAX_URL_LENGTH 127 // counter initialization values used to derive near and far future seeds for shuffling witnesses // we use the fractional bits of sqrt(2) in hex #define GRAPHENE_NEAR_SCHEDULE_CTR_IV ( (uint64_t( 0x6a09 ) << 0x30) \ | (uint64_t( 0xe667 ) << 0x20) \ | (uint64_t( 0xf3bc ) << 0x10) \ | (uint64_t( 0xc908 ) ) ) // and the fractional bits of sqrt(3) in hex #define GRAPHENE_FAR_SCHEDULE_CTR_IV ( (uint64_t( 0xbb67 ) << 0x30) \ | (uint64_t( 0xae85 ) << 0x20) \ | (uint64_t( 0x84ca ) << 0x10) \ | (uint64_t( 0xa73b ) ) ) /** * every second, the fraction of burned core asset which cycles is * GRAPHENE_CORE_ASSET_CYCLE_RATE / (1 << GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS) */ #define GRAPHENE_CORE_ASSET_CYCLE_RATE 17 #define GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS 32 #define GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t( 10) ) #define GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS (60*60*24) #define GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t(500) * 1000 ) #define GRAPHENE_DEFAULT_MINIMUM_FEEDS 7 #define GRAPHENE_MAX_INTEREST_APR uint16_t( 10000 ) #define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4 #define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3 #define GRAPHENE_CURRENT_DB_VERSION "test5b" #define GRAPHENE_IRREVERSIBLE_THRESHOLD (70 * GRAPHENE_1_PERCENT) /** * Reserved Account IDs with special meaning */ ///@{ /// Represents the current committee members, two-week review period #define GRAPHENE_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(0)) /// Represents the current witnesses #define GRAPHENE_WITNESS_ACCOUNT (graphene::chain::account_id_type(1)) /// Represents the current committee members #define GRAPHENE_RELAXED_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(2)) /// Represents the canonical account with NO authority (nobody can access funds in null account) #define GRAPHENE_NULL_ACCOUNT (graphene::chain::account_id_type(3)) /// Represents the canonical account with WILDCARD authority (anybody can access funds in temp account) #define GRAPHENE_TEMP_ACCOUNT (graphene::chain::account_id_type(4)) /// Represents the canonical account for specifying you will vote directly (as opposed to a proxy) #define GRAPHENE_PROXY_TO_SELF_ACCOUNT (graphene::chain::account_id_type(5)) /// Sentinel value used in the scheduler. #define GRAPHENE_NULL_WITNESS (graphene::chain::witness_id_type(0)) ///@} <commit_msg>config.hpp: Bump db version<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Any modified source or binaries are used only with the BitShares network. * * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 3. 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. * */ #pragma once #define GRAPHENE_SYMBOL "CORE" #define GRAPHENE_ADDRESS_PREFIX "GPH" #define GRAPHENE_MIN_ACCOUNT_NAME_LENGTH 3 #define GRAPHENE_MAX_ACCOUNT_NAME_LENGTH 63 #define GRAPHENE_MIN_ASSET_SYMBOL_LENGTH 3 #define GRAPHENE_MAX_ASSET_SYMBOL_LENGTH 16 #define GRAPHENE_MAX_SHARE_SUPPLY int64_t(1000000000000000ll) #define GRAPHENE_MAX_PAY_RATE 10000 /* 100% */ #define GRAPHENE_MAX_SIG_CHECK_DEPTH 2 /** * Don't allow the committee_members to publish a limit that would * make the network unable to operate. */ #define GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT 1024 #define GRAPHENE_MIN_BLOCK_INTERVAL 1 /* seconds */ #define GRAPHENE_MAX_BLOCK_INTERVAL 30 /* seconds */ #define GRAPHENE_DEFAULT_BLOCK_INTERVAL 5 /* seconds */ #define GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE 2048 #define GRAPHENE_DEFAULT_MAX_BLOCK_SIZE (GRAPHENE_DEFAULT_MAX_TRANSACTION_SIZE*GRAPHENE_DEFAULT_BLOCK_INTERVAL*200000) #define GRAPHENE_DEFAULT_MAX_TIME_UNTIL_EXPIRATION (60*60*24) // seconds, aka: 1 day #define GRAPHENE_DEFAULT_MAINTENANCE_INTERVAL (60*60*24) // seconds, aka: 1 day #define GRAPHENE_DEFAULT_MAINTENANCE_SKIP_SLOTS 3 // number of slots to skip for maintenance interval #define GRAPHENE_MIN_UNDO_HISTORY 10 #define GRAPHENE_MAX_UNDO_HISTORY 10000 #define GRAPHENE_MIN_BLOCK_SIZE_LIMIT (GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT*5) // 5 transactions per block #define GRAPHENE_MIN_TRANSACTION_EXPIRATION_LIMIT (GRAPHENE_MAX_BLOCK_INTERVAL * 5) // 5 transactions per block #define GRAPHENE_BLOCKCHAIN_PRECISION uint64_t( 100000 ) #define GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS 5 #define GRAPHENE_DEFAULT_TRANSFER_FEE (1*GRAPHENE_BLOCKCHAIN_PRECISION) #define GRAPHENE_MAX_INSTANCE_ID (uint64_t(-1)>>16) /** percentage fields are fixed point with a denominator of 10,000 */ #define GRAPHENE_100_PERCENT 10000 #define GRAPHENE_1_PERCENT (GRAPHENE_100_PERCENT/100) /** NOTE: making this a power of 2 (say 2^15) would greatly accelerate fee calcs */ #define GRAPHENE_MAX_MARKET_FEE_PERCENT GRAPHENE_100_PERCENT #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_DELAY (60*60*24) ///< 1 day #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_OFFSET 0 ///< 1% #define GRAPHENE_DEFAULT_FORCE_SETTLEMENT_MAX_VOLUME (20* GRAPHENE_1_PERCENT) ///< 20% #define GRAPHENE_DEFAULT_PRICE_FEED_LIFETIME (60*60*24) ///< 1 day #define GRAPHENE_MAX_FEED_PRODUCERS 200 #define GRAPHENE_DEFAULT_MAX_AUTHORITY_MEMBERSHIP 10 #define GRAPHENE_DEFAULT_MAX_ASSET_WHITELIST_AUTHORITIES 10 #define GRAPHENE_DEFAULT_MAX_ASSET_FEED_PUBLISHERS 10 /** * These ratios are fixed point numbers with a denominator of GRAPHENE_COLLATERAL_RATIO_DENOM, the * minimum maitenance collateral is therefore 1.001x and the default * maintenance ratio is 1.75x */ ///@{ #define GRAPHENE_COLLATERAL_RATIO_DENOM 1000 #define GRAPHENE_MIN_COLLATERAL_RATIO 1001 ///< lower than this could result in divide by 0 #define GRAPHENE_MAX_COLLATERAL_RATIO 32000 ///< higher than this is unnecessary and may exceed int16 storage #define GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO 1750 ///< Call when collateral only pays off 175% the debt #define GRAPHENE_DEFAULT_MAX_SHORT_SQUEEZE_RATIO 1500 ///< Stop calling when collateral only pays off 150% of the debt ///@} #define GRAPHENE_DEFAULT_MARGIN_PERIOD_SEC (30*60*60*24) #define GRAPHENE_DEFAULT_MIN_WITNESS_COUNT (11) #define GRAPHENE_DEFAULT_MIN_COMMITTEE_MEMBER_COUNT (11) #define GRAPHENE_DEFAULT_MAX_WITNESSES (1001) // SHOULD BE ODD #define GRAPHENE_DEFAULT_MAX_COMMITTEE (1001) // SHOULD BE ODD #define GRAPHENE_DEFAULT_MAX_PROPOSAL_LIFETIME_SEC (60*60*24*7*4) // Four weeks #define GRAPHENE_DEFAULT_COMMITTEE_PROPOSAL_REVIEW_PERIOD_SEC (60*60*24*7*2) // Two weeks #define GRAPHENE_DEFAULT_NETWORK_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_LIFETIME_REFERRER_PERCENT_OF_FEE (30*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_MAX_BULK_DISCOUNT_PERCENT (50*GRAPHENE_1_PERCENT) #define GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN ( GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(1000) ) #define GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MAX ( GRAPHENE_DEFAULT_BULK_DISCOUNT_THRESHOLD_MIN*int64_t(100) ) #define GRAPHENE_DEFAULT_CASHBACK_VESTING_PERIOD_SEC (60*60*24*365) ///< 1 year #define GRAPHENE_DEFAULT_CASHBACK_VESTING_THRESHOLD (GRAPHENE_BLOCKCHAIN_PRECISION*int64_t(100)) #define GRAPHENE_DEFAULT_BURN_PERCENT_OF_FEE (20*GRAPHENE_1_PERCENT) #define GRAPHENE_WITNESS_PAY_PERCENT_PRECISION (1000000000) #define GRAPHENE_DEFAULT_MAX_ASSERT_OPCODE 1 #define GRAPHENE_DEFAULT_FEE_LIQUIDATION_THRESHOLD GRAPHENE_BLOCKCHAIN_PRECISION * 100; #define GRAPHENE_DEFAULT_ACCOUNTS_PER_FEE_SCALE 1000 #define GRAPHENE_DEFAULT_ACCOUNT_FEE_SCALE_BITSHIFTS 4 #define GRAPHENE_MAX_WORKER_NAME_LENGTH 63 #define GRAPHENE_MAX_URL_LENGTH 127 // counter initialization values used to derive near and far future seeds for shuffling witnesses // we use the fractional bits of sqrt(2) in hex #define GRAPHENE_NEAR_SCHEDULE_CTR_IV ( (uint64_t( 0x6a09 ) << 0x30) \ | (uint64_t( 0xe667 ) << 0x20) \ | (uint64_t( 0xf3bc ) << 0x10) \ | (uint64_t( 0xc908 ) ) ) // and the fractional bits of sqrt(3) in hex #define GRAPHENE_FAR_SCHEDULE_CTR_IV ( (uint64_t( 0xbb67 ) << 0x30) \ | (uint64_t( 0xae85 ) << 0x20) \ | (uint64_t( 0x84ca ) << 0x10) \ | (uint64_t( 0xa73b ) ) ) /** * every second, the fraction of burned core asset which cycles is * GRAPHENE_CORE_ASSET_CYCLE_RATE / (1 << GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS) */ #define GRAPHENE_CORE_ASSET_CYCLE_RATE 17 #define GRAPHENE_CORE_ASSET_CYCLE_RATE_BITS 32 #define GRAPHENE_DEFAULT_WITNESS_PAY_PER_BLOCK (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t( 10) ) #define GRAPHENE_DEFAULT_WITNESS_PAY_VESTING_SECONDS (60*60*24) #define GRAPHENE_DEFAULT_WORKER_BUDGET_PER_DAY (GRAPHENE_BLOCKCHAIN_PRECISION * int64_t(500) * 1000 ) #define GRAPHENE_DEFAULT_MINIMUM_FEEDS 7 #define GRAPHENE_MAX_INTEREST_APR uint16_t( 10000 ) #define GRAPHENE_RECENTLY_MISSED_COUNT_INCREMENT 4 #define GRAPHENE_RECENTLY_MISSED_COUNT_DECREMENT 3 #define GRAPHENE_CURRENT_DB_VERSION "GPH2.4" #define GRAPHENE_IRREVERSIBLE_THRESHOLD (70 * GRAPHENE_1_PERCENT) /** * Reserved Account IDs with special meaning */ ///@{ /// Represents the current committee members, two-week review period #define GRAPHENE_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(0)) /// Represents the current witnesses #define GRAPHENE_WITNESS_ACCOUNT (graphene::chain::account_id_type(1)) /// Represents the current committee members #define GRAPHENE_RELAXED_COMMITTEE_ACCOUNT (graphene::chain::account_id_type(2)) /// Represents the canonical account with NO authority (nobody can access funds in null account) #define GRAPHENE_NULL_ACCOUNT (graphene::chain::account_id_type(3)) /// Represents the canonical account with WILDCARD authority (anybody can access funds in temp account) #define GRAPHENE_TEMP_ACCOUNT (graphene::chain::account_id_type(4)) /// Represents the canonical account for specifying you will vote directly (as opposed to a proxy) #define GRAPHENE_PROXY_TO_SELF_ACCOUNT (graphene::chain::account_id_type(5)) /// Sentinel value used in the scheduler. #define GRAPHENE_NULL_WITNESS (graphene::chain::witness_id_type(0)) ///@} <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> // MAIN FUNCTION int main() { std::cout << "Hello World"<<"\n"; } <commit_msg>Update game.m.cpp<commit_after>#include <stdio.h> #include <iostream> // MAIN FUNCTION int main() { std::cout << "Hello World"<<"\n"; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #ifndef CVMFS_SSL_H_ #define CVMFS_SSL_H_ #include "ssl.h" #include <string> #include <vector> #include "duplex_curl.h" #include "util/posix.h" #ifdef CVMFS_NAMESPACE_GUARD namespace CVMFS_NAMESPACE_GUARD { #endif unsigned int count_ssl_certificates(std::string directory) { if (!DirectoryExists(directory)) return 0; std::vector<std::string> dotpem = FindFilesBySuffix(directory, ".pem"); std::vector<std::string> dotcrt = FindFilesBySuffix(directory, ".crt"); return dotpem.size() + dotcrt.size(); } bool AddSSLCertificates(CURL *handle) { std::vector<std::string> cadirs; const char *cadir = getenv("X509_CERT_DIR"); if (cadir != NULL) { cadirs.push_back(std::string(cadir)); } cadirs.push_back("/etc/grid-security/certificates"); // most systems store the certificates here cadirs.push_back("/etc/ssl/certs/"); cadirs.push_back("/etc/pki/tls/certs/"); cadirs.push_back("/etc/ssl/"); cadirs.push_back("/etc/pki/tls/"); cadirs.push_back("/etc/pki/ca-trust/extracted/pem/"); cadirs.push_back("/etc/ssl/"); for (std::vector<std::string>::const_iterator cadir = cadirs.begin(); cadir != cadirs.end(); ++cadir) { if (count_ssl_certificates(*cadir) > 0) { CURLcode res = curl_easy_setopt(handle, CURLOPT_CAPATH, (*cadir).c_str()); if (CURLE_OK == res) { return true; } } } return false; } #ifdef CVMFS_NAMESPACE_GUARD } // namespace CVMFS_NAMESPACE_GUARD #endif #endif // CVMFS_SSL_H_ <commit_msg>add include for getenv<commit_after>/** * This file is part of the CernVM File System. */ #ifndef CVMFS_SSL_H_ #define CVMFS_SSL_H_ #include "ssl.h" #include <cstdlib> #include <string> #include <vector> #include "duplex_curl.h" #include "util/posix.h" #ifdef CVMFS_NAMESPACE_GUARD namespace CVMFS_NAMESPACE_GUARD { #endif unsigned int count_ssl_certificates(std::string directory) { if (!DirectoryExists(directory)) return 0; std::vector<std::string> dotpem = FindFilesBySuffix(directory, ".pem"); std::vector<std::string> dotcrt = FindFilesBySuffix(directory, ".crt"); return dotpem.size() + dotcrt.size(); } bool AddSSLCertificates(CURL *handle) { std::vector<std::string> cadirs; const char *cadir = getenv("X509_CERT_DIR"); if (cadir != NULL) { cadirs.push_back(std::string(cadir)); } cadirs.push_back("/etc/grid-security/certificates"); // most systems store the certificates here cadirs.push_back("/etc/ssl/certs/"); cadirs.push_back("/etc/pki/tls/certs/"); cadirs.push_back("/etc/ssl/"); cadirs.push_back("/etc/pki/tls/"); cadirs.push_back("/etc/pki/ca-trust/extracted/pem/"); cadirs.push_back("/etc/ssl/"); for (std::vector<std::string>::const_iterator cadir = cadirs.begin(); cadir != cadirs.end(); ++cadir) { if (count_ssl_certificates(*cadir) > 0) { CURLcode res = curl_easy_setopt(handle, CURLOPT_CAPATH, (*cadir).c_str()); if (CURLE_OK == res) { return true; } } } return false; } #ifdef CVMFS_NAMESPACE_GUARD } // namespace CVMFS_NAMESPACE_GUARD #endif #endif // CVMFS_SSL_H_ <|endoftext|>
<commit_before>/* Copyright c1997-2014 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ /** @file */ #include "vtypes.h" #include "vtypes_internal.h" #include "vstring.h" #include "vexception.h" #include <iostream> // for namespace std #include <assert.h> // Still to be determined is what constant value/type should be used here when // performing 64-bit VC++ compilation. Until then, the optional "/Wp64" option // in the 32-bit VC++ compiler ("Detect 64-bit Portability Issues") will emit // a warning #4312 so we want to disable that for this line of code. The warning // is because we are using a 32-bit constant 0xFEEEFEEE. Simply making it a // 64-bit constant is not portable either because that overflows in 32 bits. #ifdef VCOMPILER_MSVC #pragma warning(disable: 6001) // VS2010 static analysis is confused by our byte swapping functions. #pragma warning(disable: 4312) #endif const void* const VCPP_DEBUG_BAD_POINTER_VALUE = reinterpret_cast<const void*>(0xFEEEFEEE); #ifdef VCOMPILER_MSVC #pragma warning(default: 4312) #endif Vu16 vault::VbyteSwap16(Vu16 a16BitValue) { Vu16 original = a16BitValue; Vu16 swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[1]; swappedBytes[1] = originalBytes[0]; return swapped; } Vu32 vault::VbyteSwap32(Vu32 a32BitValue) { Vu32 original = a32BitValue; Vu32 swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[3]; swappedBytes[1] = originalBytes[2]; swappedBytes[2] = originalBytes[1]; swappedBytes[3] = originalBytes[0]; return swapped; } Vu64 vault::VbyteSwap64(Vu64 a64BitValue) { Vu64 original = a64BitValue; Vu64 swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[7]; swappedBytes[1] = originalBytes[6]; swappedBytes[2] = originalBytes[5]; swappedBytes[3] = originalBytes[4]; swappedBytes[4] = originalBytes[3]; swappedBytes[5] = originalBytes[2]; swappedBytes[6] = originalBytes[1]; swappedBytes[7] = originalBytes[0]; return swapped; } VFloat vault::VbyteSwapFloat(VFloat a32BitValue) { /* The key here is avoid allowing the compiler to do any conversion of the float to int, which would cause truncation of the fractional value. That's what happens if you use VbyteSwap32 because the float gets converted to an int. */ VFloat original = a32BitValue; VFloat swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[3]; swappedBytes[1] = originalBytes[2]; swappedBytes[2] = originalBytes[1]; swappedBytes[3] = originalBytes[0]; return swapped; } VDouble vault::VbyteSwapDouble(VDouble a64BitValue) { /* The key here is avoid allowing the compiler to do any conversion of the double to Vs64, which would cause truncation of the fractional value. That's what happens if you use VbyteSwap64 because the double gets converted to a Vs64. */ VDouble original = a64BitValue; VDouble swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[7]; swappedBytes[1] = originalBytes[6]; swappedBytes[2] = originalBytes[5]; swappedBytes[3] = originalBytes[4]; swappedBytes[4] = originalBytes[3]; swappedBytes[5] = originalBytes[2]; swappedBytes[6] = originalBytes[1]; swappedBytes[7] = originalBytes[0]; return swapped; } /* We don't conditionally compile this according to V_DEBUG_STATIC_INITIALIZATION_TRACE; rather, we always compile it, so that you have the option of turning it on per-file instead of all-or-nothing. We let the linker decide whether anyone calls it. */ int Vtrace(const char* fileName, int lineNumber) { std::cout << "Static Initialization @ " << fileName << ":" << lineNumber << std::endl; return 0; } <commit_msg>Work on #26. Change to push/pop pragma for VC++.<commit_after>/* Copyright c1997-2014 Trygve Isaacson. All rights reserved. This file is part of the Code Vault version 4.1 http://www.bombaydigital.com/ License: MIT. See LICENSE.md in the Vault top level directory. */ /** @file */ #include "vtypes.h" #include "vtypes_internal.h" #include "vstring.h" #include "vexception.h" #include <iostream> // for namespace std #include <assert.h> // Still to be determined is what constant value/type should be used here when // performing 64-bit VC++ compilation. Until then, the optional "/Wp64" option // in the 32-bit VC++ compiler ("Detect 64-bit Portability Issues") will emit // a warning #4312 so we want to disable that for this line of code. The warning // is because we are using a 32-bit constant 0xFEEEFEEE. Simply making it a // 64-bit constant is not portable either because that overflows in 32 bits. #ifdef VCOMPILER_MSVC #pragma warning(disable: 6001) // VS2010 static analysis is confused by our byte swapping functions. #pragma warning(push) #pragma warning(disable: 4312) #endif const void* const VCPP_DEBUG_BAD_POINTER_VALUE = reinterpret_cast<const void*>(0xFEEEFEEE); #ifdef VCOMPILER_MSVC #pragma warning(pop) #endif Vu16 vault::VbyteSwap16(Vu16 a16BitValue) { Vu16 original = a16BitValue; Vu16 swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[1]; swappedBytes[1] = originalBytes[0]; return swapped; } Vu32 vault::VbyteSwap32(Vu32 a32BitValue) { Vu32 original = a32BitValue; Vu32 swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[3]; swappedBytes[1] = originalBytes[2]; swappedBytes[2] = originalBytes[1]; swappedBytes[3] = originalBytes[0]; return swapped; } Vu64 vault::VbyteSwap64(Vu64 a64BitValue) { Vu64 original = a64BitValue; Vu64 swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[7]; swappedBytes[1] = originalBytes[6]; swappedBytes[2] = originalBytes[5]; swappedBytes[3] = originalBytes[4]; swappedBytes[4] = originalBytes[3]; swappedBytes[5] = originalBytes[2]; swappedBytes[6] = originalBytes[1]; swappedBytes[7] = originalBytes[0]; return swapped; } VFloat vault::VbyteSwapFloat(VFloat a32BitValue) { /* The key here is avoid allowing the compiler to do any conversion of the float to int, which would cause truncation of the fractional value. That's what happens if you use VbyteSwap32 because the float gets converted to an int. */ VFloat original = a32BitValue; VFloat swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[3]; swappedBytes[1] = originalBytes[2]; swappedBytes[2] = originalBytes[1]; swappedBytes[3] = originalBytes[0]; return swapped; } VDouble vault::VbyteSwapDouble(VDouble a64BitValue) { /* The key here is avoid allowing the compiler to do any conversion of the double to Vs64, which would cause truncation of the fractional value. That's what happens if you use VbyteSwap64 because the double gets converted to a Vs64. */ VDouble original = a64BitValue; VDouble swapped; Vu8* originalBytes = reinterpret_cast<Vu8*>(&original); Vu8* swappedBytes = reinterpret_cast<Vu8*>(&swapped); swappedBytes[0] = originalBytes[7]; swappedBytes[1] = originalBytes[6]; swappedBytes[2] = originalBytes[5]; swappedBytes[3] = originalBytes[4]; swappedBytes[4] = originalBytes[3]; swappedBytes[5] = originalBytes[2]; swappedBytes[6] = originalBytes[1]; swappedBytes[7] = originalBytes[0]; return swapped; } /* We don't conditionally compile this according to V_DEBUG_STATIC_INITIALIZATION_TRACE; rather, we always compile it, so that you have the option of turning it on per-file instead of all-or-nothing. We let the linker decide whether anyone calls it. */ int Vtrace(const char* fileName, int lineNumber) { std::cout << "Static Initialization @ " << fileName << ":" << lineNumber << std::endl; return 0; } <|endoftext|>
<commit_before>/* 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 "dlcl_lexer.hpp" #include "dlcl_utils.h" #include <cstring> #include <climits> #include <cstdio> namespace DarkLight { namespace CL{ void Token::toString(char *to) const{ const char *name = NULL; switch(m_type){ case Ident: if(!name) name = "Ident"; case String: if(!name) name = "String"; case GetIdent: if(!name) name = "Get"; case SetIdent: if(!name) name = "Set"; case IntIdent: if(!name) name = "IntDecl"; case StringIdent: if(!name) name = "StringDecl"; case BoolIdent: if(!name) name = "BoolDecl"; case FromIdent: if(!name) name = "From"; case CallIdent: if(!name) name = "Call"; strcpy(to, name); strcat(to, ": "); strncat(to, m_value.ident, m_length); return; case Number: strcpy(to, "Number: "); DLCL_Utils_NumberToString(to, m_value.number); return; #define CASE_(X_) case X_: strcpy(to, #X_); return CASE_(TrueLiteral); CASE_(FalseLiteral); CASE_(Return); CASE_(OpenParen); CASE_(CloseParen); CASE_(Colon); CASE_(Dot); CASE_(BeginArgs); CASE_(EndArgs); case Oper: switch(m_value.oper){ CASE_(Plus); CASE_(Minus); CASE_(Multiply); CASE_(Divide); CASE_(LessThan); CASE_(NotLessThan); CASE_(GreaterThan); CASE_(NotGreaterThan); CASE_(Equal); CASE_(NotEqual); CASE_(And); CASE_(Or); CASE_(Xor); #undef CASE_ } } } Lexer::Lexer(){ } static bool is_whitespace(char c){ return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '%'; } static bool is_digit(char c){ return c == '0' || (c >= '1' && c <= '9'); } static bool is_ident(char c){ return (c>='a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || is_digit(c); } static bool get_op(const char *&str, unsigned &len, Operator &oper){ switch(*str){ #define CASE_(CHAR_, OPER_, INC_)\ case CHAR_: oper = OPER_; len -= INC_; str += INC_; return true #define CASE_1(A_, B_) CASE_(A_, B_, 1) #define CASE_2(A_, B_) CASE_(A_, B_, 2) CASE_1('+', Plus); CASE_1('-', Minus); CASE_1('*', Multiply); CASE_1('/', Divide); CASE_1('<', LessThan); CASE_1('>', GreaterThan); CASE_1('=', Equal); CASE_1('&', And); CASE_1('|', Or); CASE_1('^', Xor); case '!': if(len == 1) return false; switch(str[1]){ CASE_2('<', NotLessThan); CASE_2('>', NotGreaterThan); CASE_2('=', NotEqual); } } return false; #undef CASE_ #undef CASE_1 #undef CASE_2 } static unsigned parseIdentifier(const char *&str, unsigned &len, char *to, unsigned max = 79){ unsigned str_len = 0; do{ to[0] = *str; to++; str++; len--; str_len++; }while(len && is_ident(*str) && str_len < max); to[str_len] = '\0'; return str_len; } static void skipWhitespace(const char *&str, unsigned &len, unsigned &line){ while(len && is_whitespace(*str)){ // Remove comments if(*str == '%'){ do{ str++; len--; }while(len && *str != '\n'); continue; } if(*str == '\n') line++; str++; len--; } } bool Lexer::lex(const char *str, unsigned len){ clear(); // char *string_cache[0x100]; // unsigned num_cached_strings = 0; const char *const start = str; unsigned line = 0u; while(len){ if(m_num_tokens >= s_max_num_tokens){ sprintf(m_data, "Out of token memory at line %i", line); return false; } if(is_whitespace(*str)){ skipWhitespace(str, len, line); } else if(is_digit(*str) || *str == '-' || *str == '+'){ const bool negate = *str=='-'; if(*str == '+' || *str == '-'){ str++; len--; if(!len) continue; } const unsigned max = UINT_MAX / 11u; unsigned u = 0; do{ u *= 10; u += *str - '0'; if(u > max){ sprintf(m_data, "Integer literal %u too large (max is %u) on line %i", u, max, line); return false; } str++; }while(--len && is_digit(*str)); const int n = u; addToken(Token::Number, static_cast<float>(negate ? -n : n)); } else if(is_ident(*str)){ char id[80]; unsigned str_len = 0u; str_len = parseIdentifier(str, len, id); bool another_ident = false, swallow_colon = false; Token::Type which = (Token::Type)99; if(str_len == 3 && *id == 'g' && memcmp(id, "get", 3)==0){ which = Token::GetIdent; another_ident = true; } else if(*id == 's'){ if(str_len == 3 && memcmp(id, "set", 3)==0){ which = Token::SetIdent; another_ident = true; } else if(str_len == 6 && memcmp(id, "string", 6)==0){ which = Token::StringIdent; swallow_colon = true; another_ident = true; } } else if(str_len == 4 && *id == 'c' && memcmp(id, "call", 4)==0){ which = Token::CallIdent; another_ident = true; } else if(str_len == 3 && *id == 'i' && memcmp(id, "int", 3) == 0){ which = Token::IntIdent; swallow_colon = another_ident = true; } else if(str_len == 4 && *id == 'b' && memcmp(id, "bool", 4) == 0){ which = Token::BoolIdent; another_ident = true; swallow_colon = true; } else if(str_len == 4 && *id == 't' && memcmp(id, "true", 4) == 0){ addTokenMod(Token::TrueLiteral); continue; } else if(str_len == 5 && *id == 'f' && memcmp(id, "false", 5) == 0){ addTokenMod(Token::FalseLiteral); continue; } if(another_ident){ skipWhitespace(str, len, line); const unsigned max_size = s_max_lexer_arena_size - m_string_len; char *const str_data = m_string_data + m_string_len; str_len = parseIdentifier(str, len, str_data, max_size); m_string_len += str_len; if(m_string_len == s_max_lexer_arena_size){ sprintf(m_data, "Out of lexer memory at line %i", line); return false; } else{ addToken(which, str_data, str_len); } } else{ if(s_max_lexer_arena_size - m_string_len < str_len){ sprintf(m_data, "Out of lexer memory at line %i", line); return false; } else{ char *const str_data = m_string_data + m_string_len; memcpy(str_data, id, str_len); addToken(Token::Ident, str_data, str_len); } } if(swallow_colon && len && *str == ':'){ str++; len--; skipWhitespace(str, len, line); } } else if(*str == '"'){ str++; len--; unsigned str_len = 0; char *const str_data = m_string_data + m_string_len; while(str[str_len] != '"' && len && m_string_len + str_len < s_max_lexer_arena_size){ m_string_data[m_string_len + str_len] = str[str_len]; if(*str == '\n') line++; str_len++; len--; } str += str_len; m_string_len += str_len; addToken(Token::String, str_data, str_len); if(len && *str == '"'){ str++; len--; } } #define SINGLE_CHAR_TOKEN(ENUM_, CHAR_)\ else if(*str == CHAR_){\ addTokenMod(Token:: ENUM_);\ str++;\ len--;\ } SINGLE_CHAR_TOKEN(Colon, ':') SINGLE_CHAR_TOKEN(Dot, '.') SINGLE_CHAR_TOKEN(OpenParen, '(') SINGLE_CHAR_TOKEN(CloseParen, ')') SINGLE_CHAR_TOKEN(BeginArgs, '[') SINGLE_CHAR_TOKEN(EndArgs, ']') #undef SINGLE_CHAR_TOKEN #define SINGLE_CHAR_TOKEN_OPER(ENUM_, CHAR_)\ else if(*str == CHAR_){\ addToken(ENUM_);\ str++;\ len--;\ } SINGLE_CHAR_TOKEN_OPER(GreaterThan, '>') SINGLE_CHAR_TOKEN_OPER(LessThan, '<') SINGLE_CHAR_TOKEN_OPER(Equal, '=') else if(*str == '!'){ str++; len--; if(!len){ sprintf(m_data, "Unterminated negation following pling (!) at line %i: '%c'", line, *str); return false; } SINGLE_CHAR_TOKEN_OPER(NotGreaterThan, '>') SINGLE_CHAR_TOKEN_OPER(NotLessThan, '<') SINGLE_CHAR_TOKEN_OPER(NotEqual, '=') else{ sprintf(m_data, "Invalid character following pling (!) at line %i: '%c'", line, *str); return false; } } #undef SINGLE_CHAR_TOKEN_OPER else{ Operator oper; if(get_op(str, len, oper)){ addToken(oper); } else{ if(str - start > 2 && len > 2) sprintf(m_data, "Invalid character at line %i: (%i) %c%c[%c]%c%c'", line, *str, str[-2], str[-1], str[0], str[1], str[2]); else sprintf(m_data, "Invalid character at line %i: (%i) %c'", line, *str, *str); return false; } } } return true; } } // namespace CL } // namespace DarkLight <commit_msg>Fix greedy lexing of unary +/-<commit_after>/* 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 "dlcl_lexer.hpp" #include "dlcl_utils.h" #include <cstring> #include <climits> #include <cstdio> namespace DarkLight { namespace CL{ void Token::toString(char *to) const{ const char *name = NULL; switch(m_type){ case Ident: if(!name) name = "Ident"; case String: if(!name) name = "String"; case GetIdent: if(!name) name = "Get"; case SetIdent: if(!name) name = "Set"; case IntIdent: if(!name) name = "IntDecl"; case StringIdent: if(!name) name = "StringDecl"; case BoolIdent: if(!name) name = "BoolDecl"; case FromIdent: if(!name) name = "From"; case CallIdent: if(!name) name = "Call"; strcpy(to, name); strcat(to, ": "); strncat(to, m_value.ident, m_length); return; case Number: strcpy(to, "Number: "); DLCL_Utils_NumberToString(to, m_value.number); return; #define CASE_(X_) case X_: strcpy(to, #X_); return CASE_(TrueLiteral); CASE_(FalseLiteral); CASE_(Return); CASE_(OpenParen); CASE_(CloseParen); CASE_(Colon); CASE_(Dot); CASE_(BeginArgs); CASE_(EndArgs); case Oper: switch(m_value.oper){ CASE_(Plus); CASE_(Minus); CASE_(Multiply); CASE_(Divide); CASE_(LessThan); CASE_(NotLessThan); CASE_(GreaterThan); CASE_(NotGreaterThan); CASE_(Equal); CASE_(NotEqual); CASE_(And); CASE_(Or); CASE_(Xor); #undef CASE_ } } } Lexer::Lexer(){ } static bool is_whitespace(char c){ return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == '%'; } static bool is_digit(char c){ return c == '0' || (c >= '1' && c <= '9'); } static bool is_ident(char c){ return (c>='a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || is_digit(c); } static bool get_op(const char *&str, unsigned &len, Operator &oper){ switch(*str){ #define CASE_(CHAR_, OPER_, INC_)\ case CHAR_: oper = OPER_; len -= INC_; str += INC_; return true #define CASE_1(A_, B_) CASE_(A_, B_, 1) #define CASE_2(A_, B_) CASE_(A_, B_, 2) CASE_1('+', Plus); CASE_1('-', Minus); CASE_1('*', Multiply); CASE_1('/', Divide); CASE_1('<', LessThan); CASE_1('>', GreaterThan); CASE_1('=', Equal); CASE_1('&', And); CASE_1('|', Or); CASE_1('^', Xor); case '!': if(len == 1) return false; switch(str[1]){ CASE_2('<', NotLessThan); CASE_2('>', NotGreaterThan); CASE_2('=', NotEqual); } } return false; #undef CASE_ #undef CASE_1 #undef CASE_2 } static unsigned parseIdentifier(const char *&str, unsigned &len, char *to, unsigned max = 79){ unsigned str_len = 0; do{ to[0] = *str; to++; str++; len--; str_len++; }while(len && is_ident(*str) && str_len < max); to[str_len] = '\0'; return str_len; } static void skipWhitespace(const char *&str, unsigned &len, unsigned &line){ while(len && is_whitespace(*str)){ // Remove comments if(*str == '%'){ do{ str++; len--; }while(len && *str != '\n'); continue; } if(*str == '\n') line++; str++; len--; } } bool Lexer::lex(const char *str, unsigned len){ clear(); // char *string_cache[0x100]; // unsigned num_cached_strings = 0; const char *const start = str; unsigned line = 0u; while(len){ if(m_num_tokens >= s_max_num_tokens){ sprintf(m_data, "Out of token memory at line %i", line); return false; } if(is_whitespace(*str)){ skipWhitespace(str, len, line); } else if(is_digit(*str)){ const unsigned max = UINT_MAX / 11u; unsigned u = 0; do{ u *= 10; u += *str - '0'; if(u > max){ sprintf(m_data, "Integer literal %u too large (max is %u) on line %i", u, max, line); return false; } str++; }while(--len && is_digit(*str)); const int n = u; addToken(Token::Number, static_cast<float>(n)); } else if(is_ident(*str)){ char id[80]; unsigned str_len = 0u; str_len = parseIdentifier(str, len, id); bool another_ident = false, swallow_colon = false; Token::Type which = (Token::Type)99; if(str_len == 3 && *id == 'g' && memcmp(id, "get", 3)==0){ which = Token::GetIdent; another_ident = true; } else if(*id == 's'){ if(str_len == 3 && memcmp(id, "set", 3)==0){ which = Token::SetIdent; another_ident = true; } else if(str_len == 6 && memcmp(id, "string", 6)==0){ which = Token::StringIdent; swallow_colon = true; another_ident = true; } } else if(str_len == 4 && *id == 'c' && memcmp(id, "call", 4)==0){ which = Token::CallIdent; another_ident = true; } else if(str_len == 3 && *id == 'i' && memcmp(id, "int", 3) == 0){ which = Token::IntIdent; swallow_colon = another_ident = true; } else if(str_len == 4 && *id == 'b' && memcmp(id, "bool", 4) == 0){ which = Token::BoolIdent; another_ident = true; swallow_colon = true; } else if(str_len == 4 && *id == 't' && memcmp(id, "true", 4) == 0){ addTokenMod(Token::TrueLiteral); continue; } else if(str_len == 5 && *id == 'f' && memcmp(id, "false", 5) == 0){ addTokenMod(Token::FalseLiteral); continue; } if(another_ident){ skipWhitespace(str, len, line); const unsigned max_size = s_max_lexer_arena_size - m_string_len; char *const str_data = m_string_data + m_string_len; str_len = parseIdentifier(str, len, str_data, max_size); m_string_len += str_len; if(m_string_len == s_max_lexer_arena_size){ sprintf(m_data, "Out of lexer memory at line %i", line); return false; } else{ addToken(which, str_data, str_len); } } else{ if(s_max_lexer_arena_size - m_string_len < str_len){ sprintf(m_data, "Out of lexer memory at line %i", line); return false; } else{ char *const str_data = m_string_data + m_string_len; memcpy(str_data, id, str_len); addToken(Token::Ident, str_data, str_len); } } if(swallow_colon && len && *str == ':'){ str++; len--; skipWhitespace(str, len, line); } } else if(*str == '"'){ str++; len--; unsigned str_len = 0; char *const str_data = m_string_data + m_string_len; while(str[str_len] != '"' && len && m_string_len + str_len < s_max_lexer_arena_size){ m_string_data[m_string_len + str_len] = str[str_len]; if(*str == '\n') line++; str_len++; len--; } str += str_len; m_string_len += str_len; addToken(Token::String, str_data, str_len); if(len && *str == '"'){ str++; len--; } } #define SINGLE_CHAR_TOKEN(ENUM_, CHAR_)\ else if(*str == CHAR_){\ addTokenMod(Token:: ENUM_);\ str++;\ len--;\ } SINGLE_CHAR_TOKEN(Colon, ':') SINGLE_CHAR_TOKEN(Dot, '.') SINGLE_CHAR_TOKEN(OpenParen, '(') SINGLE_CHAR_TOKEN(CloseParen, ')') SINGLE_CHAR_TOKEN(BeginArgs, '[') SINGLE_CHAR_TOKEN(EndArgs, ']') #undef SINGLE_CHAR_TOKEN #define SINGLE_CHAR_TOKEN_OPER(ENUM_, CHAR_)\ else if(*str == CHAR_){\ addToken(ENUM_);\ str++;\ len--;\ } SINGLE_CHAR_TOKEN_OPER(GreaterThan, '>') SINGLE_CHAR_TOKEN_OPER(LessThan, '<') SINGLE_CHAR_TOKEN_OPER(Equal, '=') else if(*str == '!'){ str++; len--; if(!len){ sprintf(m_data, "Unterminated negation following pling (!) at line %i: '%c'", line, *str); return false; } SINGLE_CHAR_TOKEN_OPER(NotGreaterThan, '>') SINGLE_CHAR_TOKEN_OPER(NotLessThan, '<') SINGLE_CHAR_TOKEN_OPER(NotEqual, '=') else{ sprintf(m_data, "Invalid character following pling (!) at line %i: '%c'", line, *str); return false; } } #undef SINGLE_CHAR_TOKEN_OPER else{ Operator oper; if(get_op(str, len, oper)){ addToken(oper); } else{ if(str - start > 2 && len > 2) sprintf(m_data, "Invalid character at line %i: (%i) %c%c[%c]%c%c'", line, *str, str[-2], str[-1], str[0], str[1], str[2]); else sprintf(m_data, "Invalid character at line %i: (%i) %c'", line, *str, *str); return false; } } } return true; } } // namespace CL } // namespace DarkLight <|endoftext|>
<commit_before><commit_msg>loplugin:deletedspecial<commit_after><|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief 6×12フォント・クラス Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> namespace graphics { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief フォント・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class font6x12 { static const uint8_t bitmap_[]; static const int8_t width_tbl_[]; public: //-----------------------------------------------------------------// /*! @brief 文字の横幅 */ //-----------------------------------------------------------------// static const int8_t width = 6; //-----------------------------------------------------------------// /*! @brief 文字の高さ */ //-----------------------------------------------------------------// static const int8_t height = 12; //-----------------------------------------------------------------// /*! @brief 文字のビットマップを取得 @param[in] code 文字コード @return 文字のビットマップ */ //-----------------------------------------------------------------// static const uint8_t* get(uint8_t code) { return &bitmap_[(static_cast<uint16_t>(code) << 3) + static_cast<uint16_t>(code)]; } //-----------------------------------------------------------------// /*! @brief プロポーショナル・フォント幅を取得 @param[in] code 文字コード @return 文字幅 */ //-----------------------------------------------------------------// static int8_t get_width(uint8_t code) { if(code < 32 || code >= 128) return width; else return width_tbl_[code - 32]; } }; } <commit_msg>update kerning<commit_after>#pragma once //=====================================================================// /*! @file @brief 6×12フォント・クラス Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> namespace graphics { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief フォント・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class font6x12 { static const uint8_t bitmap_[]; static const int8_t width_tbl_[]; public: //-----------------------------------------------------------------// /*! @brief 文字の横幅 */ //-----------------------------------------------------------------// static const int8_t width = 6; //-----------------------------------------------------------------// /*! @brief 文字の高さ */ //-----------------------------------------------------------------// static const int8_t height = 12; //-----------------------------------------------------------------// /*! @brief 文字のビットマップを取得 @param[in] code 文字コード @return 文字のビットマップ */ //-----------------------------------------------------------------// static const uint8_t* get(uint8_t code) { return &bitmap_[(static_cast<uint16_t>(code) << 3) + static_cast<uint16_t>(code)]; } //-----------------------------------------------------------------// /*! @brief プロポーショナル・フォント幅を取得 @param[in] code 文字コード @return 文字幅 */ //-----------------------------------------------------------------// static int8_t get_width(uint8_t code) { if(code < 32 || code >= 128) return width; else return width_tbl_[code - 32]; } //-----------------------------------------------------------------// /*! @brief カーニングを取得 @param[in] code 文字コード @return 文字幅 */ //-----------------------------------------------------------------// static int8_t get_kern(uint8_t code) { switch(code) { case '!': case '|': case 'i': case 'l': return -1; } return 0; } }; } <|endoftext|>
<commit_before>#include "tile.h" #include "network.h" #include "network_model.h" #include "network_types.h" #include "memory_manager.h" #include "main_core.h" #include "simulator.h" #include "log.h" #include "tile_energy_monitor.h" Tile::Tile(tile_id_t id) : _id(id) , _memory_manager(NULL) { LOG_PRINT("Tile ctor for (%i)", _id); _network = new Network(this); _core = new MainCore(this); if (Config::getSingleton()->isSimulatingSharedMemory()) _memory_manager = MemoryManager::createMMU(Sim()->getCfg()->getString("caching_protocol/type"), this); if (Config::getSingleton()->getEnablePowerModeling()) _tile_energy_monitor = new TileEnergyMonitor(this); } Tile::~Tile() { if (_memory_manager) delete _memory_manager; delete _core; delete _network; if (_tile_energy_monitor) delete _tile_energy_monitor; } void Tile::outputSummary(ostream &os) { LOG_PRINT("Core Summary"); _core->outputSummary(os); LOG_PRINT("Network Summary"); _network->outputSummary(os); LOG_PRINT("Memory Subsystem Summary"); if (_memory_manager) _memory_manager->outputSummary(os); LOG_PRINT("Tile Energy Monitor Summary"); if (_tile_energy_monitor) _tile_energy_monitor->outputSummary(os); } void Tile::enableModels() { LOG_PRINT("enableModels(%i) start", _id); _network->enableModels(); _core->enableModels(); if (_memory_manager) _memory_manager->enableModels(); LOG_PRINT("enableModels(%i) end", _id); } void Tile::disableModels() { LOG_PRINT("disableModels(%i) start", _id); _network->disableModels(); _core->disableModels(); if (_memory_manager) _memory_manager->disableModels(); LOG_PRINT("disableModels(%i) end", _id); } void Tile::updateInternalVariablesOnFrequencyChange(volatile float frequency) { _core->updateInternalVariablesOnFrequencyChange(frequency); } <commit_msg>[power monitor] Fixed a small bug that caused an error when power modeling was not enabled.<commit_after>#include "tile.h" #include "network.h" #include "network_model.h" #include "network_types.h" #include "memory_manager.h" #include "main_core.h" #include "simulator.h" #include "log.h" #include "tile_energy_monitor.h" Tile::Tile(tile_id_t id) : _id(id) , _memory_manager(NULL) , _tile_energy_monitor(NULL) { LOG_PRINT("Tile ctor for (%i)", _id); _network = new Network(this); _core = new MainCore(this); if (Config::getSingleton()->isSimulatingSharedMemory()) _memory_manager = MemoryManager::createMMU(Sim()->getCfg()->getString("caching_protocol/type"), this); if (Config::getSingleton()->getEnablePowerModeling()) _tile_energy_monitor = new TileEnergyMonitor(this); } Tile::~Tile() { if (_memory_manager) delete _memory_manager; delete _core; delete _network; if (_tile_energy_monitor) delete _tile_energy_monitor; } void Tile::outputSummary(ostream &os) { LOG_PRINT("Core Summary"); _core->outputSummary(os); LOG_PRINT("Network Summary"); _network->outputSummary(os); LOG_PRINT("Memory Subsystem Summary"); if (_memory_manager) _memory_manager->outputSummary(os); LOG_PRINT("Tile Energy Monitor Summary"); if (_tile_energy_monitor) _tile_energy_monitor->outputSummary(os); } void Tile::enableModels() { LOG_PRINT("enableModels(%i) start", _id); _network->enableModels(); _core->enableModels(); if (_memory_manager) _memory_manager->enableModels(); LOG_PRINT("enableModels(%i) end", _id); } void Tile::disableModels() { LOG_PRINT("disableModels(%i) start", _id); _network->disableModels(); _core->disableModels(); if (_memory_manager) _memory_manager->disableModels(); LOG_PRINT("disableModels(%i) end", _id); } void Tile::updateInternalVariablesOnFrequencyChange(volatile float frequency) { _core->updateInternalVariablesOnFrequencyChange(frequency); } <|endoftext|>
<commit_before> #ifndef __CONCURRENCY_PMAP_HPP__ #define __CONCURRENCY_PMAP_HPP__ #include "errors.hpp" #include <boost/bind.hpp> #include "arch/runtime/runtime.hpp" #include "concurrency/cond_var.hpp" #include "utils.hpp" template<typename callable_t, typename value_t> void pmap_runner_one_arg(value_t i, const callable_t *c, int *outstanding, cond_t *to_signal) { (*c)(i); (*outstanding)--; if (*outstanding == 0) { to_signal->pulse(); } } template<typename callable_t, typename value_t> void spawn_pmap_runner_one_arg(value_t i, const callable_t *c, int *outstanding, cond_t *to_signal) { coro_t::spawn_now(boost::bind(&pmap_runner_one_arg<callable_t, value_t>, i, c, outstanding, to_signal)); } template<typename callable_t> void pmap(int count, const callable_t &c) { if (count == 0) { return; } if (count == 1) { c(0); return; } cond_t cond; int outstanding = count - 1; for (int i = 0; i < count - 1; i++) { coro_t::spawn_now(boost::bind(&pmap_runner_one_arg<callable_t, int>, i, &c, &outstanding, &cond)); } c(count - 1); cond.wait(); } // TODO: Passing end by reference seems very questionable to me. template<typename callable_t, typename iterator_t> void pmap(iterator_t start, const iterator_t &end, const callable_t &c) { cond_t cond; int outstanding = 1; while (start != end) { outstanding++; spawn_pmap_runner_one_arg(*start, &c, &outstanding, &cond); start++; } outstanding--; if (outstanding) { cond.wait(); } } template<typename callable_t, typename value1_t, typename value2_t> void pmap_runner_two_arg(value1_t i, value2_t i2, const callable_t *c, int *outstanding, cond_t *to_signal) { (*c)(i, i2); (*outstanding)--; if (*outstanding == 0) { to_signal->pulse(); } } template<typename callable_t, typename value1_t, typename value2_t> void spawn_pmap_runner_two_arg(value1_t i, value2_t i2, const callable_t *c, int *outstanding, cond_t *to_signal) { coro_t::spawn_now(boost::bind(&pmap_runner_two_arg<callable_t, value1_t, value2_t>, i, i2, c, outstanding, to_signal)); } template<typename callable_t, typename iterator_t> void pimap(iterator_t start, const iterator_t &end, const callable_t &c) { cond_t cond; int outstanding = 1; int i = 0; while (start != end) { outstanding++; spawn_pmap_runner_two_arg(*start, i, &c, &outstanding, &cond); i++; start++; } outstanding--; if (outstanding) { cond.wait(); } } #endif /* __CONCURRENCY_PMAP_HPP__ */ <commit_msg>Replaced template<typename wtf> with template <class wtf> because No.<commit_after> #ifndef __CONCURRENCY_PMAP_HPP__ #define __CONCURRENCY_PMAP_HPP__ #include "errors.hpp" #include <boost/bind.hpp> #include "arch/runtime/runtime.hpp" #include "concurrency/cond_var.hpp" #include "utils.hpp" template <class callable_t, class value_t> void pmap_runner_one_arg(value_t i, const callable_t *c, int *outstanding, cond_t *to_signal) { (*c)(i); (*outstanding)--; if (*outstanding == 0) { to_signal->pulse(); } } template <class callable_t, class value_t> void spawn_pmap_runner_one_arg(value_t i, const callable_t *c, int *outstanding, cond_t *to_signal) { coro_t::spawn_now(boost::bind(&pmap_runner_one_arg<callable_t, value_t>, i, c, outstanding, to_signal)); } template <class callable_t> void pmap(int count, const callable_t &c) { if (count == 0) { return; } if (count == 1) { c(0); return; } cond_t cond; int outstanding = count - 1; for (int i = 0; i < count - 1; i++) { coro_t::spawn_now(boost::bind(&pmap_runner_one_arg<callable_t, int>, i, &c, &outstanding, &cond)); } c(count - 1); cond.wait(); } // TODO: Passing end by reference seems very questionable to me. template <class callable_t, class iterator_t> void pmap(iterator_t start, const iterator_t &end, const callable_t &c) { cond_t cond; int outstanding = 1; while (start != end) { outstanding++; spawn_pmap_runner_one_arg(*start, &c, &outstanding, &cond); start++; } outstanding--; if (outstanding) { cond.wait(); } } template <class callable_t, class value1_t, class value2_t> void pmap_runner_two_arg(value1_t i, value2_t i2, const callable_t *c, int *outstanding, cond_t *to_signal) { (*c)(i, i2); (*outstanding)--; if (*outstanding == 0) { to_signal->pulse(); } } template <class callable_t, class value1_t, class value2_t> void spawn_pmap_runner_two_arg(value1_t i, value2_t i2, const callable_t *c, int *outstanding, cond_t *to_signal) { coro_t::spawn_now(boost::bind(&pmap_runner_two_arg<callable_t, value1_t, value2_t>, i, i2, c, outstanding, to_signal)); } template <class callable_t, class iterator_t> void pimap(iterator_t start, const iterator_t &end, const callable_t &c) { cond_t cond; int outstanding = 1; int i = 0; while (start != end) { outstanding++; spawn_pmap_runner_two_arg(*start, i, &c, &outstanding, &cond); i++; start++; } outstanding--; if (outstanding) { cond.wait(); } } #endif /* __CONCURRENCY_PMAP_HPP__ */ <|endoftext|>
<commit_before>// Local-Hyperion includes #include "LedDevicePhilipsHue.h" // jsoncpp includes #include <json/json.h> // qt includes #include <QtCore/qmath.h> #include <QUrl> #include <QHttpRequestHeader> #include <QEventLoop> #include <set> bool operator ==(CiColor p1, CiColor p2) { return (p1.x == p2.x) && (p1.y == p2.y) && (p1.bri == p2.bri); } bool operator !=(CiColor p1, CiColor p2) { return !(p1 == p2); } PhilipsHueLamp::PhilipsHueLamp(unsigned int id, QString originalState, QString modelId) : id(id), originalState(originalState) { // Hue system model ids. const std::set<QString> HUE_BULBS_MODEL_IDS = { "LCT001", "LCT002", "LCT003" }; const std::set<QString> LIVING_COLORS_MODEL_IDS = { "LLC001", "LLC005", "LLC006", "LLC007", "LLC011", "LLC012", "LLC013", "LST001" }; // Find id in the sets and set the appropiate color space. if (HUE_BULBS_MODEL_IDS.find(modelId) != HUE_BULBS_MODEL_IDS.end()) { colorSpace.red = {0.675f, 0.322f}; colorSpace.green = {0.4091f, 0.518f}; colorSpace.blue = {0.167f, 0.04f}; } else if (LIVING_COLORS_MODEL_IDS.find(modelId) != LIVING_COLORS_MODEL_IDS.end()) { colorSpace.red = {0.703f, 0.296f}; colorSpace.green = {0.214f, 0.709f}; colorSpace.blue = {0.139f, 0.081f}; } else { colorSpace.red = {1.0f, 0.0f}; colorSpace.green = {0.0f, 1.0f}; colorSpace.blue = {0.0f, 0.0f}; } // Initialize black color. black = rgbToCiColor(0.0f, 0.0f, 0.0f); // Initialize color with black color = {black.x, black.y, black.bri}; } float PhilipsHueLamp::crossProduct(CiColor p1, CiColor p2) { return p1.x * p2.y - p1.y * p2.x; } bool PhilipsHueLamp::isPointInLampsReach(CiColor p) { CiColor v1 = { colorSpace.green.x - colorSpace.red.x, colorSpace.green.y - colorSpace.red.y }; CiColor v2 = { colorSpace.blue.x - colorSpace.red.x, colorSpace.blue.y - colorSpace.red.y }; CiColor q = { p.x - colorSpace.red.x, p.y - colorSpace.red.y }; float s = crossProduct(q, v2) / crossProduct(v1, v2); float t = crossProduct(v1, q) / crossProduct(v1, v2); if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f)) { return true; } return false; } CiColor PhilipsHueLamp::getClosestPointToPoint(CiColor a, CiColor b, CiColor p) { CiColor AP = { p.x - a.x, p.y - a.y }; CiColor AB = { b.x - a.x, b.y - a.y }; float ab2 = AB.x * AB.x + AB.y * AB.y; float ap_ab = AP.x * AB.x + AP.y * AB.y; float t = ap_ab / ab2; if (t < 0.0f) { t = 0.0f; } else if (t > 1.0f) { t = 1.0f; } return {a.x + AB.x * t, a.y + AB.y * t}; } float PhilipsHueLamp::getDistanceBetweenTwoPoints(CiColor p1, CiColor p2) { // Horizontal difference. float dx = p1.x - p2.x; // Vertical difference. float dy = p1.y - p2.y; // Absolute value. return sqrt(dx * dx + dy * dy); } CiColor PhilipsHueLamp::rgbToCiColor(float red, float green, float blue) { // Apply gamma correction. float r = (red > 0.04045f) ? powf((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f); float g = (green > 0.04045f) ? powf((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f); float b = (blue > 0.04045f) ? powf((blue + 0.055f) / (1.0f + 0.055f), 2.4f) : (blue / 12.92f); // Convert to XYZ space. float X = r * 0.649926f + g * 0.103455f + b * 0.197109f; float Y = r * 0.234327f + g * 0.743075f + b * 0.022598f; float Z = r * 0.0000000f + g * 0.053077f + b * 1.035763f; // Convert to x,y space. float cx = X / (X + Y + Z); float cy = Y / (X + Y + Z); if (isnan(cx)) { cx = 0.0f; } if (isnan(cy)) { cy = 0.0f; } // Brightness is simply Y in the XYZ space. CiColor xy = { cx, cy, Y }; // Check if the given XY value is within the color reach of our lamps. if (!isPointInLampsReach(xy)) { // It seems the color is out of reach let's find the closes color we can produce with our lamp and send this XY value out. CiColor pAB = getClosestPointToPoint(colorSpace.red, colorSpace.green, xy); CiColor pAC = getClosestPointToPoint(colorSpace.blue, colorSpace.red, xy); CiColor pBC = getClosestPointToPoint(colorSpace.green, colorSpace.blue, xy); // Get the distances per point and see which point is closer to our Point. float dAB = getDistanceBetweenTwoPoints(xy, pAB); float dAC = getDistanceBetweenTwoPoints(xy, pAC); float dBC = getDistanceBetweenTwoPoints(xy, pBC); float lowest = dAB; CiColor closestPoint = pAB; if (dAC < lowest) { lowest = dAC; closestPoint = pAC; } if (dBC < lowest) { lowest = dBC; closestPoint = pBC; } // Change the xy value to a value which is within the reach of the lamp. xy.x = closestPoint.x; xy.y = closestPoint.y; } return xy; } LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output, const std::string& username, bool switchOffOnBlack, int transitiontime) : host(output.c_str()), username(username.c_str()), switchOffOnBlack(switchOffOnBlack), transitiontime( transitiontime) { http = new QHttp(host); timer.setInterval(3000); timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(restoreStates())); } LedDevicePhilipsHue::~LedDevicePhilipsHue() { delete http; } int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) { // Save light states if not done before. if (!areStatesSaved()) { saveStates((unsigned int) ledValues.size()); switchOn((unsigned int) ledValues.size()); } // If there are less states saved than colors given, then maybe something went wrong before. if (lamps.size() != ledValues.size()) { restoreStates(); return 0; } // Iterate through colors and set light states. unsigned int idx = 0; for (const ColorRgb& color : ledValues) { // Get lamp. PhilipsHueLamp& lamp = lamps.at(idx); // Scale colors from [0, 255] to [0, 1] and convert to xy space. CiColor xy = lamp.rgbToCiColor(color.red / 255.0f, color.green / 255.0f, color.blue / 255.0f); // Write color if color has been changed. if (xy != lamp.color) { // Switch on if the lamp has been previously switched off. if (switchOffOnBlack && lamp.color == lamp.black) { put(getStateRoute(lamp.id), QString("{\"on\": true}")); } // Send adjust color and brightness command in JSON format. // We have to set the transition time each time. put(getStateRoute(lamp.id), QString("{\"xy\": [%1, %2], \"bri\": %3, \"transitiontime\": %4}").arg(xy.x).arg(xy.y).arg( qRound(xy.bri * 255.0f)).arg(transitiontime)); } // Switch lamp off if switchOffOnBlack is enabled and the lamp is currently on. if (switchOffOnBlack) { // From black to a color. if (lamp.color == lamp.black && xy != lamp.black) { put(getStateRoute(lamp.id), QString("{\"on\": true}")); } // From a color to black. else if (lamp.color != lamp.black && xy == lamp.black) { put(getStateRoute(lamp.id), QString("{\"on\": false}")); } } // Remember last color. lamp.color = xy; // Next light id. idx++; } timer.start(); return 0; } int LedDevicePhilipsHue::switchOff() { timer.stop(); // If light states have been saved before, ... if (areStatesSaved()) { // ... restore them. restoreStates(); } return 0; } void LedDevicePhilipsHue::put(QString route, QString content) { QString url = QString("/api/%1/%2").arg(username).arg(route); QHttpRequestHeader header("PUT", url); header.setValue("Host", host); header.setValue("Accept-Encoding", "identity"); header.setValue("Connection", "keep-alive"); header.setValue("Content-Length", QString("%1").arg(content.size())); QEventLoop loop; // Connect requestFinished signal to quit slot of the loop. loop.connect(http, SIGNAL(requestFinished(int, bool)), SLOT(quit())); // Perfrom request http->request(header, content.toAscii()); // Go into the loop until the request is finished. loop.exec(); } QByteArray LedDevicePhilipsHue::get(QString route) { QString url = QString("/api/%1/%2").arg(username).arg(route); // Event loop to block until request finished. QEventLoop loop; // Connect requestFinished signal to quit slot of the loop. loop.connect(http, SIGNAL(requestFinished(int, bool)), SLOT(quit())); // Perfrom request http->get(url); // Go into the loop until the request is finished. loop.exec(); // Read all data of the response. return http->readAll(); } QString LedDevicePhilipsHue::getStateRoute(unsigned int lightId) { return QString("lights/%1/state").arg(lightId); } QString LedDevicePhilipsHue::getRoute(unsigned int lightId) { return QString("lights/%1").arg(lightId); } void LedDevicePhilipsHue::saveStates(unsigned int nLights) { // Clear saved lamps. lamps.clear(); // Use json parser to parse reponse. Json::Reader reader; Json::FastWriter writer; // Iterate lights. for (unsigned int i = 0; i < nLights; i++) { // Read the response. QByteArray response = get(getRoute(i + 1)); // Parse JSON. Json::Value json; if (!reader.parse(QString(response).toStdString(), json)) { // Error occured, break loop. break; } // Get state object values which are subject to change. Json::Value state(Json::objectValue); state["on"] = json["state"]["on"]; if (json["state"]["on"] == true) { state["xy"] = json["state"]["xy"]; state["bri"] = json["state"]["bri"]; } // Determine the model id. QString modelId = QString(writer.write(json["modelid"]).c_str()).trimmed().replace("\"", ""); QString originalState = QString(writer.write(state).c_str()).trimmed(); // Save state object. lamps.push_back(PhilipsHueLamp(i + 1, originalState, modelId)); } } void LedDevicePhilipsHue::switchOn(unsigned int nLights) { for (PhilipsHueLamp lamp : lamps) { put(getStateRoute(lamp.id), "{\"on\": true}"); } } void LedDevicePhilipsHue::restoreStates() { for (PhilipsHueLamp lamp : lamps) { put(getStateRoute(lamp.id), lamp.originalState); } // Clear saved light states. lamps.clear(); } bool LedDevicePhilipsHue::areStatesSaved() { return !lamps.empty(); } <commit_msg>Small performance improvement if off on black is true.<commit_after>// Local-Hyperion includes #include "LedDevicePhilipsHue.h" // jsoncpp includes #include <json/json.h> // qt includes #include <QtCore/qmath.h> #include <QUrl> #include <QHttpRequestHeader> #include <QEventLoop> #include <set> bool operator ==(CiColor p1, CiColor p2) { return (p1.x == p2.x) && (p1.y == p2.y) && (p1.bri == p2.bri); } bool operator !=(CiColor p1, CiColor p2) { return !(p1 == p2); } PhilipsHueLamp::PhilipsHueLamp(unsigned int id, QString originalState, QString modelId) : id(id), originalState(originalState) { // Hue system model ids. const std::set<QString> HUE_BULBS_MODEL_IDS = { "LCT001", "LCT002", "LCT003" }; const std::set<QString> LIVING_COLORS_MODEL_IDS = { "LLC001", "LLC005", "LLC006", "LLC007", "LLC011", "LLC012", "LLC013", "LST001" }; // Find id in the sets and set the appropiate color space. if (HUE_BULBS_MODEL_IDS.find(modelId) != HUE_BULBS_MODEL_IDS.end()) { colorSpace.red = {0.675f, 0.322f}; colorSpace.green = {0.4091f, 0.518f}; colorSpace.blue = {0.167f, 0.04f}; } else if (LIVING_COLORS_MODEL_IDS.find(modelId) != LIVING_COLORS_MODEL_IDS.end()) { colorSpace.red = {0.703f, 0.296f}; colorSpace.green = {0.214f, 0.709f}; colorSpace.blue = {0.139f, 0.081f}; } else { colorSpace.red = {1.0f, 0.0f}; colorSpace.green = {0.0f, 1.0f}; colorSpace.blue = {0.0f, 0.0f}; } // Initialize black color. black = rgbToCiColor(0.0f, 0.0f, 0.0f); // Initialize color with black color = {black.x, black.y, black.bri}; } float PhilipsHueLamp::crossProduct(CiColor p1, CiColor p2) { return p1.x * p2.y - p1.y * p2.x; } bool PhilipsHueLamp::isPointInLampsReach(CiColor p) { CiColor v1 = { colorSpace.green.x - colorSpace.red.x, colorSpace.green.y - colorSpace.red.y }; CiColor v2 = { colorSpace.blue.x - colorSpace.red.x, colorSpace.blue.y - colorSpace.red.y }; CiColor q = { p.x - colorSpace.red.x, p.y - colorSpace.red.y }; float s = crossProduct(q, v2) / crossProduct(v1, v2); float t = crossProduct(v1, q) / crossProduct(v1, v2); if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f)) { return true; } return false; } CiColor PhilipsHueLamp::getClosestPointToPoint(CiColor a, CiColor b, CiColor p) { CiColor AP = { p.x - a.x, p.y - a.y }; CiColor AB = { b.x - a.x, b.y - a.y }; float ab2 = AB.x * AB.x + AB.y * AB.y; float ap_ab = AP.x * AB.x + AP.y * AB.y; float t = ap_ab / ab2; if (t < 0.0f) { t = 0.0f; } else if (t > 1.0f) { t = 1.0f; } return {a.x + AB.x * t, a.y + AB.y * t}; } float PhilipsHueLamp::getDistanceBetweenTwoPoints(CiColor p1, CiColor p2) { // Horizontal difference. float dx = p1.x - p2.x; // Vertical difference. float dy = p1.y - p2.y; // Absolute value. return sqrt(dx * dx + dy * dy); } CiColor PhilipsHueLamp::rgbToCiColor(float red, float green, float blue) { // Apply gamma correction. float r = (red > 0.04045f) ? powf((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f); float g = (green > 0.04045f) ? powf((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f); float b = (blue > 0.04045f) ? powf((blue + 0.055f) / (1.0f + 0.055f), 2.4f) : (blue / 12.92f); // Convert to XYZ space. float X = r * 0.649926f + g * 0.103455f + b * 0.197109f; float Y = r * 0.234327f + g * 0.743075f + b * 0.022598f; float Z = r * 0.0000000f + g * 0.053077f + b * 1.035763f; // Convert to x,y space. float cx = X / (X + Y + Z); float cy = Y / (X + Y + Z); if (isnan(cx)) { cx = 0.0f; } if (isnan(cy)) { cy = 0.0f; } // Brightness is simply Y in the XYZ space. CiColor xy = { cx, cy, Y }; // Check if the given XY value is within the color reach of our lamps. if (!isPointInLampsReach(xy)) { // It seems the color is out of reach let's find the closes color we can produce with our lamp and send this XY value out. CiColor pAB = getClosestPointToPoint(colorSpace.red, colorSpace.green, xy); CiColor pAC = getClosestPointToPoint(colorSpace.blue, colorSpace.red, xy); CiColor pBC = getClosestPointToPoint(colorSpace.green, colorSpace.blue, xy); // Get the distances per point and see which point is closer to our Point. float dAB = getDistanceBetweenTwoPoints(xy, pAB); float dAC = getDistanceBetweenTwoPoints(xy, pAC); float dBC = getDistanceBetweenTwoPoints(xy, pBC); float lowest = dAB; CiColor closestPoint = pAB; if (dAC < lowest) { lowest = dAC; closestPoint = pAC; } if (dBC < lowest) { lowest = dBC; closestPoint = pBC; } // Change the xy value to a value which is within the reach of the lamp. xy.x = closestPoint.x; xy.y = closestPoint.y; } return xy; } LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output, const std::string& username, bool switchOffOnBlack, int transitiontime) : host(output.c_str()), username(username.c_str()), switchOffOnBlack(switchOffOnBlack), transitiontime( transitiontime) { http = new QHttp(host); timer.setInterval(3000); timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(restoreStates())); } LedDevicePhilipsHue::~LedDevicePhilipsHue() { delete http; } int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) { // Save light states if not done before. if (!areStatesSaved()) { saveStates((unsigned int) ledValues.size()); switchOn((unsigned int) ledValues.size()); } // If there are less states saved than colors given, then maybe something went wrong before. if (lamps.size() != ledValues.size()) { restoreStates(); return 0; } // Iterate through colors and set light states. unsigned int idx = 0; for (const ColorRgb& color : ledValues) { // Get lamp. PhilipsHueLamp& lamp = lamps.at(idx); // Scale colors from [0, 255] to [0, 1] and convert to xy space. CiColor xy = lamp.rgbToCiColor(color.red / 255.0f, color.green / 255.0f, color.blue / 255.0f); // Write color if color has been changed. if (xy != lamp.color) { // Send adjust color and brightness command in JSON format. // We have to set the transition time each time. put(getStateRoute(lamp.id), QString("{\"xy\": [%1, %2], \"bri\": %3, \"transitiontime\": %4}").arg(xy.x).arg(xy.y).arg( qRound(xy.bri * 255.0f)).arg(transitiontime)); } // Switch lamp off if switchOffOnBlack is enabled and the lamp is currently on. if (switchOffOnBlack) { // From black to a color. if (lamp.color == lamp.black && xy != lamp.black) { put(getStateRoute(lamp.id), QString("{\"on\": true}")); } // From a color to black. else if (lamp.color != lamp.black && xy == lamp.black) { put(getStateRoute(lamp.id), QString("{\"on\": false}")); } } // Remember last color. lamp.color = xy; // Next light id. idx++; } timer.start(); return 0; } int LedDevicePhilipsHue::switchOff() { timer.stop(); // If light states have been saved before, ... if (areStatesSaved()) { // ... restore them. restoreStates(); } return 0; } void LedDevicePhilipsHue::put(QString route, QString content) { QString url = QString("/api/%1/%2").arg(username).arg(route); QHttpRequestHeader header("PUT", url); header.setValue("Host", host); header.setValue("Accept-Encoding", "identity"); header.setValue("Connection", "keep-alive"); header.setValue("Content-Length", QString("%1").arg(content.size())); QEventLoop loop; // Connect requestFinished signal to quit slot of the loop. loop.connect(http, SIGNAL(requestFinished(int, bool)), SLOT(quit())); // Perfrom request http->request(header, content.toAscii()); // Go into the loop until the request is finished. loop.exec(); } QByteArray LedDevicePhilipsHue::get(QString route) { QString url = QString("/api/%1/%2").arg(username).arg(route); // Event loop to block until request finished. QEventLoop loop; // Connect requestFinished signal to quit slot of the loop. loop.connect(http, SIGNAL(requestFinished(int, bool)), SLOT(quit())); // Perfrom request http->get(url); // Go into the loop until the request is finished. loop.exec(); // Read all data of the response. return http->readAll(); } QString LedDevicePhilipsHue::getStateRoute(unsigned int lightId) { return QString("lights/%1/state").arg(lightId); } QString LedDevicePhilipsHue::getRoute(unsigned int lightId) { return QString("lights/%1").arg(lightId); } void LedDevicePhilipsHue::saveStates(unsigned int nLights) { // Clear saved lamps. lamps.clear(); // Use json parser to parse reponse. Json::Reader reader; Json::FastWriter writer; // Iterate lights. for (unsigned int i = 0; i < nLights; i++) { // Read the response. QByteArray response = get(getRoute(i + 1)); // Parse JSON. Json::Value json; if (!reader.parse(QString(response).toStdString(), json)) { // Error occured, break loop. break; } // Get state object values which are subject to change. Json::Value state(Json::objectValue); state["on"] = json["state"]["on"]; if (json["state"]["on"] == true) { state["xy"] = json["state"]["xy"]; state["bri"] = json["state"]["bri"]; } // Determine the model id. QString modelId = QString(writer.write(json["modelid"]).c_str()).trimmed().replace("\"", ""); QString originalState = QString(writer.write(state).c_str()).trimmed(); // Save state object. lamps.push_back(PhilipsHueLamp(i + 1, originalState, modelId)); } } void LedDevicePhilipsHue::switchOn(unsigned int nLights) { for (PhilipsHueLamp lamp : lamps) { put(getStateRoute(lamp.id), "{\"on\": true}"); } } void LedDevicePhilipsHue::restoreStates() { for (PhilipsHueLamp lamp : lamps) { put(getStateRoute(lamp.id), lamp.originalState); } // Clear saved light states. lamps.clear(); } bool LedDevicePhilipsHue::areStatesSaved() { return !lamps.empty(); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver. ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <cstdlib> #include "tdriver_rubyinterface.h" #include "tdriver_util.h" #include <QMap> #include <QByteArray> #include <QList> #include <QFile> #include <QDebug> #include <QTcpSocket> #include <QHostAddress> #include <QMutexLocker> #include <QWaitCondition> #include <QMutex> #include "tdriver_debug_macros.h" static const char delimChar = 032; // note: octal static const char InteractDelimCstr[] = { delimChar, delimChar, 0 }; // debug macros #define VALIDATE_THREAD (Q_ASSERT(validThread == NULL || validThread == QThread::currentThread())) #define VALIDATE_THREAD_NOT (Q_ASSERT(validThread != QThread::currentThread())) TDriverRubyInterface::TDriverRubyInterface() : QThread(NULL), rbiPort(0), rbiVersion(0), rbiTDriverVersion(), syncMutex(new QMutex(/*QMutex::Recursive*/)), msgCond(new QWaitCondition()), helloCond(new QWaitCondition()), process(NULL), conn(NULL), handler(NULL), initState(Closed), stderrEvalSeqNum(0), stdoutEvalSeqNum(0), delimStr(InteractDelimCstr), evalStartStr(delimStr + "START "), evalEndStr(delimStr + "END "), validThread(NULL) { } TDriverRubyInterface::~TDriverRubyInterface() { delete msgCond; delete helloCond; delete syncMutex; } void TDriverRubyInterface::startGlobalInstance() { qDebug() << FFL; Q_ASSERT (!pGlobalInstance); pGlobalInstance = new TDriverRubyInterface(); pGlobalInstance->moveToThread(pGlobalInstance); connect(pGlobalInstance, SIGNAL(requestRubyConnection()), pGlobalInstance, SLOT(resetRubyConnection()), Qt::QueuedConnection); connect(pGlobalInstance, SIGNAL(requestCloseSignal()), pGlobalInstance, SLOT(close()), Qt::QueuedConnection); pGlobalInstance->start(); } void TDriverRubyInterface::requestClose() { VALIDATE_THREAD_NOT; qDebug() << FCFL; initState = Closing; emit requestCloseSignal(); } void TDriverRubyInterface::run() { qDebug() << FCFL << "THREAD START"; setValidThread(currentThread()); int result = exec(); qDebug() << FCFL << "THREAD EXIT with" << result; if (handler) { delete handler; handler = NULL; } if (conn) { delete conn; conn = NULL; } delete process; // will kill the process process = NULL; } bool TDriverRubyInterface::goOnline() { VALIDATE_THREAD_NOT; Q_ASSERT(isRunning()); // must only be called when thread is running QMutexLocker lock(syncMutex); if (initState == Closed) { static int counter=0; qDebug() << FCFL << "Waiting for Ruby start #" << ++counter; emit requestRubyConnection(); msgCond->wait(syncMutex); qDebug() << FCFL << "Ruby started" << counter; } if (initState == Running && !handler->isHelloReceived()) { // now there should be a TCP connection, but no messages received yet qDebug() << FCFL << "Waiting for HELLO"; bool ok = handler->waitHello(5000); qDebug() << FCFL << "after waitHello:" << ok << handler->isHelloReceived(); if (!handler->isHelloReceived()) { qWarning() << "Ruby script tdriver_interface.rb did not say hello to us (initState" << initState << "), closing."; requestClose(); } else { initState = Connected; } } return (initState == Connected); } void TDriverRubyInterface::recreateConn() { VALIDATE_THREAD; qDebug() << FCFL; if (handler) { delete handler; handler = NULL; } // reset or create QTcpSocket instance if (conn) { if (conn->isOpen()) { conn->close(); if (conn->bytesAvailable() > 0) { QByteArray tmp = conn->readAll(); qDebug() << FCFL << tmp.size() << "bytes"; } } } else { conn = new QTcpSocket(this); } Q_ASSERT(conn && conn->state() ==QAbstractSocket::UnconnectedState && conn->bytesAvailable() == 0); } void TDriverRubyInterface::resetProcess() { VALIDATE_THREAD; Q_ASSERT(process); initState = Closed; if (process->state() != QProcess::NotRunning) { process->terminate(); if (!process->waitForFinished(5000)) { process->kill(); if (!process->waitForFinished(5000)) { qFatal("Failed to kill ruby process!"); } } } // else aready not running qDebug() << FCFL << "reporting exitcode" << process->exitCode() << "exitstatus" << process->exitStatus(); disconnect(); // disconnect any stray signals readProcessStdout(); readProcessStderr(); } void TDriverRubyInterface::recreateProcess() { VALIDATE_THREAD; qDebug() << FCFL; // reset or create QProcess instance if (process) { resetProcess(); } else { qDebug() << FCFL; process = new QProcess(this); // set RUBYOPT env. setting if system doesn't have it already QStringList envSettings = QProcess::systemEnvironment(); if ( QString( getenv( "RUBYOPT" ) ) != "rubygems" ) { envSettings << "RUBYOPT=rubygems"; } process->setEnvironment( envSettings ); } Q_ASSERT(process && process->state() == QProcess::NotRunning && process->bytesAvailable() == 0); // (re)connect signals qDebug() << FCFL; connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SIGNAL(rubyProcessFinished())); qDebug() << FCFL; } void TDriverRubyInterface::resetRubyConnection() { VALIDATE_THREAD; qDebug() << FCFL; recreateConn(); recreateProcess(); syncMutex->lock(); bool ok = true; initErrorMsg.clear(); QString errorTitle(tr("Failed to initialize TDriver")); // if TDRIVER_VISUALIZER_LISTENER environment variable is set, use a custom file to use as the listener QString scriptFile = TDriverUtil::tdriverHelperFilePath("tdriver_interface.rb", "TDRIVER_VISUALIZER_LISTENER"); if (ok) { // verify that script file exists if (!QFile::exists( scriptFile )) { initErrorMsg = tr("Could not find Visualizer listener server file '%1'" ).arg(scriptFile); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } } if (ok) process->setTextModeEnabled(true); if (ok) process->start( "ruby", QStringList() << scriptFile ); if ( ok && !process->waitForStarted( 30000 ) ) { initErrorMsg = tr("Could not start Ruby script '%1'" ).arg(scriptFile); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } if ( ok && !process->waitForReadyRead(60000)) { initErrorMsg = tr("Could not read startup parameters." ); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } if ( ok && !process->canReadLine()) { initErrorMsg = tr("Could not read full line of." ); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } QByteArray startupLine; if (ok) { startupLine = process->readLine().simplified(); BAList startupList(startupLine.split(' ')); // Ruby string printed at script startup: // "TDriverVisualizerRubyInterface version #{tdriver_interface_rb_version} port #{server.addr[1]} tdriver #{tdriver_gem_version}" if (startupList.length() < 7 || startupList[0] != "TDriverVisualizerRubyInterface" || startupList[1] != "version" || startupList[2].toInt() == 0 || startupList[3] != "port" || startupList[4].toInt() == 0 || startupList[5] != "tdriver" || startupList[6].isEmpty()) { initErrorMsg = tr("Invalid first line '%1'.").arg(QString::fromLocal8Bit(startupLine)); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, tr("More ouput:\n") + process->readAllStandardOutput()); ok = false; } else { rbiVersion = startupList[2].toInt(); rbiPort = startupList[4].toInt(); rbiTDriverVersion = startupList[6]; } } if (ok && ((rbiPort < 1 || rbiPort > 65535) || rbiVersion != 1)) { initErrorMsg = tr("Invalid values on first line: rbiPort %1, rbiVersion %2").arg(rbiPort).arg(rbiVersion); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, tr("More ouput:\n") + process->readAllStandardOutput()); ok = false; } connect(process, SIGNAL(readyReadStandardError()), this, SLOT(readProcessStderr())); connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readProcessStdout())); // read and ignore any extra output readProcessStderr(); readProcessStdout(); if (ok) { Q_ASSERT(!handler); handler = new TDriverRbiProtocol(conn, syncMutex, msgCond, helloCond, this); handler->setValidThread(currentThread()); connect(handler, SIGNAL(helloReceived()), this, SIGNAL(rubyOnline())); connect(handler, SIGNAL(messageReceived(quint32,QByteArray,BAListMap)), this, SIGNAL(messageReceived(quint32,QByteArray,BAListMap))); connect(handler, SIGNAL(gotDisconnection()), this, SLOT(close())); qDebug() << FCFL << "Connecting localhost :" << rbiPort; conn->connectToHost(QHostAddress(QHostAddress::LocalHost), rbiPort); if (!conn->waitForConnected()) { initErrorMsg = tr("Failed to connect to Ruby process via TCP/IP!"); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } } if (ok) { initState = Running; } qDebug() << FCFL << "RESULT" << ok << initState; // Notify the thread that called resetRubyConnection msgCond->wakeAll(); if (!ok) helloCond->wakeAll(); syncMutex->unlock(); } void TDriverRubyInterface::close() { VALIDATE_THREAD; QMutexLocker lock(syncMutex); if (initState == Closed || initState == Closing) { qDebug() << FCFL << "initState already" << initState; return; } initState = Closing; msgCond->wakeAll(); helloCond->wakeAll(); qDebug() << FCFL << "TDriverRubyInterface: Closing process, process state" << process->state() << ", conn state" << conn->state(); if (conn->isOpen()) { conn->close(); } resetProcess(); } void TDriverRubyInterface::readProcessHelper(int fnum, QByteArray &readBuffer, quint32 &seqNum, QByteArray &evalBuffer) { QByteArray data( (fnum == 0) ? process->readAllStandardOutput() : process->readAllStandardError()); const char *streamName = (fnum == 0) ? "STDOUT" : "STDERR"; readBuffer.append(data); BAList lines = readBuffer.split('\n'); readBuffer = lines.takeLast(); // put empty or partial line back to buffer foreach(QByteArray line, lines) { if (line.startsWith(delimStr)) { if (seqNum > 0) { qDebug() << FCFL << streamName << "seqNum" << seqNum << "output" << evalBuffer; emit rubyOutput(fnum, seqNum, evalBuffer); } evalBuffer.clear(); seqNum = 0; if (line.startsWith(evalStartStr)) { static const QRegExp start_ex("START ([0-9]+)"); if (start_ex.indexIn(QString(line)) > 0) { seqNum = start_ex.capturedTexts().at(1).toUInt(); } else { qWarning() << FCFL << "invalid start line" << line; } } else if (line.startsWith(evalEndStr)) { // nothing } else { qDebug() << FCFL << streamName << "IGNORING" << line; } } else if (seqNum > 0) { evalBuffer.append(line); evalBuffer.append('\n'); } else { qDebug() << FCFL << streamName << "untagged line" << line; emit rubyOutput(fnum, line); } } } void TDriverRubyInterface::readProcessStdout() { VALIDATE_THREAD; readProcessHelper(0, stdoutBuffer, stdoutEvalSeqNum, stdoutEvalBuffer); } void TDriverRubyInterface::readProcessStderr() { VALIDATE_THREAD; readProcessHelper(1, stderrBuffer, stderrEvalSeqNum, stderrEvalBuffer); } quint32 TDriverRubyInterface::sendCmd( const QByteArray &name, const BAListMap &cmd) { if (initState != Connected || !handler) { return 0; } quint32 seqNum = handler->sendStringListMapMsg(name, cmd); Q_ASSERT(seqNum > 0); return seqNum; } bool TDriverRubyInterface::executeCmd(const QByteArray &name, BAListMap &cmd_reply, unsigned long timeout) { VALIDATE_THREAD_NOT; if (!goOnline()) return false; QMutexLocker lock(syncMutex); qDebug() << FCFL << "SENDING" << cmd_reply; quint32 seqNum = sendCmd(name, cmd_reply); //qDebug() << FCFL << "Sent" << seqNum << name << cmd_reply; if (seqNum != 0) { if (handler->waitSeqNum(seqNum, timeout)) { cmd_reply = handler->waitedMessage(); qDebug() << FCFL << "REPLY" << cmd_reply; return true; } } qDebug() << FCFL << "FAIL"; return false; } int TDriverRubyInterface::getPort() { QMutexLocker mut(syncMutex); return rbiPort; } int TDriverRubyInterface::getRbiVersion() { QMutexLocker mut(syncMutex); return rbiVersion; } QString TDriverRubyInterface::getTDriverVersion() { QMutexLocker mut(syncMutex); return rbiTDriverVersion; } TDriverRubyInterface::TDriverRubyInterface *TDriverRubyInterface::globalInstance() { //VALIDATE_THREAD_NOT; //Q_ASSERT(pGlobalInstance); return pGlobalInstance; } TDriverRubyInterface::TDriverRubyInterface *TDriverRubyInterface::pGlobalInstance = NULL; <commit_msg>Compilation fix for Linux<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver. ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <cstdlib> #include "tdriver_rubyinterface.h" #include "tdriver_util.h" #include <QMap> #include <QByteArray> #include <QList> #include <QFile> #include <QDebug> #include <QTcpSocket> #include <QHostAddress> #include <QMutexLocker> #include <QWaitCondition> #include <QMutex> #include "tdriver_debug_macros.h" static const char delimChar = 032; // note: octal static const char InteractDelimCstr[] = { delimChar, delimChar, 0 }; // debug macros #define VALIDATE_THREAD (Q_ASSERT(validThread == NULL || validThread == QThread::currentThread())) #define VALIDATE_THREAD_NOT (Q_ASSERT(validThread != QThread::currentThread())) TDriverRubyInterface::TDriverRubyInterface() : QThread(NULL), rbiPort(0), rbiVersion(0), rbiTDriverVersion(), syncMutex(new QMutex(/*QMutex::Recursive*/)), msgCond(new QWaitCondition()), helloCond(new QWaitCondition()), process(NULL), conn(NULL), handler(NULL), initState(Closed), stderrEvalSeqNum(0), stdoutEvalSeqNum(0), delimStr(InteractDelimCstr), evalStartStr(delimStr + "START "), evalEndStr(delimStr + "END "), validThread(NULL) { } TDriverRubyInterface::~TDriverRubyInterface() { delete msgCond; delete helloCond; delete syncMutex; } void TDriverRubyInterface::startGlobalInstance() { qDebug() << FFL; Q_ASSERT (!pGlobalInstance); pGlobalInstance = new TDriverRubyInterface(); pGlobalInstance->moveToThread(pGlobalInstance); connect(pGlobalInstance, SIGNAL(requestRubyConnection()), pGlobalInstance, SLOT(resetRubyConnection()), Qt::QueuedConnection); connect(pGlobalInstance, SIGNAL(requestCloseSignal()), pGlobalInstance, SLOT(close()), Qt::QueuedConnection); pGlobalInstance->start(); } void TDriverRubyInterface::requestClose() { VALIDATE_THREAD_NOT; qDebug() << FCFL; initState = Closing; emit requestCloseSignal(); } void TDriverRubyInterface::run() { qDebug() << FCFL << "THREAD START"; setValidThread(currentThread()); int result = exec(); qDebug() << FCFL << "THREAD EXIT with" << result; if (handler) { delete handler; handler = NULL; } if (conn) { delete conn; conn = NULL; } delete process; // will kill the process process = NULL; } bool TDriverRubyInterface::goOnline() { VALIDATE_THREAD_NOT; Q_ASSERT(isRunning()); // must only be called when thread is running QMutexLocker lock(syncMutex); if (initState == Closed) { static int counter=0; qDebug() << FCFL << "Waiting for Ruby start #" << ++counter; emit requestRubyConnection(); msgCond->wait(syncMutex); qDebug() << FCFL << "Ruby started" << counter; } if (initState == Running && !handler->isHelloReceived()) { // now there should be a TCP connection, but no messages received yet qDebug() << FCFL << "Waiting for HELLO"; bool ok = handler->waitHello(5000); qDebug() << FCFL << "after waitHello:" << ok << handler->isHelloReceived(); if (!handler->isHelloReceived()) { qWarning() << "Ruby script tdriver_interface.rb did not say hello to us (initState" << initState << "), closing."; requestClose(); } else { initState = Connected; } } return (initState == Connected); } void TDriverRubyInterface::recreateConn() { VALIDATE_THREAD; qDebug() << FCFL; if (handler) { delete handler; handler = NULL; } // reset or create QTcpSocket instance if (conn) { if (conn->isOpen()) { conn->close(); if (conn->bytesAvailable() > 0) { QByteArray tmp = conn->readAll(); qDebug() << FCFL << tmp.size() << "bytes"; } } } else { conn = new QTcpSocket(this); } Q_ASSERT(conn && conn->state() ==QAbstractSocket::UnconnectedState && conn->bytesAvailable() == 0); } void TDriverRubyInterface::resetProcess() { VALIDATE_THREAD; Q_ASSERT(process); initState = Closed; if (process->state() != QProcess::NotRunning) { process->terminate(); if (!process->waitForFinished(5000)) { process->kill(); if (!process->waitForFinished(5000)) { qFatal("Failed to kill ruby process!"); } } } // else aready not running qDebug() << FCFL << "reporting exitcode" << process->exitCode() << "exitstatus" << process->exitStatus(); disconnect(); // disconnect any stray signals readProcessStdout(); readProcessStderr(); } void TDriverRubyInterface::recreateProcess() { VALIDATE_THREAD; qDebug() << FCFL; // reset or create QProcess instance if (process) { resetProcess(); } else { qDebug() << FCFL; process = new QProcess(this); // set RUBYOPT env. setting if system doesn't have it already QStringList envSettings = QProcess::systemEnvironment(); if ( QString( getenv( "RUBYOPT" ) ) != "rubygems" ) { envSettings << "RUBYOPT=rubygems"; } process->setEnvironment( envSettings ); } Q_ASSERT(process && process->state() == QProcess::NotRunning && process->bytesAvailable() == 0); // (re)connect signals qDebug() << FCFL; connect(process, SIGNAL(finished(int,QProcess::ExitStatus)), this, SIGNAL(rubyProcessFinished())); qDebug() << FCFL; } void TDriverRubyInterface::resetRubyConnection() { VALIDATE_THREAD; qDebug() << FCFL; recreateConn(); recreateProcess(); syncMutex->lock(); bool ok = true; initErrorMsg.clear(); QString errorTitle(tr("Failed to initialize TDriver")); // if TDRIVER_VISUALIZER_LISTENER environment variable is set, use a custom file to use as the listener QString scriptFile = TDriverUtil::tdriverHelperFilePath("tdriver_interface.rb", "TDRIVER_VISUALIZER_LISTENER"); if (ok) { // verify that script file exists if (!QFile::exists( scriptFile )) { initErrorMsg = tr("Could not find Visualizer listener server file '%1'" ).arg(scriptFile); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } } if (ok) process->setTextModeEnabled(true); if (ok) process->start( "ruby", QStringList() << scriptFile ); if ( ok && !process->waitForStarted( 30000 ) ) { initErrorMsg = tr("Could not start Ruby script '%1'" ).arg(scriptFile); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } if ( ok && !process->waitForReadyRead(60000)) { initErrorMsg = tr("Could not read startup parameters." ); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } if ( ok && !process->canReadLine()) { initErrorMsg = tr("Could not read full line of." ); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } QByteArray startupLine; if (ok) { startupLine = process->readLine().simplified(); BAList startupList(startupLine.split(' ')); // Ruby string printed at script startup: // "TDriverVisualizerRubyInterface version #{tdriver_interface_rb_version} port #{server.addr[1]} tdriver #{tdriver_gem_version}" if (startupList.length() < 7 || startupList[0] != "TDriverVisualizerRubyInterface" || startupList[1] != "version" || startupList[2].toInt() == 0 || startupList[3] != "port" || startupList[4].toInt() == 0 || startupList[5] != "tdriver" || startupList[6].isEmpty()) { initErrorMsg = tr("Invalid first line '%1'.").arg(QString::fromLocal8Bit(startupLine)); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, tr("More ouput:\n") + process->readAllStandardOutput()); ok = false; } else { rbiVersion = startupList[2].toInt(); rbiPort = startupList[4].toInt(); rbiTDriverVersion = startupList[6]; } } if (ok && ((rbiPort < 1 || rbiPort > 65535) || rbiVersion != 1)) { initErrorMsg = tr("Invalid values on first line: rbiPort %1, rbiVersion %2").arg(rbiPort).arg(rbiVersion); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, tr("More ouput:\n") + process->readAllStandardOutput()); ok = false; } connect(process, SIGNAL(readyReadStandardError()), this, SLOT(readProcessStderr())); connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readProcessStdout())); // read and ignore any extra output readProcessStderr(); readProcessStdout(); if (ok) { Q_ASSERT(!handler); handler = new TDriverRbiProtocol(conn, syncMutex, msgCond, helloCond, this); handler->setValidThread(currentThread()); connect(handler, SIGNAL(helloReceived()), this, SIGNAL(rubyOnline())); connect(handler, SIGNAL(messageReceived(quint32,QByteArray,BAListMap)), this, SIGNAL(messageReceived(quint32,QByteArray,BAListMap))); connect(handler, SIGNAL(gotDisconnection()), this, SLOT(close())); qDebug() << FCFL << "Connecting localhost :" << rbiPort; conn->connectToHost(QHostAddress(QHostAddress::LocalHost), rbiPort); if (!conn->waitForConnected()) { initErrorMsg = tr("Failed to connect to Ruby process via TCP/IP!"); qDebug() << FCFL << "emit error" << errorTitle << initErrorMsg; emit error(errorTitle, initErrorMsg, ""); ok = false; } } if (ok) { initState = Running; } qDebug() << FCFL << "RESULT" << ok << initState; // Notify the thread that called resetRubyConnection msgCond->wakeAll(); if (!ok) helloCond->wakeAll(); syncMutex->unlock(); } void TDriverRubyInterface::close() { VALIDATE_THREAD; QMutexLocker lock(syncMutex); if (initState == Closed || initState == Closing) { qDebug() << FCFL << "initState already" << initState; return; } initState = Closing; msgCond->wakeAll(); helloCond->wakeAll(); qDebug() << FCFL << "TDriverRubyInterface: Closing process, process state" << process->state() << ", conn state" << conn->state(); if (conn->isOpen()) { conn->close(); } resetProcess(); } void TDriverRubyInterface::readProcessHelper(int fnum, QByteArray &readBuffer, quint32 &seqNum, QByteArray &evalBuffer) { QByteArray data( (fnum == 0) ? process->readAllStandardOutput() : process->readAllStandardError()); const char *streamName = (fnum == 0) ? "STDOUT" : "STDERR"; readBuffer.append(data); BAList lines = readBuffer.split('\n'); readBuffer = lines.takeLast(); // put empty or partial line back to buffer foreach(QByteArray line, lines) { if (line.startsWith(delimStr)) { if (seqNum > 0) { qDebug() << FCFL << streamName << "seqNum" << seqNum << "output" << evalBuffer; emit rubyOutput(fnum, seqNum, evalBuffer); } evalBuffer.clear(); seqNum = 0; if (line.startsWith(evalStartStr)) { static const QRegExp start_ex("START ([0-9]+)"); if (start_ex.indexIn(QString(line)) > 0) { seqNum = start_ex.capturedTexts().at(1).toUInt(); } else { qWarning() << FCFL << "invalid start line" << line; } } else if (line.startsWith(evalEndStr)) { // nothing } else { qDebug() << FCFL << streamName << "IGNORING" << line; } } else if (seqNum > 0) { evalBuffer.append(line); evalBuffer.append('\n'); } else { qDebug() << FCFL << streamName << "untagged line" << line; emit rubyOutput(fnum, line); } } } void TDriverRubyInterface::readProcessStdout() { VALIDATE_THREAD; readProcessHelper(0, stdoutBuffer, stdoutEvalSeqNum, stdoutEvalBuffer); } void TDriverRubyInterface::readProcessStderr() { VALIDATE_THREAD; readProcessHelper(1, stderrBuffer, stderrEvalSeqNum, stderrEvalBuffer); } quint32 TDriverRubyInterface::sendCmd( const QByteArray &name, const BAListMap &cmd) { if (initState != Connected || !handler) { return 0; } quint32 seqNum = handler->sendStringListMapMsg(name, cmd); Q_ASSERT(seqNum > 0); return seqNum; } bool TDriverRubyInterface::executeCmd(const QByteArray &name, BAListMap &cmd_reply, unsigned long timeout) { VALIDATE_THREAD_NOT; if (!goOnline()) return false; QMutexLocker lock(syncMutex); qDebug() << FCFL << "SENDING" << cmd_reply; quint32 seqNum = sendCmd(name, cmd_reply); //qDebug() << FCFL << "Sent" << seqNum << name << cmd_reply; if (seqNum != 0) { if (handler->waitSeqNum(seqNum, timeout)) { cmd_reply = handler->waitedMessage(); qDebug() << FCFL << "REPLY" << cmd_reply; return true; } } qDebug() << FCFL << "FAIL"; return false; } int TDriverRubyInterface::getPort() { QMutexLocker mut(syncMutex); return rbiPort; } int TDriverRubyInterface::getRbiVersion() { QMutexLocker mut(syncMutex); return rbiVersion; } QString TDriverRubyInterface::getTDriverVersion() { QMutexLocker mut(syncMutex); return rbiTDriverVersion; } TDriverRubyInterface *TDriverRubyInterface::globalInstance() { //VALIDATE_THREAD_NOT; //Q_ASSERT(pGlobalInstance); return pGlobalInstance; } TDriverRubyInterface *TDriverRubyInterface::pGlobalInstance = NULL; <|endoftext|>
<commit_before>/* Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com> 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 <QStringList> #include <QFile> #include <QTextStream> #include <stdio.h> const static int hashMaxLength = 8; inline int indexOfSeparator(const QString &str, int minIndex) { int dotIndex = str.indexOf(QChar('.'), minIndex); int underscoreIndex = str.indexOf(QChar('_'), minIndex); if (dotIndex < 0) { return underscoreIndex; } else if (underscoreIndex < 0) { return dotIndex; } return dotIndex < underscoreIndex ? dotIndex : underscoreIndex; } int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s <source>\n", argv[0]); return 0; } QFile sourceFile(QString::fromLatin1(argv[1])); if (!sourceFile.open(QIODevice::ReadWrite)) return -1; QTextStream input(&sourceFile); int currentLine = 0; while (!input.atEnd()) { QString line = input.readLine(); ++currentLine; if (line.simplified().isEmpty() || (line.startsWith(QLatin1String("---")) && line.endsWith(QLatin1String("---")))) { continue; } int hashIndex = line.indexOf(QChar('#')); if ((hashIndex < 1) || (hashIndex + 1 > line.length())) { printf("Bad string: %s (line %d)\n", line.toLatin1().constData(), currentLine); return -1; } QString name = line.left(hashIndex); name[0] = name.at(0).toUpper(); int separatorIndex = 0; while ((separatorIndex = indexOfSeparator(name, separatorIndex)) > 0) { if ((name.length() < separatorIndex + 1) || (!name.at(separatorIndex + 1).isLetter())) { printf("Bad name: %s (line %d)\n", name.toLatin1().constData(), currentLine); return -2; } name[separatorIndex + 1] = name.at(separatorIndex + 1).toUpper(); name.remove(separatorIndex, 1); } QString value = line.mid(hashIndex + 1, hashMaxLength); int endOfValue = value.indexOf(QChar(' ')); if (endOfValue > 0) { value.truncate(endOfValue); } // printf("Line %d: name: %s, value: %s\n", currentLine, name.toLatin1().constData(), value.toLatin1().constData()); if (!input.atEnd()) printf("%s = 0x%s,\n", name.toLatin1().constData(), value.toLatin1().constData()); else printf("%s = 0x%s\n", name.toLatin1().constData(), value.toLatin1().constData()); } return 0; } <commit_msg>TLValuesGenerator: Implemented multiply sources and files generation.<commit_after>/* Copyright (C) 2014 Alexandr Akulich <akulichalexander@gmail.com> 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 <QCoreApplication> #include <QDir> #include <QFile> #include <QStringList> #include <QTextStream> #include <stdio.h> const static int hashMaxLength = 8; inline int indexOfSeparator(const QString &str, int minIndex) { int dotIndex = str.indexOf(QChar('.'), minIndex); int underscoreIndex = str.indexOf(QChar('_'), minIndex); if (dotIndex < 0) { return underscoreIndex; } else if (underscoreIndex < 0) { return dotIndex; } return dotIndex < underscoreIndex ? dotIndex : underscoreIndex; } bool replaceSection(const QString &fileName, const QString &startMarker, const QString &endMarker, const QString &newContent) { QFile fileToProcess(fileName); if (!fileToProcess.open(QIODevice::ReadOnly)) return false; QString fileContent = fileToProcess.readAll(); fileToProcess.close(); bool winNewLines = fileContent.indexOf(QLatin1String("\r\n")) > 0; if (winNewLines) { fileContent.replace(QLatin1String("\r\n"), QLatin1String("\n")); } int startPos = fileContent.indexOf(startMarker); int endPos = fileContent.indexOf(endMarker); if (startPos >= 0) { if (endPos < 0) { printf("There is only start marker in the file %s. Error.\n", fileName.toLocal8Bit().constData()); return false; } endPos += endMarker.length(); } else { return false; } const QString previousContent = fileContent.mid(startPos, endPos - startPos); if (previousContent == startMarker + newContent + endMarker) { printf("Nothing to do: new and previous contents are exactly same.\n"); return true; } fileContent.remove(startPos, endPos - startPos); fileContent.insert(startPos, startMarker + newContent + endMarker); if (!fileToProcess.open(QIODevice::WriteOnly)) { printf("Can not write file: %s.\n", fileName.toLocal8Bit().constData()); return false; } if (winNewLines) { fileContent.replace(QLatin1String("\n"), QLatin1String("\r\n")); } fileToProcess.write(fileContent.toLatin1()); fileToProcess.close(); return true; } bool replacingHelper(const QString &fileName, int spacing, const QString &marker, const QString &newContent) { const QString space(spacing, QChar(' ')); if (!replaceSection(fileName, QString("%1// Generated %2\n").arg(space).arg(marker), QString("%1// End of generated %2\n").arg(space).arg(marker), newContent)) { printf("Can not update file %s with marker %2.\n", fileName.toLatin1().constData(), marker.toLatin1().constData()); return false; } else { return true; } } QString generateCode(const QString &fileName, int indentation, bool closeEnum) { QFile sourceFile(fileName); if (!sourceFile.open(QIODevice::ReadWrite)) { return QString(); } QTextStream input(&sourceFile); QString result; QString indentationStr(indentation, QChar(' ')); int currentLine = 0; while (!input.atEnd()) { QString line = input.readLine(); ++currentLine; if (line.simplified().isEmpty() || (line.startsWith(QLatin1String("---")) && line.endsWith(QLatin1String("---")))) { continue; } int hashIndex = line.indexOf(QChar('#')); if ((hashIndex < 1) || (hashIndex + 1 > line.length())) { printf("Bad string: %s (%s:%d)\n", line.toLocal8Bit().constData(), fileName.toLocal8Bit().constData(), currentLine); return QString(); } QString name = line.left(hashIndex); name[0] = name.at(0).toUpper(); int separatorIndex = 0; while ((separatorIndex = indexOfSeparator(name, separatorIndex)) > 0) { if ((name.length() < separatorIndex + 1) || (!name.at(separatorIndex + 1).isLetter())) { printf("Bad name: %s (%s:%d)\n", name.toLocal8Bit().constData(), fileName.toLocal8Bit().constData(), currentLine); return QString(); } name[separatorIndex + 1] = name.at(separatorIndex + 1).toUpper(); name.remove(separatorIndex, 1); } QString value = line.mid(hashIndex + 1, hashMaxLength); int endOfValue = value.indexOf(QChar(' ')); if (endOfValue > 0) { value.truncate(endOfValue); } result.append(indentationStr); if (!closeEnum || !input.atEnd()) { result.append(QString("%1 = 0x%2,\n").arg(name).arg(value)); } else { result.append(QString("%1 = 0x%2\n").arg(name).arg(value)); } } return result; } int main(int argc, char *argv[]) { if (argc != 4) { printf("Usage: %s <source file or directory> <destination file> <marker>\nExample: %s specs ../TLValues.h TLValues\n", argv[0], argv[0]); return 0; } QCoreApplication app(argc, argv); static const QStringList arguments = app.arguments(); static const int indentation = 4; QString indentationStr(indentation, QChar(' ')); QString code; QDir argDir(arguments.at(1)); if (argDir.exists()) { const QStringList filesList = argDir.entryList(QStringList() << "*.txt", QDir::Files|QDir::Readable, QDir::Name); for (int i = 0; i < filesList.count(); ++i) { bool closeEnum = i == filesList.count() - 1; code.append(indentationStr + QString("// From %1:\n").arg(filesList.at(i))); code.append(generateCode(argDir.absolutePath() + "/" + filesList.at(i), indentation, closeEnum)); if (!closeEnum) { code.append(QChar('\n')); } } } else { code.append(generateCode(arguments.at(1), indentation, /* closeEnum */ true)); } if (replacingHelper(arguments.at(2), indentation, arguments.at(3), code)) { printf("File successfully updated.\n"); } return 0; } <|endoftext|>
<commit_before><commit_msg>fix ambiguous OUString constructor call<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#738732 Uninitialized scalar field<commit_after><|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: $ */ //_________________________________________________________________________ // Analysis task that executes the analysis classes // that depend on the PartCorr frame, frame for Particle identification and correlations. // Specially designed for calorimeters but also can be used for charged tracks // Input of this task is a configuration file that contains all the settings of the analyis // // -- Author: Gustavo Conesa (INFN-LNF) #include <cstdlib> // --- Root --- #include <TROOT.h> #include <TInterpreter.h> #include <TClonesArray.h> //#include <Riostream.h> //#include <TObjectTable.h> // --- Analysis --- #include "AliAnalysisTaskParticleCorrelation.h" #include "AliAnaPartCorrMaker.h" #include "AliCaloTrackReader.h" #include "AliPDG.h" #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" ClassImp(AliAnalysisTaskParticleCorrelation) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(): AliAnalysisTaskSE(), fAna(0x0), fOutputContainer(0x0), fConfigName(""), fCuts(0x0) { // Default constructor } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name): AliAnalysisTaskSE(name), fAna(0x0), fOutputContainer(0x0), fConfigName(""), fCuts(0x0) { // Default constructor DefineOutput(1, TList::Class()); DefineOutput(2, TList::Class()); // will contain cuts or local params } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation() { // Remove all pointers // printf("********** Delete Task\n"); // // Do not delete it here, already done somewhere else, need to understand where. // if(fOutputContainer){ // fOutputContainer->Clear() ; // delete fOutputContainer ; // } if(fAna) delete fAna; // printf("********** Task deleted \n"); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() { // Create the output container if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - Begin\n"); //Get list of aod arrays, add each aod array to analysis frame TClonesArray *array = 0; TList * list = fAna->FillAndGetAODBranchList(); //Loop the analysis and create the list of branches if (DebugLevel() >= 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - n AOD branches %d\n",list->GetEntries()); //Put the delta AODs in output file, std or delta if((fAna->GetReader())->WriteDeltaAODToFile()){ TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName(); for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++){ array = (TClonesArray*) list->At(iaod); if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file } } //Histograms container OpenFile(1); fOutputContainer = fAna->GetOutputContainer(); if (DebugLevel() >= 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - n histograms %d\n",fOutputContainer->GetEntries()); fOutputContainer->SetOwner(kTRUE); if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - End\n"); PostData(1,fOutputContainer); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::LocalInit() { // Local Initialization //Call the Init to initialize the configuration of the analysis Init(); // Create cuts/param objects and publish to slot fCuts = fAna->GetListOfAnalysisCuts(); fCuts ->SetOwner(kTRUE); // Post Data PostData(2, fCuts); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Init() { // Initialization if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - Begin\n"); // Call configuration file if specified if (fConfigName.Length()) { printf("AliAnalysisTaskParticleCorrelation::Init() - ### Configuration file is %s.C ###\n", fConfigName.Data()); gROOT->LoadMacro(fConfigName+".C"); fAna = (AliAnaPartCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()"); } if(!fAna) { printf("AliAnalysisTaskParticleCorrelation::Init() - Analysis maker pointer not initialized, no analysis specified, STOP !\n"); abort(); } // Add different generator particles to PDG Data Base // to avoid problems when reading MC generator particles AliPDG::AddParticlesToPdgDataBase(); //Set in the reader the name of the task in case is needed (fAna->GetReader())->SetTaskName(GetName()); // Initialise analysis fAna->Init(); //Delta AOD if((fAna->GetReader())->GetDeltaAODFileName()!="") AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName()); if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - End\n"); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/) { // Execute analysis for current event // if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - Begin\n"); //Get the type of data, check if type is correct Int_t datatype = fAna->GetReader()->GetDataType(); if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD && datatype != AliCaloTrackReader::kMC){ printf("AliAnalysisTaskParticleCorrelation::UserExec() - Wrong type of data\n"); return ; } fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent()); //Process event fAna->ProcessEvent((Int_t) Entry(), CurrentFileName()); //printf("AliAnalysisTaskParticleCorrelation::Current Event %d; Current File Name : %s\n",(Int_t) Entry(), CurrentFileName()); if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - End\n"); PostData(1, fOutputContainer); //gObjectTable->Print(); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/) { // Terminate analysis // Do some plots // Get merged histograms from the output container // Propagate histagrams to maker fAna->Terminate((TList*)GetOutputData(1)); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::FinishTaskOutput(){ // Put in the output some event summary histograms AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inputH = dynamic_cast<AliInputEventHandler*>(am->GetInputEventHandler()); if (!inputH) return; TH2F *histStat = dynamic_cast<TH2F*>(inputH->GetStatistics()); TH2F *histBin0 = dynamic_cast<TH2F*>(inputH->GetStatistics("BIN0")); if(histStat)fOutputContainer->Add(histStat); else printf("AliAnalysisTaskParticleCorrelation::FinishTaskOutput() - Stat histogram not available check, \n if ESDs, that AliPhysicsSelection was on, \n if AODs, if EventStat_temp.root exists \n"); if(histBin0)fOutputContainer->Add(histBin0); } <commit_msg>destructor for proof mode<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id: $ */ //_________________________________________________________________________ // Analysis task that executes the analysis classes // that depend on the PartCorr frame, frame for Particle identification and correlations. // Specially designed for calorimeters but also can be used for charged tracks // Input of this task is a configuration file that contains all the settings of the analyis // // -- Author: Gustavo Conesa (INFN-LNF) #include <cstdlib> // --- Root --- #include <TROOT.h> #include <TInterpreter.h> #include <TClonesArray.h> //#include <Riostream.h> //#include <TObjectTable.h> // --- Analysis --- #include "AliAnalysisTaskParticleCorrelation.h" #include "AliAnaPartCorrMaker.h" #include "AliCaloTrackReader.h" #include "AliPDG.h" #include "AliAnalysisManager.h" #include "AliInputEventHandler.h" ClassImp(AliAnalysisTaskParticleCorrelation) //////////////////////////////////////////////////////////////////////// AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(): AliAnalysisTaskSE(), fAna(0x0), fOutputContainer(0x0), fConfigName(""), fCuts(0x0) { // Default constructor } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name): AliAnalysisTaskSE(name), fAna(0x0), fOutputContainer(0x0), fConfigName(""), fCuts(0x0) { // Default constructor DefineOutput(1, TList::Class()); DefineOutput(2, TList::Class()); // will contain cuts or local params } //_____________________________________________________ AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation() { // Remove all pointers if (fOutputContainer && ! AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { fOutputContainer->Clear() ; delete fOutputContainer ; } if (fAna && ! AliAnalysisManager::GetAnalysisManager()->IsProofMode()) delete fAna; } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() { // Create the output container if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - Begin\n"); //Get list of aod arrays, add each aod array to analysis frame TClonesArray *array = 0; TList * list = fAna->FillAndGetAODBranchList(); //Loop the analysis and create the list of branches if (DebugLevel() >= 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - n AOD branches %d\n",list->GetEntries()); //Put the delta AODs in output file, std or delta if((fAna->GetReader())->WriteDeltaAODToFile()){ TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName(); for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++){ array = (TClonesArray*) list->At(iaod); if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file } } //Histograms container OpenFile(1); fOutputContainer = fAna->GetOutputContainer(); if (DebugLevel() >= 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - n histograms %d\n",fOutputContainer->GetEntries()); fOutputContainer->SetOwner(kTRUE); if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - End\n"); PostData(1,fOutputContainer); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::LocalInit() { // Local Initialization //Call the Init to initialize the configuration of the analysis Init(); // Create cuts/param objects and publish to slot fCuts = fAna->GetListOfAnalysisCuts(); fCuts ->SetOwner(kTRUE); // Post Data PostData(2, fCuts); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Init() { // Initialization if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - Begin\n"); // Call configuration file if specified if (fConfigName.Length()) { printf("AliAnalysisTaskParticleCorrelation::Init() - ### Configuration file is %s.C ###\n", fConfigName.Data()); gROOT->LoadMacro(fConfigName+".C"); fAna = (AliAnaPartCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()"); } if(!fAna) { printf("AliAnalysisTaskParticleCorrelation::Init() - Analysis maker pointer not initialized, no analysis specified, STOP !\n"); abort(); } // Add different generator particles to PDG Data Base // to avoid problems when reading MC generator particles AliPDG::AddParticlesToPdgDataBase(); //Set in the reader the name of the task in case is needed (fAna->GetReader())->SetTaskName(GetName()); // Initialise analysis fAna->Init(); //Delta AOD if((fAna->GetReader())->GetDeltaAODFileName()!="") AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName()); if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - End\n"); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/) { // Execute analysis for current event // if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - Begin\n"); //Get the type of data, check if type is correct Int_t datatype = fAna->GetReader()->GetDataType(); if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD && datatype != AliCaloTrackReader::kMC){ printf("AliAnalysisTaskParticleCorrelation::UserExec() - Wrong type of data\n"); return ; } fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent()); //Process event fAna->ProcessEvent((Int_t) Entry(), CurrentFileName()); //printf("AliAnalysisTaskParticleCorrelation::Current Event %d; Current File Name : %s\n",(Int_t) Entry(), CurrentFileName()); if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - End\n"); PostData(1, fOutputContainer); //gObjectTable->Print(); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/) { // Terminate analysis // Do some plots // Get merged histograms from the output container // Propagate histagrams to maker fAna->Terminate((TList*)GetOutputData(1)); } //_____________________________________________________ void AliAnalysisTaskParticleCorrelation::FinishTaskOutput(){ // Put in the output some event summary histograms AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); AliInputEventHandler *inputH = dynamic_cast<AliInputEventHandler*>(am->GetInputEventHandler()); if (!inputH) return; TH2F *histStat = dynamic_cast<TH2F*>(inputH->GetStatistics()); TH2F *histBin0 = dynamic_cast<TH2F*>(inputH->GetStatistics("BIN0")); if(histStat)fOutputContainer->Add(histStat); else printf("AliAnalysisTaskParticleCorrelation::FinishTaskOutput() - Stat histogram not available check, \n if ESDs, that AliPhysicsSelection was on, \n if AODs, if EventStat_temp.root exists \n"); if(histBin0)fOutputContainer->Add(histBin0); } <|endoftext|>
<commit_before>#include "MapSequences.h" #include <cassert> #include "cocos2d\external\tinyxml2\tinyxml2.h" using namespace std; using namespace tinyxml2; MapSequences::MapSequences() :_iCurIndex(0) { addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 0, 1); addSequences(0, 1, 0); addSequences(1, 0, 0); addSequences(1, 1, 0); addSequences(0, 1, 0); addSequences(1, 0, 0); addSequences(1, 1, 0); addSequences(0, 0, 1); addSequences(0, 1, 0); addSequences(1, 1, 0); addSequences(1, 1, 0); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 0, 1); addSequences(0, 1, 0); addSequences(1, 1, 0); addSequences(1, 1, 0); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); } MapSequences::MapSequences(const char * fileName) :_iCurIndex(0) { XMLDocument doc; doc.LoadFile(fileName); auto rootNode = doc.RootElement(); auto sequence = rootNode->FirstChildElement("SEQ"); while (sequence) { auto left = sequence->FirstChildElement("Left"); auto middle = sequence->FirstChildElement("Middle"); auto right = sequence->FirstChildElement("Right"); addSequences(atoi(left->GetText()), atoi(middle->GetText()), atoi(right->GetText())); sequence = sequence->NextSiblingElement(); } } MapSequences::~MapSequences() { } void MapSequences::addSequences(unsigned short l, unsigned short m, unsigned short r) { _vSequences.push_back(std::move(SequenceInfo(l, m, r))); } SequenceInfo MapSequences::pumpSequence() { if (_iCurIndex < _vSequences.size()) { auto seq = _vSequences[_iCurIndex]; ++_iCurIndex; return seq; } else { rewind(); return pumpSequence(); } } int MapSequences::getTotalSize() { return _vSequences.size(); } void MapSequences::rewind() { _iCurIndex = 0; }<commit_msg>New mapseq for new moving speed<commit_after>#include "MapSequences.h" #include <cassert> #include "cocos2d\external\tinyxml2\tinyxml2.h" using namespace std; using namespace tinyxml2; MapSequences::MapSequences() :_iCurIndex(0) { addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 0, 2); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 1); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 1, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(1, 0, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(1, 1, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 1, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(1, 0, 0); addSequences(1, 1, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(0, 0, 1); addSequences(0, 1, 0); addSequences(0, 2, 0); addSequences(0, 2, 0); addSequences(1, 1, 0); addSequences(1, 1, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 0, 1); addSequences(0, 0, 0); addSequences(0, 1, 0); addSequences(1, 1, 0); addSequences(1, 1, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 1, 1); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); addSequences(0, 0, 0); } MapSequences::MapSequences(const char * fileName) :_iCurIndex(0) { XMLDocument doc; doc.LoadFile(fileName); auto rootNode = doc.RootElement(); auto sequence = rootNode->FirstChildElement("SEQ"); while (sequence) { auto left = sequence->FirstChildElement("Left"); auto middle = sequence->FirstChildElement("Middle"); auto right = sequence->FirstChildElement("Right"); addSequences(atoi(left->GetText()), atoi(middle->GetText()), atoi(right->GetText())); sequence = sequence->NextSiblingElement(); } } MapSequences::~MapSequences() { } void MapSequences::addSequences(unsigned short l, unsigned short m, unsigned short r) { _vSequences.push_back(std::move(SequenceInfo(l, m, r))); } SequenceInfo MapSequences::pumpSequence() { if (_iCurIndex < _vSequences.size()) { auto seq = _vSequences[_iCurIndex]; ++_iCurIndex; return seq; } else { rewind(); return pumpSequence(); } } int MapSequences::getTotalSize() { return _vSequences.size(); } void MapSequences::rewind() { _iCurIndex = 0; }<|endoftext|>
<commit_before>#include <chili/task.h> #include <chili/plugin.xpm> #include <chili/qclightbox.h> #include <qlayout.h> #include <qstring.h> #include <mitkDataTree.h> #include <QmitkStdMultiWidget.h> //#include <mitkLightBoxImageReader.h> #include "SampleApp.h" #include "QcMITKSamplePlugin.h" #include <qlabel.h> QcMITKSamplePlugin::QcMITKSamplePlugin( QWidget *parent ) : QcPlugin( parent ) { task = new QcTask( xpm(), parent, name() ); QGridLayout* layout = new QGridLayout(task,0,0,0,-1,"plugin_area"); ap = new SampleApp(task,"sample",0); ap->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); layout->addWidget(ap,0,0,0); itkGenericOutputMacro(<<"hallo"); //funktioniert nicht: //QcLightbox* lightbox; //lightbox=lightboxManager()->getActiveLightbox(); //if(lightbox==NULL) //{ // itkGenericOutputMacro(<<"lightbox is null"); //} //else //{ // itkGenericOutputMacro(<<"lightbox is not null"); //} //connect(lightbox,SIGNAL(lightbox->lightboxActivated(QcLightbox*)),this,SLOT(selectSerie (QcLightbox*))); } QString QcMITKSamplePlugin::name() { return QString( "SampleApp" ); } const char ** QcMITKSamplePlugin::xpm() { return (const char **)plugin_xpm; } QcMITKSamplePlugin::~QcMITKSamplePlugin () { task->deleteLater(); } extern "C" QcEXPORT QObject * create( QWidget *parent ) { return new QcMITKSamplePlugin( parent ); } void QcMITKSamplePlugin::lightboxFilled (QcLightbox* lightbox) { itkGenericOutputMacro(<<"lightbox filled"); selectSerie(lightbox); } void QcMITKSamplePlugin::selectSerie (QcLightbox* lightbox) { itkGenericOutputMacro(<<"selectSerie"); ipPicDescriptor* pic; if(lightbox->getFrames()==0) return; mitk::Image::Pointer image = mitk::Image::New(); //Variante 1 pic=lightbox->fetchVolume(); image->Initialize(pic); image->SetPicVolume(pic); //Variante 2 // mitk::LightBoxImageReader::Pointer reader=mitk::LightBoxImageReader::New(); //reader->SetLightBox(lightbox); //image=reader->GetOutput(); mitk::DataTree::Pointer tree = ap->GetTree(); mitk::DataTreeIterator* it = tree->inorderIterator(); mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); it->add(node); ap->getMultiWidget()->texturizePlaneSubTree( tree->inorderIterator()); ap->getMultiWidget()->updateMitkWidgets(); ap->getMultiWidget()->fit(); } /* ipPicDescriptor* pic; QcLightbox* lightbox; mitk::LightBoxImageReader::Pointer reader=mitk::LightBoxImageReader::New(); reader->SetLightBox( connect(lightbox,lightboxReloadPics(lightbox),this,SLOT( pic= von der qclightbox mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(pic); image->SetPicVolume(pic); mitk::DataTree::Pointer tree = ap->GetTree(); mitk::DataTreeIterator* it = tree->inorderIterator(); mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); it->add(node); ap->getMultiWidget()->texturizePlaneSubTree( tree->inorderIterator()); ap->getMultiWidget()->updateMitkWidgets(); ap->getMultiWidget()->fit(); */<commit_msg>now using mitk::LightBoxImageReader<commit_after>#include <chili/task.h> #include <chili/plugin.xpm> #include <chili/qclightbox.h> #include <qlayout.h> #include <qstring.h> #include <mitkDataTree.h> #include <QmitkStdMultiWidget.h> #include <mitkLightBoxImageReader.h> #include "SampleApp.h" #include "QcMITKSamplePlugin.h" #include <qlabel.h> QcMITKSamplePlugin::QcMITKSamplePlugin( QWidget *parent ) : QcPlugin( parent ) { task = new QcTask( xpm(), parent, name() ); QGridLayout* layout = new QGridLayout(task,0,0,0,-1,"plugin_area"); ap = new SampleApp(task,"sample",0); ap->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); layout->addWidget(ap,0,0,0); itkGenericOutputMacro(<<"hallo"); //funktioniert nicht: //QcLightbox* lightbox; //lightbox=lightboxManager()->getActiveLightbox(); //if(lightbox==NULL) //{ // itkGenericOutputMacro(<<"lightbox is null"); //} //else //{ // itkGenericOutputMacro(<<"lightbox is not null"); //} //connect(lightbox,SIGNAL(lightbox->lightboxActivated(QcLightbox*)),this,SLOT(selectSerie (QcLightbox*))); } QString QcMITKSamplePlugin::name() { return QString( "SampleApp" ); } const char ** QcMITKSamplePlugin::xpm() { return (const char **)plugin_xpm; } QcMITKSamplePlugin::~QcMITKSamplePlugin () { task->deleteLater(); } extern "C" QcEXPORT QObject * create( QWidget *parent ) { return new QcMITKSamplePlugin( parent ); } void QcMITKSamplePlugin::lightboxFilled (QcLightbox* lightbox) { itkGenericOutputMacro(<<"lightbox filled"); selectSerie(lightbox); } void QcMITKSamplePlugin::selectSerie (QcLightbox* lightbox) { itkGenericOutputMacro(<<"selectSerie"); if(lightbox->getFrames()==0) return; mitk::Image::Pointer image = mitk::Image::New(); //Variante 1 //ipPicDescriptor* pic; //pic=lightbox->fetchVolume(); //image->Initialize(pic); //image->SetPicVolume(pic); //Variante 2 mitk::LightBoxImageReader::Pointer reader=mitk::LightBoxImageReader::New(); reader->SetLightBox(lightbox); image=reader->GetOutput(); image->Update(); mitk::DataTree::Pointer tree = ap->GetTree(); mitk::DataTreeIterator* it = tree->inorderIterator(); mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); it->add(node); ap->getMultiWidget()->texturizePlaneSubTree( tree->inorderIterator()); ap->getMultiWidget()->updateMitkWidgets(); ap->getMultiWidget()->fit(); } /* ipPicDescriptor* pic; QcLightbox* lightbox; mitk::LightBoxImageReader::Pointer reader=mitk::LightBoxImageReader::New(); reader->SetLightBox( connect(lightbox,lightboxReloadPics(lightbox),this,SLOT( pic= von der qclightbox mitk::Image::Pointer image = mitk::Image::New(); image->Initialize(pic); image->SetPicVolume(pic); mitk::DataTree::Pointer tree = ap->GetTree(); mitk::DataTreeIterator* it = tree->inorderIterator(); mitk::DataTreeNode::Pointer node = mitk::DataTreeNode::New(); node->SetData(image); it->add(node); ap->getMultiWidget()->texturizePlaneSubTree( tree->inorderIterator()); ap->getMultiWidget()->updateMitkWidgets(); ap->getMultiWidget()->fit(); */<|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow 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 "tensorflow/core/framework/function.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/padding.h" #include "tensorflow/core/util/tensor_format.h" namespace tensorflow { typedef FunctionDefHelper FDH; Status SoftmaxGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( "SoftmaxGrad", // Arg defs {"x: T", "grad_softmax: T"}, // Ret val defs {"grad_x: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes // Based on _SoftmaxGrad in nn_grad.py. { {{"softmax"}, "Softmax", {"x"}, {{"T", "$T"}}}, {{"n0"}, "Mul", {"grad_softmax", "softmax"}, {{"T", "$T"}}}, FDH::Const<int32>("indices", {1}), {{"n1"}, "Sum", {"n0", "indices"}, {{"T", "$T"}}}, FDH::Const<int32>("newshape", {-1, 1}), {{"n2"}, "Reshape", {"n1", "newshape"}, {{"T", "$T"}}}, {{"n3"}, "Sub", {"grad_softmax", "n2"}, {{"T", "$T"}}}, {{"grad_x"}, "Mul", {"n3", "softmax"}, {{"T", "$T"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Softmax", SoftmaxGrad); Status ReluGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"x: T", "dy: T"}, // Ret val defs {"dx: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes { {{"dx"}, "ReluGrad", {"dy", "x"}, {{"T", "$T"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Relu", ReluGrad); Status Relu6Grad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"x: T", "dy: T"}, // Ret val defs {"dx: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes { {{"dx"}, "Relu6Grad", {"dy", "x"}, {{"T", "$T"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Relu6", Relu6Grad); Status CrossEntropyGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"features: T", "labels: T", "dcost_dloss: T", "donotcare: T"}, // Ret val defs {"dcost_dfeatures: T", "dcost_dlabels: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes { // _, dloss_dfeatures = CrossEntropy(features, labels) {{"donotcare_loss", "dloss_dfeatures"}, "CrossEntropy", {"features", "labels"}, {{"T", "$T"}}}, // dcost_dloss is of shape [batch_size]. // dcost_dloss_mat is of shape [batch_size, 1]. FDH::Const("neg1", -1), {{"dcost_dloss_mat"}, "ExpandDims", {"dcost_dloss", "neg1"}, {{"T", "$T"}}}, // chain rule: dcost/dfeatures = dcost/dloss * dloss/dfeatures {{"dcost_dfeatures"}, "Mul", {"dcost_dloss_mat", "dloss_dfeatures"}, {{"T", "$T"}}}, {{"dcost_dlabels"}, "ZerosLike", {"labels"}, {{"T", "$T"}}}, }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("CrossEntropy", CrossEntropyGrad); Status Conv2DGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "filter: T", "grad: T"}, // Ret val defs {"input_grad: T", "filter_grad: T"}, // Attr defs {"T: {float, double}", "strides: list(int)", "use_cudnn_on_gpu: bool = true", GetPaddingAttrString(), GetConvnetDataFormatAttrString()}, // Nodes { {{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}}, {{"input_grad"}, "Conv2DBackpropInput", {"i_shape", "filter", "grad"}, /*Attrs=*/{{"T", "$T"}, {"strides", "$strides"}, {"padding", "$padding"}, {"data_format", "$data_format"}, {"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}}, {{"f_shape"}, "Shape", {"filter"}, {{"T", "$T"}}}, {{"filter_grad"}, "Conv2DBackpropFilter", {"input", "f_shape", "grad"}, /*Attrs=*/{{"T", "$T"}, {"strides", "$strides"}, {"padding", "$padding"}, {"data_format", "$data_format"}, {"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}}, }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Conv2D", Conv2DGrad); Status MaxPoolGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "grad: T"}, // Ret val defs {"output: T"}, // Attr defs {"T: {float, half} = DT_FLOAT", "ksize: list(int) >= 4", "strides: list(int) >= 4", GetPaddingAttrString()}, // Nodes { // Invoke MaxPool again to recompute the outputs (removed by CSE?). {{"maxpool"}, "MaxPool", {"input"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}}, {{"output"}, "MaxPoolGrad", {"input", "maxpool", "grad"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("MaxPool", MaxPoolGrad); Status MaxPoolGradGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "grad: T"}, // Ret val defs {"output: T"}, // Attr defs {"T: {float, half} = DT_FLOAT", "ksize: list(int) >= 4", "strides: list(int) >= 4", GetPaddingAttrString()}, // Nodes { // Invoke MaxPool again to recompute the outputs (removed by CSE?). {{"maxpool"}, "MaxPool", {"input"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}}, {{"output"}, "MaxPoolGradGrad", {"input", "maxpool", "grad"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("MaxPoolGrad", MaxPoolGradGrad); } // end namespace tensorflow <commit_msg>Add function gradients for AvgPool and BiasAdd. Change: 153533625<commit_after>/* Copyright 2015 The TensorFlow 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 "tensorflow/core/framework/function.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/padding.h" #include "tensorflow/core/util/tensor_format.h" namespace tensorflow { typedef FunctionDefHelper FDH; Status SoftmaxGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( "SoftmaxGrad", // Arg defs {"x: T", "grad_softmax: T"}, // Ret val defs {"grad_x: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes // Based on _SoftmaxGrad in nn_grad.py. { {{"softmax"}, "Softmax", {"x"}, {{"T", "$T"}}}, {{"n0"}, "Mul", {"grad_softmax", "softmax"}, {{"T", "$T"}}}, FDH::Const<int32>("indices", {1}), {{"n1"}, "Sum", {"n0", "indices"}, {{"T", "$T"}}}, FDH::Const<int32>("newshape", {-1, 1}), {{"n2"}, "Reshape", {"n1", "newshape"}, {{"T", "$T"}}}, {{"n3"}, "Sub", {"grad_softmax", "n2"}, {{"T", "$T"}}}, {{"grad_x"}, "Mul", {"n3", "softmax"}, {{"T", "$T"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Softmax", SoftmaxGrad); Status ReluGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"x: T", "dy: T"}, // Ret val defs {"dx: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes { {{"dx"}, "ReluGrad", {"dy", "x"}, {{"T", "$T"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Relu", ReluGrad); Status Relu6Grad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"x: T", "dy: T"}, // Ret val defs {"dx: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes { {{"dx"}, "Relu6Grad", {"dy", "x"}, {{"T", "$T"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Relu6", Relu6Grad); Status CrossEntropyGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"features: T", "labels: T", "dcost_dloss: T", "donotcare: T"}, // Ret val defs {"dcost_dfeatures: T", "dcost_dlabels: T"}, // Attr defs {{"T: {float, double}"}}, // Nodes { // _, dloss_dfeatures = CrossEntropy(features, labels) {{"donotcare_loss", "dloss_dfeatures"}, "CrossEntropy", {"features", "labels"}, {{"T", "$T"}}}, // dcost_dloss is of shape [batch_size]. // dcost_dloss_mat is of shape [batch_size, 1]. FDH::Const("neg1", -1), {{"dcost_dloss_mat"}, "ExpandDims", {"dcost_dloss", "neg1"}, {{"T", "$T"}}}, // chain rule: dcost/dfeatures = dcost/dloss * dloss/dfeatures {{"dcost_dfeatures"}, "Mul", {"dcost_dloss_mat", "dloss_dfeatures"}, {{"T", "$T"}}}, {{"dcost_dlabels"}, "ZerosLike", {"labels"}, {{"T", "$T"}}}, }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("CrossEntropy", CrossEntropyGrad); Status Conv2DGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "filter: T", "grad: T"}, // Ret val defs {"input_grad: T", "filter_grad: T"}, // Attr defs {"T: {float, double}", "strides: list(int)", "use_cudnn_on_gpu: bool = true", GetPaddingAttrString(), GetConvnetDataFormatAttrString()}, // Nodes { {{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}}, {{"input_grad"}, "Conv2DBackpropInput", {"i_shape", "filter", "grad"}, /*Attrs=*/{{"T", "$T"}, {"strides", "$strides"}, {"padding", "$padding"}, {"data_format", "$data_format"}, {"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}}, {{"f_shape"}, "Shape", {"filter"}, {{"T", "$T"}}}, {{"filter_grad"}, "Conv2DBackpropFilter", {"input", "f_shape", "grad"}, /*Attrs=*/{{"T", "$T"}, {"strides", "$strides"}, {"padding", "$padding"}, {"data_format", "$data_format"}, {"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}}, }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("Conv2D", Conv2DGrad); Status MaxPoolGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "grad: T"}, // Ret val defs {"output: T"}, // Attr defs {"T: {float, half} = DT_FLOAT", "ksize: list(int) >= 4", "strides: list(int) >= 4", GetPaddingAttrString()}, // Nodes { // Invoke MaxPool again to recompute the outputs (removed by CSE?). {{"maxpool"}, "MaxPool", {"input"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}}, {{"output"}, "MaxPoolGrad", {"input", "maxpool", "grad"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("MaxPool", MaxPoolGrad); Status AvgPoolGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "grad: T"}, // Ret val defs {"output: T"}, // Attr defs {"T: {float, half} = DT_FLOAT", "ksize: list(int) >= 4", "strides: list(int) >= 4", GetPaddingAttrString()}, // Nodes { {{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}}, {{"output"}, "AvgPoolGrad", {"i_shape", "grad"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("AvgPool", AvgPoolGrad); Status MaxPoolGradGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "grad: T"}, // Ret val defs {"output: T"}, // Attr defs {"T: {float, half} = DT_FLOAT", "ksize: list(int) >= 4", "strides: list(int) >= 4", GetPaddingAttrString()}, // Nodes { // Invoke MaxPool again to recompute the outputs (removed by CSE?). {{"maxpool"}, "MaxPool", {"input"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}}, {{"output"}, "MaxPoolGradGrad", {"input", "maxpool", "grad"}, /*Attrs=*/{{"T", "$T"}, {"ksize", "$ksize"}, {"strides", "$strides"}, {"padding", "$padding"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("MaxPoolGrad", MaxPoolGradGrad); Status BiasAddGrad(const AttrSlice& attrs, FunctionDef* g) { // clang-format off *g = FDH::Define( // Arg defs {"input: T", "bias: T", "grad: T"}, // Ret val defs {"grad: T", "bias_grad: T"}, // Attr defs {{"T: {float, double}"}, GetConvnetDataFormatAttrString()}, // Nodes { {{"bias_grad"}, "BiasAddGrad", {"grad"}, /*Attrs=*/{{"T", "$T"}, {"data_format", "$data_format"}}} }); // clang-format on return Status::OK(); } REGISTER_OP_GRADIENT("BiasAdd", BiasAddGrad); } // end namespace tensorflow <|endoftext|>
<commit_before>/* This is an example file shipped by 'Aleph - A Library for Exporing Persistent Homology'. This example demonstrates how to load a VTK structured grid from a file, convert it into a simplicial complex, and calculate its persistent homology. Demonstrated classes: - aleph::PersistenceDiagram - aleph::topology::Simplex - aleph::topology::SimplicialComplex - aleph::topology::VTKStructuredGridReader Demonstrated functions: - aleph::calculatePersistenceDiagrams - aleph::utilities::extension - Simplicial complex sorting (for filtrations) Original author: Bastian Rieck */ #include "persistenceDiagrams/PersistenceDiagram.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/VTK.hh" #include <iostream> #include <string> #include <getopt.h> void usage() { std::cerr << "Usage: vtk [--superlevels] [--sublevels] FILE\n" << "\n" << "Calculates persistent homology of an input file. This program only\n" << "handles VTK files. The output is a persistence diagram and will be\n" << "written to STDOUT.\n\n" << "Flags:\n" << " -S --superlevels: calculate superlevel sets\n" << " -s --sublevels : calculate sublevel sets\n" << "\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "superlevels", no_argument, nullptr, 'S' }, { "sublevels" , no_argument, nullptr, 's' }, { nullptr , 0 , nullptr, 0 } }; bool calculateSuperlevelSets = false; int option = 0; while( ( option = getopt_long( argc, argv, "Ss", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'S': calculateSuperlevelSets = true; break; case 's': calculateSuperlevelSets = false; break; default: break; } } if( ( argc - optind ) <= 0 ) { usage(); return -1; } } <commit_msg>Extended VTK example<commit_after>/* This is an example file shipped by 'Aleph - A Library for Exporing Persistent Homology'. This example demonstrates how to load a VTK structured grid from a file, convert it into a simplicial complex, and calculate its persistent homology. Demonstrated classes: - aleph::PersistenceDiagram - aleph::topology::Simplex - aleph::topology::SimplicialComplex - aleph::topology::VTKStructuredGridReader Demonstrated functions: - aleph::calculatePersistenceDiagrams - aleph::utilities::extension - Simplicial complex sorting (for filtrations) Original author: Bastian Rieck */ #include "persistenceDiagrams/PersistenceDiagram.hh" #include "persistentHomology/Calculation.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/filtrations/Data.hh" #include "topology/io/VTK.hh" #include <functional> #include <iostream> #include <string> #include <getopt.h> void usage() { std::cerr << "Usage: vtk [--superlevels] [--sublevels] FILE\n" << "\n" << "Calculates persistent homology of an input file. This program only\n" << "handles VTK files. The output is a persistence diagram and will be\n" << "written to STDOUT.\n\n" << "Flags:\n" << " -S --superlevels: calculate superlevel sets\n" << " -s --sublevels : calculate sublevel sets\n" << "\n"; } int main( int argc, char** argv ) { static option commandLineOptions[] = { { "superlevels", no_argument, nullptr, 'S' }, { "sublevels" , no_argument, nullptr, 's' }, { nullptr , 0 , nullptr, 0 } }; bool calculateSuperlevelSets = false; int option = 0; while( ( option = getopt_long( argc, argv, "Ss", commandLineOptions, nullptr ) ) != -1 ) { switch( option ) { case 'S': calculateSuperlevelSets = true; break; case 's': calculateSuperlevelSets = false; break; default: break; } } if( ( argc - optind ) <= 0 ) { usage(); return -1; } std::string filename = argv[optind]; // Since all data types in Aleph are templated, you need to decide // which types to use beforehand---or use more advanced constructs // like a type switch over a list of admissible types. using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; // Select a functor for calculating the weights when reading // a simplicial complex. // // This is an optional argument for the main operator of the // structured grid reader class. It is used to determine the // weight of an edge. // // Since sublevel sets 'grow' from small to large weights, a // correct assignment uses the `max()` function. Analogously // the `min()` function is used for superlevel sets. // // If you do not specify this functor, sublevel sets will be // calculated by default. auto functor = calculateSuperlevelSets ? [] ( DataType a, DataType b ) { return std::min(a,b); } : [] ( DataType a, DataType b ) { return std::max(a,b); }; std::cerr << "* Loading '" << filename << "'..."; SimplicialComplex K; aleph::topology::io::VTKStructuredGridReader reader; reader( filename, K, functor ); std::cerr << "finished\n"; std::cerr << "* Calculating persistent homology..."; // Sort superlevel sets from largest to smallest weight... if( calculateSuperlevelSets ) K.sort( aleph::topology::filtrations::Data<Simplex, std::greater<DataType> >() ); // ...and sublevel sets from smallest to largest. else K.sort( aleph::topology::filtrations::Data<Simplex, std::less<DataType> >() ); auto persistenceDiagrams = aleph::calculatePersistenceDiagrams( K ); std::cerr << "finished\n"; for( auto&& D : persistenceDiagrams ) { // Remove all features with a persistence of zero. This is not // strictly required but it helps unclutter the diagram. D.removeDiagonal(); std::cout << D << "\n"; } } <|endoftext|>
<commit_before>#include "gmock/gmock.h" #include "CommandRecognizer.h" #include "CommandMetadata.h" #include "util/XPlaneDataRefSDKMock.h" using namespace testing; using namespace xcopilot; class CommandRecognizerTest : public Test { protected: NiceMock<XPlaneDataRefSDKMock> xPlaneDataRefSDKMock; CommandRecognizer commandRecognizer; CommandRecognizerTest() : xPlaneDataRefSDKMock{}, commandRecognizer(CommandMetadata("Test", CommandType::FLOAT, "^.*test$", {})) {}; }; TEST_F(CommandRecognizerTest, RecognizeCommandWhenPhraseDoesMatchRegEx) { ASSERT_THAT(commandRecognizer.commandRecognized("a test"), Eq(true)); } TEST_F(CommandRecognizerTest, DoesNotRecognizeCommandWhenPhraseDoesNotMatchRegEx) { ASSERT_THAT(commandRecognizer.commandRecognized("does not match"), Eq(false)); } <commit_msg>fix CommandRecognizerTest<commit_after>#include "gmock/gmock.h" #include "CommandRecognizer.h" #include "CommandMetadata.h" using namespace testing; using namespace xcopilot; class CommandRecognizerTest : public Test { public: CommandRecognizerTest() : commandRecognizer(CommandMetadata("Test", CommandType::FLOAT, "^.*test$", {})) {}; protected: CommandRecognizer commandRecognizer; }; TEST_F(CommandRecognizerTest, RecognizeCommandWhenPhraseDoesMatchRegEx) { ASSERT_THAT(commandRecognizer.commandRecognized("a test"), Eq(true)); } TEST_F(CommandRecognizerTest, DoesNotRecognizeCommandWhenPhraseDoesNotMatchRegEx) { ASSERT_THAT(commandRecognizer.commandRecognized("does not match"), Eq(false)); } <|endoftext|>
<commit_before>//===--- DerivedConformanceAdditiveArithmetic.cpp -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements explicit derivation of the AdditiveArithmetic protocol // for struct types. // // Currently, this is gated by a frontend flag: // `-enable-experimental-additive-arithmetic-derivation`. // // Swift Evolution pitch thread: // https://forums.swift.org/t/additivearithmetic-conformance-synthesis-for-structs/26159 // //===----------------------------------------------------------------------===// #include "CodeSynthesis.h" #include "TypeChecker.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/Module.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Pattern.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/Stmt.h" #include "swift/AST/Types.h" #include "DerivedConformances.h" using namespace swift; // Represents synthesizable math operators. enum MathOperator { // `+(Self, Self)`: AdditiveArithmetic Add, // `-(Self, Self)`: AdditiveArithmetic Subtract, }; static StringRef getMathOperatorName(MathOperator op) { switch (op) { case Add: return "+"; case Subtract: return "-"; } llvm_unreachable("invalid math operator kind"); } bool DerivedConformance::canDeriveAdditiveArithmetic(NominalTypeDecl *nominal, DeclContext *DC) { // Experimental `AdditiveArithmetic` derivation must be enabled. if (auto *SF = DC->getParentSourceFile()) if (!isAdditiveArithmeticConformanceDerivationEnabled(*SF)) return false; // Nominal type must be a struct. (No stored properties is okay.) auto *structDecl = dyn_cast<StructDecl>(nominal); if (!structDecl) return false; // Must not have any `let` stored properties with an initial value. // - This restriction may be lifted later with support for "true" memberwise // initializers that initialize all stored properties, including initial // value information. if (hasLetStoredPropertyWithInitialValue(nominal)) return false; // All stored properties must conform to `AdditiveArithmetic`. auto &C = nominal->getASTContext(); auto *proto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic); return llvm::all_of(structDecl->getStoredProperties(), [&](VarDecl *v) { if (v->getInterfaceType()->hasError()) return false; auto varType = DC->mapTypeIntoContext(v->getValueInterfaceType()); return (bool)TypeChecker::conformsToProtocol(varType, proto, DC); }); } // Synthesize body for math operator. static std::pair<BraceStmt *, bool> deriveBodyMathOperator(AbstractFunctionDecl *funcDecl, MathOperator op) { auto *parentDC = funcDecl->getParent(); auto *nominal = parentDC->getSelfNominalTypeDecl(); auto &C = nominal->getASTContext(); // Create memberwise initializer: `Nominal.init(...)`. auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer(); assert(memberwiseInitDecl && "Memberwise initializer must exist"); auto *initDRE = new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true); initDRE->setFunctionRefKind(FunctionRefKind::SingleApply); auto *nominalTypeExpr = TypeExpr::createImplicitForDecl( DeclNameLoc(), nominal, funcDecl, funcDecl->mapTypeIntoContext(nominal->getInterfaceType())); auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr); // Get operator protocol requirement. auto *proto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic); auto operatorId = C.getIdentifier(getMathOperatorName(op)); auto *operatorReq = getProtocolRequirement(proto, operatorId); // Create reference to operator parameters: lhs and rhs. auto params = funcDecl->getParameters(); // Create expression combining lhs and rhs members using member operator. auto createMemberOpExpr = [&](VarDecl *member) -> Expr * { auto module = nominal->getModuleContext(); auto memberType = parentDC->mapTypeIntoContext(member->getValueInterfaceType()); auto confRef = module->lookupConformance(memberType, proto); assert(confRef && "Member does not conform to math protocol"); // Get member type's math operator, e.g. `Member.+`. // Use protocol requirement declaration for the operator by default: this // will be dynamically dispatched. ValueDecl *memberOpDecl = operatorReq; // If conformance reference is concrete, then use concrete witness // declaration for the operator. if (confRef.isConcrete()) if (auto *concreteMemberMethodDecl = confRef.getConcrete()->getWitnessDecl(operatorReq)) memberOpDecl = concreteMemberMethodDecl; assert(memberOpDecl && "Member operator declaration must exist"); auto *memberTypeExpr = TypeExpr::createImplicit(memberType, C); auto memberOpExpr = new (C) MemberRefExpr(memberTypeExpr, SourceLoc(), memberOpDecl, DeclNameLoc(), /*Implicit*/ true); // Create expression `lhs.member <op> rhs.member`. // NOTE(TF-1054): create new `DeclRefExpr`s per loop iteration to avoid // `ConstraintSystem::resolveOverload` error. auto *lhsDRE = new (C) DeclRefExpr(params->get(0), DeclNameLoc(), /*Implicit*/ true); auto *rhsDRE = new (C) DeclRefExpr(params->get(1), DeclNameLoc(), /*Implicit*/ true); Expr *lhsArg = new (C) MemberRefExpr(lhsDRE, SourceLoc(), member, DeclNameLoc(), /*Implicit*/ true); auto *rhsArg = new (C) MemberRefExpr(rhsDRE, SourceLoc(), member, DeclNameLoc(), /*Implicit*/ true); auto *memberOpArgs = TupleExpr::create(C, SourceLoc(), {lhsArg, rhsArg}, {}, {}, SourceLoc(), /*HasTrailingClosure*/ false, /*Implicit*/ true); auto *memberOpCallExpr = new (C) BinaryExpr(memberOpExpr, memberOpArgs, /*Implicit*/ true); return memberOpCallExpr; }; // Create array of member operator call expressions. llvm::SmallVector<Expr *, 2> memberOpExprs; llvm::SmallVector<Identifier, 2> memberNames; for (auto member : nominal->getStoredProperties()) { memberOpExprs.push_back(createMemberOpExpr(member)); memberNames.push_back(member->getName()); } // Call memberwise initializer with member operator call expressions. auto *callExpr = CallExpr::createImplicit(C, initExpr, memberOpExprs, memberNames); ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true); return std::pair<BraceStmt *, bool>( BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true), false); } // Synthesize function declaration for the given math operator. static ValueDecl *deriveMathOperator(DerivedConformance &derived, MathOperator op) { auto nominal = derived.Nominal; auto parentDC = derived.getConformanceContext(); auto &C = derived.Context; auto selfInterfaceType = parentDC->getDeclaredInterfaceType(); // Create parameter declaration with the given name and type. auto createParamDecl = [&](StringRef name, Type type) -> ParamDecl * { auto *param = new (C) ParamDecl(SourceLoc(), SourceLoc(), Identifier(), SourceLoc(), C.getIdentifier(name), parentDC); param->setSpecifier(ParamDecl::Specifier::Default); param->setInterfaceType(type); param->setImplicit(); return param; }; ParameterList *params = ParameterList::create(C, {createParamDecl("lhs", selfInterfaceType), createParamDecl("rhs", selfInterfaceType)}); auto operatorId = C.getIdentifier(getMathOperatorName(op)); DeclName operatorDeclName(C, operatorId, params); auto *const operatorDecl = FuncDecl::createImplicit( C, StaticSpellingKind::KeywordStatic, operatorDeclName, /*NameLoc=*/SourceLoc(), /*Async=*/false, /*Throws=*/false, /*GenericParams=*/nullptr, params, selfInterfaceType, parentDC); auto bodySynthesizer = [](AbstractFunctionDecl *funcDecl, void *ctx) -> std::pair<BraceStmt *, bool> { auto op = (MathOperator) reinterpret_cast<intptr_t>(ctx); return deriveBodyMathOperator(funcDecl, op); }; operatorDecl->setBodySynthesizer(bodySynthesizer, (void *)op); operatorDecl->setGenericSignature(parentDC->getGenericSignatureOfContext()); operatorDecl->copyFormalAccessFrom(nominal, /*sourceIsParentContext*/ true); derived.addMembersToConformanceContext({operatorDecl}); return operatorDecl; } // Synthesize body for a property computed property getter. static std::pair<BraceStmt *, bool> deriveBodyPropertyGetter(AbstractFunctionDecl *funcDecl, ProtocolDecl *proto, ValueDecl *reqDecl) { auto *parentDC = funcDecl->getParent(); auto *nominal = parentDC->getSelfNominalTypeDecl(); auto &C = nominal->getASTContext(); auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer(); assert(memberwiseInitDecl && "Memberwise initializer must exist"); auto *initDRE = new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true); initDRE->setFunctionRefKind(FunctionRefKind::SingleApply); auto *nominalTypeExpr = TypeExpr::createImplicitForDecl( DeclNameLoc(), nominal, funcDecl, funcDecl->mapTypeIntoContext(nominal->getInterfaceType())); auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr); auto createMemberPropertyExpr = [&](VarDecl *member) -> Expr * { auto memberType = parentDC->mapTypeIntoContext(member->getValueInterfaceType()); Expr *memberExpr = nullptr; // If the property is static, create a type expression: `Member`. if (reqDecl->isStatic()) { memberExpr = TypeExpr::createImplicit(memberType, C); } // If the property is not static, create a member ref expression: // `self.member`. else { auto *selfDecl = funcDecl->getImplicitSelfDecl(); auto *selfDRE = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*Implicit*/ true); memberExpr = new (C) MemberRefExpr(selfDRE, SourceLoc(), member, DeclNameLoc(), /*Implicit*/ true); } auto *module = nominal->getModuleContext(); auto confRef = module->lookupConformance(memberType, proto); assert(confRef && "Member does not conform to `AdditiveArithmetic`"); // If conformance reference is not concrete, then concrete witness // declaration for property cannot be resolved. Return reference to // protocol requirement: this will be dynamically dispatched. if (!confRef.isConcrete()) { return new (C) MemberRefExpr(memberExpr, SourceLoc(), reqDecl, DeclNameLoc(), /*Implicit*/ true); } // Otherwise, return reference to concrete witness declaration. auto conf = confRef.getConcrete(); auto *witnessDecl = conf->getWitnessDecl(reqDecl); return new (C) MemberRefExpr(memberExpr, SourceLoc(), witnessDecl, DeclNameLoc(), /*Implicit*/ true); }; // Create array of `member.<property>` expressions. llvm::SmallVector<Expr *, 2> memberPropExprs; llvm::SmallVector<Identifier, 2> memberNames; for (auto member : nominal->getStoredProperties()) { memberPropExprs.push_back(createMemberPropertyExpr(member)); memberNames.push_back(member->getName()); } // Call memberwise initializer with member property expressions. auto *callExpr = CallExpr::createImplicit(C, initExpr, memberPropExprs, memberNames); ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true); auto *braceStmt = BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true); return std::pair<BraceStmt *, bool>(braceStmt, false); } // Synthesize body for the `AdditiveArithmetic.zero` computed property getter. static std::pair<BraceStmt *, bool> deriveBodyAdditiveArithmetic_zero(AbstractFunctionDecl *funcDecl, void *) { auto &C = funcDecl->getASTContext(); auto *addArithProto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic); auto *zeroReq = getProtocolRequirement(addArithProto, C.Id_zero); return deriveBodyPropertyGetter(funcDecl, addArithProto, zeroReq); } // Synthesize the static property declaration for `AdditiveArithmetic.zero`. static ValueDecl *deriveAdditiveArithmetic_zero(DerivedConformance &derived) { auto &C = derived.Context; auto *nominal = derived.Nominal; auto *parentDC = derived.getConformanceContext(); auto returnInterfaceTy = nominal->getDeclaredInterfaceType(); auto returnTy = parentDC->mapTypeIntoContext(returnInterfaceTy); // Create property declaration. VarDecl *propDecl; PatternBindingDecl *pbDecl; std::tie(propDecl, pbDecl) = derived.declareDerivedProperty( C.Id_zero, returnInterfaceTy, returnTy, /*isStatic*/ true, /*isFinal*/ true); // Create property getter. auto *getterDecl = derived.addGetterToReadOnlyDerivedProperty(propDecl, returnTy); getterDecl->setBodySynthesizer(deriveBodyAdditiveArithmetic_zero, nullptr); derived.addMembersToConformanceContext({propDecl, pbDecl}); return propDecl; } ValueDecl * DerivedConformance::deriveAdditiveArithmetic(ValueDecl *requirement) { // Diagnose conformances in disallowed contexts. if (checkAndDiagnoseDisallowedContext(requirement)) return nullptr; if (requirement->getBaseName() == Context.getIdentifier("+")) return deriveMathOperator(*this, Add); if (requirement->getBaseName() == Context.getIdentifier("-")) return deriveMathOperator(*this, Subtract); if (requirement->getBaseName() == Context.Id_zero) return deriveAdditiveArithmetic_zero(*this); Context.Diags.diagnose(requirement->getLoc(), diag::broken_additive_arithmetic_requirement); return nullptr; } <commit_msg>AutoDiff: Synthesize the memberwise initializer earlier<commit_after>//===--- DerivedConformanceAdditiveArithmetic.cpp -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements explicit derivation of the AdditiveArithmetic protocol // for struct types. // // Currently, this is gated by a frontend flag: // `-enable-experimental-additive-arithmetic-derivation`. // // Swift Evolution pitch thread: // https://forums.swift.org/t/additivearithmetic-conformance-synthesis-for-structs/26159 // //===----------------------------------------------------------------------===// #include "CodeSynthesis.h" #include "TypeChecker.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/Module.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Pattern.h" #include "swift/AST/ProtocolConformance.h" #include "swift/AST/Stmt.h" #include "swift/AST/Types.h" #include "DerivedConformances.h" using namespace swift; // Represents synthesizable math operators. enum MathOperator { // `+(Self, Self)`: AdditiveArithmetic Add, // `-(Self, Self)`: AdditiveArithmetic Subtract, }; static StringRef getMathOperatorName(MathOperator op) { switch (op) { case Add: return "+"; case Subtract: return "-"; } llvm_unreachable("invalid math operator kind"); } bool DerivedConformance::canDeriveAdditiveArithmetic(NominalTypeDecl *nominal, DeclContext *DC) { // Experimental `AdditiveArithmetic` derivation must be enabled. if (auto *SF = DC->getParentSourceFile()) if (!isAdditiveArithmeticConformanceDerivationEnabled(*SF)) return false; // Nominal type must be a struct. (No stored properties is okay.) auto *structDecl = dyn_cast<StructDecl>(nominal); if (!structDecl) return false; // Must not have any `let` stored properties with an initial value. // - This restriction may be lifted later with support for "true" memberwise // initializers that initialize all stored properties, including initial // value information. if (hasLetStoredPropertyWithInitialValue(nominal)) return false; // All stored properties must conform to `AdditiveArithmetic`. auto &C = nominal->getASTContext(); auto *proto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic); return llvm::all_of(structDecl->getStoredProperties(), [&](VarDecl *v) { if (v->getInterfaceType()->hasError()) return false; auto varType = DC->mapTypeIntoContext(v->getValueInterfaceType()); return (bool)TypeChecker::conformsToProtocol(varType, proto, DC); }); } // Synthesize body for math operator. static std::pair<BraceStmt *, bool> deriveBodyMathOperator(AbstractFunctionDecl *funcDecl, MathOperator op) { auto *parentDC = funcDecl->getParent(); auto *nominal = parentDC->getSelfNominalTypeDecl(); auto &C = nominal->getASTContext(); // Create memberwise initializer: `Nominal.init(...)`. auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer(); assert(memberwiseInitDecl && "Memberwise initializer must exist"); auto *initDRE = new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true); initDRE->setFunctionRefKind(FunctionRefKind::SingleApply); auto *nominalTypeExpr = TypeExpr::createImplicitForDecl( DeclNameLoc(), nominal, funcDecl, funcDecl->mapTypeIntoContext(nominal->getInterfaceType())); auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr); // Get operator protocol requirement. auto *proto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic); auto operatorId = C.getIdentifier(getMathOperatorName(op)); auto *operatorReq = getProtocolRequirement(proto, operatorId); // Create reference to operator parameters: lhs and rhs. auto params = funcDecl->getParameters(); // Create expression combining lhs and rhs members using member operator. auto createMemberOpExpr = [&](VarDecl *member) -> Expr * { auto module = nominal->getModuleContext(); auto memberType = parentDC->mapTypeIntoContext(member->getValueInterfaceType()); auto confRef = module->lookupConformance(memberType, proto); assert(confRef && "Member does not conform to math protocol"); // Get member type's math operator, e.g. `Member.+`. // Use protocol requirement declaration for the operator by default: this // will be dynamically dispatched. ValueDecl *memberOpDecl = operatorReq; // If conformance reference is concrete, then use concrete witness // declaration for the operator. if (confRef.isConcrete()) if (auto *concreteMemberMethodDecl = confRef.getConcrete()->getWitnessDecl(operatorReq)) memberOpDecl = concreteMemberMethodDecl; assert(memberOpDecl && "Member operator declaration must exist"); auto *memberTypeExpr = TypeExpr::createImplicit(memberType, C); auto memberOpExpr = new (C) MemberRefExpr(memberTypeExpr, SourceLoc(), memberOpDecl, DeclNameLoc(), /*Implicit*/ true); // Create expression `lhs.member <op> rhs.member`. // NOTE(TF-1054): create new `DeclRefExpr`s per loop iteration to avoid // `ConstraintSystem::resolveOverload` error. auto *lhsDRE = new (C) DeclRefExpr(params->get(0), DeclNameLoc(), /*Implicit*/ true); auto *rhsDRE = new (C) DeclRefExpr(params->get(1), DeclNameLoc(), /*Implicit*/ true); Expr *lhsArg = new (C) MemberRefExpr(lhsDRE, SourceLoc(), member, DeclNameLoc(), /*Implicit*/ true); auto *rhsArg = new (C) MemberRefExpr(rhsDRE, SourceLoc(), member, DeclNameLoc(), /*Implicit*/ true); auto *memberOpArgs = TupleExpr::create(C, SourceLoc(), {lhsArg, rhsArg}, {}, {}, SourceLoc(), /*HasTrailingClosure*/ false, /*Implicit*/ true); auto *memberOpCallExpr = new (C) BinaryExpr(memberOpExpr, memberOpArgs, /*Implicit*/ true); return memberOpCallExpr; }; // Create array of member operator call expressions. llvm::SmallVector<Expr *, 2> memberOpExprs; llvm::SmallVector<Identifier, 2> memberNames; for (auto member : nominal->getStoredProperties()) { memberOpExprs.push_back(createMemberOpExpr(member)); memberNames.push_back(member->getName()); } // Call memberwise initializer with member operator call expressions. auto *callExpr = CallExpr::createImplicit(C, initExpr, memberOpExprs, memberNames); ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true); return std::pair<BraceStmt *, bool>( BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true), false); } // Synthesize function declaration for the given math operator. static ValueDecl *deriveMathOperator(DerivedConformance &derived, MathOperator op) { auto nominal = derived.Nominal; auto parentDC = derived.getConformanceContext(); auto &C = derived.Context; auto selfInterfaceType = parentDC->getDeclaredInterfaceType(); // Create parameter declaration with the given name and type. auto createParamDecl = [&](StringRef name, Type type) -> ParamDecl * { auto *param = new (C) ParamDecl(SourceLoc(), SourceLoc(), Identifier(), SourceLoc(), C.getIdentifier(name), parentDC); param->setSpecifier(ParamDecl::Specifier::Default); param->setInterfaceType(type); param->setImplicit(); return param; }; ParameterList *params = ParameterList::create(C, {createParamDecl("lhs", selfInterfaceType), createParamDecl("rhs", selfInterfaceType)}); auto operatorId = C.getIdentifier(getMathOperatorName(op)); DeclName operatorDeclName(C, operatorId, params); auto *const operatorDecl = FuncDecl::createImplicit( C, StaticSpellingKind::KeywordStatic, operatorDeclName, /*NameLoc=*/SourceLoc(), /*Async=*/false, /*Throws=*/false, /*GenericParams=*/nullptr, params, selfInterfaceType, parentDC); auto bodySynthesizer = [](AbstractFunctionDecl *funcDecl, void *ctx) -> std::pair<BraceStmt *, bool> { auto op = (MathOperator) reinterpret_cast<intptr_t>(ctx); return deriveBodyMathOperator(funcDecl, op); }; operatorDecl->setBodySynthesizer(bodySynthesizer, (void *)op); operatorDecl->setGenericSignature(parentDC->getGenericSignatureOfContext()); operatorDecl->copyFormalAccessFrom(nominal, /*sourceIsParentContext*/ true); derived.addMembersToConformanceContext({operatorDecl}); // For the effective memberwise initializer before we force the body, // so that it becomes part of the emitted ABI members even if we don't // emit the body. (void) nominal->getEffectiveMemberwiseInitializer(); return operatorDecl; } // Synthesize body for a property computed property getter. static std::pair<BraceStmt *, bool> deriveBodyPropertyGetter(AbstractFunctionDecl *funcDecl, ProtocolDecl *proto, ValueDecl *reqDecl) { auto *parentDC = funcDecl->getParent(); auto *nominal = parentDC->getSelfNominalTypeDecl(); auto &C = nominal->getASTContext(); auto *memberwiseInitDecl = nominal->getEffectiveMemberwiseInitializer(); assert(memberwiseInitDecl && "Memberwise initializer must exist"); auto *initDRE = new (C) DeclRefExpr(memberwiseInitDecl, DeclNameLoc(), /*Implicit*/ true); initDRE->setFunctionRefKind(FunctionRefKind::SingleApply); auto *nominalTypeExpr = TypeExpr::createImplicitForDecl( DeclNameLoc(), nominal, funcDecl, funcDecl->mapTypeIntoContext(nominal->getInterfaceType())); auto *initExpr = new (C) ConstructorRefCallExpr(initDRE, nominalTypeExpr); auto createMemberPropertyExpr = [&](VarDecl *member) -> Expr * { auto memberType = parentDC->mapTypeIntoContext(member->getValueInterfaceType()); Expr *memberExpr = nullptr; // If the property is static, create a type expression: `Member`. if (reqDecl->isStatic()) { memberExpr = TypeExpr::createImplicit(memberType, C); } // If the property is not static, create a member ref expression: // `self.member`. else { auto *selfDecl = funcDecl->getImplicitSelfDecl(); auto *selfDRE = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*Implicit*/ true); memberExpr = new (C) MemberRefExpr(selfDRE, SourceLoc(), member, DeclNameLoc(), /*Implicit*/ true); } auto *module = nominal->getModuleContext(); auto confRef = module->lookupConformance(memberType, proto); assert(confRef && "Member does not conform to `AdditiveArithmetic`"); // If conformance reference is not concrete, then concrete witness // declaration for property cannot be resolved. Return reference to // protocol requirement: this will be dynamically dispatched. if (!confRef.isConcrete()) { return new (C) MemberRefExpr(memberExpr, SourceLoc(), reqDecl, DeclNameLoc(), /*Implicit*/ true); } // Otherwise, return reference to concrete witness declaration. auto conf = confRef.getConcrete(); auto *witnessDecl = conf->getWitnessDecl(reqDecl); return new (C) MemberRefExpr(memberExpr, SourceLoc(), witnessDecl, DeclNameLoc(), /*Implicit*/ true); }; // Create array of `member.<property>` expressions. llvm::SmallVector<Expr *, 2> memberPropExprs; llvm::SmallVector<Identifier, 2> memberNames; for (auto member : nominal->getStoredProperties()) { memberPropExprs.push_back(createMemberPropertyExpr(member)); memberNames.push_back(member->getName()); } // Call memberwise initializer with member property expressions. auto *callExpr = CallExpr::createImplicit(C, initExpr, memberPropExprs, memberNames); ASTNode returnStmt = new (C) ReturnStmt(SourceLoc(), callExpr, true); auto *braceStmt = BraceStmt::create(C, SourceLoc(), returnStmt, SourceLoc(), true); return std::pair<BraceStmt *, bool>(braceStmt, false); } // Synthesize body for the `AdditiveArithmetic.zero` computed property getter. static std::pair<BraceStmt *, bool> deriveBodyAdditiveArithmetic_zero(AbstractFunctionDecl *funcDecl, void *) { auto &C = funcDecl->getASTContext(); auto *addArithProto = C.getProtocol(KnownProtocolKind::AdditiveArithmetic); auto *zeroReq = getProtocolRequirement(addArithProto, C.Id_zero); return deriveBodyPropertyGetter(funcDecl, addArithProto, zeroReq); } // Synthesize the static property declaration for `AdditiveArithmetic.zero`. static ValueDecl *deriveAdditiveArithmetic_zero(DerivedConformance &derived) { auto &C = derived.Context; auto *nominal = derived.Nominal; auto *parentDC = derived.getConformanceContext(); auto returnInterfaceTy = nominal->getDeclaredInterfaceType(); auto returnTy = parentDC->mapTypeIntoContext(returnInterfaceTy); // Create property declaration. VarDecl *propDecl; PatternBindingDecl *pbDecl; std::tie(propDecl, pbDecl) = derived.declareDerivedProperty( C.Id_zero, returnInterfaceTy, returnTy, /*isStatic*/ true, /*isFinal*/ true); // Create property getter. auto *getterDecl = derived.addGetterToReadOnlyDerivedProperty(propDecl, returnTy); getterDecl->setBodySynthesizer(deriveBodyAdditiveArithmetic_zero, nullptr); derived.addMembersToConformanceContext({propDecl, pbDecl}); // For the effective memberwise initializer before we force the body, // so that it becomes part of the emitted ABI members even if we don't // emit the body. (void) nominal->getEffectiveMemberwiseInitializer(); return propDecl; } ValueDecl * DerivedConformance::deriveAdditiveArithmetic(ValueDecl *requirement) { // Diagnose conformances in disallowed contexts. if (checkAndDiagnoseDisallowedContext(requirement)) return nullptr; if (requirement->getBaseName() == Context.getIdentifier("+")) return deriveMathOperator(*this, Add); if (requirement->getBaseName() == Context.getIdentifier("-")) return deriveMathOperator(*this, Subtract); if (requirement->getBaseName() == Context.Id_zero) return deriveAdditiveArithmetic_zero(*this); Context.Diags.diagnose(requirement->getLoc(), diag::broken_additive_arithmetic_requirement); return nullptr; } <|endoftext|>
<commit_before>#include <functional> #include <string> #include "Common.hpp" #include "Engine.hpp" #include "BaseTypes.hpp" #include "dataspace/Dataspace.hpp" #include "BaseCollections.hpp" #include "Builtins.hpp" namespace K3 { using std::endl; using std::to_string; // Standard context implementations __standard_context::__standard_context(Engine& __engine) : __k3_context(__engine) {} unit_t __standard_context::openBuiltin(string_impl ch_id, string_impl builtin_ch_id, string_impl fmt) { __engine.openBuiltin(ch_id, builtin_ch_id); return unit_t(); } unit_t __standard_context::openFile(string_impl ch_id, string_impl path, string_impl fmt, string_impl mode) { IOMode iomode = __engine.ioMode(mode); __engine.openFile(ch_id, path, iomode); return unit_t(); } unit_t __standard_context::openSocket(string_impl ch_id, Address a, string_impl fmt, string_impl mode) { throw std::runtime_error("Not implemented: openSocket"); } unit_t __standard_context::close(string_impl chan_id) { __engine.close(chan_id); return unit_t(); } int __standard_context::random(int n) { throw std::runtime_error("Not implemented: random"); } double __standard_context::randomFraction(unit_t) { throw std::runtime_error("Not implemented: random"); } unit_t __standard_context::print(string_impl message) { std::cout << message << endl; return unit_t(); } unit_t __standard_context::haltEngine(unit_t) { __engine.forceTerminateEngine(); return unit_t(); } unit_t __standard_context::drainEngine(unit_t) { throw std::runtime_error("Not implemented: drainEngine"); } unit_t sleep(int n) { throw std::runtime_error("Not implemented: sleep"); } // TODO fix copies related to base_str / std::sring conversion F<Collection<R_elem<string_impl>>(const string_impl &)> __string_context::regex_matcher(const string_impl& regex) { auto pattern = make_shared<RE2>(regex); return [pattern] (const string_impl& in_str) { std::string str = in_str; re2::StringPiece input(str); Collection<R_elem<string_impl>> results; std::string s; while(RE2::FindAndConsume(&input, *pattern, &s)) { results.insert(string_impl(s)); } return results; }; } Collection<R_elem<string_impl>> __string_context::regex_matcher_q4(const string_impl& in_str) { if (!pattern) { pattern = make_shared<RE2>("(?P<url>https?://[^\\s]+)"); } std::string str = in_str; re2::StringPiece input(str); Collection<R_elem<string_impl>> results; std::string s; while(RE2::FindAndConsume(&input, *pattern, &s)) { results.insert(string_impl(s)); } return results; } Vector<R_elem<double>> __standard_context::zeroVector(int i) { Vector<R_elem<double>> result; auto& c = result.getContainer(); c.resize(i); for(int j = 0; j < i; j++) { c[j] = R_elem<double>{0.0}; } return result; } // TODO // Elements must have random values Vector<R_elem<double>> __standard_context::randomVector(int i) { Vector<R_elem<double>> result; auto& c = result.getContainer(); c.resize(i); for(int j = 0; j < i; j++) { c[j] = R_elem<double>{0.0}; } return result; } // Time: __time_context::__time_context() {} int __time_context::now_int(unit_t) { auto t = std::chrono::system_clock::now(); auto elapsed =std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()); return elapsed.count(); } // String operations: __string_context::__string_context() {} string_impl __string_context::itos(int i) { return string_impl(to_string(i)); } // TODO: more efficient implementation. string_impl __string_context::concat(string_impl s1, string_impl s2) { std::string ss1 = s1; std::string ss2 = s2; return string_impl(ss1 + ss2); } string_impl __string_context::rtos(double d) { return string_impl(to_string(d)); } // Split a string by substrings Seq<R_elem<string_impl>> __string_context::splitString(string_impl s, const string_impl& splitter) { return s.splitString(splitter); } // Splitter is a single char for now string_impl __string_context::takeUntil(const string_impl& s, const string_impl& splitter) { char * pch; char delim = splitter.c_str()[0]; const char* buf = s.c_str(); if (!buf) { return string_impl(); } int n = 0; while ((*buf != 0) && (*buf != delim)) { buf++; n++; } return string_impl(buf, n); } // Splitter is a single char for now int __string_context::countChar(const string_impl& s, const string_impl& splitter) { char * pch; char delim = splitter.c_str()[0]; const char* buf = s.c_str(); if (!buf) { return 0; } int n = 0; while ((*buf != 0)) { buf++; if (*buf == delim) { n++; } } return n; } } // namespace K3 <commit_msg>random Vector updated<commit_after>#include <functional> #include <string> #include <stdlib.h> #include <time.h> #include "Common.hpp" #include "Engine.hpp" #include "BaseTypes.hpp" #include "dataspace/Dataspace.hpp" #include "BaseCollections.hpp" #include "Builtins.hpp" namespace K3 { using std::endl; using std::to_string; // Standard context implementations __standard_context::__standard_context(Engine& __engine) : __k3_context(__engine) {} unit_t __standard_context::openBuiltin(string_impl ch_id, string_impl builtin_ch_id, string_impl fmt) { __engine.openBuiltin(ch_id, builtin_ch_id); return unit_t(); } unit_t __standard_context::openFile(string_impl ch_id, string_impl path, string_impl fmt, string_impl mode) { IOMode iomode = __engine.ioMode(mode); __engine.openFile(ch_id, path, iomode); return unit_t(); } unit_t __standard_context::openSocket(string_impl ch_id, Address a, string_impl fmt, string_impl mode) { throw std::runtime_error("Not implemented: openSocket"); } unit_t __standard_context::close(string_impl chan_id) { __engine.close(chan_id); return unit_t(); } int __standard_context::random(int n) { throw std::runtime_error("Not implemented: random"); } double __standard_context::randomFraction(unit_t) { throw std::runtime_error("Not implemented: random"); } unit_t __standard_context::print(string_impl message) { std::cout << message << endl; return unit_t(); } unit_t __standard_context::haltEngine(unit_t) { __engine.forceTerminateEngine(); return unit_t(); } unit_t __standard_context::drainEngine(unit_t) { throw std::runtime_error("Not implemented: drainEngine"); } unit_t sleep(int n) { throw std::runtime_error("Not implemented: sleep"); } // TODO fix copies related to base_str / std::sring conversion F<Collection<R_elem<string_impl>>(const string_impl &)> __string_context::regex_matcher(const string_impl& regex) { auto pattern = make_shared<RE2>(regex); return [pattern] (const string_impl& in_str) { std::string str = in_str; re2::StringPiece input(str); Collection<R_elem<string_impl>> results; std::string s; while(RE2::FindAndConsume(&input, *pattern, &s)) { results.insert(string_impl(s)); } return results; }; } Collection<R_elem<string_impl>> __string_context::regex_matcher_q4(const string_impl& in_str) { if (!pattern) { pattern = make_shared<RE2>("(?P<url>https?://[^\\s]+)"); } std::string str = in_str; re2::StringPiece input(str); Collection<R_elem<string_impl>> results; std::string s; while(RE2::FindAndConsume(&input, *pattern, &s)) { results.insert(string_impl(s)); } return results; } Vector<R_elem<double>> __standard_context::zeroVector(int i) { Vector<R_elem<double>> result; auto& c = result.getContainer(); c.resize(i); for(int j = 0; j < i; j++) { c[j] = R_elem<double>{0.0}; } return result; } // TODO // Elements must have random values in [0,1) Vector<R_elem<double>> __standard_context::randomVector(int i) { Vector<R_elem<double>> result; auto& c = result.getContainer(); c.resize(i); for(int j = 0; j < i; j++) { srand(time(NULL)); c[j] = R_elem<double>{(rand()/(RAND_MAX+ 1.))}; } return result; } // Time: __time_context::__time_context() {} int __time_context::now_int(unit_t) { auto t = std::chrono::system_clock::now(); auto elapsed =std::chrono::duration_cast<std::chrono::milliseconds>(t.time_since_epoch()); return elapsed.count(); } // String operations: __string_context::__string_context() {} string_impl __string_context::itos(int i) { return string_impl(to_string(i)); } // TODO: more efficient implementation. string_impl __string_context::concat(string_impl s1, string_impl s2) { std::string ss1 = s1; std::string ss2 = s2; return string_impl(ss1 + ss2); } string_impl __string_context::rtos(double d) { return string_impl(to_string(d)); } // Split a string by substrings Seq<R_elem<string_impl>> __string_context::splitString(string_impl s, const string_impl& splitter) { return s.splitString(splitter); } // Splitter is a single char for now string_impl __string_context::takeUntil(const string_impl& s, const string_impl& splitter) { char * pch; char delim = splitter.c_str()[0]; const char* buf = s.c_str(); if (!buf) { return string_impl(); } int n = 0; while ((*buf != 0) && (*buf != delim)) { buf++; n++; } return string_impl(buf, n); } // Splitter is a single char for now int __string_context::countChar(const string_impl& s, const string_impl& splitter) { char * pch; char delim = splitter.c_str()[0]; const char* buf = s.c_str(); if (!buf) { return 0; } int n = 0; while ((*buf != 0)) { buf++; if (*buf == delim) { n++; } } return n; } } // namespace K3 <|endoftext|>
<commit_before>#ifndef K3_RUNTIME_LISTENER_H #define K3_RUNTIME_LISTENER_H #include <atomic> #include <functional> #include <memory> #include <unordered_set> #include <boost/array.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/lock_types.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/thread.hpp> #include <Common.hpp> #include <Queue.hpp> #include <IOHandle.hpp> #include <Endpoint.hpp> namespace K3 { //-------------------------------------------- // A reference counter for listener instances. class ListenerCounter : public std::atomic_uint { public: ListenerCounter() : std::atomic_uint(0) {} void registerListener() { this->fetch_add(1); } void deregisterListener() { this->fetch_sub(1); } unsigned int operator()() { return this->load(); } }; //--------------------------------------------------------------- // Control data structures for multi-threaded listener execution. class ListenerControl { public: ListenerControl(shared_ptr<boost::mutex> m, shared_ptr<boost::condition_variable> c, shared_ptr<ListenerCounter> i) : listenerCounter(i), msgAvailable(false), msgAvailMutex(m), msgAvailCondition(c) {} // Waits on the message available condition variable. void waitForMessage() { boost::unique_lock<boost::mutex> lock(*msgAvailMutex); while ( !msgAvailable ) { msgAvailCondition->wait(lock); } } // Notifies one waiter on the message available condition variable. void messageAvailable() { { boost::lock_guard<boost::mutex> lock(*msgAvailMutex); msgAvailable = true; } msgAvailCondition->notify_one(); } shared_ptr<ListenerCounter> counter() { return listenerCounter; } shared_ptr<boost::mutex> msgMutex() { return msgAvailMutex; } shared_ptr<boost::condition_variable> msgCondition() { return msgAvailCondition; } protected: shared_ptr<ListenerCounter> listenerCounter; bool msgAvailable; shared_ptr<boost::mutex> msgAvailMutex; shared_ptr<boost::condition_variable> msgAvailCondition; }; //------------ // Listeners // Abstract base class for listeners. template<typename NContext, typename NEndpoint> class Listener { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<MessageQueues> q, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<InternalCodec> c) : name(n), ctxt_(ctxt), queues(q), endpoint_(ep), control_(ctrl), transfer_codec(c), listenerLog(shared_ptr<LogMT>(new LogMT("Listener_"+n))) { if ( endpoint_ ) { IOHandle::SourceDetails source = ep->handle()->networkSource(); nEndpoint_ = dynamic_pointer_cast<NEndpoint>(get<1>(source)); handle_codec = get<0>(source); } } shared_ptr<ListenerControl> control() { return control_; } shared_ptr<Codec> newCodec() { } protected: Identifier name; shared_ptr<NContext> ctxt_; shared_ptr<MessageQueues> queues; shared_ptr<Endpoint> endpoint_; shared_ptr<NEndpoint> nEndpoint_; shared_ptr<Codec> handle_codec; shared_ptr<InternalCodec> transfer_codec; shared_ptr<ListenerControl> control_; shared_ptr<LogMT> listenerLog; }; namespace Asio { using namespace boost::asio; using namespace boost::log; using namespace boost::system; using boost::system::error_code; using boost::thread; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; // TODO: close method, terminating all incoming connections to this acceptor. class Listener : public BaseListener<NContext, NEndpoint>, public boost::basic_lockable_adapter<boost::mutex> { public: typedef basic_lockable_adapter<boost::mutex> llockable; typedef list<shared_ptr<NConnection> > ConnectionList; typedef boost::externally_locked<shared_ptr<ConnectionList>, Listener> ConcurrentConnectionList; Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<MessageQueues> q, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<InternalCodec> c) : BaseListener<NContext, NEndpoint>(n, ctxt, q, ep, ctrl, c), llockable(), connections_(emptyConnections()) { if ( this->nEndpoint_ && this->handle_codec && this->ctxt_ && this->ctxt_->service_threads ) { acceptConnection(); thread_ = shared_ptr<thread>(this->ctxt_->service_threads->create_thread(*(this->ctxt_))); } else { listenerLog->logAt(boost::log::trivial::error, "Invalid listener arguments."); } } ~Listener() { if (ctxt_ && thread_) { ctxt_->service_threads->remove_thread(thread_.get()); } } protected: shared_ptr<thread> thread_; shared_ptr<boost::externally_locked<shared_ptr<ConnectionList>, Listener> > connections_; //--------- // Helpers. shared_ptr<ConcurrentConnectionList> emptyConnections() { shared_ptr<ConnectionList> l = shared_ptr<ConnectionList>(new ConnectionList()); return shared_ptr<ConcurrentConnectionList>(new ConcurrentConnectionList(*this, l)); } //--------------------- // Endpoint execution. void acceptConnection() { if ( this->endpoint_ && this->handle_codec ) { shared_ptr<NConnection> nextConnection = shared_ptr<NConnection>(new NConnection(this->ctxt_)); this->nEndpoint_->acceptor()->async_accept(*(nextConnection->socket()), [=] (const error_code& ec) { if ( !ec ) { registerConnection(nextConnection); this->listenerLog->logAt(boost::log::trivial::trace, "Listener Registered a connection"); } else { this->listenerLog->logAt(boost::log::trivial::error, "Failed to accept a connection: " + ec.message()); } // recursive call: acceptConnection(); }); } else { this->listenerLog->logAt(boost::log::trivial::error, "Invalid listener endpoint or wire description"); } } void registerConnection(shared_ptr<NConnection> c) { if ( connections_ ) { { boost::strict_lock<Listener> guard(*this); connections_->get(guard)->push_back(c); } // Notify subscribers of socket accept event. if ( this->endpoint_ ) { this->endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept, nullptr); } // Start connection, with a new codec(buffer) shared_ptr<Codec> cdec = handle_codec->freshClone(); receiveMessages(c, cdec); } } void deregisterConnection(shared_ptr<NConnection> c) { if ( connections_ ) { boost::strict_lock<Listener> guard(*this); connections_->get(guard)->remove(c); } } void receiveMessages(shared_ptr<NConnection> c, shared_ptr<Codec> cdec) { if ( c && c->socket()) { // TODO: extensible buffer size. // We use a local variable for the socket buffer since multiple threads // may invoke this handler simultaneously (i.e. for different connections). typedef boost::array<char, 1024*1024> SocketBuffer; shared_ptr<SocketBuffer> buffer_ = shared_ptr<SocketBuffer>(new SocketBuffer()); c->socket()->async_read_some(buffer(buffer_->c_array(), buffer_->size()), [=](const error_code& ec, std::size_t bytes_transferred) { // Capture the buffer in closure to keep the pointer count > 0 // until the callback has finished shared_ptr<SocketBuffer> keep_alive = buffer_; if (!ec || (ec == boost::asio::error::eof && bytes_transferred > 0 )) { // Add network data to the codec's buffer. // We assume the processor notifies subscribers regarding socket data events. string * s = new string(buffer_->c_array(), bytes_transferred); ostringstream os2; size_t len = s->length(); shared_ptr<Value> v = cdec->decode(*s); delete s; // Exhaust the codec's buffer while (v) { bool t = this->endpoint_->do_push(v, this->queues, this->transfer_codec); if (t) { this->control_->messageAvailable(); } // Attempt to decode a buffered value v = cdec->decode(""); } // Recursive invocation for the next message. receiveMessages(c, cdec); } else { deregisterConnection(c); listenerLog->logAt(boost::log::trivial::error, string("Connection error: ")+ec.message()); } }); } else { listenerLog->logAt(boost::log::trivial::error, "Invalid listener connection"); } } }; } namespace Nanomsg { using std::atomic_bool; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; class Listener : public BaseListener<NContext, NEndpoint> { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<MessageQueues> q, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<InternalCodec> c) : BaseListener<NContext, NEndpoint>(n, ctxt, q, ep, ctrl, c) { if ( this->nEndpoint_ && this->handle_codec && this->ctxt_ && this->ctxt_->listenerThreads ) { // Instantiate a new thread to listen for messages on the nanomsg // socket, tracking it in the network context. terminated_ = false; thread_ = shared_ptr<boost::thread>(this->ctxt_->listenerThreads->create_thread(*this)); } else { listenerLog->logAt(boost::log::trivial::error, "Invalid listener arguments."); } } Listener(const Listener& other) : BaseListener<NContext, NEndpoint>(other.name, other.ctxt_, other.queues, other.endpoint_, other.control_, other.transfer_codec) { this->thread_ = other.thread_; this->senders = other.senders; this->terminated_.store(other.terminated_.load()); } void operator()() { typedef boost::array<char, 8192> SocketBuffer; SocketBuffer buffer_; shared_ptr<Codec> cdec = this->handle_codec->freshClone(); while ( !terminated_ ) { // Receive a message. int bytes = nn_recv(this->nEndpoint_->acceptor(), buffer_.c_array(), buffer_.static_size, 0); if ( bytes >= 0 ) { // Decode, process. shared_ptr<Value> v = cdec->decode(string(buffer_.c_array(), buffer_.static_size)); while ( v ) { // Simulate accept events for nanomsg. refreshSenders(v); bool t = this->endpoint_->do_push(v, this->queues, this->transfer_codec); if (t) { this->control_->messageAvailable(); } v = cdec->decode(""); } } else { listenerLog->logAt(boost::log::trivial::error, string("Error receiving message: ") + nn_strerror(nn_errno())); terminate(); } } } void terminate() { terminated_ = true; } protected: shared_ptr<boost::thread> thread_; atomic_bool terminated_; unordered_set<string> senders; // TODO: simulate socket accept notifications. Since nanomsg is not connection-oriented, // we simulate connections based on the arrival of messages from unseen addresses. // TODO: break assumption that value is a Message. void refreshSenders(shared_ptr<Value> v) { /* if ( senders.find(v->address()) == senders.end() ) { senders.insert(v->address()); endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept); } // TODO: remove addresses from the recipients pool based on a timeout. // TODO: time out stale senders. */ } }; } } #endif // vim:set sw=2 ts=2 sts=2: <commit_msg>cpp: got rid of remaining 'using'<commit_after>#ifndef K3_RUNTIME_LISTENER_H #define K3_RUNTIME_LISTENER_H #include <atomic> #include <functional> #include <memory> #include <unordered_set> #include <boost/array.hpp> #include <boost/thread/condition_variable.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/lock_types.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/thread.hpp> #include <Common.hpp> #include <Queue.hpp> #include <IOHandle.hpp> #include <Endpoint.hpp> namespace K3 { //-------------------------------------------- // A reference counter for listener instances. class ListenerCounter : public std::atomic_uint { public: ListenerCounter() : std::atomic_uint(0) {} void registerListener() { this->fetch_add(1); } void deregisterListener() { this->fetch_sub(1); } unsigned int operator()() { return this->load(); } }; //--------------------------------------------------------------- // Control data structures for multi-threaded listener execution. class ListenerControl { public: ListenerControl(shared_ptr<boost::mutex> m, shared_ptr<boost::condition_variable> c, shared_ptr<ListenerCounter> i) : listenerCounter(i), msgAvailable(false), msgAvailMutex(m), msgAvailCondition(c) {} // Waits on the message available condition variable. void waitForMessage() { boost::unique_lock<boost::mutex> lock(*msgAvailMutex); while ( !msgAvailable ) { msgAvailCondition->wait(lock); } } // Notifies one waiter on the message available condition variable. void messageAvailable() { { boost::lock_guard<boost::mutex> lock(*msgAvailMutex); msgAvailable = true; } msgAvailCondition->notify_one(); } shared_ptr<ListenerCounter> counter() { return listenerCounter; } shared_ptr<boost::mutex> msgMutex() { return msgAvailMutex; } shared_ptr<boost::condition_variable> msgCondition() { return msgAvailCondition; } protected: shared_ptr<ListenerCounter> listenerCounter; bool msgAvailable; shared_ptr<boost::mutex> msgAvailMutex; shared_ptr<boost::condition_variable> msgAvailCondition; }; //------------ // Listeners // Abstract base class for listeners. template<typename NContext, typename NEndpoint> class Listener { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<MessageQueues> q, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<InternalCodec> c) : name(n), ctxt_(ctxt), queues(q), endpoint_(ep), control_(ctrl), transfer_codec(c), listenerLog(shared_ptr<LogMT>(new LogMT("Listener_"+n))) { if ( endpoint_ ) { IOHandle::SourceDetails source = ep->handle()->networkSource(); nEndpoint_ = dynamic_pointer_cast<NEndpoint>(get<1>(source)); handle_codec = get<0>(source); } } shared_ptr<ListenerControl> control() { return control_; } shared_ptr<Codec> newCodec() { } protected: Identifier name; shared_ptr<NContext> ctxt_; shared_ptr<MessageQueues> queues; shared_ptr<Endpoint> endpoint_; shared_ptr<NEndpoint> nEndpoint_; shared_ptr<Codec> handle_codec; shared_ptr<InternalCodec> transfer_codec; shared_ptr<ListenerControl> control_; shared_ptr<LogMT> listenerLog; }; namespace Asio { template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; // TODO: close method, terminating all incoming connections to this acceptor. class Listener : public BaseListener<NContext, NEndpoint>, public boost::basic_lockable_adapter<boost::mutex> { public: typedef basic_lockable_adapter<boost::mutex> llockable; typedef list<shared_ptr<NConnection> > ConnectionList; typedef boost::externally_locked<shared_ptr<ConnectionList>, Listener> ConcurrentConnectionList; Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<MessageQueues> q, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<InternalCodec> c) : BaseListener<NContext, NEndpoint>(n, ctxt, q, ep, ctrl, c), llockable(), connections_(emptyConnections()) { if ( this->nEndpoint_ && this->handle_codec && this->ctxt_ && this->ctxt_->service_threads ) { acceptConnection(); thread_ = shared_ptr<boost::thread>(this->ctxt_->service_threads->create_thread(*(this->ctxt_))); } else { listenerLog->logAt(boost::log::trivial::error, "Invalid listener arguments."); } } ~Listener() { if (ctxt_ && thread_) { ctxt_->service_threads->remove_thread(thread_.get()); } } protected: shared_ptr<boost::thread> thread_; shared_ptr<boost::externally_locked<shared_ptr<ConnectionList>, Listener> > connections_; //--------- // Helpers. shared_ptr<ConcurrentConnectionList> emptyConnections() { shared_ptr<ConnectionList> l = shared_ptr<ConnectionList>(new ConnectionList()); return shared_ptr<ConcurrentConnectionList>(new ConcurrentConnectionList(*this, l)); } //--------------------- // Endpoint execution. void acceptConnection() { if ( this->endpoint_ && this->handle_codec ) { shared_ptr<NConnection> nextConnection = shared_ptr<NConnection>(new NConnection(this->ctxt_)); this->nEndpoint_->acceptor()->async_accept(*(nextConnection->socket()), [=] (const boost::system::error_code& ec) { if ( !ec ) { registerConnection(nextConnection); this->listenerLog->logAt(boost::log::trivial::trace, "Listener Registered a connection"); } else { this->listenerLog->logAt(boost::log::trivial::error, "Failed to accept a connection: " + ec.message()); } // recursive call: acceptConnection(); }); } else { this->listenerLog->logAt(boost::log::trivial::error, "Invalid listener endpoint or wire description"); } } void registerConnection(shared_ptr<NConnection> c) { if ( connections_ ) { { boost::strict_lock<Listener> guard(*this); connections_->get(guard)->push_back(c); } // Notify subscribers of socket accept event. if ( this->endpoint_ ) { this->endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept, nullptr); } // Start connection, with a new codec(buffer) shared_ptr<Codec> cdec = handle_codec->freshClone(); receiveMessages(c, cdec); } } void deregisterConnection(shared_ptr<NConnection> c) { if ( connections_ ) { boost::strict_lock<Listener> guard(*this); connections_->get(guard)->remove(c); } } void receiveMessages(shared_ptr<NConnection> c, shared_ptr<Codec> cdec) { if ( c && c->socket()) { // TODO: extensible buffer size. // We use a local variable for the socket buffer since multiple threads // may invoke this handler simultaneously (i.e. for different connections). typedef boost::array<char, 1024*1024> SocketBuffer; shared_ptr<SocketBuffer> buffer_ = shared_ptr<SocketBuffer>(new SocketBuffer()); c->socket()->async_read_some(buffer(buffer_->c_array(), buffer_->size()), [=](const boost::system::error_code& ec, std::size_t bytes_transferred) { // Capture the buffer in closure to keep the pointer count > 0 // until the callback has finished shared_ptr<SocketBuffer> keep_alive = buffer_; if (!ec || (ec == boost::asio::error::eof && bytes_transferred > 0 )) { // Add network data to the codec's buffer. // We assume the processor notifies subscribers regarding socket data events. string * s = new string(buffer_->c_array(), bytes_transferred); ostringstream os2; size_t len = s->length(); shared_ptr<Value> v = cdec->decode(*s); delete s; // Exhaust the codec's buffer while (v) { bool t = this->endpoint_->do_push(v, this->queues, this->transfer_codec); if (t) { this->control_->messageAvailable(); } // Attempt to decode a buffered value v = cdec->decode(""); } // Recursive invocation for the next message. receiveMessages(c, cdec); } else { deregisterConnection(c); listenerLog->logAt(boost::log::trivial::error, string("Connection error: ")+ec.message()); } }); } else { listenerLog->logAt(boost::log::trivial::error, "Invalid listener connection"); } } }; } namespace Nanomsg { using std::atomic_bool; template<typename NContext, typename NEndpoint> using BaseListener = ::K3::Listener<NContext, NEndpoint>; class Listener : public BaseListener<NContext, NEndpoint> { public: Listener(Identifier n, shared_ptr<NContext> ctxt, shared_ptr<MessageQueues> q, shared_ptr<Endpoint> ep, shared_ptr<ListenerControl> ctrl, shared_ptr<InternalCodec> c) : BaseListener<NContext, NEndpoint>(n, ctxt, q, ep, ctrl, c) { if ( this->nEndpoint_ && this->handle_codec && this->ctxt_ && this->ctxt_->listenerThreads ) { // Instantiate a new thread to listen for messages on the nanomsg // socket, tracking it in the network context. terminated_ = false; thread_ = shared_ptr<boost::thread>(this->ctxt_->listenerThreads->create_thread(*this)); } else { listenerLog->logAt(boost::log::trivial::error, "Invalid listener arguments."); } } Listener(const Listener& other) : BaseListener<NContext, NEndpoint>(other.name, other.ctxt_, other.queues, other.endpoint_, other.control_, other.transfer_codec) { this->thread_ = other.thread_; this->senders = other.senders; this->terminated_.store(other.terminated_.load()); } void operator()() { typedef boost::array<char, 8192> SocketBuffer; SocketBuffer buffer_; shared_ptr<Codec> cdec = this->handle_codec->freshClone(); while ( !terminated_ ) { // Receive a message. int bytes = nn_recv(this->nEndpoint_->acceptor(), buffer_.c_array(), buffer_.static_size, 0); if ( bytes >= 0 ) { // Decode, process. shared_ptr<Value> v = cdec->decode(string(buffer_.c_array(), buffer_.static_size)); while ( v ) { // Simulate accept events for nanomsg. refreshSenders(v); bool t = this->endpoint_->do_push(v, this->queues, this->transfer_codec); if (t) { this->control_->messageAvailable(); } v = cdec->decode(""); } } else { listenerLog->logAt(boost::log::trivial::error, string("Error receiving message: ") + nn_strerror(nn_errno())); terminate(); } } } void terminate() { terminated_ = true; } protected: shared_ptr<boost::thread> thread_; atomic_bool terminated_; unordered_set<string> senders; // TODO: simulate socket accept notifications. Since nanomsg is not connection-oriented, // we simulate connections based on the arrival of messages from unseen addresses. // TODO: break assumption that value is a Message. void refreshSenders(shared_ptr<Value> v) { /* if ( senders.find(v->address()) == senders.end() ) { senders.insert(v->address()); endpoint_->subscribers()->notifyEvent(EndpointNotification::SocketAccept); } // TODO: remove addresses from the recipients pool based on a timeout. // TODO: time out stale senders. */ } }; } } #endif // vim:set sw=2 ts=2 sts=2: <|endoftext|>
<commit_before>#include "Memory.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "Type.h" #include "Runtime.h" #include "GasMeter.h" #include "Endianness.h" #include "RuntimeManager.h" namespace dev { namespace eth { namespace jit { Memory::Memory(RuntimeManager& _runtimeManager, GasMeter& _gasMeter): RuntimeHelper(_runtimeManager), // TODO: RuntimeHelper not needed m_memory{getBuilder(), _runtimeManager.getMem()}, m_gasMeter(_gasMeter) {} llvm::Function* Memory::getRequireFunc() { auto& func = m_require; if (!func) { llvm::Type* argTypes[] = {Array::getType()->getPointerTo(), Type::Word, Type::Word, Type::BytePtr, Type::GasPtr}; func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "mem.require", getModule()); func->setDoesNotThrow(); auto mem = &func->getArgumentList().front(); mem->setName("mem"); auto blkOffset = mem->getNextNode(); blkOffset->setName("blkOffset"); auto blkSize = blkOffset->getNextNode(); blkSize->setName("blkSize"); auto jmpBuf = blkSize->getNextNode(); jmpBuf->setName("jmpBuf"); auto gas = jmpBuf->getNextNode(); gas->setName("gas"); auto preBB = llvm::BasicBlock::Create(func->getContext(), "Pre", func); auto checkBB = llvm::BasicBlock::Create(func->getContext(), "Check", func); auto resizeBB = llvm::BasicBlock::Create(func->getContext(), "Resize", func); auto returnBB = llvm::BasicBlock::Create(func->getContext(), "Return", func); InsertPointGuard guard(m_builder); // Restores insert point at function exit // BB "Pre": Ignore checks with size 0 m_builder.SetInsertPoint(preBB); m_builder.CreateCondBr(m_builder.CreateICmpNE(blkSize, Constant::get(0)), checkBB, returnBB, Type::expectTrue); // BB "Check" m_builder.SetInsertPoint(checkBB); static const auto c_inputMax = uint64_t(2) << 40; // max value of blkSize and blkOffset that will not result in integer overflow in calculations below auto blkOffsetOk = m_builder.CreateICmpULE(blkOffset, Constant::get(c_inputMax), "blkOffsetOk"); auto blkO = m_builder.CreateSelect(blkOffsetOk, m_builder.CreateTrunc(blkOffset, Type::Size), m_builder.getInt64(c_inputMax), "bklO"); auto blkSizeOk = m_builder.CreateICmpULE(blkSize, Constant::get(c_inputMax), "blkSizeOk"); auto blkS = m_builder.CreateSelect(blkSizeOk, m_builder.CreateTrunc(blkSize, Type::Size), m_builder.getInt64(c_inputMax), "bklS"); auto sizeReq0 = m_builder.CreateNUWAdd(blkO, blkS, "sizeReq0"); auto sizeReq = m_builder.CreateAnd(m_builder.CreateNUWAdd(sizeReq0, m_builder.getInt64(31)), uint64_t(-1) << 5, "sizeReq"); // s' = ((s0 + 31) / 32) * 32 auto sizeCur = m_memory.size(mem); auto sizeOk = m_builder.CreateICmpULE(sizeReq, sizeCur, "sizeOk"); m_builder.CreateCondBr(sizeOk, returnBB, resizeBB, Type::expectTrue); // BB "Resize" m_builder.SetInsertPoint(resizeBB); // Check gas first auto sizeExt = m_builder.CreateNUWSub(sizeReq, sizeCur, "sizeExt"); auto sizeSum = m_builder.CreateNUWAdd(sizeReq, sizeCur, "sizeSum"); auto costL = m_builder.CreateLShr(sizeExt, 5, "costL"); auto costQ1 = m_builder.CreateLShr(sizeExt, 20, "costQ1"); auto costQ2 = m_builder.CreateLShr(sizeSum, 20, "costQ2"); auto costQ = m_builder.CreateNUWAdd(costQ1, costQ2, "costQ"); auto cost = m_builder.CreateNUWAdd(costL, costQ, "cost"); auto costOk = m_builder.CreateAnd(blkOffsetOk, blkSizeOk, "costOk"); auto c = m_builder.CreateSelect(costOk, costL, m_builder.getInt64(std::numeric_limits<int64_t>::max()), "c"); m_gasMeter.countMemory(c, jmpBuf, gas); // Resize m_memory.extend(mem, sizeReq); m_builder.CreateBr(returnBB); // BB "Return" m_builder.SetInsertPoint(returnBB); m_builder.CreateRetVoid(); } return func; } llvm::Function* Memory::createFunc(bool _isStore, llvm::Type* _valueType) { auto isWord = _valueType == Type::Word; llvm::Type* storeArgs[] = {Array::getType()->getPointerTo(), Type::Word, _valueType}; llvm::Type* loadArgs[] = {Array::getType()->getPointerTo(), Type::Word}; auto name = _isStore ? isWord ? "mstore" : "mstore8" : "mload"; auto funcType = _isStore ? llvm::FunctionType::get(Type::Void, storeArgs, false) : llvm::FunctionType::get(Type::Word, loadArgs, false); auto func = llvm::Function::Create(funcType, llvm::Function::PrivateLinkage, name, getModule()); InsertPointGuard guard(m_builder); // Restores insert point at function exit m_builder.SetInsertPoint(llvm::BasicBlock::Create(func->getContext(), {}, func)); auto mem = &func->getArgumentList().front(); mem->setName("mem"); auto index = mem->getNextNode(); index->setName("index"); if (_isStore) { auto valueArg = index->getNextNode(); valueArg->setName("value"); auto value = isWord ? Endianness::toBE(m_builder, valueArg) : valueArg; auto memPtr = m_memory.getPtr(mem, m_builder.CreateTrunc(index, Type::Size)); auto valuePtr = m_builder.CreateBitCast(memPtr, _valueType->getPointerTo(), "valuePtr"); m_builder.CreateStore(value, valuePtr); m_builder.CreateRetVoid(); } else { auto memPtr = m_memory.getPtr(mem, m_builder.CreateTrunc(index, Type::Size)); llvm::Value* ret = m_builder.CreateLoad(memPtr); ret = Endianness::toNative(m_builder, ret); m_builder.CreateRet(ret); } return func; } llvm::Function* Memory::getLoadWordFunc() { auto& func = m_loadWord; if (!func) func = createFunc(false, Type::Word); return func; } llvm::Function* Memory::getStoreWordFunc() { auto& func = m_storeWord; if (!func) func = createFunc(true, Type::Word); return func; } llvm::Function* Memory::getStoreByteFunc() { auto& func = m_storeByte; if (!func) func = createFunc(true, Type::Byte); return func; } llvm::Value* Memory::loadWord(llvm::Value* _addr) { require(_addr, Constant::get(Type::Word->getPrimitiveSizeInBits() / 8)); return createCall(getLoadWordFunc(), {getRuntimeManager().getMem(), _addr}); } void Memory::storeWord(llvm::Value* _addr, llvm::Value* _word) { require(_addr, Constant::get(Type::Word->getPrimitiveSizeInBits() / 8)); createCall(getStoreWordFunc(), {getRuntimeManager().getMem(), _addr, _word}); } void Memory::storeByte(llvm::Value* _addr, llvm::Value* _word) { require(_addr, Constant::get(Type::Byte->getPrimitiveSizeInBits() / 8)); auto byte = m_builder.CreateTrunc(_word, Type::Byte, "byte"); createCall(getStoreByteFunc(), {getRuntimeManager().getMem(), _addr, byte}); } llvm::Value* Memory::getData() { auto memPtr = m_builder.CreateBitCast(getRuntimeManager().getMem(), Type::BytePtr->getPointerTo()); auto data = m_builder.CreateLoad(memPtr, "data"); assert(data->getType() == Type::BytePtr); return data; } llvm::Value* Memory::getSize() { return m_builder.CreateZExt(m_memory.size(), Type::Word, "msize"); // TODO: Allow placing i64 on stack } llvm::Value* Memory::getBytePtr(llvm::Value* _index) { auto idx = m_builder.CreateTrunc(_index, Type::Size, "idx"); // Never allow memory index be a type bigger than i64 return m_builder.CreateGEP(getData(), idx, "ptr"); } void Memory::require(llvm::Value* _offset, llvm::Value* _size) { if (auto constant = llvm::dyn_cast<llvm::ConstantInt>(_size)) { if (!constant->getValue()) return; } createCall(getRequireFunc(), {getRuntimeManager().getMem(), _offset, _size, getRuntimeManager().getJmpBuf(), getRuntimeManager().getGasPtr()}); } void Memory::copyBytes(llvm::Value* _srcPtr, llvm::Value* _srcSize, llvm::Value* _srcIdx, llvm::Value* _destMemIdx, llvm::Value* _reqBytes) { require(_destMemIdx, _reqBytes); // Additional copy cost // TODO: This round ups to 32 happens in many places auto reqBytes = m_builder.CreateTrunc(_reqBytes, Type::Gas); auto copyWords = m_builder.CreateUDiv(m_builder.CreateNUWAdd(reqBytes, m_builder.getInt64(31)), m_builder.getInt64(32)); m_gasMeter.countCopy(copyWords); // Algorithm: // isOutsideData = idx256 >= size256 // idx64 = trunc idx256 // size64 = trunc size256 // dataLeftSize = size64 - idx64 // safe if not isOutsideData // reqBytes64 = trunc _reqBytes // require() handles large values // bytesToCopy0 = select(reqBytes64 > dataLeftSize, dataSizeLeft, reqBytes64) // min // bytesToCopy = select(isOutsideData, 0, bytesToCopy0) auto isOutsideData = m_builder.CreateICmpUGE(_srcIdx, _srcSize); auto idx64 = m_builder.CreateTrunc(_srcIdx, Type::Size); auto size64 = m_builder.CreateTrunc(_srcSize, Type::Size); auto dataLeftSize = m_builder.CreateNUWSub(size64, idx64); auto outOfBound = m_builder.CreateICmpUGT(reqBytes, dataLeftSize); auto bytesToCopyInner = m_builder.CreateSelect(outOfBound, dataLeftSize, reqBytes); auto bytesToCopy = m_builder.CreateSelect(isOutsideData, m_builder.getInt64(0), bytesToCopyInner); auto src = m_builder.CreateGEP(_srcPtr, idx64, "src"); auto dstIdx = m_builder.CreateTrunc(_destMemIdx, Type::Size, "dstIdx"); // Never allow memory index be a type bigger than i64 auto dst = m_memory.getPtr(getRuntimeManager().getMem(), dstIdx); auto dst2 = m_builder.CreateGEP(getData(), dstIdx, "dst2"); m_builder.CreateMemCpy(dst, src, bytesToCopy, 0); m_builder.CreateMemCpy(dst2, src, bytesToCopy, 0); } } } } <commit_msg>Quadratic memory cost<commit_after>#include "Memory.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "Type.h" #include "Runtime.h" #include "GasMeter.h" #include "Endianness.h" #include "RuntimeManager.h" namespace dev { namespace eth { namespace jit { Memory::Memory(RuntimeManager& _runtimeManager, GasMeter& _gasMeter): RuntimeHelper(_runtimeManager), // TODO: RuntimeHelper not needed m_memory{getBuilder(), _runtimeManager.getMem()}, m_gasMeter(_gasMeter) {} llvm::Function* Memory::getRequireFunc() { auto& func = m_require; if (!func) { llvm::Type* argTypes[] = {Array::getType()->getPointerTo(), Type::Word, Type::Word, Type::BytePtr, Type::GasPtr}; func = llvm::Function::Create(llvm::FunctionType::get(Type::Void, argTypes, false), llvm::Function::PrivateLinkage, "mem.require", getModule()); func->setDoesNotThrow(); auto mem = &func->getArgumentList().front(); mem->setName("mem"); auto blkOffset = mem->getNextNode(); blkOffset->setName("blkOffset"); auto blkSize = blkOffset->getNextNode(); blkSize->setName("blkSize"); auto jmpBuf = blkSize->getNextNode(); jmpBuf->setName("jmpBuf"); auto gas = jmpBuf->getNextNode(); gas->setName("gas"); auto preBB = llvm::BasicBlock::Create(func->getContext(), "Pre", func); auto checkBB = llvm::BasicBlock::Create(func->getContext(), "Check", func); auto resizeBB = llvm::BasicBlock::Create(func->getContext(), "Resize", func); auto returnBB = llvm::BasicBlock::Create(func->getContext(), "Return", func); InsertPointGuard guard(m_builder); // Restores insert point at function exit // BB "Pre": Ignore checks with size 0 m_builder.SetInsertPoint(preBB); m_builder.CreateCondBr(m_builder.CreateICmpNE(blkSize, Constant::get(0)), checkBB, returnBB, Type::expectTrue); // BB "Check" m_builder.SetInsertPoint(checkBB); static const auto c_inputMax = uint64_t(1) << 32; // max value of blkSize and blkOffset that will not result in integer overflow in calculations below auto blkOffsetOk = m_builder.CreateICmpULE(blkOffset, Constant::get(c_inputMax), "blkOffsetOk"); auto blkO = m_builder.CreateSelect(blkOffsetOk, m_builder.CreateTrunc(blkOffset, Type::Size), m_builder.getInt64(c_inputMax), "bklO"); auto blkSizeOk = m_builder.CreateICmpULE(blkSize, Constant::get(c_inputMax), "blkSizeOk"); auto blkS = m_builder.CreateSelect(blkSizeOk, m_builder.CreateTrunc(blkSize, Type::Size), m_builder.getInt64(c_inputMax), "bklS"); auto sizeReq0 = m_builder.CreateNUWAdd(blkO, blkS, "sizeReq0"); auto sizeReq = m_builder.CreateAnd(m_builder.CreateNUWAdd(sizeReq0, m_builder.getInt64(31)), uint64_t(-1) << 5, "sizeReq"); // s' = ((s0 + 31) / 32) * 32 auto sizeCur = m_memory.size(mem); auto sizeOk = m_builder.CreateICmpULE(sizeReq, sizeCur, "sizeOk"); m_builder.CreateCondBr(sizeOk, returnBB, resizeBB, Type::expectTrue); // BB "Resize" m_builder.SetInsertPoint(resizeBB); // Check gas first auto w1 = m_builder.CreateLShr(sizeReq, 5); auto w1s = m_builder.CreateNUWMul(w1, w1); auto c1 = m_builder.CreateAdd(w1, m_builder.CreateLShr(w1s, 10)); auto w0 = m_builder.CreateLShr(sizeCur, 5); auto w0s = m_builder.CreateNUWMul(w0, w0); auto c0 = m_builder.CreateAdd(w0, m_builder.CreateLShr(w0s, 10)); auto cc = m_builder.CreateNUWSub(c1, c0); auto costOk = m_builder.CreateAnd(blkOffsetOk, blkSizeOk, "costOk"); auto c = m_builder.CreateSelect(costOk, cc, m_builder.getInt64(std::numeric_limits<int64_t>::max()), "c"); m_gasMeter.countMemory(c, jmpBuf, gas); // Resize m_memory.extend(mem, sizeReq); m_builder.CreateBr(returnBB); // BB "Return" m_builder.SetInsertPoint(returnBB); m_builder.CreateRetVoid(); } return func; } llvm::Function* Memory::createFunc(bool _isStore, llvm::Type* _valueType) { auto isWord = _valueType == Type::Word; llvm::Type* storeArgs[] = {Array::getType()->getPointerTo(), Type::Word, _valueType}; llvm::Type* loadArgs[] = {Array::getType()->getPointerTo(), Type::Word}; auto name = _isStore ? isWord ? "mstore" : "mstore8" : "mload"; auto funcType = _isStore ? llvm::FunctionType::get(Type::Void, storeArgs, false) : llvm::FunctionType::get(Type::Word, loadArgs, false); auto func = llvm::Function::Create(funcType, llvm::Function::PrivateLinkage, name, getModule()); InsertPointGuard guard(m_builder); // Restores insert point at function exit m_builder.SetInsertPoint(llvm::BasicBlock::Create(func->getContext(), {}, func)); auto mem = &func->getArgumentList().front(); mem->setName("mem"); auto index = mem->getNextNode(); index->setName("index"); if (_isStore) { auto valueArg = index->getNextNode(); valueArg->setName("value"); auto value = isWord ? Endianness::toBE(m_builder, valueArg) : valueArg; auto memPtr = m_memory.getPtr(mem, m_builder.CreateTrunc(index, Type::Size)); auto valuePtr = m_builder.CreateBitCast(memPtr, _valueType->getPointerTo(), "valuePtr"); m_builder.CreateStore(value, valuePtr); m_builder.CreateRetVoid(); } else { auto memPtr = m_memory.getPtr(mem, m_builder.CreateTrunc(index, Type::Size)); llvm::Value* ret = m_builder.CreateLoad(memPtr); ret = Endianness::toNative(m_builder, ret); m_builder.CreateRet(ret); } return func; } llvm::Function* Memory::getLoadWordFunc() { auto& func = m_loadWord; if (!func) func = createFunc(false, Type::Word); return func; } llvm::Function* Memory::getStoreWordFunc() { auto& func = m_storeWord; if (!func) func = createFunc(true, Type::Word); return func; } llvm::Function* Memory::getStoreByteFunc() { auto& func = m_storeByte; if (!func) func = createFunc(true, Type::Byte); return func; } llvm::Value* Memory::loadWord(llvm::Value* _addr) { require(_addr, Constant::get(Type::Word->getPrimitiveSizeInBits() / 8)); return createCall(getLoadWordFunc(), {getRuntimeManager().getMem(), _addr}); } void Memory::storeWord(llvm::Value* _addr, llvm::Value* _word) { require(_addr, Constant::get(Type::Word->getPrimitiveSizeInBits() / 8)); createCall(getStoreWordFunc(), {getRuntimeManager().getMem(), _addr, _word}); } void Memory::storeByte(llvm::Value* _addr, llvm::Value* _word) { require(_addr, Constant::get(Type::Byte->getPrimitiveSizeInBits() / 8)); auto byte = m_builder.CreateTrunc(_word, Type::Byte, "byte"); createCall(getStoreByteFunc(), {getRuntimeManager().getMem(), _addr, byte}); } llvm::Value* Memory::getData() { auto memPtr = m_builder.CreateBitCast(getRuntimeManager().getMem(), Type::BytePtr->getPointerTo()); auto data = m_builder.CreateLoad(memPtr, "data"); assert(data->getType() == Type::BytePtr); return data; } llvm::Value* Memory::getSize() { return m_builder.CreateZExt(m_memory.size(), Type::Word, "msize"); // TODO: Allow placing i64 on stack } llvm::Value* Memory::getBytePtr(llvm::Value* _index) { auto idx = m_builder.CreateTrunc(_index, Type::Size, "idx"); // Never allow memory index be a type bigger than i64 return m_builder.CreateGEP(getData(), idx, "ptr"); } void Memory::require(llvm::Value* _offset, llvm::Value* _size) { if (auto constant = llvm::dyn_cast<llvm::ConstantInt>(_size)) { if (!constant->getValue()) return; } createCall(getRequireFunc(), {getRuntimeManager().getMem(), _offset, _size, getRuntimeManager().getJmpBuf(), getRuntimeManager().getGasPtr()}); } void Memory::copyBytes(llvm::Value* _srcPtr, llvm::Value* _srcSize, llvm::Value* _srcIdx, llvm::Value* _destMemIdx, llvm::Value* _reqBytes) { require(_destMemIdx, _reqBytes); // Additional copy cost // TODO: This round ups to 32 happens in many places auto reqBytes = m_builder.CreateTrunc(_reqBytes, Type::Gas); auto copyWords = m_builder.CreateUDiv(m_builder.CreateNUWAdd(reqBytes, m_builder.getInt64(31)), m_builder.getInt64(32)); m_gasMeter.countCopy(copyWords); // Algorithm: // isOutsideData = idx256 >= size256 // idx64 = trunc idx256 // size64 = trunc size256 // dataLeftSize = size64 - idx64 // safe if not isOutsideData // reqBytes64 = trunc _reqBytes // require() handles large values // bytesToCopy0 = select(reqBytes64 > dataLeftSize, dataSizeLeft, reqBytes64) // min // bytesToCopy = select(isOutsideData, 0, bytesToCopy0) auto isOutsideData = m_builder.CreateICmpUGE(_srcIdx, _srcSize); auto idx64 = m_builder.CreateTrunc(_srcIdx, Type::Size); auto size64 = m_builder.CreateTrunc(_srcSize, Type::Size); auto dataLeftSize = m_builder.CreateNUWSub(size64, idx64); auto outOfBound = m_builder.CreateICmpUGT(reqBytes, dataLeftSize); auto bytesToCopyInner = m_builder.CreateSelect(outOfBound, dataLeftSize, reqBytes); auto bytesToCopy = m_builder.CreateSelect(isOutsideData, m_builder.getInt64(0), bytesToCopyInner); auto src = m_builder.CreateGEP(_srcPtr, idx64, "src"); auto dstIdx = m_builder.CreateTrunc(_destMemIdx, Type::Size, "dstIdx"); // Never allow memory index be a type bigger than i64 auto dst = m_memory.getPtr(getRuntimeManager().getMem(), dstIdx); auto dst2 = m_builder.CreateGEP(getData(), dstIdx, "dst2"); m_builder.CreateMemCpy(dst, src, bytesToCopy, 0); m_builder.CreateMemCpy(dst2, src, bytesToCopy, 0); } } } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasilev@cern.ch> // author: Baozeng Ding <sploving1@gmail.com> //------------------------------------------------------------------------------ #include "NullDerefProtectionTransformer.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Mangle.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaDiagnostic.h" #include "llvm/IR/Module.h" #include "llvm/IR/Constants.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/InstIterator.h" #include <cstdio> #include "unistd.h" extern "C" { bool shouldProceed(void *S, void *T) { using namespace clang; Sema *Sem = (Sema *)S; DiagnosticsEngine& Diag = Sem->getDiagnostics(); cling::Transaction* Trans = (cling::Transaction*)T; // Here we will cheat a bit and assume that the warning came from the last // stmt, which will be in the 90% of the cases. CompoundStmt* CS = cast<CompoundStmt>(Trans->getWrapperFD()->getBody()); // Skip the NullStmts. SourceLocation Loc = CS->getLocStart(); for(CompoundStmt::const_reverse_body_iterator I = CS->body_rbegin(), E = CS->body_rend(); I != E; ++I) if (!isa<NullStmt>(*I)) { Loc = (*I)->getLocStart(); break; } Diag.Report(Loc, diag::warn_null_ptr_deref); if (isatty(fileno(stdin))) { int input = getchar(); getchar(); if (input == 'y' || input == 'Y') return false; } return true; } } using namespace clang; namespace cling { typedef std::map<llvm::StringRef, std::bitset<32> > nonnull_map_t; // NonNullDeclFinder finds the function decls with nonnull attribute args. class NonNullDeclFinder : public RecursiveASTVisitor<NonNullDeclFinder> { private: Sema* m_Sema; llvm::SmallVector<llvm::StringRef, 8> m_NonNullDeclNames; nonnull_map_t m_NonNullArgIndexs; public: NonNullDeclFinder(Sema* S) : m_Sema(S) {} const llvm::SmallVector<llvm::StringRef, 8>& getDeclNames() const { return m_NonNullDeclNames; } const nonnull_map_t& getArgIndexs() const { return m_NonNullArgIndexs; } // Deal with all the call expr in the transaction. bool VisitCallExpr(CallExpr* TheCall) { if (FunctionDecl* FDecl = TheCall->getDirectCallee()) { std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; // Store all the null attr argument's index into "ArgIndexs". for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) ArgIndexs.set(*i); } if (ArgIndexs.any()) { // Get the function decl's name. llvm::StringRef FName = FDecl->getName(); // Store the function decl's name into the vector. m_NonNullDeclNames.push_back(FName); // Store the function decl's name with its null attr args' indexes // into the map. m_NonNullArgIndexs.insert(std::make_pair(FName, ArgIndexs)); } } return true; // returning false will abort the in-depth traversal. } }; NullDerefProtectionTransformer::NullDerefProtectionTransformer(Sema *S) : TransactionTransformer(S), FailBB(0), Builder(0), Inst(0) {} NullDerefProtectionTransformer::~NullDerefProtectionTransformer() {} void NullDerefProtectionTransformer::Transform() { FunctionDecl* FD = getTransaction()->getWrapperFD(); if (!FD) return; // Copied from Interpreter.cpp; if (!m_MangleCtx) m_MangleCtx.reset(FD->getASTContext().createMangleContext()); std::string mangledName; if (m_MangleCtx->shouldMangleDeclName(FD)) { llvm::raw_string_ostream RawStr(mangledName); switch(FD->getKind()) { case Decl::CXXConstructor: //Ctor_Complete, // Complete object ctor //Ctor_Base, // Base object ctor //Ctor_CompleteAllocating // Complete object allocating ctor (unused) m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD), Ctor_Complete, RawStr); break; case Decl::CXXDestructor: //Dtor_Deleting, // Deleting dtor //Dtor_Complete, // Complete object dtor //Dtor_Base // Base object dtor m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD), Dtor_Complete, RawStr); break; default : m_MangleCtx->mangleName(FD, RawStr); break; } RawStr.flush(); } else { mangledName = FD->getNameAsString(); } // Find the function in the module. llvm::Function* F = getTransaction()->getModule()->getFunction(mangledName); if (!F) return; llvm::IRBuilder<> TheBuilder(F->getContext()); Builder = &TheBuilder; runOnFunction(*F); NonNullDeclFinder Finder(m_Sema); // Find all the function decls with null attribute arguments. for (size_t Idx = 0, E = getTransaction()->size(); Idx < E; ++Idx) { Transaction::DelayCallInfo I = (*getTransaction())[Idx]; for (DeclGroupRef::const_iterator J = I.m_DGR.begin(), JE = I.m_DGR.end(); J != JE; ++J) if ((*J)->hasBody()) Finder.TraverseStmt((*J)->getBody()); } const llvm::SmallVector<llvm::StringRef, 8>& FDeclNames = Finder.getDeclNames(); if (FDeclNames.empty()) return; llvm::Module* M = F->getParent(); for (llvm::SmallVector<llvm::StringRef, 8>::const_iterator i = FDeclNames.begin(), e = FDeclNames.end(); i != e; ++i) { const nonnull_map_t& ArgIndexs = Finder.getArgIndexs(); nonnull_map_t::const_iterator it = ArgIndexs.find(*i); if (it != ArgIndexs.end()) { const std::bitset<32>& ArgNums = it->second; handleNonNullArgCall(*M, *i, ArgNums); } } } llvm::BasicBlock* NullDerefProtectionTransformer::getTrapBB(llvm::BasicBlock* BB) { llvm::Function* Fn = Inst->getParent()->getParent(); llvm::Module* Md = Fn->getParent(); llvm::LLVMContext& ctx = Fn->getContext(); llvm::BasicBlock::iterator PreInsertInst = Builder->GetInsertPoint(); FailBB = llvm::BasicBlock::Create(ctx, "FailBlock", Fn); Builder->SetInsertPoint(FailBB); std::vector<llvm::Type*> ArgTys; llvm::Type* VoidTy = llvm::Type::getInt8PtrTy(ctx); ArgTys.push_back(VoidTy); ArgTys.push_back(VoidTy); llvm::FunctionType* FTy = llvm::FunctionType::get(llvm::Type::getInt1Ty(ctx), ArgTys, false); llvm::Function* CallBackFn = cast<llvm::Function>(Md->getOrInsertFunction("shouldProceed", FTy)); void* SemaRef = (void*)m_Sema; // copied from JIT.cpp llvm::Constant* SemaRefCnt = 0; llvm::Type* constantIntTy = 0; if (sizeof(void*) == 4) constantIntTy = llvm::Type::getInt32Ty(ctx); else constantIntTy = llvm::Type::getInt64Ty(ctx); SemaRefCnt = llvm::ConstantInt::get(constantIntTy, (uintptr_t)SemaRef); llvm::Value* Arg1 = llvm::ConstantExpr::getIntToPtr(SemaRefCnt, VoidTy); Transaction* Trans = getTransaction(); void* TransRef = (void*) Trans; llvm::Constant* TransRefCnt = llvm::ConstantInt::get(constantIntTy, (uintptr_t)TransRef); llvm::Value* Arg2 = llvm::ConstantExpr::getIntToPtr(TransRefCnt, VoidTy); llvm::CallInst* CI = Builder->CreateCall2(CallBackFn, Arg1, Arg2); llvm::Value* TrueVl = llvm::ConstantInt::get(ctx, llvm::APInt(1, 1)); llvm::Value* RetVl = CI; llvm::ICmpInst* Cmp = new llvm::ICmpInst(*FailBB, llvm::CmpInst::ICMP_EQ, RetVl, TrueVl, ""); llvm::BasicBlock *HandleBB = llvm::BasicBlock::Create(ctx,"HandleBlock", Fn); llvm::BranchInst::Create(HandleBB, BB, Cmp, FailBB); llvm::ReturnInst::Create(Fn->getContext(), HandleBB); Builder->SetInsertPoint(PreInsertInst); return FailBB; } // Insert a cmp instruction before the "Inst" instruction to check whether the // argument "Arg" for the instruction "Inst" is null or not. void NullDerefProtectionTransformer::instrumentInst( llvm::Instruction* Inst, llvm::Value* Arg) { llvm::BasicBlock* OldBB = Inst->getParent(); // Insert a cmp instruction to check whether "Arg" is null or not. llvm::ICmpInst* Cmp = new llvm::ICmpInst(Inst, llvm::CmpInst::ICMP_EQ, Arg, llvm::Constant::getNullValue(Arg->getType()), ""); // The block is splited into two blocks, "OldBB" and "NewBB", by the "Inst" // instruction. After that split, "Inst" is at the start of "NewBB". Then // insert a branch instruction at the end of "OldBB". If "Arg" is null, // it will jump to "FailBB" created by "getTrapBB" function. Else, it means // jump to the "NewBB". llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst); OldBB->getTerminator()->eraseFromParent(); llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB); } bool NullDerefProtectionTransformer::runOnFunction(llvm::Function &F) { std::vector<llvm::Instruction*> WorkList; for (llvm::inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) { llvm::Instruction* I = &*i; if (llvm::isa<llvm::LoadInst>(I)) WorkList.push_back(I); } for (std::vector<llvm::Instruction*>::iterator i = WorkList.begin(), e = WorkList.end(); i != e; ++i) { Inst = *i; Builder->SetInsertPoint(Inst); llvm::LoadInst* I = llvm::cast<llvm::LoadInst>(*i); // Find all the instructions that uses the instruction I. for (llvm::Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) { // Check whether I is used as the first argument for a load instruction. // If it is, then instrument the load instruction. if (llvm::LoadInst* LI = llvm::dyn_cast<llvm::LoadInst>(*UI)) { llvm::Value* Arg = LI->getOperand(0); if (Arg == I) instrumentInst(LI, Arg); } // Check whether I is used as the second argument for a store // instruction. If it is, then instrument the store instruction. else if (llvm::StoreInst* SI = llvm::dyn_cast<llvm::StoreInst>(*UI)) { llvm::Value* Arg = SI->getOperand(1); if (Arg == I) instrumentInst(SI, Arg); } // Check whether I is used as the first argument for a GEP instruction. // If it is, then instrument the GEP instruction. else if (llvm::GetElementPtrInst* GEP = llvm::dyn_cast< llvm::GetElementPtrInst>(*UI)) { llvm::Value* Arg = GEP->getOperand(0); if (Arg == I) instrumentInst(GEP, Arg); } else { // Check whether I is used as the first argument for a call instruction. // If it is, then instrument the call instruction. llvm::CallSite CS(*UI); if (CS) { llvm::CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); if (i != e) { llvm::Value *Arg = *i; if (Arg == I) instrumentInst(CS.getInstruction(), Arg); } } } } } return true; } void NullDerefProtectionTransformer::instrumentCallInst(llvm::Instruction* TheCall, const std::bitset<32>& ArgIndexs) { llvm::Type* Int8PtrTy = llvm::Type::getInt8PtrTy(TheCall->getContext()); llvm::CallSite CS = TheCall; for (int index = 0; index < 32; ++index) { if (!ArgIndexs.test(index)) continue; llvm::Value* Arg = CS.getArgument(index); if (!Arg) continue; llvm::Type* ArgTy = Arg->getType(); if (ArgTy != Int8PtrTy) continue; llvm::BasicBlock* OldBB = TheCall->getParent(); llvm::ICmpInst* Cmp = new llvm::ICmpInst(TheCall, llvm::CmpInst::ICMP_EQ, Arg, llvm::Constant::getNullValue(ArgTy), ""); llvm::Instruction* Inst = Builder->GetInsertPoint(); llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst); OldBB->getTerminator()->eraseFromParent(); llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB); } } void NullDerefProtectionTransformer::handleNonNullArgCall(llvm::Module& M, const llvm::StringRef& name, const std::bitset<32>& ArgIndexs) { // Get the function by the name. llvm::Function* func = M.getFunction(name); if (!func) return; // Find all the instructions that calls the function. std::vector<llvm::Instruction*> WorkList; for (llvm::Value::use_iterator I = func->use_begin(), E = func->use_end(); I != E; ++I) { llvm::CallSite CS(*I); if (!CS || CS.getCalledValue() != func) continue; WorkList.push_back(CS.getInstruction()); } // There is no call instructions that call the function and return. if (WorkList.empty()) return; // Instrument all the call instructions that call the function. for (std::vector<llvm::Instruction*>::iterator I = WorkList.begin(), E = WorkList.end(); I != E; ++I) { Inst = *I; Builder->SetInsertPoint(Inst); instrumentCallInst(Inst, ArgIndexs); } return; } } // end namespace cling <commit_msg>Improve style.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasilev@cern.ch> // author: Baozeng Ding <sploving1@gmail.com> //------------------------------------------------------------------------------ #include "NullDerefProtectionTransformer.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/Mangle.h" #include "clang/Basic/SourceLocation.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaDiagnostic.h" #include "llvm/IR/Module.h" #include "llvm/IR/Constants.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/InstIterator.h" #include <cstdio> #include "unistd.h" extern "C" { bool shouldProceed(void *S, void *T) { using namespace clang; Sema *Sem = (Sema *)S; DiagnosticsEngine& Diag = Sem->getDiagnostics(); cling::Transaction* Trans = (cling::Transaction*)T; // Here we will cheat a bit and assume that the warning came from the last // stmt, which will be in the 90% of the cases. CompoundStmt* CS = cast<CompoundStmt>(Trans->getWrapperFD()->getBody()); // Skip the NullStmts. SourceLocation Loc = CS->getLocStart(); for(CompoundStmt::const_reverse_body_iterator I = CS->body_rbegin(), E = CS->body_rend(); I != E; ++I) if (!isa<NullStmt>(*I)) { Loc = (*I)->getLocStart(); break; } Diag.Report(Loc, diag::warn_null_ptr_deref); if (isatty(fileno(stdin))) { int input = getchar(); getchar(); if (input == 'y' || input == 'Y') return false; } return true; } } using namespace clang; namespace cling { typedef std::map<llvm::StringRef, std::bitset<32> > nonnull_map_t; // NonNullDeclFinder finds the function decls with nonnull attribute args. class NonNullDeclFinder : public RecursiveASTVisitor<NonNullDeclFinder> { private: Sema* m_Sema; llvm::SmallVector<llvm::StringRef, 8> m_NonNullDeclNames; nonnull_map_t m_NonNullArgIndexs; public: NonNullDeclFinder(Sema* S) : m_Sema(S) {} const llvm::SmallVector<llvm::StringRef, 8>& getDeclNames() const { return m_NonNullDeclNames; } const nonnull_map_t& getArgIndexs() const { return m_NonNullArgIndexs; } // Deal with all the call expr in the transaction. bool VisitCallExpr(CallExpr* TheCall) { if (FunctionDecl* FDecl = TheCall->getDirectCallee()) { std::bitset<32> ArgIndexs; for (specific_attr_iterator<NonNullAttr> I = FDecl->specific_attr_begin<NonNullAttr>(), E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) { NonNullAttr *NonNull = *I; // Store all the null attr argument's index into "ArgIndexs". for (NonNullAttr::args_iterator i = NonNull->args_begin(), e = NonNull->args_end(); i != e; ++i) ArgIndexs.set(*i); } if (ArgIndexs.any()) { // Get the function decl's name. llvm::StringRef FName = FDecl->getName(); // Store the function decl's name into the vector. m_NonNullDeclNames.push_back(FName); // Store the function decl's name with its null attr args' indexes // into the map. m_NonNullArgIndexs.insert(std::make_pair(FName, ArgIndexs)); } } return true; // returning false will abort the in-depth traversal. } }; NullDerefProtectionTransformer::NullDerefProtectionTransformer(Sema *S) : TransactionTransformer(S), FailBB(0), Builder(0), Inst(0) {} NullDerefProtectionTransformer::~NullDerefProtectionTransformer() {} void NullDerefProtectionTransformer::Transform() { FunctionDecl* FD = getTransaction()->getWrapperFD(); if (!FD) return; // Copied from Interpreter.cpp; if (!m_MangleCtx) m_MangleCtx.reset(FD->getASTContext().createMangleContext()); std::string mangledName; if (m_MangleCtx->shouldMangleDeclName(FD)) { llvm::raw_string_ostream RawStr(mangledName); switch(FD->getKind()) { case Decl::CXXConstructor: //Ctor_Complete, // Complete object ctor //Ctor_Base, // Base object ctor //Ctor_CompleteAllocating // Complete object allocating ctor (unused) m_MangleCtx->mangleCXXCtor(cast<CXXConstructorDecl>(FD), Ctor_Complete, RawStr); break; case Decl::CXXDestructor: //Dtor_Deleting, // Deleting dtor //Dtor_Complete, // Complete object dtor //Dtor_Base // Base object dtor m_MangleCtx->mangleCXXDtor(cast<CXXDestructorDecl>(FD), Dtor_Complete, RawStr); break; default : m_MangleCtx->mangleName(FD, RawStr); break; } RawStr.flush(); } else { mangledName = FD->getNameAsString(); } // Find the function in the module. llvm::Function* F = getTransaction()->getModule()->getFunction(mangledName); if (!F) return; llvm::IRBuilder<> TheBuilder(F->getContext()); Builder = &TheBuilder; runOnFunction(*F); NonNullDeclFinder Finder(m_Sema); // Find all the function decls with null attribute arguments. for (size_t Idx = 0, E = getTransaction()->size(); Idx < E; ++Idx) { Transaction::DelayCallInfo I = (*getTransaction())[Idx]; for (DeclGroupRef::const_iterator J = I.m_DGR.begin(), JE = I.m_DGR.end(); J != JE; ++J) if ((*J)->hasBody()) Finder.TraverseStmt((*J)->getBody()); } const llvm::SmallVector<llvm::StringRef, 8>& FDeclNames = Finder.getDeclNames(); if (FDeclNames.empty()) return; llvm::Module* M = F->getParent(); for (llvm::SmallVector<llvm::StringRef, 8>::const_iterator i = FDeclNames.begin(), e = FDeclNames.end(); i != e; ++i) { const nonnull_map_t& ArgIndexs = Finder.getArgIndexs(); nonnull_map_t::const_iterator it = ArgIndexs.find(*i); if (it != ArgIndexs.end()) { const std::bitset<32>& ArgNums = it->second; handleNonNullArgCall(*M, *i, ArgNums); } } } llvm::BasicBlock* NullDerefProtectionTransformer::getTrapBB(llvm::BasicBlock* BB) { llvm::Function* Fn = Inst->getParent()->getParent(); llvm::Module* Md = Fn->getParent(); llvm::LLVMContext& ctx = Fn->getContext(); llvm::BasicBlock::iterator PreInsertInst = Builder->GetInsertPoint(); FailBB = llvm::BasicBlock::Create(ctx, "FailBlock", Fn); Builder->SetInsertPoint(FailBB); std::vector<llvm::Type*> ArgTys; llvm::Type* VoidTy = llvm::Type::getInt8PtrTy(ctx); ArgTys.push_back(VoidTy); ArgTys.push_back(VoidTy); llvm::FunctionType* FTy = llvm::FunctionType::get(llvm::Type::getInt1Ty(ctx), ArgTys, false); llvm::Function* CallBackFn = cast<llvm::Function>(Md->getOrInsertFunction("shouldProceed", FTy)); void* SemaRef = (void*)m_Sema; // copied from JIT.cpp llvm::Constant* SemaRefCnt = 0; llvm::Type* constantIntTy = 0; if (sizeof(void*) == 4) constantIntTy = llvm::Type::getInt32Ty(ctx); else constantIntTy = llvm::Type::getInt64Ty(ctx); SemaRefCnt = llvm::ConstantInt::get(constantIntTy, (uintptr_t)SemaRef); llvm::Value* Arg1 = llvm::ConstantExpr::getIntToPtr(SemaRefCnt, VoidTy); Transaction* Trans = getTransaction(); void* TransRef = (void*) Trans; llvm::Constant* TransRefCnt = llvm::ConstantInt::get(constantIntTy, (uintptr_t)TransRef); llvm::Value* Arg2 = llvm::ConstantExpr::getIntToPtr(TransRefCnt, VoidTy); llvm::CallInst* CI = Builder->CreateCall2(CallBackFn, Arg1, Arg2); llvm::Value* TrueVl = llvm::ConstantInt::get(ctx, llvm::APInt(1, 1)); llvm::Value* RetVl = CI; llvm::ICmpInst* Cmp = new llvm::ICmpInst(*FailBB, llvm::CmpInst::ICMP_EQ, RetVl, TrueVl, ""); llvm::BasicBlock *HandleBB = llvm::BasicBlock::Create(ctx,"HandleBlock", Fn); llvm::BranchInst::Create(HandleBB, BB, Cmp, FailBB); llvm::ReturnInst::Create(Fn->getContext(), HandleBB); Builder->SetInsertPoint(PreInsertInst); return FailBB; } // Insert a cmp instruction before the "Inst" instruction to check whether the // argument "Arg" for the instruction "Inst" is null or not. void NullDerefProtectionTransformer::instrumentInst(llvm::Instruction* Inst, llvm::Value* Arg) { llvm::BasicBlock* OldBB = Inst->getParent(); // Insert a cmp instruction to check whether "Arg" is null or not. llvm::ICmpInst* Cmp = new llvm::ICmpInst(Inst, llvm::CmpInst::ICMP_EQ, Arg, llvm::Constant::getNullValue(Arg->getType()), ""); // The block is splited into two blocks, "OldBB" and "NewBB", by the "Inst" // instruction. After that split, "Inst" is at the start of "NewBB". Then // insert a branch instruction at the end of "OldBB". If "Arg" is null, // it will jump to "FailBB" created by "getTrapBB" function. Else, it means // jump to the "NewBB". llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst); OldBB->getTerminator()->eraseFromParent(); llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB); } bool NullDerefProtectionTransformer::runOnFunction(llvm::Function &F) { std::vector<llvm::Instruction*> WorkList; for (llvm::inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) { llvm::Instruction* I = &*i; if (llvm::isa<llvm::LoadInst>(I)) WorkList.push_back(I); } for (std::vector<llvm::Instruction*>::iterator i = WorkList.begin(), e = WorkList.end(); i != e; ++i) { Inst = *i; Builder->SetInsertPoint(Inst); llvm::LoadInst* I = llvm::cast<llvm::LoadInst>(*i); // Find all the instructions that uses the instruction I. for (llvm::Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) { // Check whether I is used as the first argument for a load instruction. // If it is, then instrument the load instruction. if (llvm::LoadInst* LI = llvm::dyn_cast<llvm::LoadInst>(*UI)) { llvm::Value* Arg = LI->getOperand(0); if (Arg == I) instrumentInst(LI, Arg); } // Check whether I is used as the second argument for a store // instruction. If it is, then instrument the store instruction. else if (llvm::StoreInst* SI = llvm::dyn_cast<llvm::StoreInst>(*UI)) { llvm::Value* Arg = SI->getOperand(1); if (Arg == I) instrumentInst(SI, Arg); } // Check whether I is used as the first argument for a GEP instruction. // If it is, then instrument the GEP instruction. else if (llvm::GetElementPtrInst* GEP = llvm::dyn_cast< llvm::GetElementPtrInst>(*UI)) { llvm::Value* Arg = GEP->getOperand(0); if (Arg == I) instrumentInst(GEP, Arg); } else { // Check whether I is used as the first argument for a call instruction. // If it is, then instrument the call instruction. llvm::CallSite CS(*UI); if (CS) { llvm::CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end(); if (i != e) { llvm::Value *Arg = *i; if (Arg == I) instrumentInst(CS.getInstruction(), Arg); } } } } } return true; } void NullDerefProtectionTransformer::instrumentCallInst(llvm::Instruction* TheCall, const std::bitset<32>& ArgIndexs) { llvm::Type* Int8PtrTy = llvm::Type::getInt8PtrTy(TheCall->getContext()); llvm::CallSite CS = TheCall; for (int index = 0; index < 32; ++index) { if (!ArgIndexs.test(index)) continue; llvm::Value* Arg = CS.getArgument(index); if (!Arg) continue; llvm::Type* ArgTy = Arg->getType(); if (ArgTy != Int8PtrTy) continue; llvm::BasicBlock* OldBB = TheCall->getParent(); llvm::ICmpInst* Cmp = new llvm::ICmpInst(TheCall, llvm::CmpInst::ICMP_EQ, Arg, llvm::Constant::getNullValue(ArgTy), ""); llvm::Instruction* Inst = Builder->GetInsertPoint(); llvm::BasicBlock* NewBB = OldBB->splitBasicBlock(Inst); OldBB->getTerminator()->eraseFromParent(); llvm::BranchInst::Create(getTrapBB(NewBB), NewBB, Cmp, OldBB); } } void NullDerefProtectionTransformer::handleNonNullArgCall(llvm::Module& M, const llvm::StringRef& name, const std::bitset<32>& ArgIndexs) { // Get the function by the name. llvm::Function* func = M.getFunction(name); if (!func) return; // Find all the instructions that calls the function. std::vector<llvm::Instruction*> WorkList; for (llvm::Value::use_iterator I = func->use_begin(), E = func->use_end(); I != E; ++I) { llvm::CallSite CS(*I); if (!CS || CS.getCalledValue() != func) continue; WorkList.push_back(CS.getInstruction()); } // There is no call instructions that call the function and return. if (WorkList.empty()) return; // Instrument all the call instructions that call the function. for (std::vector<llvm::Instruction*>::iterator I = WorkList.begin(), E = WorkList.end(); I != E; ++I) { Inst = *I; Builder->SetInsertPoint(Inst); instrumentCallInst(Inst, ArgIndexs); } return; } } // end namespace cling <|endoftext|>
<commit_before>#include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <cal3d/buffersource.h> #include <cal3d/coreanimation.h> #include <cal3d/coreanimatedmorph.h> #include <cal3d/corebone.h> #include <cal3d/corematerial.h> #include <cal3d/coremesh.h> #include <cal3d/coreskeleton.h> #include <cal3d/coresubmesh.h> #include <cal3d/loader.h> #include <cal3d/saver.h> #include <cal3d/error.h> using namespace boost::python; CalCoreAnimationPtr loadCoreAnimationFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimationPtr(CalLoader::loadCoreAnimation(cbs)); } bool saveCoreAnimation(const boost::shared_ptr<CalCoreAnimation>& animation, const std::string& path) { return CalSaver::saveCoreAnimation(path, animation.get()); } CalCoreSkeletonPtr loadCoreSkeletonFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreSkeletonPtr(CalLoader::loadCoreSkeleton(cbs)); } bool saveCoreSkeleton(const boost::shared_ptr<CalCoreSkeleton>& skeleton, const std::string& path) { return CalSaver::saveCoreSkeleton(path, skeleton.get()); } CalCoreMaterialPtr loadCoreMaterialFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMaterialPtr(CalLoader::loadCoreMaterial(cbs)); } bool saveCoreMaterial(const boost::shared_ptr<CalCoreMaterial>& material, const std::string& path) { return CalSaver::saveCoreMaterial(path, material.get()); } CalCoreMeshPtr loadCoreMeshFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMeshPtr(CalLoader::loadCoreMesh(cbs)); } bool saveCoreMesh(const boost::shared_ptr<CalCoreMesh>& mesh, const std::string& path) { return CalSaver::saveCoreMesh(path, mesh.get()); } CalCoreAnimatedMorphPtr loadCoreAnimatedMorphFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimatedMorphPtr(CalLoader::loadCoreAnimatedMorph(cbs)); } bool saveCoreAnimatedMorph(const boost::shared_ptr<CalCoreAnimatedMorph>& animatedMorph, const std::string& path) { return CalSaver::saveCoreAnimatedMorph(path, animatedMorph.get()); } tuple getCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel) { CalVector sceneAmbient = skel->sceneAmbientColor; return make_tuple( sceneAmbient.x, sceneAmbient.y, sceneAmbient.z ); } void setCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel, tuple c) { if (len(c) != 3) { PyErr_SetString(PyExc_ValueError, "sceneAmbientColor must be a triple"); throw_error_already_set(); } skel->sceneAmbientColor.x = extract<float>(c[0]); skel->sceneAmbientColor.y = extract<float>(c[1]); skel->sceneAmbientColor.z = extract<float>(c[2]); } list getKeyframes(const CalCoreMorphTrack* t) { list rv; const std::vector<CalCoreMorphKeyframe>& keyframes = t->keyframes; for ( std::vector<CalCoreMorphKeyframe>::const_iterator i = keyframes.begin(); i != keyframes.end(); ++i ) { rv.append(*i); } return rv; } list getTracks(const CalCoreAnimatedMorph* m) { list rv; const std::vector<CalCoreMorphTrack>& tracks = m->tracks; for ( std::vector<CalCoreMorphTrack>::const_iterator i = tracks.begin(); i != tracks.end(); ++i ) { rv.append(*i); } return rv; } namespace cal3d { struct PythonBuffer : public Buffer { public: PythonBuffer(PyObject* p) { _ = p; incref(get()); } ~PythonBuffer() { boost::python::PyGILState_AssertIsCurrent(); decref(get()); } size_t size() const { void* data; return get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); } const void* data() const { void* data; get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); return data; } boost::shared_ptr<Buffer> clone() const { return boost::shared_ptr<Buffer>(new PythonBuffer(get())); } private: PyObject* get() const { return static_cast<PyObject*>(_); } }; struct BufferFromPythonObject { BufferFromPythonObject() { converter::registry::push_back( &convertible, &construct, boost::python::type_id<Buffer>() ); } static void* convertible(PyObject* obj_ptr) { return (obj_ptr->ob_type->tp_as_buffer && obj_ptr->ob_type->tp_as_buffer->bf_getreadbuffer) ? obj_ptr : 0; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data ) { // Note that we're registered as a converter to the Buffer interface, // so Boost has already allocated sizeof(Buffer) for us. Since we're // constructing PythonStringBuffer into that memory, assert that // PythonStringBuffer and Buffer have the same size. BOOST_STATIC_ASSERT(sizeof(Buffer) == sizeof(PythonBuffer)); void* storage = ((boost::python::converter::rvalue_from_python_storage<PythonBuffer>*)data)->storage.bytes; new(storage) PythonBuffer(obj_ptr); data->convertible = storage; } }; } template<unsigned i> CalIndex getFaceIndex(const CalCoreSubmesh::Face& f) { return f.vertexId[i]; } struct PythonVertex { PythonVertex() {} PythonVertex(const CalCoreSubmesh::Vertex& v) { position.x = v.position.x; position.y = v.position.y; position.z = v.position.z; normal.x = v.normal.x; normal.y = v.normal.y; normal.z = v.normal.z; } CalVector position; CalVector normal; bool operator==(const PythonVertex& rhs) const { return position == rhs.position && normal == rhs.normal; } }; std::vector<PythonVertex> getVertices(const CalCoreSubmesh& submesh) { return std::vector<PythonVertex>( submesh.getVectorVertex().begin(), submesh.getVectorVertex().end()); } #ifndef NDEBUG BOOST_PYTHON_MODULE(_cal3d_debug) #else BOOST_PYTHON_MODULE(_cal3d) #endif { cal3d::BufferFromPythonObject(); class_<CalVector>("Vector") .def_readwrite("x", &CalVector::x) .def_readwrite("y", &CalVector::y) .def_readwrite("z", &CalVector::z) ; class_<CalQuaternion>("Quaternion") .def_readwrite("x", &CalQuaternion::x) .def_readwrite("y", &CalQuaternion::y) .def_readwrite("z", &CalQuaternion::z) .def_readwrite("w", &CalQuaternion::w) ; class_<cal3d::Transform>("Transform") .def_readwrite("translation", &cal3d::Transform::translation) .def_readwrite("rotation", &cal3d::Transform::rotation) ; class_<CalCoreBone, boost::shared_ptr<CalCoreBone> >("CoreBone", no_init) .def(init<std::string>()) .def_readwrite("parentIndex", &CalCoreBone::parentId) .def_readwrite("name", &CalCoreBone::name) .def_readwrite("relativeTransform", &CalCoreBone::relativeTransform) .def_readwrite("boneSpaceTransform", &CalCoreBone::boneSpaceTransform) ; class_< std::vector<boost::shared_ptr<CalCoreBone> > >("BoneVector") .def(vector_indexing_suite< std::vector<boost::shared_ptr<CalCoreBone> >, true >()) ; class_<CalCoreSkeleton, boost::shared_ptr<CalCoreSkeleton> >("CoreSkeleton") .def("addCoreBone", &CalCoreSkeleton::addCoreBone) .add_property("sceneAmbientColor", &getCoreSkeletonSceneAmbientColor, &setCoreSkeletonSceneAmbientColor) .add_property("bones", &CalCoreSkeleton::coreBones) ; { scope CalCoreMaterial_class( class_<CalCoreMaterial, boost::shared_ptr<CalCoreMaterial> >("CoreMaterial") .def_readwrite("maps", &CalCoreMaterial::maps) ); class_< std::vector<CalCoreMaterial::Map> >("MapVector") .def(vector_indexing_suite<std::vector<CalCoreMaterial::Map> >()) ; class_<CalCoreMaterial::Map>("Map") .def_readwrite("filename", &CalCoreMaterial::Map::filename) .def_readwrite("type", &CalCoreMaterial::Map::type) ; } class_<CalCoreSubmesh::Face>("Triangle") .add_property("v1", &getFaceIndex<0>) .add_property("v2", &getFaceIndex<1>) .add_property("v3", &getFaceIndex<2>) ; class_< std::vector<CalCoreSubmesh::Face> >("TriangleVector") .def(vector_indexing_suite< std::vector<CalCoreSubmesh::Face>, true >()) ; class_<PythonVertex>("Vertex") .def_readwrite("position", &PythonVertex::position) .def_readwrite("normal", &PythonVertex::normal) ; class_< std::vector<PythonVertex> >("VertexVector") .def(vector_indexing_suite< std::vector<PythonVertex>, true >()) ; class_<CalCoreSubmesh::TextureCoordinate>("TextureCoordinate") .def_readwrite("u", &CalCoreSubmesh::TextureCoordinate::u) .def_readwrite("v", &CalCoreSubmesh::TextureCoordinate::v) ; class_< std::vector<CalCoreSubmesh::TextureCoordinate> >("TextureCoordinateVector") .def(vector_indexing_suite<std::vector<CalCoreSubmesh::TextureCoordinate>, true>()) ; class_< std::vector< std::vector<CalCoreSubmesh::TextureCoordinate> > >("TextureCoordinateVectorVector") .def(vector_indexing_suite<std::vector< std::vector<CalCoreSubmesh::TextureCoordinate> >, true>()) ; class_<CalCoreSubmesh, boost::shared_ptr<CalCoreSubmesh>, boost::noncopyable>("CoreSubmesh", no_init) .def_readwrite("coreMaterialThreadId", &CalCoreSubmesh::coreMaterialThreadId) .def_readwrite("triangles", &CalCoreSubmesh::faces) .add_property("vertices", &getVertices) .add_property("hasVertexColors", &CalCoreSubmesh::hasVertexColors) .add_property("colors", make_function(&CalCoreSubmesh::getVertexColors, return_value_policy<return_by_value>())) .add_property("texcoords", make_function(&CalCoreSubmesh::getVectorVectorTextureCoordinate, return_value_policy<return_by_value>())) ; class_< CalCoreMesh::CalCoreSubmeshVector >("CalCoreSubmeshVector") .def(vector_indexing_suite<CalCoreMesh::CalCoreSubmeshVector, true>()) ; class_<CalCoreMesh, boost::shared_ptr<CalCoreMesh> >("CoreMesh") .def_readwrite("submeshes", &CalCoreMesh::submeshes) ; class_<CalCoreAnimation, boost::shared_ptr<CalCoreAnimation> >("CoreAnimation") ; class_<CalCoreMorphKeyframe>("CoreMorphKeyframe") .add_property("time", &CalCoreMorphKeyframe::time) .add_property("weight", &CalCoreMorphKeyframe::weight) ; class_<CalCoreMorphTrack, boost::shared_ptr<CalCoreMorphTrack> >("CoreMorphTrack") .def_readonly("name", &CalCoreMorphTrack::morphName) .add_property("keyframes", &getKeyframes) ; class_<CalCoreAnimatedMorph, boost::shared_ptr<CalCoreAnimatedMorph> >("CoreAnimatedMorph") .def("removeZeroScaleTracks", &CalCoreAnimatedMorph::removeZeroScaleTracks) .def_readonly("duration", &CalCoreAnimatedMorph::duration) .add_property("tracks", &getTracks) ; def("loadCoreAnimationFromBuffer", &loadCoreAnimationFromBuffer); def("saveCoreAnimation", &saveCoreAnimation); def("saveCoreAnimationToBuffer", &CalSaver::saveCoreAnimationToBuffer); def("loadCoreSkeletonFromBuffer", &loadCoreSkeletonFromBuffer); def("saveCoreSkeleton", &saveCoreSkeleton); def("saveCoreSkeletonToBuffer", &CalSaver::saveCoreSkeletonToBuffer); def("loadCoreMaterialFromBuffer", &loadCoreMaterialFromBuffer); def("saveCoreMaterial", &saveCoreMaterial); def("saveCoreMaterialToBuffer", &CalSaver::saveCoreMaterialToBuffer); def("loadCoreMeshFromBuffer", &loadCoreMeshFromBuffer); def("saveCoreMesh", &saveCoreMesh); def("saveCoreMeshToBuffer", &CalSaver::saveCoreMeshToBuffer); def("loadCoreAnimatedMorphFromBuffer", &loadCoreAnimatedMorphFromBuffer); def("saveCoreAnimatedMorph", &saveCoreAnimatedMorph); def("saveCoreAnimatedMorphToBuffer", &CalSaver::saveCoreAnimatedMorphToBuffer); def("getLastErrorText", &CalError::getLastErrorText); } <commit_msg>Include influences in the asset server<commit_after>#include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <cal3d/buffersource.h> #include <cal3d/coreanimation.h> #include <cal3d/coreanimatedmorph.h> #include <cal3d/corebone.h> #include <cal3d/corematerial.h> #include <cal3d/coremesh.h> #include <cal3d/coreskeleton.h> #include <cal3d/coresubmesh.h> #include <cal3d/loader.h> #include <cal3d/saver.h> #include <cal3d/error.h> using namespace boost::python; CalCoreAnimationPtr loadCoreAnimationFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimationPtr(CalLoader::loadCoreAnimation(cbs)); } bool saveCoreAnimation(const boost::shared_ptr<CalCoreAnimation>& animation, const std::string& path) { return CalSaver::saveCoreAnimation(path, animation.get()); } CalCoreSkeletonPtr loadCoreSkeletonFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreSkeletonPtr(CalLoader::loadCoreSkeleton(cbs)); } bool saveCoreSkeleton(const boost::shared_ptr<CalCoreSkeleton>& skeleton, const std::string& path) { return CalSaver::saveCoreSkeleton(path, skeleton.get()); } CalCoreMaterialPtr loadCoreMaterialFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMaterialPtr(CalLoader::loadCoreMaterial(cbs)); } bool saveCoreMaterial(const boost::shared_ptr<CalCoreMaterial>& material, const std::string& path) { return CalSaver::saveCoreMaterial(path, material.get()); } CalCoreMeshPtr loadCoreMeshFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreMeshPtr(CalLoader::loadCoreMesh(cbs)); } bool saveCoreMesh(const boost::shared_ptr<CalCoreMesh>& mesh, const std::string& path) { return CalSaver::saveCoreMesh(path, mesh.get()); } CalCoreAnimatedMorphPtr loadCoreAnimatedMorphFromBuffer(const cal3d::Buffer& buffer) { CalBufferSource cbs(buffer.data(), buffer.size()); return CalCoreAnimatedMorphPtr(CalLoader::loadCoreAnimatedMorph(cbs)); } bool saveCoreAnimatedMorph(const boost::shared_ptr<CalCoreAnimatedMorph>& animatedMorph, const std::string& path) { return CalSaver::saveCoreAnimatedMorph(path, animatedMorph.get()); } tuple getCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel) { CalVector sceneAmbient = skel->sceneAmbientColor; return make_tuple( sceneAmbient.x, sceneAmbient.y, sceneAmbient.z ); } void setCoreSkeletonSceneAmbientColor(const CalCoreSkeletonPtr& skel, tuple c) { if (len(c) != 3) { PyErr_SetString(PyExc_ValueError, "sceneAmbientColor must be a triple"); throw_error_already_set(); } skel->sceneAmbientColor.x = extract<float>(c[0]); skel->sceneAmbientColor.y = extract<float>(c[1]); skel->sceneAmbientColor.z = extract<float>(c[2]); } list getKeyframes(const CalCoreMorphTrack* t) { list rv; const std::vector<CalCoreMorphKeyframe>& keyframes = t->keyframes; for ( std::vector<CalCoreMorphKeyframe>::const_iterator i = keyframes.begin(); i != keyframes.end(); ++i ) { rv.append(*i); } return rv; } list getTracks(const CalCoreAnimatedMorph* m) { list rv; const std::vector<CalCoreMorphTrack>& tracks = m->tracks; for ( std::vector<CalCoreMorphTrack>::const_iterator i = tracks.begin(); i != tracks.end(); ++i ) { rv.append(*i); } return rv; } namespace cal3d { struct PythonBuffer : public Buffer { public: PythonBuffer(PyObject* p) { _ = p; incref(get()); } ~PythonBuffer() { boost::python::PyGILState_AssertIsCurrent(); decref(get()); } size_t size() const { void* data; return get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); } const void* data() const { void* data; get()->ob_type->tp_as_buffer->bf_getreadbuffer(get(), 0, &data); return data; } boost::shared_ptr<Buffer> clone() const { return boost::shared_ptr<Buffer>(new PythonBuffer(get())); } private: PyObject* get() const { return static_cast<PyObject*>(_); } }; struct BufferFromPythonObject { BufferFromPythonObject() { converter::registry::push_back( &convertible, &construct, boost::python::type_id<Buffer>() ); } static void* convertible(PyObject* obj_ptr) { return (obj_ptr->ob_type->tp_as_buffer && obj_ptr->ob_type->tp_as_buffer->bf_getreadbuffer) ? obj_ptr : 0; } static void construct( PyObject* obj_ptr, boost::python::converter::rvalue_from_python_stage1_data* data ) { // Note that we're registered as a converter to the Buffer interface, // so Boost has already allocated sizeof(Buffer) for us. Since we're // constructing PythonStringBuffer into that memory, assert that // PythonStringBuffer and Buffer have the same size. BOOST_STATIC_ASSERT(sizeof(Buffer) == sizeof(PythonBuffer)); void* storage = ((boost::python::converter::rvalue_from_python_storage<PythonBuffer>*)data)->storage.bytes; new(storage) PythonBuffer(obj_ptr); data->convertible = storage; } }; } template<unsigned i> CalIndex getFaceIndex(const CalCoreSubmesh::Face& f) { return f.vertexId[i]; } struct PythonVertex { PythonVertex() {} PythonVertex(const CalCoreSubmesh::Vertex& v) { position.x = v.position.x; position.y = v.position.y; position.z = v.position.z; normal.x = v.normal.x; normal.y = v.normal.y; normal.z = v.normal.z; } CalVector position; CalVector normal; bool operator==(const PythonVertex& rhs) const { return position == rhs.position && normal == rhs.normal; } }; std::vector<PythonVertex> getVertices(const CalCoreSubmesh& submesh) { return std::vector<PythonVertex>( submesh.getVectorVertex().begin(), submesh.getVectorVertex().end()); } template<typename T> void exportVector(const char* name) { class_<std::vector<typename T> >(name) .def(vector_indexing_suite< std::vector<typename T>, true>()) ; } #ifndef NDEBUG BOOST_PYTHON_MODULE(_cal3d_debug) #else BOOST_PYTHON_MODULE(_cal3d) #endif { cal3d::BufferFromPythonObject(); class_<CalVector>("Vector") .def_readwrite("x", &CalVector::x) .def_readwrite("y", &CalVector::y) .def_readwrite("z", &CalVector::z) ; class_<CalQuaternion>("Quaternion") .def_readwrite("x", &CalQuaternion::x) .def_readwrite("y", &CalQuaternion::y) .def_readwrite("z", &CalQuaternion::z) .def_readwrite("w", &CalQuaternion::w) ; class_<cal3d::Transform>("Transform") .def_readwrite("translation", &cal3d::Transform::translation) .def_readwrite("rotation", &cal3d::Transform::rotation) ; class_<CalCoreBone, boost::shared_ptr<CalCoreBone> >("CoreBone", no_init) .def(init<std::string>()) .def_readwrite("parentIndex", &CalCoreBone::parentId) .def_readwrite("name", &CalCoreBone::name) .def_readwrite("relativeTransform", &CalCoreBone::relativeTransform) .def_readwrite("boneSpaceTransform", &CalCoreBone::boneSpaceTransform) ; exportVector<CalCoreBonePtr>("BoneVector"); class_<CalCoreSkeleton, boost::shared_ptr<CalCoreSkeleton> >("CoreSkeleton") .def("addCoreBone", &CalCoreSkeleton::addCoreBone) .add_property("sceneAmbientColor", &getCoreSkeletonSceneAmbientColor, &setCoreSkeletonSceneAmbientColor) .add_property("bones", &CalCoreSkeleton::coreBones) ; { scope CalCoreMaterial_class( class_<CalCoreMaterial, boost::shared_ptr<CalCoreMaterial> >("CoreMaterial") .def_readwrite("maps", &CalCoreMaterial::maps) ); exportVector<CalCoreMaterial::Map>("MapVector"); class_<CalCoreMaterial::Map>("Map") .def_readwrite("filename", &CalCoreMaterial::Map::filename) .def_readwrite("type", &CalCoreMaterial::Map::type) ; } class_<CalCoreSubmesh::Face>("Triangle") .add_property("v1", &getFaceIndex<0>) .add_property("v2", &getFaceIndex<1>) .add_property("v3", &getFaceIndex<2>) ; exportVector<CalCoreSubmesh::Face>("TriangleVector"); class_<PythonVertex>("Vertex") .def_readwrite("position", &PythonVertex::position) .def_readwrite("normal", &PythonVertex::normal) ; exportVector<PythonVertex>("VertexVector"); class_<CalCoreSubmesh::TextureCoordinate>("TextureCoordinate") .def_readwrite("u", &CalCoreSubmesh::TextureCoordinate::u) .def_readwrite("v", &CalCoreSubmesh::TextureCoordinate::v) ; exportVector<CalCoreSubmesh::TextureCoordinate>("TextureCoordinateVector"); exportVector<std::vector<CalCoreSubmesh::TextureCoordinate> >("TextureCoordinateVectorVector"); class_<CalCoreSubmesh::Influence>("Influence") .def_readwrite("boneId", &CalCoreSubmesh::Influence::boneId) .def_readwrite("weight", &CalCoreSubmesh::Influence::weight) .def_readwrite("isLast", &CalCoreSubmesh::Influence::lastInfluenceForThisVertex) ; exportVector<CalCoreSubmesh::Influence>("InfluenceVector"); class_<CalCoreSubmesh, boost::shared_ptr<CalCoreSubmesh>, boost::noncopyable>("CoreSubmesh", no_init) .def_readwrite("coreMaterialThreadId", &CalCoreSubmesh::coreMaterialThreadId) .def_readwrite("triangles", &CalCoreSubmesh::faces) .add_property("vertices", &getVertices) .add_property("hasVertexColors", &CalCoreSubmesh::hasVertexColors) .add_property("colors", make_function(&CalCoreSubmesh::getVertexColors, return_value_policy<return_by_value>())) .add_property("texcoords", make_function(&CalCoreSubmesh::getVectorVectorTextureCoordinate, return_value_policy<return_by_value>())) .add_property("influences", make_function(&CalCoreSubmesh::getInfluences, return_value_policy<return_by_value>())) ; class_< CalCoreMesh::CalCoreSubmeshVector >("CalCoreSubmeshVector") .def(vector_indexing_suite<CalCoreMesh::CalCoreSubmeshVector, true>()) ; class_<CalCoreMesh, boost::shared_ptr<CalCoreMesh> >("CoreMesh") .def_readwrite("submeshes", &CalCoreMesh::submeshes) ; class_<CalCoreAnimation, boost::shared_ptr<CalCoreAnimation> >("CoreAnimation") ; class_<CalCoreMorphKeyframe>("CoreMorphKeyframe") .add_property("time", &CalCoreMorphKeyframe::time) .add_property("weight", &CalCoreMorphKeyframe::weight) ; class_<CalCoreMorphTrack, boost::shared_ptr<CalCoreMorphTrack> >("CoreMorphTrack") .def_readonly("name", &CalCoreMorphTrack::morphName) .add_property("keyframes", &getKeyframes) ; class_<CalCoreAnimatedMorph, boost::shared_ptr<CalCoreAnimatedMorph> >("CoreAnimatedMorph") .def("removeZeroScaleTracks", &CalCoreAnimatedMorph::removeZeroScaleTracks) .def_readonly("duration", &CalCoreAnimatedMorph::duration) .add_property("tracks", &getTracks) ; def("loadCoreAnimationFromBuffer", &loadCoreAnimationFromBuffer); def("saveCoreAnimation", &saveCoreAnimation); def("saveCoreAnimationToBuffer", &CalSaver::saveCoreAnimationToBuffer); def("loadCoreSkeletonFromBuffer", &loadCoreSkeletonFromBuffer); def("saveCoreSkeleton", &saveCoreSkeleton); def("saveCoreSkeletonToBuffer", &CalSaver::saveCoreSkeletonToBuffer); def("loadCoreMaterialFromBuffer", &loadCoreMaterialFromBuffer); def("saveCoreMaterial", &saveCoreMaterial); def("saveCoreMaterialToBuffer", &CalSaver::saveCoreMaterialToBuffer); def("loadCoreMeshFromBuffer", &loadCoreMeshFromBuffer); def("saveCoreMesh", &saveCoreMesh); def("saveCoreMeshToBuffer", &CalSaver::saveCoreMeshToBuffer); def("loadCoreAnimatedMorphFromBuffer", &loadCoreAnimatedMorphFromBuffer); def("saveCoreAnimatedMorph", &saveCoreAnimatedMorph); def("saveCoreAnimatedMorphToBuffer", &CalSaver::saveCoreAnimatedMorphToBuffer); def("getLastErrorText", &CalError::getLastErrorText); } <|endoftext|>
<commit_before>//== ReturnUndefChecker.cpp -------------------------------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines ReturnUndefChecker, which is a path-sensitive // check which looks for undefined or garbage values being returned to the // caller. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" using namespace clang; using namespace ento; namespace { class ReturnUndefChecker : public Checker< check::PreStmt<ReturnStmt> > { mutable OwningPtr<BuiltinBug> BT; public: void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const; }; } void ReturnUndefChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const { const Expr *RetE = RS->getRetValue(); if (!RetE) return; if (!C.getState()->getSVal(RetE, C.getLocationContext()).isUndef()) return; ExplodedNode *N = C.generateSink(); if (!N) return; if (!BT) BT.reset(new BuiltinBug("Garbage return value", "Undefined or garbage value returned to caller")); BugReport *report = new BugReport(*BT, BT->getDescription(), N); report->addRange(RetE->getSourceRange()); report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, RetE, report)); C.EmitReport(report); } void ento::registerReturnUndefChecker(CheckerManager &mgr) { mgr.registerChecker<ReturnUndefChecker>(); } <commit_msg>Disable diagnosic path pruning for ReturnUndefChecker.<commit_after>//== ReturnUndefChecker.cpp -------------------------------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines ReturnUndefChecker, which is a path-sensitive // check which looks for undefined or garbage values being returned to the // caller. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" using namespace clang; using namespace ento; namespace { class ReturnUndefChecker : public Checker< check::PreStmt<ReturnStmt> > { mutable OwningPtr<BuiltinBug> BT; public: void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const; }; } void ReturnUndefChecker::checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const { const Expr *RetE = RS->getRetValue(); if (!RetE) return; if (!C.getState()->getSVal(RetE, C.getLocationContext()).isUndef()) return; ExplodedNode *N = C.generateSink(); if (!N) return; if (!BT) BT.reset(new BuiltinBug("Garbage return value", "Undefined or garbage value returned to caller")); BugReport *report = new BugReport(*BT, BT->getDescription(), N); report->disablePathPruning(); report->addRange(RetE->getSourceRange()); report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N, RetE, report)); C.EmitReport(report); } void ento::registerReturnUndefChecker(CheckerManager &mgr) { mgr.registerChecker<ReturnUndefChecker>(); } <|endoftext|>
<commit_before>/* * File: Renderer.cpp * Author: morgan * * Created on February 15, 2014, 2:37 PM */ #include <ogli/util.h> #include <glm/gtx/projection.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/transform2.hpp> #include <glm/gtc/random.hpp> #include "Renderer.h" #include "Vertex.h" #include "Mesh.h" #include "Texture2D.h" #include "Model.h" namespace mo { Renderer::Renderer() : position_attribute_3P3N2UV_(0, 3, "position", sizeof (Vertex), sizeof (glm::vec3), 0), normal_attribute_3P3N2UV_(1, 3, "normal", sizeof (Vertex), sizeof (glm::vec3), sizeof (glm::vec3)), uv_attribute_3P3N2UV_(2, 2, "uv", sizeof (Vertex), sizeof (glm::vec2), sizeof (glm::vec3) + sizeof (glm::vec3)) { ogli::init(); // Should this be done int ogli or mo? glEnable(GL_DEPTH_TEST); #ifdef __ANDROID__ #else glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif glDepthFunc(GL_LEQUAL); glDepthMask(true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); std::string standard_vertex_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#endif\n" "uniform mat4 model_view_projection;\n" "uniform mat4 model_view;\n" "attribute vec3 position;\n" "attribute vec3 normal;\n" "attribute vec2 uv;\n" "varying vec3 fragment_position;\n" "varying vec3 fragment_normal\n;" "varying vec2 fragment_uv;\n" "varying mat3 normal_matrix;\n" "void main()\n" "{\n" " fragment_uv = uv;\n" " fragment_position = (model_view * vec4(position, 0.0)).xyz;\n" " normal_matrix = mat3(model_view);\n" " fragment_normal = normal_matrix * normal;\n" " gl_Position = model_view_projection * vec4(position, 1.0);\n" "}\n"; std::string standard_fragment_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#endif\n" "uniform vec4 color;\n" "uniform float opacity;\n" "uniform sampler2D texture;\n" "uniform vec3 light_position;\n" "varying vec3 fragment_position;\n" "varying vec3 fragment_normal;\n" "varying vec2 fragment_uv;\n" "void main() {\n" "vec3 normal = normalize(fragment_normal);\n" "vec3 surface_to_light = light_position - fragment_position;\n" "float intensity = dot(normal, surface_to_light) / (length(surface_to_light) * length(normal));\n" "float dist = length(surface_to_light);\n" //"float att = 1.0 / (1.0 + 0.1*dist + 0.01*dist*dist);\n" "intensity = clamp(intensity, 0.0, 1.0);\n" "vec4 diffuse = texture2D(texture, fragment_uv).rgba;\n" "vec3 ambient = vec3(0.1, 0.1, 0.1);\n" "gl_FragColor = vec4((intensity*diffuse.rgb) + ambient, diffuse.a * opacity);\n" "}\n"; addProgram("standard", standard_vertex_source, standard_fragment_source); std::string text_vertex_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#endif\n" "uniform mat4 model_view_projection;\n" "uniform mat4 model_view;\n" "attribute vec3 position;\n" "attribute vec2 uv;\n" "varying vec2 v_position;\n" "varying vec2 v_uv;\n" "void main(){\n" "v_position = (model_view * vec4(position, 0.0)).xy;\n" "v_uv = uv;\n" "gl_Position = model_view_projection * vec4(position, 1.0);\n" "}\n"; std::string text_fragment_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#endif\n" "varying vec3 v_position;\n" "varying vec2 v_uv;\n" "uniform sampler2D texture;\n" "uniform float opacity;\n" "void main() {\n" "gl_FragColor = texture2D(texture, v_uv);\n" "gl_FragColor.w = gl_FragColor.w * opacity;\n" "//gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n" "}\n"; addProgram("text", text_vertex_source, text_fragment_source); std::string particles_vertex_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#endif\n" "uniform mat4 model_view_projection;\n" "uniform mat4 model_view;\n" "attribute vec3 position;\n" "attribute vec2 uv;\n" "varying vec2 v_position;\n" "varying vec2 v_uv;\n" "void main(){\n" "#ifdef GL_ES\n" "#else\n" "gl_PointSize = 3;\n" "#endif\n" "v_position = (model_view * vec4(position, 0.0)).xy;\n" "v_uv = uv;\n" "gl_Position = model_view_projection * vec4(position, 1.0);\n" "}\n"; std::string particles_fragment_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#endif\n" "varying vec3 v_position;\n" "varying vec2 v_uv;\n" "uniform float opacity;\n" "void main() {\n" "gl_FragColor = vec4(1.0, 1.0, 1.0, opacity);\n" "}\n"; addProgram("particles", particles_vertex_source, particles_fragment_source); } Renderer::~Renderer() { } void Renderer::addProgram(const std::string path, const std::string vertex_shader_source, const std::string fragment_shader_source) { auto vertex_shader = ogli::createShader(vertex_shader_source, GL_VERTEX_SHADER); auto fragment_shader = ogli::createShader(fragment_shader_source, GL_FRAGMENT_SHADER); auto program = ogli::createProgram(); ogli::attachShader(program, vertex_shader); ogli::attachShader(program, fragment_shader); ogli::bindAttribute(program, position_attribute_3P3N2UV_); ogli::bindAttribute(program, normal_attribute_3P3N2UV_); ogli::bindAttribute(program, uv_attribute_3P3N2UV_); ogli::linkProgram(program); auto mvp_uniform = ogli::createUniform(program, "model_view_projection"); auto mv_uniform = ogli::createUniform(program, "model_view"); auto texture_uniform = ogli::createUniform(program, "texture"); auto opacity_uniform = ogli::createUniform(program, "opacity"); auto light_uniform = ogli::createUniform(program, "light_position"); programs_.insert(ProgramPair(path, ProgramData{program, mvp_uniform, mv_uniform, texture_uniform, opacity_uniform, light_uniform})); } void Renderer::addProgram(const std::string path) { addProgram(path, ogli::loadText(path + ".vs"), ogli::loadText(path + ".fs")); } void Renderer::clear(const glm::vec3 color) { ogli::clearDepth(1.0f); ogli::clearColor(glm::vec4(color.r, color.g, color.b, 0.0f)); } void Renderer::render(const Model & model, const glm::mat4 transform, const glm::mat4 view, const glm::mat4 projection, const float opacity, const std::string program_name, const glm::vec3 light_position) { if (array_buffers_.find(model.mesh->id()) == array_buffers_.end()) { array_buffers_.insert(ArrayPair(model.mesh->id(), ogli::createArrayBuffer(model.mesh->verticesBegin(), model.mesh->verticesEnd()))); } if (element_array_buffers_.find(model.mesh->id()) == element_array_buffers_.end()) { element_array_buffers_.insert(ElementPair(model.mesh->id(), ogli::createElementArrayBuffer(model.mesh->elementsBegin(), model.mesh->elementsEnd()))); } if (!model.mesh->valid) { ogli::updateArrayBuffer(array_buffers_.at(model.mesh->id()), model.mesh->verticesBegin(), model.mesh->verticesEnd()); model.mesh->valid = true; } if (textures_.find(model.texture->id()) == textures_.end()) { ogli::TextureBuffer texture = ogli::createTexture(model.texture->begin(), model.texture->end(), model.texture->width(), model.texture->height(), model.texture->mipmaps); textures_.insert(std::pair<unsigned int, ogli::TextureBuffer>(model.texture->id(), texture)); } glm::mat4 mv = view * transform * model.transform; glm::mat4 mvp = projection * view * model.transform * transform; //ogli::useProgram(standard_program_); ogli::useProgram(programs_.at(program_name).program); //ogli::useProgram(std::get<0>(programs_.at(program_name))); ogli::bindBuffer(array_buffers_.at(model.mesh->id())); ogli::bindBuffer(element_array_buffers_.at(model.mesh->id())); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures_.at(model.texture->id())); ogli::uniform(programs_.at(program_name).mvp, mvp); ogli::uniform(programs_.at(program_name).mv, mv); ogli::uniform(programs_.at(program_name).texture); ogli::uniform(programs_.at(program_name).opacity, opacity); ogli::uniform(programs_.at(program_name).light_position, light_position); ogli::attribute(position_attribute_3P3N2UV_); ogli::attribute(normal_attribute_3P3N2UV_); ogli::attribute(uv_attribute_3P3N2UV_); int num_elements = std::distance(model.mesh->elementsBegin(), model.mesh->elementsEnd()); int draw_type = GL_TRIANGLES; if (model.draw == Model::Draw::LINES){ draw_type = GL_LINES; } else if (model.draw == Model::Draw::POINTS){ draw_type = GL_POINTS; } if (num_elements > 0){ ogli::drawElements(num_elements, draw_type); } else { ogli::drawArrays(std::distance(model.mesh->verticesBegin(), model.mesh->verticesEnd()), draw_type); } } }<commit_msg>Shader compability.<commit_after>/* * File: Renderer.cpp * Author: morgan * * Created on February 15, 2014, 2:37 PM */ #include <ogli/util.h> #include <glm/gtx/projection.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/transform2.hpp> #include <glm/gtc/random.hpp> #include "Renderer.h" #include "Vertex.h" #include "Mesh.h" #include "Texture2D.h" #include "Model.h" namespace mo { Renderer::Renderer() : position_attribute_3P3N2UV_(0, 3, "position", sizeof (Vertex), sizeof (glm::vec3), 0), normal_attribute_3P3N2UV_(1, 3, "normal", sizeof (Vertex), sizeof (glm::vec3), sizeof (glm::vec3)), uv_attribute_3P3N2UV_(2, 2, "uv", sizeof (Vertex), sizeof (glm::vec2), sizeof (glm::vec3) + sizeof (glm::vec3)) { ogli::init(); // Should this be done int ogli or mo? glEnable(GL_DEPTH_TEST); #ifdef __ANDROID__ #else glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif glDepthFunc(GL_LEQUAL); glDepthMask(true); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); std::string standard_vertex_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#else\n" "#version 120\n" "#endif\n" "uniform mat4 model_view_projection;\n" "uniform mat4 model_view;\n" "attribute vec3 position;\n" "attribute vec3 normal;\n" "attribute vec2 uv;\n" "varying vec3 fragment_position;\n" "varying vec3 fragment_normal\n;" "varying vec2 fragment_uv;\n" "varying mat3 normal_matrix;\n" "void main()\n" "{\n" " fragment_uv = uv;\n" " fragment_position = (model_view * vec4(position, 0.0)).xyz;\n" " normal_matrix = mat3(model_view);\n" " fragment_normal = normal_matrix * normal;\n" " gl_Position = model_view_projection * vec4(position, 1.0);\n" "}\n"; std::string standard_fragment_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#else\n" "#version 120\n" "#endif\n" "uniform vec4 color;\n" "uniform float opacity;\n" "uniform sampler2D texture;\n" "uniform vec3 light_position;\n" "varying vec3 fragment_position;\n" "varying vec3 fragment_normal;\n" "varying vec2 fragment_uv;\n" "void main() {\n" "vec3 normal = normalize(fragment_normal);\n" "vec3 surface_to_light = light_position - fragment_position;\n" "float intensity = dot(normal, surface_to_light) / (length(surface_to_light) * length(normal));\n" "float dist = length(surface_to_light);\n" //"float att = 1.0 / (1.0 + 0.1*dist + 0.01*dist*dist);\n" "intensity = clamp(intensity, 0.0, 1.0);\n" "vec4 diffuse = texture2D(texture, fragment_uv).rgba;\n" "vec3 ambient = vec3(0.1, 0.1, 0.1);\n" "gl_FragColor = vec4((intensity*diffuse.rgb) + ambient, diffuse.a * opacity);\n" "}\n"; addProgram("standard", standard_vertex_source, standard_fragment_source); std::string text_vertex_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#else\n" "#version 120\n" "#endif\n" "uniform mat4 model_view_projection;\n" "uniform mat4 model_view;\n" "attribute vec3 position;\n" "attribute vec2 uv;\n" "varying vec2 v_position;\n" "varying vec2 v_uv;\n" "void main(){\n" "v_position = (model_view * vec4(position, 0.0)).xy;\n" "v_uv = uv;\n" "gl_Position = model_view_projection * vec4(position, 1.0);\n" "}\n"; std::string text_fragment_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#else\n" "#version 120\n" "#endif\n" "varying vec3 v_position;\n" "varying vec2 v_uv;\n" "uniform sampler2D texture;\n" "uniform float opacity;\n" "void main() {\n" "gl_FragColor = texture2D(texture, v_uv);\n" "gl_FragColor.w = gl_FragColor.w * opacity;\n" "//gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n" "}\n"; addProgram("text", text_vertex_source, text_fragment_source); std::string particles_vertex_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#else\n" "#version 120\n" "#endif\n" "uniform mat4 model_view_projection;\n" "uniform mat4 model_view;\n" "attribute vec3 position;\n" "attribute vec2 uv;\n" "varying vec2 v_position;\n" "varying vec2 v_uv;\n" "void main(){\n" "#ifdef GL_ES\n" "#else\n" "gl_PointSize = 3.0;\n" "#endif\n" "v_position = (model_view * vec4(position, 0.0)).xy;\n" "v_uv = uv;\n" "gl_Position = model_view_projection * vec4(position, 1.0);\n" "}\n"; std::string particles_fragment_source = "#ifdef GL_ES\n" "precision mediump float;\n" "precision mediump int;\n" "#else\n" "#version 120\n" "#endif\n" "varying vec3 v_position;\n" "varying vec2 v_uv;\n" "uniform float opacity;\n" "void main() {\n" "gl_FragColor = vec4(1.0, 1.0, 1.0, opacity);\n" "}\n"; addProgram("particles", particles_vertex_source, particles_fragment_source); } Renderer::~Renderer() { } void Renderer::addProgram(const std::string path, const std::string vertex_shader_source, const std::string fragment_shader_source) { auto vertex_shader = ogli::createShader(vertex_shader_source, GL_VERTEX_SHADER); auto fragment_shader = ogli::createShader(fragment_shader_source, GL_FRAGMENT_SHADER); auto program = ogli::createProgram(); ogli::attachShader(program, vertex_shader); ogli::attachShader(program, fragment_shader); ogli::bindAttribute(program, position_attribute_3P3N2UV_); ogli::bindAttribute(program, normal_attribute_3P3N2UV_); ogli::bindAttribute(program, uv_attribute_3P3N2UV_); ogli::linkProgram(program); auto mvp_uniform = ogli::createUniform(program, "model_view_projection"); auto mv_uniform = ogli::createUniform(program, "model_view"); auto texture_uniform = ogli::createUniform(program, "texture"); auto opacity_uniform = ogli::createUniform(program, "opacity"); auto light_uniform = ogli::createUniform(program, "light_position"); programs_.insert(ProgramPair(path, ProgramData{program, mvp_uniform, mv_uniform, texture_uniform, opacity_uniform, light_uniform})); } void Renderer::addProgram(const std::string path) { addProgram(path, ogli::loadText(path + ".vs"), ogli::loadText(path + ".fs")); } void Renderer::clear(const glm::vec3 color) { ogli::clearDepth(1.0f); ogli::clearColor(glm::vec4(color.r, color.g, color.b, 0.0f)); } void Renderer::render(const Model & model, const glm::mat4 transform, const glm::mat4 view, const glm::mat4 projection, const float opacity, const std::string program_name, const glm::vec3 light_position) { if (array_buffers_.find(model.mesh->id()) == array_buffers_.end()) { array_buffers_.insert(ArrayPair(model.mesh->id(), ogli::createArrayBuffer(model.mesh->verticesBegin(), model.mesh->verticesEnd()))); } if (element_array_buffers_.find(model.mesh->id()) == element_array_buffers_.end()) { element_array_buffers_.insert(ElementPair(model.mesh->id(), ogli::createElementArrayBuffer(model.mesh->elementsBegin(), model.mesh->elementsEnd()))); } if (!model.mesh->valid) { ogli::updateArrayBuffer(array_buffers_.at(model.mesh->id()), model.mesh->verticesBegin(), model.mesh->verticesEnd()); model.mesh->valid = true; } if (textures_.find(model.texture->id()) == textures_.end()) { ogli::TextureBuffer texture = ogli::createTexture(model.texture->begin(), model.texture->end(), model.texture->width(), model.texture->height(), model.texture->mipmaps); textures_.insert(std::pair<unsigned int, ogli::TextureBuffer>(model.texture->id(), texture)); } glm::mat4 mv = view * transform * model.transform; glm::mat4 mvp = projection * view * model.transform * transform; //ogli::useProgram(standard_program_); ogli::useProgram(programs_.at(program_name).program); //ogli::useProgram(std::get<0>(programs_.at(program_name))); ogli::bindBuffer(array_buffers_.at(model.mesh->id())); ogli::bindBuffer(element_array_buffers_.at(model.mesh->id())); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures_.at(model.texture->id())); ogli::uniform(programs_.at(program_name).mvp, mvp); ogli::uniform(programs_.at(program_name).mv, mv); ogli::uniform(programs_.at(program_name).texture); ogli::uniform(programs_.at(program_name).opacity, opacity); ogli::uniform(programs_.at(program_name).light_position, light_position); ogli::attribute(position_attribute_3P3N2UV_); ogli::attribute(normal_attribute_3P3N2UV_); ogli::attribute(uv_attribute_3P3N2UV_); int num_elements = std::distance(model.mesh->elementsBegin(), model.mesh->elementsEnd()); int draw_type = GL_TRIANGLES; if (model.draw == Model::Draw::LINES){ draw_type = GL_LINES; } else if (model.draw == Model::Draw::POINTS){ draw_type = GL_POINTS; } if (num_elements > 0){ ogli::drawElements(num_elements, draw_type); } else { ogli::drawArrays(std::distance(model.mesh->verticesBegin(), model.mesh->verticesEnd()), draw_type); } } }<|endoftext|>
<commit_before>// ========================================================================== // Line And Polygon Geometry // // Adapted from Sonny Chan's CPSC453 OpenGL Core Profile Boilerplate // http://pages.cpsc.ucalgary.ca/~sonny.chan/cpsc453/resources/handouts/CPSC453-BoilerplateCode.zip // // Author: Matthew Sembinelli, University of Calgary // Date: January 17, 2015 // ========================================================================== #include <iostream> #include <fstream> #include <algorithm> // specify that we want the OpenGL core profile before including GLFW headers #define GLFW_INCLUDE_GLCOREARB #define GL_GLEXT_PROTOTYPES #include <GLFW/glfw3.h> using namespace std; // -------------------------------------------------------------------------- // OpenGL utility and support function prototypes void QueryGLVersion(); bool CheckGLErrors(); string LoadSource(const string &filename); GLuint CompileShader(GLenum shaderType, const string &source); GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader); // -------------------------------------------------------------------------- // Functions to set up OpenGL shader programs for rendering struct MyShader { // OpenGL names for vertex and fragment shaders, shader program GLuint vertex; GLuint fragment; GLuint program; // initialize shader and program names to zero (OpenGL reserved value) MyShader() : vertex(0), fragment(0), program(0) {} }; // load, compile, and link shaders, returning true if successful bool InitializeShaders(MyShader *shader) { // load shader source from files string vertexSource = LoadSource("vertex.glsl"); string fragmentSource = LoadSource("fragment.glsl"); if (vertexSource.empty() || fragmentSource.empty()) return false; // compile shader source into shader objects shader->vertex = CompileShader(GL_VERTEX_SHADER, vertexSource); shader->fragment = CompileShader(GL_FRAGMENT_SHADER, fragmentSource); // link shader program shader->program = LinkProgram(shader->vertex, shader->fragment); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate shader-related objects void DestroyShaders(MyShader *shader) { // unbind any shader programs and destroy shader objects glUseProgram(0); glDeleteProgram(shader->program); glDeleteShader(shader->vertex); glDeleteShader(shader->fragment); } // -------------------------------------------------------------------------- // Functions to set up OpenGL buffers for storing geometry data struct MyGeometry { // OpenGL names for array buffer objects, vertex array object GLuint vertexBuffer; GLuint colourBuffer; GLuint vertexArray; GLsizei elementCount; // initialize object names to zero (OpenGL reserved value) MyGeometry() : vertexBuffer(0), colourBuffer(0), vertexArray(0), elementCount(0) {} }; // create buffers and fill with geometry data, returning true if successful bool InitializeGeometry(MyGeometry *geometry) { // three vertex positions and assocated colours of a triangle const GLfloat vertices[][2] = { { -0.6, -0.4 }, { 0.6, -0.4 }, { 0.0, 0.6 } }; const GLfloat colours[][3] = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } }; geometry->elementCount = 3; // these vertex attribute indices correspond to those specified for the // input variables in the vertex shader const GLuint VERTEX_INDEX = 0; const GLuint COLOUR_INDEX = 1; // create an array buffer object for storing our vertices glGenBuffers(1, &geometry->vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // create another one for storing our colours glGenBuffers(1, &geometry->colourBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(colours), colours, GL_STATIC_DRAW); // create a vertex array object encapsulating all our vertex attributes glGenVertexArrays(1, &geometry->vertexArray); glBindVertexArray(geometry->vertexArray); // associate the position array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glVertexAttribPointer(VERTEX_INDEX, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(VERTEX_INDEX); // assocaite the colour array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glVertexAttribPointer(COLOUR_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(COLOUR_INDEX); // unbind our buffers, resetting to default state glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate geometry-related objects void DestroyGeometry(MyGeometry *geometry) { // unbind and destroy our vertex array object and associated buffers glBindVertexArray(0); glDeleteVertexArrays(1, &geometry->vertexArray); glDeleteBuffers(1, &geometry->vertexBuffer); glDeleteBuffers(1, &geometry->colourBuffer); } // -------------------------------------------------------------------------- // Rendering function that draws our scene to the frame buffer void RenderScene(MyGeometry *geometry, MyShader *shader) { // clear screen to a dark grey colour glClearColor(0.2, 0.2, 0.2, 1.0); glClear(GL_COLOR_BUFFER_BIT); // bind our shader program and the vertex array object containing our // scene geometry, then tell OpenGL to draw our geometry glUseProgram(shader->program); glBindVertexArray(geometry->vertexArray); glDrawArrays(GL_TRIANGLES, 0, geometry->elementCount); // reset state to default (no shader or geometry bound) glBindVertexArray(0); glUseProgram(0); // check for an report any OpenGL errors CheckGLErrors(); } // -------------------------------------------------------------------------- // GLFW callback functions // reports GLFW errors void ErrorCallback(int error, const char* description) { cout << "GLFW ERROR " << error << ":" << endl; cout << description << endl; } // handles keyboard input events void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch(key) { case GLFW_KEY_F1: break; case GLFW_KEY_F2: break; case GLFW_KEY_F3: break; case GLFW_KEY_1: break; case GLFW_KEY_2: break; case GLFW_KEY_3: break; case GLFW_KEY_4: break; case GLFW_KEY_5: break; case GLFW_KEY_6: break; case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GL_TRUE); break; } } } // ========================================================================== // PROGRAM ENTRY POINT int main(int argc, char *argv[]) { // initialize the GLFW windowing system if (!glfwInit()) { cout << "ERROR: GLFW failed to initilize, TERMINATING" << endl; return -1; } glfwSetErrorCallback(ErrorCallback); // attempt to create a window with an OpenGL 4.1 core profile context GLFWwindow *window = 0; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(512, 512, "CPSC 453 OpenGL Boilerplate", 0, 0); if (!window) { cout << "Program failed to create GLFW window, TERMINATING" << endl; glfwTerminate(); return -1; } // set keyboard callback function and make our context current (active) glfwSetKeyCallback(window, KeyCallback); glfwMakeContextCurrent(window); // query and print out information about our OpenGL environment QueryGLVersion(); // call function to load and compile shader programs MyShader shader; if (!InitializeShaders(&shader)) { cout << "Program could not initialize shaders, TERMINATING" << endl; return -1; } // call function to create and fill buffers with geometry data MyGeometry geometry; if (!InitializeGeometry(&geometry)) cout << "Program failed to intialize geometry!" << endl; // run an event-triggered main loop while (!glfwWindowShouldClose(window)) { // call function to draw our scene RenderScene(&geometry, &shader); // scene is rendered to the back buffer, so swap to front for display glfwSwapBuffers(window); // sleep until next event before drawing again glfwWaitEvents(); } // clean up allocated resources before exit DestroyGeometry(&geometry); DestroyShaders(&shader); glfwDestroyWindow(window); glfwTerminate(); cout << "Goodbye!" << endl; return 0; } // ========================================================================== // SUPPORT FUNCTION DEFINITIONS // -------------------------------------------------------------------------- // OpenGL utility functions void QueryGLVersion() { // query opengl version and renderer information string version = reinterpret_cast<const char *>(glGetString(GL_VERSION)); string glslver = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); string renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)); cout << "OpenGL [ " << version << " ] " << "with GLSL [ " << glslver << " ] " << "on renderer [ " << renderer << " ]" << endl; } bool CheckGLErrors() { bool error = false; for (GLenum flag = glGetError(); flag != GL_NO_ERROR; flag = glGetError()) { cout << "OpenGL ERROR: "; switch (flag) { case GL_INVALID_ENUM: cout << "GL_INVALID_ENUM" << endl; break; case GL_INVALID_VALUE: cout << "GL_INVALID_VALUE" << endl; break; case GL_INVALID_OPERATION: cout << "GL_INVALID_OPERATION" << endl; break; case GL_INVALID_FRAMEBUFFER_OPERATION: cout << "GL_INVALID_FRAMEBUFFER_OPERATION" << endl; break; case GL_OUT_OF_MEMORY: cout << "GL_OUT_OF_MEMORY" << endl; break; default: cout << "[unknown error code]" << endl; } error = true; } return error; } // -------------------------------------------------------------------------- // OpenGL shader support functions // reads a text file with the given name into a string string LoadSource(const string &filename) { string source; ifstream input(filename.c_str()); if (input) { copy(istreambuf_iterator<char>(input), istreambuf_iterator<char>(), back_inserter(source)); input.close(); } else { cout << "ERROR: Could not load shader source from file " << filename << endl; } return source; } // creates and returns a shader object compiled from the given source GLuint CompileShader(GLenum shaderType, const string &source) { // allocate shader object name GLuint shaderObject = glCreateShader(shaderType); // try compiling the source as a shader of the given type const GLchar *source_ptr = source.c_str(); glShaderSource(shaderObject, 1, &source_ptr, 0); glCompileShader(shaderObject); // retrieve compile status GLint status; glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetShaderiv(shaderObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetShaderInfoLog(shaderObject, info.length(), &length, &info[0]); cout << "ERROR compiling shader:" << endl << endl; cout << source << endl; cout << info << endl; } return shaderObject; } // creates and returns a program object linked from vertex and fragment shaders GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader) { // allocate program object name GLuint programObject = glCreateProgram(); // attach provided shader objects to this program if (vertexShader) glAttachShader(programObject, vertexShader); if (fragmentShader) glAttachShader(programObject, fragmentShader); // try linking the program with given attachments glLinkProgram(programObject); // retrieve link status GLint status; glGetProgramiv(programObject, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetProgramInfoLog(programObject, info.length(), &length, &info[0]); cout << "ERROR linking shader program:" << endl; cout << info << endl; } return programObject; } // ========================================================================== <commit_msg>Modified to draw solid red square<commit_after>// ========================================================================== // Line And Polygon Geometry // // Adapted from Sonny Chan's CPSC453 OpenGL Core Profile Boilerplate // http://pages.cpsc.ucalgary.ca/~sonny.chan/cpsc453/resources/handouts/CPSC453-BoilerplateCode.zip // // Author: Matthew Sembinelli, University of Calgary // Date: January 17, 2015 // ========================================================================== #include <iostream> #include <fstream> #include <algorithm> // specify that we want the OpenGL core profile before including GLFW headers #define GLFW_INCLUDE_GLCOREARB #define GL_GLEXT_PROTOTYPES #include <GLFW/glfw3.h> using namespace std; // -------------------------------------------------------------------------- // OpenGL utility and support function prototypes void QueryGLVersion(); bool CheckGLErrors(); string LoadSource(const string &filename); GLuint CompileShader(GLenum shaderType, const string &source); GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader); // -------------------------------------------------------------------------- // Functions to set up OpenGL shader programs for rendering struct MyShader { // OpenGL names for vertex and fragment shaders, shader program GLuint vertex; GLuint fragment; GLuint program; // initialize shader and program names to zero (OpenGL reserved value) MyShader() : vertex(0), fragment(0), program(0) {} }; // load, compile, and link shaders, returning true if successful bool InitializeShaders(MyShader *shader) { // load shader source from files string vertexSource = LoadSource("vertex.glsl"); string fragmentSource = LoadSource("fragment.glsl"); if (vertexSource.empty() || fragmentSource.empty()) return false; // compile shader source into shader objects shader->vertex = CompileShader(GL_VERTEX_SHADER, vertexSource); shader->fragment = CompileShader(GL_FRAGMENT_SHADER, fragmentSource); // link shader program shader->program = LinkProgram(shader->vertex, shader->fragment); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate shader-related objects void DestroyShaders(MyShader *shader) { // unbind any shader programs and destroy shader objects glUseProgram(0); glDeleteProgram(shader->program); glDeleteShader(shader->vertex); glDeleteShader(shader->fragment); } // -------------------------------------------------------------------------- // Functions to set up OpenGL buffers for storing geometry data struct MyGeometry { // OpenGL names for array buffer objects, vertex array object GLuint vertexBuffer; GLuint colourBuffer; GLuint vertexArray; GLsizei elementCount; // initialize object names to zero (OpenGL reserved value) MyGeometry() : vertexBuffer(0), colourBuffer(0), vertexArray(0), elementCount(0) {} }; // create buffers and fill with geometry data, returning true if successful bool InitializeGeometry(MyGeometry *geometry) { //Draw square consisting of two triangles const GLfloat vertices[][2] = { { -0.5, 0.5 }, { -0.5, -0.5 }, { 0.5, 0.5 }, { 0.5, -0.5 }, { -0.5, -0.5 }, { 0.5, 0.5 } }; const GLfloat colours[][3] = { { 1.0, 0.0, 0.0 }, { 1.0, 0.0, 0.0 }, { 1.0, 0.0, 0.0 }, { 1.0, 0.0, 0.0 }, { 1.0, 0.0, 0.0 }, { 1.0, 0.0, 0.0 } }; geometry->elementCount = 6; // these vertex attribute indices correspond to those specified for the // input variables in the vertex shader const GLuint VERTEX_INDEX = 0; const GLuint COLOUR_INDEX = 1; // create an array buffer object for storing our vertices glGenBuffers(1, &geometry->vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // create another one for storing our colours glGenBuffers(1, &geometry->colourBuffer); glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(colours), colours, GL_STATIC_DRAW); // create a vertex array object encapsulating all our vertex attributes glGenVertexArrays(1, &geometry->vertexArray); glBindVertexArray(geometry->vertexArray); // associate the position array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->vertexBuffer); glVertexAttribPointer(VERTEX_INDEX, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(VERTEX_INDEX); // assocaite the colour array with the vertex array object glBindBuffer(GL_ARRAY_BUFFER, geometry->colourBuffer); glVertexAttribPointer(COLOUR_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(COLOUR_INDEX); // unbind our buffers, resetting to default state glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // check for OpenGL errors and return false if error occurred return !CheckGLErrors(); } // deallocate geometry-related objects void DestroyGeometry(MyGeometry *geometry) { // unbind and destroy our vertex array object and associated buffers glBindVertexArray(0); glDeleteVertexArrays(1, &geometry->vertexArray); glDeleteBuffers(1, &geometry->vertexBuffer); glDeleteBuffers(1, &geometry->colourBuffer); } // -------------------------------------------------------------------------- // Rendering function that draws our scene to the frame buffer void RenderScene(MyGeometry *geometry, MyShader *shader) { // clear screen to a dark grey colour glClearColor(0.2, 0.2, 0.2, 1.0); glClear(GL_COLOR_BUFFER_BIT); // bind our shader program and the vertex array object containing our // scene geometry, then tell OpenGL to draw our geometry glUseProgram(shader->program); glBindVertexArray(geometry->vertexArray); glDrawArrays(GL_TRIANGLES, 0, geometry->elementCount); // reset state to default (no shader or geometry bound) glBindVertexArray(0); glUseProgram(0); // check for an report any OpenGL errors CheckGLErrors(); } // -------------------------------------------------------------------------- // GLFW callback functions // reports GLFW errors void ErrorCallback(int error, const char* description) { cout << "GLFW ERROR " << error << ":" << endl; cout << description << endl; } // handles keyboard input events void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (action == GLFW_PRESS) { switch(key) { case GLFW_KEY_F1: break; case GLFW_KEY_F2: break; case GLFW_KEY_F3: break; case GLFW_KEY_1: break; case GLFW_KEY_2: break; case GLFW_KEY_3: break; case GLFW_KEY_4: break; case GLFW_KEY_5: break; case GLFW_KEY_6: break; case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GL_TRUE); break; } } } // ========================================================================== // PROGRAM ENTRY POINT int main(int argc, char *argv[]) { // initialize the GLFW windowing system if (!glfwInit()) { cout << "ERROR: GLFW failed to initilize, TERMINATING" << endl; return -1; } glfwSetErrorCallback(ErrorCallback); // attempt to create a window with an OpenGL 4.1 core profile context GLFWwindow *window = 0; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); window = glfwCreateWindow(512, 512, "CPSC 453 Assignment 1 - Line And Polygon Geometry", 0, 0); if (!window) { cout << "Program failed to create GLFW window, TERMINATING" << endl; glfwTerminate(); return -1; } // set keyboard callback function and make our context current (active) glfwSetKeyCallback(window, KeyCallback); glfwMakeContextCurrent(window); // query and print out information about our OpenGL environment QueryGLVersion(); // call function to load and compile shader programs MyShader shader; if (!InitializeShaders(&shader)) { cout << "Program could not initialize shaders, TERMINATING" << endl; return -1; } // call function to create and fill buffers with geometry data MyGeometry geometry; if (!InitializeGeometry(&geometry)) cout << "Program failed to intialize geometry!" << endl; // run an event-triggered main loop while (!glfwWindowShouldClose(window)) { // call function to draw our scene RenderScene(&geometry, &shader); // scene is rendered to the back buffer, so swap to front for display glfwSwapBuffers(window); // sleep until next event before drawing again glfwWaitEvents(); } // clean up allocated resources before exit DestroyGeometry(&geometry); DestroyShaders(&shader); glfwDestroyWindow(window); glfwTerminate(); cout << "Goodbye!" << endl; return 0; } // ========================================================================== // SUPPORT FUNCTION DEFINITIONS // -------------------------------------------------------------------------- // OpenGL utility functions void QueryGLVersion() { // query opengl version and renderer information string version = reinterpret_cast<const char *>(glGetString(GL_VERSION)); string glslver = reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); string renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER)); cout << "OpenGL [ " << version << " ] " << "with GLSL [ " << glslver << " ] " << "on renderer [ " << renderer << " ]" << endl; } bool CheckGLErrors() { bool error = false; for (GLenum flag = glGetError(); flag != GL_NO_ERROR; flag = glGetError()) { cout << "OpenGL ERROR: "; switch (flag) { case GL_INVALID_ENUM: cout << "GL_INVALID_ENUM" << endl; break; case GL_INVALID_VALUE: cout << "GL_INVALID_VALUE" << endl; break; case GL_INVALID_OPERATION: cout << "GL_INVALID_OPERATION" << endl; break; case GL_INVALID_FRAMEBUFFER_OPERATION: cout << "GL_INVALID_FRAMEBUFFER_OPERATION" << endl; break; case GL_OUT_OF_MEMORY: cout << "GL_OUT_OF_MEMORY" << endl; break; default: cout << "[unknown error code]" << endl; } error = true; } return error; } // -------------------------------------------------------------------------- // OpenGL shader support functions // reads a text file with the given name into a string string LoadSource(const string &filename) { string source; ifstream input(filename.c_str()); if (input) { copy(istreambuf_iterator<char>(input), istreambuf_iterator<char>(), back_inserter(source)); input.close(); } else { cout << "ERROR: Could not load shader source from file " << filename << endl; } return source; } // creates and returns a shader object compiled from the given source GLuint CompileShader(GLenum shaderType, const string &source) { // allocate shader object name GLuint shaderObject = glCreateShader(shaderType); // try compiling the source as a shader of the given type const GLchar *source_ptr = source.c_str(); glShaderSource(shaderObject, 1, &source_ptr, 0); glCompileShader(shaderObject); // retrieve compile status GLint status; glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetShaderiv(shaderObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetShaderInfoLog(shaderObject, info.length(), &length, &info[0]); cout << "ERROR compiling shader:" << endl << endl; cout << source << endl; cout << info << endl; } return shaderObject; } // creates and returns a program object linked from vertex and fragment shaders GLuint LinkProgram(GLuint vertexShader, GLuint fragmentShader) { // allocate program object name GLuint programObject = glCreateProgram(); // attach provided shader objects to this program if (vertexShader) glAttachShader(programObject, vertexShader); if (fragmentShader) glAttachShader(programObject, fragmentShader); // try linking the program with given attachments glLinkProgram(programObject); // retrieve link status GLint status; glGetProgramiv(programObject, GL_LINK_STATUS, &status); if (status == GL_FALSE) { GLint length; glGetProgramiv(programObject, GL_INFO_LOG_LENGTH, &length); string info(length, ' '); glGetProgramInfoLog(programObject, info.length(), &length, &info[0]); cout << "ERROR linking shader program:" << endl; cout << info << endl; } return programObject; } // ========================================================================== <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDelimitedTextReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkDelimitedTextReader.h" #include "vtkCommand.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkInformation.h" #include "vtkStringArray.h" #include "vtkStdString.h" #include <vtkstd/algorithm> #include <vtkstd/vector> #include <vtkstd/string> vtkCxxRevisionMacro(vtkDelimitedTextReader, "1.7"); vtkStandardNewMacro(vtkDelimitedTextReader); struct vtkDelimitedTextReaderInternals { ifstream *File; }; // Forward function reference (definition at bottom :) static int splitString(const vtkStdString& input, char fieldDelimiter, char stringDelimiter, bool useStringDelimiter, vtkstd::vector<vtkStdString>& results, bool includeEmpties=true); // I need a safe way to read a line of arbitrary length. It exists on // some platforms but not others so I'm afraid I have to write it // myself. static int my_getline(istream& stream, vtkStdString &output, char delim='\n'); // ---------------------------------------------------------------------- vtkDelimitedTextReader::vtkDelimitedTextReader() { this->Internals = new vtkDelimitedTextReaderInternals(); this->Internals->File = 0; this->FileName = 0; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->ReadBuffer = new char[2048]; this->FieldDelimiter = ','; this->StringDelimiter = '"'; this->UseStringDelimiter = true; } // ---------------------------------------------------------------------- vtkDelimitedTextReader::~vtkDelimitedTextReader() { this->SetFileName(0); delete this->ReadBuffer; delete this->Internals; } // ---------------------------------------------------------------------- void vtkDelimitedTextReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << endl; os << indent << "Field delimiter: '" << this->FieldDelimiter << "'" << endl; os << indent << "String delimiter: '" << this->StringDelimiter << "'" << endl; os << indent << "UseStringDelimiter: " << (this->UseStringDelimiter ? "true" : "false") << endl; os << indent << "HaveHeaders: " << (this->HaveHeaders ? "true" : "false") << endl; } // ---------------------------------------------------------------------- void vtkDelimitedTextReader::OpenFile() { // If the file was open close it. if (this->Internals->File) { this->Internals->File->close(); delete this->Internals->File; this->Internals->File = NULL; } // Open the new file. vtkDebugMacro(<< "vtkDelimitedTextReader is opening file: " << this->FileName); this->Internals->File = new ifstream(this->FileName, ios::in); // Check to see if open was successful if (! this->Internals->File || this->Internals->File->fail()) { vtkErrorMacro(<< "vtkDelimitedTextReader could not open file " << this->FileName); return; } } // ---------------------------------------------------------------------- int vtkDelimitedTextReader::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { int numLines = 0; // Check that the filename has been specified if (!this->FileName) { vtkErrorMacro("vtkDelimitedTextReader: You must specify a filename!"); return 0; } // Open the file this->OpenFile(); // Go to the top of the file this->Internals->File->seekg(0,ios::beg); // Store the text data into a vtkTable vtkTable* table = vtkTable::GetData(outputVector); // The first line of the file might contain the headers, so we want // to be a little bit careful about it. If we don't have headers // we'll have to make something up. vtkstd::vector<vtkStdString> headers; // Not all platforms support vtkstd::getline(istream&, vtkstd::string) so // I have to do this the clunky way. vtkstd::vector<vtkStdString> firstLineFields; vtkStdString firstLine; my_getline(*(this->Internals->File), firstLine); vtkDebugMacro(<<"First line of file: " << firstLine.c_str()); if (this->HaveHeaders) { splitString(firstLine, this->FieldDelimiter, this->StringDelimiter, this->UseStringDelimiter, headers); } else { splitString(firstLine, this->FieldDelimiter, this->StringDelimiter, this->UseStringDelimiter, firstLineFields); for (unsigned int i = 0; i < firstLineFields.size(); ++i) { // I know it's not a great idea to use sprintf. It's safe right // here because an unsigned int will never take up enough // characters to fill up this buffer. char fieldName[64]; sprintf(fieldName, "Field %d", i); headers.push_back(fieldName); } } // Now we can create the arrays that will hold the data for each // field. vtkstd::vector<vtkStdString>::const_iterator fieldIter; for(fieldIter = headers.begin(); fieldIter != headers.end(); ++fieldIter) { vtkStringArray* array = vtkStringArray::New(); array->SetName((*fieldIter).c_str()); table->AddColumn(array); array->Delete(); } // If the first line did not contain headers then we need to add it // to the table. if (!this->HaveHeaders) { vtkVariantArray* dataArray = vtkVariantArray::New(); vtkstd::vector<vtkStdString>::const_iterator I; for(I = firstLineFields.begin(); I != firstLineFields.end(); ++I) { dataArray->InsertNextValue(vtkVariant(*I)); } // Insert the data into the table table->InsertNextRow(dataArray); dataArray->Delete(); } // Okay read the file and add the data to the table vtkStdString nextLine; while (my_getline(*(this->Internals->File), nextLine)) { ++numLines; if (numLines > 0 && numLines % 100 == 0) { float numLinesRead = numLines; this->InvokeEvent(vtkCommand::ProgressEvent, &numLinesRead); } vtkDebugMacro(<<"Next line: " << nextLine.c_str()); vtkstd::vector<vtkStdString> dataVector; // Split string on the delimiters splitString(nextLine, this->FieldDelimiter, this->StringDelimiter, this->UseStringDelimiter, dataVector); vtkDebugMacro(<<"Split into " << dataVector.size() << " fields"); // Add data to the output arrays // Convert from vector to variant array vtkVariantArray* dataArray = vtkVariantArray::New(); vtkstd::vector<vtkStdString>::const_iterator I; for(I = dataVector.begin(); I != dataVector.end(); ++I) { dataArray->InsertNextValue(vtkVariant(*I)); } // Pad out any missing columns while (dataArray->GetNumberOfTuples() < table->GetNumberOfColumns()) { dataArray->InsertNextValue(vtkVariant()); } // Insert the data into the table table->InsertNextRow(dataArray); dataArray->Delete(); } return 1; } // ---------------------------------------------------------------------- static int splitString(const vtkStdString& input, char fieldDelimiter, char stringDelimiter, bool useStringDelimiter, vtkstd::vector<vtkStdString>& results, bool includeEmpties) { if (input.size() == 0) { return 0; } bool inString = false; char thisCharacter = 0; char lastCharacter = 0; vtkstd::string currentField; for (unsigned int i = 0; i < input.size(); ++i) { thisCharacter = input[i]; // Zeroth: are we in an escape sequence? If so, interpret this // character accordingly. if (lastCharacter == '\\') { char characterToAppend; switch (thisCharacter) { case '0': characterToAppend = '\0'; break; case 'a': characterToAppend = '\a'; break; case 'b': characterToAppend = '\b'; break; case 't': characterToAppend = '\t'; break; case 'n': characterToAppend = '\n'; break; case 'v': characterToAppend = '\v'; break; case 'f': characterToAppend = '\f'; break; case 'r': characterToAppend = '\r'; break; case '\\': characterToAppend = '\\'; break; default: characterToAppend = thisCharacter; break; } currentField += characterToAppend; lastCharacter = thisCharacter; if (lastCharacter == '\\') lastCharacter = 0; } else { // We're not in an escape sequence. // First, are we /starting/ an escape sequence? if (thisCharacter == '\\') { lastCharacter = thisCharacter; continue; } else if (useStringDelimiter && thisCharacter == stringDelimiter) { // this should just toggle inString inString = (inString == false); } else if (thisCharacter == fieldDelimiter && !inString) { // A delimiter starts a new field unless we're in a string, in // which case it's normal text and we won't even get here. if (includeEmpties || currentField.size() > 0) { results.push_back(currentField); } currentField = vtkStdString(); } else { // The character is just plain text. Accumulate it and move on. currentField += thisCharacter; } lastCharacter = thisCharacter; } } results.push_back(currentField); return results.size(); } // ---------------------------------------------------------------------- static int my_getline(istream& in, vtkStdString &out, char delimiter) { out = vtkStdString(); unsigned int numCharactersRead = 0; int nextValue = 0; while ((nextValue = in.get()) != EOF && numCharactersRead < out.max_size()) { ++numCharactersRead; char downcast = static_cast<char>(nextValue); if (downcast != delimiter) { out += downcast; } else { return numCharactersRead; } } return numCharactersRead; } <commit_msg>BUG: Fix an uninitialized-variable error<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDelimitedTextReader.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkDelimitedTextReader.h" #include "vtkCommand.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkInformation.h" #include "vtkStringArray.h" #include "vtkStdString.h" #include <vtkstd/algorithm> #include <vtkstd/vector> #include <vtkstd/string> vtkCxxRevisionMacro(vtkDelimitedTextReader, "1.8"); vtkStandardNewMacro(vtkDelimitedTextReader); struct vtkDelimitedTextReaderInternals { ifstream *File; }; // Forward function reference (definition at bottom :) static int splitString(const vtkStdString& input, char fieldDelimiter, char stringDelimiter, bool useStringDelimiter, vtkstd::vector<vtkStdString>& results, bool includeEmpties=true); // I need a safe way to read a line of arbitrary length. It exists on // some platforms but not others so I'm afraid I have to write it // myself. static int my_getline(istream& stream, vtkStdString &output, char delim='\n'); // ---------------------------------------------------------------------- vtkDelimitedTextReader::vtkDelimitedTextReader() { this->Internals = new vtkDelimitedTextReaderInternals(); this->Internals->File = 0; this->FileName = 0; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->ReadBuffer = new char[2048]; this->HaveHeaders = false; this->FieldDelimiter = ','; this->StringDelimiter = '"'; this->UseStringDelimiter = true; } // ---------------------------------------------------------------------- vtkDelimitedTextReader::~vtkDelimitedTextReader() { this->SetFileName(0); delete this->ReadBuffer; delete this->Internals; } // ---------------------------------------------------------------------- void vtkDelimitedTextReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "(none)") << endl; os << indent << "Field delimiter: '" << this->FieldDelimiter << "'" << endl; os << indent << "String delimiter: '" << this->StringDelimiter << "'" << endl; os << indent << "UseStringDelimiter: " << (this->UseStringDelimiter ? "true" : "false") << endl; os << indent << "HaveHeaders: " << (this->HaveHeaders ? "true" : "false") << endl; } // ---------------------------------------------------------------------- void vtkDelimitedTextReader::OpenFile() { // If the file was open close it. if (this->Internals->File) { this->Internals->File->close(); delete this->Internals->File; this->Internals->File = NULL; } // Open the new file. vtkDebugMacro(<< "vtkDelimitedTextReader is opening file: " << this->FileName); this->Internals->File = new ifstream(this->FileName, ios::in); // Check to see if open was successful if (! this->Internals->File || this->Internals->File->fail()) { vtkErrorMacro(<< "vtkDelimitedTextReader could not open file " << this->FileName); return; } } // ---------------------------------------------------------------------- int vtkDelimitedTextReader::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { int numLines = 0; // Check that the filename has been specified if (!this->FileName) { vtkErrorMacro("vtkDelimitedTextReader: You must specify a filename!"); return 0; } // Open the file this->OpenFile(); // Go to the top of the file this->Internals->File->seekg(0,ios::beg); // Store the text data into a vtkTable vtkTable* table = vtkTable::GetData(outputVector); // The first line of the file might contain the headers, so we want // to be a little bit careful about it. If we don't have headers // we'll have to make something up. vtkstd::vector<vtkStdString> headers; // Not all platforms support vtkstd::getline(istream&, vtkstd::string) so // I have to do this the clunky way. vtkstd::vector<vtkStdString> firstLineFields; vtkStdString firstLine; my_getline(*(this->Internals->File), firstLine); vtkDebugMacro(<<"First line of file: " << firstLine.c_str()); if (this->HaveHeaders) { splitString(firstLine, this->FieldDelimiter, this->StringDelimiter, this->UseStringDelimiter, headers); } else { splitString(firstLine, this->FieldDelimiter, this->StringDelimiter, this->UseStringDelimiter, firstLineFields); for (unsigned int i = 0; i < firstLineFields.size(); ++i) { // I know it's not a great idea to use sprintf. It's safe right // here because an unsigned int will never take up enough // characters to fill up this buffer. char fieldName[64]; sprintf(fieldName, "Field %d", i); headers.push_back(fieldName); } } // Now we can create the arrays that will hold the data for each // field. vtkstd::vector<vtkStdString>::const_iterator fieldIter; for(fieldIter = headers.begin(); fieldIter != headers.end(); ++fieldIter) { vtkStringArray* array = vtkStringArray::New(); array->SetName((*fieldIter).c_str()); table->AddColumn(array); array->Delete(); } // If the first line did not contain headers then we need to add it // to the table. if (!this->HaveHeaders) { vtkVariantArray* dataArray = vtkVariantArray::New(); vtkstd::vector<vtkStdString>::const_iterator I; for(I = firstLineFields.begin(); I != firstLineFields.end(); ++I) { dataArray->InsertNextValue(vtkVariant(*I)); } // Insert the data into the table table->InsertNextRow(dataArray); dataArray->Delete(); } // Okay read the file and add the data to the table vtkStdString nextLine; while (my_getline(*(this->Internals->File), nextLine)) { ++numLines; if (numLines > 0 && numLines % 100 == 0) { float numLinesRead = numLines; this->InvokeEvent(vtkCommand::ProgressEvent, &numLinesRead); } vtkDebugMacro(<<"Next line: " << nextLine.c_str()); vtkstd::vector<vtkStdString> dataVector; // Split string on the delimiters splitString(nextLine, this->FieldDelimiter, this->StringDelimiter, this->UseStringDelimiter, dataVector); vtkDebugMacro(<<"Split into " << dataVector.size() << " fields"); // Add data to the output arrays // Convert from vector to variant array vtkVariantArray* dataArray = vtkVariantArray::New(); vtkstd::vector<vtkStdString>::const_iterator I; for(I = dataVector.begin(); I != dataVector.end(); ++I) { dataArray->InsertNextValue(vtkVariant(*I)); } // Pad out any missing columns while (dataArray->GetNumberOfTuples() < table->GetNumberOfColumns()) { dataArray->InsertNextValue(vtkVariant()); } // Insert the data into the table table->InsertNextRow(dataArray); dataArray->Delete(); } return 1; } // ---------------------------------------------------------------------- static int splitString(const vtkStdString& input, char fieldDelimiter, char stringDelimiter, bool useStringDelimiter, vtkstd::vector<vtkStdString>& results, bool includeEmpties) { if (input.size() == 0) { return 0; } bool inString = false; char thisCharacter = 0; char lastCharacter = 0; vtkstd::string currentField; for (unsigned int i = 0; i < input.size(); ++i) { thisCharacter = input[i]; // Zeroth: are we in an escape sequence? If so, interpret this // character accordingly. if (lastCharacter == '\\') { char characterToAppend; switch (thisCharacter) { case '0': characterToAppend = '\0'; break; case 'a': characterToAppend = '\a'; break; case 'b': characterToAppend = '\b'; break; case 't': characterToAppend = '\t'; break; case 'n': characterToAppend = '\n'; break; case 'v': characterToAppend = '\v'; break; case 'f': characterToAppend = '\f'; break; case 'r': characterToAppend = '\r'; break; case '\\': characterToAppend = '\\'; break; default: characterToAppend = thisCharacter; break; } currentField += characterToAppend; lastCharacter = thisCharacter; if (lastCharacter == '\\') lastCharacter = 0; } else { // We're not in an escape sequence. // First, are we /starting/ an escape sequence? if (thisCharacter == '\\') { lastCharacter = thisCharacter; continue; } else if (useStringDelimiter && thisCharacter == stringDelimiter) { // this should just toggle inString inString = (inString == false); } else if (thisCharacter == fieldDelimiter && !inString) { // A delimiter starts a new field unless we're in a string, in // which case it's normal text and we won't even get here. if (includeEmpties || currentField.size() > 0) { results.push_back(currentField); } currentField = vtkStdString(); } else { // The character is just plain text. Accumulate it and move on. currentField += thisCharacter; } lastCharacter = thisCharacter; } } results.push_back(currentField); return results.size(); } // ---------------------------------------------------------------------- static int my_getline(istream& in, vtkStdString &out, char delimiter) { out = vtkStdString(); unsigned int numCharactersRead = 0; int nextValue = 0; while ((nextValue = in.get()) != EOF && numCharactersRead < out.max_size()) { ++numCharactersRead; char downcast = static_cast<char>(nextValue); if (downcast != delimiter) { out += downcast; } else { return numCharactersRead; } } return numCharactersRead; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDebugLeaks.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDebugLeaks.h" #include "vtkObjectFactory.h" #include "vtkCriticalSection.h" static const char *vtkDebugLeaksIgnoreClasses[] = { 0 }; // return 1 if the class should be ignored int vtkDebugLeaksIgnoreClassesCheck(const char* s) { int i =0; while(vtkDebugLeaksIgnoreClasses[i]) { if(strcmp(s, vtkDebugLeaksIgnoreClasses[i]) == 0) { return 1; } i++; } return 0; } vtkCxxRevisionMacro(vtkDebugLeaks, "1.23"); vtkStandardNewMacro(vtkDebugLeaks); // A hash function for converting a string to a long inline size_t vtkHashString(const char* s) { unsigned long h = 0; for ( ; *s; ++s) { h = 5*h + *s; } return size_t(h); } class vtkDebugLeaksHashNode { public: vtkDebugLeaksHashNode() { this->Count =1; // if it goes in, then there is one of them this->Key = 0; this->Next =0; } void Print(ostream& os) { if(this->Count) { os << "Class " << this->Key << " has " << this->Count << ((this->Count==1)? " instance" : " instances") << " still around.\n"; } } ~vtkDebugLeaksHashNode() { delete [] this->Key; if(this->Next) { delete this->Next; } } public: vtkDebugLeaksHashNode *Next; char *Key; int Count; }; class vtkDebugLeaksHashTable { public: vtkDebugLeaksHashTable(); vtkDebugLeaksHashNode* GetNode(const char* name); void IncrementCount(const char *name); unsigned int GetCount(const char *name); int DecrementCount(const char* name); void PrintTable(ostream& os); int IsEmpty(); ~vtkDebugLeaksHashTable() { for (int i = 0; i < 64; i++) { vtkDebugLeaksHashNode *pos = this->Nodes[i]; if(pos) { delete pos; } } } private: vtkDebugLeaksHashNode* Nodes[64]; }; vtkDebugLeaksHashTable::vtkDebugLeaksHashTable() { int i; for (i = 0; i < 64; i++) { this->Nodes[i] = NULL; } } void vtkDebugLeaksHashTable::IncrementCount(const char * name) { vtkDebugLeaksHashNode *pos; vtkDebugLeaksHashNode *newpos; int loc; pos = this->GetNode(name); if(pos) { pos->Count++; return; } newpos = new vtkDebugLeaksHashNode; newpos->Key = strcpy(new char[strlen(name)+1], name); loc = (((unsigned long)vtkHashString(name)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) { this->Nodes[loc] = newpos; return; } while (pos->Next) { pos = pos->Next; } pos->Next = newpos; } vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key) { vtkDebugLeaksHashNode *pos; int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) { return NULL; } while ((pos) && (strcmp(pos->Key, key) != 0) ) { pos = pos->Next; } return pos; } unsigned int vtkDebugLeaksHashTable::GetCount(const char* key) { vtkDebugLeaksHashNode *pos; int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) { return 0; } while ((pos)&&(pos->Key != key)) { pos = pos->Next; } if (pos) { return pos->Count; } return 0; } int vtkDebugLeaksHashTable::IsEmpty() { int count = 0; for(int i =0; i < 64; i++) { vtkDebugLeaksHashNode *pos = this->Nodes[i]; if(pos) { if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { count += pos->Count; } while(pos->Next) { pos = pos->Next; if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { count += pos->Count; } } } } return !count; } int vtkDebugLeaksHashTable::DecrementCount(const char *key) { vtkDebugLeaksHashNode *pos = this->GetNode(key); if(pos) { pos->Count--; return 1; } else { return 0; } } void vtkDebugLeaksHashTable::PrintTable(ostream& os) { for(int i =0; i < 64; i++) { vtkDebugLeaksHashNode *pos = this->Nodes[i]; if(pos) { if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { pos->Print(os); } while(pos->Next) { pos = pos->Next; if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { pos->Print(os); } } } } } #ifdef VTK_DEBUG_LEAKS void vtkDebugLeaks::ConstructClass(const char* name) { vtkDebugLeaks::CriticalSection->Lock(); vtkDebugLeaks::MemoryTable->IncrementCount(name); vtkDebugLeaks::CriticalSection->Unlock(); } #else void vtkDebugLeaks::ConstructClass(const char*) { } #endif #ifdef VTK_DEBUG_LEAKS void vtkDebugLeaks::DestructClass(const char* p) { vtkDebugLeaks::CriticalSection->Lock(); // Due to globals being deleted, this table may already have // been deleted. if(vtkDebugLeaks::MemoryTable && !vtkDebugLeaks::MemoryTable->DecrementCount(p)) { vtkDebugLeaks::CriticalSection->Unlock(); vtkGenericWarningMacro("Deleting unknown object: " << p); } else { vtkDebugLeaks::CriticalSection->Unlock(); } } #else void vtkDebugLeaks::DestructClass(const char*) { } #endif void vtkDebugLeaks::PrintCurrentLeaks() { #ifdef VTK_DEBUG_LEAKS if(vtkDebugLeaks::MemoryTable->IsEmpty()) { return; } // print the table strstream leaks; vtkDebugLeaks::MemoryTable->PrintTable(leaks); leaks << ends; #ifdef _WIN32 int cancel=0; while(!cancel && !!leaks) { char line[1000]; strstream msg; msg << "vtkDebugLeaks has detected LEAKS!\n"; int i=0; while((++i <= 10) && !!leaks.getline(line, 1000)) { msg << line << "\n"; } msg << ends; cancel = vtkDebugLeaks::DisplayMessageBox(msg.str()); msg.rdbuf()->freeze(0); } #else cout << "vtkDebugLeaks has detected LEAKS!\n"; cout << leaks.rdbuf() << "\n"; #endif #endif } #ifdef _WIN32 int vtkDebugLeaks::DisplayMessageBox(const char* msg) { #ifdef UNICODE wchar_t *wmsg = new wchar_t [mbstowcs(NULL, msg, 32000)]; mbstowcs(wmsg, msg, 32000); int result = (MessageBox(NULL, wmsg, L"Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL); delete [] wmsg; #else int result = (MessageBox(NULL, msg, "Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL); #endif return result; } #else int vtkDebugLeaks::DisplayMessageBox(const char*) { return 0; } #endif //---------------------------------------------------------------------------- void vtkDebugLeaks::ClassInitialize() { #ifdef VTK_DEBUG_LEAKS // Create the hash table. vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable; // Create the lock for the critical sections. vtkDebugLeaks::CriticalSection = new vtkSimpleCriticalSection; #else vtkDebugLeaks::MemoryTable = 0; vtkDebugLeaks::CriticalSection = 0; #endif } //---------------------------------------------------------------------------- void vtkDebugLeaks::ClassFinalize() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::PrintCurrentLeaks(); // Destroy the hash table. delete vtkDebugLeaks::MemoryTable; vtkDebugLeaks::MemoryTable = 0; // Destroy the lock for the critical sections. delete vtkDebugLeaks::CriticalSection; vtkDebugLeaks::CriticalSection = 0; #endif } //---------------------------------------------------------------------------- // Purposely not initialized. ClassInitialize will handle it. vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable; // Purposely not initialized. ClassInitialize will handle it. vtkSimpleCriticalSection* vtkDebugLeaks::CriticalSection; <commit_msg>BUG: Removed stray append of ends to string stream.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDebugLeaks.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDebugLeaks.h" #include "vtkObjectFactory.h" #include "vtkCriticalSection.h" static const char *vtkDebugLeaksIgnoreClasses[] = { 0 }; // return 1 if the class should be ignored int vtkDebugLeaksIgnoreClassesCheck(const char* s) { int i =0; while(vtkDebugLeaksIgnoreClasses[i]) { if(strcmp(s, vtkDebugLeaksIgnoreClasses[i]) == 0) { return 1; } i++; } return 0; } vtkCxxRevisionMacro(vtkDebugLeaks, "1.24"); vtkStandardNewMacro(vtkDebugLeaks); // A hash function for converting a string to a long inline size_t vtkHashString(const char* s) { unsigned long h = 0; for ( ; *s; ++s) { h = 5*h + *s; } return size_t(h); } class vtkDebugLeaksHashNode { public: vtkDebugLeaksHashNode() { this->Count =1; // if it goes in, then there is one of them this->Key = 0; this->Next =0; } void Print(ostream& os) { if(this->Count) { os << "Class " << this->Key << " has " << this->Count << ((this->Count==1)? " instance" : " instances") << " still around.\n"; } } ~vtkDebugLeaksHashNode() { delete [] this->Key; if(this->Next) { delete this->Next; } } public: vtkDebugLeaksHashNode *Next; char *Key; int Count; }; class vtkDebugLeaksHashTable { public: vtkDebugLeaksHashTable(); vtkDebugLeaksHashNode* GetNode(const char* name); void IncrementCount(const char *name); unsigned int GetCount(const char *name); int DecrementCount(const char* name); void PrintTable(ostream& os); int IsEmpty(); ~vtkDebugLeaksHashTable() { for (int i = 0; i < 64; i++) { vtkDebugLeaksHashNode *pos = this->Nodes[i]; if(pos) { delete pos; } } } private: vtkDebugLeaksHashNode* Nodes[64]; }; vtkDebugLeaksHashTable::vtkDebugLeaksHashTable() { int i; for (i = 0; i < 64; i++) { this->Nodes[i] = NULL; } } void vtkDebugLeaksHashTable::IncrementCount(const char * name) { vtkDebugLeaksHashNode *pos; vtkDebugLeaksHashNode *newpos; int loc; pos = this->GetNode(name); if(pos) { pos->Count++; return; } newpos = new vtkDebugLeaksHashNode; newpos->Key = strcpy(new char[strlen(name)+1], name); loc = (((unsigned long)vtkHashString(name)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) { this->Nodes[loc] = newpos; return; } while (pos->Next) { pos = pos->Next; } pos->Next = newpos; } vtkDebugLeaksHashNode* vtkDebugLeaksHashTable::GetNode(const char* key) { vtkDebugLeaksHashNode *pos; int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) { return NULL; } while ((pos) && (strcmp(pos->Key, key) != 0) ) { pos = pos->Next; } return pos; } unsigned int vtkDebugLeaksHashTable::GetCount(const char* key) { vtkDebugLeaksHashNode *pos; int loc = (((unsigned long)vtkHashString(key)) & 0x03f0) / 16; pos = this->Nodes[loc]; if (!pos) { return 0; } while ((pos)&&(pos->Key != key)) { pos = pos->Next; } if (pos) { return pos->Count; } return 0; } int vtkDebugLeaksHashTable::IsEmpty() { int count = 0; for(int i =0; i < 64; i++) { vtkDebugLeaksHashNode *pos = this->Nodes[i]; if(pos) { if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { count += pos->Count; } while(pos->Next) { pos = pos->Next; if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { count += pos->Count; } } } } return !count; } int vtkDebugLeaksHashTable::DecrementCount(const char *key) { vtkDebugLeaksHashNode *pos = this->GetNode(key); if(pos) { pos->Count--; return 1; } else { return 0; } } void vtkDebugLeaksHashTable::PrintTable(ostream& os) { for(int i =0; i < 64; i++) { vtkDebugLeaksHashNode *pos = this->Nodes[i]; if(pos) { if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { pos->Print(os); } while(pos->Next) { pos = pos->Next; if(!vtkDebugLeaksIgnoreClassesCheck(pos->Key)) { pos->Print(os); } } } } } #ifdef VTK_DEBUG_LEAKS void vtkDebugLeaks::ConstructClass(const char* name) { vtkDebugLeaks::CriticalSection->Lock(); vtkDebugLeaks::MemoryTable->IncrementCount(name); vtkDebugLeaks::CriticalSection->Unlock(); } #else void vtkDebugLeaks::ConstructClass(const char*) { } #endif #ifdef VTK_DEBUG_LEAKS void vtkDebugLeaks::DestructClass(const char* p) { vtkDebugLeaks::CriticalSection->Lock(); // Due to globals being deleted, this table may already have // been deleted. if(vtkDebugLeaks::MemoryTable && !vtkDebugLeaks::MemoryTable->DecrementCount(p)) { vtkDebugLeaks::CriticalSection->Unlock(); vtkGenericWarningMacro("Deleting unknown object: " << p); } else { vtkDebugLeaks::CriticalSection->Unlock(); } } #else void vtkDebugLeaks::DestructClass(const char*) { } #endif void vtkDebugLeaks::PrintCurrentLeaks() { #ifdef VTK_DEBUG_LEAKS if(vtkDebugLeaks::MemoryTable->IsEmpty()) { return; } // print the table strstream leaks; vtkDebugLeaks::MemoryTable->PrintTable(leaks); #ifdef _WIN32 int cancel=0; while(!cancel && !!leaks) { char line[1000]; strstream msg; msg << "vtkDebugLeaks has detected LEAKS!\n"; int i=0; while((++i <= 10) && !!leaks.getline(line, 1000)) { msg << line << "\n"; } msg << ends; cancel = vtkDebugLeaks::DisplayMessageBox(msg.str()); msg.rdbuf()->freeze(0); } #else cout << "vtkDebugLeaks has detected LEAKS!\n"; cout << leaks.rdbuf() << "\n"; #endif #endif } #ifdef _WIN32 int vtkDebugLeaks::DisplayMessageBox(const char* msg) { #ifdef UNICODE wchar_t *wmsg = new wchar_t [mbstowcs(NULL, msg, 32000)]; mbstowcs(wmsg, msg, 32000); int result = (MessageBox(NULL, wmsg, L"Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL); delete [] wmsg; #else int result = (MessageBox(NULL, msg, "Error", MB_ICONERROR | MB_OKCANCEL) == IDCANCEL); #endif return result; } #else int vtkDebugLeaks::DisplayMessageBox(const char*) { return 0; } #endif //---------------------------------------------------------------------------- void vtkDebugLeaks::ClassInitialize() { #ifdef VTK_DEBUG_LEAKS // Create the hash table. vtkDebugLeaks::MemoryTable = new vtkDebugLeaksHashTable; // Create the lock for the critical sections. vtkDebugLeaks::CriticalSection = new vtkSimpleCriticalSection; #else vtkDebugLeaks::MemoryTable = 0; vtkDebugLeaks::CriticalSection = 0; #endif } //---------------------------------------------------------------------------- void vtkDebugLeaks::ClassFinalize() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::PrintCurrentLeaks(); // Destroy the hash table. delete vtkDebugLeaks::MemoryTable; vtkDebugLeaks::MemoryTable = 0; // Destroy the lock for the critical sections. delete vtkDebugLeaks::CriticalSection; vtkDebugLeaks::CriticalSection = 0; #endif } //---------------------------------------------------------------------------- // Purposely not initialized. ClassInitialize will handle it. vtkDebugLeaksHashTable* vtkDebugLeaks::MemoryTable; // Purposely not initialized. ClassInitialize will handle it. vtkSimpleCriticalSection* vtkDebugLeaks::CriticalSection; <|endoftext|>
<commit_before>/* Copyright (C) 2011 Lasath Fernando <kde@lasath.org> Copyright (C) 2013 Lasath Fernando <davidedmundson@kde.org> 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 "messages-model.h" #include <KDebug> #include <KLocalizedString> #include <TelepathyQt/ReceivedMessage> #include <TelepathyQt/TextChannel> #include <TelepathyQt/Account> #include <KTp/message-processor.h> #include <KTp/message-context.h> #include <KTp/Logger/scrollback-manager.h> class MessagePrivate { public: MessagePrivate(const KTp::Message &message); KTp::Message message; MessagesModel::DeliveryStatus deliveryStatus; QDateTime deliveryReportReceiveTime; }; MessagePrivate::MessagePrivate(const KTp::Message &message) : message(message), deliveryStatus(MessagesModel::DeliveryStatusUnknown) { } class MessagesModel::MessagesModelPrivate { public: Tp::TextChannelPtr textChannel; Tp::AccountPtr account; ScrollbackManager *logManager; QList<MessagePrivate> messages; // For fast lookup of original messages upon receipt of a message delivery report. QHash<QString /*messageToken*/, QPersistentModelIndex> messagesByMessageToken; bool visible; }; MessagesModel::MessagesModel(const Tp::AccountPtr &account, QObject *parent) : QAbstractListModel(parent), d(new MessagesModelPrivate) { kDebug(); QHash<int, QByteArray> roles; roles[TextRole] = "text"; roles[TimeRole] = "time"; roles[TypeRole] = "type"; roles[SenderIdRole] = "senderId"; roles[SenderAliasRole] = "senderAlias"; roles[SenderAvatarRole] = "senderAvatar"; roles[DeliveryStatusRole] = "deliveryStatus"; roles[DeliveryReportReceiveTimeRole] = "deliveryReportReceiveTime"; setRoleNames(roles); d->account = account; d->visible = false; d->logManager = new ScrollbackManager(this); connect(d->logManager, SIGNAL(fetched(QList<KTp::Message>)), SLOT(onHistoryFetched(QList<KTp::Message>))); //Load configuration for number of message to show KConfig config(QLatin1String("ktelepathyrc")); KConfigGroup tabConfig = config.group("Behavior"); d->logManager->setScrollbackLength(tabConfig.readEntry<int>("scrollbackLength", 10)); } Tp::TextChannelPtr MessagesModel::textChannel() const { return d->textChannel; } bool MessagesModel::verifyPendingOperation(Tp::PendingOperation *op) { bool operationSucceeded = true; if (op->isError()) { kWarning() << op->errorName() << "+" << op->errorMessage(); operationSucceeded = false; } return operationSucceeded; } void MessagesModel::setupChannelSignals(const Tp::TextChannelPtr &channel) { connect(channel.data(), SIGNAL(messageReceived(Tp::ReceivedMessage)), SLOT(onMessageReceived(Tp::ReceivedMessage))); connect(channel.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)), SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString))); connect(channel.data(), SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage)), SLOT(onPendingMessageRemoved())); } void MessagesModel::setTextChannel(const Tp::TextChannelPtr &channel) { Q_ASSERT(channel != d->textChannel); kDebug(); setupChannelSignals(channel); if (d->textChannel) { removeChannelSignals(d->textChannel); } d->textChannel = channel; d->logManager->setTextChannel(d->account, d->textChannel); d->logManager->fetchScrollback(); QList<Tp::ReceivedMessage> messageQueue = channel->messageQueue(); Q_FOREACH(const Tp::ReceivedMessage &message, messageQueue) { bool messageAlreadyInModel = false; Q_FOREACH(const MessagePrivate &current, d->messages) { //FIXME: docs say messageToken can return an empty string. What to do if that happens? //Tp::Message has an == operator. maybe I can use that? if (current.message.token() == message.messageToken()) { messageAlreadyInModel = true; break; } } if (!messageAlreadyInModel) { onMessageReceived(message); } } } void MessagesModel::onHistoryFetched(const QList<KTp::Message> &messages) { kDebug() << "found" << messages.count() << "messages in history"; if (!messages.isEmpty()) { //Add all messages before the ones already present in the channel for(int i=messages.size()-1;i>=0;i--) { beginInsertRows(QModelIndex(), 0, 0); d->messages.prepend(messages[i]); endInsertRows(); } } } void MessagesModel::onMessageReceived(const Tp::ReceivedMessage &message) { int unreadCount = d->textChannel->messageQueue().size(); kDebug() << "unreadMessagesCount =" << unreadCount; kDebug() << "text =" << message.text(); kDebug() << "messageType = " << message.messageType(); kDebug() << "messageToken =" << message.messageToken(); if (message.isDeliveryReport()) { d->textChannel->acknowledge(QList<Tp::ReceivedMessage>() << message); Tp::ReceivedMessage::DeliveryDetails deliveryDetails = message.deliveryDetails(); if(!deliveryDetails.hasOriginalToken()) { kDebug() << "Delivery report without original message token received."; // Matching the delivery report to the original message is impossible without the token. return; } kDebug() << "originalMessageToken =" << deliveryDetails.originalToken(); QPersistentModelIndex originalMessageIndex = d->messagesByMessageToken.value( deliveryDetails.originalToken()); if (!originalMessageIndex.isValid() || originalMessageIndex.row() >= d->messages.count()) { // The original message for this delivery report was not found. return; } MessagePrivate &originalMessage = d->messages[originalMessageIndex.row()]; kDebug() << "Got delivery status" << deliveryDetails.status() << "for message with text" << originalMessage.message.mainMessagePart(); originalMessage.deliveryReportReceiveTime = message.received(); switch(deliveryDetails.status()) { case Tp::DeliveryStatusPermanentlyFailed: case Tp::DeliveryStatusTemporarilyFailed: originalMessage.deliveryStatus = DeliveryStatusFailed; if (deliveryDetails.hasDebugMessage()) { kDebug() << "Delivery failure debug message:" << deliveryDetails.debugMessage(); } break; case Tp::DeliveryStatusDelivered: originalMessage.deliveryStatus = DeliveryStatusDelivered; break; case Tp::DeliveryStatusRead: originalMessage.deliveryStatus = DeliveryStatusRead; break; default: originalMessage.deliveryStatus = DeliveryStatusUnknown; break; } Q_EMIT dataChanged(originalMessageIndex, originalMessageIndex); } else { int length = rowCount(); beginInsertRows(QModelIndex(), length, length); d->messages.append(KTp::MessageProcessor::instance()->processIncomingMessage( message, d->account, d->textChannel)); endInsertRows(); if (d->visible) { acknowledgeAllMessages(); } else { Q_EMIT unreadCountChanged(unreadCount); } } } void MessagesModel::onMessageSent(const Tp::Message &message, Tp::MessageSendingFlags flags, const QString &messageToken) { Q_UNUSED(flags); int length = rowCount(); beginInsertRows(QModelIndex(), length, length); kDebug() << "text =" << message.text(); const KTp::Message &newMessage = KTp::MessageProcessor::instance()->processIncomingMessage( message, d->account, d->textChannel); d->messages.append(newMessage); if (!messageToken.isEmpty()) { // Insert the message into the lookup table for delivery reports. const QPersistentModelIndex &modelIndex(createIndex(length, 0)); d->messagesByMessageToken.insert(messageToken, modelIndex); } endInsertRows(); } void MessagesModel::onPendingMessageRemoved() { Q_EMIT unreadCountChanged(unreadCount()); } QVariant MessagesModel::data(const QModelIndex &index, int role) const { QVariant result; if (index.isValid()) { const MessagePrivate m = d->messages[index.row()]; switch (role) { case TextRole: result = m.message.finalizedMessage(); break; case TypeRole: if (m.message.type() == Tp::ChannelTextMessageTypeAction) { result = MessageTypeAction; } else { if (m.message.direction() == KTp::Message::LocalToRemote) { result = MessageTypeOutgoing; } else { result = MessageTypeIncoming; } } break; case TimeRole: result = m.message.time(); break; case SenderIdRole: result = m.message.senderId(); break; case SenderAliasRole: result = m.message.senderAlias(); break; case SenderAvatarRole: if (m.message.sender()) { result = QVariant::fromValue(m.message.sender()->avatarPixmap()); } break; case DeliveryStatusRole: result = m.deliveryStatus; break; case DeliveryReportReceiveTimeRole: result = m.deliveryReportReceiveTime; break; }; } else { kError() << "Attempting to access data at invalid index (" << index << ")"; } return result; } int MessagesModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return d->messages.size(); } void MessagesModel::sendNewMessage(const QString &message) { if (message.isEmpty()) { kWarning() << "Attempting to send empty string"; } else { Tp::PendingOperation *op; QString modifiedMessage = message; if (d->textChannel->supportsMessageType(Tp::ChannelTextMessageTypeAction) && modifiedMessage.startsWith(QLatin1String("/me "))) { //remove "/me " from the start of the message modifiedMessage.remove(0,4); op = d->textChannel->send(modifiedMessage, Tp::ChannelTextMessageTypeAction); } else { op = d->textChannel->send(modifiedMessage); } connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(verifyPendingOperation(Tp::PendingOperation*))); } } void MessagesModel::removeChannelSignals(const Tp::TextChannelPtr &channel) { QObject::disconnect(channel.data(), SIGNAL(messageReceived(Tp::ReceivedMessage)), this, SLOT(onMessageReceived(Tp::ReceivedMessage)) ); QObject::disconnect(channel.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)), this, SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString)) ); } int MessagesModel::unreadCount() const { return d->textChannel->messageQueue().size(); } void MessagesModel::acknowledgeAllMessages() { QList<Tp::ReceivedMessage> queue = d->textChannel->messageQueue(); kDebug() << "Conversation Visible, Acknowledging " << queue.size() << " messages."; d->textChannel->acknowledge(queue); Q_EMIT unreadCountChanged(queue.size()); } void MessagesModel::setVisibleToUser(bool visible) { kDebug() << visible; if (d->visible != visible) { d->visible = visible; Q_EMIT visibleToUserChanged(d->visible); } if (visible) { acknowledgeAllMessages(); } } bool MessagesModel::isVisibleToUser() const { return d->visible; } MessagesModel::~MessagesModel() { kDebug(); delete d; } bool MessagesModel::shouldStartOpened() const { return d->textChannel->isRequested(); } <commit_msg>optimize InsertRows in model<commit_after>/* Copyright (C) 2011 Lasath Fernando <kde@lasath.org> Copyright (C) 2013 Lasath Fernando <davidedmundson@kde.org> 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 "messages-model.h" #include <KDebug> #include <KLocalizedString> #include <TelepathyQt/ReceivedMessage> #include <TelepathyQt/TextChannel> #include <TelepathyQt/Account> #include <KTp/message-processor.h> #include <KTp/message-context.h> #include <KTp/Logger/scrollback-manager.h> class MessagePrivate { public: MessagePrivate(const KTp::Message &message); KTp::Message message; MessagesModel::DeliveryStatus deliveryStatus; QDateTime deliveryReportReceiveTime; }; MessagePrivate::MessagePrivate(const KTp::Message &message) : message(message), deliveryStatus(MessagesModel::DeliveryStatusUnknown) { } class MessagesModel::MessagesModelPrivate { public: Tp::TextChannelPtr textChannel; Tp::AccountPtr account; ScrollbackManager *logManager; QList<MessagePrivate> messages; // For fast lookup of original messages upon receipt of a message delivery report. QHash<QString /*messageToken*/, QPersistentModelIndex> messagesByMessageToken; bool visible; }; MessagesModel::MessagesModel(const Tp::AccountPtr &account, QObject *parent) : QAbstractListModel(parent), d(new MessagesModelPrivate) { kDebug(); QHash<int, QByteArray> roles; roles[TextRole] = "text"; roles[TimeRole] = "time"; roles[TypeRole] = "type"; roles[SenderIdRole] = "senderId"; roles[SenderAliasRole] = "senderAlias"; roles[SenderAvatarRole] = "senderAvatar"; roles[DeliveryStatusRole] = "deliveryStatus"; roles[DeliveryReportReceiveTimeRole] = "deliveryReportReceiveTime"; setRoleNames(roles); d->account = account; d->visible = false; d->logManager = new ScrollbackManager(this); connect(d->logManager, SIGNAL(fetched(QList<KTp::Message>)), SLOT(onHistoryFetched(QList<KTp::Message>))); //Load configuration for number of message to show KConfig config(QLatin1String("ktelepathyrc")); KConfigGroup tabConfig = config.group("Behavior"); d->logManager->setScrollbackLength(tabConfig.readEntry<int>("scrollbackLength", 10)); } Tp::TextChannelPtr MessagesModel::textChannel() const { return d->textChannel; } bool MessagesModel::verifyPendingOperation(Tp::PendingOperation *op) { bool operationSucceeded = true; if (op->isError()) { kWarning() << op->errorName() << "+" << op->errorMessage(); operationSucceeded = false; } return operationSucceeded; } void MessagesModel::setupChannelSignals(const Tp::TextChannelPtr &channel) { connect(channel.data(), SIGNAL(messageReceived(Tp::ReceivedMessage)), SLOT(onMessageReceived(Tp::ReceivedMessage))); connect(channel.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)), SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString))); connect(channel.data(), SIGNAL(pendingMessageRemoved(Tp::ReceivedMessage)), SLOT(onPendingMessageRemoved())); } void MessagesModel::setTextChannel(const Tp::TextChannelPtr &channel) { Q_ASSERT(channel != d->textChannel); kDebug(); setupChannelSignals(channel); if (d->textChannel) { removeChannelSignals(d->textChannel); } d->textChannel = channel; d->logManager->setTextChannel(d->account, d->textChannel); d->logManager->fetchScrollback(); QList<Tp::ReceivedMessage> messageQueue = channel->messageQueue(); Q_FOREACH(const Tp::ReceivedMessage &message, messageQueue) { bool messageAlreadyInModel = false; Q_FOREACH(const MessagePrivate &current, d->messages) { //FIXME: docs say messageToken can return an empty string. What to do if that happens? //Tp::Message has an == operator. maybe I can use that? if (current.message.token() == message.messageToken()) { messageAlreadyInModel = true; break; } } if (!messageAlreadyInModel) { onMessageReceived(message); } } } void MessagesModel::onHistoryFetched(const QList<KTp::Message> &messages) { kDebug() << "found" << messages.count() << "messages in history"; if (!messages.isEmpty()) { //Add all messages before the ones already present in the channel beginInsertRows(QModelIndex(), 0, messages.count() - 1); for(int i=messages.size()-1;i>=0;i--) { d->messages.prepend(messages[i]); } endInsertRows(); } } void MessagesModel::onMessageReceived(const Tp::ReceivedMessage &message) { int unreadCount = d->textChannel->messageQueue().size(); kDebug() << "unreadMessagesCount =" << unreadCount; kDebug() << "text =" << message.text(); kDebug() << "messageType = " << message.messageType(); kDebug() << "messageToken =" << message.messageToken(); if (message.isDeliveryReport()) { d->textChannel->acknowledge(QList<Tp::ReceivedMessage>() << message); Tp::ReceivedMessage::DeliveryDetails deliveryDetails = message.deliveryDetails(); if(!deliveryDetails.hasOriginalToken()) { kDebug() << "Delivery report without original message token received."; // Matching the delivery report to the original message is impossible without the token. return; } kDebug() << "originalMessageToken =" << deliveryDetails.originalToken(); QPersistentModelIndex originalMessageIndex = d->messagesByMessageToken.value( deliveryDetails.originalToken()); if (!originalMessageIndex.isValid() || originalMessageIndex.row() >= d->messages.count()) { // The original message for this delivery report was not found. return; } MessagePrivate &originalMessage = d->messages[originalMessageIndex.row()]; kDebug() << "Got delivery status" << deliveryDetails.status() << "for message with text" << originalMessage.message.mainMessagePart(); originalMessage.deliveryReportReceiveTime = message.received(); switch(deliveryDetails.status()) { case Tp::DeliveryStatusPermanentlyFailed: case Tp::DeliveryStatusTemporarilyFailed: originalMessage.deliveryStatus = DeliveryStatusFailed; if (deliveryDetails.hasDebugMessage()) { kDebug() << "Delivery failure debug message:" << deliveryDetails.debugMessage(); } break; case Tp::DeliveryStatusDelivered: originalMessage.deliveryStatus = DeliveryStatusDelivered; break; case Tp::DeliveryStatusRead: originalMessage.deliveryStatus = DeliveryStatusRead; break; default: originalMessage.deliveryStatus = DeliveryStatusUnknown; break; } Q_EMIT dataChanged(originalMessageIndex, originalMessageIndex); } else { int length = rowCount(); beginInsertRows(QModelIndex(), length, length); d->messages.append(KTp::MessageProcessor::instance()->processIncomingMessage( message, d->account, d->textChannel)); endInsertRows(); if (d->visible) { acknowledgeAllMessages(); } else { Q_EMIT unreadCountChanged(unreadCount); } } } void MessagesModel::onMessageSent(const Tp::Message &message, Tp::MessageSendingFlags flags, const QString &messageToken) { Q_UNUSED(flags); int length = rowCount(); beginInsertRows(QModelIndex(), length, length); kDebug() << "text =" << message.text(); const KTp::Message &newMessage = KTp::MessageProcessor::instance()->processIncomingMessage( message, d->account, d->textChannel); d->messages.append(newMessage); if (!messageToken.isEmpty()) { // Insert the message into the lookup table for delivery reports. const QPersistentModelIndex &modelIndex(createIndex(length, 0)); d->messagesByMessageToken.insert(messageToken, modelIndex); } endInsertRows(); } void MessagesModel::onPendingMessageRemoved() { Q_EMIT unreadCountChanged(unreadCount()); } QVariant MessagesModel::data(const QModelIndex &index, int role) const { QVariant result; if (index.isValid()) { const MessagePrivate m = d->messages[index.row()]; switch (role) { case TextRole: result = m.message.finalizedMessage(); break; case TypeRole: if (m.message.type() == Tp::ChannelTextMessageTypeAction) { result = MessageTypeAction; } else { if (m.message.direction() == KTp::Message::LocalToRemote) { result = MessageTypeOutgoing; } else { result = MessageTypeIncoming; } } break; case TimeRole: result = m.message.time(); break; case SenderIdRole: result = m.message.senderId(); break; case SenderAliasRole: result = m.message.senderAlias(); break; case SenderAvatarRole: if (m.message.sender()) { result = QVariant::fromValue(m.message.sender()->avatarPixmap()); } break; case DeliveryStatusRole: result = m.deliveryStatus; break; case DeliveryReportReceiveTimeRole: result = m.deliveryReportReceiveTime; break; }; } else { kError() << "Attempting to access data at invalid index (" << index << ")"; } return result; } int MessagesModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return d->messages.size(); } void MessagesModel::sendNewMessage(const QString &message) { if (message.isEmpty()) { kWarning() << "Attempting to send empty string"; } else { Tp::PendingOperation *op; QString modifiedMessage = message; if (d->textChannel->supportsMessageType(Tp::ChannelTextMessageTypeAction) && modifiedMessage.startsWith(QLatin1String("/me "))) { //remove "/me " from the start of the message modifiedMessage.remove(0,4); op = d->textChannel->send(modifiedMessage, Tp::ChannelTextMessageTypeAction); } else { op = d->textChannel->send(modifiedMessage); } connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(verifyPendingOperation(Tp::PendingOperation*))); } } void MessagesModel::removeChannelSignals(const Tp::TextChannelPtr &channel) { QObject::disconnect(channel.data(), SIGNAL(messageReceived(Tp::ReceivedMessage)), this, SLOT(onMessageReceived(Tp::ReceivedMessage)) ); QObject::disconnect(channel.data(), SIGNAL(messageSent(Tp::Message,Tp::MessageSendingFlags,QString)), this, SLOT(onMessageSent(Tp::Message,Tp::MessageSendingFlags,QString)) ); } int MessagesModel::unreadCount() const { return d->textChannel->messageQueue().size(); } void MessagesModel::acknowledgeAllMessages() { QList<Tp::ReceivedMessage> queue = d->textChannel->messageQueue(); kDebug() << "Conversation Visible, Acknowledging " << queue.size() << " messages."; d->textChannel->acknowledge(queue); Q_EMIT unreadCountChanged(queue.size()); } void MessagesModel::setVisibleToUser(bool visible) { kDebug() << visible; if (d->visible != visible) { d->visible = visible; Q_EMIT visibleToUserChanged(d->visible); } if (visible) { acknowledgeAllMessages(); } } bool MessagesModel::isVisibleToUser() const { return d->visible; } MessagesModel::~MessagesModel() { kDebug(); delete d; } bool MessagesModel::shouldStartOpened() const { return d->textChannel->isRequested(); } <|endoftext|>
<commit_before>/* Copyright (c) 2015 Genome Research Ltd. Author: Jouni Siren <jouni.siren@iki.fi> 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 <sdsl/suffix_trees.hpp> #include <sdsl/suffix_tree_algorithm.hpp> #include "relative_cst.h" using namespace relative; //------------------------------------------------------------------------------ //#define VERIFY_RESULTS template<class CST> void buildCST(CST& cst, const std::string& base_name, const std::string& type); void buildSelect(RelativeFM<>& fm, const std::string& base_name); template<class CST> void matchingStatistics(const CST& cst, const int_vector<8>& seq, std::vector<range_type>& ranges, std::vector<uint64_t>& depths, const std::string& name, uint64_t indent = 18); //------------------------------------------------------------------------------ int main(int argc, char** argv) { if(argc < 4) { std::cerr << "Usage: cst_compare reference target sequence" << std::endl; std::cerr << std::endl; return 1; } std::cout << "Finding the matching statistics with a CST" << std::endl; std::cout << std::endl; std::string ref_name = argv[1]; std::cout << "Reference: " << ref_name << std::endl; SimpleFM<> ref_fm(ref_name); uint64_t fm_bytes = ref_fm.reportSize(); printSize("FM-index", fm_bytes, ref_fm.size()); RelativeLCP::lcp_type ref_lcp; load_from_file(ref_lcp, ref_name + LCP_EXTENSION); uint64_t lcp_bytes = size_in_bytes(ref_lcp); printSize("LCP array", lcp_bytes, ref_lcp.size()); printSize("Reference data", fm_bytes + lcp_bytes, ref_fm.size()); std::cout << std::endl; std::string target_name = argv[2]; std::cout << "Target: " << target_name << std::endl; std::string seq_name = argv[3]; int_vector<8> seq; { std::ifstream in(seq_name.c_str(), std::ios_base::binary); if(!in) { std::cerr << "cst_compare: Cannot open sequence file " << seq_name << std::endl; return 2; } uint64_t size = util::file_size(seq_name); seq.resize(size); in.read((char*)(seq.data()), size); in.close(); } std::cout << "Sequence: " << seq_name << " (" << seq.size() << " bytes)" << std::endl; std::cout << std::endl; std::vector<range_type> rcst_ranges; std::vector<uint64_t> rcst_depths; { std::string name = "Relative CST"; RelativeFM<> rfm(ref_fm, target_name); buildSelect(rfm, target_name); RelativeLCP rlcp(ref_lcp, target_name); RelativeCST<> rcst(rfm, rlcp); printSize(name, rcst.reportSize(), rcst.size()); matchingStatistics(rcst, seq, rcst_ranges, rcst_depths, name); std::cout << std::endl; } std::vector<range_type> cst_ranges; std::vector<uint64_t> cst_depths; { std::string name = "cst_sct3_dac"; cst_sct3<> cst; buildCST(cst, target_name, name); matchingStatistics(cst, seq, cst_ranges, cst_depths, name); std::cout << std::endl; } { std::string name = "cst_sct3_plcp"; cst_sct3<csa_wt<>, lcp_support_sada<>> cst; buildCST(cst, target_name, name); matchingStatistics(cst, seq, cst_ranges, cst_depths, name); std::cout << std::endl; } { std::string name = "cst_sada"; cst_sada<> cst; buildCST(cst, target_name, name); matchingStatistics(cst, seq, cst_ranges, cst_depths, name); std::cout << std::endl; } #ifdef VERIFY_RESULTS for(uint64_t i = 0; i < seq.size(); i++) { if(rcst_ranges[i] != cst_ranges[i] || rcst_depths[i] != cst_depths[i]) { std::cerr << "cst_compare: Matching statistics for " << seq_name << "[" << i << "]:" << std::endl; std::cerr << " Relative CST: range " << rcst_ranges[i] << ", depth " << rcst_depths[i] << std::endl; std::cerr << " CST: range " << cst_ranges[i] << ", depth " << cst_depths[i] << std::endl; break; } } #endif std::cout << "Memory used: " << inMegabytes(memoryUsage()) << " MB" << std::endl; std::cout << std::endl; return 0; } //------------------------------------------------------------------------------ bool file_exists(const std::string& name) { std::ifstream in(name.c_str(), std::ios_base::binary); if(!in) { return false; } in.close(); return true; } template<class CST> void buildCST(CST& cst, const std::string& base_name, const std::string& type) { std::string cst_file = base_name + "." + type; if(file_exists(cst_file)) { load_from_file(cst, cst_file); } else { construct(cst, base_name, 1); store_to_file(cst, cst_file); } printSize(type, size_in_bytes(cst), cst.size()); } void buildSelect(RelativeFM<>& rfm, const std::string& base_name) { if(rfm.fastSelect()) { return; } if(!(rfm.loadSelect(base_name))) { double start = readTimer(); rfm.buildSelect(); double seconds = readTimer() - start; std::cout << "Select structures built in " << seconds << " seconds" << std::endl; std::cout << std::endl; rfm.writeSelect(base_name); } } //------------------------------------------------------------------------------ template<class CST> void maximalMatch(const CST& cst, const int_vector<8>& seq, typename CST::node_type& prev, typename CST::node_type& next, uint64_t start_offset, typename CST::size_type& depth, typename CST::size_type& next_depth) { typename CST::size_type bwt_pos = (depth >= next_depth ? 0 : get_char_pos(cst.lb(next), depth - 1, cst.csa)); while(start_offset + depth < seq.size()) { auto comp = cst.csa.char2comp[seq[start_offset + depth]]; if(comp == 0 && seq[start_offset + depth] != 0) { break; } if(depth >= next_depth) // Next node reached, follow a new edge. { typename CST::node_type temp = cst.child(next, seq[start_offset + depth], bwt_pos); if(temp == cst.root()) { break; } next = temp; next_depth = cst.depth(next); } else // Continue in the edge. { bwt_pos = cst.csa.psi[bwt_pos]; if(bwt_pos < cst.csa.C[comp] || bwt_pos >= cst.csa.C[comp + 1]) { break; } } depth++; if(depth >= next_depth) { prev = next; } } } template<> void maximalMatch(const RelativeCST<>& cst, const int_vector<8>& seq, RelativeCST<>::node_type& prev, RelativeCST<>::node_type& next, uint64_t start_offset, RelativeCST<>::size_type& depth, RelativeCST<>::size_type& next_depth) { RelativeCST<>::size_type bwt_pos = (depth >= next_depth ? cst.size() : cst.index.Psi(cst.lb(next), depth - 1)); while(start_offset + depth < seq.size() && cst.forward_search(next, next_depth, depth, seq[start_offset + depth], bwt_pos)) { depth++; if(depth >= next_depth) { prev = next; } } } template<class CST> void matchingStatistics(const CST& cst, const int_vector<8>& seq, std::vector<range_type>& ranges, std::vector<uint64_t>& depths, const std::string& name, uint64_t indent) { util::clear(ranges); util::clear(depths); // prev is the last node we have fully matched. // If next != prev, we are in the edge from prev to next. double start = readTimer(); typename CST::node_type prev = cst.root(), next = cst.root(); typename CST::size_type depth = 0, next_depth = 0; maximalMatch(cst, seq, prev, next, 0, depth, next_depth); ranges.push_back(range_type(cst.lb(next), cst.rb(next))); depths.push_back(depth); uint64_t total_length = depth; for(uint64_t i = 1; i < seq.size(); i++) { if(depth == 0) { maximalMatch(cst, seq, prev, next, i, depth, next_depth); } else { next = prev = cst.sl(prev); depth--; next_depth = cst.depth(prev); while(next_depth < depth) { typename CST::size_type bwt_pos; next = cst.child(next, seq[i + next_depth], bwt_pos); next_depth = cst.depth(next); if(next_depth <= depth) { prev = next; } } maximalMatch(cst, seq, prev, next, i, depth, next_depth); } ranges.push_back(range_type(cst.lb(next), cst.rb(next))); depths.push_back(depth); total_length += depth; } double seconds = readTimer() - start; std::string padding; if(name.length() + 1 < indent) { padding = std::string(indent - 1 - name.length(), ' '); } std::cout << name << ":" << padding << "Average maximal match: " << (total_length / (double)(cst.size())) << " (" << seconds << " seconds)" << std::endl; } //------------------------------------------------------------------------------ <commit_msg>Minor output change.<commit_after>/* Copyright (c) 2015 Genome Research Ltd. Author: Jouni Siren <jouni.siren@iki.fi> 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 <sdsl/suffix_trees.hpp> #include <sdsl/suffix_tree_algorithm.hpp> #include "relative_cst.h" using namespace relative; //------------------------------------------------------------------------------ //#define VERIFY_RESULTS template<class CST> void buildCST(CST& cst, const std::string& base_name, const std::string& type); void buildSelect(RelativeFM<>& fm, const std::string& base_name); template<class CST> void matchingStatistics(const CST& cst, const int_vector<8>& seq, std::vector<range_type>& ranges, std::vector<uint64_t>& depths, const std::string& name, uint64_t indent = 18); //------------------------------------------------------------------------------ int main(int argc, char** argv) { if(argc < 4) { std::cerr << "Usage: cst_compare reference target sequence" << std::endl; std::cerr << std::endl; return 1; } std::cout << "Finding the matching statistics with a CST" << std::endl; std::cout << std::endl; std::string ref_name = argv[1]; std::cout << "Reference: " << ref_name << std::endl; SimpleFM<> ref_fm(ref_name); uint64_t fm_bytes = ref_fm.reportSize(); printSize("FM-index", fm_bytes, ref_fm.size()); RelativeLCP::lcp_type ref_lcp; load_from_file(ref_lcp, ref_name + LCP_EXTENSION); uint64_t lcp_bytes = size_in_bytes(ref_lcp); printSize("LCP array", lcp_bytes, ref_lcp.size()); printSize("Reference data", fm_bytes + lcp_bytes, ref_fm.size()); std::cout << std::endl; std::string target_name = argv[2]; std::cout << "Target: " << target_name << std::endl; std::string seq_name = argv[3]; int_vector<8> seq; { std::ifstream in(seq_name.c_str(), std::ios_base::binary); if(!in) { std::cerr << "cst_compare: Cannot open sequence file " << seq_name << std::endl; return 2; } uint64_t size = util::file_size(seq_name); seq.resize(size); in.read((char*)(seq.data()), size); in.close(); } std::cout << "Sequence: " << seq_name << " (" << seq.size() << " bytes)" << std::endl; std::cout << std::endl; std::vector<range_type> rcst_ranges; std::vector<uint64_t> rcst_depths; { std::string name = "Relative CST"; RelativeFM<> rfm(ref_fm, target_name); buildSelect(rfm, target_name); RelativeLCP rlcp(ref_lcp, target_name); RelativeCST<> rcst(rfm, rlcp); printSize(name, rcst.reportSize(), rcst.size()); matchingStatistics(rcst, seq, rcst_ranges, rcst_depths, name); std::cout << std::endl; } std::vector<range_type> cst_ranges; std::vector<uint64_t> cst_depths; { std::string name = "cst_sct3_dac"; cst_sct3<> cst; buildCST(cst, target_name, name); matchingStatistics(cst, seq, cst_ranges, cst_depths, name); std::cout << std::endl; } { std::string name = "cst_sct3_plcp"; cst_sct3<csa_wt<>, lcp_support_sada<>> cst; buildCST(cst, target_name, name); matchingStatistics(cst, seq, cst_ranges, cst_depths, name); std::cout << std::endl; } { std::string name = "cst_sada"; cst_sada<> cst; buildCST(cst, target_name, name); matchingStatistics(cst, seq, cst_ranges, cst_depths, name); std::cout << std::endl; } #ifdef VERIFY_RESULTS for(uint64_t i = 0; i < seq.size(); i++) { if(rcst_ranges[i] != cst_ranges[i] || rcst_depths[i] != cst_depths[i]) { std::cerr << "cst_compare: Matching statistics for " << seq_name << "[" << i << "]:" << std::endl; std::cerr << " Relative CST: range " << rcst_ranges[i] << ", depth " << rcst_depths[i] << std::endl; std::cerr << " CST: range " << cst_ranges[i] << ", depth " << cst_depths[i] << std::endl; break; } } std::cout << "Matching statistics verified." << std::endl; std::cout << std::endl; #endif std::cout << "Memory used: " << inMegabytes(memoryUsage()) << " MB" << std::endl; std::cout << std::endl; return 0; } //------------------------------------------------------------------------------ bool file_exists(const std::string& name) { std::ifstream in(name.c_str(), std::ios_base::binary); if(!in) { return false; } in.close(); return true; } template<class CST> void buildCST(CST& cst, const std::string& base_name, const std::string& type) { std::string cst_file = base_name + "." + type; if(file_exists(cst_file)) { load_from_file(cst, cst_file); } else { construct(cst, base_name, 1); store_to_file(cst, cst_file); } printSize(type, size_in_bytes(cst), cst.size()); } void buildSelect(RelativeFM<>& rfm, const std::string& base_name) { if(rfm.fastSelect()) { return; } if(!(rfm.loadSelect(base_name))) { double start = readTimer(); rfm.buildSelect(); double seconds = readTimer() - start; std::cout << "Select structures built in " << seconds << " seconds" << std::endl; std::cout << std::endl; rfm.writeSelect(base_name); } } //------------------------------------------------------------------------------ template<class CST> void maximalMatch(const CST& cst, const int_vector<8>& seq, typename CST::node_type& prev, typename CST::node_type& next, uint64_t start_offset, typename CST::size_type& depth, typename CST::size_type& next_depth) { typename CST::size_type bwt_pos = (depth >= next_depth ? 0 : get_char_pos(cst.lb(next), depth - 1, cst.csa)); while(start_offset + depth < seq.size()) { auto comp = cst.csa.char2comp[seq[start_offset + depth]]; if(comp == 0 && seq[start_offset + depth] != 0) { break; } if(depth >= next_depth) // Next node reached, follow a new edge. { typename CST::node_type temp = cst.child(next, seq[start_offset + depth], bwt_pos); if(temp == cst.root()) { break; } next = temp; next_depth = cst.depth(next); } else // Continue in the edge. { bwt_pos = cst.csa.psi[bwt_pos]; if(bwt_pos < cst.csa.C[comp] || bwt_pos >= cst.csa.C[comp + 1]) { break; } } depth++; if(depth >= next_depth) { prev = next; } } } template<> void maximalMatch(const RelativeCST<>& cst, const int_vector<8>& seq, RelativeCST<>::node_type& prev, RelativeCST<>::node_type& next, uint64_t start_offset, RelativeCST<>::size_type& depth, RelativeCST<>::size_type& next_depth) { RelativeCST<>::size_type bwt_pos = (depth >= next_depth ? cst.size() : cst.index.Psi(cst.lb(next), depth - 1)); while(start_offset + depth < seq.size() && cst.forward_search(next, next_depth, depth, seq[start_offset + depth], bwt_pos)) { depth++; if(depth >= next_depth) { prev = next; } } } template<class CST> void matchingStatistics(const CST& cst, const int_vector<8>& seq, std::vector<range_type>& ranges, std::vector<uint64_t>& depths, const std::string& name, uint64_t indent) { util::clear(ranges); util::clear(depths); // prev is the last node we have fully matched. // If next != prev, we are in the edge from prev to next. double start = readTimer(); typename CST::node_type prev = cst.root(), next = cst.root(); typename CST::size_type depth = 0, next_depth = 0; maximalMatch(cst, seq, prev, next, 0, depth, next_depth); ranges.push_back(range_type(cst.lb(next), cst.rb(next))); depths.push_back(depth); uint64_t total_length = depth; for(uint64_t i = 1; i < seq.size(); i++) { if(depth == 0) { maximalMatch(cst, seq, prev, next, i, depth, next_depth); } else { next = prev = cst.sl(prev); depth--; next_depth = cst.depth(prev); while(next_depth < depth) { typename CST::size_type bwt_pos; next = cst.child(next, seq[i + next_depth], bwt_pos); next_depth = cst.depth(next); if(next_depth <= depth) { prev = next; } } maximalMatch(cst, seq, prev, next, i, depth, next_depth); } ranges.push_back(range_type(cst.lb(next), cst.rb(next))); depths.push_back(depth); total_length += depth; } double seconds = readTimer() - start; std::string padding; if(name.length() + 1 < indent) { padding = std::string(indent - 1 - name.length(), ' '); } std::cout << name << ":" << padding << "Average maximal match: " << (total_length / (double)(cst.size())) << " (" << seconds << " seconds)" << std::endl; } //------------------------------------------------------------------------------ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2011, 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_LRUCACHE_INL #define IECORE_LRUCACHE_INL #include <cassert> #include "tbb/tbb_thread.h" #include "IECore/Exception.h" namespace IECore { template<typename Key, typename Ptr> LRUCache<Key, Ptr>::CacheEntry::CacheEntry() : cost( 0 ), status( New ), data() { } template<typename Key, typename Ptr> LRUCache<Key, Ptr>::LRUCache( GetterFunction getter ) : m_getter( getter ), m_maxCost( 500 ), m_currentCost( 0 ) { } template<typename Key, typename Ptr> LRUCache<Key, Ptr>::LRUCache( GetterFunction getter, Cost maxCost ) : m_getter( getter ), m_maxCost( maxCost ), m_currentCost( 0 ) { } template<typename Key, typename Ptr> LRUCache<Key, Ptr>::~LRUCache() { } template<typename Key, typename Ptr> void LRUCache<Key, Ptr>::clear() { Mutex::scoped_lock lock( m_mutex ); m_currentCost = Cost(0); m_list.clear(); m_cache.clear(); } template<typename Key, typename Ptr> void LRUCache<Key, Ptr>::setMaxCost( Cost maxCost ) { Mutex::scoped_lock lock( m_mutex ); assert( maxCost >= Cost(0) ); m_maxCost = maxCost; limitCost( m_maxCost ); } template<typename Key, typename Ptr> typename LRUCache<Key, Ptr>::Cost LRUCache<Key, Ptr>::getMaxCost() const { Mutex::scoped_lock lock( m_mutex ); return m_maxCost; } template<typename Key, typename Ptr> typename LRUCache<Key, Ptr>::Cost LRUCache<Key, Ptr>::currentCost() const { Mutex::scoped_lock lock( m_mutex ); return m_currentCost; } template<typename Key, typename Ptr> bool LRUCache<Key, Ptr>::cached( const Key &key ) const { Mutex::scoped_lock lock( m_mutex ); ConstCacheIterator it = m_cache.find( key ); return ( it != m_cache.end() && it->second.status==Cached ); } template<typename Key, typename Ptr> Ptr LRUCache<Key, Ptr>::get( const Key& key ) { Mutex::scoped_lock lock( m_mutex ); CacheEntry &cacheEntry = m_cache[key]; // creates an entry if one doesn't exist yet if( cacheEntry.status==Caching ) { // another thread is doing the work. we need to wait // until it is done. lock.release(); while( cacheEntry.status==Caching ) { tbb::this_tbb_thread::yield(); } lock.acquire( m_mutex ); } if( cacheEntry.status==New || cacheEntry.status==Erased || cacheEntry.status==TooCostly ) { assert( cacheEntry.data==Ptr() ); Ptr data = Ptr(); Cost cost = 0; try { cacheEntry.status = Caching; lock.release(); // allows other threads to do stuff while we're computing the value data = m_getter( key, cost ); lock.acquire( m_mutex ); } catch( ... ) { lock.acquire( m_mutex ); CacheEntry &cacheEntry = m_cache[key]; // in case some other thread erased our entry while we had released the lock cacheEntry.status = Failed; throw; } assert( data ); assert( cacheEntry.status != Cached ); // this would indicate that another thread somehow assert( cacheEntry.status != Failed ); // loaded the same thing as us, which is not the intention. set( key, data, cost ); return data; } else if( cacheEntry.status==Cached ) { // move the entry to the front of the list m_list.erase( cacheEntry.listIterator ); m_list.push_front( key ); cacheEntry.listIterator = m_list.begin(); return cacheEntry.data; } else { assert( cacheEntry.status==Failed ); throw Exception( "Previous attempt to get item failed." ); } } template<typename Key, typename Ptr> bool LRUCache<Key, Ptr>::set( const Key &key, const Ptr &data, Cost cost ) { Mutex::scoped_lock lock( m_mutex ); CacheEntry &cacheEntry = m_cache[key]; // creates an entry if one doesn't exist yet if( cacheEntry.status==Cached ) { m_currentCost -= cacheEntry.cost; cacheEntry.data = Ptr(); m_list.erase( cacheEntry.listIterator ); } if( cost > m_maxCost ) { cacheEntry.status = TooCostly; return false; } limitCost( m_maxCost - cost ); cacheEntry.data = data; cacheEntry.cost = cost; cacheEntry.status = Cached; m_list.push_front( key ); cacheEntry.listIterator = m_list.begin(); m_currentCost += cost; return true; } template<typename Key, typename Ptr> void LRUCache<Key, Ptr>::limitCost( Cost cost ) { Mutex::scoped_lock lock( m_mutex ); assert( cost >= Cost(0) ); while( m_currentCost > cost && m_list.size() ) { bool erased = erase( m_list.back() ); assert( erased ); (void)erased; } assert( m_currentCost <= cost ); } template<typename Key, typename Ptr> bool LRUCache<Key, Ptr>::erase( const Key &key ) { Mutex::scoped_lock lock( m_mutex ); typename Cache::iterator it = m_cache.find( key ); if( it == m_cache.end() ) { return false; } if( it->second.status==Cached ) { m_currentCost -= it->second.cost; m_list.erase( it->second.listIterator ); it->second.data = Ptr(); } it->second.status = Erased; return true; } } // namespace IECore #endif // IECORE_LRUCACHE_INL <commit_msg>Fixed a few potential problems in IECore/LRUCache.inl, related to invalid pointers and general threading shenanigans<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2011, 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. // ////////////////////////////////////////////////////////////////////////// #ifndef IECORE_LRUCACHE_INL #define IECORE_LRUCACHE_INL #include <cassert> #include "tbb/tbb_thread.h" #include "IECore/Exception.h" namespace IECore { template<typename Key, typename Ptr> LRUCache<Key, Ptr>::CacheEntry::CacheEntry() : cost( 0 ), status( New ), data() { } template<typename Key, typename Ptr> LRUCache<Key, Ptr>::LRUCache( GetterFunction getter ) : m_getter( getter ), m_maxCost( 500 ), m_currentCost( 0 ) { } template<typename Key, typename Ptr> LRUCache<Key, Ptr>::LRUCache( GetterFunction getter, Cost maxCost ) : m_getter( getter ), m_maxCost( maxCost ), m_currentCost( 0 ) { } template<typename Key, typename Ptr> LRUCache<Key, Ptr>::~LRUCache() { } template<typename Key, typename Ptr> void LRUCache<Key, Ptr>::clear() { Mutex::scoped_lock lock( m_mutex ); m_currentCost = Cost(0); m_list.clear(); // TODO: make it so you can actually clear this map. If a clear happens while m_mutex has // been released down in the get() method, bad things can happen, as iterators can get // invalidated. Therefore, we don't erase the cache entries, we just erase the data. for( typename Cache::iterator it = m_cache.begin(); it != m_cache.end(); ++it ) { it->second.status = Erased; it->second.cost = 0; it->second.data = Ptr(); } } template<typename Key, typename Ptr> void LRUCache<Key, Ptr>::setMaxCost( Cost maxCost ) { Mutex::scoped_lock lock( m_mutex ); assert( maxCost >= Cost(0) ); m_maxCost = maxCost; limitCost( m_maxCost ); } template<typename Key, typename Ptr> typename LRUCache<Key, Ptr>::Cost LRUCache<Key, Ptr>::getMaxCost() const { Mutex::scoped_lock lock( m_mutex ); return m_maxCost; } template<typename Key, typename Ptr> typename LRUCache<Key, Ptr>::Cost LRUCache<Key, Ptr>::currentCost() const { Mutex::scoped_lock lock( m_mutex ); return m_currentCost; } template<typename Key, typename Ptr> bool LRUCache<Key, Ptr>::cached( const Key &key ) const { Mutex::scoped_lock lock( m_mutex ); ConstCacheIterator it = m_cache.find( key ); return ( it != m_cache.end() && it->second.status==Cached ); } template<typename Key, typename Ptr> Ptr LRUCache<Key, Ptr>::get( const Key& key ) { Mutex::scoped_lock lock( m_mutex ); m_cache[key]; // creates an entry if one doesn't exist yet // this must be an iterator rather than a reference to a CacheEntry, as there's no guarantee // that the underlying pointer will remain valid if the map is modified. Iterators, however, always remain // valid (unless they're erased). typename Cache::iterator it = m_cache.find( key ); while( it->second.status==Caching ) { // another thread is doing the work. we need to wait // until it is done. lock.release(); while( it->second.status==Caching ) { tbb::this_tbb_thread::yield(); } lock.acquire( m_mutex ); // we use a while loop, because at this point it's possible another thread could have // set the status back to Caching, meaning we'd end up in the else block below and // trigger an assertion failure. } if( it->second.status==New || it->second.status==Erased || it->second.status==TooCostly ) { assert( it->second.data==Ptr() ); Ptr data = Ptr(); Cost cost = 0; try { it->second.status = Caching; lock.release(); // allows other threads to do stuff while we're computing the value data = m_getter( key, cost ); lock.acquire( m_mutex ); } catch( ... ) { lock.acquire( m_mutex ); it->second.status = Failed; throw; } assert( data ); assert( it->second.status != Cached ); // this would indicate that another thread somehow assert( it->second.status != Failed ); // loaded the same thing as us, which is not the intention. set( key, data, cost ); return data; } else if( it->second.status==Cached ) { // move the entry to the front of the list m_list.erase( it->second.listIterator ); m_list.push_front( key ); it->second.listIterator = m_list.begin(); return it->second.data; } else { assert( it->second.status==Failed ); throw Exception( "Previous attempt to get item failed." ); } } template<typename Key, typename Ptr> bool LRUCache<Key, Ptr>::set( const Key &key, const Ptr &data, Cost cost ) { Mutex::scoped_lock lock( m_mutex ); CacheEntry &cacheEntry = m_cache[key]; // creates an entry if one doesn't exist yet if( cacheEntry.status==Cached ) { m_currentCost -= cacheEntry.cost; cacheEntry.data = Ptr(); m_list.erase( cacheEntry.listIterator ); } if( cost > m_maxCost ) { cacheEntry.status = TooCostly; return false; } limitCost( m_maxCost - cost ); cacheEntry.data = data; cacheEntry.cost = cost; cacheEntry.status = Cached; m_list.push_front( key ); cacheEntry.listIterator = m_list.begin(); m_currentCost += cost; return true; } template<typename Key, typename Ptr> void LRUCache<Key, Ptr>::limitCost( Cost cost ) { Mutex::scoped_lock lock( m_mutex ); assert( cost >= Cost(0) ); while( m_currentCost > cost && m_list.size() ) { bool erased = erase( m_list.back() ); assert( erased ); (void)erased; } assert( m_currentCost <= cost ); } template<typename Key, typename Ptr> bool LRUCache<Key, Ptr>::erase( const Key &key ) { Mutex::scoped_lock lock( m_mutex ); typename Cache::iterator it = m_cache.find( key ); if( it == m_cache.end() ) { return false; } if( it->second.status==Cached ) { m_currentCost -= it->second.cost; m_list.erase( it->second.listIterator ); it->second.data = Ptr(); } it->second.status = Erased; return true; } } // namespace IECore #endif // IECORE_LRUCACHE_INL <|endoftext|>
<commit_before>/* * IncrementalKMeans.cpp * * Created on: May 13, 2015 * Author: andresf */ #include <IncrementalKMeans.hpp> #include <opencv2/core/core.hpp> namespace vlr { static const int MAX_OUTLIERS = 10; IncrementalKMeans::IncrementalKMeans(vlr::Mat data, const cvflann::IndexParams& params) : m_dataset(data), m_dim(data.cols), m_numDatapoints(data.rows) { // Attributes initialization m_numClusters = cvflann::get_param<int>(params, "num.clusters"); // Compute the global data set mean m_miu = cv::Mat::zeros(1, m_dim * 8, cv::DataType<double>::type); for (int i = 0; i < m_numDatapoints; ++i) { cv::Mat row = m_dataset.row(i); uchar byte = 0; for (int l = 0; l < m_miu.cols; l++) { if ((l % 8) == 0) { byte = *(row.col((int) l / 8).data); } m_miu.at<double>(0, l) += ((int) ((byte >> (7 - (l % 8))) % 2)); } } m_miu /= m_numDatapoints; // Compute the global data set standard deviations m_sigma = cv::Mat::zeros(1, m_dim * 8, cv::DataType<double>::type); for (int i = 0; i < m_numDatapoints; ++i) { cv::Mat row = m_dataset.row(i); uchar byte = 0; for (int l = 0; l < m_sigma.cols; l++) { if ((l % 8) == 0) { byte = *(row.col((int) l / 8).data); } m_sigma.at<double>(0, l) += pow(((int) ((byte >> (7 - (l % 8))) % 2)) - m_miu.at<double>(0, l), 2); } } m_sigma /= m_numDatapoints; cv::sqrt(m_sigma, m_sigma); m_centroids.create(m_numClusters, m_dim * 8, cv::DataType<double>::type); m_clustersVariances.create(m_numClusters, m_dim * 8, cv::DataType<double>::type); m_clustersWeights.create(1, m_numClusters, cv::DataType<double>::type); m_clustersSums.create(m_numClusters, m_dim * 8, cv::DataType<int>::type); m_clustersCounts.create(1, m_numClusters, cv::DataType<int>::type); m_clusterDistancesToNullTransaction.create(1, m_numClusters, cv::DataType<double>::type); m_outliers.resize(m_numClusters); } // -------------------------------------------------------------------------- IncrementalKMeans::~IncrementalKMeans() { } // -------------------------------------------------------------------------- void IncrementalKMeans::build() { // Mean-based initialization initCentroids(); // Compute distances between clusters centers and the null transaction preComputeDistances(); // Nj <- 0 // Mj <- 0 // Wj <- 1/k initClustersCounters(); double L = sqrt(m_numDatapoints); int clusterIndex; double distanceToCluster; for (int i = 0; i < m_numDatapoints; ++i) { cv::Mat transaction = m_dataset.row(i); // Cluster assignment // j = NN(ti) findNearestNeighbor(transaction, clusterIndex, distanceToCluster); // Insert transaction in the list of outliers bool isOutlier = insertOutlier(i, clusterIndex, distanceToCluster); // If the transaction is not an outlier then assign it to the jth cluster if (isOutlier) { // If the transaction is an outlier and is the farthest one on the jth cluster // then pop and assign the nearest outlier on the jth cluster if (m_outliers.at(clusterIndex).size() > MAX_OUTLIERS) { transaction = m_dataset.row(m_outliers.at(clusterIndex).back().first); m_outliers.at(clusterIndex).pop_back(); // Mj <- Mj + ti sparseSum(transaction, clusterIndex); // Nj <- Nj + 1 m_clustersCounts.col(clusterIndex) += 1; } } else { // Mj <- Mj + ti sparseSum(transaction, clusterIndex); // Nj <- Nj + 1 m_clustersCounts.col(clusterIndex) += 1; } // Update clusters centers every L times if (i % ((int) (m_numDatapoints / L)) == 0) { // Re-compute clusters centers computeCentroids(i); // Compute distances between clusters centers and the null transaction preComputeDistances(); // Re-seeding handleEmptyClusters(); } } } // -------------------------------------------------------------------------- void IncrementalKMeans::save(const std::string& filename) const { // TODO Implement this method } // -------------------------------------------------------------------------- void IncrementalKMeans::load(const std::string& filename) { // TODO Implement this method } // -------------------------------------------------------------------------- void IncrementalKMeans::initCentroids() { for (int j = 0; j < m_numClusters; ++j) { // Cj <- miu +/-sigma*r/d double r = (double) rand() / RAND_MAX; if (rand() % 2 == 0) { m_centroids.row(j) = (m_miu + m_sigma * r / (m_dim * 8)); } else { m_centroids.row(j) = (m_miu - m_sigma * r / (m_dim * 8)); } } } // -------------------------------------------------------------------------- void IncrementalKMeans::computeCentroids(const int& i) { for (int j = 0; j < m_numClusters; ++j) { // Cj <- Mj/Nj m_clustersSums.row(j).convertTo(m_centroids.row(j), cv::DataType<double>::type); m_centroids.row(j) = m_centroids.row(j) / ((double) m_clustersCounts.at<int>(0, j)); // Rj <- Cj - diag(Cj*Cj') cv::Mat clusterVariance(m_dim * 8, m_dim * 8, cv::DataType<double>::type); cv::mulTransposed(m_centroids.row(j), clusterVariance, true); m_clustersVariances.row(j) = m_centroids.row(j) - clusterVariance.diag(0).t(); // Wj <- Nj/i m_clustersWeights.col(j) = ((double) m_clustersCounts.at<int>(0, j)) / ((double) i); } } // -------------------------------------------------------------------------- void IncrementalKMeans::preComputeDistances() { cv::Mat nullTransaction = cv::Mat::zeros(1, m_dim * 8, cv::DataType<double>::type); for (int j = 0; j < m_numClusters; ++j) { cv::mulTransposed(nullTransaction - m_centroids.row(j), m_clusterDistancesToNullTransaction.col(j), false); } } // -------------------------------------------------------------------------- void IncrementalKMeans::initClustersCounters() { m_clustersCounts = cv::Mat::zeros(1, m_numClusters, cv::DataType<int>::type); m_clustersSums = cv::Mat::zeros(m_numClusters, m_dim * 8, cv::DataType<int>::type); m_clustersWeights = cv::Mat::ones(1, m_numClusters, cv::DataType<double>::type) / m_numClusters; } // -------------------------------------------------------------------------- bool IncrementalKMeans::insertOutlier(const int& transactionIndex, const int& clusterIndex, const double& distanceToCluster) { // Retrieve list of outliers for the given cluster index // std::vector<std::pair<int, double>> clusterOutliers = m_outliers.at(clusterIndex); // Insert item into the list of outliers for the given cluster index std::pair<int, double> item(transactionIndex, distanceToCluster); // Limit size of outliers list if(m_outliers.at(clusterIndex).size() < MAX_OUTLIERS) { std::vector<std::pair<int, double>>::iterator position = std::upper_bound(m_outliers.at(clusterIndex).begin(), m_outliers.at(clusterIndex).end(), item, [](const std::pair<int, double>& lhs, const std::pair<int, double>& rhs) {return lhs.second >= rhs.second;}); m_outliers.at(clusterIndex).insert(position, item); return true; } else { if (item.second >= m_outliers.at(clusterIndex).front().second) { m_outliers.at(clusterIndex).insert(m_outliers.at(clusterIndex).begin(), item); return true; } else { return false; } } } // -------------------------------------------------------------------------- void IncrementalKMeans::handleEmptyClusters() { for (unsigned int j = 0; j < m_numClusters; ++j) { bool allEmpty = true; for (unsigned int i = 0; i < m_outliers.size(); ++i) { allEmpty = allEmpty && m_outliers.at(i).empty(); } if (allEmpty) { break; } // if Wj = 0 then Cj <- to if (m_clustersWeights.at<double>(0, j) != 0) { continue; } // Get an outlier transaction assigned to a cluster different than the jth cluster int outlierTransactionIndex; for (unsigned int i = 0; i < m_outliers.size(); ++i) { if (i !=j && !m_outliers.at(i).empty()) { outlierTransactionIndex = m_outliers.at(i).back().first; m_outliers.at(i).pop_back(); } } cv::Mat outlierTransaction = m_dataset.row(outlierTransactionIndex); // Assign outlier transaction to the jth cluster // Mj <- Mj + ti sparseSum(outlierTransaction, j); // Nj <- Nj + 1 m_clustersCounts.col(j) += 1; } } // -------------------------------------------------------------------------- void IncrementalKMeans::findNearestNeighbor(cv::Mat transaction, int& clusterIndex, double& distanceToCluster) { clusterIndex = 0; distanceToCluster = std::numeric_limits<double>::max(); double tempDistanceToCluster; uchar byte = 0; for (int j = 0; j < m_centroids.rows; ++j) { tempDistanceToCluster = m_clusterDistancesToNullTransaction.at<double>(0, j); for (int l = 0; l < m_centroids.cols; l++) { if ((l % 8) == 0) { byte = *(transaction.col((int) l / 8).data); } int bit = ((int) ((byte >> (7 - (l % 8))) % 2)); // Compute only differences for non-null dimensions if (bit == 1) { tempDistanceToCluster += pow(bit - m_centroids.at<double>(j, l), 2) - pow(m_centroids.at<double>(j, l), 2); } } if (tempDistanceToCluster < distanceToCluster) { clusterIndex = j; distanceToCluster = tempDistanceToCluster; } } } // -------------------------------------------------------------------------- void IncrementalKMeans::sparseSum(cv::Mat transaction, const int& rowIndex) { uchar byte = 0; for (int l = 0; l < m_clustersSums.cols; l++) { if ((l % 8) == 0) { byte = *(transaction.col((int) l / 8).data); } m_clustersSums.at<int>(rowIndex, l) += ((int) ((byte >> (7 - (l % 8))) % 2)); } } // -------------------------------------------------------------------------- void IncrementalKMeans::sparseSubtraction(cv::Mat transaction, const int& rowIndex) { uchar byte = 0; for (int l = 0; l < m_clustersSums.cols; l++) { if ((l % 8) == 0) { byte = *(transaction.col((int) l / 8).data); } m_clustersSums.at<int>(rowIndex, l) -= ((int) ((byte >> (7 - (l % 8))) % 2)); } } } /* namespace vlr */ <commit_msg>Fix up handleEmptyClusters method<commit_after>/* * IncrementalKMeans.cpp * * Created on: May 13, 2015 * Author: andresf */ #include <IncrementalKMeans.hpp> #include <opencv2/core/core.hpp> namespace vlr { static const int MAX_OUTLIERS = 10; IncrementalKMeans::IncrementalKMeans(vlr::Mat data, const cvflann::IndexParams& params) : m_dataset(data), m_dim(data.cols), m_numDatapoints(data.rows) { // Attributes initialization m_numClusters = cvflann::get_param<int>(params, "num.clusters"); // Compute the global data set mean m_miu = cv::Mat::zeros(1, m_dim * 8, cv::DataType<double>::type); for (int i = 0; i < m_numDatapoints; ++i) { cv::Mat row = m_dataset.row(i); uchar byte = 0; for (int l = 0; l < m_miu.cols; l++) { if ((l % 8) == 0) { byte = *(row.col((int) l / 8).data); } m_miu.at<double>(0, l) += ((int) ((byte >> (7 - (l % 8))) % 2)); } } m_miu /= m_numDatapoints; // Compute the global data set standard deviations m_sigma = cv::Mat::zeros(1, m_dim * 8, cv::DataType<double>::type); for (int i = 0; i < m_numDatapoints; ++i) { cv::Mat row = m_dataset.row(i); uchar byte = 0; for (int l = 0; l < m_sigma.cols; l++) { if ((l % 8) == 0) { byte = *(row.col((int) l / 8).data); } m_sigma.at<double>(0, l) += pow(((int) ((byte >> (7 - (l % 8))) % 2)) - m_miu.at<double>(0, l), 2); } } m_sigma /= m_numDatapoints; cv::sqrt(m_sigma, m_sigma); m_centroids.create(m_numClusters, m_dim * 8, cv::DataType<double>::type); m_clustersVariances.create(m_numClusters, m_dim * 8, cv::DataType<double>::type); m_clustersWeights.create(1, m_numClusters, cv::DataType<double>::type); m_clustersSums.create(m_numClusters, m_dim * 8, cv::DataType<int>::type); m_clustersCounts.create(1, m_numClusters, cv::DataType<int>::type); m_clusterDistancesToNullTransaction.create(1, m_numClusters, cv::DataType<double>::type); m_outliers.resize(m_numClusters); } // -------------------------------------------------------------------------- IncrementalKMeans::~IncrementalKMeans() { } // -------------------------------------------------------------------------- void IncrementalKMeans::build() { // Mean-based initialization initCentroids(); // Compute distances between clusters centers and the null transaction preComputeDistances(); // Nj <- 0 // Mj <- 0 // Wj <- 1/k initClustersCounters(); double L = sqrt(m_numDatapoints); int clusterIndex; double distanceToCluster; for (int i = 0; i < m_numDatapoints; ++i) { cv::Mat transaction = m_dataset.row(i); // Cluster assignment // j = NN(ti) findNearestNeighbor(transaction, clusterIndex, distanceToCluster); // Insert transaction in the list of outliers bool isOutlier = insertOutlier(i, clusterIndex, distanceToCluster); // If the transaction is not an outlier then assign it to the jth cluster if (isOutlier) { // If the transaction is an outlier and is the farthest one on the jth cluster // then pop and assign the nearest outlier on the jth cluster if (m_outliers.at(clusterIndex).size() > MAX_OUTLIERS) { transaction = m_dataset.row(m_outliers.at(clusterIndex).back().first); m_outliers.at(clusterIndex).pop_back(); // Mj <- Mj + ti sparseSum(transaction, clusterIndex); // Nj <- Nj + 1 m_clustersCounts.col(clusterIndex) += 1; } } else { // Mj <- Mj + ti sparseSum(transaction, clusterIndex); // Nj <- Nj + 1 m_clustersCounts.col(clusterIndex) += 1; } // Update clusters centers every L times if (i % ((int) (m_numDatapoints / L)) == 0) { // Re-compute clusters centers computeCentroids(i); // Compute distances between clusters centers and the null transaction preComputeDistances(); // Re-seeding handleEmptyClusters(); } } } // -------------------------------------------------------------------------- void IncrementalKMeans::save(const std::string& filename) const { // TODO Implement this method } // -------------------------------------------------------------------------- void IncrementalKMeans::load(const std::string& filename) { // TODO Implement this method } // -------------------------------------------------------------------------- void IncrementalKMeans::initCentroids() { for (int j = 0; j < m_numClusters; ++j) { // Cj <- miu +/-sigma*r/d double r = (double) rand() / RAND_MAX; if (rand() % 2 == 0) { m_centroids.row(j) = (m_miu + m_sigma * r / (m_dim * 8)); } else { m_centroids.row(j) = (m_miu - m_sigma * r / (m_dim * 8)); } } } // -------------------------------------------------------------------------- void IncrementalKMeans::computeCentroids(const int& i) { for (int j = 0; j < m_numClusters; ++j) { // Cj <- Mj/Nj m_clustersSums.row(j).convertTo(m_centroids.row(j), cv::DataType<double>::type); m_centroids.row(j) = m_centroids.row(j) / ((double) m_clustersCounts.at<int>(0, j)); // Rj <- Cj - diag(Cj*Cj') cv::Mat clusterVariance(m_dim * 8, m_dim * 8, cv::DataType<double>::type); cv::mulTransposed(m_centroids.row(j), clusterVariance, true); m_clustersVariances.row(j) = m_centroids.row(j) - clusterVariance.diag(0).t(); // Wj <- Nj/i m_clustersWeights.col(j) = ((double) m_clustersCounts.at<int>(0, j)) / ((double) i); } } // -------------------------------------------------------------------------- void IncrementalKMeans::preComputeDistances() { cv::Mat nullTransaction = cv::Mat::zeros(1, m_dim * 8, cv::DataType<double>::type); for (int j = 0; j < m_numClusters; ++j) { cv::mulTransposed(nullTransaction - m_centroids.row(j), m_clusterDistancesToNullTransaction.col(j), false); } } // -------------------------------------------------------------------------- void IncrementalKMeans::initClustersCounters() { m_clustersCounts = cv::Mat::zeros(1, m_numClusters, cv::DataType<int>::type); m_clustersSums = cv::Mat::zeros(m_numClusters, m_dim * 8, cv::DataType<int>::type); m_clustersWeights = cv::Mat::ones(1, m_numClusters, cv::DataType<double>::type) / m_numClusters; } // -------------------------------------------------------------------------- bool IncrementalKMeans::insertOutlier(const int& transactionIndex, const int& clusterIndex, const double& distanceToCluster) { // Retrieve list of outliers for the given cluster index // std::vector<std::pair<int, double>> clusterOutliers = m_outliers.at(clusterIndex); // Insert item into the list of outliers for the given cluster index std::pair<int, double> item(transactionIndex, distanceToCluster); // Limit size of outliers list if(m_outliers.at(clusterIndex).size() < MAX_OUTLIERS) { std::vector<std::pair<int, double>>::iterator position = std::upper_bound(m_outliers.at(clusterIndex).begin(), m_outliers.at(clusterIndex).end(), item, [](const std::pair<int, double>& lhs, const std::pair<int, double>& rhs) {return lhs.second >= rhs.second;}); m_outliers.at(clusterIndex).insert(position, item); return true; } else { if (item.second >= m_outliers.at(clusterIndex).front().second) { m_outliers.at(clusterIndex).insert(m_outliers.at(clusterIndex).begin(), item); return true; } else { return false; } } } // -------------------------------------------------------------------------- void IncrementalKMeans::handleEmptyClusters() { for (unsigned int j = 0; j < m_numClusters; ++j) { bool allEmpty = true; for (unsigned int i = 0; i < m_outliers.size(); ++i) { allEmpty = allEmpty && m_outliers.at(i).empty(); } if (allEmpty) { break; } // if Wj = 0 then Cj <- to if (m_clustersWeights.at<double>(0, j) != 0) { continue; } // Get an outlier transaction assigned to a cluster different than the jth cluster int outlierTransactionIndex; for (unsigned int i = 0; i < m_outliers.size(); ++i) { if (i !=j && !m_outliers.at(i).empty()) { outlierTransactionIndex = m_outliers.at(i).front().first; m_outliers.at(i).pop_back(); break; } } cv::Mat outlierTransaction = m_dataset.row(outlierTransactionIndex); // Assign outlier transaction to the jth cluster // Mj <- Mj + ti sparseSum(outlierTransaction, j); // Nj <- Nj + 1 m_clustersCounts.col(j) += 1; } } // -------------------------------------------------------------------------- void IncrementalKMeans::findNearestNeighbor(cv::Mat transaction, int& clusterIndex, double& distanceToCluster) { clusterIndex = 0; distanceToCluster = std::numeric_limits<double>::max(); double tempDistanceToCluster; uchar byte = 0; for (int j = 0; j < m_centroids.rows; ++j) { tempDistanceToCluster = m_clusterDistancesToNullTransaction.at<double>(0, j); for (int l = 0; l < m_centroids.cols; l++) { if ((l % 8) == 0) { byte = *(transaction.col((int) l / 8).data); } int bit = ((int) ((byte >> (7 - (l % 8))) % 2)); // Compute only differences for non-null dimensions if (bit == 1) { tempDistanceToCluster += pow(bit - m_centroids.at<double>(j, l), 2) - pow(m_centroids.at<double>(j, l), 2); } } if (tempDistanceToCluster < distanceToCluster) { clusterIndex = j; distanceToCluster = tempDistanceToCluster; } } } // -------------------------------------------------------------------------- void IncrementalKMeans::sparseSum(cv::Mat transaction, const int& rowIndex) { uchar byte = 0; for (int l = 0; l < m_clustersSums.cols; l++) { if ((l % 8) == 0) { byte = *(transaction.col((int) l / 8).data); } m_clustersSums.at<int>(rowIndex, l) += ((int) ((byte >> (7 - (l % 8))) % 2)); } } // -------------------------------------------------------------------------- void IncrementalKMeans::sparseSubtraction(cv::Mat transaction, const int& rowIndex) { uchar byte = 0; for (int l = 0; l < m_clustersSums.cols; l++) { if ((l % 8) == 0) { byte = *(transaction.col((int) l / 8).data); } m_clustersSums.at<int>(rowIndex, l) -= ((int) ((byte >> (7 - (l % 8))) % 2)); } } } /* namespace vlr */ <|endoftext|>
<commit_before>// // snowflake.hpp // aegis.cpp // // Copyright (c) 2017 Sara W (sara at xandium dot net) // // This file is part of aegis.cpp . // // 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. #pragma once #include "aegis/config.hpp" namespace aegiscpp { /**\todo Needs documentation */ class snowflake { public: snowflake() : snowflake_id(0) {} snowflake(uint64_t _snowflake) : snowflake_id(_snowflake) {} operator uint64_t() const { return snowflake_id; } constexpr std::tuple<uint64_t, uint8_t, uint8_t, uint16_t> get_all() { return { get_timestamp(), get_worker(), get_process(), get_count() }; }; constexpr uint16_t get_count() { return static_cast<int16_t>(snowflake_id & _countMask); }; constexpr uint8_t get_process() { return static_cast<int8_t>(snowflake_id & _workerMask) >> 12; }; constexpr uint8_t get_worker() { return static_cast<int8_t>(snowflake_id & _workerMask) >> 17; }; constexpr uint64_t get_timestamp() { return (snowflake_id & _timestampMask) >> 22; }; static constexpr std::tuple<uint64_t, uint8_t, uint8_t, uint16_t> c_get_all(uint64_t snowflake) { return { c_get_timestamp(snowflake), c_get_worker(snowflake), c_get_process(snowflake), c_get_count(snowflake) }; }; static constexpr uint16_t c_get_count(uint64_t snowflake) { return static_cast<int16_t>(snowflake & _countMask); }; static constexpr int8_t c_get_process(uint64_t snowflake) { return static_cast<int8_t>(snowflake & _workerMask) >> 12; }; static constexpr uint8_t c_get_worker(uint64_t snowflake) { return static_cast<int8_t>(snowflake & _workerMask) >> 17; }; static constexpr uint64_t c_get_timestamp(uint64_t snowflake) { return (snowflake & _timestampMask) >> 22; }; constexpr uint64_t get_time() { return get_timestamp() + _discordEpoch; }; static constexpr uint64_t c_get_time(uint64_t snowflake) { return c_get_timestamp(snowflake) + _discordEpoch; }; private: uint64_t snowflake_id; static constexpr uint64_t _countMask = 0x0000000000000FFFL; static constexpr uint64_t _processMask = 0x000000000001F000L; static constexpr uint64_t _workerMask = 0x00000000003E0000L; static constexpr uint64_t _timestampMask = 0xFFFFFFFFFFC00000L; static constexpr uint64_t _discordEpoch = 1420070400000; }; /**\todo Needs documentation */ inline void from_json(const nlohmann::json& j, snowflake& s) { if (j.is_string()) s = std::stoll(j.get<std::string>()); else if (j.is_number()) s = j.get<int64_t>(); } /**\todo Needs documentation */ inline void to_json(nlohmann::json& j, const snowflake& s) { j = json{ static_cast<int64_t>(s) }; } } <commit_msg>Snowflake adjustments<commit_after>// // snowflake.hpp // aegis.cpp // // Copyright (c) 2017 Sara W (sara at xandium dot net) // // This file is part of aegis.cpp . // // 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. #pragma once #include "aegis/config.hpp" namespace aegiscpp { /**\todo Needs documentation */ class snowflake { public: snowflake() : snowflake_id(0) {} snowflake(int64_t _snowflake) : snowflake_id(_snowflake) {} operator int64_t() const noexcept { return snowflake_id; } operator std::string() const noexcept { return std::to_string(snowflake_id); } constexpr int64_t get() const noexcept { return snowflake_id; }; constexpr std::tuple<int64_t, int8_t, int8_t, int16_t> get_all() const noexcept { return { get_timestamp(), get_worker(), get_process(), get_count() }; }; constexpr int16_t get_count() const noexcept { return static_cast<int16_t>(snowflake_id & _countMask); }; constexpr int8_t get_process() const noexcept { return static_cast<int8_t>((snowflake_id & _workerMask) >> 12); }; constexpr int8_t get_worker() const noexcept { return static_cast<int8_t>((snowflake_id & _workerMask) >> 17); }; constexpr int64_t get_timestamp() const noexcept { return (snowflake_id & _timestampMask) >> 22; }; static constexpr std::tuple<int64_t, int8_t, int8_t, int16_t> c_get_all(int64_t snowflake) { return { c_get_timestamp(snowflake), c_get_worker(snowflake), c_get_process(snowflake), c_get_count(snowflake) }; }; static constexpr int16_t c_get_count(int64_t snowflake) { return static_cast<int16_t>(snowflake & _countMask); }; static constexpr int8_t c_get_process(int64_t snowflake) { return static_cast<int8_t>((snowflake & _workerMask) >> 12); }; static constexpr int8_t c_get_worker(int64_t snowflake) { return static_cast<int8_t>((snowflake & _workerMask) >> 17); }; static constexpr int64_t c_get_timestamp(int64_t snowflake) { return (snowflake & _timestampMask) >> 22; }; constexpr int64_t get_time() const noexcept { return get_timestamp() + _discordEpoch; }; static constexpr int64_t c_get_time(int64_t snowflake) { return c_get_timestamp(snowflake) + _discordEpoch; }; private: uint64_t snowflake_id; static constexpr uint64_t _countMask = 0x0000000000000FFFL; static constexpr uint64_t _processMask = 0x000000000001F000L; static constexpr uint64_t _workerMask = 0x00000000003E0000L; static constexpr uint64_t _timestampMask = 0xFFFFFFFFFFC00000L; static constexpr uint64_t _discordEpoch = 1420070400000; }; /**\todo Needs documentation */ inline void from_json(const nlohmann::json& j, snowflake& s) { if (j.is_string()) s = std::stoll(j.get<std::string>()); else if (j.is_number()) s = j.get<int64_t>(); } /**\todo Needs documentation */ inline void to_json(nlohmann::json& j, const snowflake& s) { j = nlohmann::json{ static_cast<int64_t>(s) }; } } <|endoftext|>
<commit_before>#ifndef AMGCL_VALUE_TYPE_STATIC_MATRIX_HPP #define AMGCL_VALUE_TYPE_STATIC_MATRIX_HPP /* The MIT License Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.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. */ /** * \file amgcl/value_type/static_matrix.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Enable statically sized matrices as value types. */ #include <boost/array.hpp> #include <boost/type_traits.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/storage.hpp> #include <boost/numeric/ublas/lu.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/value_type/interface.hpp> namespace amgcl { template <typename T, int N, int M> struct static_matrix { boost::array<T, N * M> buf; T operator()(int i, int j) const { return buf[i * M + j]; } T& operator()(int i, int j) { return buf[i * M + j]; } T operator()(int i) const { return buf[i]; } T& operator()(int i) { return buf[i]; } const T* data() const { return buf.data(); } T* data() { return buf.data(); } const static_matrix& operator+=(const static_matrix &y) { for(int i = 0; i < N * M; ++i) buf[i] += y.buf[i]; return *this; } const static_matrix& operator-=(const static_matrix &y) { for(int i = 0; i < N * M; ++i) buf[i] -= y.buf[i]; return *this; } const static_matrix& operator*=(T c) { for(int i = 0; i < N * M; ++i) buf[i] *= c; return *this; } friend static_matrix operator+(static_matrix x, const static_matrix &y) { return x += y; } friend static_matrix operator-(static_matrix x, const static_matrix &y) { return x -= y; } friend static_matrix operator*(T a, static_matrix x) { return x *= a; } friend static_matrix operator-(static_matrix x) { for(int i = 0; i < N * M; ++i) x.buf[i] = -x.buf[i]; return x; } friend bool operator<(const static_matrix &x, const static_matrix &y) { T xtrace = math::zero<T>(); T ytrace = math::zero<T>(); const int K = N < M ? N : M; for(int i = 0; i < K; ++i) { xtrace += x(i,i); ytrace += y(i,i); } return xtrace < ytrace; } }; template <typename T, int N, int K, int M> static_matrix<T, N, M> operator*( const static_matrix<T, N, K> &a, const static_matrix<T, K, M> &b ) { static_matrix<T, N, M> c; for(int i = 0; i < N; ++i) { for(int j = 0; j < M; ++j) { T sum = math::zero<T>(); for(int k = 0; k < K; ++k) sum += a(i,k) * b(k,j); c(i,j) = sum; } } return c; } template <class T> struct is_static_matrix : boost::false_type {}; template <class T, int N, int M> struct is_static_matrix< static_matrix<T, N, M> > : boost::true_type {}; namespace backend { /// Enable static matrix as a value-type. template <typename T, int N, int M> struct is_builtin_vector< std::vector<static_matrix<T, N, M> > > : boost::true_type {}; } // namespace backend namespace math { /// Scalar type of a non-scalar type. template <class T, int N, int M> struct scalar_of< static_matrix<T, N, M> > { typedef T type; }; /// RHS type corresponding to a non-scalar type. template <class T, int N> struct rhs_of< static_matrix<T, N, N> > { typedef static_matrix<T, N, 1> type; }; /// Specialization of conjugate transpose for static matrices. template <typename T, int N, int M> struct adjoint_impl< static_matrix<T, N, M> > { typedef static_matrix<T, M, N> return_type; static static_matrix<T, M, N> get(const static_matrix<T, N, M> &x) { static_matrix<T, M, N> y; for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j) y(j,i) = x(i,j); return y; } }; /// Inner-product result of two static vectors. template <class T, int N> struct inner_product_impl< static_matrix<T, N, 1> > { typedef T return_type; static T get(const static_matrix<T, N, 1> &x, const static_matrix<T, N, 1> &y) { T sum = math::zero<T>(); for(int i = 0; i < N; ++i) sum += x(i) * y(i); return sum; } }; /// Inner-product result of two static matrices. template <class T, int N, int M> struct inner_product_impl< static_matrix<T, N, M> > { typedef static_matrix<T, M, M> return_type; static return_type get(const static_matrix<T, N, M> &x, const static_matrix<T, N, M> &y) { static_matrix<T, M, M> p; for(int i = 0; i < M; ++i) { for(int j = 0; j < M; ++j) { T sum = math::zero<T>(); for(int k = 0; k < N; ++k) sum += x(k,i) * y(k,j); p(i,j) = sum; } } return p; } }; /// Specialization of element norm for static matrices. template <typename T, int N, int M> struct norm_impl< static_matrix<T, N, M> > { static T get(const static_matrix<T, N, M> &x) { T s = math::zero<T>(); for(int i = 0; i < N * M; ++i) s += x(i) * x(i); return sqrt(s); } }; /// Specialization of zero element for static matrices. template <typename T, int N, int M> struct zero_impl< static_matrix<T, N, M> > { static static_matrix<T, N, M> get() { static_matrix<T, N, M> z; for(int i = 0; i < N * M; ++i) z(i) = math::zero<T>(); return z; } }; /// Specialization of zero element for static matrices. template <typename T, int N, int M> struct is_zero_impl< static_matrix<T, N, M> > { static bool get(const static_matrix<T, N, M> &x) { for(int i = 0; i < N * M; ++i) if (!math::is_zero(x(i))) return false; return true; } }; /// Specialization of identity for static matrices. template <typename T, int N> struct identity_impl< static_matrix<T, N, N> > { static static_matrix<T, N, N> get() { static_matrix<T, N, N> I; for(int i = 0; i < N; ++i) for(int j = 0; j < N; ++j) I(i,j) = static_cast<T>(i == j); return I; } }; /// Specialization of constant for static matrices. template <typename T, int N, int M> struct constant_impl< static_matrix<T, N, M> > { static static_matrix<T, N, M> get(T c) { static_matrix<T, N, M> C; for(int i = 0; i < N * M; ++i) C(i) = c; return C; } }; /// Specialization of inversion for static matrices. template <typename T, int N> struct inverse_impl< static_matrix<T, N, N> > { static static_matrix<T, N, N> get(static_matrix<T, N, N> A) { // Perform LU-factorization of A in-place for(int k = 0; k < N; ++k) { T d = A(k,k); assert(!math::is_zero(d)); for(int i = k+1; i < N; ++i) { A(i,k) /= d; for(int j = k+1; j < N; ++j) A(i,j) -= A(i,k) * A(k,j); } } // Invert identity matrix in-place to get the solution. static_matrix<T, N, N> y; for(int k = 0; k < N; ++k) { // Lower triangular solve: for(int i = 0; i < N; ++i) { T b = static_cast<T>(i == k); for(int j = 0; j < i; ++j) b -= A(i,j) * y(k,j); y(k,i) = b; } // Upper triangular solve: for(int i = N; i --> 0; ) { for(int j = i+1; j < N; ++j) y(k,i) -= A(i,j) * y(k,j); y(k,i) /= A(i,i); } } return y; } }; } // namespace math namespace relaxation { template <class Backend> struct spai1; } //namespace relaxation namespace backend { template <class Backend> struct relaxation_is_supported< Backend, relaxation::spai1, typename boost::enable_if< typename amgcl::is_static_matrix< typename Backend::value_type >::type >::type > : boost::false_type {}; } // namespace backend } // namespace amgcl #endif <commit_msg>Improve implementation of static matrix-matrix product<commit_after>#ifndef AMGCL_VALUE_TYPE_STATIC_MATRIX_HPP #define AMGCL_VALUE_TYPE_STATIC_MATRIX_HPP /* The MIT License Copyright (c) 2012-2015 Denis Demidov <dennis.demidov@gmail.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. */ /** * \file amgcl/value_type/static_matrix.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Enable statically sized matrices as value types. */ #include <boost/array.hpp> #include <boost/type_traits.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/storage.hpp> #include <boost/numeric/ublas/lu.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/value_type/interface.hpp> namespace amgcl { template <typename T, int N, int M> struct static_matrix { boost::array<T, N * M> buf; T operator()(int i, int j) const { return buf[i * M + j]; } T& operator()(int i, int j) { return buf[i * M + j]; } T operator()(int i) const { return buf[i]; } T& operator()(int i) { return buf[i]; } const T* data() const { return buf.data(); } T* data() { return buf.data(); } const static_matrix& operator+=(const static_matrix &y) { for(int i = 0; i < N * M; ++i) buf[i] += y.buf[i]; return *this; } const static_matrix& operator-=(const static_matrix &y) { for(int i = 0; i < N * M; ++i) buf[i] -= y.buf[i]; return *this; } const static_matrix& operator*=(T c) { for(int i = 0; i < N * M; ++i) buf[i] *= c; return *this; } friend static_matrix operator+(static_matrix x, const static_matrix &y) { return x += y; } friend static_matrix operator-(static_matrix x, const static_matrix &y) { return x -= y; } friend static_matrix operator*(T a, static_matrix x) { return x *= a; } friend static_matrix operator-(static_matrix x) { for(int i = 0; i < N * M; ++i) x.buf[i] = -x.buf[i]; return x; } friend bool operator<(const static_matrix &x, const static_matrix &y) { T xtrace = math::zero<T>(); T ytrace = math::zero<T>(); const int K = N < M ? N : M; for(int i = 0; i < K; ++i) { xtrace += x(i,i); ytrace += y(i,i); } return xtrace < ytrace; } }; template <typename T, int N, int K, int M> static_matrix<T, N, M> operator*( const static_matrix<T, N, K> &a, const static_matrix<T, K, M> &b ) { static_matrix<T, N, M> c; for(int i = 0; i < N; ++i) { for(int j = 0; j < M; ++j) c(i,j) = math::zero<T>(); for(int k = 0; k < K; ++k) { T aik = a(i,k); for(int j = 0; j < M; ++j) c(i,j) += aik * b(k,j); } } return c; } template <class T> struct is_static_matrix : boost::false_type {}; template <class T, int N, int M> struct is_static_matrix< static_matrix<T, N, M> > : boost::true_type {}; namespace backend { /// Enable static matrix as a value-type. template <typename T, int N, int M> struct is_builtin_vector< std::vector<static_matrix<T, N, M> > > : boost::true_type {}; } // namespace backend namespace math { /// Scalar type of a non-scalar type. template <class T, int N, int M> struct scalar_of< static_matrix<T, N, M> > { typedef T type; }; /// RHS type corresponding to a non-scalar type. template <class T, int N> struct rhs_of< static_matrix<T, N, N> > { typedef static_matrix<T, N, 1> type; }; /// Specialization of conjugate transpose for static matrices. template <typename T, int N, int M> struct adjoint_impl< static_matrix<T, N, M> > { typedef static_matrix<T, M, N> return_type; static static_matrix<T, M, N> get(const static_matrix<T, N, M> &x) { static_matrix<T, M, N> y; for(int i = 0; i < N; ++i) for(int j = 0; j < M; ++j) y(j,i) = x(i,j); return y; } }; /// Inner-product result of two static vectors. template <class T, int N> struct inner_product_impl< static_matrix<T, N, 1> > { typedef T return_type; static T get(const static_matrix<T, N, 1> &x, const static_matrix<T, N, 1> &y) { T sum = math::zero<T>(); for(int i = 0; i < N; ++i) sum += x(i) * y(i); return sum; } }; /// Inner-product result of two static matrices. template <class T, int N, int M> struct inner_product_impl< static_matrix<T, N, M> > { typedef static_matrix<T, M, M> return_type; static return_type get(const static_matrix<T, N, M> &x, const static_matrix<T, N, M> &y) { static_matrix<T, M, M> p; for(int i = 0; i < M; ++i) { for(int j = 0; j < M; ++j) { T sum = math::zero<T>(); for(int k = 0; k < N; ++k) sum += x(k,i) * y(k,j); p(i,j) = sum; } } return p; } }; /// Implementation of Frobenius norm for static matrices. template <typename T, int N, int M> struct norm_impl< static_matrix<T, N, M> > { static T get(const static_matrix<T, N, M> &x) { T s = math::zero<T>(); for(int i = 0; i < N * M; ++i) s += x(i) * x(i); return sqrt(s); } }; /// Specialization of zero element for static matrices. template <typename T, int N, int M> struct zero_impl< static_matrix<T, N, M> > { static static_matrix<T, N, M> get() { static_matrix<T, N, M> z; for(int i = 0; i < N * M; ++i) z(i) = math::zero<T>(); return z; } }; /// Specialization of zero element for static matrices. template <typename T, int N, int M> struct is_zero_impl< static_matrix<T, N, M> > { static bool get(const static_matrix<T, N, M> &x) { for(int i = 0; i < N * M; ++i) if (!math::is_zero(x(i))) return false; return true; } }; /// Specialization of identity for static matrices. template <typename T, int N> struct identity_impl< static_matrix<T, N, N> > { static static_matrix<T, N, N> get() { static_matrix<T, N, N> I; for(int i = 0; i < N; ++i) for(int j = 0; j < N; ++j) I(i,j) = static_cast<T>(i == j); return I; } }; /// Specialization of constant for static matrices. template <typename T, int N, int M> struct constant_impl< static_matrix<T, N, M> > { static static_matrix<T, N, M> get(T c) { static_matrix<T, N, M> C; for(int i = 0; i < N * M; ++i) C(i) = c; return C; } }; /// Specialization of inversion for static matrices. template <typename T, int N> struct inverse_impl< static_matrix<T, N, N> > { static static_matrix<T, N, N> get(static_matrix<T, N, N> A) { // Perform LU-factorization of A in-place for(int k = 0; k < N; ++k) { T d = A(k,k); assert(!math::is_zero(d)); for(int i = k+1; i < N; ++i) { A(i,k) /= d; for(int j = k+1; j < N; ++j) A(i,j) -= A(i,k) * A(k,j); } } // Invert identity matrix in-place to get the solution. static_matrix<T, N, N> y; for(int k = 0; k < N; ++k) { // Lower triangular solve: for(int i = 0; i < N; ++i) { T b = static_cast<T>(i == k); for(int j = 0; j < i; ++j) b -= A(i,j) * y(k,j); y(k,i) = b; } // Upper triangular solve: for(int i = N; i --> 0; ) { for(int j = i+1; j < N; ++j) y(k,i) -= A(i,j) * y(k,j); y(k,i) /= A(i,i); } } return y; } }; } // namespace math namespace relaxation { template <class Backend> struct spai1; } //namespace relaxation namespace backend { template <class Backend> struct relaxation_is_supported< Backend, relaxation::spai1, typename boost::enable_if< typename amgcl::is_static_matrix< typename Backend::value_type >::type >::type > : boost::false_type {}; } // namespace backend } // namespace amgcl #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_BITCOIN_HPP #define LIBBITCOIN_BITCOIN_HPP /** * @mainpage libbitcoin API dox * * @section intro_sec Introduction * * libbitcoin is a bitcoin library targeted towards high end use. * The library places a heavy focus around asychronicity. This enables a * big scope for future scalability as each component has its own * thread pool. By increasing the number of threads for that component * the library is able to scale outwards across CPU cores. This will be * vital in the future as the demands of the bitcoin network grow. * * Another core design principle is libbitcoin is not a framework, but * a toolkit. Frameworks hinder development during the latter stages of * a development cycle, enforce one style of coding and do not work well * with other frameworks. By contrast, we have gone to great pains to make * libbitcoin function as an independent set of mutual components with no * dependencies between them. * * @section overview_sec Overview * * Broadly speaking the main services in libbitcoin can be divided down * three lines. * * @subsection network Network services * * These services are concerned with the network side of things. * * - @link libbitcoin::channel channel @endlink * - @link libbitcoin::network network @endlink * - @link libbitcoin::protocol protocol @endlink * - @link libbitcoin::hosts hosts @endlink * - @link libbitcoin::handshake handshake @endlink * * @subsection supporting Supporting services * * These services utilise other services and provide additional * functionality. They can be thought of as composed services. * * - @link libbitcoin::poller poller @endlink * - @link libbitcoin::transaction_pool transaction_pool @endlink * - @link libbitcoin::session session @endlink * * @section primitive Primitive * * libbitcoin operates around primitives. Each primitive corresponds to * one of the messages in the bitcoin network protocol. * * These primitives make up the corpus of libbitcoin. * * - @link libbitcoin::version_type version_type @endlink * - @link libbitcoin::verack_type verack_type @endlink * - @link libbitcoin::address_type address_type @endlink * - @link libbitcoin::inventory_type inventory_type @endlink * - @link libbitcoin::get_data_type get_data_type @endlink * - @link libbitcoin::get_blocks_type get_blocks_type @endlink * - @link libbitcoin::transaction_type transaction_type @endlink * - @link libbitcoin::block_type block_type @endlink * - @link libbitcoin::get_address_type get_address_type @endlink * - @link libbitcoin::ping_type ping_type @endlink * - @link libbitcoin::pong_type pong_type @endlink * * @section base Foundational * * These classes provide foundational functionality that is widely used. * * - @link libbitcoin::serializer serializer @endlink / * @link libbitcoin::deserializer deserializer @endlink * - @link libbitcoin::script script @endlink * - @link libbitcoin::payment_address payment_address @endlink * - @link libbitcoin::script_number script_number @endlink * - @link libbitcoin::threadpool threadpool @endlink * * @section useful-funcs Useful functions * * In accordance with C++ principles of encapsulation, operations which * wrap or compose other operations are not provided as member functions, * but as free functions. * * This minimises intrusion of class interfaces and provides a clear * separation as a matter of API design choice. * * @subsection transaction Transaction * * - @link libbitcoin::hash_transaction hash_transaction @endlink * - @link libbitcoin::generate_merkle_root generate_merkle_root @endlink * - @link libbitcoin::previous_output_is_null previous_output_is_null @endlink * - @link libbitcoin::is_coinbase is_coinbase @endlink * - @link libbitcoin::total_output_value total_output_value @endlink * * @subsection block Block * * - @link libbitcoin::hash_block_header hash_block_header @endlink * - @link libbitcoin::block_value block_value @endlink * - @link libbitcoin::block_work block_work @endlink * - @link libbitcoin::block_locator_indices block_locator_indices @endlink * - @link libbitcoin::genesis_block genesis_block @endlink * * @subsection blockchain Blockchain * * - @link libbitcoin::fetch_block fetch_block @endlink * * @subsection format Format * * - @link libbitcoin::encode_hex pretty_hex @endlink * - @link libbitcoin::decode_hex bytes_from_pretty @endlink * - @link libbitcoin::decode_hex_digest hash_from_pretty @endlink * - @link libbitcoin::extend_data extend_data @endlink * - @link libbitcoin::to_little_endian to_little_endian @endlink * - @link libbitcoin::to_big_endian to_big_endian @endlink * - @link libbitcoin::from_little_endian from_little_endian @endlink * - @link libbitcoin::from_big_endian from_big_endian @endlink * - @link libbitcoin::btc_to_satoshi btc_to_satoshi @endlink * - @link libbitcoin::satoshi_to_btc satoshi_to_btc @endlink * * @subsection hashing Hashing * * - @link libbitcoin::short_hash ripemd160_hash @endlink * - @link libbitcoin::short_hash sha1_hash @endlink * - @link libbitcoin::hash_digest sha256_hash @endlink * - @link libbitcoin::long_hash sha512_hash @endlink * - @link libbitcoin::long_hash hmac_sha512_hash @endlink * - @link libbitcoin::hash_digest bitcoin_hash @endlink * - @link libbitcoin::short_hash bitcoin_short_hash @endlink * - @link libbitcoin::append_checksum append_checksum @endlink * - @link libbitcoin::uint32_t bitcoin_checksum @endlink * - @link libbitcoin::bool verify_checksum @endlink * * @subsection base58 Base58 * * - @link libbitcoin::encode_base58 encode_base58 @endlink * - @link libbitcoin::decode_base58 decode_base58 @endlink * * @subsection wallet Wallet * * @author Amir Taaki <amir@unsystem.net> * */ // Convenience header that includes everything // Not to be used internally. For API users. #include <bitcoin/blockchain/blockchain.hpp> #include <bitcoin/block.hpp> #include <bitcoin/constants.hpp> #include <bitcoin/define.hpp> #include <bitcoin/error.hpp> #include <bitcoin/format.hpp> #include <bitcoin/getx_responder.hpp> #include <bitcoin/network/channel.hpp> #include <bitcoin/network/handshake.hpp> #include <bitcoin/network/hosts.hpp> #include <bitcoin/network/network.hpp> #include <bitcoin/network/protocol.hpp> #include <bitcoin/network/shared_const_buffer.hpp> #include <bitcoin/poller.hpp> #include <bitcoin/primitives.hpp> #include <bitcoin/script.hpp> #include <bitcoin/session.hpp> #include <bitcoin/stealth.hpp> #include <bitcoin/threadpool.hpp> #include <bitcoin/transaction.hpp> #include <bitcoin/transaction_indexer.hpp> #include <bitcoin/transaction_pool.hpp> #include <bitcoin/types.hpp> #include <bitcoin/utility/assert.hpp> #include <bitcoin/utility/async_parallel.hpp> #include <bitcoin/utility/base58.hpp> #include <bitcoin/utility/checksum.hpp> #include <bitcoin/utility/ec_keys.hpp> #include <bitcoin/utility/hash.hpp> #include <bitcoin/utility/logger.hpp> #include <bitcoin/utility/mmfile.hpp> #include <bitcoin/utility/script_number.hpp> #include <bitcoin/utility/serializer.hpp> #include <bitcoin/utility/subscriber.hpp> #include <bitcoin/utility/weak_bind.hpp> #include <bitcoin/validate.hpp> #include <bitcoin/wallet/amount.hpp> #include <bitcoin/wallet/hd_keys.hpp> #include <bitcoin/wallet/key_formats.hpp> #include <bitcoin/wallet/mnemonic.hpp> #include <bitcoin/wallet/stealth_address.hpp> #include <bitcoin/wallet/uri.hpp> namespace bc = libbitcoin; #endif <commit_msg>Prevent boost asio warnings in MSVC.<commit_after>/* * Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_BITCOIN_HPP #define LIBBITCOIN_BITCOIN_HPP /** * @mainpage libbitcoin API dox * * @section intro_sec Introduction * * libbitcoin is a bitcoin library targeted towards high end use. * The library places a heavy focus around asychronicity. This enables a * big scope for future scalability as each component has its own * thread pool. By increasing the number of threads for that component * the library is able to scale outwards across CPU cores. This will be * vital in the future as the demands of the bitcoin network grow. * * Another core design principle is libbitcoin is not a framework, but * a toolkit. Frameworks hinder development during the latter stages of * a development cycle, enforce one style of coding and do not work well * with other frameworks. By contrast, we have gone to great pains to make * libbitcoin function as an independent set of mutual components with no * dependencies between them. * * @section overview_sec Overview * * Broadly speaking the main services in libbitcoin can be divided down * three lines. * * @subsection network Network services * * These services are concerned with the network side of things. * * - @link libbitcoin::channel channel @endlink * - @link libbitcoin::network network @endlink * - @link libbitcoin::protocol protocol @endlink * - @link libbitcoin::hosts hosts @endlink * - @link libbitcoin::handshake handshake @endlink * * @subsection supporting Supporting services * * These services utilise other services and provide additional * functionality. They can be thought of as composed services. * * - @link libbitcoin::poller poller @endlink * - @link libbitcoin::transaction_pool transaction_pool @endlink * - @link libbitcoin::session session @endlink * * @section primitive Primitive * * libbitcoin operates around primitives. Each primitive corresponds to * one of the messages in the bitcoin network protocol. * * These primitives make up the corpus of libbitcoin. * * - @link libbitcoin::version_type version_type @endlink * - @link libbitcoin::verack_type verack_type @endlink * - @link libbitcoin::address_type address_type @endlink * - @link libbitcoin::inventory_type inventory_type @endlink * - @link libbitcoin::get_data_type get_data_type @endlink * - @link libbitcoin::get_blocks_type get_blocks_type @endlink * - @link libbitcoin::transaction_type transaction_type @endlink * - @link libbitcoin::block_type block_type @endlink * - @link libbitcoin::get_address_type get_address_type @endlink * - @link libbitcoin::ping_type ping_type @endlink * - @link libbitcoin::pong_type pong_type @endlink * * @section base Foundational * * These classes provide foundational functionality that is widely used. * * - @link libbitcoin::serializer serializer @endlink / * @link libbitcoin::deserializer deserializer @endlink * - @link libbitcoin::script script @endlink * - @link libbitcoin::payment_address payment_address @endlink * - @link libbitcoin::script_number script_number @endlink * - @link libbitcoin::threadpool threadpool @endlink * * @section useful-funcs Useful functions * * In accordance with C++ principles of encapsulation, operations which * wrap or compose other operations are not provided as member functions, * but as free functions. * * This minimises intrusion of class interfaces and provides a clear * separation as a matter of API design choice. * * @subsection transaction Transaction * * - @link libbitcoin::hash_transaction hash_transaction @endlink * - @link libbitcoin::generate_merkle_root generate_merkle_root @endlink * - @link libbitcoin::previous_output_is_null previous_output_is_null @endlink * - @link libbitcoin::is_coinbase is_coinbase @endlink * - @link libbitcoin::total_output_value total_output_value @endlink * * @subsection block Block * * - @link libbitcoin::hash_block_header hash_block_header @endlink * - @link libbitcoin::block_value block_value @endlink * - @link libbitcoin::block_work block_work @endlink * - @link libbitcoin::block_locator_indices block_locator_indices @endlink * - @link libbitcoin::genesis_block genesis_block @endlink * * @subsection blockchain Blockchain * * - @link libbitcoin::fetch_block fetch_block @endlink * * @subsection format Format * * - @link libbitcoin::encode_hex pretty_hex @endlink * - @link libbitcoin::decode_hex bytes_from_pretty @endlink * - @link libbitcoin::decode_hex_digest hash_from_pretty @endlink * - @link libbitcoin::extend_data extend_data @endlink * - @link libbitcoin::to_little_endian to_little_endian @endlink * - @link libbitcoin::to_big_endian to_big_endian @endlink * - @link libbitcoin::from_little_endian from_little_endian @endlink * - @link libbitcoin::from_big_endian from_big_endian @endlink * - @link libbitcoin::btc_to_satoshi btc_to_satoshi @endlink * - @link libbitcoin::satoshi_to_btc satoshi_to_btc @endlink * * @subsection hashing Hashing * * - @link libbitcoin::short_hash ripemd160_hash @endlink * - @link libbitcoin::short_hash sha1_hash @endlink * - @link libbitcoin::hash_digest sha256_hash @endlink * - @link libbitcoin::long_hash sha512_hash @endlink * - @link libbitcoin::long_hash hmac_sha512_hash @endlink * - @link libbitcoin::hash_digest bitcoin_hash @endlink * - @link libbitcoin::short_hash bitcoin_short_hash @endlink * - @link libbitcoin::append_checksum append_checksum @endlink * - @link libbitcoin::uint32_t bitcoin_checksum @endlink * - @link libbitcoin::bool verify_checksum @endlink * * @subsection base58 Base58 * * - @link libbitcoin::encode_base58 encode_base58 @endlink * - @link libbitcoin::decode_base58 decode_base58 @endlink * * @subsection wallet Wallet * * @author Amir Taaki <amir@unsystem.net> * */ // Convenience header that includes everything // Not to be used internally. For API users. #ifdef _MSC_VER // Suppressing msvc warnings from boost that are heard to deal with // because boost/algorithm carelessly defines _SCL_SECURE_NO_WARNINGS // without first testing it. #pragma warning(push) #pragma warning(disable : 4267) #endif #include <bitcoin/blockchain/blockchain.hpp> #include <bitcoin/block.hpp> #include <bitcoin/constants.hpp> #include <bitcoin/define.hpp> #include <bitcoin/error.hpp> #include <bitcoin/format.hpp> #include <bitcoin/getx_responder.hpp> #include <bitcoin/network/channel.hpp> #include <bitcoin/network/handshake.hpp> #include <bitcoin/network/hosts.hpp> #include <bitcoin/network/network.hpp> #include <bitcoin/network/protocol.hpp> #include <bitcoin/network/shared_const_buffer.hpp> #include <bitcoin/poller.hpp> #include <bitcoin/primitives.hpp> #include <bitcoin/script.hpp> #include <bitcoin/session.hpp> #include <bitcoin/stealth.hpp> #include <bitcoin/threadpool.hpp> #include <bitcoin/transaction.hpp> #include <bitcoin/transaction_indexer.hpp> #include <bitcoin/transaction_pool.hpp> #include <bitcoin/types.hpp> #include <bitcoin/utility/assert.hpp> #include <bitcoin/utility/async_parallel.hpp> #include <bitcoin/utility/base58.hpp> #include <bitcoin/utility/checksum.hpp> #include <bitcoin/utility/ec_keys.hpp> #include <bitcoin/utility/hash.hpp> #include <bitcoin/utility/logger.hpp> #include <bitcoin/utility/mmfile.hpp> #include <bitcoin/utility/script_number.hpp> #include <bitcoin/utility/serializer.hpp> #include <bitcoin/utility/subscriber.hpp> #include <bitcoin/utility/weak_bind.hpp> #include <bitcoin/validate.hpp> #include <bitcoin/wallet/amount.hpp> #include <bitcoin/wallet/hd_keys.hpp> #include <bitcoin/wallet/key_formats.hpp> #include <bitcoin/wallet/mnemonic.hpp> #include <bitcoin/wallet/stealth_address.hpp> #include <bitcoin/wallet/uri.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif namespace bc = libbitcoin; #endif <|endoftext|>
<commit_before>#ifndef SPROUT_GRAMMAR_HEADER #define SPROUT_GRAMMAR_HEADER #include "Node.hpp" #include <rule/rules.hpp> #include <rule/Proxy.hpp> #include <rule/Shared.hpp> #include <rule/Reduce.hpp> #include <rule/Literal.hpp> #include <rule/Discard.hpp> #include <rule/Shared.hpp> #include <rule/Multiple.hpp> #include <rule/Optional.hpp> #include <rule/Predicate.hpp> #include <rule/Alternative.hpp> #include <rule/Reduce.hpp> #include <rule/Join.hpp> #include <rule/Recursive.hpp> #include <unordered_map> #include <QElapsedTimer> #include <QSet> #include <QString> #include <QChar> namespace sprout { namespace grammar { enum class TokenType { Unknown, /** * A named reference to some other rule. */ Name, /** * An ordered sequence of subrules. */ Sequence, /** * A rule to match a literal string. */ Literal, /** * An opaque rule, usually one implmeented in C++ for primitive matching. */ Opaque, /** * A rule that matches repeatedly. Analagous to the + in regular expressions. */ OneOrMore, /** * A rule that will attempt to match its subrule, but will pass regardless. */ Optional, /** * A rule that allows selection from a set of possible choices. */ Alternative, /** * A rule that implements left-recursion. This cannot be created directly in a grammar. */ Recursive, /** * A rule that discards the output, but forwards its subrule's result. In other words, * discard does not imply optional. */ Discard, // Convenience rules. These could be implemented using our primitives. Join, ZeroOrMore, // Rule types Rule, GroupRule, TokenRule }; } // namespace grammar } // namespace sprout namespace std { template<> struct hash<sprout::grammar::TokenType> { int operator()(const sprout::grammar::TokenType& type) const { return static_cast<int>(type); } }; std::ostream& operator<<(std::ostream& stream, const sprout::grammar::TokenType& type); } // namespace std namespace sprout { namespace grammar { typedef Token<TokenType, QString> GToken; typedef Node<TokenType, QString> GNode; typedef rule::Proxy<QChar, QString> GRule; template <class Type, class Value> class Grammar { public: typedef Node<Type, Value> PNode; typedef rule::Proxy<QChar, PNode> PRule; private: typedef QHash<QString, rule::Shared<GRule>> RulesMap; QHash<QString, rule::Shared<PRule>> _rules; rule::Proxy<QChar, GNode> _grammarParser; QHash<QString, GNode> _parsedRules; rule::Proxy<QChar, GNode>& grammarParser() { if (!_grammarParser) { _grammarParser = createGrammarParser(); } return _grammarParser; } rule::Proxy<QChar, GNode> createGrammarParser(); public: Grammar() { _rules["alpha"] = rule::Proxy<QChar, PNode>([](Cursor<QChar>& iter, Result<PNode>& result) { if (iter && (*iter).isLetter()) { result << PNode("", *iter++); return true; } return false; }); _rules["alnum"] = rule::Proxy<QChar, PNode>([](Cursor<QChar>& iter, Result<PNode>& result) { if (iter && (*iter).isLetterOrNumber()) { result << PNode("", *iter++); return true; } return false; }); _rules["string"] = rule::convert<PNode>( rule::wrap<QChar, QString>(&rule::parseQuotedString), [](QString& value) { return PNode("string", value); } ); _rules["number"] = rule::convert<PNode>( rule::wrap<QChar, double>(&rule::parseFloating), [](const float& value) { return PNode("number", QString::number(value)); } ); } rule::Proxy<QChar, PNode> buildRule(const GNode& node, const TokenType& ruleType) { bool excludeWhitespace = ruleType != TokenType::TokenRule; auto ws = rule::discard(rule::optional(rule::multiple(rule::proxyAlternative<QChar, QString>( rule::whitespace<QString>(), rule::lineComment("--") )))); switch (node.type()) { case TokenType::Sequence: { rule::ProxySequence<QChar, PNode> rule; for (auto child : node.children()) { auto childRule = buildRule(child, ruleType); if (child.type() == TokenType::Literal) { rule << discard(childRule); } else { rule << childRule; } if (excludeWhitespace) { rule << ws; } } if (ruleType == TokenType::TokenRule) { return rule::reduce<PNode>( rule, [](Result<PNode>& dest, Result<PNode>& src) { QString cumulative; while (src) { cumulative += src->value(); ++src; } dest.insert(PNode("", cumulative)); } ); } return rule; } case TokenType::Recursive: { rule::Proxy<QChar, PNode> terminal = buildRule(node[0], ruleType); if (excludeWhitespace) { terminal = rule::proxySequence<QChar, PNode>( terminal, ws ); } return rule::recursive( terminal, buildRule(node[1], ruleType), [node](Result<PNode>& result) { PNode recursiveNode(node.value()); while (result) { recursiveNode.insert(*result++); } result.clear(); result.insert(recursiveNode); } ); } case TokenType::Alternative: { rule::ProxyAlternative<QChar, PNode> rule; for (auto child : node.children()) { rule << buildRule(child, ruleType); } return rule; } case TokenType::Join: { auto content = buildRule(node[0], ruleType); auto separator = buildRule(node[1], ruleType); if (node[1].type() == TokenType::Literal) { separator = discard(separator); } if (excludeWhitespace) { content = rule::proxySequence<QChar, PNode>(content, ws); separator = rule::proxySequence<QChar, PNode>(separator, ws); } return rule::join(content, separator); } case TokenType::ZeroOrMore: { return rule::optional(rule::multiple(buildRule(node[0], ruleType))); } case TokenType::Optional: { return rule::optional(buildRule(node[0], ruleType)); } case TokenType::Discard: { return rule::discard(buildRule(node[0], ruleType)); } case TokenType::OneOrMore: { return rule::multiple(buildRule(node[0], ruleType)); } case TokenType::Opaque: case TokenType::Name: { return _rules[node.value()]; } case TokenType::Literal: { return rule::OrderedLiteral<QChar, PNode>(node.value(), PNode("", node.value())); } default: { std::stringstream str; str << "I don't know how to build a " << node.type() << " rule"; throw std::runtime_error(str.str()); } } } void readGrammar(Cursor<QChar>& cursor) { Result<GNode> nodes; QElapsedTimer timer; timer.start(); auto parseSuccessful = grammarParser()(cursor, nodes); std::cout << "Parsing completed in " << timer.nsecsElapsed() << " ns\n"; if (!parseSuccessful) { throw std::runtime_error("Failed to parse grammar. :("); } for (GNode& node : nodes) { _parsedRules[node.value()] = node; } } void build() { for (GNode& node : _parsedRules.values()) { _rules[node.value()] = rule::reduce<PNode>( buildRule(node[0], node.type()), [node](Result<PNode>& dest, Result<PNode>& src) { switch (node.type()) { case TokenType::GroupRule: dest.insert(src); break; case TokenType::TokenRule: if (src.size() == 1 && src[0].type() == "") { src[0].setType(node.value()); dest << src[0]; break; } // Otherwise, fall through case TokenType::Rule: { if (node[0].type() == TokenType::Recursive) { // Recursive rules already create a group node, so don't double-nest it dest.insert(src); break; } PNode rv(node.value()); while (src) { rv.insert(*src++); } dest << rv; break; } default: throw std::logic_error("Unexpected rule type"); } } ); } } rule::Shared<PRule> operator[](const char* name) { return _rules[name]; } decltype(_parsedRules)& parsedRules() { return _parsedRules; } typename decltype(_parsedRules)::iterator begin() { return _parsedRules.begin(); } typename decltype(_parsedRules)::iterator end() { return _parsedRules.end(); } }; template <class Type, class Value> rule::Proxy<QChar, GNode> Grammar<Type, Value>::createGrammarParser() { auto whitespace = rule::multiple(rule::proxyAlternative<QChar, QString>( rule::whitespace<QString>(), rule::lineComment("#") )); auto ws = rule::discard(rule::optional(whitespace)); auto name = rule::convert<GNode>( rule::aggregate<QString>( rule::multiple(rule::simplePredicate<QChar>([](const QChar& input) { return input.isLetter() || input == '_'; })), [](QString& target, const QChar& c) { target += c; } ), [this](QString& value) { if (_rules.contains(value)) { return GNode(TokenType::Opaque, value); } return GNode(TokenType::Name, value); } ); auto literal = rule::convert<GNode>( rule::wrap<QChar, QString>(&rule::parseQuotedString), [](QString& value) { return GNode(TokenType::Literal, value); } ); auto expression = rule::shared(rule::proxyAlternative<QChar, GNode>()); auto singleExpression = rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::optional(rule::OrderedLiteral<QChar, GNode>("-", TokenType::Discard)), ws, rule::proxyAlternative<QChar, GNode>( literal, name, rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::discard(rule::OrderedLiteral<QChar, GNode>("{")), ws, expression, expression, ws, rule::discard(rule::OrderedLiteral<QChar, GNode>("}")), ws ), [](Result<GNode>& dest, Result<GNode>& src) { GNode joinNode(TokenType::Join); while (src) { joinNode.insert(*src++); } dest.insert(joinNode); } ), rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::discard(rule::OrderedLiteral<QChar, GNode>("(")), ws, rule::multiple(expression), ws, rule::discard(rule::OrderedLiteral<QChar, GNode>(")")), ws ), [](Result<GNode>& dest, Result<GNode>& src) { GNode parenNode(TokenType::Sequence); while (src) { parenNode.insert(*src++); } dest.insert(parenNode); } ) ), ws, rule::optional(rule::proxyAlternative<QChar, GNode>( rule::OrderedLiteral<QChar, GNode>("*", TokenType::ZeroOrMore), rule::OrderedLiteral<QChar, GNode>("+", TokenType::OneOrMore), rule::OrderedLiteral<QChar, GNode>("?", TokenType::Optional) )), ws ), [](Result<GNode>& results, Result<GNode>& src) { if (src[0].type() == TokenType::Discard) { GNode discardNode(TokenType::Discard); if (src.size() == 3) { GNode node(src[2].type()); node.insert(src[1]); discardNode.insert(node); } else { discardNode.insert(src[1]); } results.insert(discardNode); } else if (src.size() == 2) { GNode node(src[1].type()); node.insert(src[0]); results.insert(node); } else { results.insert(src); } } ); expression << rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::join<QChar, GNode>( rule::proxySequence<QChar, GNode>( singleExpression, ws ), rule::discard(rule::proxySequence<QChar, GNode>( rule::discard(rule::OrderedLiteral<QChar, QString>("|")), ws )) ), ws ), [](Result<GNode>& dest, Result<GNode>& src) { if (src.size() > 1) { dest.insert(GNode(TokenType::Alternative, src.data())); } else { dest.insert(*src); } } ); auto rule = rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::proxyAlternative<QChar, GNode>( rule::OrderedLiteral<QChar, GNode>("Rule", TokenType::Rule), rule::OrderedLiteral<QChar, GNode>("Token", TokenType::TokenRule), rule::OrderedLiteral<QChar, GNode>("Group", TokenType::GroupRule) ), ws, name, ws, rule::discard(rule::OrderedLiteral<QChar, QString>("=")), ws, rule::multiple(expression), ws, rule::discard(rule::OrderedLiteral<QChar, QString>(";")), ws ), [](Result<GNode>& results, Result<GNode>& subresults) { GNode rule = *subresults++; rule.setValue(subresults->value()); ++subresults; GNode sequence(TokenType::Sequence); while (subresults) { sequence.insert(*subresults++); } rule.insert(sequence); results << rule; } ); return rule::proxySequence<QChar, GNode>( ws, rule::multiple(rule), rule::end<QChar, GNode>() ); } } // namespace grammar } // namespace sprout #endif // SPROUT_GRAMMAR_HEADER // vim: set ts=4 sw=4 : <commit_msg>Always create the grammar parser<commit_after>#ifndef SPROUT_GRAMMAR_HEADER #define SPROUT_GRAMMAR_HEADER #include "Node.hpp" #include <rule/rules.hpp> #include <rule/Proxy.hpp> #include <rule/Shared.hpp> #include <rule/Reduce.hpp> #include <rule/Literal.hpp> #include <rule/Discard.hpp> #include <rule/Shared.hpp> #include <rule/Multiple.hpp> #include <rule/Optional.hpp> #include <rule/Predicate.hpp> #include <rule/Alternative.hpp> #include <rule/Reduce.hpp> #include <rule/Join.hpp> #include <rule/Recursive.hpp> #include <unordered_map> #include <QElapsedTimer> #include <QSet> #include <QString> #include <QChar> namespace sprout { namespace grammar { enum class TokenType { Unknown, /** * A named reference to some other rule. */ Name, /** * An ordered sequence of subrules. */ Sequence, /** * A rule to match a literal string. */ Literal, /** * An opaque rule, usually one implmeented in C++ for primitive matching. */ Opaque, /** * A rule that matches repeatedly. Analagous to the + in regular expressions. */ OneOrMore, /** * A rule that will attempt to match its subrule, but will pass regardless. */ Optional, /** * A rule that allows selection from a set of possible choices. */ Alternative, /** * A rule that implements left-recursion. This cannot be created directly in a grammar. */ Recursive, /** * A rule that discards the output, but forwards its subrule's result. In other words, * discard does not imply optional. */ Discard, // Convenience rules. These could be implemented using our primitives. Join, ZeroOrMore, // Rule types Rule, GroupRule, TokenRule }; } // namespace grammar } // namespace sprout namespace std { template<> struct hash<sprout::grammar::TokenType> { int operator()(const sprout::grammar::TokenType& type) const { return static_cast<int>(type); } }; std::ostream& operator<<(std::ostream& stream, const sprout::grammar::TokenType& type); } // namespace std namespace sprout { namespace grammar { typedef Token<TokenType, QString> GToken; typedef Node<TokenType, QString> GNode; typedef rule::Proxy<QChar, QString> GRule; template <class Type, class Value> class Grammar { public: typedef Node<Type, Value> PNode; typedef rule::Proxy<QChar, PNode> PRule; private: typedef QHash<QString, rule::Shared<GRule>> RulesMap; QHash<QString, rule::Shared<PRule>> _rules; rule::Proxy<QChar, GNode> _grammarParser; QHash<QString, GNode> _parsedRules; rule::Proxy<QChar, GNode>& grammarParser() { return _grammarParser; } rule::Proxy<QChar, GNode> createGrammarParser(); public: Grammar() { _rules["alpha"] = rule::Proxy<QChar, PNode>([](Cursor<QChar>& iter, Result<PNode>& result) { if (iter && (*iter).isLetter()) { result << PNode("", *iter++); return true; } return false; }); _rules["alnum"] = rule::Proxy<QChar, PNode>([](Cursor<QChar>& iter, Result<PNode>& result) { if (iter && (*iter).isLetterOrNumber()) { result << PNode("", *iter++); return true; } return false; }); _rules["string"] = rule::convert<PNode>( rule::wrap<QChar, QString>(&rule::parseQuotedString), [](QString& value) { return PNode("string", value); } ); _rules["number"] = rule::convert<PNode>( rule::wrap<QChar, double>(&rule::parseFloating), [](const float& value) { return PNode("number", QString::number(value)); } ); _grammarParser = createGrammarParser(); } rule::Proxy<QChar, PNode> buildRule(const GNode& node, const TokenType& ruleType) { bool excludeWhitespace = ruleType != TokenType::TokenRule; auto ws = rule::discard(rule::optional(rule::multiple(rule::proxyAlternative<QChar, QString>( rule::whitespace<QString>(), rule::lineComment("--") )))); switch (node.type()) { case TokenType::Sequence: { rule::ProxySequence<QChar, PNode> rule; for (auto child : node.children()) { auto childRule = buildRule(child, ruleType); if (child.type() == TokenType::Literal) { rule << discard(childRule); } else { rule << childRule; } if (excludeWhitespace) { rule << ws; } } if (ruleType == TokenType::TokenRule) { return rule::reduce<PNode>( rule, [](Result<PNode>& dest, Result<PNode>& src) { QString cumulative; while (src) { cumulative += src->value(); ++src; } dest.insert(PNode("", cumulative)); } ); } return rule; } case TokenType::Recursive: { rule::Proxy<QChar, PNode> terminal = buildRule(node[0], ruleType); if (excludeWhitespace) { terminal = rule::proxySequence<QChar, PNode>( terminal, ws ); } return rule::recursive( terminal, buildRule(node[1], ruleType), [node](Result<PNode>& result) { PNode recursiveNode(node.value()); while (result) { recursiveNode.insert(*result++); } result.clear(); result.insert(recursiveNode); } ); } case TokenType::Alternative: { rule::ProxyAlternative<QChar, PNode> rule; for (auto child : node.children()) { rule << buildRule(child, ruleType); } return rule; } case TokenType::Join: { auto content = buildRule(node[0], ruleType); auto separator = buildRule(node[1], ruleType); if (node[1].type() == TokenType::Literal) { separator = discard(separator); } if (excludeWhitespace) { content = rule::proxySequence<QChar, PNode>(content, ws); separator = rule::proxySequence<QChar, PNode>(separator, ws); } return rule::join(content, separator); } case TokenType::ZeroOrMore: { return rule::optional(rule::multiple(buildRule(node[0], ruleType))); } case TokenType::Optional: { return rule::optional(buildRule(node[0], ruleType)); } case TokenType::Discard: { return rule::discard(buildRule(node[0], ruleType)); } case TokenType::OneOrMore: { return rule::multiple(buildRule(node[0], ruleType)); } case TokenType::Opaque: case TokenType::Name: { return _rules[node.value()]; } case TokenType::Literal: { return rule::OrderedLiteral<QChar, PNode>(node.value(), PNode("", node.value())); } default: { std::stringstream str; str << "I don't know how to build a " << node.type() << " rule"; throw std::runtime_error(str.str()); } } } void readGrammar(Cursor<QChar>& cursor) { Result<GNode> nodes; QElapsedTimer timer; timer.start(); auto parseSuccessful = grammarParser()(cursor, nodes); std::cout << "Parsing completed in " << timer.nsecsElapsed() << " ns\n"; if (!parseSuccessful) { throw std::runtime_error("Failed to parse grammar. :("); } for (GNode& node : nodes) { _parsedRules[node.value()] = node; } } void build() { for (GNode& node : _parsedRules.values()) { _rules[node.value()] = rule::reduce<PNode>( buildRule(node[0], node.type()), [node](Result<PNode>& dest, Result<PNode>& src) { switch (node.type()) { case TokenType::GroupRule: dest.insert(src); break; case TokenType::TokenRule: if (src.size() == 1 && src[0].type() == "") { src[0].setType(node.value()); dest << src[0]; break; } // Otherwise, fall through case TokenType::Rule: { if (node[0].type() == TokenType::Recursive) { // Recursive rules already create a group node, so don't double-nest it dest.insert(src); break; } PNode rv(node.value()); while (src) { rv.insert(*src++); } dest << rv; break; } default: throw std::logic_error("Unexpected rule type"); } } ); } } rule::Shared<PRule> operator[](const char* name) { return _rules[name]; } decltype(_parsedRules)& parsedRules() { return _parsedRules; } typename decltype(_parsedRules)::iterator begin() { return _parsedRules.begin(); } typename decltype(_parsedRules)::iterator end() { return _parsedRules.end(); } }; template <class Type, class Value> rule::Proxy<QChar, GNode> Grammar<Type, Value>::createGrammarParser() { auto whitespace = rule::multiple(rule::proxyAlternative<QChar, QString>( rule::whitespace<QString>(), rule::lineComment("#") )); auto ws = rule::discard(rule::optional(whitespace)); auto name = rule::convert<GNode>( rule::aggregate<QString>( rule::multiple(rule::simplePredicate<QChar>([](const QChar& input) { return input.isLetter() || input == '_'; })), [](QString& target, const QChar& c) { target += c; } ), [this](QString& value) { if (_rules.contains(value)) { return GNode(TokenType::Opaque, value); } return GNode(TokenType::Name, value); } ); auto literal = rule::convert<GNode>( rule::wrap<QChar, QString>(&rule::parseQuotedString), [](QString& value) { return GNode(TokenType::Literal, value); } ); auto expression = rule::shared(rule::proxyAlternative<QChar, GNode>()); auto singleExpression = rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::optional(rule::OrderedLiteral<QChar, GNode>("-", TokenType::Discard)), ws, rule::proxyAlternative<QChar, GNode>( literal, name, rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::discard(rule::OrderedLiteral<QChar, GNode>("{")), ws, expression, expression, ws, rule::discard(rule::OrderedLiteral<QChar, GNode>("}")), ws ), [](Result<GNode>& dest, Result<GNode>& src) { GNode joinNode(TokenType::Join); while (src) { joinNode.insert(*src++); } dest.insert(joinNode); } ), rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::discard(rule::OrderedLiteral<QChar, GNode>("(")), ws, rule::multiple(expression), ws, rule::discard(rule::OrderedLiteral<QChar, GNode>(")")), ws ), [](Result<GNode>& dest, Result<GNode>& src) { GNode parenNode(TokenType::Sequence); while (src) { parenNode.insert(*src++); } dest.insert(parenNode); } ) ), ws, rule::optional(rule::proxyAlternative<QChar, GNode>( rule::OrderedLiteral<QChar, GNode>("*", TokenType::ZeroOrMore), rule::OrderedLiteral<QChar, GNode>("+", TokenType::OneOrMore), rule::OrderedLiteral<QChar, GNode>("?", TokenType::Optional) )), ws ), [](Result<GNode>& results, Result<GNode>& src) { if (src[0].type() == TokenType::Discard) { GNode discardNode(TokenType::Discard); if (src.size() == 3) { GNode node(src[2].type()); node.insert(src[1]); discardNode.insert(node); } else { discardNode.insert(src[1]); } results.insert(discardNode); } else if (src.size() == 2) { GNode node(src[1].type()); node.insert(src[0]); results.insert(node); } else { results.insert(src); } } ); expression << rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::join<QChar, GNode>( rule::proxySequence<QChar, GNode>( singleExpression, ws ), rule::discard(rule::proxySequence<QChar, GNode>( rule::discard(rule::OrderedLiteral<QChar, QString>("|")), ws )) ), ws ), [](Result<GNode>& dest, Result<GNode>& src) { if (src.size() > 1) { dest.insert(GNode(TokenType::Alternative, src.data())); } else { dest.insert(*src); } } ); auto rule = rule::reduce<GNode>( rule::proxySequence<QChar, GNode>( rule::proxyAlternative<QChar, GNode>( rule::OrderedLiteral<QChar, GNode>("Rule", TokenType::Rule), rule::OrderedLiteral<QChar, GNode>("Token", TokenType::TokenRule), rule::OrderedLiteral<QChar, GNode>("Group", TokenType::GroupRule) ), ws, name, ws, rule::discard(rule::OrderedLiteral<QChar, QString>("=")), ws, rule::multiple(expression), ws, rule::discard(rule::OrderedLiteral<QChar, QString>(";")), ws ), [](Result<GNode>& results, Result<GNode>& subresults) { GNode rule = *subresults++; rule.setValue(subresults->value()); ++subresults; GNode sequence(TokenType::Sequence); while (subresults) { sequence.insert(*subresults++); } rule.insert(sequence); results << rule; } ); return rule::proxySequence<QChar, GNode>( ws, rule::multiple(rule), rule::end<QChar, GNode>() ); } } // namespace grammar } // namespace sprout #endif // SPROUT_GRAMMAR_HEADER // vim: set ts=4 sw=4 : <|endoftext|>
<commit_before>//============================================================================== /* LuaBridge is Copyright (C) 2007 by Nathan Reed. 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. */ //============================================================================== /* * Implementation of shared_ptr class template. */ // Declaration of container for the refcounts #ifdef _MSC_VER typedef stdext::hash_map<const void *, int> refcounts_t; #else struct ptr_hash { size_t operator () (const void * const v) const { static __gnu_cxx::hash<unsigned int> H; return H((unsigned int)v); } }; typedef __gnu_cxx::hash_map<const void *, int, ptr_hash> refcounts_t; #endif extern refcounts_t refcounts_; /* * shared_ptr <T> implementation */ template <typename T> shared_ptr<T>::shared_ptr (T* ptr_): ptr(ptr_) { ++refcounts_[ptr]; } template <typename T> shared_ptr<T>::shared_ptr (const shared_ptr<T>& rhs): ptr(rhs.get()) { ++refcounts_[ptr]; } template <typename T> template <typename U> shared_ptr<T>::shared_ptr (const shared_ptr<U>& rhs): ptr(rhs.get()) { ++refcounts_[ptr]; } template <typename T> shared_ptr<T>& shared_ptr<T>::operator = (const shared_ptr<T>& rhs) { reset(); ptr = rhs.ptr; ++refcounts_[ptr]; return *this; } template <typename T> template <typename U> shared_ptr<T>& shared_ptr<T>::operator = (const shared_ptr<U>& rhs) { reset(); ptr = static_cast<T*>(rhs.get()); ++refcounts_[ptr]; return *this; } template <typename T> T* shared_ptr<T>::get () const { return ptr; } template <typename T> T* shared_ptr<T>::operator * () const { return ptr; } template <typename T> T* shared_ptr<T>::operator -> () const { return ptr; } template <typename T> long shared_ptr<T>::use_count () const { return refcounts_[ptr]; } template <typename T> void shared_ptr<T>::reset () { if (!ptr) return; if (--refcounts_[ptr] <= 0) delete ptr; ptr = 0; } template <typename T> shared_ptr<T>::~shared_ptr () { reset(); } <commit_msg>Fix 64 bit integer cast<commit_after>//============================================================================== /* LuaBridge is Copyright (C) 2007 by Nathan Reed. 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 <stdint.h> /* * Implementation of shared_ptr class template. */ // Declaration of container for the refcounts #ifdef _MSC_VER typedef stdext::hash_map<const void *, int> refcounts_t; #else struct ptr_hash { size_t operator () (const void * const v) const { static __gnu_cxx::hash<unsigned int> H; return H(uintptr_t(v)); } }; typedef __gnu_cxx::hash_map<const void *, int, ptr_hash> refcounts_t; #endif extern refcounts_t refcounts_; /* * shared_ptr <T> implementation */ template <typename T> shared_ptr<T>::shared_ptr (T* ptr_): ptr(ptr_) { ++refcounts_[ptr]; } template <typename T> shared_ptr<T>::shared_ptr (const shared_ptr<T>& rhs): ptr(rhs.get()) { ++refcounts_[ptr]; } template <typename T> template <typename U> shared_ptr<T>::shared_ptr (const shared_ptr<U>& rhs): ptr(rhs.get()) { ++refcounts_[ptr]; } template <typename T> shared_ptr<T>& shared_ptr<T>::operator = (const shared_ptr<T>& rhs) { reset(); ptr = rhs.ptr; ++refcounts_[ptr]; return *this; } template <typename T> template <typename U> shared_ptr<T>& shared_ptr<T>::operator = (const shared_ptr<U>& rhs) { reset(); ptr = static_cast<T*>(rhs.get()); ++refcounts_[ptr]; return *this; } template <typename T> T* shared_ptr<T>::get () const { return ptr; } template <typename T> T* shared_ptr<T>::operator * () const { return ptr; } template <typename T> T* shared_ptr<T>::operator -> () const { return ptr; } template <typename T> long shared_ptr<T>::use_count () const { return refcounts_[ptr]; } template <typename T> void shared_ptr<T>::reset () { if (!ptr) return; if (--refcounts_[ptr] <= 0) delete ptr; ptr = 0; } template <typename T> shared_ptr<T>::~shared_ptr () { reset(); } <|endoftext|>
<commit_before>/* Copyright (c) 2003-2012, 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_FILE_HPP_INCLUDED #define TORRENT_FILE_HPP_INCLUDED #include <memory> #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/noncopyable.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/error_code.hpp" #include "libtorrent/size_type.hpp" #include "libtorrent/config.hpp" #include "libtorrent/intrusive_ptr_base.hpp" #ifdef TORRENT_WINDOWS // windows part #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <winioctl.h> #include <sys/types.h> #else // posix part #define _FILE_OFFSET_BITS 64 #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 600 #endif #include <unistd.h> #include <sys/uio.h> #include <fcntl.h> #include <sys/types.h> #include <dirent.h> // for DIR #undef _FILE_OFFSET_BITS #endif namespace libtorrent { struct file_status { size_type file_size; time_t atime; time_t mtime; time_t ctime; enum { #if defined TORRENT_WINDOWS fifo = 0x1000, // named pipe (fifo) character_special = 0x2000, // character special directory = 0x4000, // directory regular_file = 0x8000 // regular #else fifo = 0010000, // named pipe (fifo) character_special = 0020000, // character special directory = 0040000, // directory block_special = 0060000, // block special regular_file = 0100000, // regular link = 0120000, // symbolic link socket = 0140000 // socket #endif } modes_t; int mode; }; // TODO: why are all these functions exported? enum stat_flags_t { dont_follow_links = 1 }; TORRENT_EXPORT void stat_file(std::string f, file_status* s , error_code& ec, int flags = 0); TORRENT_EXPORT void rename(std::string const& f , std::string const& newf, error_code& ec); TORRENT_EXPORT void create_directories(std::string const& f , error_code& ec); TORRENT_EXPORT void create_directory(std::string const& f , error_code& ec); TORRENT_EXPORT void remove_all(std::string const& f , error_code& ec); TORRENT_EXPORT void remove(std::string const& f, error_code& ec); TORRENT_EXPORT bool exists(std::string const& f); TORRENT_EXPORT size_type file_size(std::string const& f); TORRENT_EXPORT bool is_directory(std::string const& f , error_code& ec); TORRENT_EXPORT void recursive_copy(std::string const& old_path , std::string const& new_path, error_code& ec); TORRENT_EXPORT void copy_file(std::string const& f , std::string const& newf, error_code& ec); TORRENT_EXPORT std::string split_path(std::string const& f); TORRENT_EXPORT char const* next_path_element(char const* p); TORRENT_EXPORT std::string extension(std::string const& f); TORRENT_EXPORT void replace_extension(std::string& f, std::string const& ext); TORRENT_EXPORT bool is_root_path(std::string const& f); TORRENT_EXPORT std::string parent_path(std::string const& f); TORRENT_EXPORT bool has_parent_path(std::string const& f); TORRENT_EXPORT std::string filename(std::string const& f); TORRENT_EXPORT std::string combine_path(std::string const& lhs , std::string const& rhs); TORRENT_EXPORT std::string complete(std::string const& f); TORRENT_EXPORT bool is_complete(std::string const& f); TORRENT_EXPORT std::string current_working_directory(); #if TORRENT_USE_UNC_PATHS TORRENT_EXTRA_EXPORT std::string canonicalize_path(std::string const& f); #endif class TORRENT_EXPORT directory : public boost::noncopyable { public: directory(std::string const& path, error_code& ec); ~directory(); void next(error_code& ec); std::string file() const; bool done() const { return m_done; } private: #ifdef TORRENT_WINDOWS HANDLE m_handle; #if TORRENT_USE_WSTRING WIN32_FIND_DATAW m_fd; #else WIN32_FIND_DATAA m_fd; #endif #else DIR* m_handle; // the dirent struct contains a zero-sized // array at the end, it will end up referring // to the m_name field struct dirent m_dirent; char m_name[TORRENT_MAX_PATH + 1]; // +1 to make room for null #endif bool m_done; }; struct TORRENT_EXPORT file: boost::noncopyable, intrusive_ptr_base<file> { enum { // when a file is opened with no_buffer // file offsets have to be aligned to // pos_alignment() and buffer addresses // to buf_alignment() and read/write sizes // to size_alignment() read_only = 0, write_only = 1, read_write = 2, rw_mask = read_only | write_only | read_write, no_buffer = 4, sparse = 8, no_atime = 16, random_access = 32, lock_file = 64, attribute_hidden = 0x1000, attribute_executable = 0x2000, attribute_mask = attribute_hidden | attribute_executable }; #ifdef TORRENT_WINDOWS struct iovec_t { void* iov_base; size_t iov_len; }; #else typedef iovec iovec_t; #endif // use a typedef for the type of iovec_t::iov_base // since it may differ #ifdef TORRENT_SOLARIS typedef char* iovec_base_t; #else typedef void* iovec_base_t; #endif file(); file(std::string const& p, int m, error_code& ec); ~file(); bool open(std::string const& p, int m, error_code& ec); bool is_open() const; void close(); bool set_size(size_type size, error_code& ec); int open_mode() const { return m_open_mode; } // when opened in unbuffered mode, this is the // required alignment of file_offsets. i.e. // any (file_offset & (pos_alignment()-1)) == 0 // is a precondition to read and write operations int pos_alignment() const; // when opened in unbuffered mode, this is the // required alignment of buffer addresses int buf_alignment() const; // read/write buffer sizes needs to be aligned to // this when in unbuffered mode int size_alignment() const; size_type writev(size_type file_offset, iovec_t const* bufs, int num_bufs, error_code& ec); size_type readv(size_type file_offset, iovec_t const* bufs, int num_bufs, error_code& ec); void hint_read(size_type file_offset, int len); size_type get_size(error_code& ec) const; // return the offset of the first byte that // belongs to a data-region size_type sparse_end(size_type start) const; size_type phys_offset(size_type offset); #ifdef TORRENT_WINDOWS HANDLE native_handle() const { return m_file_handle; } #else int native_handle() const { return m_fd; } #endif private: #ifdef TORRENT_WINDOWS HANDLE m_file_handle; #if TORRENT_USE_WSTRING std::wstring m_path; #else std::string m_path; #endif // TORRENT_USE_WSTRING #else // TORRENT_WINDOWS int m_fd; #endif // TORRENT_WINDOWS #if defined TORRENT_WINDOWS || defined TORRENT_LINUX || defined TORRENT_DEBUG static void init_file(); static int m_page_size; #endif int m_open_mode; #if defined TORRENT_WINDOWS || defined TORRENT_LINUX mutable int m_sector_size; #endif #if defined TORRENT_WINDOWS mutable int m_cluster_size; #endif }; } #endif // TORRENT_FILE_HPP_INCLUDED <commit_msg>none of the internal file abstraction should be exported from the library<commit_after>/* Copyright (c) 2003-2012, 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_FILE_HPP_INCLUDED #define TORRENT_FILE_HPP_INCLUDED #include <memory> #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/noncopyable.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/error_code.hpp" #include "libtorrent/size_type.hpp" #include "libtorrent/config.hpp" #include "libtorrent/intrusive_ptr_base.hpp" #ifdef TORRENT_WINDOWS // windows part #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <winioctl.h> #include <sys/types.h> #else // posix part #define _FILE_OFFSET_BITS 64 #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE 600 #endif #include <unistd.h> #include <sys/uio.h> #include <fcntl.h> #include <sys/types.h> #include <dirent.h> // for DIR #undef _FILE_OFFSET_BITS #endif namespace libtorrent { struct file_status { size_type file_size; time_t atime; time_t mtime; time_t ctime; enum { #if defined TORRENT_WINDOWS fifo = 0x1000, // named pipe (fifo) character_special = 0x2000, // character special directory = 0x4000, // directory regular_file = 0x8000 // regular #else fifo = 0010000, // named pipe (fifo) character_special = 0020000, // character special directory = 0040000, // directory block_special = 0060000, // block special regular_file = 0100000, // regular link = 0120000, // symbolic link socket = 0140000 // socket #endif } modes_t; int mode; }; // flags for stat_file enum { dont_follow_links = 1 }; TORRENT_EXTRA_EXPORT void stat_file(std::string f, file_status* s , error_code& ec, int flags = 0); TORRENT_EXTRA_EXPORT void rename(std::string const& f , std::string const& newf, error_code& ec); TORRENT_EXTRA_EXPORT void create_directories(std::string const& f , error_code& ec); TORRENT_EXTRA_EXPORT void create_directory(std::string const& f , error_code& ec); TORRENT_EXTRA_EXPORT void remove_all(std::string const& f , error_code& ec); TORRENT_EXTRA_EXPORT void remove(std::string const& f, error_code& ec); TORRENT_EXTRA_EXPORT bool exists(std::string const& f); TORRENT_EXTRA_EXPORT size_type file_size(std::string const& f); TORRENT_EXTRA_EXPORT bool is_directory(std::string const& f , error_code& ec); TORRENT_EXTRA_EXPORT void recursive_copy(std::string const& old_path , std::string const& new_path, error_code& ec); TORRENT_EXTRA_EXPORT void copy_file(std::string const& f , std::string const& newf, error_code& ec); TORRENT_EXTRA_EXPORT std::string split_path(std::string const& f); TORRENT_EXTRA_EXPORT char const* next_path_element(char const* p); TORRENT_EXTRA_EXPORT std::string extension(std::string const& f); TORRENT_EXTRA_EXPORT void replace_extension(std::string& f, std::string const& ext); TORRENT_EXTRA_EXPORT bool is_root_path(std::string const& f); TORRENT_EXTRA_EXPORT std::string parent_path(std::string const& f); TORRENT_EXTRA_EXPORT bool has_parent_path(std::string const& f); TORRENT_EXTRA_EXPORT std::string filename(std::string const& f); TORRENT_EXTRA_EXPORT std::string combine_path(std::string const& lhs , std::string const& rhs); TORRENT_EXTRA_EXPORT std::string complete(std::string const& f); TORRENT_EXTRA_EXPORT bool is_complete(std::string const& f); TORRENT_EXTRA_EXPORT std::string current_working_directory(); #if TORRENT_USE_UNC_PATHS TORRENT_EXTRA_EXPORT std::string canonicalize_path(std::string const& f); #endif class TORRENT_EXTRA_EXPORT directory : public boost::noncopyable { public: directory(std::string const& path, error_code& ec); ~directory(); void next(error_code& ec); std::string file() const; bool done() const { return m_done; } private: #ifdef TORRENT_WINDOWS HANDLE m_handle; #if TORRENT_USE_WSTRING WIN32_FIND_DATAW m_fd; #else WIN32_FIND_DATAA m_fd; #endif #else DIR* m_handle; // the dirent struct contains a zero-sized // array at the end, it will end up referring // to the m_name field struct dirent m_dirent; char m_name[TORRENT_MAX_PATH + 1]; // +1 to make room for null #endif bool m_done; }; struct TORRENT_EXTRA_EXPORT file: boost::noncopyable, intrusive_ptr_base<file> { enum { // when a file is opened with no_buffer // file offsets have to be aligned to // pos_alignment() and buffer addresses // to buf_alignment() and read/write sizes // to size_alignment() read_only = 0, write_only = 1, read_write = 2, rw_mask = read_only | write_only | read_write, no_buffer = 4, sparse = 8, no_atime = 16, random_access = 32, lock_file = 64, attribute_hidden = 0x1000, attribute_executable = 0x2000, attribute_mask = attribute_hidden | attribute_executable }; #ifdef TORRENT_WINDOWS struct iovec_t { void* iov_base; size_t iov_len; }; #else typedef iovec iovec_t; #endif // use a typedef for the type of iovec_t::iov_base // since it may differ #ifdef TORRENT_SOLARIS typedef char* iovec_base_t; #else typedef void* iovec_base_t; #endif file(); file(std::string const& p, int m, error_code& ec); ~file(); bool open(std::string const& p, int m, error_code& ec); bool is_open() const; void close(); bool set_size(size_type size, error_code& ec); int open_mode() const { return m_open_mode; } // when opened in unbuffered mode, this is the // required alignment of file_offsets. i.e. // any (file_offset & (pos_alignment()-1)) == 0 // is a precondition to read and write operations int pos_alignment() const; // when opened in unbuffered mode, this is the // required alignment of buffer addresses int buf_alignment() const; // read/write buffer sizes needs to be aligned to // this when in unbuffered mode int size_alignment() const; size_type writev(size_type file_offset, iovec_t const* bufs, int num_bufs, error_code& ec); size_type readv(size_type file_offset, iovec_t const* bufs, int num_bufs, error_code& ec); void hint_read(size_type file_offset, int len); size_type get_size(error_code& ec) const; // return the offset of the first byte that // belongs to a data-region size_type sparse_end(size_type start) const; size_type phys_offset(size_type offset); #ifdef TORRENT_WINDOWS HANDLE native_handle() const { return m_file_handle; } #else int native_handle() const { return m_fd; } #endif private: #ifdef TORRENT_WINDOWS HANDLE m_file_handle; #if TORRENT_USE_WSTRING std::wstring m_path; #else std::string m_path; #endif // TORRENT_USE_WSTRING #else // TORRENT_WINDOWS int m_fd; #endif // TORRENT_WINDOWS #if defined TORRENT_WINDOWS || defined TORRENT_LINUX || defined TORRENT_DEBUG static void init_file(); static int m_page_size; #endif int m_open_mode; #if defined TORRENT_WINDOWS || defined TORRENT_LINUX mutable int m_sector_size; #endif #if defined TORRENT_WINDOWS mutable int m_cluster_size; #endif }; } #endif // TORRENT_FILE_HPP_INCLUDED <|endoftext|>
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #ifndef NIX_FILTER_H #define NIX_FILTER_H #include <functional> #include <vector> #include <unordered_set> #include <string> namespace nix { namespace util { /** * Base struct to be inherited by all filter implementations. * Child classes will have to implement ()-operator and will * all inherit typedef "type" which corresponds to the type of "()". */ template<typename T> struct Filter : public std::unary_function<T, bool> { virtual bool operator()(const T&) = 0; typedef std::function<bool(const T&)> type; }; /** * One Filter struct to that filters nothing but always returns true. * Use "AcceptAll<T>()" to pass it on as filter and "::type" to define * its' type. */ template<typename T> struct AcceptAll : public Filter<T> { virtual bool operator()(const T &e) { return true; } }; template<typename T> struct IdFilter : public Filter<T> { const std::string id; IdFilter(const std::string &str) : id(str) {} virtual bool operator()(const T &e) { return e.id() == id; } }; template<typename T> struct IdsFilter : public Filter<T> { std::unordered_set<std::string> ids; IdsFilter(const std::vector<std::string> &ids_vect) : ids(ids_vect.begin(), ids_vect.end()) {} virtual bool operator()(const T &e) { // std::unordered_set.count is a fast by-hash-getter that // returns 1 (if val found) or 0 (if not found). return (bool) ids.count(e.id()); } }; template<typename T> struct TypeFilter : public Filter<T> { const std::string type; TypeFilter(const std::string &str) : type(str) {} virtual bool operator()(const T &e) { return e.type() == type; } }; template<typename T> struct NameFilter : public Filter<T> { const std::string name; NameFilter(const std::string &str) : name(str) {} virtual bool operator()(const T &e) { return e.name() == name; } }; } // namespace util } // namespace nix #endif // include guard <commit_msg>IdsFilter: dont cast to bool but compare<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #ifndef NIX_FILTER_H #define NIX_FILTER_H #include <functional> #include <vector> #include <unordered_set> #include <string> namespace nix { namespace util { /** * Base struct to be inherited by all filter implementations. * Child classes will have to implement ()-operator and will * all inherit typedef "type" which corresponds to the type of "()". */ template<typename T> struct Filter : public std::unary_function<T, bool> { virtual bool operator()(const T&) = 0; typedef std::function<bool(const T&)> type; }; /** * One Filter struct to that filters nothing but always returns true. * Use "AcceptAll<T>()" to pass it on as filter and "::type" to define * its' type. */ template<typename T> struct AcceptAll : public Filter<T> { virtual bool operator()(const T &e) { return true; } }; template<typename T> struct IdFilter : public Filter<T> { const std::string id; IdFilter(const std::string &str) : id(str) {} virtual bool operator()(const T &e) { return e.id() == id; } }; template<typename T> struct IdsFilter : public Filter<T> { std::unordered_set<std::string> ids; IdsFilter(const std::vector<std::string> &ids_vect) : ids(ids_vect.begin(), ids_vect.end()) {} virtual bool operator()(const T &e) { // std::unordered_set.count is a fast by-hash-getter that // returns 1 (if val found) or 0 (if not found). return ids.count(e.id()) > 0; } }; template<typename T> struct TypeFilter : public Filter<T> { const std::string type; TypeFilter(const std::string &str) : type(str) {} virtual bool operator()(const T &e) { return e.type() == type; } }; template<typename T> struct NameFilter : public Filter<T> { const std::string name; NameFilter(const std::string &str) : name(str) {} virtual bool operator()(const T &e) { return e.name() == name; } }; } // namespace util } // namespace nix #endif // include guard <|endoftext|>
<commit_before>#ifndef UTIL_ARGS_HPP #define UTIL_ARGS_HPP #include "../core/error.hpp" #include <unordered_map> #include <map> #include <vector> #include <iostream> #include <iomanip> namespace nnlib { class Args { public: Args(int argc, const char **argv) : m_argc(argc), m_argv(argv), m_argi(0) {} Args &unpop() { NNHardAssert(m_argi > 0, "Cannot unpop from a full argument stack!"); --m_argi; return *this; } bool hasNext() const { return m_argi < m_argc; } bool ifPop(const std::string &s) { NNHardAssert(hasNext(), "Attempted to pop from an empty argument stack!"); if(s == m_argv[m_argi]) { ++m_argi; return true; } return false; } bool nextIsNumber() const { NNHardAssert(hasNext(), "Attempted to use empty argument stack!"); try { std::stod(m_argv[m_argi]); return true; } catch(const std::invalid_argument &) { return false; } } std::string popString() { NNHardAssert(hasNext(), "Attempted to pop from an empty argument stack!"); return m_argv[m_argi++]; } double popDouble() { NNHardAssert(nextIsNumber(), "Attempted to pop a string as a number!"); return std::stod(popString()); } int popInt() { NNHardAssert(nextIsNumber(), "Attempted to pop a string as a number!"); return std::stoi(popString()); } private: int m_argc; const char **m_argv; int m_argi; }; class ArgsParser { public: explicit ArgsParser(bool help = true) : m_helpOpt(help ? 'h' : '\0'), m_nextUnnamedOpt(0) { if(m_helpOpt != '\0') addFlag(m_helpOpt, "help"); } explicit ArgsParser(char helpOpt, std::string helpLong = "help") : m_helpOpt(helpOpt), m_nextUnnamedOpt(0) { if(m_helpOpt != '\0') addFlag(m_helpOpt, helpLong); } ArgsParser &addFlag(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_data[opt].type = Type::Bool; m_data[opt].b = false; return *this; } ArgsParser &addFlag(std::string longOpt) { return addFlag(++m_nextUnnamedOpt, longOpt); } ArgsParser &addInt(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_expected[opt] = Type::Int; return *this; } ArgsParser &addInt(char opt, std::string longOpt, int defaultValue) { addInt(opt, longOpt); m_data[opt].type = Type::Int; m_data[opt].i = defaultValue; return *this; } ArgsParser &addInt(std::string longOpt) { return addInt(++m_nextUnnamedOpt, longOpt); } ArgsParser &addInt(std::string longOpt, int defaultValue) { return addInt(++m_nextUnnamedOpt, longOpt, defaultValue); } ArgsParser &addDouble(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_expected[opt] = Type::Double; return *this; } ArgsParser &addDouble(char opt, std::string longOpt, double defaultValue) { addDouble(opt, longOpt); m_data[opt].type = Type::Double; m_data[opt].d = defaultValue; return *this; } ArgsParser &addDouble(std::string longOpt) { return addDouble(++m_nextUnnamedOpt, longOpt); } ArgsParser &addDouble(std::string longOpt, double defaultValue) { return addDouble(++m_nextUnnamedOpt, longOpt, defaultValue); } ArgsParser &addString(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_expected[opt] = Type::String; return *this; } ArgsParser &addString(char opt, std::string longOpt, std::string defaultValue) { addString(opt, longOpt); m_data[opt].type = Type::String; m_stringStorage.push_back(defaultValue); m_data[opt].i = m_stringStorage.size() - 1; return *this; } ArgsParser &addString(std::string longOpt) { return addString(++m_nextUnnamedOpt, longOpt); } ArgsParser &addString(std::string longOpt, std::string defaultValue) { return addString(++m_nextUnnamedOpt, longOpt, defaultValue); } /// Parses command line arguments. /// If -h or --help is present, this prints help and ends the program. ArgsParser &parse(int argc, const char **argv, bool popCommand = true, std::ostream &out = std::cout) { Args args(argc, argv); if(popCommand) args.popString(); while(args.hasNext()) { NNHardAssert(!args.nextIsNumber(), "Unexpected number!"); std::string arg = args.popString(); char opt; if(arg.length() > 1 && arg[0] == '-' && arg[1] == '-') { auto i = m_longToChar.find(std::string(arg.c_str() + 2)); NNHardAssert(i != m_longToChar.end(), "Unexpected argument '" + std::string(arg.c_str() + 2) + "'!"); opt = i->second; } else if(arg.length() > 1 && arg[0] == '-') { for(size_t i = 1; i < arg.length() - 1; ++i) { auto j = m_expected.find(arg[i]); NNHardAssert(j != m_expected.end(), "Unexpected argument '" + std::string(1, arg[i]) + "'!"); NNHardAssert(j->second == Type::Bool, "Multiple options for a single - must be flags!"); m_data[arg[i]].type = Type::Bool; m_data[arg[i]].b = true; } opt = arg.back(); } auto i = m_expected.find(opt); NNHardAssert(i != m_expected.end(), "Unexpected argument '" + std::string(1, opt) + "'!"); m_data[opt].type = i->second; switch(i->second) { case Type::Bool: m_data[opt].b = true; break; case Type::Int: m_data[opt].i = args.popInt(); break; case Type::Double: m_data[opt].d = args.popDouble(); break; case Type::String: m_stringStorage.push_back(args.popString()); m_data[opt].i = m_stringStorage.size() - 1; break; } } if(m_helpOpt != '\0' && getFlag(m_helpOpt)) { printHelp(out); exit(0); } return *this; } const ArgsParser &printHelp(std::ostream &out = std::cout) const { out << std::left; std::map<std::string, Type> orderedOpts; for(auto &p : m_expected) { orderedOpts.emplace(optName(p.first), p.second); } for(auto &p : orderedOpts) { char opt; if(p.first.size() == 1) opt = p.first[0]; else opt = m_longToChar.at(p.first); std::string name; if(opt < 32) name = "--" + p.first; else { name = std::string("-") + opt; if(p.first.size() > 1) name += ",--" + p.first; } out << std::setw(25) << name; switch(p.second) { case Type::Bool: out << "Flag"; break; case Type::Int: out << "Int"; break; case Type::Double: out << "Double"; break; case Type::String: out << "String"; break; } auto d = m_data.find(opt); if(d != m_data.end()) { out << " [value = "; switch(d->second.type) { case Type::Bool: out << (d->second.b ? "true" : "false"); break; case Type::Int: out << d->second.i; break; case Type::Double: out << d->second.d; break; case Type::String: out << "\"" << m_stringStorage[d->second.i] << "\""; break; } out << "]"; } out << std::endl; } return *this; } const ArgsParser &printOpts(std::ostream &out = std::cout) const { out << std::left; std::map<std::string, Data> orderedOpts; for(auto &p : m_data) { orderedOpts.emplace(optName(p.first), p.second); } for(auto &p : orderedOpts) { out << std::setw(20) << p.first << "= "; switch(p.second.type) { case Type::Bool: out << p.second.b; break; case Type::Int: out << p.second.i; break; case Type::Double: out << p.second.d; break; case Type::String: out << m_stringStorage[p.second.i]; break; } out << std::endl; } return *this; } bool hasOpt(char opt) const { auto i = m_data.find(opt); return i != m_data.end(); } bool hasOpt(std::string longOpt) const { auto i = m_longToChar.find(longOpt); return i != m_longToChar.end() && hasOpt(i->second); } std::string optName(char opt) const { auto i = m_charToLong.find(opt); if(i != m_charToLong.end()) return i->second; else return std::string(1, opt); } bool getFlag(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::Bool, "Attempted to get an incompatible type!"); return m_data.at(opt).b; } bool getFlag(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getFlag(i->second); } int getInt(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::Int, "Attempted to get an incompatible type!"); return m_data.at(opt).i; } int getInt(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getInt(i->second); } double getDouble(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::Double, "Attempted to get an incompatible type!"); return m_data.at(opt).d; } double getDouble(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getDouble(i->second); } std::string getString(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::String, "Attempted to get an incompatible type!"); return m_stringStorage[m_data.at(opt).i]; } std::string getString(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getString(i->second); } private: enum class Type { Bool, Int, Double, String }; struct Data { Type type; union { bool b; int i; double d; }; }; void addOpt(char opt, std::string longOpt) { NNHardAssert(m_expected.find(opt) == m_expected.end(), "Attempted to redefine '" + optName(opt) + "'!"); m_expected[opt] = Type::Bool; if(longOpt != "") { NNHardAssert(m_charToLong.find(opt) == m_charToLong.end(), "Attempted to redefine '" + optName(opt) + "'!"); m_longToChar[longOpt] = opt; m_charToLong[opt] = longOpt; } } char m_helpOpt, m_nextUnnamedOpt; std::unordered_map<char, Type> m_expected; std::unordered_map<char, Data> m_data; std::unordered_map<std::string, char> m_longToChar; std::unordered_map<char, std::string> m_charToLong; std::vector<std::string> m_stringStorage; }; } #endif <commit_msg>Updated ArgsParser.<commit_after>#ifndef UTIL_ARGS_HPP #define UTIL_ARGS_HPP #include "../core/error.hpp" #include <unordered_map> #include <map> #include <vector> #include <iostream> #include <iomanip> namespace nnlib { class Args { public: Args(int argc, const char **argv) : m_argc(argc), m_argv(argv), m_argi(0) {} Args &unpop() { NNHardAssert(m_argi > 0, "Cannot unpop from a full argument stack!"); --m_argi; return *this; } bool hasNext() const { return m_argi < m_argc; } bool ifPop(const std::string &s) { if(hasNext() && s == m_argv[m_argi]) { ++m_argi; return true; } return false; } bool nextIsNumber() const { if(!hasNext()) return false; try { std::stod(m_argv[m_argi]); return true; } catch(const std::invalid_argument &) { return false; } } std::string popString() { NNHardAssert(hasNext(), "Attempted to pop from an empty argument stack!"); return m_argv[m_argi++]; } double popDouble() { NNHardAssert(nextIsNumber(), "Attempted to pop a string as a number!"); return std::stod(popString()); } int popInt() { NNHardAssert(nextIsNumber(), "Attempted to pop a string as a number!"); return std::stoi(popString()); } private: int m_argc; const char **m_argv; int m_argi; }; class ArgsParser { public: explicit ArgsParser(bool help = true) : m_helpOpt(help ? 'h' : '\0'), m_nextUnnamedOpt(0) { if(m_helpOpt != '\0') addFlag(m_helpOpt, "help"); } explicit ArgsParser(char helpOpt, std::string helpLong = "help") : m_helpOpt(helpOpt), m_nextUnnamedOpt(0) { if(m_helpOpt != '\0') addFlag(m_helpOpt, helpLong); } ArgsParser &addFlag(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_data[opt].type = Type::Bool; m_data[opt].b = false; return *this; } ArgsParser &addFlag(std::string longOpt) { return addFlag(++m_nextUnnamedOpt, longOpt); } ArgsParser &addInt(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_expected[opt] = Type::Int; return *this; } ArgsParser &addInt(char opt, std::string longOpt, int defaultValue) { addInt(opt, longOpt); m_data[opt].type = Type::Int; m_data[opt].i = defaultValue; return *this; } ArgsParser &addInt(std::string longOpt) { return addInt(++m_nextUnnamedOpt, longOpt); } ArgsParser &addInt(std::string longOpt, int defaultValue) { return addInt(++m_nextUnnamedOpt, longOpt, defaultValue); } ArgsParser &addDouble(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_expected[opt] = Type::Double; return *this; } ArgsParser &addDouble(char opt, std::string longOpt, double defaultValue) { addDouble(opt, longOpt); m_data[opt].type = Type::Double; m_data[opt].d = defaultValue; return *this; } ArgsParser &addDouble(std::string longOpt) { return addDouble(++m_nextUnnamedOpt, longOpt); } ArgsParser &addDouble(std::string longOpt, double defaultValue) { return addDouble(++m_nextUnnamedOpt, longOpt, defaultValue); } ArgsParser &addString(char opt, std::string longOpt = "") { addOpt(opt, longOpt); m_expected[opt] = Type::String; return *this; } ArgsParser &addString(char opt, std::string longOpt, std::string defaultValue) { addString(opt, longOpt); m_data[opt].type = Type::String; m_stringStorage.push_back(defaultValue); m_data[opt].i = m_stringStorage.size() - 1; return *this; } ArgsParser &addString(std::string longOpt) { return addString(++m_nextUnnamedOpt, longOpt); } ArgsParser &addString(std::string longOpt, std::string defaultValue) { return addString(++m_nextUnnamedOpt, longOpt, defaultValue); } /// Parses command line arguments. /// If -h or --help is present, this prints help and ends the program. ArgsParser &parse(int argc, const char **argv, bool popCommand = true, std::ostream &out = std::cout) { Args args(argc, argv); if(popCommand) args.popString(); while(args.hasNext()) { NNHardAssert(!args.nextIsNumber(), "Unexpected number!"); std::string arg = args.popString(); char opt; if(arg.length() > 1 && arg[0] == '-' && arg[1] == '-') { auto i = m_longToChar.find(std::string(arg.c_str() + 2)); NNHardAssert(i != m_longToChar.end(), "Unexpected argument '" + std::string(arg.c_str() + 2) + "'!"); opt = i->second; } else if(arg.length() > 1 && arg[0] == '-') { for(size_t i = 1; i < arg.length() - 1; ++i) { auto j = m_expected.find(arg[i]); NNHardAssert(j != m_expected.end(), "Unexpected argument '" + std::string(1, arg[i]) + "'!"); NNHardAssert(j->second == Type::Bool, "Multiple options for a single - must be flags!"); m_data[arg[i]].type = Type::Bool; m_data[arg[i]].b = true; } opt = arg.back(); } auto i = m_expected.find(opt); NNHardAssert(i != m_expected.end(), "Unexpected argument '" + std::string(1, opt) + "'!"); m_data[opt].type = i->second; switch(i->second) { case Type::Bool: m_data[opt].b = true; break; case Type::Int: m_data[opt].i = args.popInt(); break; case Type::Double: m_data[opt].d = args.popDouble(); break; case Type::String: m_stringStorage.push_back(args.popString()); m_data[opt].i = m_stringStorage.size() - 1; break; } } if(m_helpOpt != '\0' && getFlag(m_helpOpt)) { printHelp(out); exit(0); } return *this; } const ArgsParser &printHelp(std::ostream &out = std::cout) const { out << std::left; std::map<std::string, Type> orderedOpts; for(auto &p : m_expected) { orderedOpts.emplace(optName(p.first), p.second); } for(auto &p : orderedOpts) { char opt; if(p.first.size() == 1) opt = p.first[0]; else opt = m_longToChar.at(p.first); std::string name; if(opt < 32) name = "--" + p.first; else { name = std::string("-") + opt; if(p.first.size() > 1) name += ",--" + p.first; } out << std::setw(25) << name; switch(p.second) { case Type::Bool: out << "Flag"; break; case Type::Int: out << "Int"; break; case Type::Double: out << "Double"; break; case Type::String: out << "String"; break; } auto d = m_data.find(opt); if(d != m_data.end()) { out << " [value = "; switch(d->second.type) { case Type::Bool: out << (d->second.b ? "true" : "false"); break; case Type::Int: out << d->second.i; break; case Type::Double: out << d->second.d; break; case Type::String: out << "\"" << m_stringStorage[d->second.i] << "\""; break; } out << "]"; } out << std::endl; } return *this; } const ArgsParser &printOpts(std::ostream &out = std::cout) const { out << std::left; std::map<std::string, Data> orderedOpts; for(auto &p : m_data) { orderedOpts.emplace(optName(p.first), p.second); } for(auto &p : orderedOpts) { out << std::setw(20) << p.first << "= "; switch(p.second.type) { case Type::Bool: out << p.second.b; break; case Type::Int: out << p.second.i; break; case Type::Double: out << p.second.d; break; case Type::String: out << m_stringStorage[p.second.i]; break; } out << std::endl; } return *this; } bool hasOpt(char opt) const { auto i = m_data.find(opt); return i != m_data.end(); } bool hasOpt(std::string longOpt) const { auto i = m_longToChar.find(longOpt); return i != m_longToChar.end() && hasOpt(i->second); } std::string optName(char opt) const { auto i = m_charToLong.find(opt); if(i != m_charToLong.end()) return i->second; else return std::string(1, opt); } bool getFlag(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::Bool, "Attempted to get an incompatible type!"); return m_data.at(opt).b; } bool getFlag(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getFlag(i->second); } int getInt(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::Int, "Attempted to get an incompatible type!"); return m_data.at(opt).i; } int getInt(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getInt(i->second); } double getDouble(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::Double, "Attempted to get an incompatible type!"); return m_data.at(opt).d; } double getDouble(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getDouble(i->second); } std::string getString(char opt) const { NNHardAssert(hasOpt(opt), "Attempted to get undefined option '" + optName(opt) + "'!"); NNHardAssert(m_data.at(opt).type == Type::String, "Attempted to get an incompatible type!"); return m_stringStorage[m_data.at(opt).i]; } std::string getString(std::string opt) const { auto i = m_longToChar.find(opt); NNHardAssert(i != m_longToChar.end(), "Attempted to get undefined option '" + opt + "'!"); return getString(i->second); } private: enum class Type { Bool, Int, Double, String }; struct Data { Type type; union { bool b; int i; double d; }; }; void addOpt(char opt, std::string longOpt) { NNHardAssert(m_expected.find(opt) == m_expected.end(), "Attempted to redefine '" + optName(opt) + "'!"); m_expected[opt] = Type::Bool; if(longOpt != "") { NNHardAssert(m_charToLong.find(opt) == m_charToLong.end(), "Attempted to redefine '" + optName(opt) + "'!"); m_longToChar[longOpt] = opt; m_charToLong[opt] = longOpt; } } char m_helpOpt, m_nextUnnamedOpt; std::unordered_map<char, Type> m_expected; std::unordered_map<char, Data> m_data; std::unordered_map<std::string, char> m_longToChar; std::unordered_map<char, std::string> m_charToLong; std::vector<std::string> m_stringStorage; }; } #endif <|endoftext|>
<commit_before>/** @file command.hpp * * RedisXX Command implementation * * For the full copyright and license information, please view the LICENSE file * that was distributed with this project source code. * */ #pragma once #include <string> #include <vector> #include <cstddef> #include <redisxx/type_traits.hpp> namespace redis { namespace priv { // ---------------------------------------------------------------------------- // API to enable stringification of common non-nested types // replace bad characters std::string stringify(std::string value) { // tba: escape '\r' and '\n' return value; } // convert arithmetic type template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type stringify(T value) { return std::to_string(value); } // ---------------------------------------------------------------------------- // API to apply protocol specifications to various types // map string to bulk string std::string protocolify(std::size_t& num, std::string const & value) { ++num; return '$' + std::to_string(value.size()) + "\r\n" + value + "\r\n"; } // map nullptr_t to null std::string protocolify(std::size_t& num, std::nullptr_t ptr) { ++num; return "$-1\r\n"; } // map numbers to bulk string template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type protocolify(std::size_t& num, T value) { auto tmp = std::to_string(value); ++num; return '$' + std::to_string(tmp.size()) + "\r\n" + tmp + "\r\n"; } // map each set to bulk strings template <typename T> typename std::enable_if<is_set<T>::value, std::string>::type protocolify(std::size_t& num, T const & value) { // <value0> <value1> ... std::string buffer; for (auto const & elem: value) { // handle each item as simple string auto const & tmp = stringify(elem); buffer += '$' + std::to_string(tmp.size()) + "\r\n" + tmp + "\r\n"; } num += value.size(); return buffer; } // map each map to bulk strings template <typename T> typename std::enable_if<is_map<T>::value, std::string>::type protocolify(std::size_t& num, T const & value) { // <key0> <value0> <key1> <value1> ... std::string buffer; for (auto const & pair: value) { // handle each key and value as simple strings auto const & tmp_1 = stringify(pair.first); auto const & tmp_2 = stringify(pair.second); buffer += '$' + std::to_string(tmp_1.size()) + "\r\n" + tmp_1 + "\r\n" + '$' + std::to_string(tmp_2.size()) + "\r\n" + tmp_2 + "\r\n"; } num += value.size() * 2u; return buffer; } // map each sequence to bulk strings template <typename T> typename std::enable_if<is_sequence<T>::value, std::string>::type protocolify(std::size_t& num, T const & value) { // <value0> <value1> ... std::string buffer; for (auto const & elem: value) { // handle each item as simple string auto const & tmp = stringify(elem); buffer += '$' + std::to_string(tmp.size()) + "\r\n" + tmp + "\r\n"; } num += value.size(); return buffer; } // ---------------------------------------------------------------------------- // API to dump various types according to the RESP // base definition of each command template <typename... Tail> struct Dump; // recursive definition of each command template <typename Head, typename... Tail> struct Dump<Head, Tail...> { static inline void process(std::string& out, std::size_t& num, Head&& head, Tail&& ...tail) { // push head to array out += protocolify(num, std::forward<Head>(head)); // process tail Dump<Tail...>::process(out, num, std::forward<Tail>(tail)...); } }; // recursion base case of each command template <> struct Dump<> { static inline void process(std::string& out, std::size_t& num) { // nothing left to append return; } }; } // ::priv // ---------------------------------------------------------------------------- /// Public pipeline class class CommandList; /// Public command class class Command { friend class CommandList; template <typename T> friend Command& operator<<(Command& cmd, T&& value); friend bool operator==(Command const & lhs, Command const & rhs); friend bool operator!=(Command const & lhs, Command const & rhs); private: std::string buffer; // preformatted bulk strings std::size_t num_bulks; // number of bulk strings public: /// Construct a new command /** * The ctor can handle a variadic list of arguments and dumps them * according to RESP. Passing arguments of multiple types is supported * here. But keep in mind that each argument is handled as an atomic. * So "GET foo" as one argument will not cause getting they key 'foo'. * Instead pass two arguments "GET" and "foo". * Supported types are: primitive types (int, float etc.), std::string, * std::vector<>, std::list<>, std::(unordered_)map<> and * std::(unordered_)set<> of those supported types. * Remember that no nested types (such as a set of sequences) are * allowed here. * * @param ...args variadic list of arguments */ template <typename ...Args> Command(Args&& ...args) : buffer{} , num_bulks{0} { priv::Dump<Args...>::process(buffer, num_bulks, std::forward<Args>(args)...); } /// Return internal buffer /** * This method can be used to const-access the command buffer. The * returned string already contains the leading '*' etc., so it is * completly RESP-compliant, so it's ready to be sent. * * @return non-reference to the internal buffer. */ inline std::string operator*() const { return "*" + std::to_string(num_bulks) + "\r\n" + buffer; } inline void clear() { buffer.clear(); num_bulks = 0u; } }; /// Append another value to the command /** * This method appends a value of a generic type to the given command. The * given argument is dumped according to RESP. But keep in mind that each * argument is handled as an atomic. So "GET foo" as one argument will not * cause getting they key 'foo'. Instead call this method twice: first with * "GET" and the second time with "foo". * supported types are the same as used for the ctor of `Command`: * primitive types (int, float etc.), std::string, std::vector<>, std::list<>, * std::(unordered_)map<> and std::(unordered_)set<> of those supported types. * Remember that no nested types (such as a set of sequences) are allowed here. * * @param cmd Command to append the argument to * @param value Value to append to the command * @param return The given command. */ template <typename T> Command& operator<<(Command& cmd, T&& value) { priv::Dump<T>::process(cmd.buffer, cmd.num_bulks, std::forward<T>(value)); return cmd; } bool operator==(Command const & lhs, Command const & rhs) { return (lhs.buffer == rhs.buffer && lhs.num_bulks == rhs.num_bulks); } bool operator!=(Command const & lhs, Command const & rhs) { return (lhs.buffer == rhs.buffer || lhs.num_bulks == rhs.num_bulks); } // ---------------------------------------------------------------------------- enum class BatchType { Pipeline, Transaction }; class CommandList: private std::vector<Command> { friend CommandList& operator<<(CommandList& list, Command const & cmd); using Parent = std::vector<Command>; private: BatchType type; public: CommandList(BatchType type=BatchType::Transaction) : Parent{} , type{type} { } inline BatchType getBatchType() const { return type; } inline void setBatchType(BatchType type) { this->type = type; } inline std::string operator*() const { std::string out; std::size_t num_bulks = 0u; // start command batch switch (type) { case BatchType::Pipeline: out = '*'; for (auto const & cmd: *this) { num_bulks += cmd.num_bulks; } out += std::to_string(num_bulks) + "\r\n"; break; case BatchType::Transaction: out = "$5\r\nMULTI\r\n"; break; } // concatenate commands for (auto const & cmd: *this) { out += cmd.buffer; } // finish command batch switch (type) { case BatchType::Pipeline: // nothing to do break; case BatchType::Transaction: out += "$4\r\nEXEC\r\n"; break; } return out; } // add some methods of std::vector to the public interface using Parent::reserve; using Parent::size; using Parent::capacity; using Parent::clear; using Parent::empty; using Parent::at; }; CommandList& operator<<(CommandList& list, Command const & cmd) { list.push_back(cmd); return list; } } // ::redis <commit_msg>[Command/CommandList] Documentation completed<commit_after>/** @file command.hpp * * RedisXX Command implementation * * For the full copyright and license information, please view the LICENSE file * that was distributed with this project source code. * */ #pragma once #include <string> #include <vector> #include <cstddef> #include <redisxx/type_traits.hpp> namespace redis { namespace priv { // ---------------------------------------------------------------------------- // API to enable stringification of common non-nested types // replace bad characters std::string stringify(std::string value) { // tba: escape '\r' and '\n' return value; } // convert arithmetic type template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type stringify(T value) { return std::to_string(value); } // ---------------------------------------------------------------------------- // API to apply protocol specifications to various types // map string to bulk string std::string protocolify(std::size_t& num, std::string const & value) { ++num; return '$' + std::to_string(value.size()) + "\r\n" + value + "\r\n"; } // map nullptr_t to null std::string protocolify(std::size_t& num, std::nullptr_t ptr) { ++num; return "$-1\r\n"; } // map numbers to bulk string template <typename T> typename std::enable_if<std::is_arithmetic<T>::value, std::string>::type protocolify(std::size_t& num, T value) { auto tmp = std::to_string(value); ++num; return '$' + std::to_string(tmp.size()) + "\r\n" + tmp + "\r\n"; } // map each set to bulk strings template <typename T> typename std::enable_if<is_set<T>::value, std::string>::type protocolify(std::size_t& num, T const & value) { // <value0> <value1> ... std::string buffer; for (auto const & elem: value) { // handle each item as simple string auto const & tmp = stringify(elem); buffer += '$' + std::to_string(tmp.size()) + "\r\n" + tmp + "\r\n"; } num += value.size(); return buffer; } // map each map to bulk strings template <typename T> typename std::enable_if<is_map<T>::value, std::string>::type protocolify(std::size_t& num, T const & value) { // <key0> <value0> <key1> <value1> ... std::string buffer; for (auto const & pair: value) { // handle each key and value as simple strings auto const & tmp_1 = stringify(pair.first); auto const & tmp_2 = stringify(pair.second); buffer += '$' + std::to_string(tmp_1.size()) + "\r\n" + tmp_1 + "\r\n" + '$' + std::to_string(tmp_2.size()) + "\r\n" + tmp_2 + "\r\n"; } num += value.size() * 2u; return buffer; } // map each sequence to bulk strings template <typename T> typename std::enable_if<is_sequence<T>::value, std::string>::type protocolify(std::size_t& num, T const & value) { // <value0> <value1> ... std::string buffer; for (auto const & elem: value) { // handle each item as simple string auto const & tmp = stringify(elem); buffer += '$' + std::to_string(tmp.size()) + "\r\n" + tmp + "\r\n"; } num += value.size(); return buffer; } // ---------------------------------------------------------------------------- // API to dump various types according to the RESP // base definition of each command template <typename... Tail> struct Dump; // recursive definition of each command template <typename Head, typename... Tail> struct Dump<Head, Tail...> { static inline void process(std::string& out, std::size_t& num, Head&& head, Tail&& ...tail) { // push head to array out += protocolify(num, std::forward<Head>(head)); // process tail Dump<Tail...>::process(out, num, std::forward<Tail>(tail)...); } }; // recursion base case of each command template <> struct Dump<> { static inline void process(std::string& out, std::size_t& num) { // nothing left to append return; } }; } // ::priv // ---------------------------------------------------------------------------- /// CommandList class CommandList; /// Command /** * This class is used to create RESP-compliant request strings. Each command * instance can hold multiple arguments that belong to one redis command. * Note that each argument that is passed to the Command needs to be atomic. * So "GET foo" as single argument will NOT work to GET the key "foo". Instead * use two arguments "GET" and "foo. * Different argument types are supported: primitive types (such as int, float * and similar), std::string, std::vector<>, std::list<>, std::map<>, * std::unordered_map<>, std::set<>, std::unordered_set<>. Note that those * containers can only contain primitive types or string. Nested types (e.g. * a set of sequences) are NOT supported. * * Example usage: * @code * // using primitive types / strings * redis::Command cmd{"SET"}; * cmd << "my_key" << 5; * // means: "SET my_key 5" * * // using a vector * redis::Command cmd2; * std::vector<int> numbers = {1, 3, 17, 12, 5}; * cmd2 << "SADD" << "ids" << numbers; * // means: "SADD ids 1 3 17 12 5" * * // using a map * redis::Command cmd3{"HMSET"}; * std::map<std::string, std::string> data; * data["name"] = "max" * data["passwd"] = "secret" * cmd3 << "user:5" << data; * // means: "HMSET user:5 name max passwd secret" * @endcode */ class Command { friend class CommandList; template <typename T> friend Command& operator<<(Command& cmd, T&& value); friend bool operator==(Command const & lhs, Command const & rhs); friend bool operator!=(Command const & lhs, Command const & rhs); private: std::string buffer; // preformatted bulk strings std::size_t num_bulks; // number of bulk strings public: /// Construct a new command /** * The ctor can handle a variadic list of arguments and dumps them * according to RESP. Passing arguments of multiple types is supported * here. * * @param ...args variadic list of arguments */ template <typename ...Args> Command(Args&& ...args) : buffer{} , num_bulks{0} { priv::Dump<Args...>::process(buffer, num_bulks, std::forward<Args>(args)...); } /// Return RESP-compliant request string /** * This method can be used to create a RESP-compliant request. * * @return A ready-to-send request string */ inline std::string operator*() const { return "*" + std::to_string(num_bulks) + "\r\n" + buffer; } /// Clear internal buffer /** * This method can be used to clear the internal command buffer. Note * that all added values will be lost. */ inline void clear() { buffer.clear(); num_bulks = 0u; } }; /// Append another value to the command /** * This method appends a value of a generic type to the given command. The * given argument is dumped according to RESP. * * @param cmd Command to append the argument to * @param value Value to append to the command * @param return The given command. */ template <typename T> Command& operator<<(Command& cmd, T&& value) { priv::Dump<T>::process(cmd.buffer, cmd.num_bulks, std::forward<T>(value)); return cmd; } /// Check whether to commands equal /** * Two commands equal if their buffers (and the number of bulk strings inside * the buffers) equal. * * @param lhs Left-hand-side command object * @param rhs Right-hand-side command object * @return True if both objects equal */ bool operator==(Command const & lhs, Command const & rhs) { return (lhs.buffer == rhs.buffer && lhs.num_bulks == rhs.num_bulks); } /// Check whether to commands do not equal /** * Two commands do not equal if their buffers (or the number of bulk strings * inside the buffers) do not equal. * * @param lhs Left-hand-side command object * @param rhs Right-hand-side command object * @return True if both objects do not equal */ bool operator!=(Command const & lhs, Command const & rhs) { return (lhs.num_bulks == rhs.num_bulks || lhs.buffer == rhs.buffer); } // ---------------------------------------------------------------------------- /// Type of batch request used for a CommandList enum class BatchType { Pipeline, Transaction }; /// CommandList /** * A command list can be used to process multiple commands at once using * pipelining or a transaction. This "batch type" can be modified during * runtime. * Only command objects can be appended to a command list. So the list can be * used to produce a larger RESP-compliant request (either pipelined or using * a transaction). * A limited set of functionality is inherited from std::vector to allow more * detailed access to the underlying container. * * Example usage: * @code * redis::CommandList list; * list.reserve(5); * for (int i = 0; i < 5; ++i) { * list << redis::Command{"HGETALL", "user:" + std::to_string(i)}; * } * * redis::CommandList list2; * list2.setBatchType(redis::BatchType::Transaction); * redis::Command cmd{"PING"}; * list2 << cmd << cmd << cmd; * list2.at(1) = redis::Command{"INFO"}; * @endcode */ class CommandList: private std::vector<Command> { friend CommandList& operator<<(CommandList& list, Command const & cmd); using Parent = std::vector<Command>; private: BatchType type; // determines type of request batch public: /// Construct a new command list /** * This will construct a new command list. Specifying the batch type * is optional. The default batch type is a transaction. * * @param type BatchType to use for creating a request string */ CommandList(BatchType type=BatchType::Transaction) : Parent{} , type{type} { } /// Returns current batch type /** * Returns whether the current batch type is pipelining or transaction. * * @return Current BatchType */ inline BatchType getBatchType() const { return type; } /// Set batch type to the given value /** * Sets the batch type to the pipelining or transaction. * * @param type BatchType to use from now on */ inline void setBatchType(BatchType type) { this->type = type; } /// Return RESP-compliant request string /** * This method can be used to create a RESP-compliant request. * Depending on the currently set batch type, this string will be a * pipeline- or transaction-based request. * * @return A ready-to-send request string */ inline std::string operator*() const { std::string out; std::size_t num_bulks = 0u; // start command batch switch (type) { case BatchType::Pipeline: out = '*'; for (auto const & cmd: *this) { num_bulks += cmd.num_bulks; } out += std::to_string(num_bulks) + "\r\n"; break; case BatchType::Transaction: out = "$5\r\nMULTI\r\n"; break; } // concatenate commands for (auto const & cmd: *this) { out += cmd.buffer; } // finish command batch switch (type) { case BatchType::Pipeline: // nothing to do break; case BatchType::Transaction: out += "$4\r\nEXEC\r\n"; break; } return out; } // add some methods of std::vector to the public interface using Parent::reserve; using Parent::size; using Parent::capacity; using Parent::clear; using Parent::empty; using Parent::at; }; /// Append another command to the list /** * This method appends a command to the given command list without invalidating * the RESP-compliance of the command list. * * @param list CommandList to append the command to * @param cmd Command to append to the list * @param return The given command list. */ CommandList& operator<<(CommandList& list, Command const & cmd) { list.push_back(cmd); return list; } } // ::redis <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <string> #include "reflection_binding.hpp" namespace shadow { struct type_info { const char* name; std::size_t size; address_of_signature address_of_bind_point; }; inline bool operator==(const type_info& lhs, const type_info& rhs) { return std::string(lhs.name) == std::string(rhs.name); } struct constructor_info { std::size_t type_index; std::size_t num_parameters; const std::size_t* parameter_type_indices; constructor_binding_signature bind_point; }; inline bool operator==(const constructor_info& lhs, const constructor_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct conversion_info { std::size_t from_type_index; std::size_t to_type_index; conversion_binding_signature bind_point; }; inline bool operator==(const conversion_info& lhs, const conversion_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct free_function_info { const char* name; std::size_t return_type_index; std::size_t num_parameters; const std::size_t* parameter_type_indices; const bool* parameter_pointer_flags; free_function_binding_signature bind_point; }; inline bool operator==(const free_function_info& lhs, const free_function_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct member_function_info { const char* name; std::size_t object_type_index; std::size_t return_type_index; std::size_t num_parameters; const std::size_t* parameter_type_indices; member_function_binding_signature bind_point; }; inline bool operator==(const member_function_info& lhs, const member_function_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct member_variable_info { const char* name; std::size_t object_type_index; std::size_t type_index; member_variable_get_binding_signature get_bind_point; member_variable_set_binding_signature set_bind_point; }; inline bool operator==(const member_variable_info& lhs, const member_variable_info& rhs) { return lhs.get_bind_point == rhs.get_bind_point && lhs.set_bind_point == rhs.set_bind_point; } struct string_serialization_info { std::size_t type_index; string_serialization_signature serialize_bind_point; string_deserialization_signature deserialize_bind_point; }; inline bool operator==(const string_serialization_info& lhs, const string_serialization_info& rhs) { return lhs.serialize_bind_point == rhs.serialize_bind_point && lhs.deserialize_bind_point == rhs.deserialize_bind_point; } } // namespace shadow <commit_msg>Add dereference_signature field to type_info. modified: include/reflection_info.hpp<commit_after>#pragma once #include <cstddef> #include <string> #include "reflection_binding.hpp" namespace shadow { struct type_info { const char* name; std::size_t size; address_of_signature address_of_bind_point; dereference_signature dereference_bind_point; }; inline bool operator==(const type_info& lhs, const type_info& rhs) { return std::string(lhs.name) == std::string(rhs.name); } struct constructor_info { std::size_t type_index; std::size_t num_parameters; const std::size_t* parameter_type_indices; constructor_binding_signature bind_point; }; inline bool operator==(const constructor_info& lhs, const constructor_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct conversion_info { std::size_t from_type_index; std::size_t to_type_index; conversion_binding_signature bind_point; }; inline bool operator==(const conversion_info& lhs, const conversion_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct free_function_info { const char* name; std::size_t return_type_index; std::size_t num_parameters; const std::size_t* parameter_type_indices; const bool* parameter_pointer_flags; free_function_binding_signature bind_point; }; inline bool operator==(const free_function_info& lhs, const free_function_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct member_function_info { const char* name; std::size_t object_type_index; std::size_t return_type_index; std::size_t num_parameters; const std::size_t* parameter_type_indices; member_function_binding_signature bind_point; }; inline bool operator==(const member_function_info& lhs, const member_function_info& rhs) { return lhs.bind_point == rhs.bind_point; } struct member_variable_info { const char* name; std::size_t object_type_index; std::size_t type_index; member_variable_get_binding_signature get_bind_point; member_variable_set_binding_signature set_bind_point; }; inline bool operator==(const member_variable_info& lhs, const member_variable_info& rhs) { return lhs.get_bind_point == rhs.get_bind_point && lhs.set_bind_point == rhs.set_bind_point; } struct string_serialization_info { std::size_t type_index; string_serialization_signature serialize_bind_point; string_deserialization_signature deserialize_bind_point; }; inline bool operator==(const string_serialization_info& lhs, const string_serialization_info& rhs) { return lhs.serialize_bind_point == rhs.serialize_bind_point && lhs.deserialize_bind_point == rhs.deserialize_bind_point; } } // namespace shadow <|endoftext|>
<commit_before>#pragma once #include <limits> #include <cmath> #include <array> #include <vector> #include "zmsg_cmm.hpp" namespace zmsg { /** * \brief typedefs */ #if 0 int{8|16|32}_t uint{8|16|32}_t float double #endif } /* namespace zmsg */ /** * \brief bool image */ struct bool_img { bool_img() : width(0) , height(0) , data() { } void init(void) { this->width = 0; this->height = 0; this->data.clear(); } uint16_t width; uint16_t height; std::vector<bool> data; public: ZMSG_PU(width, height, data) }; /** * \brief img fiber defect description */ typedef uint32_t ifd_t; static constexpr ifd_t ifd_end_crude = 0x1; static constexpr ifd_t ifd_horizontal_angle = 0x2; static constexpr ifd_t ifd_vertical_angle = 0x4; static constexpr ifd_t ifd_cant_identify = 0x80000000; static constexpr ifd_t ifd_all = std::numeric_limits<ifd_t>::max(); inline void ifd_clr(ifd_t & dst, const ifd_t src) { dst &= ~src; } inline void ifd_set(ifd_t & dst, const ifd_t src) { dst |= src; } typedef struct ifd_line final { ifd_t dbmp; /// \note all angles' unit are degree double h_angle; double v_angle; int32_t wrap_diameter; /// unit: pixel ifd_line() : dbmp(0) , h_angle(0) , v_angle(0) , wrap_diameter(0) { } void init(void) { this->dbmp = 0; this->h_angle = 0; this->v_angle = 0; this->wrap_diameter = 0; } operator bool() const { return dbmp; } bool check(ifd_t msk) const { return (dbmp & msk); } public: ZMSG_PU(dbmp, h_angle, v_angle, wrap_diameter) } ifd_line_t; typedef struct img_defects final { ifd_line_t yzl; ifd_line_t yzr; ifd_line_t xzl; ifd_line_t xzr; double yz_hangle_intersect; double xz_hangle_intersect; /// the image contain missed corner info bool_img yz_img; bool_img xz_img; img_defects() : yzl(), yzr(), xzl(), xzr() , yz_hangle_intersect(0) , xz_hangle_intersect(0) , yz_img(), xz_img() { } void init(void) { this->yzl.init(); this->yzr.init(); this->xzl.init(); this->xzr.init(); this->yz_hangle_intersect = 0; this->xz_hangle_intersect = 0; this->yz_img.init(); this->xz_img.init(); } operator bool() const { return (yzl || yzr || xzl || xzr); } bool check(ifd_t msk) const { return (yzl.check(msk) || yzr.check(msk) || xzl.check(msk) || xzr.check(msk)); } double left_cut_angle(void) const { return std::max(yzl.v_angle, xzl.v_angle); } double right_cut_angle(void) const { return std::max(yzr.v_angle, xzr.v_angle); } public: ZMSG_PU(yzl, yzr, xzl, xzr, yz_hangle_intersect, xz_hangle_intersect, yz_img, xz_img) } img_defects_t; /** * \biref fiber recognition infomation */ typedef struct final { uint32_t wrap_diameter; /// unit: nm uint32_t core_diameter; /// unit: nm public: ZMSG_PU(wrap_diameter, core_diameter) } fiber_rec_info_t; /** * \brief service fs state * \note all states mean enter this state. */ enum class svc_fs_state_t : uint16_t { fs_reseting, fs_idle, fs_ready, fs_entering, fs_push1, fs_calibrating, fs_waiting, fs_clring, fs_focusing, fs_defect_detecting, fs_push2, fs_pause1, fs_precise_calibrating, fs_pause2, fs_pre_splice, fs_discharge1, fs_discharge2, fs_discharge_manual, fs_loss_estimating, fs_tension_testing, fs_finished, fs_wait_reset, }; /** * \brief service heat state */ enum class svc_heat_state_t : uint16_t { heat_idle, heat_ready, heat_ascending, heat_stabling, heat_descending, }; /** * \brief motor id */ enum motorId_t : uint8_t { LZ = 0, // left z RZ, // right z X, // x Y, // y NUM, // total number }; /** * \brief fusion splice display mode */ enum class fs_display_mode_t : uint8_t { X = 0x0, /// only x Y, /// only y TB, /// top <-> bottom LR, /// left <-> right NO, /// no max, /// number }; /** * \brief fusion splicer related error code */ enum class fs_err_t : uint8_t { success, cover_openned, no_fiber, fiber_defect, fiber_cross_over, /// sw or hw problem fiber_off_center, img_brightness, abnormal_arc, tense_test_fail, fiber_broken, quit_midway, push_timeout, calibrate_timeout, reset_timeout, arc_time_zero, ignore, revise1_mag, revise2_mag, focus_x, focus_y, img_process_error, system_error, fiber_offside, /// user should replace fiber cmos_exposure, loss_estimate, }; /** * \brief led id */ enum ledId_t : uint8_t { CMOS_X = 0x0, CMOS_Y, LED_NUM, }; /** * \brief discharge_data_t, used for discharge revising */ typedef struct { struct { double x; /// unit: volt double y; /// unit: um public: ZMSG_PU(x, y) } p[2]; double temp; /// unit: degree centigrade double pressure; /// unit: bar bool empty() const { return (p[0].x == p[1].x); } void clear() { p[0].x = p[1].x = 0; p[0].y = p[1].y = 0; temp = 0; pressure = 0; } public: ZMSG_PU(p, temp, pressure) } discharge_data_t; /** * \brief rt_revise_data_t, used for real time discharge revising */ typedef struct { int32_t rt_x_exposure; int32_t rt_y_exposure; double rt_revise_a3; double rt_revise_a2; double rt_revise_a1; double rt_revise_a0; double rt_offset_auto; double rt_offset_cal; bool empty() const { return (rt_x_exposure <= 0 || rt_y_exposure <= 0); } void clear() { rt_x_exposure = 0; rt_y_exposure = 0; rt_revise_a3 = rt_revise_a2 = rt_revise_a1 = rt_revise_a0 = 0; rt_offset_auto = rt_offset_cal = 0; } public: ZMSG_PU(rt_x_exposure, rt_y_exposure, rt_revise_a3, rt_revise_a2, rt_revise_a1, rt_revise_a0, rt_offset_auto, rt_offset_cal) } rt_revise_data_t; enum class fiber_t : uint8_t { sm = 0x0, ds, nz, mm, max, }; /** * \brief fusion splice pattern */ enum class fs_pattern_t : uint8_t { automatic = 0x0, calibrate, normal, special, }; /** * \brief loss estimate mode */ enum class loss_estimate_mode_t : uint8_t { off = 0x0, accurate, core, cladding, }; /** * \brief shrinkabletube length */ enum class shrink_tube_t : uint8_t { len_20mm = 0x0, len_40mm, len_60mm, }; /** * \brief fiber align method */ enum class align_method_t : uint8_t { fine = 0x0, clad, core, manual, }; <commit_msg>add failed to fs_err_t<commit_after>#pragma once #include <limits> #include <cmath> #include <array> #include <vector> #include "zmsg_cmm.hpp" namespace zmsg { /** * \brief typedefs */ #if 0 int{8|16|32}_t uint{8|16|32}_t float double #endif } /* namespace zmsg */ /** * \brief bool image */ struct bool_img { bool_img() : width(0) , height(0) , data() { } void init(void) { this->width = 0; this->height = 0; this->data.clear(); } uint16_t width; uint16_t height; std::vector<bool> data; public: ZMSG_PU(width, height, data) }; /** * \brief img fiber defect description */ typedef uint32_t ifd_t; static constexpr ifd_t ifd_end_crude = 0x1; static constexpr ifd_t ifd_horizontal_angle = 0x2; static constexpr ifd_t ifd_vertical_angle = 0x4; static constexpr ifd_t ifd_cant_identify = 0x80000000; static constexpr ifd_t ifd_all = std::numeric_limits<ifd_t>::max(); inline void ifd_clr(ifd_t & dst, const ifd_t src) { dst &= ~src; } inline void ifd_set(ifd_t & dst, const ifd_t src) { dst |= src; } typedef struct ifd_line final { ifd_t dbmp; /// \note all angles' unit are degree double h_angle; double v_angle; int32_t wrap_diameter; /// unit: pixel ifd_line() : dbmp(0) , h_angle(0) , v_angle(0) , wrap_diameter(0) { } void init(void) { this->dbmp = 0; this->h_angle = 0; this->v_angle = 0; this->wrap_diameter = 0; } operator bool() const { return dbmp; } bool check(ifd_t msk) const { return (dbmp & msk); } public: ZMSG_PU(dbmp, h_angle, v_angle, wrap_diameter) } ifd_line_t; typedef struct img_defects final { ifd_line_t yzl; ifd_line_t yzr; ifd_line_t xzl; ifd_line_t xzr; double yz_hangle_intersect; double xz_hangle_intersect; /// the image contain missed corner info bool_img yz_img; bool_img xz_img; img_defects() : yzl(), yzr(), xzl(), xzr() , yz_hangle_intersect(0) , xz_hangle_intersect(0) , yz_img(), xz_img() { } void init(void) { this->yzl.init(); this->yzr.init(); this->xzl.init(); this->xzr.init(); this->yz_hangle_intersect = 0; this->xz_hangle_intersect = 0; this->yz_img.init(); this->xz_img.init(); } operator bool() const { return (yzl || yzr || xzl || xzr); } bool check(ifd_t msk) const { return (yzl.check(msk) || yzr.check(msk) || xzl.check(msk) || xzr.check(msk)); } double left_cut_angle(void) const { return std::max(yzl.v_angle, xzl.v_angle); } double right_cut_angle(void) const { return std::max(yzr.v_angle, xzr.v_angle); } public: ZMSG_PU(yzl, yzr, xzl, xzr, yz_hangle_intersect, xz_hangle_intersect, yz_img, xz_img) } img_defects_t; /** * \biref fiber recognition infomation */ typedef struct final { uint32_t wrap_diameter; /// unit: nm uint32_t core_diameter; /// unit: nm public: ZMSG_PU(wrap_diameter, core_diameter) } fiber_rec_info_t; /** * \brief service fs state * \note all states mean enter this state. */ enum class svc_fs_state_t : uint16_t { fs_reseting, fs_idle, fs_ready, fs_entering, fs_push1, fs_calibrating, fs_waiting, fs_clring, fs_focusing, fs_defect_detecting, fs_push2, fs_pause1, fs_precise_calibrating, fs_pause2, fs_pre_splice, fs_discharge1, fs_discharge2, fs_discharge_manual, fs_loss_estimating, fs_tension_testing, fs_finished, fs_wait_reset, }; /** * \brief service heat state */ enum class svc_heat_state_t : uint16_t { heat_idle, heat_ready, heat_ascending, heat_stabling, heat_descending, }; /** * \brief motor id */ enum motorId_t : uint8_t { LZ = 0, // left z RZ, // right z X, // x Y, // y NUM, // total number }; /** * \brief fusion splice display mode */ enum class fs_display_mode_t : uint8_t { X = 0x0, /// only x Y, /// only y TB, /// top <-> bottom LR, /// left <-> right NO, /// no max, /// number }; /** * \brief fusion splicer related error code */ enum class fs_err_t : uint8_t { success, cover_openned, no_fiber, fiber_defect, fiber_cross_over, /// sw or hw problem fiber_off_center, img_brightness, abnormal_arc, tense_test_fail, fiber_broken, quit_midway, push_timeout, calibrate_timeout, reset_timeout, arc_time_zero, ignore, revise1_mag, revise2_mag, focus_x, focus_y, img_process_error, system_error, fiber_offside, /// user should replace fiber cmos_exposure, loss_estimate, failed }; /** * \brief led id */ enum ledId_t : uint8_t { CMOS_X = 0x0, CMOS_Y, LED_NUM, }; /** * \brief discharge_data_t, used for discharge revising */ typedef struct { struct { double x; /// unit: volt double y; /// unit: um public: ZMSG_PU(x, y) } p[2]; double temp; /// unit: degree centigrade double pressure; /// unit: bar bool empty() const { return (p[0].x == p[1].x); } void clear() { p[0].x = p[1].x = 0; p[0].y = p[1].y = 0; temp = 0; pressure = 0; } public: ZMSG_PU(p, temp, pressure) } discharge_data_t; /** * \brief rt_revise_data_t, used for real time discharge revising */ typedef struct { int32_t rt_x_exposure; int32_t rt_y_exposure; double rt_revise_a3; double rt_revise_a2; double rt_revise_a1; double rt_revise_a0; double rt_offset_auto; double rt_offset_cal; bool empty() const { return (rt_x_exposure <= 0 || rt_y_exposure <= 0); } void clear() { rt_x_exposure = 0; rt_y_exposure = 0; rt_revise_a3 = rt_revise_a2 = rt_revise_a1 = rt_revise_a0 = 0; rt_offset_auto = rt_offset_cal = 0; } public: ZMSG_PU(rt_x_exposure, rt_y_exposure, rt_revise_a3, rt_revise_a2, rt_revise_a1, rt_revise_a0, rt_offset_auto, rt_offset_cal) } rt_revise_data_t; enum class fiber_t : uint8_t { sm = 0x0, ds, nz, mm, max, }; /** * \brief fusion splice pattern */ enum class fs_pattern_t : uint8_t { automatic = 0x0, calibrate, normal, special, }; /** * \brief loss estimate mode */ enum class loss_estimate_mode_t : uint8_t { off = 0x0, accurate, core, cladding, }; /** * \brief shrinkabletube length */ enum class shrink_tube_t : uint8_t { len_20mm = 0x0, len_40mm, len_60mm, }; /** * \brief fiber align method */ enum class align_method_t : uint8_t { fine = 0x0, clad, core, manual, }; <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #ifndef PEGTL_TRACE_HH #define PEGTL_TRACE_HH #include <iostream> #include "parse.hh" #include "normal.hh" #include "nothing.hh" #include "position_info.hh" #include "internal/demangle.hh" namespace pegtl { template< typename Rule > struct tracer : normal< Rule > { template< typename Input, typename ... States > static void start( const Input & in, States && ... ) { std::cerr << position_info( in ) << " start " << internal::demangle< Rule >() << std::endl; } template< typename Input, typename ... States > static void success( const Input & in, States && ... ) { std::cerr << position_info( in ) << " success " << internal::demangle< Rule >() << std::endl; } template< typename Input, typename ... States > static void failure( const Input & in, States && ... ) { std::cerr << position_info( in ) << " failure " << internal::demangle< Rule >() << std::endl; } }; template< typename Rule, template< typename ... > class Action = nothing, typename ... Args > bool trace( Args && ... args ) { return parse< Rule, Action, tracer >( std::forward< Args >( args ) ... ); } } // pegtl #endif <commit_msg>Added trace_input<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #ifndef PEGTL_TRACE_HH #define PEGTL_TRACE_HH #include <iostream> #include "parse.hh" #include "normal.hh" #include "nothing.hh" #include "position_info.hh" #include "internal/demangle.hh" namespace pegtl { template< typename Rule > struct tracer : normal< Rule > { template< typename Input, typename ... States > static void start( const Input & in, States && ... ) { std::cerr << position_info( in ) << " start " << internal::demangle< Rule >() << std::endl; } template< typename Input, typename ... States > static void success( const Input & in, States && ... ) { std::cerr << position_info( in ) << " success " << internal::demangle< Rule >() << std::endl; } template< typename Input, typename ... States > static void failure( const Input & in, States && ... ) { std::cerr << position_info( in ) << " failure " << internal::demangle< Rule >() << std::endl; } }; template< typename Rule, template< typename ... > class Action = nothing, typename Input, typename ... States > bool trace_input( Input & in, States && ... st ) { return parse_input< Rule, Action, tracer >( in, st ... ); } template< typename Rule, template< typename ... > class Action = nothing, typename ... Args > bool trace( Args && ... args ) { return parse< Rule, Action, tracer >( args ... ); } } // pegtl #endif <|endoftext|>
<commit_before>#include "chainerx/native/native_device.h" #include <cmath> #include <cstdint> #include <type_traits> #ifdef CHAINERX_ENABLE_BLAS #include <cblas.h> #endif // CHAINERX_ENABLE_BLAS #include "chainerx/array.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/indexable_array.h" #include "chainerx/macro.h" #include "chainerx/native/data_type.h" #include "chainerx/native/elementwise.h" #include "chainerx/routines/creation.h" #include "chainerx/shape.h" namespace chainerx { namespace native { #ifdef CHAINERX_ENABLE_BLAS namespace { // Dispatch gemm routines based on the element type T template <typename T> struct GemmImpl; template <> struct GemmImpl<float> { template <typename... Args> void operator()(Args&&... args) const { cblas_sgemm(std::forward<Args>(args)...); } }; template <> struct GemmImpl<double> { template <typename... Args> void operator()(Args&&... args) const { cblas_dgemm(std::forward<Args>(args)...); } }; struct GemmInputLayout { int64_t ld = 0; CBLAS_TRANSPOSE trans = CblasNoTrans; // Configure leading dimension and transposition accordingly, and makes the array C contiguous if necessary Array Configure(const Array& a) { CHAINERX_ASSERT(a.ndim() == 2); // Row-major // Note that this condition is slightly relaxed than Array::IsContiguous() which requires // a.strides()[0] == a.GetItemSize() * a.shape()[1] if (a.strides()[1] == a.GetItemSize() && a.strides()[0] / a.GetItemSize() >= a.shape()[1] && a.strides()[0] % a.GetItemSize() == 0) { ld = a.strides()[0] / a.GetItemSize(); return a; } // Column-major if (a.strides()[0] == a.GetItemSize() && a.strides()[1] / a.GetItemSize() >= a.shape()[0] && a.strides()[1] % a.GetItemSize() == 0) { ld = a.strides()[1] / a.GetItemSize(); trans = CblasTrans; return a; } // Force row-major contiguous ld = a.shape()[1]; return internal::AsContiguous(a); } }; void Gemm(const Array& a, const Array& b, const Array& out) { CHAINERX_ASSERT(a.ndim() == 2); CHAINERX_ASSERT(b.ndim() == 2); CHAINERX_ASSERT(out.ndim() == 2); CHAINERX_ASSERT(out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64); int64_t m = a.shape()[0]; int64_t k = a.shape()[1]; int64_t n = b.shape()[1]; CHAINERX_ASSERT(b.shape()[0] == k); CHAINERX_ASSERT(out.shape()[0] == m); CHAINERX_ASSERT(out.shape()[1] == n); bool is_out_contiguous = out.IsContiguous(); Array out_contiguous = is_out_contiguous ? out : EmptyLike(out, out.device()); auto gemm_impl = [&](auto pt) { using T = typename decltype(pt)::type; GemmInputLayout a_layout; GemmInputLayout b_layout; Array a_config = a_layout.Configure(a); Array b_config = b_layout.Configure(b); const T one = 1; const T zero = 0; const T* a_ptr = static_cast<const T*>(internal::GetRawOffsetData(a_config)); const T* b_ptr = static_cast<const T*>(internal::GetRawOffsetData(b_config)); T* out_ptr = static_cast<T*>(internal::GetRawOffsetData(out_contiguous)); GemmImpl<T>{}( CblasRowMajor, a_layout.trans, b_layout.trans, m, n, k, one, a_ptr, a_layout.ld, b_ptr, b_layout.ld, zero, out_ptr, n); }; if (a.dtype() == Dtype::kFloat32) { gemm_impl(PrimitiveType<float>{}); } else { CHAINERX_ASSERT(a.dtype() == Dtype::kFloat64); gemm_impl(PrimitiveType<double>{}); } if (!is_out_contiguous) { out.device().Copy(out_contiguous, out); } } } // namespace #endif // CHAINERX_ENABLE_BLAS namespace { template <typename T> T MultiplyAdd(T x, T y, T z) { return x * y + z; } float MultiplyAdd(Float16 x, Float16 y, float z) { return std::fmaf(static_cast<float>(x), static_cast<float>(y), z); } float MultiplyAdd(float x, float y, float z) { return std::fmaf(x, y, z); } double MultiplyAdd(double x, double y, double z) { return std::fma(x, y, z); } } // namespace void NativeDevice::Dot(const Array& a, const Array& b, const Array& out) { CheckDevicesCompatible(a, b, out); // TODO(sonots): Support ndim >= 2 if (a.ndim() != 2 || b.ndim() != 2 || out.ndim() != 2) { throw DimensionError{"ChainerX dot supports only 2-dimensional arrays."}; } #ifdef CHAINERX_ENABLE_BLAS if (out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64) { Gemm(a, b, out); return; } if (out.dtype() == Dtype::kFloat16) { Array a32 = a.AsType(Dtype::kFloat32, false); Array b32 = b.AsType(Dtype::kFloat32, false); Array acc = out.AsType(Dtype::kFloat32); Gemm(a32, b32, acc); out.Fill(0); out += acc.AsType(Dtype::kFloat16); return; } #endif // CHAINERX_ENABLE_BLAS VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T, 2> a_iarray{a}; IndexableArray<const T, 2> b_iarray{b}; IndexableArray<T, 2> out_iarray{out}; int64_t m = a.shape()[0]; int64_t k = a.shape()[1]; int64_t n = b.shape()[1]; CHAINERX_ASSERT(b.shape()[0] == k); CHAINERX_ASSERT(out.shape()[0] == m); CHAINERX_ASSERT(out.shape()[1] == n); using AccT = typename std::conditional<std::is_same<T, Float16>{}, float, T>::type; constexpr auto acc_dtype = PrimitiveType<AccT>::kDtype; Array acc = out.AsType(acc_dtype, false); acc.Fill(0); IndexableArray<AccT, 2> acc_iarray{acc}; for (int64_t i = 0; i < m; ++i) { for (int64_t l = 0; l < k; ++l) { int64_t a_i_l[] = {i, l}; T a_value = native_internal::StorageToDataType<const T>(a_iarray[a_i_l]); for (int64_t j = 0; j < n; ++j) { int64_t acc_i_j[] = {i, j}; int64_t b_l_j[] = {l, j}; T b_value = native_internal::StorageToDataType<const T>(b_iarray[b_l_j]); AccT& acc_value = native_internal::StorageToDataType<AccT>(acc_iarray[acc_i_j]); acc_value = MultiplyAdd(a_value, b_value, acc_value); } } } if (!std::is_same<T, AccT>{}) { for (int64_t i = 0; i < m; ++i) { for (int64_t j = 0; j < n; ++j) { int64_t i_j[] = {i, j}; AccT acc_value = native_internal::StorageToDataType<AccT>(acc_iarray[i_j]); T& out_value = native_internal::StorageToDataType<T>(out_iarray[i_j]); out_value = static_cast<T>(acc_value); } } } }); } } // namespace native } // namespace chainerx <commit_msg>Add TODO<commit_after>#include "chainerx/native/native_device.h" #include <cmath> #include <cstdint> #include <type_traits> #ifdef CHAINERX_ENABLE_BLAS #include <cblas.h> #endif // CHAINERX_ENABLE_BLAS #include "chainerx/array.h" #include "chainerx/device.h" #include "chainerx/dtype.h" #include "chainerx/indexable_array.h" #include "chainerx/macro.h" #include "chainerx/native/data_type.h" #include "chainerx/native/elementwise.h" #include "chainerx/routines/creation.h" #include "chainerx/shape.h" namespace chainerx { namespace native { #ifdef CHAINERX_ENABLE_BLAS namespace { // Dispatch gemm routines based on the element type T template <typename T> struct GemmImpl; template <> struct GemmImpl<float> { template <typename... Args> void operator()(Args&&... args) const { cblas_sgemm(std::forward<Args>(args)...); } }; template <> struct GemmImpl<double> { template <typename... Args> void operator()(Args&&... args) const { cblas_dgemm(std::forward<Args>(args)...); } }; struct GemmInputLayout { int64_t ld = 0; CBLAS_TRANSPOSE trans = CblasNoTrans; // Configure leading dimension and transposition accordingly, and makes the array C contiguous if necessary Array Configure(const Array& a) { CHAINERX_ASSERT(a.ndim() == 2); // Row-major // Note that this condition is slightly relaxed than Array::IsContiguous() which requires // a.strides()[0] == a.GetItemSize() * a.shape()[1] if (a.strides()[1] == a.GetItemSize() && a.strides()[0] / a.GetItemSize() >= a.shape()[1] && a.strides()[0] % a.GetItemSize() == 0) { ld = a.strides()[0] / a.GetItemSize(); return a; } // Column-major if (a.strides()[0] == a.GetItemSize() && a.strides()[1] / a.GetItemSize() >= a.shape()[0] && a.strides()[1] % a.GetItemSize() == 0) { ld = a.strides()[1] / a.GetItemSize(); trans = CblasTrans; return a; } // Force row-major contiguous ld = a.shape()[1]; return internal::AsContiguous(a); } }; void Gemm(const Array& a, const Array& b, const Array& out) { CHAINERX_ASSERT(a.ndim() == 2); CHAINERX_ASSERT(b.ndim() == 2); CHAINERX_ASSERT(out.ndim() == 2); CHAINERX_ASSERT(out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64); int64_t m = a.shape()[0]; int64_t k = a.shape()[1]; int64_t n = b.shape()[1]; CHAINERX_ASSERT(b.shape()[0] == k); CHAINERX_ASSERT(out.shape()[0] == m); CHAINERX_ASSERT(out.shape()[1] == n); bool is_out_contiguous = out.IsContiguous(); Array out_contiguous = is_out_contiguous ? out : EmptyLike(out, out.device()); auto gemm_impl = [&](auto pt) { using T = typename decltype(pt)::type; GemmInputLayout a_layout; GemmInputLayout b_layout; Array a_config = a_layout.Configure(a); Array b_config = b_layout.Configure(b); const T one = 1; const T zero = 0; const T* a_ptr = static_cast<const T*>(internal::GetRawOffsetData(a_config)); const T* b_ptr = static_cast<const T*>(internal::GetRawOffsetData(b_config)); T* out_ptr = static_cast<T*>(internal::GetRawOffsetData(out_contiguous)); GemmImpl<T>{}( CblasRowMajor, a_layout.trans, b_layout.trans, m, n, k, one, a_ptr, a_layout.ld, b_ptr, b_layout.ld, zero, out_ptr, n); }; if (a.dtype() == Dtype::kFloat32) { gemm_impl(PrimitiveType<float>{}); } else { CHAINERX_ASSERT(a.dtype() == Dtype::kFloat64); gemm_impl(PrimitiveType<double>{}); } if (!is_out_contiguous) { out.device().Copy(out_contiguous, out); } } } // namespace #endif // CHAINERX_ENABLE_BLAS namespace { template <typename T> T MultiplyAdd(T x, T y, T z) { return x * y + z; } float MultiplyAdd(Float16 x, Float16 y, float z) { return std::fmaf(static_cast<float>(x), static_cast<float>(y), z); } float MultiplyAdd(float x, float y, float z) { return std::fmaf(x, y, z); } double MultiplyAdd(double x, double y, double z) { return std::fma(x, y, z); } } // namespace void NativeDevice::Dot(const Array& a, const Array& b, const Array& out) { CheckDevicesCompatible(a, b, out); // TODO(sonots): Support ndim >= 2 if (a.ndim() != 2 || b.ndim() != 2 || out.ndim() != 2) { throw DimensionError{"ChainerX dot supports only 2-dimensional arrays."}; } #ifdef CHAINERX_ENABLE_BLAS if (out.dtype() == Dtype::kFloat32 || out.dtype() == Dtype::kFloat64) { Gemm(a, b, out); return; } if (out.dtype() == Dtype::kFloat16) { Array a32 = a.AsType(Dtype::kFloat32, false); Array b32 = b.AsType(Dtype::kFloat32, false); Array acc = out.AsType(Dtype::kFloat32); Gemm(a32, b32, acc); // TODO(gwtnb): Replace Fill(0) and += with CopyTo when CopyTo is added out.Fill(0); out += acc.AsType(Dtype::kFloat16); return; } #endif // CHAINERX_ENABLE_BLAS VisitDtype(out.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; IndexableArray<const T, 2> a_iarray{a}; IndexableArray<const T, 2> b_iarray{b}; IndexableArray<T, 2> out_iarray{out}; int64_t m = a.shape()[0]; int64_t k = a.shape()[1]; int64_t n = b.shape()[1]; CHAINERX_ASSERT(b.shape()[0] == k); CHAINERX_ASSERT(out.shape()[0] == m); CHAINERX_ASSERT(out.shape()[1] == n); using AccT = typename std::conditional<std::is_same<T, Float16>{}, float, T>::type; constexpr auto acc_dtype = PrimitiveType<AccT>::kDtype; Array acc = out.AsType(acc_dtype, false); acc.Fill(0); IndexableArray<AccT, 2> acc_iarray{acc}; for (int64_t i = 0; i < m; ++i) { for (int64_t l = 0; l < k; ++l) { int64_t a_i_l[] = {i, l}; T a_value = native_internal::StorageToDataType<const T>(a_iarray[a_i_l]); for (int64_t j = 0; j < n; ++j) { int64_t acc_i_j[] = {i, j}; int64_t b_l_j[] = {l, j}; T b_value = native_internal::StorageToDataType<const T>(b_iarray[b_l_j]); AccT& acc_value = native_internal::StorageToDataType<AccT>(acc_iarray[acc_i_j]); acc_value = MultiplyAdd(a_value, b_value, acc_value); } } } if (!std::is_same<T, AccT>{}) { for (int64_t i = 0; i < m; ++i) { for (int64_t j = 0; j < n; ++j) { int64_t i_j[] = {i, j}; AccT acc_value = native_internal::StorageToDataType<AccT>(acc_iarray[i_j]); T& out_value = native_internal::StorageToDataType<T>(out_iarray[i_j]); out_value = static_cast<T>(acc_value); } } } }); } } // namespace native } // namespace chainerx <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: managedframe.cpp // Purpose: Implementation of wxExManagedFrame class. // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <list> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/wxcrt.h> #include <wx/extension/managedframe.h> #include <wx/extension/defs.h> #include <wx/extension/ex.h> #include <wx/extension/frd.h> #include <wx/extension/stc.h> #include <wx/extension/toolbar.h> #include <wx/extension/util.h> #if wxUSE_GUI // Support class. // Offers a text ctrl related to a ex object. class wxExExTextCtrl: public wxTextCtrl { public: /// Constructor. Creates empty control. wxExExTextCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* prefix, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); /// Destructor. ~wxExExTextCtrl(); /// Returns ex component. wxExEx* GetEx() {return m_ex;}; /// Sets ex component. void SetEx(wxExEx* ex); protected: void OnChar(wxKeyEvent& event); void OnCommand(wxCommandEvent& event); void OnEnter(wxCommandEvent& event); void OnFocus(wxFocusEvent& event); private: void Handle(wxKeyEvent& event); bool IsCalc() const {return m_Prefix->GetLabel() == "=";}; bool IsCommand() const {return m_Prefix->GetLabel() == ":";}; bool IsFind() const {return m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?";}; wxExManagedFrame* m_Frame; wxExEx* m_ex; wxStaticText* m_Prefix; bool m_Controlr; bool m_UserInput; wxString m_Command; std::list < wxString > m_Commands; std::list < wxString >::const_iterator m_CommandsIterator; std::list < wxString > m_Finds; std::list < wxString >::const_iterator m_FindsIterator; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame) EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand) EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand) EVT_UPDATE_UI_RANGE( ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI) END_EVENT_TABLE() wxExManagedFrame::wxExManagedFrame(wxWindow* parent, wxWindowID id, const wxString& title, long style) : wxExFrame(parent, id, title, style) { m_Manager.SetManagedWindow(this); m_ToolBar = new wxExToolBar(this); m_ToolBar->AddControls(); AddToolBarPane(m_ToolBar, "TOOLBAR", _("Toolbar")); AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar")); AddToolBarPane(CreateExPanel(), "VIBAR"); m_Manager.Update(); } wxExManagedFrame::~wxExManagedFrame() { m_Manager.UnInit(); } bool wxExManagedFrame::AddToolBarPane( wxWindow* window, const wxString& name, const wxString& caption) { wxAuiPaneInfo pane; pane .LeftDockable(false) .RightDockable(false) .Name(name); // If the toolbar has a caption, it is at the top, // otherwise fixed at the bottom and initially hidden. if (!caption.empty()) { pane .Top() .ToolbarPane() .Caption(caption); // Initially hide findbar as well. if (name == "FINDBAR") { pane.Hide(); } } else { pane .Bottom() .CloseButton(false) .Hide() .DockFixed(true) .Movable(false) .Row(10) .CaptionVisible(false); } return m_Manager.AddPane(window, pane); } bool wxExManagedFrame::AllowClose(wxWindowID id, wxWindow* page) { // The page will be closed, so do not update find focus now. SetFindFocus(NULL); return true; } wxPanel* wxExManagedFrame::CreateExPanel() { // A ex panel starts with small static text for : or /, then // comes the ex ctrl for getting user input. wxPanel* panel = new wxPanel(this); m_exTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString); m_exTextCtrl = new wxExExTextCtrl(panel, this, m_exTextPrefix, wxID_ANY); wxFlexGridSizer* sizer = new wxFlexGridSizer(2); sizer->AddGrowableCol(1); sizer->Add(m_exTextPrefix, wxSizerFlags().Expand()); sizer->Add(m_exTextCtrl, wxSizerFlags().Expand()); panel->SetSizerAndFit(sizer); return panel; } void wxExManagedFrame::GetExCommand(wxExEx* ex, const wxString& command) { m_exTextPrefix->SetLabel(command); m_exTextCtrl->SetEx(ex); m_Manager.GetPane("VIBAR").Show(); m_Manager.Update(); } void wxExManagedFrame::HideExBar(bool set_focus) { if (m_Manager.GetPane("VIBAR").IsShown()) { m_Manager.GetPane("VIBAR").Hide(); m_Manager.Update(); if (set_focus && m_exTextCtrl != NULL && m_exTextCtrl->GetEx() != NULL) { m_exTextCtrl->GetEx()->GetSTC()->SetFocus(); } } } void wxExManagedFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break; case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break; default: wxFAIL; } } void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_FINDBAR: event.Check(m_Manager.GetPane("FINDBAR").IsShown()); break; case ID_VIEW_TOOLBAR: event.Check(m_Manager.GetPane("TOOLBAR").IsShown()); break; default: wxFAIL; } } void wxExManagedFrame::OnNotebook(wxWindowID id, wxWindow* page) { SetFindFocus(page); } void wxExManagedFrame::ShowExMessage(const wxString& text) { HideExBar(); if (GetStatusBar() != NULL && GetStatusBar()->IsShown()) { GetStatusBar()->SetStatusText(text); } else { wxLogMessage(text); } } void wxExManagedFrame::SyncCloseAll(wxWindowID id) { SetFindFocus(NULL); } bool wxExManagedFrame::TogglePane(const wxString& pane) { wxAuiPaneInfo& info = m_Manager.GetPane(pane); if (!info.IsOk()) { return false; } info.IsShown() ? info.Hide(): info.Show(); m_Manager.Update(); return true; } // Implementation of support class. BEGIN_EVENT_TABLE(wxExExTextCtrl, wxTextCtrl) EVT_CHAR(wxExExTextCtrl::OnChar) EVT_SET_FOCUS(wxExExTextCtrl::OnFocus) EVT_TEXT(wxID_ANY, wxExExTextCtrl::OnCommand) EVT_TEXT_ENTER(wxID_ANY, wxExExTextCtrl::OnEnter) END_EVENT_TABLE() wxExExTextCtrl::wxExExTextCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* prefix, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER) , m_Frame(frame) , m_ex(NULL) , m_Controlr(false) , m_UserInput(false) , m_Prefix(prefix) { wxStringTokenizer tkz(wxConfigBase::Get()->Read("excommand"), wxExGetFieldSeparator()); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } m_CommandsIterator = m_Commands.begin(); m_Finds = wxExFindReplaceData::Get()->GetFindStrings(); m_FindsIterator = m_Finds.begin(); // Next does not work. //AutoCompleteFileNames(); } wxExExTextCtrl::~wxExExTextCtrl() { const int commandsSaveInConfig = 25; wxString values; int items = 0; for ( std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < commandsSaveInConfig; ++it) { values += *it + wxExGetFieldSeparator(); items++; } wxConfigBase::Get()->Write("excommand", values); } void wxExExTextCtrl::Handle(wxKeyEvent& event) { bool skip = true; if (event.GetKeyCode() != WXK_RETURN) { if ( IsCalc() && event.GetUnicodeKey() != (wxChar)WXK_NONE && m_Controlr) { skip = false; const wxChar c = event.GetUnicodeKey(); switch (c) { case '\"': AppendText(wxExClipboardGet()); break; default: if ( m_ex != NULL && !m_ex->GetMacros().GetRegister(c).empty()) { AppendText(m_ex->GetMacros().GetRegister(c)); break; } } } m_UserInput = true; } if (skip) { event.Skip(); } m_Controlr = false; } void wxExExTextCtrl::OnChar(wxKeyEvent& event) { if (event.GetUnicodeKey() != (wxChar)WXK_NONE) { if (event.GetKeyCode() == WXK_BACK) { m_Command = m_Command.Truncate(m_Command.size() - 1); } else { m_Command += event.GetUnicodeKey(); } } const int key = event.GetKeyCode(); switch (key) { case WXK_UP: case WXK_DOWN: if (IsCommand()) { wxExSetTextCtrlValue(this, key, m_Commands, m_CommandsIterator); } else if (IsFind()) { wxExSetTextCtrlValue(this, key, m_Finds, m_FindsIterator); } break; case WXK_ESCAPE: if (m_ex != NULL) { m_ex->GetSTC()->PositionRestore(); } m_Frame->HideExBar(); m_Controlr = false; m_UserInput = false; break; case WXK_CONTROL_R: m_Controlr = true; break; default: Handle(event); } } void wxExExTextCtrl::OnCommand(wxCommandEvent& event) { event.Skip(); if ( m_UserInput && m_ex != NULL && IsFind()) { m_ex->GetSTC()->PositionRestore(); m_ex->GetSTC()->FindNext( GetValue(), wxSTC_FIND_REGEXP | wxFR_MATCHCASE, m_Prefix->GetLabel() == "/"); } } void wxExExTextCtrl::OnEnter(wxCommandEvent& event) { if (m_ex == NULL) { return; } if (GetValue().empty()) { m_Frame->HideExBar(); return; } if (IsCommand()) { if (m_ex->Command(m_Prefix->GetLabel() + GetValue())) { const bool set_focus = (GetValue() == "n" || GetValue() == "prev"); m_Commands.remove(GetValue()); m_Commands.push_front(GetValue()); m_CommandsIterator = m_Commands.begin(); m_Frame->HideExBar(!set_focus); } } else if (IsFind()) { m_Finds.remove(GetValue()); m_Finds.push_front(GetValue()); m_FindsIterator = m_Finds.begin(); wxExFindReplaceData::Get()->SetFindString(GetValue()); if (m_UserInput) { m_ex->GetMacros().Record(m_Prefix->GetLabel() + GetValue()); } else { m_ex->Command(m_Prefix->GetLabel() + GetValue()); } m_Frame->HideExBar(); } else if (IsCalc()) { if (m_UserInput) { m_ex->GetMacros().Record(m_Prefix->GetLabel() + m_Command); } m_ex->Command(m_Prefix->GetLabel() + GetValue()); m_Frame->HideExBar(); } else { wxFAIL; } } void wxExExTextCtrl::OnFocus(wxFocusEvent& event) { event.Skip(); if (m_ex != NULL) { m_ex->GetSTC()->PositionSave(); } } void wxExExTextCtrl::SetEx(wxExEx* ex) { m_Command.clear(); m_Controlr = false; m_UserInput = false; m_ex = ex; if (IsFind()) { if (!m_ex->GetSTC()->GetSelectedText().empty()) { SetValue(m_ex->GetSTC()->GetSelectedText()); wxExFindReplaceData::Get()->SetFindString(GetValue()); } else { SetValue(wxExFindReplaceData::Get()->GetFindString()); } } else if (IsCommand()) { if (m_Commands.begin() != m_Commands.end()) { SetValue(*m_Commands.begin()); } } else if (IsCalc()) { SetValue(wxEmptyString); } Show(); SelectAll(); SetFocus(); } #endif // wxUSE_GUI <commit_msg>made toolbar resizable<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: managedframe.cpp // Purpose: Implementation of wxExManagedFrame class. // Author: Anton van Wezenbeek // Copyright: (c) 2013 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <list> #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/config.h> #include <wx/tokenzr.h> #include <wx/wxcrt.h> #include <wx/extension/managedframe.h> #include <wx/extension/defs.h> #include <wx/extension/ex.h> #include <wx/extension/frd.h> #include <wx/extension/stc.h> #include <wx/extension/toolbar.h> #include <wx/extension/util.h> #if wxUSE_GUI // Support class. // Offers a text ctrl related to a ex object. class wxExExTextCtrl: public wxTextCtrl { public: /// Constructor. Creates empty control. wxExExTextCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* prefix, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize); /// Destructor. ~wxExExTextCtrl(); /// Returns ex component. wxExEx* GetEx() {return m_ex;}; /// Sets ex component. void SetEx(wxExEx* ex); protected: void OnChar(wxKeyEvent& event); void OnCommand(wxCommandEvent& event); void OnEnter(wxCommandEvent& event); void OnFocus(wxFocusEvent& event); private: void Handle(wxKeyEvent& event); bool IsCalc() const {return m_Prefix->GetLabel() == "=";}; bool IsCommand() const {return m_Prefix->GetLabel() == ":";}; bool IsFind() const {return m_Prefix->GetLabel() == "/" || m_Prefix->GetLabel() == "?";}; wxExManagedFrame* m_Frame; wxExEx* m_ex; wxStaticText* m_Prefix; bool m_Controlr; bool m_UserInput; wxString m_Command; std::list < wxString > m_Commands; std::list < wxString >::const_iterator m_CommandsIterator; std::list < wxString > m_Finds; std::list < wxString >::const_iterator m_FindsIterator; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxExManagedFrame, wxExFrame) EVT_MENU(wxID_PREFERENCES, wxExManagedFrame::OnCommand) EVT_MENU_RANGE(ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnCommand) EVT_UPDATE_UI_RANGE( ID_VIEW_LOWEST, ID_VIEW_HIGHEST, wxExManagedFrame::OnUpdateUI) END_EVENT_TABLE() wxExManagedFrame::wxExManagedFrame(wxWindow* parent, wxWindowID id, const wxString& title, long style) : wxExFrame(parent, id, title, style) { m_Manager.SetManagedWindow(this); m_ToolBar = new wxExToolBar(this); m_ToolBar->AddControls(); AddToolBarPane(m_ToolBar, "TOOLBAR", _("Toolbar")); AddToolBarPane(new wxExFindToolBar(this), "FINDBAR", _("Findbar")); AddToolBarPane(CreateExPanel(), "VIBAR"); m_Manager.Update(); } wxExManagedFrame::~wxExManagedFrame() { m_Manager.UnInit(); } bool wxExManagedFrame::AddToolBarPane( wxWindow* window, const wxString& name, const wxString& caption) { wxAuiPaneInfo pane; pane .LeftDockable(false) .RightDockable(false) .Name(name); // If the toolbar has a caption, it is at the top, // otherwise fixed at the bottom and initially hidden. if (!caption.empty()) { pane .Top() .ToolbarPane() .Resizable() .Caption(caption); // Initially hide findbar as well. if (name == "FINDBAR") { pane.Hide(); } } else { pane .Bottom() .CloseButton(false) .Hide() .DockFixed(true) .Movable(false) .Row(10) .CaptionVisible(false); } return m_Manager.AddPane(window, pane); } bool wxExManagedFrame::AllowClose(wxWindowID id, wxWindow* page) { // The page will be closed, so do not update find focus now. SetFindFocus(NULL); return true; } wxPanel* wxExManagedFrame::CreateExPanel() { // A ex panel starts with small static text for : or /, then // comes the ex ctrl for getting user input. wxPanel* panel = new wxPanel(this); m_exTextPrefix = new wxStaticText(panel, wxID_ANY, wxEmptyString); m_exTextCtrl = new wxExExTextCtrl(panel, this, m_exTextPrefix, wxID_ANY); wxFlexGridSizer* sizer = new wxFlexGridSizer(2); sizer->AddGrowableCol(1); sizer->Add(m_exTextPrefix, wxSizerFlags().Expand()); sizer->Add(m_exTextCtrl, wxSizerFlags().Expand()); panel->SetSizerAndFit(sizer); return panel; } void wxExManagedFrame::GetExCommand(wxExEx* ex, const wxString& command) { m_exTextPrefix->SetLabel(command); m_exTextCtrl->SetEx(ex); m_Manager.GetPane("VIBAR").Show(); m_Manager.Update(); } void wxExManagedFrame::HideExBar(bool set_focus) { if (m_Manager.GetPane("VIBAR").IsShown()) { m_Manager.GetPane("VIBAR").Hide(); m_Manager.Update(); if (set_focus && m_exTextCtrl != NULL && m_exTextCtrl->GetEx() != NULL) { m_exTextCtrl->GetEx()->GetSTC()->SetFocus(); } } } void wxExManagedFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case ID_VIEW_FINDBAR: TogglePane("FINDBAR"); break; case ID_VIEW_TOOLBAR: TogglePane("TOOLBAR"); break; default: wxFAIL; } } void wxExManagedFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case ID_VIEW_FINDBAR: event.Check(m_Manager.GetPane("FINDBAR").IsShown()); break; case ID_VIEW_TOOLBAR: event.Check(m_Manager.GetPane("TOOLBAR").IsShown()); break; default: wxFAIL; } } void wxExManagedFrame::OnNotebook(wxWindowID id, wxWindow* page) { SetFindFocus(page); } void wxExManagedFrame::ShowExMessage(const wxString& text) { HideExBar(); if (GetStatusBar() != NULL && GetStatusBar()->IsShown()) { GetStatusBar()->SetStatusText(text); } else { wxLogMessage(text); } } void wxExManagedFrame::SyncCloseAll(wxWindowID id) { SetFindFocus(NULL); } bool wxExManagedFrame::TogglePane(const wxString& pane) { wxAuiPaneInfo& info = m_Manager.GetPane(pane); if (!info.IsOk()) { return false; } info.IsShown() ? info.Hide(): info.Show(); m_Manager.Update(); return true; } // Implementation of support class. BEGIN_EVENT_TABLE(wxExExTextCtrl, wxTextCtrl) EVT_CHAR(wxExExTextCtrl::OnChar) EVT_SET_FOCUS(wxExExTextCtrl::OnFocus) EVT_TEXT(wxID_ANY, wxExExTextCtrl::OnCommand) EVT_TEXT_ENTER(wxID_ANY, wxExExTextCtrl::OnEnter) END_EVENT_TABLE() wxExExTextCtrl::wxExExTextCtrl( wxWindow* parent, wxExManagedFrame* frame, wxStaticText* prefix, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxTextCtrl(parent, id, wxEmptyString, pos, size, wxTE_PROCESS_ENTER) , m_Frame(frame) , m_ex(NULL) , m_Controlr(false) , m_UserInput(false) , m_Prefix(prefix) { wxStringTokenizer tkz(wxConfigBase::Get()->Read("excommand"), wxExGetFieldSeparator()); while (tkz.HasMoreTokens()) { const wxString val = tkz.GetNextToken(); m_Commands.push_front(val); } m_CommandsIterator = m_Commands.begin(); m_Finds = wxExFindReplaceData::Get()->GetFindStrings(); m_FindsIterator = m_Finds.begin(); // Next does not work. //AutoCompleteFileNames(); } wxExExTextCtrl::~wxExExTextCtrl() { const int commandsSaveInConfig = 25; wxString values; int items = 0; for ( std::list < wxString >::reverse_iterator it = m_Commands.rbegin(); it != m_Commands.rend() && items < commandsSaveInConfig; ++it) { values += *it + wxExGetFieldSeparator(); items++; } wxConfigBase::Get()->Write("excommand", values); } void wxExExTextCtrl::Handle(wxKeyEvent& event) { bool skip = true; if (event.GetKeyCode() != WXK_RETURN) { if ( IsCalc() && event.GetUnicodeKey() != (wxChar)WXK_NONE && m_Controlr) { skip = false; const wxChar c = event.GetUnicodeKey(); switch (c) { case '\"': AppendText(wxExClipboardGet()); break; default: if ( m_ex != NULL && !m_ex->GetMacros().GetRegister(c).empty()) { AppendText(m_ex->GetMacros().GetRegister(c)); break; } } } m_UserInput = true; } if (skip) { event.Skip(); } m_Controlr = false; } void wxExExTextCtrl::OnChar(wxKeyEvent& event) { if (event.GetUnicodeKey() != (wxChar)WXK_NONE) { if (event.GetKeyCode() == WXK_BACK) { m_Command = m_Command.Truncate(m_Command.size() - 1); } else { m_Command += event.GetUnicodeKey(); } } const int key = event.GetKeyCode(); switch (key) { case WXK_UP: case WXK_DOWN: if (IsCommand()) { wxExSetTextCtrlValue(this, key, m_Commands, m_CommandsIterator); } else if (IsFind()) { wxExSetTextCtrlValue(this, key, m_Finds, m_FindsIterator); } break; case WXK_ESCAPE: if (m_ex != NULL) { m_ex->GetSTC()->PositionRestore(); } m_Frame->HideExBar(); m_Controlr = false; m_UserInput = false; break; case WXK_CONTROL_R: m_Controlr = true; break; default: Handle(event); } } void wxExExTextCtrl::OnCommand(wxCommandEvent& event) { event.Skip(); if ( m_UserInput && m_ex != NULL && IsFind()) { m_ex->GetSTC()->PositionRestore(); m_ex->GetSTC()->FindNext( GetValue(), wxSTC_FIND_REGEXP | wxFR_MATCHCASE, m_Prefix->GetLabel() == "/"); } } void wxExExTextCtrl::OnEnter(wxCommandEvent& event) { if (m_ex == NULL) { return; } if (GetValue().empty()) { m_Frame->HideExBar(); return; } if (IsCommand()) { if (m_ex->Command(m_Prefix->GetLabel() + GetValue())) { const bool set_focus = (GetValue() == "n" || GetValue() == "prev"); m_Commands.remove(GetValue()); m_Commands.push_front(GetValue()); m_CommandsIterator = m_Commands.begin(); m_Frame->HideExBar(!set_focus); } } else if (IsFind()) { m_Finds.remove(GetValue()); m_Finds.push_front(GetValue()); m_FindsIterator = m_Finds.begin(); wxExFindReplaceData::Get()->SetFindString(GetValue()); if (m_UserInput) { m_ex->GetMacros().Record(m_Prefix->GetLabel() + GetValue()); } else { m_ex->Command(m_Prefix->GetLabel() + GetValue()); } m_Frame->HideExBar(); } else if (IsCalc()) { if (m_UserInput) { m_ex->GetMacros().Record(m_Prefix->GetLabel() + m_Command); } m_ex->Command(m_Prefix->GetLabel() + GetValue()); m_Frame->HideExBar(); } else { wxFAIL; } } void wxExExTextCtrl::OnFocus(wxFocusEvent& event) { event.Skip(); if (m_ex != NULL) { m_ex->GetSTC()->PositionSave(); } } void wxExExTextCtrl::SetEx(wxExEx* ex) { m_Command.clear(); m_Controlr = false; m_UserInput = false; m_ex = ex; if (IsFind()) { if (!m_ex->GetSTC()->GetSelectedText().empty()) { SetValue(m_ex->GetSTC()->GetSelectedText()); wxExFindReplaceData::Get()->SetFindString(GetValue()); } else { SetValue(wxExFindReplaceData::Get()->GetFindString()); } } else if (IsCommand()) { if (m_Commands.begin() != m_Commands.end()) { SetValue(*m_Commands.begin()); } } else if (IsCalc()) { SetValue(wxEmptyString); } Show(); SelectAll(); SetFocus(); } #endif // wxUSE_GUI <|endoftext|>
<commit_before><commit_msg>Remove unnecessary `#include` lines.<commit_after><|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #include <utility> #include <algorithm> #include <iostream> #include <fstream> #include <errno.h> #include <unistd.h> #include <assert.h> #include "../vowpalwabbit/vw.h" using namespace std; void usage(char *prog) { fprintf(stderr, "usage: %s [-b <2|4|8|...|32>] [-v] <blacklist> <users> <items> <topN> <vwparams>\n", prog); exit(EXIT_FAILURE); } int b=16; int topn=10; int verbose=0; char * blacklistfilename = NULL; char * itemfilename = NULL; char * userfilename = NULL; char * vwparams = NULL; unsigned hash_ber(char *in, size_t len) { unsigned hashv = 0; while (len--) hashv = ((hashv) * 33) + *in++; return hashv; } unsigned hash_fnv(char *in, size_t len) { unsigned hashv = 2166136261UL; while(len--) hashv = (hashv * 16777619) ^ *in++; return hashv; } #define MASK(u,b) ( u & ((1UL << b) - 1)) #define NUM_HASHES 2 void get_hashv(char *in, size_t len, unsigned *out) { assert(NUM_HASHES==2); out[0] = MASK(hash_ber(in,len),b); out[1] = MASK(hash_fnv(in,len),b); } #define BIT_TEST(c,i) (c[i/8] & (1 << (i % 8))) #define BIT_SET(c,i) (c[i/8] |= (1 << (i % 8))) #define byte_len(b) (((1UL << b) / 8) + (((1UL << b) % 8) ? 1 : 0)) #define num_bits(b) (1UL << b) char *bf_new(unsigned b) { char *bf = (char*)calloc(1,byte_len(b)); return bf; } void bf_add(char *bf, char *line) { unsigned i, hashv[NUM_HASHES]; get_hashv(line,strlen(line),hashv); for(i=0;i<NUM_HASHES;i++) BIT_SET(bf,hashv[i]); } void bf_info(char *bf, FILE *f) { unsigned i, on=0; for(i=0; i<num_bits(b); i++) if (BIT_TEST(bf,i)) on++; fprintf(f, "%.2f%% saturation (%lu bits)\n", on*100.0/num_bits(b), num_bits(b)); } int bf_hit(char *bf, char *line) { unsigned i, hashv[NUM_HASHES]; get_hashv(line,strlen(line),hashv); for(i=0;i<NUM_HASHES;i++) { if (BIT_TEST(bf,hashv[i])==0) return 0; } return 1; } typedef pair<float, string> scored_example; vector<scored_example> scored_examples; bool compare_scored_examples (scored_example i,scored_example j) { return (i.first>j.first); }; int main(int argc, char *argv[]) { int opt; while ( (opt = getopt(argc, argv, "b:v+N:")) != -1) { switch (opt) { case 'N': topn = atoi(optarg); break; case 'b': b = atoi(optarg); break; case 'v': verbose++; break; default: usage(argv[0]); break; } } if (optind < argc) blacklistfilename=argv[optind++]; if (optind < argc) userfilename=argv[optind++]; if (optind < argc) itemfilename=argv[optind++]; if (optind < argc) vwparams=argv[optind++]; if (!blacklistfilename || !userfilename || !itemfilename || !vwparams) usage(argv[0]); FILE * fB; FILE * fU; FILE * fI; if((fB = fopen(blacklistfilename, "r")) == NULL) { fprintf(stderr,"can't open %s: %s\n", blacklistfilename, strerror(errno)); usage(argv[0]); } if((fU = fopen(userfilename, "r")) == NULL ) { fprintf(stderr,"can't open %s: %s\n", userfilename, strerror(errno)); usage(argv[0]); } if((fI = fopen(itemfilename, "r")) == NULL ) { fprintf(stderr,"can't open %s: %s\n", itemfilename, strerror(errno)); usage(argv[0]); } char * buf = NULL; char * u = NULL; char * i = NULL; size_t len = 0; ssize_t read; /* make the bloom filter */ if(verbose>0) fprintf(stderr, "loading blacklist into bloom filter...\n"); char *bf= bf_new(b); /* loop over the source file */ while ((read = getline(&buf,&len,fB)) != -1) { bf_add(bf,buf); } /* print saturation etc */ if (verbose) bf_info(bf,stderr); // INITIALIZE WITH WHATEVER YOU WOULD PUT ON THE VW COMMAND LINE if(verbose>0) fprintf(stderr, "initializing vw...\n"); vw model = VW::initialize(vwparams); char * estr = NULL; if(verbose>0) fprintf(stderr, "predicting...\n"); while ((read = getline(&u, &len, fU)) != -1) { u[strlen(u)-1] = 0; // chop rewind(fI); while ((read = getline(&i, &len, fI)) != -1) { free(estr); estr = strdup((string(u)+string(i)).c_str()); if (!bf_hit(bf,estr)) { example *ex = VW::read_example(model, estr); model.learn(ex); const string str(estr); scored_examples.push_back(make_pair(ex->final_prediction, str)); VW::finish_example(model, ex); } else { if(verbose>=2) fprintf(stderr,"skipping:\t%s\n", buf); } } sort(scored_examples.begin(), scored_examples.end(), compare_scored_examples); for(unsigned int i = 0;i<topn;i++) { cout << scored_examples.at(i).first << "\t" << scored_examples.at(i).second; } scored_examples.clear(); } VW::finish(model); fclose(fI); fclose(fU); exit(EXIT_SUCCESS); } <commit_msg>fix library build<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #include <utility> #include <algorithm> #include <iostream> #include <fstream> #include <errno.h> #include <unistd.h> #include <assert.h> #include "../vowpalwabbit/vw.h" using namespace std; void usage(char *prog) { fprintf(stderr, "usage: %s [-b <2|4|8|...|32>] [-v] <blacklist> <users> <items> <topN> <vwparams>\n", prog); exit(EXIT_FAILURE); } int b=16; int topn=10; int verbose=0; char * blacklistfilename = NULL; char * itemfilename = NULL; char * userfilename = NULL; char * vwparams = NULL; unsigned hash_ber(char *in, size_t len) { unsigned hashv = 0; while (len--) hashv = ((hashv) * 33) + *in++; return hashv; } unsigned hash_fnv(char *in, size_t len) { unsigned hashv = 2166136261UL; while(len--) hashv = (hashv * 16777619) ^ *in++; return hashv; } #define MASK(u,b) ( u & ((1UL << b) - 1)) #define NUM_HASHES 2 void get_hashv(char *in, size_t len, unsigned *out) { assert(NUM_HASHES==2); out[0] = MASK(hash_ber(in,len),b); out[1] = MASK(hash_fnv(in,len),b); } #define BIT_TEST(c,i) (c[i/8] & (1 << (i % 8))) #define BIT_SET(c,i) (c[i/8] |= (1 << (i % 8))) #define byte_len(b) (((1UL << b) / 8) + (((1UL << b) % 8) ? 1 : 0)) #define num_bits(b) (1UL << b) char *bf_new(unsigned b) { char *bf = (char*)calloc(1,byte_len(b)); return bf; } void bf_add(char *bf, char *line) { unsigned i, hashv[NUM_HASHES]; get_hashv(line,strlen(line),hashv); for(i=0;i<NUM_HASHES;i++) BIT_SET(bf,hashv[i]); } void bf_info(char *bf, FILE *f) { unsigned i, on=0; for(i=0; i<num_bits(b); i++) if (BIT_TEST(bf,i)) on++; fprintf(f, "%.2f%% saturation (%lu bits)\n", on*100.0/num_bits(b), num_bits(b)); } int bf_hit(char *bf, char *line) { unsigned i, hashv[NUM_HASHES]; get_hashv(line,strlen(line),hashv); for(i=0;i<NUM_HASHES;i++) { if (BIT_TEST(bf,hashv[i])==0) return 0; } return 1; } typedef pair<float, string> scored_example; vector<scored_example> scored_examples; bool compare_scored_examples (scored_example i,scored_example j) { return (i.first>j.first); }; int main(int argc, char *argv[]) { int opt; while ( (opt = getopt(argc, argv, "b:v+N:")) != -1) { switch (opt) { case 'N': topn = atoi(optarg); break; case 'b': b = atoi(optarg); break; case 'v': verbose++; break; default: usage(argv[0]); break; } } if (optind < argc) blacklistfilename=argv[optind++]; if (optind < argc) userfilename=argv[optind++]; if (optind < argc) itemfilename=argv[optind++]; if (optind < argc) vwparams=argv[optind++]; if (!blacklistfilename || !userfilename || !itemfilename || !vwparams) usage(argv[0]); FILE * fB; FILE * fU; FILE * fI; if((fB = fopen(blacklistfilename, "r")) == NULL) { fprintf(stderr,"can't open %s: %s\n", blacklistfilename, strerror(errno)); usage(argv[0]); } if((fU = fopen(userfilename, "r")) == NULL ) { fprintf(stderr,"can't open %s: %s\n", userfilename, strerror(errno)); usage(argv[0]); } if((fI = fopen(itemfilename, "r")) == NULL ) { fprintf(stderr,"can't open %s: %s\n", itemfilename, strerror(errno)); usage(argv[0]); } char * buf = NULL; char * u = NULL; char * i = NULL; size_t len = 0; ssize_t read; /* make the bloom filter */ if(verbose>0) fprintf(stderr, "loading blacklist into bloom filter...\n"); char *bf= bf_new(b); /* loop over the source file */ while ((read = getline(&buf,&len,fB)) != -1) { bf_add(bf,buf); } /* print saturation etc */ if (verbose) bf_info(bf,stderr); // INITIALIZE WITH WHATEVER YOU WOULD PUT ON THE VW COMMAND LINE if(verbose>0) fprintf(stderr, "initializing vw...\n"); vw* model = VW::initialize(vwparams); char * estr = NULL; if(verbose>0) fprintf(stderr, "predicting...\n"); while ((read = getline(&u, &len, fU)) != -1) { u[strlen(u)-1] = 0; // chop rewind(fI); while ((read = getline(&i, &len, fI)) != -1) { free(estr); estr = strdup((string(u)+string(i)).c_str()); if (!bf_hit(bf,estr)) { example *ex = VW::read_example(*model, estr); model->learn(ex); const string str(estr); scored_examples.push_back(make_pair(ex->final_prediction, str)); VW::finish_example(*model, ex); } else { if(verbose>=2) fprintf(stderr,"skipping:\t%s\n", buf); } } sort(scored_examples.begin(), scored_examples.end(), compare_scored_examples); for(unsigned int i = 0;i<topn;i++) { cout << scored_examples.at(i).first << "\t" << scored_examples.at(i).second; } scored_examples.clear(); } VW::finish(*model); fclose(fI); fclose(fU); exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkLevelWindowManager.h" #include "mitkStandaloneDataStorage.h" #include <mitkTestingMacros.h> #include <mitkIOUtil.h> #include <itkMersenneTwisterRandomVariateGenerator.h> #include "mitkRenderingModeProperty.h" #include <itkImageIterator.h> #include <mitkImageCast.h> #include <itkImageDuplicator.h> #include <itkComposeImageFilter.h> #include <itkEventObject.h> class mitkLevelWindowManagerTestClass { public: static void TestInstantiation() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); MITK_TEST_CONDITION_REQUIRED(manager.IsNotNull(),"Testing mitk::LevelWindowManager::New()"); } static void TestSetGetDataStorage() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); MITK_TEST_OUTPUT(<< "Creating DataStorage: "); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); bool success = true; try { manager->SetDataStorage(ds); } catch(std::exception e) { success = false; MITK_ERROR << "Exception: " << e.what(); } MITK_TEST_CONDITION_REQUIRED(success,"Testing mitk::LevelWindowManager SetDataStorage() "); MITK_TEST_CONDITION_REQUIRED(ds == manager->GetDataStorage(),"Testing mitk::LevelWindowManager GetDataStorage "); } static void TestMethodsWithInvalidParameters() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); bool success = false; mitk::LevelWindowProperty::Pointer levelWindowProperty = mitk::LevelWindowProperty::New(); try { manager->SetLevelWindowProperty(levelWindowProperty); } catch(mitk::Exception e) { success = true; } MITK_TEST_CONDITION(success,"Testing mitk::LevelWindowManager SetLevelWindowProperty with invalid parameter"); } static void TestOtherMethods() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); MITK_TEST_CONDITION(manager->isAutoTopMost(),"Testing mitk::LevelWindowManager isAutoTopMost"); // It is not clear what the following code is supposed to test. The expression in // the catch(...) block does have no effect, so success is always true. // Related bugs are 13894 and 13889 /* bool success = true; try { mitk::LevelWindow levelWindow = manager->GetLevelWindow(); manager->SetLevelWindow(levelWindow); } catch (...) { success == false; } MITK_TEST_CONDITION(success,"Testing mitk::LevelWindowManager GetLevelWindow() and SetLevelWindow()"); */ manager->SetAutoTopMostImage(true); MITK_TEST_CONDITION(manager->isAutoTopMost(),"Testing mitk::LevelWindowManager isAutoTopMost()"); } static void TestRemoveObserver(std::string testImageFile) { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::Image::Pointer image1 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node1 = mitk::DataNode::New(); node1->SetData(image1); mitk::Image::Pointer image2 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node2 = mitk::DataNode::New(); node2->SetData(image2); ds->Add(node1); ds->Add(node2); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 2, "Test if nodes have been added"); MITK_TEST_CONDITION_REQUIRED(static_cast<int>(manager->GetRelevantNodes()->size()) == manager->GetNumberOfObservers(), "Test if number of nodes is similar to number of observers"); mitk::Image::Pointer image3 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node3 = mitk::DataNode::New(); node3->SetData(image3); ds->Add(node3); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 3, "Test if another node have been added"); MITK_TEST_CONDITION_REQUIRED(static_cast<int>(manager->GetRelevantNodes()->size()) == manager->GetNumberOfObservers(), "Test if number of nodes is similar to number of observers"); ds->Remove(node1); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 2, "Deleted node 1 (test GetRelevantNodes())"); MITK_TEST_CONDITION_REQUIRED(manager->GetNumberOfObservers() == 2, "Deleted node 1 (test GetNumberOfObservers())"); ds->Remove(node2); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 1, "Deleted node 2 (test GetRelevantNodes())"); MITK_TEST_CONDITION_REQUIRED(manager->GetNumberOfObservers() == 1, "Deleted node 2 (test GetNumberOfObservers())"); ds->Remove(node3); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 0, "Deleted node 3 (test GetRelevantNodes())"); MITK_TEST_CONDITION_REQUIRED(manager->GetNumberOfObservers() == 0, "Deleted node 3 (test GetNumberOfObservers())"); } static bool VerifyRenderingModes() { bool ok = false; ok = ( mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR == 1 ) && (mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR == 2 ) && (mitk::RenderingModeProperty::LOOKUPTABLE_COLOR == 3 ) && (mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR == 4 ); return ok; } static void TestLevelWindowSliderVisibility(std::string testImageFile) { bool renderingModesValid = mitkLevelWindowManagerTestClass::VerifyRenderingModes(); if ( !renderingModesValid ) { MITK_ERROR << "Exception: Image Rendering.Mode property value types inconsistent."; } mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::Image::Pointer image1 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node1 = mitk::DataNode::New(); node1->SetData(image1); ds->Add(node1); //mitk::DataNode::Pointer node1 = mitk::IOUtil::LoadDataNode( testImageFile ); mitk::DataNode::Pointer node2 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node3 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); std::vector< mitk::DataNode::Pointer > nodeVec; //nodeVec.resize( 3 ); nodeVec.push_back( node1 ); nodeVec.push_back( node2 ); nodeVec.push_back( node3 ); typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; RandomGeneratorType::Pointer rnd = RandomGeneratorType::New(); rnd->Initialize(); for( unsigned int i=0; i<8; ++i ) { unsigned int parity = i; for( unsigned int img = 0; img < 3; ++img ) { if ( parity & 1 ) { int mode = rnd->GetIntegerVariate() % 3; nodeVec[img]->SetProperty( "Image Rendering.Mode", mitk::RenderingModeProperty::New( mode ) ); } else { int mode = rnd->GetIntegerVariate() % 2; nodeVec[img]->SetProperty( "Image Rendering.Mode", mitk::RenderingModeProperty::New( 3 + mode ) ); } parity >>= 1; } MITK_TEST_CONDITION( renderingModesValid && ( (!manager->GetLevelWindowProperty() && !i) || (manager->GetLevelWindowProperty() && i) ), "Testing level window property member according to rendering mode"); } } static void TestSetLevelWindowProperty( std::string testImageFile ) { mitk::LevelWindowManager::Pointer manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::DataNode::Pointer node3 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node2 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node1 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); //manager->SetAutoTopMostImage( true, node1 ); node3->SetIntProperty( "layer" , 1 ); node2->SetIntProperty( "layer" , 2 ); node1->SetIntProperty( "layer" , 3 ); manager->SetAutoTopMostImage( true ); bool isImageForLevelWindow1, isImageForLevelWindow2, isImageForLevelWindow3; node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( isImageForLevelWindow1 && !isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 1."); manager->SetAutoTopMostImage( false ); mitk::LevelWindowProperty::Pointer prop = dynamic_cast<mitk::LevelWindowProperty*>(node2->GetProperty("levelwindow")); manager->SetLevelWindowProperty( prop ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 2."); prop = dynamic_cast<mitk::LevelWindowProperty*>(node3->GetProperty("levelwindow")); manager->SetLevelWindowProperty( prop ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && !isImageForLevelWindow2 && isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); prop = dynamic_cast<mitk::LevelWindowProperty*>(node1->GetProperty("levelwindow")); manager->SetLevelWindowProperty( prop ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( isImageForLevelWindow1 && !isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); } }; int mitkLevelWindowManagerTest(int argc, char* args[]) { MITK_TEST_BEGIN("mitkLevelWindowManager"); MITK_TEST_CONDITION_REQUIRED( argc >= 2, "Testing if test file is given."); std::string testImage = args[1]; mitkLevelWindowManagerTestClass::TestInstantiation(); mitkLevelWindowManagerTestClass::TestSetGetDataStorage(); mitkLevelWindowManagerTestClass::TestMethodsWithInvalidParameters(); mitkLevelWindowManagerTestClass::TestOtherMethods(); mitkLevelWindowManagerTestClass::TestRemoveObserver(testImage); mitkLevelWindowManagerTestClass::TestLevelWindowSliderVisibility(testImage); mitkLevelWindowManagerTestClass::TestSetLevelWindowProperty( testImage ); MITK_TEST_END(); } <commit_msg>Test case for visibility changes added.<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkLevelWindowManager.h" #include "mitkStandaloneDataStorage.h" #include <mitkTestingMacros.h> #include <mitkIOUtil.h> #include <itkMersenneTwisterRandomVariateGenerator.h> #include "mitkRenderingModeProperty.h" #include <itkImageIterator.h> #include <mitkImageCast.h> #include <itkImageDuplicator.h> #include <itkComposeImageFilter.h> #include <itkEventObject.h> class mitkLevelWindowManagerTestClass { public: static void TestInstantiation() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); MITK_TEST_CONDITION_REQUIRED(manager.IsNotNull(),"Testing mitk::LevelWindowManager::New()"); } static void TestSetGetDataStorage() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); MITK_TEST_OUTPUT(<< "Creating DataStorage: "); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); bool success = true; try { manager->SetDataStorage(ds); } catch(std::exception e) { success = false; MITK_ERROR << "Exception: " << e.what(); } MITK_TEST_CONDITION_REQUIRED(success,"Testing mitk::LevelWindowManager SetDataStorage() "); MITK_TEST_CONDITION_REQUIRED(ds == manager->GetDataStorage(),"Testing mitk::LevelWindowManager GetDataStorage "); } static void TestMethodsWithInvalidParameters() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); bool success = false; mitk::LevelWindowProperty::Pointer levelWindowProperty = mitk::LevelWindowProperty::New(); try { manager->SetLevelWindowProperty(levelWindowProperty); } catch(mitk::Exception e) { success = true; } MITK_TEST_CONDITION(success,"Testing mitk::LevelWindowManager SetLevelWindowProperty with invalid parameter"); } static void TestOtherMethods() { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); MITK_TEST_CONDITION(manager->isAutoTopMost(),"Testing mitk::LevelWindowManager isAutoTopMost"); // It is not clear what the following code is supposed to test. The expression in // the catch(...) block does have no effect, so success is always true. // Related bugs are 13894 and 13889 /* bool success = true; try { mitk::LevelWindow levelWindow = manager->GetLevelWindow(); manager->SetLevelWindow(levelWindow); } catch (...) { success == false; } MITK_TEST_CONDITION(success,"Testing mitk::LevelWindowManager GetLevelWindow() and SetLevelWindow()"); */ manager->SetAutoTopMostImage(true); MITK_TEST_CONDITION(manager->isAutoTopMost(),"Testing mitk::LevelWindowManager isAutoTopMost()"); } static void TestRemoveObserver(std::string testImageFile) { mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::Image::Pointer image1 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node1 = mitk::DataNode::New(); node1->SetData(image1); mitk::Image::Pointer image2 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node2 = mitk::DataNode::New(); node2->SetData(image2); ds->Add(node1); ds->Add(node2); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 2, "Test if nodes have been added"); MITK_TEST_CONDITION_REQUIRED(static_cast<int>(manager->GetRelevantNodes()->size()) == manager->GetNumberOfObservers(), "Test if number of nodes is similar to number of observers"); mitk::Image::Pointer image3 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node3 = mitk::DataNode::New(); node3->SetData(image3); ds->Add(node3); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 3, "Test if another node have been added"); MITK_TEST_CONDITION_REQUIRED(static_cast<int>(manager->GetRelevantNodes()->size()) == manager->GetNumberOfObservers(), "Test if number of nodes is similar to number of observers"); ds->Remove(node1); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 2, "Deleted node 1 (test GetRelevantNodes())"); MITK_TEST_CONDITION_REQUIRED(manager->GetNumberOfObservers() == 2, "Deleted node 1 (test GetNumberOfObservers())"); ds->Remove(node2); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 1, "Deleted node 2 (test GetRelevantNodes())"); MITK_TEST_CONDITION_REQUIRED(manager->GetNumberOfObservers() == 1, "Deleted node 2 (test GetNumberOfObservers())"); ds->Remove(node3); MITK_TEST_CONDITION_REQUIRED(manager->GetRelevantNodes()->size() == 0, "Deleted node 3 (test GetRelevantNodes())"); MITK_TEST_CONDITION_REQUIRED(manager->GetNumberOfObservers() == 0, "Deleted node 3 (test GetNumberOfObservers())"); } static bool VerifyRenderingModes() { bool ok = false; ok = ( mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR == 1 ) && (mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR == 2 ) && (mitk::RenderingModeProperty::LOOKUPTABLE_COLOR == 3 ) && (mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR == 4 ); return ok; } static void TestLevelWindowSliderVisibility(std::string testImageFile) { bool renderingModesValid = mitkLevelWindowManagerTestClass::VerifyRenderingModes(); if ( !renderingModesValid ) { MITK_ERROR << "Exception: Image Rendering.Mode property value types inconsistent."; } mitk::LevelWindowManager::Pointer manager; manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::Image::Pointer image1 = mitk::IOUtil::LoadImage(testImageFile); mitk::DataNode::Pointer node1 = mitk::DataNode::New(); node1->SetData(image1); ds->Add(node1); //mitk::DataNode::Pointer node1 = mitk::IOUtil::LoadDataNode( testImageFile ); mitk::DataNode::Pointer node2 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node3 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); std::vector< mitk::DataNode::Pointer > nodeVec; //nodeVec.resize( 3 ); nodeVec.push_back( node1 ); nodeVec.push_back( node2 ); nodeVec.push_back( node3 ); typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType; RandomGeneratorType::Pointer rnd = RandomGeneratorType::New(); rnd->Initialize(); for( unsigned int i=0; i<8; ++i ) { unsigned int parity = i; for( unsigned int img = 0; img < 3; ++img ) { if ( parity & 1 ) { int mode = rnd->GetIntegerVariate() % 3; nodeVec[img]->SetProperty( "Image Rendering.Mode", mitk::RenderingModeProperty::New( mode ) ); } else { int mode = rnd->GetIntegerVariate() % 2; nodeVec[img]->SetProperty( "Image Rendering.Mode", mitk::RenderingModeProperty::New( 3 + mode ) ); } parity >>= 1; } MITK_TEST_CONDITION( renderingModesValid && ( (!manager->GetLevelWindowProperty() && !i) || (manager->GetLevelWindowProperty() && i) ), "Testing level window property member according to rendering mode"); } } static void TestSetLevelWindowProperty( std::string testImageFile ) { mitk::LevelWindowManager::Pointer manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::DataNode::Pointer node3 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node2 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node1 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); //manager->SetAutoTopMostImage( true, node1 ); node3->SetIntProperty( "layer" , 1 ); node2->SetIntProperty( "layer" , 2 ); node1->SetIntProperty( "layer" , 3 ); manager->SetAutoTopMostImage( true ); bool isImageForLevelWindow1, isImageForLevelWindow2, isImageForLevelWindow3; node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( isImageForLevelWindow1 && !isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 1."); manager->SetAutoTopMostImage( false ); mitk::LevelWindowProperty::Pointer prop = dynamic_cast<mitk::LevelWindowProperty*>(node2->GetProperty("levelwindow")); manager->SetLevelWindowProperty( prop ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 2."); prop = dynamic_cast<mitk::LevelWindowProperty*>(node3->GetProperty("levelwindow")); manager->SetLevelWindowProperty( prop ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && !isImageForLevelWindow2 && isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); prop = dynamic_cast<mitk::LevelWindowProperty*>(node1->GetProperty("levelwindow")); manager->SetLevelWindowProperty( prop ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( isImageForLevelWindow1 && !isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); } static void TestImageForLevelWindowOnVisibilityChange( std::string testImageFile ) { mitk::LevelWindowManager::Pointer manager = mitk::LevelWindowManager::New(); mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New(); manager->SetDataStorage(ds); //add multiple objects to the data storage => multiple observers should be created mitk::DataNode::Pointer node3 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node2 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); mitk::DataNode::Pointer node1 = mitk::IOUtil::Load( testImageFile, *ds )->GetElement(0); //manager->SetAutoTopMostImage( true, node1 ); node3->SetIntProperty( "layer" , 1 ); node2->SetIntProperty( "layer" , 2 ); node1->SetIntProperty( "layer" , 3 ); manager->SetAutoTopMostImage( false ); bool isImageForLevelWindow1, isImageForLevelWindow2, isImageForLevelWindow3; node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( isImageForLevelWindow1 && !isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing initial imageForLevelWindow setting."); node1->SetVisibility( false ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 2."); node2->SetVisibility( false ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && !isImageForLevelWindow2 && isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); node3->SetVisibility( false ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( !isImageForLevelWindow1 && !isImageForLevelWindow2 && isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); node1->SetVisibility( true ); node1->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow1 ); node2->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow2 ); node3->GetBoolProperty( "imageForLevelWindow", isImageForLevelWindow3 ); MITK_TEST_CONDITION( isImageForLevelWindow1 && !isImageForLevelWindow2 && !isImageForLevelWindow3, "Testing exclusive imageForLevelWindow property for node 3."); } }; int mitkLevelWindowManagerTest(int argc, char* args[]) { MITK_TEST_BEGIN("mitkLevelWindowManager"); MITK_TEST_CONDITION_REQUIRED( argc >= 2, "Testing if test file is given."); std::string testImage = args[1]; mitkLevelWindowManagerTestClass::TestInstantiation(); mitkLevelWindowManagerTestClass::TestSetGetDataStorage(); mitkLevelWindowManagerTestClass::TestMethodsWithInvalidParameters(); mitkLevelWindowManagerTestClass::TestOtherMethods(); mitkLevelWindowManagerTestClass::TestRemoveObserver(testImage); mitkLevelWindowManagerTestClass::TestLevelWindowSliderVisibility(testImage); mitkLevelWindowManagerTestClass::TestSetLevelWindowProperty( testImage ); mitkLevelWindowManagerTestClass::TestImageForLevelWindowOnVisibilityChange( testImage ); MITK_TEST_END(); } <|endoftext|>
<commit_before>// Filename: pystub.cxx // Created by: drose (09Aug00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // panda3d-general@lists.sourceforge.net . // //////////////////////////////////////////////////////////////////// #include "pystub.h" extern "C" { EXPCL_DTOOLCONFIG int PyArg_ParseTuple(...); EXPCL_DTOOLCONFIG int Py_BuildValue(...); EXPCL_DTOOLCONFIG int PyInt_FromLong(...); EXPCL_DTOOLCONFIG int PyInt_Type(...); EXPCL_DTOOLCONFIG int PyLong_Type(...); EXPCL_DTOOLCONFIG int PyType_IsSubtype(...); EXPCL_DTOOLCONFIG int PyFloat_Type(...); EXPCL_DTOOLCONFIG int PyFloat_FromDouble(...); EXPCL_DTOOLCONFIG int PyString_Type(...); EXPCL_DTOOLCONFIG int PyUnicode_Type(...); EXPCL_DTOOLCONFIG int PyString_FromString(...); EXPCL_DTOOLCONFIG int PyString_FromStringAndSize(...); EXPCL_DTOOLCONFIG int Py_InitModule4(...); EXPCL_DTOOLCONFIG int PyObject_IsTrue(...); EXPCL_DTOOLCONFIG int PyObject_Str(...); EXPCL_DTOOLCONFIG int PyErr_SetString(...); EXPCL_DTOOLCONFIG int PySequence_GetItem(...); EXPCL_DTOOLCONFIG int PySequence_Tuple(...); EXPCL_DTOOLCONFIG int PyLong_AsUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyErr_Occurred(...); EXPCL_DTOOLCONFIG int PyObject_GetAttrString(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLong(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyTuple_GetItem(...); EXPCL_DTOOLCONFIG int PyString_AsString(...); EXPCL_DTOOLCONFIG int PySequence_Size(...); EXPCL_DTOOLCONFIG int PyList_New(...); EXPCL_DTOOLCONFIG int PyList_AsTuple(...); EXPCL_DTOOLCONFIG int PyList_Append(...); EXPCL_DTOOLCONFIG int PyFloat_AsDouble(...); EXPCL_DTOOLCONFIG int PyString_AsStringAndSize(...); EXPCL_DTOOLCONFIG int PyObject_CallObject(...); EXPCL_DTOOLCONFIG int PyLong_AsLongLong(...); EXPCL_DTOOLCONFIG int PyLong_FromLongLong(...); EXPCL_DTOOLCONFIG int PyInt_AsLong(...); EXPCL_DTOOLCONFIG int PyObject_HasAttrString(...); EXPCL_DTOOLCONFIG int PySequence_Check(...); EXPCL_DTOOLCONFIG int PyTuple_New(...); EXPCL_DTOOLCONFIG extern void *PyExc_AssertionError; }; int PyArg_ParseTuple(...) { return 0; } int Py_BuildValue(...) { return 0; } int PyInt_FromLong(...) { return 0; } int PyInt_Type(...) { return 0; } int PyLong_Type(...) { return 0; } int PyType_IsSubtype(...) { return 0; } int PyFloat_Type(...) { return 0; } int PyFloat_FromDouble(...) { return 0; } int PyString_Type(...) { return 0; } int PyUnicode_Type(...) { return 0; } int PyString_FromStringAndSize(...) { return 0; } int PyString_FromString(...) { return 0; } int Py_InitModule4(...) { return 0; } int PyObject_IsTrue(...) { return 0; } int PyObject_Str(...) { return 0; } int PyErr_SetString(...) { return 0; } int PySequence_GetItem(...) { return 0; } int PySequence_Tuple(...) { return 0; } int PyLong_AsUnsignedLongLong(...) { return 0; } int PyErr_Occurred(...) { return 0; } int PyObject_GetAttrString(...) { return 0; } int PyLong_FromUnsignedLong(...) { return 0; } int PyLong_FromUnsignedLongLong(...) { return 0; } int PyTuple_GetItem(...) { return 0; } int PyString_AsString(...) { return 0; } int PySequence_Size(...) { return 0; } int PyList_New(...) { return 0; } int PyList_AsTuple(...) { return 0; } int PyList_Append(...) { return 0; } int PyFloat_AsDouble(...) { return 0; } int PyString_AsStringAndSize(...) { return 0; } int PyObject_CallObject(...) { return 0; } int PyLong_AsLongLong(...) { return 0; } int PyLong_FromLongLong(...) { return 0; } int PyInt_AsLong(...) { return 0; } int PyObject_HasAttrString(...) { return 0; } int PySequence_Check(...) { return 0; } int PyTuple_New(...) { return 0; } void *PyExc_AssertionError = (void *)NULL; void pystub() { } <commit_msg>stub out more<commit_after>// Filename: pystub.cxx // Created by: drose (09Aug00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // panda3d-general@lists.sourceforge.net . // //////////////////////////////////////////////////////////////////// #include "pystub.h" extern "C" { EXPCL_DTOOLCONFIG int PyArg_ParseTuple(...); EXPCL_DTOOLCONFIG int Py_BuildValue(...); EXPCL_DTOOLCONFIG int PyInt_FromLong(...); EXPCL_DTOOLCONFIG int PyInt_Type(...); EXPCL_DTOOLCONFIG int PyLong_Type(...); EXPCL_DTOOLCONFIG int PyType_IsSubtype(...); EXPCL_DTOOLCONFIG int PyFloat_Type(...); EXPCL_DTOOLCONFIG int PyFloat_FromDouble(...); EXPCL_DTOOLCONFIG int PyString_Type(...); EXPCL_DTOOLCONFIG int PyUnicode_Type(...); EXPCL_DTOOLCONFIG int PyString_FromString(...); EXPCL_DTOOLCONFIG int PyString_FromStringAndSize(...); EXPCL_DTOOLCONFIG int Py_InitModule4(...); EXPCL_DTOOLCONFIG int PyObject_IsTrue(...); EXPCL_DTOOLCONFIG int PyObject_Str(...); EXPCL_DTOOLCONFIG int PyErr_SetString(...); EXPCL_DTOOLCONFIG int PySequence_GetItem(...); EXPCL_DTOOLCONFIG int PySequence_Tuple(...); EXPCL_DTOOLCONFIG int PyLong_AsUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyErr_Occurred(...); EXPCL_DTOOLCONFIG int PyObject_GetAttrString(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLong(...); EXPCL_DTOOLCONFIG int PyLong_FromUnsignedLongLong(...); EXPCL_DTOOLCONFIG int PyTuple_GetItem(...); EXPCL_DTOOLCONFIG int PyString_AsString(...); EXPCL_DTOOLCONFIG int PySequence_Size(...); EXPCL_DTOOLCONFIG int PyList_New(...); EXPCL_DTOOLCONFIG int PyList_AsTuple(...); EXPCL_DTOOLCONFIG int PyList_Append(...); EXPCL_DTOOLCONFIG int PyFloat_AsDouble(...); EXPCL_DTOOLCONFIG int PyString_AsStringAndSize(...); EXPCL_DTOOLCONFIG int PyObject_CallObject(...); EXPCL_DTOOLCONFIG int PyLong_AsLongLong(...); EXPCL_DTOOLCONFIG int PyLong_FromLongLong(...); EXPCL_DTOOLCONFIG int PyInt_AsLong(...); EXPCL_DTOOLCONFIG int PyObject_HasAttrString(...); EXPCL_DTOOLCONFIG int PySequence_Check(...); EXPCL_DTOOLCONFIG int PyTuple_New(...); EXPCL_DTOOLCONFIG extern void *PyExc_AssertionError; EXPCL_DTOOLCONFIG extern void *_Py_NoneStruct; }; int PyArg_ParseTuple(...) { return 0; } int Py_BuildValue(...) { return 0; } int PyInt_FromLong(...) { return 0; } int PyInt_Type(...) { return 0; } int PyLong_Type(...) { return 0; } int PyType_IsSubtype(...) { return 0; } int PyFloat_Type(...) { return 0; } int PyFloat_FromDouble(...) { return 0; } int PyString_Type(...) { return 0; } int PyUnicode_Type(...) { return 0; } int PyString_FromStringAndSize(...) { return 0; } int PyString_FromString(...) { return 0; } int Py_InitModule4(...) { return 0; } int PyObject_IsTrue(...) { return 0; } int PyObject_Str(...) { return 0; } int PyErr_SetString(...) { return 0; } int PySequence_GetItem(...) { return 0; } int PySequence_Tuple(...) { return 0; } int PyLong_AsUnsignedLongLong(...) { return 0; } int PyErr_Occurred(...) { return 0; } int PyObject_GetAttrString(...) { return 0; } int PyLong_FromUnsignedLong(...) { return 0; } int PyLong_FromUnsignedLongLong(...) { return 0; } int PyTuple_GetItem(...) { return 0; } int PyString_AsString(...) { return 0; } int PySequence_Size(...) { return 0; } int PyList_New(...) { return 0; } int PyList_AsTuple(...) { return 0; } int PyList_Append(...) { return 0; } int PyFloat_AsDouble(...) { return 0; } int PyString_AsStringAndSize(...) { return 0; } int PyObject_CallObject(...) { return 0; } int PyLong_AsLongLong(...) { return 0; } int PyLong_FromLongLong(...) { return 0; } int PyInt_AsLong(...) { return 0; } int PyObject_HasAttrString(...) { return 0; } int PySequence_Check(...) { return 0; } int PyTuple_New(...) { return 0; } void *PyExc_AssertionError = (void *)NULL; void *_Py_NoneStruct = (void *)NULL; void pystub() { } <|endoftext|>
<commit_before>#include <stdio.h> #include <algorithm> // for std::swap #include "allocore/system/al_Config.h" #include "allocore/system/al_Thread.hpp" #ifdef AL_WINDOWS #define USE_THREADEX #else #define USE_PTHREAD #endif namespace al { #ifdef USE_PTHREAD #include <pthread.h> //typedef pthread_t ThreadHandle; //typedef void * (*ThreadFunction)(void *); //#define THREAD_FUNCTION(name) void * name(void * user) struct Thread::Impl{ Impl() : mHandle(0) { //printf("Thread::Impl(): %p\n", this); pthread_attr_init(&mAttr); // threads are not required to be joinable by default, so make it so pthread_attr_setdetachstate(&mAttr, PTHREAD_CREATE_JOINABLE); } ~Impl(){ //printf("Thread::~Impl(): %p\n", this); pthread_attr_destroy(&mAttr); } bool start(ThreadFunction& func){ if(mHandle) return false; //return 0 == pthread_create(&mHandle, NULL, cThreadFunc, &func); return 0 == pthread_create(&mHandle, &mAttr, cThreadFunc, &func); } bool join(){ if(pthread_join(mHandle, NULL) == 0){ mHandle = 0; return true; } return false; } void priority(int v){ struct sched_param param; if(v >= 1 && v <= 99){ param.sched_priority = v; //pthread_setschedparam(mHandle, SCHED_FIFO, &param); // FIFO and RR (round-robin) are for real-time scheduling pthread_attr_setschedpolicy(&mAttr, SCHED_FIFO); //pthread_attr_setschedpolicy(&mAttr, SCHED_RR); pthread_attr_setschedparam(&mAttr, &param); } else{ param.sched_priority = 0; //pthread_setschedparam(mHandle, SCHED_OTHER, &param); pthread_attr_setschedpolicy(&mAttr, SCHED_OTHER); pthread_attr_setschedparam(&mAttr, &param); } } // bool cancel(){ // return 0 == pthread_cancel(mHandle); // } // // void testCancel(){ // pthread_testcancel(); // } pthread_t mHandle; pthread_attr_t mAttr; static void * cThreadFunc(void * user){ ThreadFunction& tfunc = *((ThreadFunction*)user); tfunc(); return NULL; } }; void * Thread::current(){ // pthread_t pthread_self(void); static pthread_t r; r = pthread_self(); return (void*)(&r); } #elif defined(USE_THREADEX) #define WIN32_MEAN_AND_LEAN #include <windows.h> #include <process.h> //typedef unsigned long ThreadHandle; //typedef unsigned (__stdcall *ThreadFunction)(void *); //#define THREAD_FUNCTION(name) unsigned _stdcall * name(void * user) struct Thread::Impl{ Impl(): mHandle(0){} bool start(ThreadFunction& func){ if(mHandle) return false; unsigned thread_id; mHandle = _beginthreadex(NULL, 0, cThreadFunc, &func, 0, &thread_id); if(mHandle) return true; return false; } bool join(){ long retval = WaitForSingleObject((HANDLE)mHandle, INFINITE); if(retval == WAIT_OBJECT_0){ CloseHandle((HANDLE)mHandle); mHandle = 0; return true; } return false; } // TODO: Threadx priority void priority(int v){ } // bool cancel(){ // TerminateThread((HANDLE)mHandle, 0); // return true; // } // // void testCancel(){ // } unsigned long mHandle; // ThreadFunction mRoutine; static unsigned cThreadFunc(void * user){ // static unsigned _stdcall cThreadFunc(void * user){ ThreadFunction& tfunc = *((ThreadFunction*)user); tfunc(); return 0; } }; #endif Thread::Thread() : mImpl(new Impl), mJoinOnDestroy(false) {} Thread::Thread(ThreadFunction& func) : mImpl(new Impl), mJoinOnDestroy(false) { start(func); } Thread::Thread(void * (*cThreadFunc)(void * userData), void * userData) : mImpl(new Impl), mJoinOnDestroy(false) { start(cThreadFunc, userData); } Thread::Thread(const Thread& other) : mImpl(new Impl), mCFunc(other.mCFunc), mJoinOnDestroy(other.mJoinOnDestroy) { } Thread::~Thread(){ if(mJoinOnDestroy) join(); delete mImpl; } void swap(Thread& a, Thread& b){ using std::swap; swap(a.mImpl, b.mImpl); swap(a.mCFunc, b.mCFunc); swap(a.mJoinOnDestroy, b.mJoinOnDestroy); } Thread& Thread::operator= (Thread other){ swap(*this, other); return *this; } /*Thread& Thread::operator= (const Thread& other){ //printf("Thread::operator=\n"); if(this != &other){ //join(); // delete Impl only if we are sure we are the owner if(mImpl != other.mImpl) delete mImpl; // always construct a new Impl mImpl = new Impl; mCFunc = other.mCFunc; mJoinOnDestroy = other.mJoinOnDestroy; } return *this; }*/ Thread& Thread::priority(int v){ mImpl->priority(v); return *this; } bool Thread::start(ThreadFunction& func){ return mImpl->start(func); } bool Thread::join(){ return mImpl->join(); } } // al:: <commit_msg>Thread: fix MSVC warning<commit_after>#include <stdio.h> #include <algorithm> // for std::swap #include "allocore/system/al_Config.h" #include "allocore/system/al_Thread.hpp" #ifdef AL_WINDOWS #define USE_THREADEX #else #define USE_PTHREAD #endif namespace al { #ifdef USE_PTHREAD #include <pthread.h> //typedef pthread_t ThreadHandle; //typedef void * (*ThreadFunction)(void *); //#define THREAD_FUNCTION(name) void * name(void * user) struct Thread::Impl{ Impl() : mHandle(0) { //printf("Thread::Impl(): %p\n", this); pthread_attr_init(&mAttr); // threads are not required to be joinable by default, so make it so pthread_attr_setdetachstate(&mAttr, PTHREAD_CREATE_JOINABLE); } ~Impl(){ //printf("Thread::~Impl(): %p\n", this); pthread_attr_destroy(&mAttr); } bool start(ThreadFunction& func){ if(mHandle) return false; //return 0 == pthread_create(&mHandle, NULL, cThreadFunc, &func); return 0 == pthread_create(&mHandle, &mAttr, cThreadFunc, &func); } bool join(){ if(pthread_join(mHandle, NULL) == 0){ mHandle = 0; return true; } return false; } void priority(int v){ struct sched_param param; if(v >= 1 && v <= 99){ param.sched_priority = v; //pthread_setschedparam(mHandle, SCHED_FIFO, &param); // FIFO and RR (round-robin) are for real-time scheduling pthread_attr_setschedpolicy(&mAttr, SCHED_FIFO); //pthread_attr_setschedpolicy(&mAttr, SCHED_RR); pthread_attr_setschedparam(&mAttr, &param); } else{ param.sched_priority = 0; //pthread_setschedparam(mHandle, SCHED_OTHER, &param); pthread_attr_setschedpolicy(&mAttr, SCHED_OTHER); pthread_attr_setschedparam(&mAttr, &param); } } // bool cancel(){ // return 0 == pthread_cancel(mHandle); // } // // void testCancel(){ // pthread_testcancel(); // } pthread_t mHandle; pthread_attr_t mAttr; static void * cThreadFunc(void * user){ ThreadFunction& tfunc = *((ThreadFunction*)user); tfunc(); return NULL; } }; void * Thread::current(){ // pthread_t pthread_self(void); static pthread_t r; r = pthread_self(); return (void*)(&r); } #elif defined(USE_THREADEX) #define WIN32_MEAN_AND_LEAN #include <windows.h> #include <process.h> //typedef unsigned long ThreadHandle; //typedef unsigned (__stdcall *ThreadFunction)(void *); //#define THREAD_FUNCTION(name) unsigned _stdcall * name(void * user) class Thread::Impl{ public: Impl(): mHandle(0){} bool start(ThreadFunction& func){ if(mHandle) return false; unsigned thread_id; mHandle = _beginthreadex(NULL, 0, cThreadFunc, &func, 0, &thread_id); if(mHandle) return true; return false; } bool join(){ long retval = WaitForSingleObject((HANDLE)mHandle, INFINITE); if(retval == WAIT_OBJECT_0){ CloseHandle((HANDLE)mHandle); mHandle = 0; return true; } return false; } // TODO: Threadx priority void priority(int v){ } // bool cancel(){ // TerminateThread((HANDLE)mHandle, 0); // return true; // } // // void testCancel(){ // } unsigned long mHandle; // ThreadFunction mRoutine; static unsigned cThreadFunc(void * user){ // static unsigned _stdcall cThreadFunc(void * user){ ThreadFunction& tfunc = *((ThreadFunction*)user); tfunc(); return 0; } }; #endif Thread::Thread() : mImpl(new Impl), mJoinOnDestroy(false) {} Thread::Thread(ThreadFunction& func) : mImpl(new Impl), mJoinOnDestroy(false) { start(func); } Thread::Thread(void * (*cThreadFunc)(void * userData), void * userData) : mImpl(new Impl), mJoinOnDestroy(false) { start(cThreadFunc, userData); } Thread::Thread(const Thread& other) : mImpl(new Impl), mCFunc(other.mCFunc), mJoinOnDestroy(other.mJoinOnDestroy) { } Thread::~Thread(){ if(mJoinOnDestroy) join(); delete mImpl; } void swap(Thread& a, Thread& b){ using std::swap; swap(a.mImpl, b.mImpl); swap(a.mCFunc, b.mCFunc); swap(a.mJoinOnDestroy, b.mJoinOnDestroy); } Thread& Thread::operator= (Thread other){ swap(*this, other); return *this; } /*Thread& Thread::operator= (const Thread& other){ //printf("Thread::operator=\n"); if(this != &other){ //join(); // delete Impl only if we are sure we are the owner if(mImpl != other.mImpl) delete mImpl; // always construct a new Impl mImpl = new Impl; mCFunc = other.mCFunc; mJoinOnDestroy = other.mJoinOnDestroy; } return *this; }*/ Thread& Thread::priority(int v){ mImpl->priority(v); return *this; } bool Thread::start(ThreadFunction& func){ return mImpl->start(func); } bool Thread::join(){ return mImpl->join(); } } // al:: <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \brief A Lua class proxy for IO's dataset class. */ #include "Controller/Controller.h" #include "3rdParty/LUA/lua.hpp" #include "IO/IOManager.h" #include "IO/FileBackedDataset.h" #include <vector> #include "../LuaScripting.h" #include "../LuaClassRegistration.h" #include "LuaTuvokTypes.h" #include "LuaDatasetProxy.h" namespace tuvok { LuaDatasetProxy::LuaDatasetProxy() { mReg = NULL; } LuaDatasetProxy::~LuaDatasetProxy() { if (mReg != NULL) delete mReg; } void LuaDatasetProxy::bindDataset(Dataset* ds) { if (mReg == NULL) throw LuaError("Unable to bind dataset, no class registration available."); mReg->clearProxyFunctions(); if (ds != NULL) { // Register dataset functions using ds. std::string id; //GetDomainSize id = mReg->functionProxy(ds, &Dataset::GetDomainSize, "getDomainSize", "", false); id = mReg->functionProxy(ds, &Dataset::GetRange, "getRange", "", false); // Attempt to cast the dataset to a file backed dataset. FileBackedDataset* fileDataset = dynamic_cast<FileBackedDataset*>(ds); if (fileDataset != NULL) { id = mReg->functionProxy(fileDataset, &FileBackedDataset::Filename, "path", "Full path to the dataset.", false); } } } void LuaDatasetProxy::defineLuaInterface( LuaClassRegistration<LuaDatasetProxy>& reg, LuaDatasetProxy* me, LuaScripting*) { me->mReg = new LuaClassRegistration<LuaDatasetProxy>(reg); } } /* namespace tuvok */ <commit_msg>Exposed getLODLevelCount from dataset.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** \brief A Lua class proxy for IO's dataset class. */ #include "Controller/Controller.h" #include "3rdParty/LUA/lua.hpp" #include "IO/IOManager.h" #include "IO/FileBackedDataset.h" #include <vector> #include "../LuaScripting.h" #include "../LuaClassRegistration.h" #include "LuaTuvokTypes.h" #include "LuaDatasetProxy.h" namespace tuvok { LuaDatasetProxy::LuaDatasetProxy() { mReg = NULL; } LuaDatasetProxy::~LuaDatasetProxy() { if (mReg != NULL) delete mReg; } void LuaDatasetProxy::bindDataset(Dataset* ds) { if (mReg == NULL) throw LuaError("Unable to bind dataset, no class registration available."); mReg->clearProxyFunctions(); if (ds != NULL) { // Register dataset functions using ds. std::string id; id = mReg->functionProxy(ds, &Dataset::GetDomainSize, "getDomainSize", "", false); id = mReg->functionProxy(ds, &Dataset::GetRange, "getRange", "", false); id = mReg->functionProxy(ds, &Dataset::GetLODLevelCount, "getLODLevelCount", "", false); // Attempt to cast the dataset to a file backed dataset. FileBackedDataset* fileDataset = dynamic_cast<FileBackedDataset*>(ds); if (fileDataset != NULL) { id = mReg->functionProxy(fileDataset, &FileBackedDataset::Filename, "path", "Full path to the dataset.", false); } } } void LuaDatasetProxy::defineLuaInterface( LuaClassRegistration<LuaDatasetProxy>& reg, LuaDatasetProxy* me, LuaScripting*) { me->mReg = new LuaClassRegistration<LuaDatasetProxy>(reg); } } /* namespace tuvok */ <|endoftext|>
<commit_before><commit_msg>use icons for buttons<commit_after><|endoftext|>
<commit_before> /* mbed Microcontroller Library * Copyright (c) 2013 ARM Limited * * 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 "mbed.h" #include <stdio.h> #include "minar/minar.h" #include "core-util/Event.h" #if DEVICE_SPI_ASYNCH #define SHORT_XFR 3 #define LONG_XFR 16 #define TEST_BYTE0 0x00 #define TEST_BYTE1 0x11 #define TEST_BYTE2 0xFF #define TEST_BYTE3 0xAA #define TEST_BYTE4 0x55 #define TEST_BYTE5 0x50 #define TEST_BYTE_RX TEST_BYTE3 #define TEST_BYTE_TX_BASE TEST_BYTE5 #if defined(TARGET_K64F) #define TEST_MOSI_PIN PTD2 #define TEST_MISO_PIN PTD3 #define TEST_SCLK_PIN PTD1 #define TEST_CS_PIN PTD0 #else #error Target not supported #endif using namespace minar; class SPITest { public: SPITest(): spi(TEST_MOSI_PIN, TEST_MISO_PIN, TEST_SCLK_PIN), cs(TEST_CS_PIN) { for (uint32_t i = 0; i < sizeof(tx_buf); i++) { tx_buf[i] = i + TEST_BYTE_TX_BASE; } cs = 1; } void start() { printf("Starting short transfer test\r\n"); init_rx_buffer(); cs = 0; int rc = spi.transfer() .tx(tx_buf, SHORT_XFR) .rx(rx_buf, SHORT_XFR) .callback(SPI::event_callback_t(this, &SPITest::short_transfer_complete_cb), SPI_EVENT_COMPLETE) .apply(); printf("Res is %d\r\n", rc); } private: void init_rx_buffer() { for (uint32_t i = 0; i < sizeof(rx_buf); i ++) { rx_buf[i] = 0; } } void compare_buffers(const uint8_t *src, const uint8_t *dest, uint32_t len) { for (uint32_t i = 0; i < len; i ++) { if (src[i] != dest[i]) { printf("MISMATCH at position %u: expected %d, got %d\r\n", (unsigned)i, (int)src[i], (int)dest[i]); } } } void short_transfer_complete_cb(Buffer tx_buffer, Buffer rx_buffer, int event) { cs = 1; printf("Short transfer DONE, event is %d\r\n", event); compare_buffers((uint8_t*)rx_buffer.buf, (uint8_t*)tx_buffer.buf, rx_buffer.length); printf("Starting long transfer test\r\n"); init_rx_buffer(); cs = 0; int rc = spi.transfer() .tx(tx_buf, LONG_XFR) .rx(rx_buf, LONG_XFR) .callback(SPI::event_callback_t(this, &SPITest::long_transfer_complete_cb), SPI_EVENT_COMPLETE) .apply(); printf("Res is %d\r\n", rc); } void long_transfer_complete_cb(Buffer tx_buffer, Buffer rx_buffer, int event) { cs = 1; printf("Long transfer DONE, event is %d\r\n", event); compare_buffers((uint8_t*)rx_buffer.buf, (uint8_t*)tx_buffer.buf, rx_buffer.length); printf("**** Test done ****\r\n"); } private: SPI spi; DigitalOut cs; uint8_t tx_buf[LONG_XFR]; uint8_t rx_buf[LONG_XFR]; }; void app_start(int, char*[]) { static SPITest test; Scheduler::postCallback(mbed::util::FunctionPointer0<void>(&test, &SPITest::start).bind()); } #else void app_start(int, char*[]) { } #endif <commit_msg>Tests - SPI - fix supported targets<commit_after> /* mbed Microcontroller Library * Copyright (c) 2013 ARM Limited * * 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 "mbed.h" #include <stdio.h> #include "minar/minar.h" #include "core-util/Event.h" // Note: this needs fix with config #if defined(TARGET_K64F) #define TARGET_SUPPORTED 1 #define TEST_MOSI_PIN PTD2 #define TEST_MISO_PIN PTD3 #define TEST_SCLK_PIN PTD1 #define TEST_CS_PIN PTD0 #else #define TARGET_SUPPORTED 0 #endif #if (TARGET_SUPPORTED == 1) #define SHORT_XFR 3 #define LONG_XFR 16 #define TEST_BYTE0 0x00 #define TEST_BYTE1 0x11 #define TEST_BYTE2 0xFF #define TEST_BYTE3 0xAA #define TEST_BYTE4 0x55 #define TEST_BYTE5 0x50 #define TEST_BYTE_RX TEST_BYTE3 #define TEST_BYTE_TX_BASE TEST_BYTE5 using namespace minar; class SPITest { public: SPITest(): spi(TEST_MOSI_PIN, TEST_MISO_PIN, TEST_SCLK_PIN), cs(TEST_CS_PIN) { for (uint32_t i = 0; i < sizeof(tx_buf); i++) { tx_buf[i] = i + TEST_BYTE_TX_BASE; } cs = 1; } void start() { printf("Starting short transfer test\r\n"); init_rx_buffer(); cs = 0; int rc = spi.transfer() .tx(tx_buf, SHORT_XFR) .rx(rx_buf, SHORT_XFR) .callback(SPI::event_callback_t(this, &SPITest::short_transfer_complete_cb), SPI_EVENT_COMPLETE) .apply(); printf("Res is %d\r\n", rc); } private: void init_rx_buffer() { for (uint32_t i = 0; i < sizeof(rx_buf); i ++) { rx_buf[i] = 0; } } void compare_buffers(const uint8_t *src, const uint8_t *dest, uint32_t len) { for (uint32_t i = 0; i < len; i ++) { if (src[i] != dest[i]) { printf("MISMATCH at position %u: expected %d, got %d\r\n", (unsigned)i, (int)src[i], (int)dest[i]); } } } void short_transfer_complete_cb(Buffer tx_buffer, Buffer rx_buffer, int event) { cs = 1; printf("Short transfer DONE, event is %d\r\n", event); compare_buffers((uint8_t*)rx_buffer.buf, (uint8_t*)tx_buffer.buf, rx_buffer.length); printf("Starting long transfer test\r\n"); init_rx_buffer(); cs = 0; int rc = spi.transfer() .tx(tx_buf, LONG_XFR) .rx(rx_buf, LONG_XFR) .callback(SPI::event_callback_t(this, &SPITest::long_transfer_complete_cb), SPI_EVENT_COMPLETE) .apply(); printf("Res is %d\r\n", rc); } void long_transfer_complete_cb(Buffer tx_buffer, Buffer rx_buffer, int event) { cs = 1; printf("Long transfer DONE, event is %d\r\n", event); compare_buffers((uint8_t*)rx_buffer.buf, (uint8_t*)tx_buffer.buf, rx_buffer.length); printf("**** Test done ****\r\n"); } private: SPI spi; DigitalOut cs; uint8_t tx_buf[LONG_XFR]; uint8_t rx_buf[LONG_XFR]; }; void app_start(int, char*[]) { static SPITest test; Scheduler::postCallback(mbed::util::FunctionPointer0<void>(&test, &SPITest::start).bind()); } #else void app_start(int, char*[]) { } #endif <|endoftext|>
<commit_before>#include "dataaccess.h" //#include <ofstream> #include <fstream> #include <iostream> #include <vector> DataAccess::DataAccess() { } void DataAccess::readData () { vector<string> logs; string name, gender; int birth, death; cout << "Testing loading of file." << endl; ifstream myfile ("Info.txt"); if ( myfile.is_open() ) { while ( ! myfile.eof() ) { getline (myfile, name, ','); getline (myfile, gender, ','); getline (myfile, birth, ','); getline (myfile, death, ','); logs.push_back(line); } myfile.close(); } else { cout << "Unable to open file." << endl; } for(size_t i = 0; i < logs.size(); i++) { cout << logs[i] << endl; } } /* void readData (parameters) { ifstream myfile; file.open ("info.txt"); vector <string> information for(int i = 0; i < count; i++) } myfile.close(); return 0; } void writeData (parameters) { ofstream outputFile; outputFile.open("InfoTestFile.txt", fstream::app); string name; string sex; int birth; int death; cout << "Enter name of a Computer Scientist: "; cin >> name; outputFile << name << ", "; cout << "Enter sex: "; cin >> sex; outputFile << sex << ", "; cout << "Enter year of birth: "; cin >> birth; outputFile << birth << ", "; cout << "Enter year of death or -- if alive: "; cin >> death; outputFile << death << endl; outputFile.close(); cout << "Done!\n"; return 0; } */ <commit_msg>made the project executable<commit_after>#include "dataaccess.h" //#include <ofstream> #include <fstream> #include <iostream> #include <vector> DataAccess::DataAccess() { } void DataAccess::readData () { vector<string> logs; string name, gender; string birth, death; cout << "Testing loading of file." << endl; ifstream myfile ("Info.txt"); if ( myfile.is_open() ) { while ( ! myfile.eof() ) { getline (myfile, name, ','); getline (myfile, gender, ','); getline (myfile, birth, ','); getline (myfile, death, ','); logs.push_back(name); } myfile.close(); } else { cout << "Unable to open file." << endl; } for(size_t i = 0; i < logs.size(); i++) { cout << logs[i] << endl; } } /* void readData (parameters) { ifstream myfile; file.open ("info.txt"); vector <string> information for(int i = 0; i < count; i++) } myfile.close(); return 0; } void writeData (parameters) { ofstream outputFile; outputFile.open("InfoTestFile.txt", fstream::app); string name; string sex; int birth; int death; cout << "Enter name of a Computer Scientist: "; cin >> name; outputFile << name << ", "; cout << "Enter sex: "; cin >> sex; outputFile << sex << ", "; cout << "Enter year of birth: "; cin >> birth; outputFile << birth << ", "; cout << "Enter year of death or -- if alive: "; cin >> death; outputFile << death << endl; outputFile.close(); cout << "Done!\n"; return 0; } */ <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: InverseKinematicsSolver.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 "InverseKinematicsSolver.h" #include "CoordinateReference.h" #include "MarkersReference.h" #include "OrientationsReference.h" #include "Model/Model.h" #include "Model/MarkerSet.h" using namespace std; using namespace SimTK; namespace OpenSim { //______________________________________________________________________________ /* * An implementation of the InverseKinematicsSolver * * @param model to assemble */ InverseKinematicsSolver:: InverseKinematicsSolver(const Model &model, MarkersReference &markersReference, SimTK::Array_<CoordinateReference> &coordinateReferences, double constraintWeight) : AssemblySolver(model, coordinateReferences, constraintWeight), _markersReference(markersReference), _orientationsReference(*new OrientationsReference()) { setAuthors("Ajay Seth"); // Do some consistency checking for markers const MarkerSet &modelMarkerSet = getModel().getMarkerSet(); if(modelMarkerSet.getSize() < 1){ std::cout << "InverseKinematicsSolver: Model has no markers!" << std::endl; throw Exception("InverseKinematicsSolver: Model has no markers!"); } const SimTK::Array_<std::string> &markerNames = _markersReference.getNames(); // size and content as in trc file if(markerNames.size() < 1){ std::cout << "InverseKinematicsSolver: No markers available from data provided." << std::endl; throw Exception("InverseKinematicsSolver: No markers available from data provided."); } int index=0, cnt=0; for(unsigned int i=0; i < markerNames.size(); i++) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); if(index >= 0) //found corresponding model cnt++; } if(cnt < 1){ std::cout <<"InverseKinematicsSolver: Marker data does not correspond to any model markers." << std::endl; throw Exception("InverseKinematicsSolver: Marker data does not correspond to any model markers."); } if(cnt < 4) cout << "WARNING: InverseKinematicsSolver found only " << cnt << " markers to track." << endl; } /* Change the weighting of a marker to take affect when assemble or track is called next. Update a marker's weight by name. */ void InverseKinematicsSolver::updateMarkerWeight(const std::string &markerName, double value) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); updateMarkerWeight(index, value); } /* Update a marker's weight by its index. */ void InverseKinematicsSolver::updateMarkerWeight(int markerIndex, double value) { if(markerIndex >=0 && markerIndex < _markersReference.updMarkerWeightSet().getSize()){ _markersReference.updMarkerWeightSet()[markerIndex].setWeight(value); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(markerIndex), value); } else throw Exception("InverseKinematicsSolver::updateMarkerWeight: invalid markerIndex."); } /* Update all markers weights by order in the markersReference passed in to construct the solver. */ void InverseKinematicsSolver::updateMarkerWeights(const SimTK::Array_<double> &weights) { if(static_cast<unsigned>(_markersReference.updMarkerWeightSet().getSize()) == weights.size()){ for(unsigned int i=0; i<weights.size(); i++){ _markersReference.updMarkerWeightSet()[i].setWeight(weights[i]); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(i), weights[i]); } } else throw Exception("InverseKinematicsSolver::updateMarkerWeights: invalid size of weights."); } /* Compute and return the spatial location of a marker in ground. */ SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); return computeCurrentMarkerLocation(index); } SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerLocation: invalid markerIndex."); } /* Compute and return the spatial locations of all markers in ground. */ void InverseKinematicsSolver::computeCurrentMarkerLocations(SimTK::Array_<SimTK::Vec3> &markerLocations) { markerLocations.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerLocations.size(); i++) markerLocations[i] = _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(i)); } /* Compute and return the distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); return computeCurrentMarkerError(index); } double InverseKinematicsSolver::computeCurrentMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerError: invalid markerIndex."); } /* Compute and return the distance errors between all model markers and their observations. */ void InverseKinematicsSolver::computeCurrentMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(i)); } /* Compute and return the squared-distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentSquaredMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); return computeCurrentSquaredMarkerError(index); } double InverseKinematicsSolver::computeCurrentSquaredMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerSquaredError: invalid markerIndex."); } /* Compute and return the distance errors between all model marker and observations. */ void InverseKinematicsSolver::computeCurrentSquaredMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(i)); } /* Marker errors are reported in order different from tasks file or model, find name corresponding to passed in index */ std::string InverseKinematicsSolver::getMarkerNameForIndex(int markerIndex) const { return _markerAssemblyCondition->getMarkerName(SimTK::Markers::MarkerIx(markerIndex)); } /* Internal method to convert the MarkerReferences into additional goals of the of the base assembly solver, that is going to do the assembly. */ void InverseKinematicsSolver::setupGoals(SimTK::State &s) { // Setup coordinates performed by the base class AssemblySolver::setupGoals(s); setupMarkersGoal(s); updateGoals(s); } void InverseKinematicsSolver::setupMarkersGoal(SimTK::State &s) { std::unique_ptr<SimTK::Markers> condOwner(new SimTK::Markers()); _markerAssemblyCondition.reset(condOwner.get()); // Setup markers goals // Get lists of all markers by names and corresponding weights from the MarkersReference const SimTK::Array_<SimTK::String> &markerNames = _markersReference.getNames(); SimTK::Array_<double> markerWeights; _markersReference.getWeights(s, markerWeights); // get markers defined by the model const MarkerSet &modelMarkerSet = getModel().getMarkerSet(); // get markers with specified tasks/weights const Set<MarkerWeight>& mwSet = _markersReference.updMarkerWeightSet(); int index = -1; int wIndex = -1; SimTK::Transform X_BF; //Loop through all markers in the reference for (unsigned int i = 0; i < markerNames.size(); ++i) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); wIndex = mwSet.getIndex(markerNames[i], wIndex); if ((index >= 0) && (wIndex >= 0)) { Marker &marker = modelMarkerSet[index]; const SimTK::MobilizedBody& mobod = marker.getParentFrame().getMobilizedBody(); X_BF = marker.getParentFrame().findTransformInBaseFrame(); _markerAssemblyCondition-> addMarker(marker.getName(), mobod, X_BF*marker.get_location(), markerWeights[i]); } } // Add marker goal to the ik objective and transfer ownership of the // goal (AssemblyCondition) to Assembler updAssembler().adoptAssemblyGoal(condOwner.release()); // lock-in the order that the observations (markers) are in and this cannot change from frame to frame // and we can use an array of just the data for updating _markerAssemblyCondition->defineObservationOrder(markerNames); } void InverseKinematicsSolver::setupOrientationsGoal(SimTK::State &s) { std::unique_ptr<SimTK::OrientationSensors> condOwner(new SimTK::OrientationSensors()); _orientationAssemblyCondition.reset(condOwner.get()); // Setup markers goals // Get lists of all markers by names and corresponding weights from the MarkersReference const SimTK::Array_<SimTK::String> &markerNames = _markersReference.getNames(); SimTK::Array_<double> markerWeights; _markersReference.getWeights(s, markerWeights); // get markers defined by the model const MarkerSet &modelMarkerSet = getModel().getMarkerSet(); // get markers with specified tasks/weights const Set<MarkerWeight>& mwSet = _markersReference.updMarkerWeightSet(); int index = -1; int wIndex = -1; SimTK::Transform X_BF; //Loop through all markers in the reference for (unsigned int i = 0; i < markerNames.size(); ++i) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); wIndex = mwSet.getIndex(markerNames[i], wIndex); if ((index >= 0) && (wIndex >= 0)) { Marker &marker = modelMarkerSet[index]; const SimTK::MobilizedBody& mobod = marker.getParentFrame().getMobilizedBody(); X_BF = marker.getParentFrame().findTransformInBaseFrame(); _markerAssemblyCondition-> addMarker(marker.getName(), mobod, X_BF*marker.get_location(), markerWeights[i]); } } // Add marker goal to the ik objective and transfer ownership of the // goal (AssemblyCondition) to Assembler updAssembler().adoptAssemblyGoal(condOwner.release()); // lock-in the order that the observations (markers) are in and this cannot change from frame to frame // and we can use an array of just the data for updating _markerAssemblyCondition->defineObservationOrder(markerNames); } /* Internal method to update the time, reference values and/or their weights based on the state */ void InverseKinematicsSolver::updateGoals(const SimTK::State &s) { // update coordinates performed by the base class AssemblySolver::updateGoals(s); // specify the marker observations to be matched _markersReference.getValues(s, _markerValues); _markerAssemblyCondition->moveAllObservations(_markerValues); // specify the orientation observations to be matched //_orientationsReference.getValues(s, _orientationValues); //_orientationAssemblyCondition->moveAllObservations(_orientationValues); } } // end of namespace OpenSim <commit_msg>Implement the setup of the OrientationsGoal for the InverseKinematicsSolver<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: InverseKinematicsSolver.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Ajay Seth * * * * 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 "InverseKinematicsSolver.h" #include "CoordinateReference.h" #include "MarkersReference.h" #include "OrientationsReference.h" #include "Model/Model.h" #include "Model/MarkerSet.h" using namespace std; using namespace SimTK; namespace OpenSim { //______________________________________________________________________________ /* * An implementation of the InverseKinematicsSolver * * @param model to assemble */ InverseKinematicsSolver:: InverseKinematicsSolver(const Model &model, MarkersReference &markersReference, SimTK::Array_<CoordinateReference> &coordinateReferences, double constraintWeight) : AssemblySolver(model, coordinateReferences, constraintWeight), _markersReference(markersReference), _orientationsReference(*new OrientationsReference()) { setAuthors("Ajay Seth"); // Do some consistency checking for markers const MarkerSet &modelMarkerSet = getModel().getMarkerSet(); if(modelMarkerSet.getSize() < 1){ std::cout << "InverseKinematicsSolver: Model has no markers!" << std::endl; throw Exception("InverseKinematicsSolver: Model has no markers!"); } const SimTK::Array_<std::string> &markerNames = _markersReference.getNames(); // size and content as in trc file if(markerNames.size() < 1){ std::cout << "InverseKinematicsSolver: No markers available from data provided." << std::endl; throw Exception("InverseKinematicsSolver: No markers available from data provided."); } int index=0, cnt=0; for(unsigned int i=0; i < markerNames.size(); i++) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); if(index >= 0) //found corresponding model cnt++; } if(cnt < 1){ std::cout <<"InverseKinematicsSolver: Marker data does not correspond to any model markers." << std::endl; throw Exception("InverseKinematicsSolver: Marker data does not correspond to any model markers."); } if(cnt < 4) cout << "WARNING: InverseKinematicsSolver found only " << cnt << " markers to track." << endl; } /* Change the weighting of a marker to take affect when assemble or track is called next. Update a marker's weight by name. */ void InverseKinematicsSolver::updateMarkerWeight(const std::string &markerName, double value) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); updateMarkerWeight(index, value); } /* Update a marker's weight by its index. */ void InverseKinematicsSolver::updateMarkerWeight(int markerIndex, double value) { if(markerIndex >=0 && markerIndex < _markersReference.updMarkerWeightSet().getSize()){ _markersReference.updMarkerWeightSet()[markerIndex].setWeight(value); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(markerIndex), value); } else throw Exception("InverseKinematicsSolver::updateMarkerWeight: invalid markerIndex."); } /* Update all markers weights by order in the markersReference passed in to construct the solver. */ void InverseKinematicsSolver::updateMarkerWeights(const SimTK::Array_<double> &weights) { if(static_cast<unsigned>(_markersReference.updMarkerWeightSet().getSize()) == weights.size()){ for(unsigned int i=0; i<weights.size(); i++){ _markersReference.updMarkerWeightSet()[i].setWeight(weights[i]); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(i), weights[i]); } } else throw Exception("InverseKinematicsSolver::updateMarkerWeights: invalid size of weights."); } /* Compute and return the spatial location of a marker in ground. */ SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); return computeCurrentMarkerLocation(index); } SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerLocation: invalid markerIndex."); } /* Compute and return the spatial locations of all markers in ground. */ void InverseKinematicsSolver::computeCurrentMarkerLocations(SimTK::Array_<SimTK::Vec3> &markerLocations) { markerLocations.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerLocations.size(); i++) markerLocations[i] = _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(i)); } /* Compute and return the distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); return computeCurrentMarkerError(index); } double InverseKinematicsSolver::computeCurrentMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerError: invalid markerIndex."); } /* Compute and return the distance errors between all model markers and their observations. */ void InverseKinematicsSolver::computeCurrentMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(i)); } /* Compute and return the squared-distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentSquaredMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = (int)std::distance(names.begin(), p); return computeCurrentSquaredMarkerError(index); } double InverseKinematicsSolver::computeCurrentSquaredMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerSquaredError: invalid markerIndex."); } /* Compute and return the distance errors between all model marker and observations. */ void InverseKinematicsSolver::computeCurrentSquaredMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(i)); } /* Marker errors are reported in order different from tasks file or model, find name corresponding to passed in index */ std::string InverseKinematicsSolver::getMarkerNameForIndex(int markerIndex) const { return _markerAssemblyCondition->getMarkerName(SimTK::Markers::MarkerIx(markerIndex)); } /* Internal method to convert the MarkerReferences into additional goals of the of the base assembly solver, that is going to do the assembly. */ void InverseKinematicsSolver::setupGoals(SimTK::State &s) { // Setup coordinates performed by the base class AssemblySolver::setupGoals(s); setupMarkersGoal(s); setupOrientationsGoal(s); updateGoals(s); } void InverseKinematicsSolver::setupMarkersGoal(SimTK::State &s) { std::unique_ptr<SimTK::Markers> condOwner(new SimTK::Markers()); _markerAssemblyCondition.reset(condOwner.get()); // Setup markers goals // Get lists of all markers by names and corresponding weights from the MarkersReference const SimTK::Array_<SimTK::String> &markerNames = _markersReference.getNames(); SimTK::Array_<double> markerWeights; _markersReference.getWeights(s, markerWeights); // get markers defined by the model const MarkerSet &modelMarkerSet = getModel().getMarkerSet(); // get markers with specified tasks/weights const Set<MarkerWeight>& mwSet = _markersReference.updMarkerWeightSet(); int index = -1; int wIndex = -1; SimTK::Transform X_BF; //Loop through all markers in the reference for (unsigned int i = 0; i < markerNames.size(); ++i) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); wIndex = mwSet.getIndex(markerNames[i], wIndex); if ((index >= 0) && (wIndex >= 0)) { Marker &marker = modelMarkerSet[index]; const SimTK::MobilizedBody& mobod = marker.getParentFrame().getMobilizedBody(); X_BF = marker.getParentFrame().findTransformInBaseFrame(); _markerAssemblyCondition-> addMarker(marker.getName(), mobod, X_BF*marker.get_location(), markerWeights[i]); } } // Add marker goal to the ik objective and transfer ownership of the // goal (AssemblyCondition) to Assembler updAssembler().adoptAssemblyGoal(condOwner.release()); // lock-in the order that the observations (markers) are in and this cannot change from frame to frame // and we can use an array of just the data for updating _markerAssemblyCondition->defineObservationOrder(markerNames); } void InverseKinematicsSolver::setupOrientationsGoal(SimTK::State &s) { std::unique_ptr<SimTK::OrientationSensors> condOwner(new SimTK::OrientationSensors()); _orientationAssemblyCondition.reset(condOwner.get()); // Setup orientations tracking goal // Get lists of orientations by name and corresponding weights const SimTK::Array_<SimTK::String> &osensorNames = _orientationsReference.getNames(); // If no orientations in the reference to be trackes, then no goal // to add and we can stop. if (osensorNames.size() < 1) { return; } SimTK::Array_<double> orientationWeights; _orientationsReference.getWeights(s, orientationWeights); // get orientation sensors defined by the model const auto onFrames = getModel().getComponentList<PhysicalFrame>(); for (const auto& modelFrame : onFrames) { const std::string& modelFrameName = modelFrame.getName(); auto found = std::find(osensorNames.begin(), osensorNames.end(), modelFrameName); if (found) { int index = (int)std::distance(osensorNames.begin(), found); _orientationAssemblyCondition->addOSensor(modelFrameName, modelFrame.getMobilizedBodyIndex(), modelFrame.findTransformInBaseFrame().R(), orientationWeights[index]); } } // Add orientations goal to the ik objective and transfer ownership of the // goal (AssemblyCondition) to Assembler updAssembler().adoptAssemblyGoal(condOwner.release()); // lock-in the order that the observations (orientations) are in and this // cannot change from frame to frame and we can use an array of just the // data for updating _markerAssemblyCondition->defineObservationOrder(osensorNames); } /* Internal method to update the time, reference values and/or their weights based on the state */ void InverseKinematicsSolver::updateGoals(const SimTK::State &s) { // update coordinates performed by the base class AssemblySolver::updateGoals(s); // specify the marker observations to be matched _markersReference.getValues(s, _markerValues); _markerAssemblyCondition->moveAllObservations(_markerValues); // specify the orientation observations to be matched //_orientationsReference.getValues(s, _orientationValues); //_orientationAssemblyCondition->moveAllObservations(_orientationValues); } } // end of namespace OpenSim <|endoftext|>
<commit_before>/* InverseKinematicsSolver.cpp * Author: Ajay Seth * Copyright (c) 2006 Stanford University * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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 "InverseKinematicsSolver.h" #include "CoordinateReference.h" #include "MarkersReference.h" #include "Model/Model.h" #include "Model/MarkerSet.h" using namespace std; using namespace SimTK; namespace OpenSim { //______________________________________________________________________________ /** * An implementation of the InverseKinematicsSolver * * @param model to assemble */ InverseKinematicsSolver::InverseKinematicsSolver(const Model &model, MarkersReference &markersReference, SimTK::Array_<CoordinateReference> &coordinateReferences, double constraintWeight) : AssemblySolver(model, coordinateReferences, constraintWeight), _markersReference(markersReference) { // Base AssemblySolver takes care of creating the underlying _assembler and setting up CoordinateReferences; _markerAssemblyCondition = NULL; // Do some consistency checking for markers const MarkerSet &modelMarkerSet = _model.getMarkerSet(); if(modelMarkerSet.getSize() < 1) throw Exception("InverseKinematicsSolver: Model has no markers!"); const SimTK::Array_<std::string> &markerNames = _markersReference.getNames(); if(markerNames.size() < 1) throw Exception("InverseKinematicsSolver: No markers available from data provided."); int index=0, cnt=0; for(unsigned int i=0; i < markerNames.size(); i++) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); if(index >= 0) //found corresponding model cnt++; } if(cnt < 1) throw Exception("InverseKinematicsSolver: Marker data does not correspond to any model markers."); if(cnt < 4) cout << "WARNING: InverseKinematicsSolver found only " << cnt << " markers to track." << endl; } /** Change the weighting of a marker to take affect when assemble or track is called next. Update a marker's weight by name. */ void InverseKinematicsSolver::updateMarkerWeight(const std::string &markerName, double value) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); updateMarkerWeight(index, value); } /** Update a marker's weight by its index. */ void InverseKinematicsSolver::updateMarkerWeight(int markerIndex, double value) { if(markerIndex >=0 && markerIndex < _markersReference.updMarkerWeightSet().getSize()){ _markersReference.updMarkerWeightSet()[markerIndex].setWeight(value); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(markerIndex), value); } else throw Exception("InverseKinematicsSolver::updateMarkerWeight: invalid markerIndex."); } /** Update all markers weights by order in the markersReference passed in to construct the solver. */ void InverseKinematicsSolver::updateMarkerWeights(const SimTK::Array_<double> &weights) { if(_markersReference.updMarkerWeightSet().getSize() == weights.size()){ for(unsigned int i=0; i<weights.size(); i++){ _markersReference.updMarkerWeightSet()[i].setWeight(weights[i]); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(i), weights[i]); } } else throw Exception("InverseKinematicsSolver::updateMarkerWeights: invalid size of weights."); } /** Compute and return the spatial location of a marker in ground. */ SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); return computeCurrentMarkerLocation(index); } SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerLocation: invalid markerIndex."); } /** Compute and return the spatial locations of all markers in ground. */ void InverseKinematicsSolver::computeCurrentMarkerLocations(SimTK::Array_<SimTK::Vec3> &markerLocations) { markerLocations.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerLocations.size(); i++) markerLocations[i] = _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(i)); } /** Compute and return the distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); return computeCurrentMarkerError(index); } double InverseKinematicsSolver::computeCurrentMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerError: invalid markerIndex."); } /** Compute and return the distance errors between all model markers and their observations. */ void InverseKinematicsSolver::computeCurrentMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(i)); } /** Compute and return the squared-distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentSquaredMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); return computeCurrentSquaredMarkerError(index); } double InverseKinematicsSolver::computeCurrentSquaredMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerSquaredError: invalid markerIndex."); } /** Compute and return the distance errors between all model marker and observations. */ void InverseKinematicsSolver::computeCurrentSquaredMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(i)); } /** Internal method to convert the MarkerReferences into additional goals of the of the base assembly solver, that is going to do the assembly. */ void InverseKinematicsSolver::setupGoals(SimTK::State &s) { // Setup coordinates performed by the base class AssemblySolver::setupGoals(s); _markerAssemblyCondition = new SimTK::Markers(); // Setup markers goals // Get lists of all markers by names and corresponding weights from the MarkersReference const SimTK::Array_<std::string> &markerNames = _markersReference.getNames(); SimTK::Array_<double> markerWeights; _markersReference.getWeights(s, markerWeights); // get markers defined by the model const MarkerSet &modelMarkerSet = _model.getMarkerSet(); int index = 0; //Loop through all markers in the reference for(unsigned int i=0; i < markerNames.size(); i++){ // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); if(index >= 0){ Marker &marker = modelMarkerSet[index]; const SimTK::MobilizedBody &mobod = _model.getMatterSubsystem().getMobilizedBody(marker.getBody().getIndex()); _markerAssemblyCondition->addMarker(marker.getName(), mobod, marker.getOffset(), markerWeights[i]); cout << "IKSolver Marker: " << markerNames[i] << " " << marker.getName() << " weight: " << markerWeights[i] << endl; } } // Add marker goal to the ik objective _assembler->adoptAssemblyGoal(_markerAssemblyCondition); // lock-in the order that the observations (markers) are in and this cannot change from frame to frame // and we can use an array of just the data for updating _markerAssemblyCondition->defineObservationOrder(markerNames); updateGoals(s); } /** Internal method to update the time, reference values and/or their weights based on the state */ void InverseKinematicsSolver::updateGoals(const SimTK::State &s) { // update coordinates performed by the base class AssemblySolver::updateGoals(s); // specify the (initial) observations to be matched _markersReference.getValues(s, _markerValues); _markerAssemblyCondition->moveAllObservations(_markerValues); } } // end of namespace OpenSim<commit_msg>Use SimTK::String instead of std::string for Marker names when interfacing to SimTK. Fixes compilation/link errors under VS8Pro<commit_after>/* InverseKinematicsSolver.cpp * Author: Ajay Seth * Copyright (c) 2006 Stanford University * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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 "InverseKinematicsSolver.h" #include "CoordinateReference.h" #include "MarkersReference.h" #include "Model/Model.h" #include "Model/MarkerSet.h" using namespace std; using namespace SimTK; namespace OpenSim { //______________________________________________________________________________ /** * An implementation of the InverseKinematicsSolver * * @param model to assemble */ InverseKinematicsSolver::InverseKinematicsSolver(const Model &model, MarkersReference &markersReference, SimTK::Array_<CoordinateReference> &coordinateReferences, double constraintWeight) : AssemblySolver(model, coordinateReferences, constraintWeight), _markersReference(markersReference) { // Base AssemblySolver takes care of creating the underlying _assembler and setting up CoordinateReferences; _markerAssemblyCondition = NULL; // Do some consistency checking for markers const MarkerSet &modelMarkerSet = _model.getMarkerSet(); if(modelMarkerSet.getSize() < 1) throw Exception("InverseKinematicsSolver: Model has no markers!"); const SimTK::Array_<std::string> &markerNames = _markersReference.getNames(); if(markerNames.size() < 1) throw Exception("InverseKinematicsSolver: No markers available from data provided."); int index=0, cnt=0; for(unsigned int i=0; i < markerNames.size(); i++) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); if(index >= 0) //found corresponding model cnt++; } if(cnt < 1) throw Exception("InverseKinematicsSolver: Marker data does not correspond to any model markers."); if(cnt < 4) cout << "WARNING: InverseKinematicsSolver found only " << cnt << " markers to track." << endl; } /** Change the weighting of a marker to take affect when assemble or track is called next. Update a marker's weight by name. */ void InverseKinematicsSolver::updateMarkerWeight(const std::string &markerName, double value) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); updateMarkerWeight(index, value); } /** Update a marker's weight by its index. */ void InverseKinematicsSolver::updateMarkerWeight(int markerIndex, double value) { if(markerIndex >=0 && markerIndex < _markersReference.updMarkerWeightSet().getSize()){ _markersReference.updMarkerWeightSet()[markerIndex].setWeight(value); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(markerIndex), value); } else throw Exception("InverseKinematicsSolver::updateMarkerWeight: invalid markerIndex."); } /** Update all markers weights by order in the markersReference passed in to construct the solver. */ void InverseKinematicsSolver::updateMarkerWeights(const SimTK::Array_<double> &weights) { if(_markersReference.updMarkerWeightSet().getSize() == weights.size()){ for(unsigned int i=0; i<weights.size(); i++){ _markersReference.updMarkerWeightSet()[i].setWeight(weights[i]); _markerAssemblyCondition->changeMarkerWeight(SimTK::Markers::MarkerIx(i), weights[i]); } } else throw Exception("InverseKinematicsSolver::updateMarkerWeights: invalid size of weights."); } /** Compute and return the spatial location of a marker in ground. */ SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); return computeCurrentMarkerLocation(index); } SimTK::Vec3 InverseKinematicsSolver::computeCurrentMarkerLocation(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerLocation: invalid markerIndex."); } /** Compute and return the spatial locations of all markers in ground. */ void InverseKinematicsSolver::computeCurrentMarkerLocations(SimTK::Array_<SimTK::Vec3> &markerLocations) { markerLocations.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerLocations.size(); i++) markerLocations[i] = _markerAssemblyCondition->findCurrentMarkerLocation(SimTK::Markers::MarkerIx(i)); } /** Compute and return the distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); return computeCurrentMarkerError(index); } double InverseKinematicsSolver::computeCurrentMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerError: invalid markerIndex."); } /** Compute and return the distance errors between all model markers and their observations. */ void InverseKinematicsSolver::computeCurrentMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerError(SimTK::Markers::MarkerIx(i)); } /** Compute and return the squared-distance error between model marker and observation. */ double InverseKinematicsSolver::computeCurrentSquaredMarkerError(const std::string &markerName) { const Array_<std::string> &names = _markersReference.getNames(); SimTK::Array_<const std::string>::iterator p = std::find(names.begin(), names.end(), markerName); int index = std::distance(names.begin(), p); return computeCurrentSquaredMarkerError(index); } double InverseKinematicsSolver::computeCurrentSquaredMarkerError(int markerIndex) { if(markerIndex >=0 && markerIndex < _markerAssemblyCondition->getNumMarkers()){ return _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(markerIndex)); } else throw Exception("InverseKinematicsSolver::computeCurrentMarkerSquaredError: invalid markerIndex."); } /** Compute and return the distance errors between all model marker and observations. */ void InverseKinematicsSolver::computeCurrentSquaredMarkerErrors(SimTK::Array_<double> &markerErrors) { markerErrors.resize(_markerAssemblyCondition->getNumMarkers()); for(unsigned int i=0; i<markerErrors.size(); i++) markerErrors[i] = _markerAssemblyCondition->findCurrentMarkerErrorSquared(SimTK::Markers::MarkerIx(i)); } /** Internal method to convert the MarkerReferences into additional goals of the of the base assembly solver, that is going to do the assembly. */ void InverseKinematicsSolver::setupGoals(SimTK::State &s) { // Setup coordinates performed by the base class AssemblySolver::setupGoals(s); _markerAssemblyCondition = new SimTK::Markers(); // Setup markers goals // Get lists of all markers by names and corresponding weights from the MarkersReference const SimTK::Array_<SimTK::String> &markerNames = _markersReference.getNames(); SimTK::Array_<double> markerWeights; _markersReference.getWeights(s, markerWeights); // get markers defined by the model const MarkerSet &modelMarkerSet = _model.getMarkerSet(); int index = 0; //Loop through all markers in the reference for(unsigned int i=0; i < markerNames.size(); i++){ // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(markerNames[i], index); if(index >= 0){ Marker &marker = modelMarkerSet[index]; const SimTK::MobilizedBody &mobod = _model.getMatterSubsystem().getMobilizedBody(marker.getBody().getIndex()); _markerAssemblyCondition->addMarker(marker.getName(), mobod, marker.getOffset(), markerWeights[i]); cout << "IKSolver Marker: " << markerNames[i] << " " << marker.getName() << " weight: " << markerWeights[i] << endl; } } // Add marker goal to the ik objective _assembler->adoptAssemblyGoal(_markerAssemblyCondition); // lock-in the order that the observations (markers) are in and this cannot change from frame to frame // and we can use an array of just the data for updating _markerAssemblyCondition->defineObservationOrder(markerNames); updateGoals(s); } /** Internal method to update the time, reference values and/or their weights based on the state */ void InverseKinematicsSolver::updateGoals(const SimTK::State &s) { // update coordinates performed by the base class AssemblySolver::updateGoals(s); // specify the (initial) observations to be matched _markersReference.getValues(s, _markerValues); _markerAssemblyCondition->moveAllObservations(_markerValues); } } // end of namespace OpenSim<|endoftext|>
<commit_before>// now in options //=============================================// //const char* centralityEstimator = "V0M"; //const char* centralityEstimator = "CL1"; //const char* centralityEstimator = "TRK"; //=============================================// //Bool_t gRunShuffling = kFALSE; //Bool_t gRunShuffling = kTRUE; //=============================================// //_________________________________________________________// AliAnalysisTaskBF *AddTaskBalanceCentralityTrain(Double_t centrMin=0., Double_t centrMax=100., Bool_t gRunShuffling=kFALSE, TString centralityEstimator="V0M", Double_t vertexZ=10., Double_t DCAxy=-1, Double_t DCAz=-1, Double_t ptMin=0.3, Double_t ptMax=1.5, Double_t etaMin=-0.8, Double_t etaMax=0.8, Double_t maxTPCchi2 = -1, Int_t minNClustersTPC = -1, TString fileNameBase="AnalysisResults") { // Creates a balance function analysis task and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. TString centralityName(""); centralityName+=Form("%.0f",centrMin); centralityName+="-"; centralityName+=Form("%.0f",centrMax); centralityName+="_"; centralityName+=Form("vZ%.1f",vertexZ); centralityName+="_"; centralityName+=Form("DCAxy%.1f",DCAxy); centralityName+="_"; centralityName+=Form("DCAz%.1f",DCAz); centralityName+="_Pt"; centralityName+=Form("%.1f",ptMin); centralityName+="-"; centralityName+=Form("%.1f",ptMax); centralityName+="_Eta"; centralityName+=Form("%.1f",etaMin); centralityName+="-"; centralityName+=Form("%.1f",etaMax); TString outputFileName(fileNameBase); outputFileName.Append(".root"); //=========================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskBF", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //=========================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskBF", "This task requires an input event handler"); return NULL; } TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if(dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())) analysisType = "MC"; // for local changed BF configuration //gROOT->LoadMacro("./configBalanceFunctionAnalysis.C"); gROOT->LoadMacro("$ALICE_ROOT/PWG2/EBYE/macros/configBalanceFunctionAnalysis.C"); AliBalance *bf = 0; // Balance Function object AliBalance *bfs = 0; // shuffled Balance function object if (analysisType=="ESD"){ bf = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax); if(gRunShuffling) bfs = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kTRUE); } else if (analysisType=="AOD"){ bf = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax); if(gRunShuffling) bfs = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kTRUE); } else if (analysisType=="MC"){ bf = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax); if(gRunShuffling) bfs = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kTRUE); } else{ ::Error("AddTaskBF", "analysis type NOT known."); return NULL; } // Create the task, add it to manager and configure it. //=========================================================================== AliAnalysisTaskBF *taskBF = new AliAnalysisTaskBF("TaskBF"); taskBF->SetAnalysisObject(bf); if(gRunShuffling) taskBF->SetShufflingObject(bfs); taskBF->SetCentralityPercentileRange(centrMin,centrMax); if(analysisType == "ESD") { AliESDtrackCuts *trackCuts = GetTrackCutsObject(ptMin,ptMax,etaMin,etaMax,maxTPCchi2,DCAxy,DCAz,minNClustersTPC); taskBF->SetAnalysisCutObject(trackCuts); } else if(analysisType == "AOD") { // pt and eta cut (pt_min, pt_max, eta_min, eta_max) taskBF->SetAODtrackCutBit(128); taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax); // set extra DCA cuts (-1 no extra cut) taskBF->SetExtraDCACutsAOD(DCAxy,DCAz); // set extra TPC chi2 / nr of clusters cut taskBF->SetExtraTPCCutsAOD(maxTPCchi2, minNClustersTPC); } else if(analysisType == "MC") { taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax); } // offline trigger selection (AliVEvent.h) // taskBF->UseOfflineTrigger(); // NOT used (selection is done with the AliAnalysisTaskSE::SelectCollisionCandidates()) // with this only selected events are analyzed (first 2 bins in event QA histogram are the same)) // documentation in https://twiki.cern.ch/twiki/bin/viewauth/ALICE/PWG1EvSelDocumentation taskBF->SelectCollisionCandidates(AliVEvent::kMB); // centrality estimator (default = V0M) taskBF->SetCentralityEstimator(centralityEstimator); // vertex cut (x,y,z) taskBF->SetVertexDiamond(.3,.3,vertexZ); //bf->PrintAnalysisSettings(); mgr->AddTask(taskBF); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWG2EbyE.outputBalanceFunctionAnalysis"; AliAnalysisDataContainer *coutQA = mgr->CreateContainer(Form("listQA_%s",centralityName.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); AliAnalysisDataContainer *coutBF = mgr->CreateContainer(Form("listBF_%s",centralityName.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); if(gRunShuffling) AliAnalysisDataContainer *coutBFS= mgr->CreateContainer(Form("listBFShuffled_%s",centralityName.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); mgr->ConnectInput(taskBF, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskBF, 1, coutQA); mgr->ConnectOutput(taskBF, 2, coutBF); if(gRunShuffling) mgr->ConnectOutput(taskBF, 3, coutBFS); return taskBF; } <commit_msg>Updated macro (Micahael Weber)<commit_after>// now in options //=============================================// //const char* centralityEstimator = "V0M"; //const char* centralityEstimator = "CL1"; //const char* centralityEstimator = "TRK"; //=============================================// //Bool_t gRunShuffling = kFALSE; //Bool_t gRunShuffling = kTRUE; //=============================================// //_________________________________________________________// AliAnalysisTaskBF *AddTaskBalanceCentralityTrain(Double_t centrMin=0., Double_t centrMax=100., Bool_t gRunShuffling=kFALSE, TString centralityEstimator="V0M", Double_t vertexZ=10., Double_t DCAxy=-1, Double_t DCAz=-1, Double_t ptMin=0.3, Double_t ptMax=1.5, Double_t etaMin=-0.8, Double_t etaMax=0.8, Double_t maxTPCchi2 = -1, Int_t minNClustersTPC = -1, Int_t AODfilterBit = 128, TString fileNameBase="AnalysisResults") { // Creates a balance function analysis task and adds it to the analysis manager. // Get the pointer to the existing analysis manager via the static access method. TString centralityName(""); centralityName+=Form("%.0f",centrMin); centralityName+="-"; centralityName+=Form("%.0f",centrMax); centralityName+="_"; centralityName+=Form("vZ%.1f",vertexZ); centralityName+="_"; centralityName+=Form("DCAxy%.1f",DCAxy); centralityName+="_"; centralityName+=Form("DCAz%.1f",DCAz); centralityName+="_Pt"; centralityName+=Form("%.1f",ptMin); centralityName+="-"; centralityName+=Form("%.1f",ptMax); centralityName+="_Eta"; centralityName+=Form("%.1f",etaMin); centralityName+="-"; centralityName+=Form("%.1f",etaMax); centralityName+="_Chi"; centralityName+=Form("%.1f",maxTPCchi2); centralityName+="_nClus"; centralityName+=Form("%d",minNClustersTPC); centralityName+="_Bit"; centralityName+=Form("%d",AODfilterBit); TString outputFileName(fileNameBase); outputFileName.Append(".root"); //=========================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskBF", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //=========================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskBF", "This task requires an input event handler"); return NULL; } TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" if(dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())) analysisType = "MC"; // for local changed BF configuration //gROOT->LoadMacro("./configBalanceFunctionAnalysis.C"); gROOT->LoadMacro("$ALICE_ROOT/PWG2/EBYE/macros/configBalanceFunctionAnalysis.C"); AliBalance *bf = 0; // Balance Function object AliBalance *bfs = 0; // shuffled Balance function object if (analysisType=="ESD"){ bf = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax); if(gRunShuffling) bfs = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kTRUE); } else if (analysisType=="AOD"){ bf = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax); if(gRunShuffling) bfs = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kTRUE); } else if (analysisType=="MC"){ bf = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax); if(gRunShuffling) bfs = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kTRUE); } else{ ::Error("AddTaskBF", "analysis type NOT known."); return NULL; } // Create the task, add it to manager and configure it. //=========================================================================== AliAnalysisTaskBF *taskBF = new AliAnalysisTaskBF("TaskBF"); taskBF->SetAnalysisObject(bf); if(gRunShuffling) taskBF->SetShufflingObject(bfs); taskBF->SetCentralityPercentileRange(centrMin,centrMax); if(analysisType == "ESD") { AliESDtrackCuts *trackCuts = GetTrackCutsObject(ptMin,ptMax,etaMin,etaMax,maxTPCchi2,DCAxy,DCAz,minNClustersTPC); taskBF->SetAnalysisCutObject(trackCuts); } else if(analysisType == "AOD") { // pt and eta cut (pt_min, pt_max, eta_min, eta_max) taskBF->SetAODtrackCutBit(AODfilterBit); taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax); // set extra DCA cuts (-1 no extra cut) taskBF->SetExtraDCACutsAOD(DCAxy,DCAz); // set extra TPC chi2 / nr of clusters cut taskBF->SetExtraTPCCutsAOD(maxTPCchi2, minNClustersTPC); } else if(analysisType == "MC") { taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax); } // offline trigger selection (AliVEvent.h) // taskBF->UseOfflineTrigger(); // NOT used (selection is done with the AliAnalysisTaskSE::SelectCollisionCandidates()) // with this only selected events are analyzed (first 2 bins in event QA histogram are the same)) // documentation in https://twiki.cern.ch/twiki/bin/viewauth/ALICE/PWG1EvSelDocumentation taskBF->SelectCollisionCandidates(AliVEvent::kMB); // centrality estimator (default = V0M) taskBF->SetCentralityEstimator(centralityEstimator); // vertex cut (x,y,z) taskBF->SetVertexDiamond(.3,.3,vertexZ); //bf->PrintAnalysisSettings(); mgr->AddTask(taskBF); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputFileName = AliAnalysisManager::GetCommonFileName(); outputFileName += ":PWG2EbyE.outputBalanceFunctionAnalysis"; AliAnalysisDataContainer *coutQA = mgr->CreateContainer(Form("listQA_%s",centralityName.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); AliAnalysisDataContainer *coutBF = mgr->CreateContainer(Form("listBF_%s",centralityName.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); if(gRunShuffling) AliAnalysisDataContainer *coutBFS= mgr->CreateContainer(Form("listBFShuffled_%s",centralityName.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data()); mgr->ConnectInput(taskBF, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskBF, 1, coutQA); mgr->ConnectOutput(taskBF, 2, coutBF); if(gRunShuffling) mgr->ConnectOutput(taskBF, 3, coutBFS); return taskBF; } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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. ******************************************************************************/ #ifdef _WIN32 #include <Windows.h> #include <processenv.h> #include <io.h> #include <fcntl.h> #include <iostream> #include <direct.h> #include <csignal> #include <cstdio> #include <cstdlib> #include <codecvt> #include <packr.h> #define RETURN_SUCCESS (0x00000000) typedef LONG NT_STATUS; typedef NT_STATUS (WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); using namespace std; const char __CLASS_PATH_DELIM = ';'; extern "C" { __declspec(dllexport) DWORD NvOptimusEnablement = 1; __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; } static void waitAtExit() { cout << "Press ENTER key to exit." << endl << flush; cin.get(); } /** * If the '--console' argument is passed, then a new console is allocated, otherwise attaching to the parent console is attempted. * * @param argc the number of elements in {@code argv} * @param argv the list of arguments to parse for --console * @return true if the parent console was successfully attached to or a new console was allocated. false if no console could be acquired */ static bool attachToOrAllocateConsole(int argc, PTCHAR *argv) { bool allocConsole = false; // pre-parse command line here to have a console in case of command line parse errors for (int arg = 0; arg < argc && !allocConsole; arg++) { allocConsole = (argv[arg] != nullptr && wcsicmp(argv[arg], TEXT("--console")) == 0); } bool gotConsole = false; if (allocConsole) { FreeConsole(); gotConsole = AllocConsole(); } else { gotConsole = AttachConsole(ATTACH_PARENT_PROCESS); } if (gotConsole) { // Open C standard streams FILE *reusedThrowAwayHandle; freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stdout); freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stderr); freopen_s(&reusedThrowAwayHandle, "CONIN$", "r", stdin); cout.clear(); clog.clear(); cerr.clear(); cin.clear(); // Open the C++ wide streams HANDLE hConOut = CreateFile(TEXT("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); HANDLE hConIn = CreateFile(TEXT("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); SetStdHandle(STD_OUTPUT_HANDLE, hConOut); SetStdHandle(STD_ERROR_HANDLE, hConOut); SetStdHandle(STD_INPUT_HANDLE, hConIn); wcout.clear(); wclog.clear(); wcerr.clear(); wcin.clear(); SetConsoleOutputCP(CP_UTF8); if (allocConsole) { atexit(waitAtExit); } } return gotConsole; } static void printLastError(const PTCHAR reason) { LPTSTR buffer; DWORD errorCode = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, nullptr); wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; cerr << "Error code [" << errorCode << "] when trying to " << converter.to_bytes(reason) << ": " << converter.to_bytes(buffer) << endl; LocalFree(buffer); } static void catchFunction(int signo) { puts("Interactive attention signal caught."); cerr << "Caught signal " << signo << endl; } bool g_showCrashDialog = false; LONG WINAPI crashHandler(EXCEPTION_POINTERS * /*ExceptionInfo*/) { cerr << "Unhandled windows exception occurred" << endl; return g_showCrashDialog ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER; } static void clearEnvironment() { cout << "clearEnvironment" << endl; _putenv_s("_JAVA_OPTIONS", ""); _putenv_s("JAVA_TOOL_OPTIONS", ""); _putenv_s("CLASSPATH", ""); } static void registerSignalHandlers() { void (*code)(int); code = signal(SIGINT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGINT" << endl; } code = signal(SIGILL, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGILL" << endl; } code = signal(SIGFPE, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGFPE" << endl; } code = signal(SIGSEGV, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGSEGV" << endl; } code = signal(SIGTERM, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGTERM" << endl; } code = signal(SIGBREAK, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGBREAK" << endl; } code = signal(SIGABRT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT" << endl; } code = signal(SIGABRT_COMPAT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT_COMPAT" << endl; } SetUnhandledExceptionFilter(crashHandler); } int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { registerSignalHandlers(); clearEnvironment(); try { int argc = 0; PTCHAR commandLine = GetCommandLine(); PTCHAR *argv = CommandLineToArgvW(commandLine, &argc); attachToOrAllocateConsole(argc, argv); if (!setCmdLineArguments(argc, argv)) { cerr << "Failed to set the command line arguments" << endl; return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); } catch (exception &theException) { cerr << "Caught exception:" << endl; cerr << theException.what() << endl; } catch (...) { cerr << "Caught unknown exception:" << endl; } return 0; } int wmain(int argc, wchar_t **argv) { SetConsoleOutputCP(CP_UTF8); registerSignalHandlers(); clearEnvironment(); if (!setCmdLineArguments(argc, argv)) { return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); return 0; } bool loadJNIFunctions(GetDefaultJavaVMInitArgs *getDefaultJavaVMInitArgs, CreateJavaVM *createJavaVM) { LPCTSTR jvmDLLPath = TEXT("jre\\bin\\server\\jvm.dll"); HINSTANCE hinstLib = LoadLibrary(jvmDLLPath); if (hinstLib == nullptr) { DWORD errorCode = GetLastError(); if (verbose) { cout << "Last error code " << errorCode << endl; } if (errorCode == 126) { // "The specified module could not be found." // load msvcr*.dll from the bundled JRE, then try again if (verbose) { cout << "Failed to load jvm.dll. Trying to load msvcr*.dll first ..." << endl; } WIN32_FIND_DATA FindFileData; HANDLE hFind = nullptr; TCHAR msvcrPath[MAX_PATH]; hFind = FindFirstFile(TEXT("jre\\bin\\msvcr*.dll"), &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { if (verbose) { cout << "Couldn't find msvcr*.dll file." << "FindFirstFile failed " << GetLastError() << "." << endl; } } else { FindClose(hFind); if (verbose) { cout << "Found msvcr*.dll file " << FindFileData.cFileName << endl; } wcscpy(msvcrPath, TEXT("jre\\bin\\")); wcscat(msvcrPath, FindFileData.cFileName); HINSTANCE hinstVCR = LoadLibrary(msvcrPath); if (hinstVCR != nullptr) { hinstLib = LoadLibrary(jvmDLLPath); if (verbose) { cout << "Loaded library " << msvcrPath << endl; } } else { if (verbose) { cout << "Failed to load library " << FindFileData.cFileName << endl; } } } } } if (hinstLib == nullptr) { printLastError(TEXT("load jvm.dll")); return false; } *getDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs) GetProcAddress(hinstLib, "JNI_GetDefaultJavaVMInitArgs"); if (*getDefaultJavaVMInitArgs == nullptr) { printLastError(TEXT("obtain JNI_GetDefaultJavaVMInitArgs address")); return false; } *createJavaVM = (CreateJavaVM) GetProcAddress(hinstLib, "JNI_CreateJavaVM"); if (*createJavaVM == nullptr) { printLastError(TEXT("obtain JNI_CreateJavaVM address")); return false; } return true; } const dropt_char *getExecutablePath(const dropt_char *argv0) { return argv0; } bool changeWorkingDir(const dropt_char *directory) { BOOL currentDirectory = SetCurrentDirectory(directory); if(currentDirectory == 0){ printLastError(TEXT("Failed to change the working directory")); } return currentDirectory != 0; } /** * In Java 14, Windows 10 1803 is required for ZGC, see https://wiki.openjdk.java.net/display/zgc/Main#Main-SupportedPlatforms * for more information. Windows 10 1803 is build 17134. * @return true if the Windows version is 10 build 17134 or higher */ bool isZgcSupported() { // Try to get the Windows version from RtlGetVersion HMODULE ntDllHandle = ::GetModuleHandleW(L"ntdll.dll"); if (ntDllHandle) { auto rtlGetVersionFunction = (RtlGetVersionPtr) ::GetProcAddress(ntDllHandle, "RtlGetVersion"); if (rtlGetVersionFunction != nullptr) { RTL_OSVERSIONINFOW versionInformation = {0}; versionInformation.dwOSVersionInfoSize = sizeof(versionInformation); if (RETURN_SUCCESS == rtlGetVersionFunction(&versionInformation)) { if (verbose) { cout << "versionInformation.dwMajorVersion=" << versionInformation.dwMajorVersion << ", versionInformation.dwMinorVersion=" << versionInformation.dwMinorVersion << ", versionInformation.dwBuildNumber=" << versionInformation.dwBuildNumber << endl; } return (versionInformation.dwMajorVersion >= 10 && versionInformation.dwBuildNumber >= 17134) || (versionInformation.dwMajorVersion >= 10 && versionInformation.dwMinorVersion >= 1); } else { if (verbose) { cout << "RtlGetVersion didn't work" << endl; } } } } return false; } #endif<commit_msg>Added support for loading vcruntime*.dll<commit_after>/******************************************************************************* * Copyright 2015 See AUTHORS file. * * 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. ******************************************************************************/ #ifdef _WIN32 #include <Windows.h> #include <processenv.h> #include <io.h> #include <fcntl.h> #include <iostream> #include <direct.h> #include <csignal> #include <cstdio> #include <cstdlib> #include <codecvt> #include <packr.h> #define RETURN_SUCCESS (0x00000000) typedef LONG NT_STATUS; typedef NT_STATUS (WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); using namespace std; const char __CLASS_PATH_DELIM = ';'; extern "C" { __declspec(dllexport) DWORD NvOptimusEnablement = 1; __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; } static void waitAtExit() { cout << "Press ENTER key to exit." << endl << flush; cin.get(); } /** * If the '--console' argument is passed, then a new console is allocated, otherwise attaching to the parent console is attempted. * * @param argc the number of elements in {@code argv} * @param argv the list of arguments to parse for --console * @return true if the parent console was successfully attached to or a new console was allocated. false if no console could be acquired */ static bool attachToOrAllocateConsole(int argc, PTCHAR *argv) { bool allocConsole = false; // pre-parse command line here to have a console in case of command line parse errors for (int arg = 0; arg < argc && !allocConsole; arg++) { allocConsole = (argv[arg] != nullptr && wcsicmp(argv[arg], TEXT("--console")) == 0); } bool gotConsole = false; if (allocConsole) { FreeConsole(); gotConsole = AllocConsole(); } else { gotConsole = AttachConsole(ATTACH_PARENT_PROCESS); } if (gotConsole) { // Open C standard streams FILE *reusedThrowAwayHandle; freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stdout); freopen_s(&reusedThrowAwayHandle, "CONOUT$", "w", stderr); freopen_s(&reusedThrowAwayHandle, "CONIN$", "r", stdin); cout.clear(); clog.clear(); cerr.clear(); cin.clear(); // Open the C++ wide streams HANDLE hConOut = CreateFile(TEXT("CONOUT$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); HANDLE hConIn = CreateFile(TEXT("CONIN$"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); SetStdHandle(STD_OUTPUT_HANDLE, hConOut); SetStdHandle(STD_ERROR_HANDLE, hConOut); SetStdHandle(STD_INPUT_HANDLE, hConIn); wcout.clear(); wclog.clear(); wcerr.clear(); wcin.clear(); SetConsoleOutputCP(CP_UTF8); if (allocConsole) { atexit(waitAtExit); } } return gotConsole; } static void printLastError(const PTCHAR reason) { LPTSTR buffer; DWORD errorCode = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT), (LPTSTR) &buffer, 0, nullptr); wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; cerr << "Error code [" << errorCode << "] when trying to " << converter.to_bytes(reason) << ": " << converter.to_bytes(buffer) << endl; LocalFree(buffer); } static void catchFunction(int signo) { puts("Interactive attention signal caught."); cerr << "Caught signal " << signo << endl; } bool g_showCrashDialog = false; LONG WINAPI crashHandler(EXCEPTION_POINTERS * /*ExceptionInfo*/) { cerr << "Unhandled windows exception occurred" << endl; return g_showCrashDialog ? EXCEPTION_CONTINUE_SEARCH : EXCEPTION_EXECUTE_HANDLER; } static void clearEnvironment() { cout << "clearEnvironment" << endl; _putenv_s("_JAVA_OPTIONS", ""); _putenv_s("JAVA_TOOL_OPTIONS", ""); _putenv_s("CLASSPATH", ""); } static void registerSignalHandlers() { void (*code)(int); code = signal(SIGINT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGINT" << endl; } code = signal(SIGILL, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGILL" << endl; } code = signal(SIGFPE, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGFPE" << endl; } code = signal(SIGSEGV, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGSEGV" << endl; } code = signal(SIGTERM, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGTERM" << endl; } code = signal(SIGBREAK, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGBREAK" << endl; } code = signal(SIGABRT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT" << endl; } code = signal(SIGABRT_COMPAT, catchFunction); if (code == SIG_ERR) { cerr << "Failed to listen to SIGABRT_COMPAT" << endl; } SetUnhandledExceptionFilter(crashHandler); } int CALLBACK WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { registerSignalHandlers(); clearEnvironment(); try { int argc = 0; PTCHAR commandLine = GetCommandLine(); PTCHAR *argv = CommandLineToArgvW(commandLine, &argc); attachToOrAllocateConsole(argc, argv); if (!setCmdLineArguments(argc, argv)) { cerr << "Failed to set the command line arguments" << endl; return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); } catch (exception &theException) { cerr << "Caught exception:" << endl; cerr << theException.what() << endl; } catch (...) { cerr << "Caught unknown exception:" << endl; } return 0; } int wmain(int argc, wchar_t **argv) { SetConsoleOutputCP(CP_UTF8); registerSignalHandlers(); clearEnvironment(); if (!setCmdLineArguments(argc, argv)) { return EXIT_FAILURE; } launchJavaVM(defaultLaunchVMDelegate); return 0; } bool loadRuntimeLibrary(const PTCHAR runtimeLibraryPattern){ WIN32_FIND_DATA FindFileData; HANDLE hFind = nullptr; TCHAR msvcrPath[MAX_PATH]; wstring_convert<codecvt_utf8_utf16<wchar_t>> converter; bool loadedRuntimeDll = false; hFind = FindFirstFile(runtimeLibraryPattern, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { if (verbose) { cout << "Couldn't find " << converter.to_bytes(runtimeLibraryPattern) << " file." << "FindFirstFile failed " << GetLastError() << "." << endl; } } else { FindClose(hFind); if (verbose) { cout << "Found " << converter.to_bytes(runtimeLibraryPattern) << " file " << converter.to_bytes(FindFileData.cFileName) << endl; } wcscpy(msvcrPath, TEXT("jre\\bin\\")); wcscat(msvcrPath, FindFileData.cFileName); HINSTANCE hinstVCR = LoadLibrary(msvcrPath); if (hinstVCR != nullptr) { loadedRuntimeDll = true; if (verbose) { cout << "Loaded library " << converter.to_bytes(msvcrPath) << endl; } } else { if (verbose) { cout << "Failed to load library " << converter.to_bytes(FindFileData.cFileName) << endl; } } } return loadedRuntimeDll; } bool loadJNIFunctions(GetDefaultJavaVMInitArgs *getDefaultJavaVMInitArgs, CreateJavaVM *createJavaVM) { LPCTSTR jvmDLLPath = TEXT("jre\\bin\\server\\jvm.dll"); HINSTANCE hinstLib = LoadLibrary(jvmDLLPath); if (hinstLib == nullptr) { DWORD errorCode = GetLastError(); if (verbose) { cout << "Last error code " << errorCode << endl; } if (errorCode == 126) { // "The specified module could not be found." // load msvcr*.dll from the bundled JRE, then try again if (verbose) { cout << "Failed to load jvm.dll. Trying to load Microsoft runtime libraries" << endl; } bool loadedRuntimeDll = loadRuntimeLibrary(TEXT("jre\\bin\\msvcr*.dll")); loadedRuntimeDll = loadRuntimeLibrary(TEXT("jre\\bin\\vcruntime*.dll")); if(loadedRuntimeDll){ hinstLib = LoadLibrary(jvmDLLPath); } } } if (hinstLib == nullptr) { printLastError(TEXT("load jvm.dll")); return false; } *getDefaultJavaVMInitArgs = (GetDefaultJavaVMInitArgs) GetProcAddress(hinstLib, "JNI_GetDefaultJavaVMInitArgs"); if (*getDefaultJavaVMInitArgs == nullptr) { printLastError(TEXT("obtain JNI_GetDefaultJavaVMInitArgs address")); return false; } *createJavaVM = (CreateJavaVM) GetProcAddress(hinstLib, "JNI_CreateJavaVM"); if (*createJavaVM == nullptr) { printLastError(TEXT("obtain JNI_CreateJavaVM address")); return false; } return true; } const dropt_char *getExecutablePath(const dropt_char *argv0) { return argv0; } bool changeWorkingDir(const dropt_char *directory) { BOOL currentDirectory = SetCurrentDirectory(directory); if(currentDirectory == 0){ printLastError(TEXT("Failed to change the working directory")); } return currentDirectory != 0; } /** * In Java 14, Windows 10 1803 is required for ZGC, see https://wiki.openjdk.java.net/display/zgc/Main#Main-SupportedPlatforms * for more information. Windows 10 1803 is build 17134. * @return true if the Windows version is 10 build 17134 or higher */ bool isZgcSupported() { // Try to get the Windows version from RtlGetVersion HMODULE ntDllHandle = ::GetModuleHandleW(L"ntdll.dll"); if (ntDllHandle) { auto rtlGetVersionFunction = (RtlGetVersionPtr) ::GetProcAddress(ntDllHandle, "RtlGetVersion"); if (rtlGetVersionFunction != nullptr) { RTL_OSVERSIONINFOW versionInformation = {0}; versionInformation.dwOSVersionInfoSize = sizeof(versionInformation); if (RETURN_SUCCESS == rtlGetVersionFunction(&versionInformation)) { if (verbose) { cout << "versionInformation.dwMajorVersion=" << versionInformation.dwMajorVersion << ", versionInformation.dwMinorVersion=" << versionInformation.dwMinorVersion << ", versionInformation.dwBuildNumber=" << versionInformation.dwBuildNumber << endl; } return (versionInformation.dwMajorVersion >= 10 && versionInformation.dwBuildNumber >= 17134) || (versionInformation.dwMajorVersion >= 10 && versionInformation.dwMinorVersion >= 1); } else { if (verbose) { cout << "RtlGetVersion didn't work" << endl; } } } } return false; } #endif<|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "AbstractMessagingTest.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "libjoynrclustercontroller/messaging/joynr-messaging/HttpMessagingStubFactory.h" using namespace ::testing; using namespace joynr; class HttpMessagingTest : public AbstractMessagingTest { public: ADD_LOGGER(HttpMessagingTest); HttpMessagingTest() : receiverChannelId("receiverChannelId"), isLocalMessage(true) { // provision global capabilities directory auto addressCapabilitiesDirectory = std::make_shared<const joynr::system::RoutingTypes::ChannelAddress>( messagingSettings.getCapabilitiesDirectoryUrl() + messagingSettings.getCapabilitiesDirectoryChannelId() + "/", messagingSettings.getCapabilitiesDirectoryChannelId()); messageRouter->addProvisionedNextHop(messagingSettings.getCapabilitiesDirectoryParticipantId(), addressCapabilitiesDirectory); messagingStubFactory->registerStubFactory(std::make_shared<HttpMessagingStubFactory>(mockMessageSender)); } ~HttpMessagingTest(){ } protected: const std::string receiverChannelId; const bool isLocalMessage; private: DISALLOW_COPY_AND_ASSIGN(HttpMessagingTest); }; INIT_LOGGER(HttpMessagingTest); TEST_F(HttpMessagingTest, sendMsgFromMessageSenderViaInProcessMessagingAndMessageRouterToCommunicationManager) { // Test Outline: send message from JoynrMessageSender to ICommunicationManager // - MessageSender.sendRequest (IMessageSender) // -> adds reply caller to dispatcher (IDispatcher.addReplyCaller) // - InProcessMessagingStub.transmit (IMessaging) // - InProcessClusterControllerMessagingSkeleton.transmit (IMessaging) // - MessageRouter.route // - MessageRunnable.run // - HttpMessagingStub.transmit (IMessaging) // - MessageSender.send auto joynrMessagingEndpointAddr = std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(); joynrMessagingEndpointAddr->setChannelId(receiverChannelId); sendMsgFromMessageSenderViaInProcessMessagingAndMessageRouterToCommunicationManager(joynrMessagingEndpointAddr); } TEST_F(HttpMessagingTest, routeMsgWithInvalidParticipantId) { routeMsgWithInvalidParticipantId(); } TEST_F(HttpMessagingTest, routeMsgToInProcessMessagingSkeleton) { routeMsgToInProcessMessagingSkeleton(); } TEST_F(HttpMessagingTest, DISABLED_routeMsgToLipciMessagingSkeleton) { // NOTE: LipciMessaging doesn't exists (2012-05-08) // std::shared_ptr<MockLipceMessagingSkeleton> messagingSkeleton( // new MockLipciMessagingSkeleton()); JoynrMessage message = messageFactory.createRequest( senderId, receiverId, qos, request, isLocalMessage); // LipciMessagingSkeleton should receive the message // NOTE: LipciMessaging doesn't exists (2012-05-08) // EXPECT_CALL(*messagingSkeleton, transmit(Eq(message),Eq(qos))) // .Times(1); // InProcessMessagingSkeleton should not receive the message EXPECT_CALL(*inProcessMessagingSkeleton, transmit(Eq(message),_)) .Times(0); // MessageSender should not receive the message EXPECT_CALL(*mockMessageSender, sendMessage(_,_,_)) .Times(0); // NOTE: LipciMessaging doesn't exists (2012-05-08) // std::shared_ptr<LipciEndpointAddress> messagingSkeletonEndpointAddr = // std::shared_ptr<LipciEndpointAddress>(new LipciEndpointAddress(messagingSkeleton)); // messageRouter->add(receiverId, messagingSkeletonEndpointAddr); messageRouter->route(message); } TEST_F(HttpMessagingTest, routeMsgToHttpCommunicationMgr) { auto joynrMessagingEndpointAddr = std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(); joynrMessagingEndpointAddr->setChannelId(receiverChannelId); routeMsgToCommunicationManager(joynrMessagingEndpointAddr); } TEST_F(HttpMessagingTest, routeMultipleMessages) { auto joynrMessagingEndpointAddr = std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(); joynrMessagingEndpointAddr->setChannelId(receiverChannelId); routeMultipleMessages(joynrMessagingEndpointAddr); } <commit_msg>[C++] removed outdated and disabled test<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "AbstractMessagingTest.h" #include "joynr/system/RoutingTypes/ChannelAddress.h" #include "libjoynrclustercontroller/messaging/joynr-messaging/HttpMessagingStubFactory.h" using namespace ::testing; using namespace joynr; class HttpMessagingTest : public AbstractMessagingTest { public: ADD_LOGGER(HttpMessagingTest); HttpMessagingTest() : receiverChannelId("receiverChannelId"), isLocalMessage(true) { // provision global capabilities directory auto addressCapabilitiesDirectory = std::make_shared<const joynr::system::RoutingTypes::ChannelAddress>( messagingSettings.getCapabilitiesDirectoryUrl() + messagingSettings.getCapabilitiesDirectoryChannelId() + "/", messagingSettings.getCapabilitiesDirectoryChannelId()); messageRouter->addProvisionedNextHop(messagingSettings.getCapabilitiesDirectoryParticipantId(), addressCapabilitiesDirectory); messagingStubFactory->registerStubFactory(std::make_shared<HttpMessagingStubFactory>(mockMessageSender)); } ~HttpMessagingTest(){ } protected: const std::string receiverChannelId; const bool isLocalMessage; private: DISALLOW_COPY_AND_ASSIGN(HttpMessagingTest); }; INIT_LOGGER(HttpMessagingTest); TEST_F(HttpMessagingTest, sendMsgFromMessageSenderViaInProcessMessagingAndMessageRouterToCommunicationManager) { // Test Outline: send message from JoynrMessageSender to ICommunicationManager // - MessageSender.sendRequest (IMessageSender) // -> adds reply caller to dispatcher (IDispatcher.addReplyCaller) // - InProcessMessagingStub.transmit (IMessaging) // - InProcessClusterControllerMessagingSkeleton.transmit (IMessaging) // - MessageRouter.route // - MessageRunnable.run // - HttpMessagingStub.transmit (IMessaging) // - MessageSender.send auto joynrMessagingEndpointAddr = std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(); joynrMessagingEndpointAddr->setChannelId(receiverChannelId); sendMsgFromMessageSenderViaInProcessMessagingAndMessageRouterToCommunicationManager(joynrMessagingEndpointAddr); } TEST_F(HttpMessagingTest, routeMsgWithInvalidParticipantId) { routeMsgWithInvalidParticipantId(); } TEST_F(HttpMessagingTest, routeMsgToInProcessMessagingSkeleton) { routeMsgToInProcessMessagingSkeleton(); } TEST_F(HttpMessagingTest, routeMsgToHttpCommunicationMgr) { auto joynrMessagingEndpointAddr = std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(); joynrMessagingEndpointAddr->setChannelId(receiverChannelId); routeMsgToCommunicationManager(joynrMessagingEndpointAddr); } TEST_F(HttpMessagingTest, routeMultipleMessages) { auto joynrMessagingEndpointAddr = std::make_shared<joynr::system::RoutingTypes::ChannelAddress>(); joynrMessagingEndpointAddr->setChannelId(receiverChannelId); routeMultipleMessages(joynrMessagingEndpointAddr); } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2018 BMW Car IT GmbH * %% * 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. * #L% */ #include <memory> #include <string> #include "tests/utils/Gmock.h" #include "tests/utils/Gtest.h" #include "joynr/Future.h" #include "joynr/Logger.h" #include "joynr/MulticastPublication.h" #include "joynr/MulticastSubscriptionCallback.h" #include "joynr/SingleThreadedIOService.h" #include "joynr/SubscriptionReply.h" #include "joynr/UnicastSubscriptionCallback.h" #include "joynr/exceptions/SubscriptionException.h" #include "tests/JoynrTest.h" #include "tests/mock/MockMessageRouter.h" #include "tests/mock/MockSubscriptionListener.h" #include "tests/mock/MockSubscriptionManager.h" using namespace joynr; using namespace testing; template <typename SubscriptionCallbackType> class SubscriptionCallbackTest : public testing::Test { public: SubscriptionCallbackTest() : subscriptionId("testSubscriptionId"), singleThreadIOService(), mockMessageRouter( std::make_shared<MockMessageRouter>(singleThreadIOService.getIOService())), mockSubscriptionManager(std::make_shared<MockSubscriptionManager>( singleThreadIOService.getIOService(), mockMessageRouter)), subscriptionIdFuture(std::make_shared<Future<std::string>>()), mockSubscriptionListener( std::make_shared<MockSubscriptionListenerOneType<std::string>>()), subscriptionCallback(subscriptionId, subscriptionIdFuture, mockSubscriptionManager, nullptr) { ON_CALL(*mockSubscriptionManager, getSubscriptionListener(subscriptionId)) .WillByDefault(Return(mockSubscriptionListener)); ON_CALL(*mockSubscriptionManager, getMulticastSubscriptionListeners(subscriptionId)) .WillByDefault( Return(std::forward_list<std::shared_ptr<joynr::ISubscriptionListenerBase>>{ mockSubscriptionListener})); } protected: const std::string subscriptionId; SingleThreadedIOService singleThreadIOService; std::shared_ptr<MockMessageRouter> mockMessageRouter; std::shared_ptr<MockSubscriptionManager> mockSubscriptionManager; std::shared_ptr<Future<std::string>> subscriptionIdFuture; std::shared_ptr<MockSubscriptionListenerOneType<std::string>> mockSubscriptionListener; SubscriptionCallbackType subscriptionCallback; }; typedef ::testing::Types<MulticastSubscriptionCallback<std::string>, UnicastSubscriptionCallback<std::string>> SubscriptionCallbackTypes; TYPED_TEST_SUITE(SubscriptionCallbackTest, SubscriptionCallbackTypes, ); TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionReplyToFutureAndListener) { SubscriptionReply reply; reply.setSubscriptionId(this->subscriptionId); EXPECT_CALL(*(this->mockSubscriptionListener), onSubscribed(this->subscriptionId)); this->subscriptionCallback.execute(reply); std::string subscriptionIdFromFuture; this->subscriptionIdFuture->get(100, subscriptionIdFromFuture); EXPECT_EQ(subscriptionIdFromFuture, this->subscriptionId); } TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionExceptionToFutureAndListener) { SubscriptionReply reply; reply.setSubscriptionId(this->subscriptionId); auto expectedException = std::make_shared<exceptions::SubscriptionException>(this->subscriptionId); reply.setError(expectedException); EXPECT_CALL(*(this->mockSubscriptionManager), unregisterSubscription(this->subscriptionId)); EXPECT_CALL(*(this->mockSubscriptionListener), onError(*expectedException)).Times(1); EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0); this->subscriptionCallback.execute(reply); try { std::string subscriptionIdFromFuture; this->subscriptionIdFuture->get(100, subscriptionIdFromFuture); ADD_FAILURE() << "expected SubscriptionException"; } catch (const exceptions::SubscriptionException& error) { EXPECT_EQ(error, *expectedException); } } TYPED_TEST(SubscriptionCallbackTest, forwardPublicationToListener) { const std::string response = "testResponse"; EXPECT_CALL(*(this->mockSubscriptionListener), onError(_)).Times(0); EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(response)).Times(1); if (typeid(this->subscriptionCallback) == typeid(MulticastSubscriptionCallback<std::string>)) { MulticastPublication publication; publication.setMulticastId(this->subscriptionId); publication.setResponse(response); this->subscriptionCallback.execute(std::move(publication)); } else if (typeid(this->subscriptionCallback) == typeid(UnicastSubscriptionCallback<std::string>)) { BasePublication publication; publication.setResponse(response); this->subscriptionCallback.execute(std::move(publication)); } else { FAIL() << "Could not evaluate type"; } } TYPED_TEST(SubscriptionCallbackTest, forwardPublicationErrorToListener) { auto error = std::make_shared<exceptions::ProviderRuntimeException>("testException"); EXPECT_CALL(*(this->mockSubscriptionListener), onError(*error)).Times(1); EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0); if (typeid(this->subscriptionCallback) == typeid(MulticastSubscriptionCallback<std::string>)) { MulticastPublication publication; publication.setMulticastId(this->subscriptionId); publication.setError(error); this->subscriptionCallback.execute(std::move(publication)); } else if (typeid(this->subscriptionCallback) == typeid(UnicastSubscriptionCallback<std::string>)) { BasePublication publication; publication.setError(error); this->subscriptionCallback.execute(std::move(publication)); } else { FAIL() << "Could not evaluate type"; } } <commit_msg>[C++] Fix SubscriptionCallbackTest<commit_after>/* * #%L * %% * Copyright (C) 2018 BMW Car IT GmbH * %% * 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. * #L% */ #include <memory> #include <string> #include "tests/utils/Gmock.h" #include "tests/utils/Gtest.h" #include "joynr/Future.h" #include "joynr/Logger.h" #include "joynr/MulticastPublication.h" #include "joynr/MulticastSubscriptionCallback.h" #include "joynr/SingleThreadedIOService.h" #include "joynr/SubscriptionReply.h" #include "joynr/UnicastSubscriptionCallback.h" #include "joynr/exceptions/SubscriptionException.h" #include "tests/JoynrTest.h" #include "tests/mock/MockMessageRouter.h" #include "tests/mock/MockSubscriptionListener.h" #include "tests/mock/MockSubscriptionManager.h" using namespace joynr; using namespace testing; template <typename SubscriptionCallbackType> class SubscriptionCallbackTest : public testing::Test { public: SubscriptionCallbackTest() : subscriptionId("testSubscriptionId"), singleThreadIOService(), mockMessageRouter( std::make_shared<MockMessageRouter>(singleThreadIOService.getIOService())), mockSubscriptionManager(std::make_shared<MockSubscriptionManager>( singleThreadIOService.getIOService(), mockMessageRouter)), subscriptionIdFuture(std::make_shared<Future<std::string>>()), mockSubscriptionListener( std::make_shared<MockSubscriptionListenerOneType<std::string>>()), subscriptionCallback() { } void setOnCalls() { ON_CALL(*mockSubscriptionManager, getSubscriptionListener(subscriptionId)) .WillByDefault(Return(mockSubscriptionListener)); ON_CALL(*mockSubscriptionManager, getMulticastSubscriptionListeners(subscriptionId)) .WillByDefault( Return(std::forward_list<std::shared_ptr<joynr::ISubscriptionListenerBase>>{ mockSubscriptionListener})); } void createSubscriptionCallback() { subscriptionCallback = std::make_shared<SubscriptionCallbackType>( subscriptionId, subscriptionIdFuture, mockSubscriptionManager, nullptr); } protected: const std::string subscriptionId; SingleThreadedIOService singleThreadIOService; std::shared_ptr<MockMessageRouter> mockMessageRouter; std::shared_ptr<MockSubscriptionManager> mockSubscriptionManager; std::shared_ptr<Future<std::string>> subscriptionIdFuture; std::shared_ptr<MockSubscriptionListenerOneType<std::string>> mockSubscriptionListener; std::shared_ptr<SubscriptionCallbackType> subscriptionCallback; }; typedef ::testing::Types<MulticastSubscriptionCallback<std::string>, UnicastSubscriptionCallback<std::string>> SubscriptionCallbackTypes; TYPED_TEST_SUITE(SubscriptionCallbackTest, SubscriptionCallbackTypes, ); TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionReplyToFutureAndListener) { EXPECT_CALL(*(this->mockSubscriptionListener), onSubscribed(this->subscriptionId)); this->setOnCalls(); SubscriptionReply reply; reply.setSubscriptionId(this->subscriptionId); this->createSubscriptionCallback(); this->subscriptionCallback->execute(reply); std::string subscriptionIdFromFuture; this->subscriptionIdFuture->get(100, subscriptionIdFromFuture); EXPECT_EQ(subscriptionIdFromFuture, this->subscriptionId); } TYPED_TEST(SubscriptionCallbackTest, forwardSubscriptionExceptionToFutureAndListener) { SubscriptionReply reply; reply.setSubscriptionId(this->subscriptionId); auto expectedException = std::make_shared<exceptions::SubscriptionException>(this->subscriptionId); reply.setError(expectedException); EXPECT_CALL(*(this->mockSubscriptionManager), unregisterSubscription(this->subscriptionId)); EXPECT_CALL(*(this->mockSubscriptionListener), onError(*expectedException)).Times(1); EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0); this->setOnCalls(); this->createSubscriptionCallback(); this->subscriptionCallback->execute(reply); try { std::string subscriptionIdFromFuture; this->subscriptionIdFuture->get(100, subscriptionIdFromFuture); ADD_FAILURE() << "expected SubscriptionException"; } catch (const exceptions::SubscriptionException& error) { EXPECT_EQ(error, *expectedException); } } TYPED_TEST(SubscriptionCallbackTest, forwardPublicationToListener) { const std::string response = "testResponse"; EXPECT_CALL(*(this->mockSubscriptionListener), onError(_)).Times(0); EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(response)).Times(1); this->setOnCalls(); this->createSubscriptionCallback(); if (typeid(*this->subscriptionCallback.get()) == typeid(MulticastSubscriptionCallback<std::string>)) { MulticastPublication publication; publication.setMulticastId(this->subscriptionId); publication.setResponse(response); this->subscriptionCallback->execute(std::move(publication)); } else if (typeid(*this->subscriptionCallback.get()) == typeid(UnicastSubscriptionCallback<std::string>)) { BasePublication publication; publication.setResponse(response); this->subscriptionCallback->execute(std::move(publication)); } else { FAIL() << "Could not evaluate type"; } } TYPED_TEST(SubscriptionCallbackTest, forwardPublicationErrorToListener) { auto error = std::make_shared<exceptions::ProviderRuntimeException>("testException"); EXPECT_CALL(*(this->mockSubscriptionListener), onError(*error)).Times(1); EXPECT_CALL(*(this->mockSubscriptionListener), onReceive(_)).Times(0); this->setOnCalls(); this->createSubscriptionCallback(); if (typeid(*this->subscriptionCallback.get()) == typeid(MulticastSubscriptionCallback<std::string>)) { MulticastPublication publication; publication.setMulticastId(this->subscriptionId); publication.setError(error); this->subscriptionCallback->execute(std::move(publication)); } else if (typeid(*this->subscriptionCallback.get()) == typeid(UnicastSubscriptionCallback<std::string>)) { BasePublication publication; publication.setError(error); this->subscriptionCallback->execute(std::move(publication)); } else { FAIL() << "Could not evaluate type"; } } <|endoftext|>
<commit_before>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <atomic> #include <chrono> #include <thread> #include "iree/task/task.h" #include "iree/task/testing/task_test.h" #include "iree/testing/gtest.h" #include "iree/testing/status_matchers.h" namespace { using iree::Status; using iree::StatusCode; using iree::testing::status::StatusIs; // NOTE: we intentionally perform most signaling to/from C++ std::threads. // This models a real application that may be passing in handles tied to custom // or system primitives unrelated to the task system. class TaskWaitTest : public TaskTest {}; // Issues a wait task on a handle that has already been signaled. // The poller will query the status of the handle and immediately retire the // task. TEST_F(TaskWaitTest, IssueSignaled) { IREE_TRACE_SCOPE(); iree_event_t event; iree_event_initialize(/*initial_state=*/true, &event); iree_task_wait_t task; iree_task_wait_initialize(&scope_, iree_event_await(&event), IREE_TIME_INFINITE_FUTURE, &task); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); iree_event_deinitialize(&event); } // Issues a wait task on an unsignaled handle such that the poller must wait. // We'll spin up a thread that sets it a short time in the future and ensure // that the poller woke and retired the task. TEST_F(TaskWaitTest, IssueUnsignaled) { IREE_TRACE_SCOPE(); iree_event_t event; iree_event_initialize(/*initial_state=*/false, &event); iree_task_wait_t task; iree_task_wait_initialize(&scope_, iree_event_await(&event), IREE_TIME_INFINITE_FUTURE, &task); // Spin up a thread that will signal the event after we start waiting on it. std::atomic<bool> has_signaled = {false}; std::thread signal_thread([&]() { IREE_TRACE_SCOPE(); std::this_thread::sleep_for(std::chrono::milliseconds(150)); EXPECT_FALSE(has_signaled); has_signaled = true; iree_event_set(&event); }); EXPECT_FALSE(has_signaled); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); EXPECT_TRUE(has_signaled); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); signal_thread.join(); iree_event_deinitialize(&event); } // Issues a wait task on a handle that will never be signaled. // We set the deadline in the near future and ensure that the poller correctly // fails the wait with a DEADLINE_EXCEEDED. TEST_F(TaskWaitTest, IssueTimeout) { IREE_TRACE_SCOPE(); iree_event_t event; iree_event_initialize(/*initial_state=*/false, &event); iree_task_wait_t task; iree_task_wait_initialize(&scope_, iree_event_await(&event), iree_time_now() + (150 * 1000000), &task); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); EXPECT_THAT(Status(iree_task_scope_consume_status(&scope_)), StatusIs(StatusCode::kDeadlineExceeded)); iree_event_deinitialize(&event); } // Issues a delay task that should wait until the requested time. // NOTE: this kind of test can be flaky - if we have issues we can bump the // sleep time up. TEST_F(TaskWaitTest, IssueDelay) { IREE_TRACE_SCOPE(); iree_time_t start_time_ns = iree_time_now(); iree_task_wait_t task; iree_task_wait_initialize_delay(&scope_, start_time_ns + (50 * 1000000), &task); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); iree_time_t end_time_ns = iree_time_now(); EXPECT_GE(end_time_ns - start_time_ns, 25 * 1000000); } // Issues multiple waits that join on a single task. This models a wait-all. TEST_F(TaskWaitTest, WaitAll) { IREE_TRACE_SCOPE(); iree_event_t event_a; iree_event_initialize(/*initial_state=*/false, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), IREE_TIME_INFINITE_FUTURE, &task_a); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), IREE_TIME_INFINITE_FUTURE, &task_b); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); // Spin up a thread that will signal the event after we start waiting on it. std::atomic<bool> has_signaled = {false}; std::thread signal_thread([&]() { IREE_TRACE_SCOPE(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); EXPECT_FALSE(has_signaled); iree_event_set(&event_a); std::this_thread::sleep_for(std::chrono::milliseconds(50)); iree_event_set(&event_b); has_signaled = true; }); EXPECT_FALSE(has_signaled); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_TRUE(has_signaled); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); signal_thread.join(); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } // Issues multiple waits that join on a single task but where one times out. TEST_F(TaskWaitTest, WaitAllTimeout) { IREE_TRACE_SCOPE(); iree_event_t event_a; iree_event_initialize(/*initial_state=*/true, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), IREE_TIME_INFINITE_FUTURE, &task_a); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), iree_time_now() + (50 * 1000000), &task_b); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_THAT(Status(iree_task_scope_consume_status(&scope_)), StatusIs(StatusCode::kDeadlineExceeded)); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } // Issues multiple waits that join on a single task in wait-any mode. // This means that if one wait finishes all other waits will be cancelled and // the completion task will continue. // // Here event_a is signaled but event_b is not. TEST_F(TaskWaitTest, WaitAny) { IREE_TRACE_SCOPE(); // Flag shared between all waits in a group. iree_atomic_int32_t cancellation_flag = IREE_ATOMIC_VAR_INIT(0); iree_event_t event_a; iree_event_initialize(/*initial_state=*/false, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), IREE_TIME_INFINITE_FUTURE, &task_a); iree_task_wait_set_wait_any(&task_a, &cancellation_flag); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), IREE_TIME_INFINITE_FUTURE, &task_b); iree_task_wait_set_wait_any(&task_b, &cancellation_flag); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); // Spin up a thread that will signal the event after we start waiting on it. std::atomic<bool> has_signaled = {false}; std::thread signal_thread([&]() { IREE_TRACE_SCOPE(); // NOTE: we only signal event_a - event_b remains unsignaled. std::this_thread::sleep_for(std::chrono::milliseconds(50)); EXPECT_FALSE(has_signaled); iree_event_set(&event_a); has_signaled = true; }); EXPECT_FALSE(has_signaled); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_TRUE(has_signaled); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); signal_thread.join(); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } // Issues multiple waits that join on a single task in wait-any mode. // Here instead of signaling anything we cause event_a to timeout so that the // entire wait is cancelled. TEST_F(TaskWaitTest, WaitAnyTimeout) { IREE_TRACE_SCOPE(); // Flag shared between all waits in a group. iree_atomic_int32_t cancellation_flag = IREE_ATOMIC_VAR_INIT(0); iree_event_t event_a; iree_event_initialize(/*initial_state=*/false, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), iree_time_now() + (50 * 1000000), &task_a); iree_task_wait_set_wait_any(&task_a, &cancellation_flag); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), IREE_TIME_INFINITE_FUTURE, &task_b); iree_task_wait_set_wait_any(&task_b, &cancellation_flag); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_THAT(Status(iree_task_scope_consume_status(&scope_)), StatusIs(StatusCode::kDeadlineExceeded)); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } } // namespace <commit_msg>Fixing task tests to signal after setting the test flag. (#8416)<commit_after>// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include <atomic> #include <chrono> #include <thread> #include "iree/task/task.h" #include "iree/task/testing/task_test.h" #include "iree/testing/gtest.h" #include "iree/testing/status_matchers.h" namespace { using iree::Status; using iree::StatusCode; using iree::testing::status::StatusIs; // NOTE: we intentionally perform most signaling to/from C++ std::threads. // This models a real application that may be passing in handles tied to custom // or system primitives unrelated to the task system. class TaskWaitTest : public TaskTest {}; // Issues a wait task on a handle that has already been signaled. // The poller will query the status of the handle and immediately retire the // task. TEST_F(TaskWaitTest, IssueSignaled) { IREE_TRACE_SCOPE(); iree_event_t event; iree_event_initialize(/*initial_state=*/true, &event); iree_task_wait_t task; iree_task_wait_initialize(&scope_, iree_event_await(&event), IREE_TIME_INFINITE_FUTURE, &task); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); iree_event_deinitialize(&event); } // Issues a wait task on an unsignaled handle such that the poller must wait. // We'll spin up a thread that sets it a short time in the future and ensure // that the poller woke and retired the task. TEST_F(TaskWaitTest, IssueUnsignaled) { IREE_TRACE_SCOPE(); iree_event_t event; iree_event_initialize(/*initial_state=*/false, &event); iree_task_wait_t task; iree_task_wait_initialize(&scope_, iree_event_await(&event), IREE_TIME_INFINITE_FUTURE, &task); // Spin up a thread that will signal the event after we start waiting on it. std::atomic<bool> has_signaled = {false}; std::thread signal_thread([&]() { IREE_TRACE_SCOPE(); std::this_thread::sleep_for(std::chrono::milliseconds(150)); EXPECT_FALSE(has_signaled); has_signaled = true; iree_event_set(&event); }); EXPECT_FALSE(has_signaled); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); EXPECT_TRUE(has_signaled); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); signal_thread.join(); iree_event_deinitialize(&event); } // Issues a wait task on a handle that will never be signaled. // We set the deadline in the near future and ensure that the poller correctly // fails the wait with a DEADLINE_EXCEEDED. TEST_F(TaskWaitTest, IssueTimeout) { IREE_TRACE_SCOPE(); iree_event_t event; iree_event_initialize(/*initial_state=*/false, &event); iree_task_wait_t task; iree_task_wait_initialize(&scope_, iree_event_await(&event), iree_time_now() + (150 * 1000000), &task); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); EXPECT_THAT(Status(iree_task_scope_consume_status(&scope_)), StatusIs(StatusCode::kDeadlineExceeded)); iree_event_deinitialize(&event); } // Issues a delay task that should wait until the requested time. // NOTE: this kind of test can be flaky - if we have issues we can bump the // sleep time up. TEST_F(TaskWaitTest, IssueDelay) { IREE_TRACE_SCOPE(); iree_time_t start_time_ns = iree_time_now(); iree_task_wait_t task; iree_task_wait_initialize_delay(&scope_, start_time_ns + (50 * 1000000), &task); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&task.header, &task.header)); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); iree_time_t end_time_ns = iree_time_now(); EXPECT_GE(end_time_ns - start_time_ns, 25 * 1000000); } // Issues multiple waits that join on a single task. This models a wait-all. TEST_F(TaskWaitTest, WaitAll) { IREE_TRACE_SCOPE(); iree_event_t event_a; iree_event_initialize(/*initial_state=*/false, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), IREE_TIME_INFINITE_FUTURE, &task_a); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), IREE_TIME_INFINITE_FUTURE, &task_b); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); // Spin up a thread that will signal the event after we start waiting on it. std::atomic<bool> has_signaled = {false}; std::thread signal_thread([&]() { IREE_TRACE_SCOPE(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); EXPECT_FALSE(has_signaled); iree_event_set(&event_a); std::this_thread::sleep_for(std::chrono::milliseconds(50)); has_signaled = true; iree_event_set(&event_b); }); EXPECT_FALSE(has_signaled); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_TRUE(has_signaled); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); signal_thread.join(); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } // Issues multiple waits that join on a single task but where one times out. TEST_F(TaskWaitTest, WaitAllTimeout) { IREE_TRACE_SCOPE(); iree_event_t event_a; iree_event_initialize(/*initial_state=*/true, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), IREE_TIME_INFINITE_FUTURE, &task_a); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), iree_time_now() + (50 * 1000000), &task_b); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_THAT(Status(iree_task_scope_consume_status(&scope_)), StatusIs(StatusCode::kDeadlineExceeded)); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } // Issues multiple waits that join on a single task in wait-any mode. // This means that if one wait finishes all other waits will be cancelled and // the completion task will continue. // // Here event_a is signaled but event_b is not. TEST_F(TaskWaitTest, WaitAny) { IREE_TRACE_SCOPE(); // Flag shared between all waits in a group. iree_atomic_int32_t cancellation_flag = IREE_ATOMIC_VAR_INIT(0); iree_event_t event_a; iree_event_initialize(/*initial_state=*/false, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), IREE_TIME_INFINITE_FUTURE, &task_a); iree_task_wait_set_wait_any(&task_a, &cancellation_flag); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), IREE_TIME_INFINITE_FUTURE, &task_b); iree_task_wait_set_wait_any(&task_b, &cancellation_flag); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); // Spin up a thread that will signal the event after we start waiting on it. std::atomic<bool> has_signaled = {false}; std::thread signal_thread([&]() { IREE_TRACE_SCOPE(); // NOTE: we only signal event_a - event_b remains unsignaled. std::this_thread::sleep_for(std::chrono::milliseconds(50)); EXPECT_FALSE(has_signaled); has_signaled = true; iree_event_set(&event_a); }); EXPECT_FALSE(has_signaled); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_TRUE(has_signaled); IREE_EXPECT_OK(iree_task_scope_consume_status(&scope_)); signal_thread.join(); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } // Issues multiple waits that join on a single task in wait-any mode. // Here instead of signaling anything we cause event_a to timeout so that the // entire wait is cancelled. TEST_F(TaskWaitTest, WaitAnyTimeout) { IREE_TRACE_SCOPE(); // Flag shared between all waits in a group. iree_atomic_int32_t cancellation_flag = IREE_ATOMIC_VAR_INIT(0); iree_event_t event_a; iree_event_initialize(/*initial_state=*/false, &event_a); iree_task_wait_t task_a; iree_task_wait_initialize(&scope_, iree_event_await(&event_a), iree_time_now() + (50 * 1000000), &task_a); iree_task_wait_set_wait_any(&task_a, &cancellation_flag); iree_event_t event_b; iree_event_initialize(/*initial_state=*/false, &event_b); iree_task_wait_t task_b; iree_task_wait_initialize(&scope_, iree_event_await(&event_b), IREE_TIME_INFINITE_FUTURE, &task_b); iree_task_wait_set_wait_any(&task_b, &cancellation_flag); iree_task_t* wait_tasks[] = {&task_a.header, &task_b.header}; iree_task_barrier_t barrier; iree_task_barrier_initialize(&scope_, IREE_ARRAYSIZE(wait_tasks), wait_tasks, &barrier); iree_task_fence_t fence; iree_task_fence_initialize(&scope_, iree_wait_primitive_immediate(), &fence); iree_task_set_completion_task(&task_a.header, &fence.header); iree_task_set_completion_task(&task_b.header, &fence.header); IREE_ASSERT_OK(SubmitTasksAndWaitIdle(&barrier.header, &fence.header)); EXPECT_THAT(Status(iree_task_scope_consume_status(&scope_)), StatusIs(StatusCode::kDeadlineExceeded)); iree_event_deinitialize(&event_a); iree_event_deinitialize(&event_b); } } // namespace <|endoftext|>
<commit_before>//===-- sanitizer_flags_test.cc -------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer/AddressSanitizer runtime. // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_flags.h" #include "sanitizer_common/sanitizer_flag_parser.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_allocator_internal.h" #include "gtest/gtest.h" #include <string.h> namespace __sanitizer { static const char kFlagName[] = "flag_name"; static const char kFlagDesc[] = "flag description"; template <typename T> static void TestFlag(T start_value, const char *env, T final_value) { T flag = start_value; FlagParser parser; RegisterFlag(&parser, kFlagName, kFlagDesc, &flag); parser.ParseString(env); EXPECT_EQ(final_value, flag); } template <> void TestFlag(const char *start_value, const char *env, const char *final_value) { const char *flag = start_value; FlagParser parser; RegisterFlag(&parser, kFlagName, kFlagDesc, &flag); parser.ParseString(env); EXPECT_EQ(0, internal_strcmp(final_value, flag)); // Reporting unrecognized flags is needed to reset them. ReportUnrecognizedFlags(); } TEST(SanitizerCommon, BooleanFlags) { TestFlag(false, "flag_name=1", true); TestFlag(false, "flag_name=yes", true); TestFlag(false, "flag_name=true", true); TestFlag(true, "flag_name=0", false); TestFlag(true, "flag_name=no", false); TestFlag(true, "flag_name=false", false); } TEST(SanitizerCommon, IntFlags) { TestFlag(-11, 0, -11); TestFlag(-11, "flag_name=0", 0); TestFlag(-11, "flag_name=42", 42); TestFlag(-11, "flag_name=-42", -42); // Unrecognized flags are ignored. TestFlag(-11, "--flag_name=42", -11); TestFlag(-11, "zzzzzzz=42", -11); EXPECT_DEATH(TestFlag(-11, "flag_name", 0), "expected '='"); EXPECT_DEATH(TestFlag(-11, "flag_name=42U", 0), "Invalid value for int option"); } TEST(SanitizerCommon, StrFlags) { TestFlag("zzz", 0, "zzz"); TestFlag("zzz", "flag_name=", ""); TestFlag("zzz", "flag_name=abc", "abc"); TestFlag("", "flag_name=abc", "abc"); TestFlag("", "flag_name='abc zxc'", "abc zxc"); // TestStrFlag("", "flag_name=\"abc qwe\" asd", "abc qwe"); } static void TestTwoFlags(const char *env, bool expected_flag1, const char *expected_flag2, const char *name1 = "flag1", const char *name2 = "flag2") { bool flag1 = !expected_flag1; const char *flag2 = ""; FlagParser parser; RegisterFlag(&parser, name1, kFlagDesc, &flag1); RegisterFlag(&parser, name2, kFlagDesc, &flag2); parser.ParseString(env); EXPECT_EQ(expected_flag1, flag1); EXPECT_EQ(0, internal_strcmp(flag2, expected_flag2)); // Reporting unrecognized flags is needed to reset them. ReportUnrecognizedFlags(); } TEST(SanitizerCommon, MultipleFlags) { TestTwoFlags("flag1=1 flag2='zzz'", true, "zzz"); TestTwoFlags("flag2='qxx' flag1=0", false, "qxx"); TestTwoFlags("flag1=false:flag2='zzz'", false, "zzz"); TestTwoFlags("flag2=qxx:flag1=yes", true, "qxx"); TestTwoFlags("flag2=qxx\nflag1=yes", true, "qxx"); TestTwoFlags("flag2=qxx\r\nflag1=yes", true, "qxx"); TestTwoFlags("flag2=qxx\tflag1=yes", true, "qxx"); } TEST(SanitizerCommon, CommonSuffixFlags) { TestTwoFlags("flag=1 other_flag='zzz'", true, "zzz", "flag", "other_flag"); TestTwoFlags("other_flag='zzz' flag=1", true, "zzz", "flag", "other_flag"); TestTwoFlags("other_flag=' flag=0 ' flag=1", true, " flag=0 ", "flag", "other_flag"); TestTwoFlags("flag=1 other_flag=' flag=0 '", true, " flag=0 ", "flag", "other_flag"); } TEST(SanitizerCommon, CommonFlags) { CommonFlags cf; FlagParser parser; RegisterCommonFlags(&parser, &cf); cf.SetDefaults(); EXPECT_TRUE(cf.symbolize); EXPECT_STREQ(".", cf.coverage_dir); cf.symbolize = false; cf.coverage = true; cf.coverage_direct = true; cf.log_path = "path/one"; parser.ParseString("symbolize=1:coverage_direct=false log_path='path/two'"); EXPECT_TRUE(cf.symbolize); EXPECT_TRUE(cf.coverage); EXPECT_FALSE(cf.coverage_direct); EXPECT_STREQ("path/two", cf.log_path); } } // namespace __sanitizer <commit_msg>[compiler-rt] Add negative test for boolean flags.<commit_after>//===-- sanitizer_flags_test.cc -------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer/AddressSanitizer runtime. // //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_flags.h" #include "sanitizer_common/sanitizer_flag_parser.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_allocator_internal.h" #include "gtest/gtest.h" #include <string.h> namespace __sanitizer { static const char kFlagName[] = "flag_name"; static const char kFlagDesc[] = "flag description"; template <typename T> static void TestFlag(T start_value, const char *env, T final_value) { T flag = start_value; FlagParser parser; RegisterFlag(&parser, kFlagName, kFlagDesc, &flag); parser.ParseString(env); EXPECT_EQ(final_value, flag); } template <> void TestFlag(const char *start_value, const char *env, const char *final_value) { const char *flag = start_value; FlagParser parser; RegisterFlag(&parser, kFlagName, kFlagDesc, &flag); parser.ParseString(env); EXPECT_EQ(0, internal_strcmp(final_value, flag)); // Reporting unrecognized flags is needed to reset them. ReportUnrecognizedFlags(); } TEST(SanitizerCommon, BooleanFlags) { TestFlag(false, "flag_name=1", true); TestFlag(false, "flag_name=yes", true); TestFlag(false, "flag_name=true", true); TestFlag(true, "flag_name=0", false); TestFlag(true, "flag_name=no", false); TestFlag(true, "flag_name=false", false); EXPECT_DEATH(TestFlag(false, "flag_name", true), "expected '='"); EXPECT_DEATH(TestFlag(false, "flag_name=", true), "Invalid value for bool option: ''"); EXPECT_DEATH(TestFlag(false, "flag_name=2", true), "Invalid value for bool option: '2'"); EXPECT_DEATH(TestFlag(false, "flag_name=-1", true), "Invalid value for bool option: '-1'"); } TEST(SanitizerCommon, IntFlags) { TestFlag(-11, 0, -11); TestFlag(-11, "flag_name=0", 0); TestFlag(-11, "flag_name=42", 42); TestFlag(-11, "flag_name=-42", -42); // Unrecognized flags are ignored. TestFlag(-11, "--flag_name=42", -11); TestFlag(-11, "zzzzzzz=42", -11); EXPECT_DEATH(TestFlag(-11, "flag_name", 0), "expected '='"); EXPECT_DEATH(TestFlag(-11, "flag_name=42U", 0), "Invalid value for int option"); } TEST(SanitizerCommon, StrFlags) { TestFlag("zzz", 0, "zzz"); TestFlag("zzz", "flag_name=", ""); TestFlag("zzz", "flag_name=abc", "abc"); TestFlag("", "flag_name=abc", "abc"); TestFlag("", "flag_name='abc zxc'", "abc zxc"); // TestStrFlag("", "flag_name=\"abc qwe\" asd", "abc qwe"); } static void TestTwoFlags(const char *env, bool expected_flag1, const char *expected_flag2, const char *name1 = "flag1", const char *name2 = "flag2") { bool flag1 = !expected_flag1; const char *flag2 = ""; FlagParser parser; RegisterFlag(&parser, name1, kFlagDesc, &flag1); RegisterFlag(&parser, name2, kFlagDesc, &flag2); parser.ParseString(env); EXPECT_EQ(expected_flag1, flag1); EXPECT_EQ(0, internal_strcmp(flag2, expected_flag2)); // Reporting unrecognized flags is needed to reset them. ReportUnrecognizedFlags(); } TEST(SanitizerCommon, MultipleFlags) { TestTwoFlags("flag1=1 flag2='zzz'", true, "zzz"); TestTwoFlags("flag2='qxx' flag1=0", false, "qxx"); TestTwoFlags("flag1=false:flag2='zzz'", false, "zzz"); TestTwoFlags("flag2=qxx:flag1=yes", true, "qxx"); TestTwoFlags("flag2=qxx\nflag1=yes", true, "qxx"); TestTwoFlags("flag2=qxx\r\nflag1=yes", true, "qxx"); TestTwoFlags("flag2=qxx\tflag1=yes", true, "qxx"); } TEST(SanitizerCommon, CommonSuffixFlags) { TestTwoFlags("flag=1 other_flag='zzz'", true, "zzz", "flag", "other_flag"); TestTwoFlags("other_flag='zzz' flag=1", true, "zzz", "flag", "other_flag"); TestTwoFlags("other_flag=' flag=0 ' flag=1", true, " flag=0 ", "flag", "other_flag"); TestTwoFlags("flag=1 other_flag=' flag=0 '", true, " flag=0 ", "flag", "other_flag"); } TEST(SanitizerCommon, CommonFlags) { CommonFlags cf; FlagParser parser; RegisterCommonFlags(&parser, &cf); cf.SetDefaults(); EXPECT_TRUE(cf.symbolize); EXPECT_STREQ(".", cf.coverage_dir); cf.symbolize = false; cf.coverage = true; cf.coverage_direct = true; cf.log_path = "path/one"; parser.ParseString("symbolize=1:coverage_direct=false log_path='path/two'"); EXPECT_TRUE(cf.symbolize); EXPECT_TRUE(cf.coverage); EXPECT_FALSE(cf.coverage_direct); EXPECT_STREQ("path/two", cf.log_path); } } // namespace __sanitizer <|endoftext|>
<commit_before>/* * Arduino JSON library * Benoit Blanchon 2014 - MIT License */ #include "CppUnitTest.h" #include "JsonParser.h" #include <string> using namespace std; using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace ArduinoJson::Parser; namespace ArduinoJsonParserTests { TEST_CLASS(JsonHashTableTests) { JsonParser<32> parser; JsonHashTable hashTable; JsonArray nestedArray; char json[256]; public: TEST_METHOD(EmptyString) { whenInputIs(""); parseMustFail(); } TEST_METHOD(EmptyHashTable) { whenInputIs("{}"); parseMustSucceed(); } TEST_METHOD(TwoIntegers) { whenInputIs("{\"key1\":1,\"key2\":2}"); parseMustSucceed(); itemMustBe("key1", 1L); itemMustBe("key2", 2L); itemMustNotExists("key3"); } TEST_METHOD(TwoBooleans) { whenInputIs("{\"key1\":true,\"key2\":false}"); parseMustSucceed(); itemMustBe("key1", true); itemMustBe("key2", false); itemMustNotExists("key3"); } TEST_METHOD(TwoStrings) { whenInputIs("{\"key1\":\"hello\",\"key2\":\"world\"}"); parseMustSucceed(); itemMustBe("key1", "hello"); itemMustBe("key2", "world"); itemMustNotExists("key3"); } TEST_METHOD(TwoNestedArrays) { whenInputIs("{\"key1\":[1,2],\"key2\":[3,4]}"); parseMustSucceed(); itemMustBeAnArray("key1"); arrayLengthMustBe(2); arrayItemMustBe(0, 1L); arrayItemMustBe(1, 2L); arrayItemMustBe(2, 0L); itemMustBeAnArray("key2"); arrayLengthMustBe(2); arrayItemMustBe(0, 3L); arrayItemMustBe(1, 4L); arrayItemMustBe(2, 0L); itemMustNotExists("key3"); } private: void whenInputIs(const char* input) { strcpy(json, input); hashTable = parser.parseHashTable(json); } void parseMustFail() { Assert::IsFalse(hashTable.success()); } void parseMustSucceed() { Assert::IsTrue(hashTable.success()); } void itemMustBe(const char* key, long expected) { Assert::AreEqual(expected, hashTable.getLong(key)); } void itemMustBe(const char* key, bool expected) { Assert::AreEqual(expected, hashTable.getBool(key)); } void itemMustBe(const char* key, const char* expected) { Assert::AreEqual(expected, hashTable.getString(key)); } void itemMustNotExists(const char* key) { Assert::IsFalse(hashTable.containsKey(key)); Assert::IsFalse(hashTable.getHashTable(key).success()); Assert::IsFalse(hashTable.getArray(key).success()); Assert::IsFalse(hashTable.getBool(key)); Assert::AreEqual(0.0, hashTable.getDouble(key)); Assert::AreEqual(0L, hashTable.getLong(key)); Assert::IsNull(hashTable.getString(key)); } void itemMustBeAnArray(const char* key) { nestedArray = hashTable.getArray(key); Assert::IsTrue(nestedArray.success()); } void arrayLengthMustBe(int expected) { Assert::AreEqual(expected, nestedArray.getLength()); } void arrayItemMustBe(int index, long expected) { Assert::AreEqual(expected, nestedArray.getLong(index)); } }; }<commit_msg>Added a test when token count is too small<commit_after>/* * Arduino JSON library * Benoit Blanchon 2014 - MIT License */ #include "CppUnitTest.h" #include "JsonParser.h" #include <string> using namespace std; using namespace Microsoft::VisualStudio::CppUnitTestFramework; using namespace ArduinoJson::Parser; namespace ArduinoJsonParserTests { TEST_CLASS(JsonHashTableTests) { JsonHashTable hashTable; JsonArray nestedArray; char json[256]; jsmntok_t tokens[32]; JsonParserBase parser = JsonParserBase(tokens, 32); public: TEST_METHOD(EmptyString) { whenInputIs(""); parseMustFail(); } TEST_METHOD(EmptyHashTable) { whenInputIs("{}"); parseMustSucceed(); } TEST_METHOD(NotEnoughTokens) { setTokenCountTo(2); whenInputIs("{\"key\":0}"); parseMustFail(); itemMustNotExists("key"); } TEST_METHOD(TwoIntegers) { setTokenCountTo(5); whenInputIs("{\"key1\":1,\"key2\":2}"); parseMustSucceed(); itemMustBe("key1", 1L); itemMustBe("key2", 2L); itemMustNotExists("key3"); } TEST_METHOD(TwoBooleans) { setTokenCountTo(5); whenInputIs("{\"key1\":true,\"key2\":false}"); parseMustSucceed(); itemMustBe("key1", true); itemMustBe("key2", false); itemMustNotExists("key3"); } TEST_METHOD(TwoStrings) { setTokenCountTo(5); whenInputIs("{\"key1\":\"hello\",\"key2\":\"world\"}"); parseMustSucceed(); itemMustBe("key1", "hello"); itemMustBe("key2", "world"); itemMustNotExists("key3"); } TEST_METHOD(TwoNestedArrays) { setTokenCountTo(9); whenInputIs("{\"key1\":[1,2],\"key2\":[3,4]}"); parseMustSucceed(); itemMustBeAnArray("key1"); arrayLengthMustBe(2); arrayItemMustBe(0, 1L); arrayItemMustBe(1, 2L); arrayItemMustBe(2, 0L); itemMustBeAnArray("key2"); arrayLengthMustBe(2); arrayItemMustBe(0, 3L); arrayItemMustBe(1, 4L); arrayItemMustBe(2, 0L); itemMustNotExists("key3"); } private: void setTokenCountTo(int n) { parser = JsonParserBase(tokens, n); } void whenInputIs(const char* input) { strcpy(json, input); hashTable = parser.parseHashTable(json); } void parseMustFail() { Assert::IsFalse(hashTable.success()); } void parseMustSucceed() { Assert::IsTrue(hashTable.success()); } void itemMustBe(const char* key, long expected) { Assert::AreEqual(expected, hashTable.getLong(key)); } void itemMustBe(const char* key, bool expected) { Assert::AreEqual(expected, hashTable.getBool(key)); } void itemMustBe(const char* key, const char* expected) { Assert::AreEqual(expected, hashTable.getString(key)); } void itemMustNotExists(const char* key) { Assert::IsFalse(hashTable.containsKey(key)); Assert::IsFalse(hashTable.getHashTable(key).success()); Assert::IsFalse(hashTable.getArray(key).success()); Assert::IsFalse(hashTable.getBool(key)); Assert::AreEqual(0.0, hashTable.getDouble(key)); Assert::AreEqual(0L, hashTable.getLong(key)); Assert::IsNull(hashTable.getString(key)); } void itemMustBeAnArray(const char* key) { nestedArray = hashTable.getArray(key); Assert::IsTrue(nestedArray.success()); } void arrayLengthMustBe(int expected) { Assert::AreEqual(expected, nestedArray.getLength()); } void arrayItemMustBe(int index, long expected) { Assert::AreEqual(expected, nestedArray.getLong(index)); } }; }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: adminpages.cxx,v $ * * $Revision: 1.49 $ * * last change: $Author: hr $ $Date: 2007-11-01 15:08:22 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBAUI_ADMINPAGES_HXX_ #include "adminpages.hxx" #endif #ifndef _DBAUI_DBADMIN_HRC_ #include "dbadmin.hrc" #endif #ifndef _DBU_DLG_HRC_ #include "dbu_dlg.hrc" #endif #ifndef _SFXSTRITEM_HXX #include <svtools/stritem.hxx> #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _DBAUI_DATASOURCEITEMS_HXX_ #include "dsitems.hxx" #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _DBAUI_DBADMIN_HXX_ #include "dbadmin.hxx" #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DBAUI_SQLMESSAGE_HXX_ #include "sqlmessage.hxx" #endif #ifndef _SV_ACCEL_HXX #include <vcl/accel.hxx> #endif #include <algorithm> #include <stdlib.h> #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _DBAUI_DSSELECT_HXX_ #include "dsselect.hxx" #endif #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _DBAUI_LOCALRESACCESS_HXX_ #include "localresaccess.hxx" #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::dbtools; using namespace ::svt; //========================================================================= //= OGenericAdministrationPage //========================================================================= DBG_NAME(OGenericAdministrationPage) //------------------------------------------------------------------------- OGenericAdministrationPage::OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet) :SfxTabPage(_pParent, _rId, _rAttrSet) ,m_abEnableRoadmap(sal_False) ,m_pAdminDialog(NULL) ,m_pItemSetHelper(NULL) ,m_pFT_HeaderText(NULL) { DBG_CTOR(OGenericAdministrationPage,NULL); SetExchangeSupport(sal_True); } //------------------------------------------------------------------------- OGenericAdministrationPage::~OGenericAdministrationPage() { DELETEZ(m_pFT_HeaderText); DBG_DTOR(OGenericAdministrationPage,NULL); } //------------------------------------------------------------------------- int OGenericAdministrationPage::DeactivatePage(SfxItemSet* _pSet) { if (_pSet) { if (!prepareLeave()) return KEEP_PAGE; FillItemSet(*_pSet); } return LEAVE_PAGE; } //------------------------------------------------------------------------- void OGenericAdministrationPage::Reset(const SfxItemSet& _rCoreAttrs) { implInitControls(_rCoreAttrs, sal_False); } //------------------------------------------------------------------------- void OGenericAdministrationPage::ActivatePage() { TabPage::ActivatePage(); OSL_ENSURE(m_pItemSetHelper,"NO ItemSetHelper set!"); if ( m_pItemSetHelper ) ActivatePage(*m_pItemSetHelper->getOutputSet()); } //------------------------------------------------------------------------- void OGenericAdministrationPage::ActivatePage(const SfxItemSet& _rSet) { implInitControls(_rSet, sal_True); } // ----------------------------------------------------------------------- void OGenericAdministrationPage::getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly) { SFX_ITEMSET_GET(_rSet, pInvalid, SfxBoolItem, DSID_INVALID_SELECTION, sal_True); _rValid = !pInvalid || !pInvalid->GetValue(); SFX_ITEMSET_GET(_rSet, pReadonly, SfxBoolItem, DSID_READONLY, sal_True); _rReadonly = !_rValid || (pReadonly && pReadonly->GetValue()); } // ----------------------------------------------------------------------- IMPL_LINK(OGenericAdministrationPage, OnControlModified, Control*, EMPTYARG) { callModifiedHdl(); return 0L; } // ----------------------------------------------------------------------- sal_Bool OGenericAdministrationPage::getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr) { // collect all ODBC data source names StringBag aOdbcDatasources; OOdbcEnumeration aEnumeration; if (!aEnumeration.isLoaded()) { // show an error message LocalResourceAccess aLocRes( PAGE_GENERAL, RSC_TABPAGE ); String sError(ModuleRes(STR_COULDNOTLOAD_ODBCLIB)); sError.SearchAndReplaceAscii("#lib#", aEnumeration.getLibraryName()); ErrorBox aDialog(this, WB_OK, sError); aDialog.Execute(); return sal_False; } else { aEnumeration.getDatasourceNames(aOdbcDatasources); // excute the select dialog ODatasourceSelectDialog aSelector(GetParent(), aOdbcDatasources, _eType); if (_sCurr.getLength()) aSelector.Select(_sCurr); if ( RET_OK == aSelector.Execute() ) _sReturn = aSelector.GetSelected(); } return sal_True; } // ----------------------------------------------------------------------- void OGenericAdministrationPage::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { // check whether or not the selection is invalid or readonly (invalid implies readonly, but not vice versa) sal_Bool bValid, bReadonly; getFlags(_rSet, bValid, bReadonly); ::std::vector< ISaveValueWrapper* > aControlList; if ( _bSaveValue ) { fillControls(aControlList); ::std::for_each(aControlList.begin(),aControlList.end(),TSaveValueWrapperFunctor()); } if ( bReadonly ) { fillWindows(aControlList); ::std::for_each(aControlList.begin(),aControlList.end(),TDisableWrapperFunctor()); } ::std::for_each(aControlList.begin(),aControlList.end(),TDeleteWrapperFunctor()); aControlList.clear(); } // ----------------------------------------------------------------------- void OGenericAdministrationPage::enableHeader( const Bitmap& /*_rBitmap*/, sal_Int32 /*_nPixelHeight*/, GrantAccess ) { } // ----------------------------------------------------------------------- void OGenericAdministrationPage::initializePage() { OSL_ENSURE(m_pItemSetHelper,"NO ItemSetHelper set!"); if ( m_pItemSetHelper ) Reset(*m_pItemSetHelper->getOutputSet()); } // ----------------------------------------------------------------------- sal_Bool OGenericAdministrationPage::commitPage(COMMIT_REASON /*_eReason*/) { return sal_True; } // ----------------------------------------------------------------------- void OGenericAdministrationPage::fillBool( SfxItemSet& _rSet, CheckBox* _pCheckBox, USHORT _nID, sal_Bool& _bChangedSomething, bool _bRevertValue ) { if ( (_pCheckBox != NULL ) && ( _pCheckBox->GetState() != _pCheckBox->GetSavedValue() ) ) { sal_Bool bValue = _pCheckBox->IsChecked(); if ( _bRevertValue ) bValue = !bValue; _rSet.Put( SfxBoolItem( _nID, bValue ) ); _bChangedSomething = sal_True; } } // ----------------------------------------------------------------------- void OGenericAdministrationPage::fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething) { if( (_pEdit != NULL) && (_pEdit->GetValue() != _pEdit->GetSavedValue().ToInt32()) ) { _rSet.Put(SfxInt32Item(_nID, static_cast<INT32>(_pEdit->GetValue()))); _bChangedSomething = sal_True; } } // ----------------------------------------------------------------------- void OGenericAdministrationPage::fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething) { if( (_pEdit != NULL) && (_pEdit->GetText() != _pEdit->GetSavedValue()) ) { _rSet.Put(SfxStringItem(_nID, _pEdit->GetText())); _bChangedSomething = sal_True; } } void OGenericAdministrationPage::SetControlFontWeight(Window* _pWindow, FontWeight _eWeight) { Font aFont = _pWindow->GetControlFont(); aFont.SetWeight( _eWeight ); _pWindow->SetControlFont( aFont ); } // ----------------------------------------------------------------------- IMPL_LINK(OGenericAdministrationPage, OnTestConnectionClickHdl, PushButton*, /*_pButton*/) { OSL_ENSURE(m_pAdminDialog,"No Admin dialog set! ->GPF"); sal_Bool bSuccess = sal_False; if ( m_pAdminDialog ) { m_pAdminDialog->saveDatasource(); OGenericAdministrationPage::implInitControls(*m_pItemSetHelper->getOutputSet(), sal_True); sal_Bool bShowMessage = sal_True; try { ::std::pair< Reference<XConnection>,sal_Bool> xConnection = m_pAdminDialog->createConnection(); bShowMessage = xConnection.second; bSuccess = xConnection.first.is(); ::comphelper::disposeComponent(xConnection.first); } catch(Exception&) { } if ( bShowMessage ) { OSQLMessageBox::MessageType eImage = OSQLMessageBox::Info; String aMessage,sTitle; sTitle = String (ModuleRes(STR_CONNECTION_TEST)); if ( bSuccess ) { aMessage = String(ModuleRes(STR_CONNECTION_SUCCESS)); } else { eImage = OSQLMessageBox::Error; aMessage = String(ModuleRes(STR_CONNECTION_NO_SUCCESS)); } OSQLMessageBox aMsg(this,sTitle,aMessage); aMsg.Execute(); } if ( !bSuccess ) m_pAdminDialog->clearPassword(); } return 0L; } void OGenericAdministrationPage::SetHeaderText( USHORT _nFTResId, USHORT _StringResId) { delete(m_pFT_HeaderText); m_pFT_HeaderText = new FixedText(this, ModuleRes(_nFTResId)); String sHeaderText = String(ModuleRes(_StringResId)); m_pFT_HeaderText->SetText(sHeaderText); SetControlFontWeight(m_pFT_HeaderText); } Point OGenericAdministrationPage::MovePoint(Point _aPixelBasePoint, sal_Int32 _XShift, sal_Int32 _YShift) { Point rLogicPoint = PixelToLogic( _aPixelBasePoint, MAP_APPFONT ); sal_uInt32 XPos = rLogicPoint.X() + _XShift; sal_uInt32 YPos = rLogicPoint.Y() + _YShift; Point aNewPixelPoint = LogicToPixel(Point(XPos, YPos), MAP_APPFONT); return aNewPixelPoint; } //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS odbmacros2 (1.49.20); FILE MERGED 2008/02/11 11:17:53 fs 1.49.20.2: IWizardPage is COMMIT_REASON is deprecated - replace usages with CommitPageReason, while I have an svtools-incompatible CWS 2008/01/15 09:50:00 fs 1.49.20.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: adminpages.cxx,v $ * * $Revision: 1.50 $ * * last change: $Author: kz $ $Date: 2008-03-06 18:16:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef _DBAUI_ADMINPAGES_HXX_ #include "adminpages.hxx" #endif #ifndef _DBAUI_DBADMIN_HRC_ #include "dbadmin.hrc" #endif #ifndef _DBU_DLG_HRC_ #include "dbu_dlg.hrc" #endif #ifndef _SFXSTRITEM_HXX #include <svtools/stritem.hxx> #endif #ifndef _SFXENUMITEM_HXX #include <svtools/eitem.hxx> #endif #ifndef _SFXINTITEM_HXX #include <svtools/intitem.hxx> #endif #ifndef _DBAUI_DATASOURCEITEMS_HXX_ #include "dsitems.hxx" #endif #ifndef DBACCESS_SHARED_DBUSTRINGS_HRC #include "dbustrings.hrc" #endif #ifndef _DBAUI_DBADMIN_HXX_ #include "dbadmin.hxx" #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DBAUI_SQLMESSAGE_HXX_ #include "sqlmessage.hxx" #endif #ifndef _SV_ACCEL_HXX #include <vcl/accel.hxx> #endif #include <algorithm> #include <stdlib.h> #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _DBAUI_DSSELECT_HXX_ #include "dsselect.hxx" #endif #ifndef _DBAUI_ODBC_CONFIG_HXX_ #include "odbcconfig.hxx" #endif #ifndef _DBAUI_LOCALRESACCESS_HXX_ #include "localresaccess.hxx" #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::dbtools; using namespace ::svt; //========================================================================= //= OGenericAdministrationPage //========================================================================= DBG_NAME(OGenericAdministrationPage) //------------------------------------------------------------------------- OGenericAdministrationPage::OGenericAdministrationPage(Window* _pParent, const ResId& _rId, const SfxItemSet& _rAttrSet) :SfxTabPage(_pParent, _rId, _rAttrSet) ,m_abEnableRoadmap(sal_False) ,m_pAdminDialog(NULL) ,m_pItemSetHelper(NULL) ,m_pFT_HeaderText(NULL) { DBG_CTOR(OGenericAdministrationPage,NULL); SetExchangeSupport(sal_True); } //------------------------------------------------------------------------- OGenericAdministrationPage::~OGenericAdministrationPage() { DELETEZ(m_pFT_HeaderText); DBG_DTOR(OGenericAdministrationPage,NULL); } //------------------------------------------------------------------------- int OGenericAdministrationPage::DeactivatePage(SfxItemSet* _pSet) { if (_pSet) { if (!prepareLeave()) return KEEP_PAGE; FillItemSet(*_pSet); } return LEAVE_PAGE; } //------------------------------------------------------------------------- void OGenericAdministrationPage::Reset(const SfxItemSet& _rCoreAttrs) { implInitControls(_rCoreAttrs, sal_False); } //------------------------------------------------------------------------- void OGenericAdministrationPage::ActivatePage() { TabPage::ActivatePage(); OSL_ENSURE(m_pItemSetHelper,"NO ItemSetHelper set!"); if ( m_pItemSetHelper ) ActivatePage(*m_pItemSetHelper->getOutputSet()); } //------------------------------------------------------------------------- void OGenericAdministrationPage::ActivatePage(const SfxItemSet& _rSet) { implInitControls(_rSet, sal_True); } // ----------------------------------------------------------------------- void OGenericAdministrationPage::getFlags(const SfxItemSet& _rSet, sal_Bool& _rValid, sal_Bool& _rReadonly) { SFX_ITEMSET_GET(_rSet, pInvalid, SfxBoolItem, DSID_INVALID_SELECTION, sal_True); _rValid = !pInvalid || !pInvalid->GetValue(); SFX_ITEMSET_GET(_rSet, pReadonly, SfxBoolItem, DSID_READONLY, sal_True); _rReadonly = !_rValid || (pReadonly && pReadonly->GetValue()); } // ----------------------------------------------------------------------- IMPL_LINK(OGenericAdministrationPage, OnControlModified, Control*, EMPTYARG) { callModifiedHdl(); return 0L; } // ----------------------------------------------------------------------- sal_Bool OGenericAdministrationPage::getSelectedDataSource(DATASOURCE_TYPE _eType,::rtl::OUString& _sReturn,::rtl::OUString& _sCurr) { // collect all ODBC data source names StringBag aOdbcDatasources; OOdbcEnumeration aEnumeration; if (!aEnumeration.isLoaded()) { // show an error message LocalResourceAccess aLocRes( PAGE_GENERAL, RSC_TABPAGE ); String sError(ModuleRes(STR_COULDNOTLOAD_ODBCLIB)); sError.SearchAndReplaceAscii("#lib#", aEnumeration.getLibraryName()); ErrorBox aDialog(this, WB_OK, sError); aDialog.Execute(); return sal_False; } else { aEnumeration.getDatasourceNames(aOdbcDatasources); // excute the select dialog ODatasourceSelectDialog aSelector(GetParent(), aOdbcDatasources, _eType); if (_sCurr.getLength()) aSelector.Select(_sCurr); if ( RET_OK == aSelector.Execute() ) _sReturn = aSelector.GetSelected(); } return sal_True; } // ----------------------------------------------------------------------- void OGenericAdministrationPage::implInitControls(const SfxItemSet& _rSet, sal_Bool _bSaveValue) { // check whether or not the selection is invalid or readonly (invalid implies readonly, but not vice versa) sal_Bool bValid, bReadonly; getFlags(_rSet, bValid, bReadonly); ::std::vector< ISaveValueWrapper* > aControlList; if ( _bSaveValue ) { fillControls(aControlList); ::std::for_each(aControlList.begin(),aControlList.end(),TSaveValueWrapperFunctor()); } if ( bReadonly ) { fillWindows(aControlList); ::std::for_each(aControlList.begin(),aControlList.end(),TDisableWrapperFunctor()); } ::std::for_each(aControlList.begin(),aControlList.end(),TDeleteWrapperFunctor()); aControlList.clear(); } // ----------------------------------------------------------------------- void OGenericAdministrationPage::initializePage() { OSL_ENSURE(m_pItemSetHelper,"NO ItemSetHelper set!"); if ( m_pItemSetHelper ) Reset(*m_pItemSetHelper->getOutputSet()); } // ----------------------------------------------------------------------- sal_Bool OGenericAdministrationPage::commitPage( CommitPageReason ) { return sal_True; } // ----------------------------------------------------------------------- void OGenericAdministrationPage::fillBool( SfxItemSet& _rSet, CheckBox* _pCheckBox, USHORT _nID, sal_Bool& _bChangedSomething, bool _bRevertValue ) { if ( (_pCheckBox != NULL ) && ( _pCheckBox->GetState() != _pCheckBox->GetSavedValue() ) ) { sal_Bool bValue = _pCheckBox->IsChecked(); if ( _bRevertValue ) bValue = !bValue; _rSet.Put( SfxBoolItem( _nID, bValue ) ); _bChangedSomething = sal_True; } } // ----------------------------------------------------------------------- void OGenericAdministrationPage::fillInt32(SfxItemSet& _rSet,NumericField* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething) { if( (_pEdit != NULL) && (_pEdit->GetValue() != _pEdit->GetSavedValue().ToInt32()) ) { _rSet.Put(SfxInt32Item(_nID, static_cast<INT32>(_pEdit->GetValue()))); _bChangedSomething = sal_True; } } // ----------------------------------------------------------------------- void OGenericAdministrationPage::fillString(SfxItemSet& _rSet,Edit* _pEdit,USHORT _nID,sal_Bool& _bChangedSomething) { if( (_pEdit != NULL) && (_pEdit->GetText() != _pEdit->GetSavedValue()) ) { _rSet.Put(SfxStringItem(_nID, _pEdit->GetText())); _bChangedSomething = sal_True; } } void OGenericAdministrationPage::SetControlFontWeight(Window* _pWindow, FontWeight _eWeight) { Font aFont = _pWindow->GetControlFont(); aFont.SetWeight( _eWeight ); _pWindow->SetControlFont( aFont ); } // ----------------------------------------------------------------------- IMPL_LINK(OGenericAdministrationPage, OnTestConnectionClickHdl, PushButton*, /*_pButton*/) { OSL_ENSURE(m_pAdminDialog,"No Admin dialog set! ->GPF"); sal_Bool bSuccess = sal_False; if ( m_pAdminDialog ) { m_pAdminDialog->saveDatasource(); OGenericAdministrationPage::implInitControls(*m_pItemSetHelper->getOutputSet(), sal_True); sal_Bool bShowMessage = sal_True; try { ::std::pair< Reference<XConnection>,sal_Bool> xConnection = m_pAdminDialog->createConnection(); bShowMessage = xConnection.second; bSuccess = xConnection.first.is(); ::comphelper::disposeComponent(xConnection.first); } catch(Exception&) { } if ( bShowMessage ) { OSQLMessageBox::MessageType eImage = OSQLMessageBox::Info; String aMessage,sTitle; sTitle = String (ModuleRes(STR_CONNECTION_TEST)); if ( bSuccess ) { aMessage = String(ModuleRes(STR_CONNECTION_SUCCESS)); } else { eImage = OSQLMessageBox::Error; aMessage = String(ModuleRes(STR_CONNECTION_NO_SUCCESS)); } OSQLMessageBox aMsg(this,sTitle,aMessage); aMsg.Execute(); } if ( !bSuccess ) m_pAdminDialog->clearPassword(); } return 0L; } void OGenericAdministrationPage::SetHeaderText( USHORT _nFTResId, USHORT _StringResId) { delete(m_pFT_HeaderText); m_pFT_HeaderText = new FixedText(this, ModuleRes(_nFTResId)); String sHeaderText = String(ModuleRes(_StringResId)); m_pFT_HeaderText->SetText(sHeaderText); SetControlFontWeight(m_pFT_HeaderText); } Point OGenericAdministrationPage::MovePoint(Point _aPixelBasePoint, sal_Int32 _XShift, sal_Int32 _YShift) { Point rLogicPoint = PixelToLogic( _aPixelBasePoint, MAP_APPFONT ); sal_uInt32 XPos = rLogicPoint.X() + _XShift; sal_uInt32 YPos = rLogicPoint.Y() + _YShift; Point aNewPixelPoint = LogicToPixel(Point(XPos, YPos), MAP_APPFONT); return aNewPixelPoint; } //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>#include "minesweeperwelcomeview.h" #include "ui_minesweeprwelcomeview.h" #include <QPushButton> namespace MS { MinesweeperWelcomeView::MinesweeperWelcomeView(QWidget* parent) : QWidget(parent), ui_(new Ui::MinesweeperWelcomeView) { ui_->setupUi(this); connect(ui_->quitPushButton, &QPushButton::clicked, this, &MinesweeperWelcomeView::quit); connect(ui_->playPushButton, &QPushButton::clicked, [this] { auto checkedButton = ui_->buttonGroup->checkedButton(); if(!checkedButton) { return; } auto targetString = checkedButton->text(); if(targetString == ui_->easyRadioButton->text()) { emit start(8, 8, 10); } else if(targetString == ui_->middleRadioButton->text()) { emit start(16, 16, 40); } else if(targetString == ui_->hardRadioButton->text()) { emit start(16, 30, 99); } else if(targetString == ui_->customRadioButton->text()) { bool rowOk = false; auto row = ui_->rowLineEdit->text().toInt(&rowOk); if(!rowOk || row <= 0) { return; } bool columnOk = false; auto column = ui_->columnLineEdit->text().toInt(&columnOk); if(!columnOk || column <= 0) { return; } bool mineOk = false; auto mine = ui_->minesLineEdit->text().toInt(&mineOk); if(!mineOk || !(0 < mine && mine < (row * column))) { return; } emit start(row, column, mine); } hide(); }); } MinesweeperWelcomeView::~MinesweeperWelcomeView() { } } // namespace MS <commit_msg>fix filename typo<commit_after>#include "minesweeperwelcomeview.h" #include "ui_minesweeperwelcomeview.h" #include <QPushButton> namespace MS { MinesweeperWelcomeView::MinesweeperWelcomeView(QWidget* parent) : QWidget(parent), ui_(new Ui::MinesweeperWelcomeView) { ui_->setupUi(this); connect(ui_->quitPushButton, &QPushButton::clicked, this, &MinesweeperWelcomeView::quit); connect(ui_->playPushButton, &QPushButton::clicked, [this] { auto checkedButton = ui_->buttonGroup->checkedButton(); if(!checkedButton) { return; } auto targetString = checkedButton->text(); if(targetString == ui_->easyRadioButton->text()) { emit start(8, 8, 10); } else if(targetString == ui_->middleRadioButton->text()) { emit start(16, 16, 40); } else if(targetString == ui_->hardRadioButton->text()) { emit start(16, 30, 99); } else if(targetString == ui_->customRadioButton->text()) { bool rowOk = false; auto row = ui_->rowLineEdit->text().toInt(&rowOk); if(!rowOk || row <= 0) { return; } bool columnOk = false; auto column = ui_->columnLineEdit->text().toInt(&columnOk); if(!columnOk || column <= 0) { return; } bool mineOk = false; auto mine = ui_->minesLineEdit->text().toInt(&mineOk); if(!mineOk || !(0 < mine && mine < (row * column))) { return; } emit start(row, column, mine); } hide(); }); } MinesweeperWelcomeView::~MinesweeperWelcomeView() { } } // namespace MS <|endoftext|>
<commit_before>/* * Haxe Setup * Copyright (c)2006 Nicolas Cannasse * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // this is a small program that do basic Haxe setup on Windows #include <windows.h> static void Set( HKEY k, const char *name, DWORD t, const char *data ) { RegSetValueEx(k,name,0,t,(const BYTE*)data,(DWORD)strlen(data)+1); } int WINAPI WinMain( HINSTANCE inst, HINSTANCE prev, LPSTR lpCmdLine, int nCmdShow ) { char path[MAX_PATH]; *path = '"'; GetModuleFileName(NULL,path+1,MAX_PATH); // register .hxml extension char *s = strrchr(path,'\\') + 1; strcpy(s,"haxe.exe\" -prompt \"%1\""); HKEY k; RegCreateKey(HKEY_CLASSES_ROOT,".hxml\\shell\\Compile\\command",&k); RegSetValueEx(k,NULL,0,REG_SZ,(const BYTE*)path,(DWORD)(strlen(path)+1)); *s = 0; // add %HAXEPATH% to PATH and set HAXEPATH to current path DWORD ktype; DWORD ksize = 16000; char *kdata = new char[16000]; memset(kdata,0,ksize); RegOpenKey(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",&k); RegQueryValueEx(k,"PATH",NULL,&ktype,(LPBYTE)kdata,&ksize); if( strstr(kdata,"%HAXEPATH%") == NULL ) { char *s = kdata + strlen(kdata); strcpy(s,";%HAXEPATH%"); Set(k,"PATH",REG_EXPAND_SZ,kdata); } if( strstr(kdata,"%NEKO_INSTPATH%") == NULL ) { char *s = kdata + strlen(kdata); strcpy(s,";%NEKO_INSTPATH%"); Set(k,"PATH",REG_EXPAND_SZ,kdata); } Set(k,"HAXEPATH",REG_SZ,path + 1); s[-1] = 0; strcpy(strrchr(path,'\\'),"\\neko"); Set(k,"NEKO_INSTPATH",REG_SZ,path+1); RegCloseKey(k); // inform running apps of env changes (W2K/NT systems only ?) DWORD unused; SendMessageTimeout(HWND_BROADCAST,WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 5000, &unused ); delete kdata; // register if( strcmp(lpCmdLine,"-silent") != 0 ) MessageBox(NULL,"Setup completed, you can start using Haxe now","haxesetup",MB_OK | MB_ICONINFORMATION); return 0; } <commit_msg>[installer] fixed crash<commit_after>/* * Haxe Setup * Copyright (c)2006 Nicolas Cannasse * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // this is a small program that do basic Haxe setup on Windows #include <windows.h> static void Set( HKEY k, const char *name, DWORD t, const char *data ) { RegSetValueEx(k,name,0,t,(const BYTE*)data,(DWORD)strlen(data)+1); } int WINAPI WinMain( HINSTANCE inst, HINSTANCE prev, LPSTR lpCmdLine, int nCmdShow ) { char path[MAX_PATH]; *path = '"'; GetModuleFileName(NULL,path+1,MAX_PATH); // register .hxml extension char *s = strrchr(path,'\\') + 1; strcpy(s,"haxe.exe\" -prompt \"%1\""); HKEY k; RegCreateKey(HKEY_CLASSES_ROOT,".hxml\\shell\\Compile\\command",&k); RegSetValueEx(k,NULL,0,REG_SZ,(const BYTE*)path,(DWORD)(strlen(path)+1)); *s = 0; // add %HAXEPATH% to PATH and set HAXEPATH to current path DWORD ktype; DWORD ksize = 16000; char *kdata = new char[16000]; memset(kdata,0,ksize); RegOpenKey(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",&k); RegQueryValueEx(k,"PATH",NULL,&ktype,(LPBYTE)kdata,&ksize); if( strstr(kdata,"%HAXEPATH%") == NULL ) { char *s = kdata + strlen(kdata); strcpy(s,";%HAXEPATH%"); Set(k,"PATH",REG_EXPAND_SZ,kdata); } if( strstr(kdata,"%NEKO_INSTPATH%") == NULL ) { char *s = kdata + strlen(kdata); strcpy(s,";%NEKO_INSTPATH%"); Set(k,"PATH",REG_EXPAND_SZ,kdata); } Set(k,"HAXEPATH",REG_SZ,path + 1); s[-1] = 0; strcpy(strrchr(path,'\\'),"\\neko"); Set(k,"NEKO_INSTPATH",REG_SZ,path+1); RegCloseKey(k); // inform running apps of env changes (W2K/NT systems only ?) DWORD unused; SendMessageTimeout(HWND_BROADCAST,WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 5000, &unused ); // delete kdata; // // register // if( strcmp(lpCmdLine,"-silent") != 0 ) // MessageBox(NULL,"Setup completed, you can start using Haxe now","haxesetup",MB_OK | MB_ICONINFORMATION); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: desktopcontext.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-05-10 13:00:50 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DESKTOP_DESKTOPCONTEXT_HXX_ #define _DESKTOP_DESKTOPCONTEXT_HXX_ #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _UNO_CURRENT_CONTEXT_HXX_ #include <uno/current_context.hxx> #endif #define DESKTOP_ENVIRONMENT_NAME "system.desktop-environment" namespace desktop { class DesktopContext: public cppu::WeakImplHelper1< com::sun::star::uno::XCurrentContext > { public: DesktopContext( const com::sun::star::uno::Reference< com::sun::star::uno::XCurrentContext > & ctx); // XCurrentContext virtual com::sun::star::uno::Any SAL_CALL getValueByName( const rtl::OUString& Name ) throw (com::sun::star::uno::RuntimeException); private: com::sun::star::uno::Reference< com::sun::star::uno::XCurrentContext > m_xNextContext; }; } #endif // _DESKTOP_DESKTOPCONTEXT_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.2.322); FILE MERGED 2005/09/05 17:50:19 rt 1.2.322.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: desktopcontext.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:07:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DESKTOP_DESKTOPCONTEXT_HXX_ #define _DESKTOP_DESKTOPCONTEXT_HXX_ #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _UNO_CURRENT_CONTEXT_HXX_ #include <uno/current_context.hxx> #endif #define DESKTOP_ENVIRONMENT_NAME "system.desktop-environment" namespace desktop { class DesktopContext: public cppu::WeakImplHelper1< com::sun::star::uno::XCurrentContext > { public: DesktopContext( const com::sun::star::uno::Reference< com::sun::star::uno::XCurrentContext > & ctx); // XCurrentContext virtual com::sun::star::uno::Any SAL_CALL getValueByName( const rtl::OUString& Name ) throw (com::sun::star::uno::RuntimeException); private: com::sun::star::uno::Reference< com::sun::star::uno::XCurrentContext > m_xNextContext; }; } #endif // _DESKTOP_DESKTOPCONTEXT_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: db.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 09:40:50 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #include <db.hxx> #include <rtl/alloc.h> #include <cstring> #include <errno.h> namespace berkeleydbproxy { //---------------------------------------------------------------------------- namespace db_internal { static void raise_error(int dberr, const char * where); static inline int check_error(int dberr, const char * where) { if (dberr) raise_error(dberr,where); return dberr; } } //---------------------------------------------------------------------------- DbEnv::DbEnv(u_int32_t flags) : m_pDBENV(0) { db_internal::check_error( db_env_create(&m_pDBENV,flags), "DbEnv::DbEnv" ); } DbEnv::~DbEnv() { if (m_pDBENV) { // should not happen // TODO: add assert m_pDBENV->close(m_pDBENV,0); } } int DbEnv::open(const char *db_home, u_int32_t flags, int mode) { return db_internal::check_error( m_pDBENV->open(m_pDBENV,db_home,flags,mode), "DbEnv::open" ); } void DbEnv::close(u_int32_t flags) { int error = m_pDBENV->close(m_pDBENV,flags); m_pDBENV = 0; db_internal::check_error(error, "DbEnv::close"); } int DbEnv::set_alloc(db_malloc_fcn_type app_malloc, db_realloc_fcn_type app_realloc, db_free_fcn_type app_free) { int err = m_pDBENV->set_alloc(m_pDBENV,app_malloc,app_realloc,app_free); return db_internal::check_error(err,"Db::set_alloc"); } char *DbEnv::strerror(int error) { return (db_strerror(error)); } //---------------------------------------------------------------------------- int Db::set_alloc( db_malloc_fcn_type app_malloc, db_realloc_fcn_type app_realloc, db_free_fcn_type app_free) { int err = m_pDBP->set_alloc(m_pDBP,app_malloc,app_realloc,app_free); return db_internal::check_error(err,"Db::set_alloc"); } Db::Db(DbEnv* pDbenv,u_int32_t flags) : m_pDBP(0) { db_internal::check_error( db_create(&m_pDBP,pDbenv ? pDbenv->m_pDBENV:0,flags),"Db::Db" ); } Db::~Db() { if (m_pDBP) { // should not happen // TODO: add assert } } int Db::close(u_int32_t flags) { int error = m_pDBP->close(m_pDBP,flags); m_pDBP = 0; return db_internal::check_error(error,"Db::close"); } int Db::open(DB_TXN *txnid, const char *file, const char *database, DBTYPE type, u_int32_t flags, int mode) { int err = m_pDBP->open(m_pDBP,txnid,file,database,type,flags,mode); return db_internal::check_error( err,"Db::open" ); } int Db::get(DB_TXN *txnid, Dbt *key, Dbt *data, u_int32_t flags) { int err = m_pDBP->get(m_pDBP,txnid,key,data,flags); // these are non-exceptional outcomes if (err != DB_NOTFOUND && err != DB_KEYEMPTY) db_internal::check_error( err,"Db::get" ); return err; } int Db::put(DB_TXN* txnid, Dbt *key, Dbt *data, u_int32_t flags) { int err = m_pDBP->put(m_pDBP,txnid,key,data,flags); if (err != DB_KEYEXIST) // this is a non-exceptional outcome db_internal::check_error( err,"Db::put" ); return err; } int Db::cursor(DB_TXN *txnid, Dbc **cursorp, u_int32_t flags) { DBC * dbc = 0; int error = m_pDBP->cursor(m_pDBP,txnid,&dbc,flags); if (!db_internal::check_error(error,"Db::cursor")) *cursorp = new Dbc(dbc); return error; } #define DB_INCOMPLETE (-30999)/* Sync didn't finish. */ int Db::sync(u_int32_t flags) { int err; DB *db = m_pDBP; if (!db) { db_internal::check_error(EINVAL,"Db::sync"); return (EINVAL); } if ((err = db->sync(db, flags)) != 0 && err != DB_INCOMPLETE) { db_internal::check_error(err, "Db::sync"); return (err); } return (err); } int Db::del(Dbt *key, u_int32_t flags) { DB *db = m_pDBP; int err; if ((err = db->del(db, 0, key, flags)) != 0) { // DB_NOTFOUND is a "normal" return, so should not be // thrown as an error // if (err != DB_NOTFOUND) { db_internal::check_error(err, "Db::del"); return (err); } } return (err); } //---------------------------------------------------------------------------- Dbc::Dbc(DBC * dbc) : m_pDBC(dbc) { } Dbc::~Dbc() { } int Dbc::close() { int err = m_pDBC->c_close(m_pDBC); delete this; return db_internal::check_error( err,"Dbcursor::close" ); } int Dbc::get(Dbt *key, Dbt *data, u_int32_t flags) { int err = m_pDBC->c_get(m_pDBC,key,data,flags); // these are non-exceptional outcomes if (err != DB_NOTFOUND && err != DB_KEYEMPTY) db_internal::check_error( err, "Dbcursor::get" ); return err; } int Dbc::del(u_int32_t flags_arg) { DBC *cursor = m_pDBC; int err; if ((err = cursor->c_del(cursor, flags_arg)) != 0) { // DB_KEYEMPTY is a "normal" return, so should not be // thrown as an error // if (err != DB_KEYEMPTY) { db_internal::check_error( err, "Db::del"); return (err); } } return (err); } //---------------------------------------------------------------------------- Dbt::Dbt() { using namespace std; DBT * thispod = this; memset(thispod, 0, sizeof *thispod); } Dbt::Dbt(void *data_arg, u_int32_t size_arg) { using namespace std; DBT * thispod = this; memset(thispod, 0, sizeof *thispod); this->set_data(data_arg); this->set_size(size_arg); } Dbt::Dbt(const Dbt & other) { using namespace std; const DBT *otherpod = &other; DBT *thispod = this; memcpy(thispod, otherpod, sizeof *thispod); } Dbt& Dbt::operator = (const Dbt & other) { if (this != &other) { using namespace std; const DBT *otherpod = &other; DBT *thispod = this; memcpy(thispod, otherpod, sizeof *thispod); } return *this; } Dbt::~Dbt() { } void * Dbt::get_data() const { return this->data; } void Dbt::set_data(void *value) { this->data = value; } u_int32_t Dbt::get_size() const { return this->size; } void Dbt::set_size(u_int32_t value) { this->size = value; } void Dbt::set_flags(u_int32_t value) { this->flags = value; } //---------------------------------------------------------------------------- void db_internal::raise_error(int dberr, const char * where) { if (!where) where = "<unknown>"; const char * dberrmsg = db_strerror(dberr); if (!dberrmsg || !*dberrmsg) dberrmsg = "<unknown DB error>"; rtl::OString msg = where; msg += ": "; msg += dberrmsg; throw DbException(msg); } //---------------------------------------------------------------------------- } // namespace ecomp <commit_msg>INTEGRATION: CWS changefileheader (1.4.396); FILE MERGED 2008/03/28 15:26:43 rt 1.4.396.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: db.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_desktop.hxx" #include <db.hxx> #include <rtl/alloc.h> #include <cstring> #include <errno.h> namespace berkeleydbproxy { //---------------------------------------------------------------------------- namespace db_internal { static void raise_error(int dberr, const char * where); static inline int check_error(int dberr, const char * where) { if (dberr) raise_error(dberr,where); return dberr; } } //---------------------------------------------------------------------------- DbEnv::DbEnv(u_int32_t flags) : m_pDBENV(0) { db_internal::check_error( db_env_create(&m_pDBENV,flags), "DbEnv::DbEnv" ); } DbEnv::~DbEnv() { if (m_pDBENV) { // should not happen // TODO: add assert m_pDBENV->close(m_pDBENV,0); } } int DbEnv::open(const char *db_home, u_int32_t flags, int mode) { return db_internal::check_error( m_pDBENV->open(m_pDBENV,db_home,flags,mode), "DbEnv::open" ); } void DbEnv::close(u_int32_t flags) { int error = m_pDBENV->close(m_pDBENV,flags); m_pDBENV = 0; db_internal::check_error(error, "DbEnv::close"); } int DbEnv::set_alloc(db_malloc_fcn_type app_malloc, db_realloc_fcn_type app_realloc, db_free_fcn_type app_free) { int err = m_pDBENV->set_alloc(m_pDBENV,app_malloc,app_realloc,app_free); return db_internal::check_error(err,"Db::set_alloc"); } char *DbEnv::strerror(int error) { return (db_strerror(error)); } //---------------------------------------------------------------------------- int Db::set_alloc( db_malloc_fcn_type app_malloc, db_realloc_fcn_type app_realloc, db_free_fcn_type app_free) { int err = m_pDBP->set_alloc(m_pDBP,app_malloc,app_realloc,app_free); return db_internal::check_error(err,"Db::set_alloc"); } Db::Db(DbEnv* pDbenv,u_int32_t flags) : m_pDBP(0) { db_internal::check_error( db_create(&m_pDBP,pDbenv ? pDbenv->m_pDBENV:0,flags),"Db::Db" ); } Db::~Db() { if (m_pDBP) { // should not happen // TODO: add assert } } int Db::close(u_int32_t flags) { int error = m_pDBP->close(m_pDBP,flags); m_pDBP = 0; return db_internal::check_error(error,"Db::close"); } int Db::open(DB_TXN *txnid, const char *file, const char *database, DBTYPE type, u_int32_t flags, int mode) { int err = m_pDBP->open(m_pDBP,txnid,file,database,type,flags,mode); return db_internal::check_error( err,"Db::open" ); } int Db::get(DB_TXN *txnid, Dbt *key, Dbt *data, u_int32_t flags) { int err = m_pDBP->get(m_pDBP,txnid,key,data,flags); // these are non-exceptional outcomes if (err != DB_NOTFOUND && err != DB_KEYEMPTY) db_internal::check_error( err,"Db::get" ); return err; } int Db::put(DB_TXN* txnid, Dbt *key, Dbt *data, u_int32_t flags) { int err = m_pDBP->put(m_pDBP,txnid,key,data,flags); if (err != DB_KEYEXIST) // this is a non-exceptional outcome db_internal::check_error( err,"Db::put" ); return err; } int Db::cursor(DB_TXN *txnid, Dbc **cursorp, u_int32_t flags) { DBC * dbc = 0; int error = m_pDBP->cursor(m_pDBP,txnid,&dbc,flags); if (!db_internal::check_error(error,"Db::cursor")) *cursorp = new Dbc(dbc); return error; } #define DB_INCOMPLETE (-30999)/* Sync didn't finish. */ int Db::sync(u_int32_t flags) { int err; DB *db = m_pDBP; if (!db) { db_internal::check_error(EINVAL,"Db::sync"); return (EINVAL); } if ((err = db->sync(db, flags)) != 0 && err != DB_INCOMPLETE) { db_internal::check_error(err, "Db::sync"); return (err); } return (err); } int Db::del(Dbt *key, u_int32_t flags) { DB *db = m_pDBP; int err; if ((err = db->del(db, 0, key, flags)) != 0) { // DB_NOTFOUND is a "normal" return, so should not be // thrown as an error // if (err != DB_NOTFOUND) { db_internal::check_error(err, "Db::del"); return (err); } } return (err); } //---------------------------------------------------------------------------- Dbc::Dbc(DBC * dbc) : m_pDBC(dbc) { } Dbc::~Dbc() { } int Dbc::close() { int err = m_pDBC->c_close(m_pDBC); delete this; return db_internal::check_error( err,"Dbcursor::close" ); } int Dbc::get(Dbt *key, Dbt *data, u_int32_t flags) { int err = m_pDBC->c_get(m_pDBC,key,data,flags); // these are non-exceptional outcomes if (err != DB_NOTFOUND && err != DB_KEYEMPTY) db_internal::check_error( err, "Dbcursor::get" ); return err; } int Dbc::del(u_int32_t flags_arg) { DBC *cursor = m_pDBC; int err; if ((err = cursor->c_del(cursor, flags_arg)) != 0) { // DB_KEYEMPTY is a "normal" return, so should not be // thrown as an error // if (err != DB_KEYEMPTY) { db_internal::check_error( err, "Db::del"); return (err); } } return (err); } //---------------------------------------------------------------------------- Dbt::Dbt() { using namespace std; DBT * thispod = this; memset(thispod, 0, sizeof *thispod); } Dbt::Dbt(void *data_arg, u_int32_t size_arg) { using namespace std; DBT * thispod = this; memset(thispod, 0, sizeof *thispod); this->set_data(data_arg); this->set_size(size_arg); } Dbt::Dbt(const Dbt & other) { using namespace std; const DBT *otherpod = &other; DBT *thispod = this; memcpy(thispod, otherpod, sizeof *thispod); } Dbt& Dbt::operator = (const Dbt & other) { if (this != &other) { using namespace std; const DBT *otherpod = &other; DBT *thispod = this; memcpy(thispod, otherpod, sizeof *thispod); } return *this; } Dbt::~Dbt() { } void * Dbt::get_data() const { return this->data; } void Dbt::set_data(void *value) { this->data = value; } u_int32_t Dbt::get_size() const { return this->size; } void Dbt::set_size(u_int32_t value) { this->size = value; } void Dbt::set_flags(u_int32_t value) { this->flags = value; } //---------------------------------------------------------------------------- void db_internal::raise_error(int dberr, const char * where) { if (!where) where = "<unknown>"; const char * dberrmsg = db_strerror(dberr); if (!dberrmsg || !*dberrmsg) dberrmsg = "<unknown DB error>"; rtl::OString msg = where; msg += ": "; msg += dberrmsg; throw DbException(msg); } //---------------------------------------------------------------------------- } // namespace ecomp <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLESPixelFormat.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreBitwise.h" namespace Ogre { GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat) { switch (mFormat) { case PF_A8: return GL_ALPHA; case PF_L8: case PF_L16: case PF_FLOAT16_R: case PF_FLOAT32_R: return GL_LUMINANCE; case PF_BYTE_LA: case PF_SHORT_GR: case PF_FLOAT16_GR: case PF_FLOAT32_GR: return GL_LUMINANCE_ALPHA; // PVRTC compressed formats #if GL_IMG_texture_compression_pvrtc case PF_PVRTC_RGB2: return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGB4: return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; case PF_PVRTC_RGBA2: return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGBA4: return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; #endif case PF_R3G3B2: case PF_R5G6B5: case PF_FLOAT16_RGB: case PF_FLOAT32_RGB: case PF_SHORT_RGB: return GL_RGB; case PF_X8R8G8B8: case PF_A8R8G8B8: case PF_B8G8R8A8: case PF_A1R5G5B5: case PF_A4R4G4B4: case PF_A2R10G10B10: // This case in incorrect, swaps R & B channels // return GL_BGRA; case PF_X8B8G8R8: case PF_A8B8G8R8: case PF_A2B10G10R10: case PF_FLOAT16_RGBA: case PF_FLOAT32_RGBA: case PF_SHORT_RGBA: return GL_RGBA; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG // Formats are in native endian, so R8G8B8 on little endian is // BGR, on big endian it is RGB. case PF_R8G8B8: return GL_RGB; case PF_B8G8R8: return 0; #else case PF_R8G8B8: return 0; case PF_B8G8R8: return GL_RGB; #endif case PF_DXT1: case PF_DXT3: case PF_DXT5: case PF_B5G6R5: default: return 0; } } GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat) { switch (mFormat) { case PF_A8: case PF_L8: case PF_R8G8B8: case PF_B8G8R8: case PF_BYTE_LA: return GL_UNSIGNED_BYTE; case PF_R5G6B5: case PF_B5G6R5: return GL_UNSIGNED_SHORT_5_6_5; case PF_L16: return GL_UNSIGNED_SHORT; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG case PF_X8B8G8R8: case PF_A8B8G8R8: return GL_UNSIGNED_INT_8_8_8_8_REV; case PF_X8R8G8B8: case PF_A8R8G8B8: return GL_UNSIGNED_INT_8_8_8_8_REV; case PF_B8G8R8A8: return GL_UNSIGNED_BYTE; case PF_R8G8B8A8: return GL_UNSIGNED_BYTE; #else case PF_X8B8G8R8: case PF_A8B8G8R8: case PF_X8R8G8B8: case PF_A8R8G8B8: return GL_UNSIGNED_BYTE; case PF_B8G8R8A8: case PF_R8G8B8A8: return 0; #endif case PF_FLOAT32_R: case PF_FLOAT32_GR: case PF_FLOAT32_RGB: case PF_FLOAT32_RGBA: return GL_FLOAT; case PF_SHORT_RGBA: case PF_SHORT_RGB: case PF_SHORT_GR: return GL_UNSIGNED_SHORT; case PF_A2R10G10B10: case PF_A2B10G10R10: case PF_FLOAT16_R: case PF_FLOAT16_GR: case PF_FLOAT16_RGB: case PF_FLOAT16_RGBA: case PF_R3G3B2: case PF_A1R5G5B5: case PF_A4R4G4B4: // TODO not supported default: return 0; } } GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma) { switch (fmt) { case PF_L8: return GL_LUMINANCE; case PF_A8: return GL_ALPHA; case PF_BYTE_LA: return GL_LUMINANCE_ALPHA; #if GL_IMG_texture_compression_pvrtc case PF_PVRTC_RGB2: return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGB4: return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; case PF_PVRTC_RGBA2: return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGBA4: return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; #endif case PF_R8G8B8: case PF_B8G8R8: case PF_X8B8G8R8: case PF_X8R8G8B8: case PF_A8R8G8B8: case PF_B8G8R8A8: if (!hwGamma) { return GL_RGBA; } case PF_A4L4: case PF_L16: case PF_A4R4G4B4: case PF_R3G3B2: case PF_A1R5G5B5: case PF_R5G6B5: case PF_B5G6R5: case PF_A2R10G10B10: case PF_A2B10G10R10: case PF_FLOAT16_R: case PF_FLOAT16_RGB: case PF_FLOAT16_GR: case PF_FLOAT16_RGBA: case PF_FLOAT32_R: case PF_FLOAT32_GR: case PF_FLOAT32_RGB: case PF_FLOAT32_RGBA: case PF_SHORT_RGBA: case PF_SHORT_RGB: case PF_SHORT_GR: case PF_DXT1: case PF_DXT3: case PF_DXT5: default: return 0; } } GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat, bool hwGamma) { GLenum format = getGLInternalFormat(mFormat, hwGamma); if (format == 0) { if (hwGamma) { // TODO not supported return 0; } else { return GL_RGBA; } } else { return format; } } PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt) { switch (fmt) { #if GL_IMG_texture_compression_pvrtc case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG: return PF_PVRTC_RGB2; case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: return PF_PVRTC_RGBA2; case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG: return PF_PVRTC_RGB4; case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: return PF_PVRTC_RGBA4; #endif case GL_LUMINANCE: return PF_L8; case GL_ALPHA: return PF_A8; case GL_LUMINANCE_ALPHA: return PF_BYTE_LA; case GL_RGB: return PF_X8R8G8B8; case GL_RGBA: #if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) // seems that in windows we need this value to get the right color return PF_X8B8G8R8; #endif return PF_A8R8G8B8; #ifdef GL_BGRA case GL_BGRA: #endif // return PF_X8B8G8R8; default: //TODO: not supported return PF_A8R8G8B8; }; } size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth, PixelFormat format) { size_t count = 0; do { if (width > 1) { width = width / 2; } if (height > 1) { height = height / 2; } if (depth > 1) { depth = depth / 2; } /* NOT needed, compressed formats will have mipmaps up to 1x1 if(PixelUtil::isValidExtent(width, height, depth, format)) count ++; else break; */ count++; } while (!(width == 1 && height == 1 && depth == 1)); return count; } size_t GLESPixelUtil::optionalPO2(size_t value) { const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES)) { return value; } else { return Bitwise::firstPO2From((uint32)value); } } PixelBox* GLESPixelUtil::convertToGLformat(const PixelBox &data, GLenum *outputFormat) { GLenum glFormat = GLESPixelUtil::getGLOriginFormat(data.format); if (glFormat != 0) { // format already supported return OGRE_NEW PixelBox(data); } PixelBox *converted = 0; if (data.format == PF_R8G8B8) { // Convert BGR -> RGB converted->format = PF_B8G8R8; *outputFormat = GL_RGB; converted = OGRE_NEW PixelBox(data); uint32 *data = (uint32 *) converted->data; for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++) { uint32 *color = data; *color = (*color & 0x000000ff) << 16 | (*color & 0x0000FF00) | (*color & 0x00FF0000) >> 16; data += 1; } } return converted; } } <commit_msg>Symbian port: Fixed texture color. It seems that PF_X8B8G8R8 is the format needed on both win32 and Symbian. Until now there were only two platforms for the gles 1.x render system - win32 and iPhone. There was an #if in the code (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) - to select the PF_X8B8G8R8 only if the platform is windows. It seems that Symbian also need that format - meaning that iPhone and not win32 is the special case. The #if was changed to reflect this.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLESPixelFormat.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreBitwise.h" namespace Ogre { GLenum GLESPixelUtil::getGLOriginFormat(PixelFormat mFormat) { switch (mFormat) { case PF_A8: return GL_ALPHA; case PF_L8: case PF_L16: case PF_FLOAT16_R: case PF_FLOAT32_R: return GL_LUMINANCE; case PF_BYTE_LA: case PF_SHORT_GR: case PF_FLOAT16_GR: case PF_FLOAT32_GR: return GL_LUMINANCE_ALPHA; // PVRTC compressed formats #if GL_IMG_texture_compression_pvrtc case PF_PVRTC_RGB2: return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGB4: return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; case PF_PVRTC_RGBA2: return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGBA4: return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; #endif case PF_R3G3B2: case PF_R5G6B5: case PF_FLOAT16_RGB: case PF_FLOAT32_RGB: case PF_SHORT_RGB: return GL_RGB; case PF_X8R8G8B8: case PF_A8R8G8B8: case PF_B8G8R8A8: case PF_A1R5G5B5: case PF_A4R4G4B4: case PF_A2R10G10B10: // This case in incorrect, swaps R & B channels // return GL_BGRA; case PF_X8B8G8R8: case PF_A8B8G8R8: case PF_A2B10G10R10: case PF_FLOAT16_RGBA: case PF_FLOAT32_RGBA: case PF_SHORT_RGBA: return GL_RGBA; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG // Formats are in native endian, so R8G8B8 on little endian is // BGR, on big endian it is RGB. case PF_R8G8B8: return GL_RGB; case PF_B8G8R8: return 0; #else case PF_R8G8B8: return 0; case PF_B8G8R8: return GL_RGB; #endif case PF_DXT1: case PF_DXT3: case PF_DXT5: case PF_B5G6R5: default: return 0; } } GLenum GLESPixelUtil::getGLOriginDataType(PixelFormat mFormat) { switch (mFormat) { case PF_A8: case PF_L8: case PF_R8G8B8: case PF_B8G8R8: case PF_BYTE_LA: return GL_UNSIGNED_BYTE; case PF_R5G6B5: case PF_B5G6R5: return GL_UNSIGNED_SHORT_5_6_5; case PF_L16: return GL_UNSIGNED_SHORT; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG case PF_X8B8G8R8: case PF_A8B8G8R8: return GL_UNSIGNED_INT_8_8_8_8_REV; case PF_X8R8G8B8: case PF_A8R8G8B8: return GL_UNSIGNED_INT_8_8_8_8_REV; case PF_B8G8R8A8: return GL_UNSIGNED_BYTE; case PF_R8G8B8A8: return GL_UNSIGNED_BYTE; #else case PF_X8B8G8R8: case PF_A8B8G8R8: case PF_X8R8G8B8: case PF_A8R8G8B8: return GL_UNSIGNED_BYTE; case PF_B8G8R8A8: case PF_R8G8B8A8: return 0; #endif case PF_FLOAT32_R: case PF_FLOAT32_GR: case PF_FLOAT32_RGB: case PF_FLOAT32_RGBA: return GL_FLOAT; case PF_SHORT_RGBA: case PF_SHORT_RGB: case PF_SHORT_GR: return GL_UNSIGNED_SHORT; case PF_A2R10G10B10: case PF_A2B10G10R10: case PF_FLOAT16_R: case PF_FLOAT16_GR: case PF_FLOAT16_RGB: case PF_FLOAT16_RGBA: case PF_R3G3B2: case PF_A1R5G5B5: case PF_A4R4G4B4: // TODO not supported default: return 0; } } GLenum GLESPixelUtil::getGLInternalFormat(PixelFormat fmt, bool hwGamma) { switch (fmt) { case PF_L8: return GL_LUMINANCE; case PF_A8: return GL_ALPHA; case PF_BYTE_LA: return GL_LUMINANCE_ALPHA; #if GL_IMG_texture_compression_pvrtc case PF_PVRTC_RGB2: return GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGB4: return GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; case PF_PVRTC_RGBA2: return GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; case PF_PVRTC_RGBA4: return GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; #endif case PF_R8G8B8: case PF_B8G8R8: case PF_X8B8G8R8: case PF_X8R8G8B8: case PF_A8R8G8B8: case PF_B8G8R8A8: if (!hwGamma) { return GL_RGBA; } case PF_A4L4: case PF_L16: case PF_A4R4G4B4: case PF_R3G3B2: case PF_A1R5G5B5: case PF_R5G6B5: case PF_B5G6R5: case PF_A2R10G10B10: case PF_A2B10G10R10: case PF_FLOAT16_R: case PF_FLOAT16_RGB: case PF_FLOAT16_GR: case PF_FLOAT16_RGBA: case PF_FLOAT32_R: case PF_FLOAT32_GR: case PF_FLOAT32_RGB: case PF_FLOAT32_RGBA: case PF_SHORT_RGBA: case PF_SHORT_RGB: case PF_SHORT_GR: case PF_DXT1: case PF_DXT3: case PF_DXT5: default: return 0; } } GLenum GLESPixelUtil::getClosestGLInternalFormat(PixelFormat mFormat, bool hwGamma) { GLenum format = getGLInternalFormat(mFormat, hwGamma); if (format == 0) { if (hwGamma) { // TODO not supported return 0; } else { return GL_RGBA; } } else { return format; } } PixelFormat GLESPixelUtil::getClosestOGREFormat(GLenum fmt) { switch (fmt) { #if GL_IMG_texture_compression_pvrtc case GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG: return PF_PVRTC_RGB2; case GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: return PF_PVRTC_RGBA2; case GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG: return PF_PVRTC_RGB4; case GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: return PF_PVRTC_RGBA4; #endif case GL_LUMINANCE: return PF_L8; case GL_ALPHA: return PF_A8; case GL_LUMINANCE_ALPHA: return PF_BYTE_LA; case GL_RGB: return PF_X8R8G8B8; case GL_RGBA: #if (OGRE_PLATFORM == OGRE_PLATFORM_IPHONE) // seems that in iPhone we need this value to get the right color return PF_A8R8G8B8; #else return PF_X8B8G8R8; #endif #ifdef GL_BGRA case GL_BGRA: #endif // return PF_X8B8G8R8; default: //TODO: not supported return PF_A8R8G8B8; }; } size_t GLESPixelUtil::getMaxMipmaps(size_t width, size_t height, size_t depth, PixelFormat format) { size_t count = 0; do { if (width > 1) { width = width / 2; } if (height > 1) { height = height / 2; } if (depth > 1) { depth = depth / 2; } /* NOT needed, compressed formats will have mipmaps up to 1x1 if(PixelUtil::isValidExtent(width, height, depth, format)) count ++; else break; */ count++; } while (!(width == 1 && height == 1 && depth == 1)); return count; } size_t GLESPixelUtil::optionalPO2(size_t value) { const RenderSystemCapabilities *caps = Root::getSingleton().getRenderSystem()->getCapabilities(); if (caps->hasCapability(RSC_NON_POWER_OF_2_TEXTURES)) { return value; } else { return Bitwise::firstPO2From((uint32)value); } } PixelBox* GLESPixelUtil::convertToGLformat(const PixelBox &data, GLenum *outputFormat) { GLenum glFormat = GLESPixelUtil::getGLOriginFormat(data.format); if (glFormat != 0) { // format already supported return OGRE_NEW PixelBox(data); } PixelBox *converted = 0; if (data.format == PF_R8G8B8) { // Convert BGR -> RGB converted->format = PF_B8G8R8; *outputFormat = GL_RGB; converted = OGRE_NEW PixelBox(data); uint32 *data = (uint32 *) converted->data; for (uint i = 0; i < converted->getWidth() * converted->getHeight(); i++) { uint32 *color = data; *color = (*color & 0x000000ff) << 16 | (*color & 0x0000FF00) | (*color & 0x00FF0000) >> 16; data += 1; } } return converted; } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreRoot.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreEGLSupport.h" #include "OgreEGLWindow.h" #include "OgreEGLRenderTexture.h" namespace Ogre { EGLSupport::EGLSupport() : mGLDisplay(0), mNativeDisplay(0), mRandr(false) { } EGLSupport::~EGLSupport() { } void EGLSupport::addConfig(void) { ConfigOption optFullScreen; ConfigOption optVideoMode; ConfigOption optDisplayFrequency; ConfigOption optFSAA; ConfigOption optRTTMode; optFullScreen.name = "Full Screen"; optFullScreen.immutable = false; optVideoMode.name = "Video Mode"; optVideoMode.immutable = false; optDisplayFrequency.name = "Display Frequency"; optDisplayFrequency.immutable = false; optFSAA.name = "FSAA"; optFSAA.immutable = false; optRTTMode.name = "RTT Preferred Mode"; optRTTMode.immutable = false; optFullScreen.possibleValues.push_back("No"); optFullScreen.possibleValues.push_back("Yes"); optFullScreen.currentValue = optFullScreen.possibleValues[1]; VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); optVideoMode.possibleValues.push_back(mode); } removeDuplicates(optVideoMode.possibleValues); optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4); refreshConfig(); if (!mSampleLevels.empty()) { StringVector::const_iterator value = mSampleLevels.begin(); StringVector::const_iterator end = mSampleLevels.end(); for (; value != end; value++) { optFSAA.possibleValues.push_back(*value); } optFSAA.currentValue = optFSAA.possibleValues[0]; } optRTTMode.possibleValues.push_back("Copy"); optRTTMode.currentValue = optRTTMode.possibleValues[0]; mOptions[optFullScreen.name] = optFullScreen; mOptions[optVideoMode.name] = optVideoMode; mOptions[optDisplayFrequency.name] = optDisplayFrequency; mOptions[optFSAA.name] = optFSAA; mOptions[optRTTMode.name] = optRTTMode; refreshConfig(); } void EGLSupport::refreshConfig(void) { ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode"); ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency"); if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end()) { optDisplayFrequency->second.possibleValues.clear(); VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); if (mode == optVideoMode->second.currentValue) { String frequency = StringConverter::toString(value->second) + " MHz"; optDisplayFrequency->second.possibleValues.push_back(frequency); } } if (!optDisplayFrequency->second.possibleValues.empty()) { optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0]; } else { optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4); optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " MHz"; } } } void EGLSupport::setConfigOption(const String &name, const String &value) { GLES2Support::setConfigOption(name, value); if (name == "Video Mode") { refreshConfig(); } } String EGLSupport::validateConfig(void) { // TODO return StringUtil::BLANK; } EGLDisplay EGLSupport::getGLDisplay(void) { EGLint major = 0, minor = 0; mGLDisplay = eglGetDisplay(mNativeDisplay); EGL_CHECK_ERROR if(mGLDisplay == EGL_NO_DISPLAY) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open EGLDisplay " + getDisplayName(), "EGLSupport::getGLDisplay"); } if (eglInitialize(mGLDisplay, &major, &minor) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t initialize EGLDisplay ", "EGLSupport::getGLDisplay"); } EGL_CHECK_ERROR return mGLDisplay; } String EGLSupport::getDisplayName(void) { return "todo"; } EGLConfig* EGLSupport::chooseGLConfig(const GLint *attribList, GLint *nElements) { EGLConfig *configs; if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, GLint attribute, GLint *value) { EGLBoolean status; status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); EGL_CHECK_ERROR return status; } void* EGLSupport::getProcAddress(const Ogre::String& name) { return (void*)eglGetProcAddress((const char*) name.c_str()); } ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) { ::EGLConfig glConfig = 0; if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context", __FUNCTION__); return 0; } EGL_CHECK_ERROR return glConfig; } ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable, unsigned int *w, unsigned int *h) { ::EGLConfig glConfig = 0; if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from drawable", __FUNCTION__); return 0; } EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w); EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h); EGL_CHECK_ERROR return glConfig; } //------------------------------------------------------------------------ // A helper class for the implementation of selectFBConfig //------------------------------------------------------------------------ class GLConfigAttribs { public: GLConfigAttribs(const int* attribs) { fields[EGL_CONFIG_CAVEAT] = EGL_NONE; for (int i = 0; attribs[2*i] != EGL_NONE; i++) { fields[attribs[2*i]] = attribs[2*i+1]; } } void load(EGLSupport* const glSupport, EGLConfig glConfig) { std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { it->second = EGL_NONE; glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); } } bool operator>(GLConfigAttribs& alternative) { // Caveats are best avoided, but might be needed for anti-aliasing if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) { if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) { return false; } if (fields.find(EGL_SAMPLES) != fields.end() && fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) { return false; } } std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { if (it->first != EGL_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) { return true; } } return false; } std::map<int,int> fields; }; ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) { EGLConfig *glConfigs; EGLConfig glConfig = 0; int config, nConfigs = 0; glConfigs = chooseGLConfig(minAttribs, &nConfigs); if (!nConfigs) { return 0; } glConfig = glConfigs[0]; if (maxAttribs) { GLConfigAttribs maximum(maxAttribs); GLConfigAttribs best(maxAttribs); GLConfigAttribs candidate(maxAttribs); best.load(this, glConfig); for (config = 1; config < nConfigs; config++) { candidate.load(this, glConfigs[config]); if (candidate > maximum) { continue; } if (candidate > best) { glConfig = glConfigs[config]; best.load(this, glConfig); } } } free(glConfigs); return glConfig; } void EGLSupport::switchMode(void) { return switchMode(mOriginalMode.first.first, mOriginalMode.first.second, mOriginalMode.second); } RenderWindow* EGLSupport::createWindow(bool autoCreateWindow, GLES2RenderSystem* renderSystem, const String& windowTitle) { RenderWindow *window = 0; if (autoCreateWindow) { ConfigOptionMap::iterator opt; ConfigOptionMap::iterator end = mOptions.end(); NameValuePairList miscParams; bool fullscreen = false; uint w = 640, h = 480; if ((opt = mOptions.find("Full Screen")) != end) { fullscreen = (opt->second.currentValue == "Yes"); } if ((opt = mOptions.find("Display Frequency")) != end) { miscParams["displayFrequency"] = opt->second.currentValue; } if ((opt = mOptions.find("Video Mode")) != end) { String val = opt->second.currentValue; String::size_type pos = val.find('x'); if (pos != String::npos) { w = StringConverter::parseUnsignedInt(val.substr(0, pos)); h = StringConverter::parseUnsignedInt(val.substr(pos + 1)); } } if ((opt = mOptions.find("FSAA")) != end) { miscParams["FSAA"] = opt->second.currentValue; } window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams); } return window; } ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const { EGLint contextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE }; ::EGLContext context = ((::EGLContext) 0); if (eglDisplay == ((EGLDisplay) 0)) { context = eglCreateContext(mGLDisplay, glconfig, shareList, contextAttrs); EGL_CHECK_ERROR } else { context = eglCreateContext(eglDisplay, glconfig, 0, contextAttrs); EGL_CHECK_ERROR } if (context == ((::EGLContext) 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to create New context", __FUNCTION__); return 0; } return context; } void EGLSupport::start() { } void EGLSupport::stop() { } void EGLSupport::setGLDisplay( EGLDisplay val ) { mGLDisplay = val; } } <commit_msg>GLES2: When running on Linux, use FBO's for RTT's by default.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreRoot.h" #include "OgreGLES2Prerequisites.h" #include "OgreGLES2RenderSystem.h" #include "OgreEGLSupport.h" #include "OgreEGLWindow.h" #include "OgreEGLRenderTexture.h" namespace Ogre { EGLSupport::EGLSupport() : mGLDisplay(0), mNativeDisplay(0), mRandr(false) { } EGLSupport::~EGLSupport() { } void EGLSupport::addConfig(void) { ConfigOption optFullScreen; ConfigOption optVideoMode; ConfigOption optDisplayFrequency; ConfigOption optFSAA; ConfigOption optRTTMode; optFullScreen.name = "Full Screen"; optFullScreen.immutable = false; optVideoMode.name = "Video Mode"; optVideoMode.immutable = false; optDisplayFrequency.name = "Display Frequency"; optDisplayFrequency.immutable = false; optFSAA.name = "FSAA"; optFSAA.immutable = false; optRTTMode.name = "RTT Preferred Mode"; optRTTMode.possibleValues.push_back("FBO"); optRTTMode.possibleValues.push_back("Copy"); optRTTMode.currentValue = "FBO"; optRTTMode.immutable = false; optFullScreen.possibleValues.push_back("No"); optFullScreen.possibleValues.push_back("Yes"); optFullScreen.currentValue = optFullScreen.possibleValues[1]; VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); optVideoMode.possibleValues.push_back(mode); } removeDuplicates(optVideoMode.possibleValues); optVideoMode.currentValue = StringConverter::toString(mCurrentMode.first.first,4) + " x " + StringConverter::toString(mCurrentMode.first.second,4); refreshConfig(); if (!mSampleLevels.empty()) { StringVector::const_iterator value = mSampleLevels.begin(); StringVector::const_iterator end = mSampleLevels.end(); for (; value != end; value++) { optFSAA.possibleValues.push_back(*value); } optFSAA.currentValue = optFSAA.possibleValues[0]; } optRTTMode.currentValue = optRTTMode.possibleValues[0]; mOptions[optFullScreen.name] = optFullScreen; mOptions[optVideoMode.name] = optVideoMode; mOptions[optDisplayFrequency.name] = optDisplayFrequency; mOptions[optFSAA.name] = optFSAA; mOptions[optRTTMode.name] = optRTTMode; refreshConfig(); } void EGLSupport::refreshConfig(void) { ConfigOptionMap::iterator optVideoMode = mOptions.find("Video Mode"); ConfigOptionMap::iterator optDisplayFrequency = mOptions.find("Display Frequency"); if (optVideoMode != mOptions.end() && optDisplayFrequency != mOptions.end()) { optDisplayFrequency->second.possibleValues.clear(); VideoModes::const_iterator value = mVideoModes.begin(); VideoModes::const_iterator end = mVideoModes.end(); for (; value != end; value++) { String mode = StringConverter::toString(value->first.first,4) + " x " + StringConverter::toString(value->first.second,4); if (mode == optVideoMode->second.currentValue) { String frequency = StringConverter::toString(value->second) + " MHz"; optDisplayFrequency->second.possibleValues.push_back(frequency); } } if (!optDisplayFrequency->second.possibleValues.empty()) { optDisplayFrequency->second.currentValue = optDisplayFrequency->second.possibleValues[0]; } else { optVideoMode->second.currentValue = StringConverter::toString(mVideoModes[0].first.first,4) + " x " + StringConverter::toString(mVideoModes[0].first.second,4); optDisplayFrequency->second.currentValue = StringConverter::toString(mVideoModes[0].second) + " MHz"; } } } void EGLSupport::setConfigOption(const String &name, const String &value) { GLES2Support::setConfigOption(name, value); if (name == "Video Mode") { refreshConfig(); } } String EGLSupport::validateConfig(void) { // TODO return StringUtil::BLANK; } EGLDisplay EGLSupport::getGLDisplay(void) { EGLint major = 0, minor = 0; mGLDisplay = eglGetDisplay(mNativeDisplay); EGL_CHECK_ERROR if(mGLDisplay == EGL_NO_DISPLAY) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t open EGLDisplay " + getDisplayName(), "EGLSupport::getGLDisplay"); } if (eglInitialize(mGLDisplay, &major, &minor) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t initialize EGLDisplay ", "EGLSupport::getGLDisplay"); } EGL_CHECK_ERROR return mGLDisplay; } String EGLSupport::getDisplayName(void) { return "todo"; } EGLConfig* EGLSupport::chooseGLConfig(const GLint *attribList, GLint *nElements) { EGLConfig *configs; if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config", __FUNCTION__); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, GLint attribute, GLint *value) { EGLBoolean status; status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); EGL_CHECK_ERROR return status; } void* EGLSupport::getProcAddress(const Ogre::String& name) { return (void*)eglGetProcAddress((const char*) name.c_str()); } ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) { ::EGLConfig glConfig = 0; if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context", __FUNCTION__); return 0; } EGL_CHECK_ERROR return glConfig; } ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable, unsigned int *w, unsigned int *h) { ::EGLConfig glConfig = 0; if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, (EGLint *) &glConfig) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from drawable", __FUNCTION__); return 0; } EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w); EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h); EGL_CHECK_ERROR return glConfig; } //------------------------------------------------------------------------ // A helper class for the implementation of selectFBConfig //------------------------------------------------------------------------ class GLConfigAttribs { public: GLConfigAttribs(const int* attribs) { fields[EGL_CONFIG_CAVEAT] = EGL_NONE; for (int i = 0; attribs[2*i] != EGL_NONE; i++) { fields[attribs[2*i]] = attribs[2*i+1]; } } void load(EGLSupport* const glSupport, EGLConfig glConfig) { std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { it->second = EGL_NONE; glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); } } bool operator>(GLConfigAttribs& alternative) { // Caveats are best avoided, but might be needed for anti-aliasing if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) { if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) { return false; } if (fields.find(EGL_SAMPLES) != fields.end() && fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) { return false; } } std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { if (it->first != EGL_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) { return true; } } return false; } std::map<int,int> fields; }; ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) { EGLConfig *glConfigs; EGLConfig glConfig = 0; int config, nConfigs = 0; glConfigs = chooseGLConfig(minAttribs, &nConfigs); if (!nConfigs) { return 0; } glConfig = glConfigs[0]; if (maxAttribs) { GLConfigAttribs maximum(maxAttribs); GLConfigAttribs best(maxAttribs); GLConfigAttribs candidate(maxAttribs); best.load(this, glConfig); for (config = 1; config < nConfigs; config++) { candidate.load(this, glConfigs[config]); if (candidate > maximum) { continue; } if (candidate > best) { glConfig = glConfigs[config]; best.load(this, glConfig); } } } free(glConfigs); return glConfig; } void EGLSupport::switchMode(void) { return switchMode(mOriginalMode.first.first, mOriginalMode.first.second, mOriginalMode.second); } RenderWindow* EGLSupport::createWindow(bool autoCreateWindow, GLES2RenderSystem* renderSystem, const String& windowTitle) { RenderWindow *window = 0; if (autoCreateWindow) { ConfigOptionMap::iterator opt; ConfigOptionMap::iterator end = mOptions.end(); NameValuePairList miscParams; bool fullscreen = false; uint w = 640, h = 480; if ((opt = mOptions.find("Full Screen")) != end) { fullscreen = (opt->second.currentValue == "Yes"); } if ((opt = mOptions.find("Display Frequency")) != end) { miscParams["displayFrequency"] = opt->second.currentValue; } if ((opt = mOptions.find("Video Mode")) != end) { String val = opt->second.currentValue; String::size_type pos = val.find('x'); if (pos != String::npos) { w = StringConverter::parseUnsignedInt(val.substr(0, pos)); h = StringConverter::parseUnsignedInt(val.substr(pos + 1)); } } if ((opt = mOptions.find("FSAA")) != end) { miscParams["FSAA"] = opt->second.currentValue; } window = renderSystem->_createRenderWindow(windowTitle, w, h, fullscreen, &miscParams); } return window; } ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const { EGLint contextAttrs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE }; ::EGLContext context = ((::EGLContext) 0); if (eglDisplay == ((EGLDisplay) 0)) { context = eglCreateContext(mGLDisplay, glconfig, shareList, contextAttrs); EGL_CHECK_ERROR } else { context = eglCreateContext(eglDisplay, glconfig, 0, contextAttrs); EGL_CHECK_ERROR } if (context == ((::EGLContext) 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to create New context", __FUNCTION__); return 0; } return context; } void EGLSupport::start() { } void EGLSupport::stop() { } void EGLSupport::setGLDisplay( EGLDisplay val ) { mGLDisplay = val; } } <|endoftext|>