text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) 2012 Holger Schletz <[email protected]> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QDebug> #include <QFileInfo> #include "adobereader.h" #include "application.h" #include "downloader.h" AdobeReader::AdobeReader() : Package("Adobe Reader", "10.1.3") { } void AdobeReader::build(NSIS *installer, Version version) { isError = false; download(version); if (!isError) { // Compose options for msiexec command line QStringList msiOptions; if (getConfig("Suppress reboot", false).toBool()) { msiOptions << "REBOOT=ReallySuppress"; } if (getConfig("Accept EULA", false).toBool()) { msiOptions << "EULA_ACCEPT=YES"; } if (!getConfig("Desktop shortcut", true).toBool()) { msiOptions << "DISABLEDESKTOPSHORTCUT=1"; } if (getConfig("Set default PDF viewer", false).toBool()) { msiOptions << "IW_DEFAULT_VERB=READ"; msiOptions << "LEAVE_PDFOWNERSHIP=NO"; } else { msiOptions << "LEAVE_PDFOWNERSHIP=YES"; } if (!getConfig("Install synchronizer", true).toBool()) { msiOptions << "SYNCHRONIZER=NO"; } if (!getConfig("Use automatic update", true).toBool()) { msiOptions << "DISABLE_ARM_SERVICE_INSTALL=1"; } qDebug() << "MSI options:" << msiOptions; // Compose main installation routine Version msiVersion(version.truncate(2).pad(2)); QString src(loadResource(":NSIS/AdobeReader/main.nsh")); src.replace("${VersionMajor}", msiVersion.part(1)); src.replace("${VersionMinor}", msiVersion.part(2)); src.replace("${MsiFile}", QFileInfo(msiFile).fileName()); src.replace("${MsiOptions}", msiOptions.join(" ")); // Compose patch installation if necessary QString header; if (!mspFiles.isEmpty()) { header = loadResource(":NSIS/AdobeReader/header.nsh"); QPair<Version, QString> mspFile; foreach (mspFile, mspFiles) { src += loadResource(":NSIS/AdobeReader/installpatch.nsh") .replace("${MspVersion}", mspFile.first) .replace("${MspFile}", QFileInfo(mspFile.second).fileName()) ; } } // Add code to disable updater if requested if (!getConfig("Use automatic update", true).toBool()) { src += loadResource(":NSIS/AdobeReader/disableupdater.nsh"); } installer->build( objectName(), getOutputFile(), NSIS::Zlib, 300, browsers() << "AcroRd32.exe", tempFiles, src, header ); } cleanup(); } void AdobeReader::download(Version version) { // MSI version always has 2 parts (10.0, 10.1...) Version msiVersion; if (version.part(1).toInt() >= 11) { msiVersion = version.pad(2).pad(3, "00"); } else { msiVersion = version.truncate(2).pad(2); } qDebug() << "MSI version" << msiVersion.toString(); QString language(getConfig("Language", "en_US").toString()); qDebug()<<"language:"<<language; // Download MSI file. QString msiUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/%4/AdbeRdr%3_%4.msi"); msiFile = Downloader::get( msiUrl .arg(msiVersion.truncate(2).replace(2, "x")) .arg(msiVersion.pad(3)) .arg(msiVersion.pad(3).stripDots()) .arg(language), Application::getTmpDir() ); if (msiFile.isEmpty()) { isError = true; return; } tempFiles << msiFile; // If version has 3 parts, download MSP file. if (version.numParts() < 3) { return; } QString mspUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/misc/AdbeRdrUpd%3.msp"); QString mspFile = Downloader::get( mspUrl .arg(msiVersion.replace(2, "x")) .arg(version) .arg(version.stripDots()), Application::getTmpDir() ); if (mspFile.isEmpty()) { isError = true; } else { // In the past, there have been releases where more than 1 MSP was // required for a fresh up-to-date installation. For this reason, // the patches are stored in a list. // The dependency tracking is not implemented yet (it will should it // ever become necessary again), but the rest of the code is already // prepared for multiple patches. mspFiles << qMakePair(version, mspFile); tempFiles << mspFile; } } <commit_msg>Fixed bugs in Adobe Reader download.<commit_after>/* * Copyright (c) 2012 Holger Schletz <[email protected]> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QDebug> #include <QFileInfo> #include "adobereader.h" #include "application.h" #include "downloader.h" AdobeReader::AdobeReader() : Package("Adobe Reader", "10.1.3") { } void AdobeReader::build(NSIS *installer, Version version) { isError = false; download(version); if (!isError) { // Compose options for msiexec command line QStringList msiOptions; if (getConfig("Suppress reboot", false).toBool()) { msiOptions << "REBOOT=ReallySuppress"; } if (getConfig("Accept EULA", false).toBool()) { msiOptions << "EULA_ACCEPT=YES"; } if (!getConfig("Desktop shortcut", true).toBool()) { msiOptions << "DISABLEDESKTOPSHORTCUT=1"; } if (getConfig("Set default PDF viewer", false).toBool()) { msiOptions << "IW_DEFAULT_VERB=READ"; msiOptions << "LEAVE_PDFOWNERSHIP=NO"; } else { msiOptions << "LEAVE_PDFOWNERSHIP=YES"; } if (!getConfig("Install synchronizer", true).toBool()) { msiOptions << "SYNCHRONIZER=NO"; } if (!getConfig("Use automatic update", true).toBool()) { msiOptions << "DISABLE_ARM_SERVICE_INSTALL=1"; } qDebug() << "MSI options:" << msiOptions; // Compose main installation routine Version msiVersion(version.truncate(2).pad(2)); QString src(loadResource(":NSIS/AdobeReader/main.nsh")); src.replace("${VersionMajor}", msiVersion.part(1)); src.replace("${VersionMinor}", msiVersion.part(2)); src.replace("${MsiFile}", QFileInfo(msiFile).fileName()); src.replace("${MsiOptions}", msiOptions.join(" ")); // Compose patch installation if necessary QString header; if (!mspFiles.isEmpty()) { header = loadResource(":NSIS/AdobeReader/header.nsh"); QPair<Version, QString> mspFile; foreach (mspFile, mspFiles) { src += loadResource(":NSIS/AdobeReader/installpatch.nsh") .replace("${MspVersion}", mspFile.first) .replace("${MspFile}", QFileInfo(mspFile.second).fileName()) ; } } // Add code to disable updater if requested if (!getConfig("Use automatic update", true).toBool()) { src += loadResource(":NSIS/AdobeReader/disableupdater.nsh"); } installer->build( objectName(), getOutputFile(), NSIS::Zlib, 300, browsers() << "AcroRd32.exe", tempFiles, src, header ); } cleanup(); } void AdobeReader::download(Version version) { // MSI version always has 2 parts (10.0, 10.1...) Version msiVersion; if (version.part(1).toInt() >= 11) { msiVersion = version.truncate(2).pad(3, "00"); } else { msiVersion = version.truncate(2).pad(3); } qDebug() << "MSI version" << msiVersion.toString(); QString language(getConfig("Language", "en_US").toString()); qDebug()<<"language:"<<language; // Download MSI file. QString msiUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/%4/AdbeRdr%3_%4.msi"); msiFile = Downloader::get( msiUrl .arg(msiVersion.truncate(2).replace(2, "x")) .arg(msiVersion.pad(3)) .arg(msiVersion.stripDots()) .arg(language), Application::getTmpDir() ); if (msiFile.isEmpty()) { isError = true; return; } tempFiles << msiFile; // If version has 3 parts, download MSP file. if (version.numParts() < 3) { return; } QString mspUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/misc/AdbeRdrUpd%3.msp"); QString mspFile = Downloader::get( mspUrl .arg(msiVersion.truncate(2).replace(2, "x")) .arg(version) .arg(version.stripDots()), Application::getTmpDir() ); if (mspFile.isEmpty()) { isError = true; } else { // In the past, there have been releases where more than 1 MSP was // required for a fresh up-to-date installation. For this reason, // the patches are stored in a list. // The dependency tracking is not implemented yet (it will should it // ever become necessary again), but the rest of the code is already // prepared for multiple patches. mspFiles << qMakePair(version, mspFile); tempFiles << mspFile; } } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/cimg/cimgutils.h> #include <inviwo/core/datastructures/image/layerramprecision.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/io/datawriter.h> #include <algorithm> #include <warn/push> #include <warn/ignore/all> #define cimg_verbosity 0 //Disable all cimg output #define cimg_display 0 // Do not use any gui stuff #include <modules/cimg/ext/cimg/CImg.h> #include <warn/pop> #include <warn/push> #include <warn/ignore/switch-enum> #include <warn/ignore/conversion> #if (_MSC_VER) #pragma warning(disable : 4146) #pragma warning(disable : 4197) #pragma warning(disable : 4297) #pragma warning(disable : 4267) #pragma warning(disable : 4293) #endif // Added in Cimg.h below struct type<float>... /*#include <limits> #include <half/half.hpp> template<> struct type < half_float::half > { static const char* string() { static const char *const s = "half"; return s; } static bool is_float() { return true; } static bool is_inf(const half_float::half val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<half_float::half>::min() || val>cimg::type<half_float::half>::max()); #endif } static bool is_nan(const half_float::half val) { #ifdef isnan return (bool)isnan(val); #else return !(val == val); #endif } static half_float::half min() { return std::numeric_limits<half_float::half>::min(); } static half_float::half max() { return std::numeric_limits<half_float::half>::max(); } static half_float::half inf() { return (half_float::half)cimg::type<double>::inf(); } static half_float::half nan() { return (half_float::half)cimg::type<double>::nan(); } static half_float::half cut(const double val) { return val<(double)min() ? min() : val>(double)max() ? max() : (half_float::half)val; } static const char* format() { return "%.16g"; } static double format(const half_float::half val) { return (double)val; } }; */ using namespace cimg_library; namespace inviwo { std::unordered_map<std::string, DataFormatId> extToBaseTypeMap_ = { {"png", DataFormatId::UInt8}, {"jpg", DataFormatId::UInt8}, {"jpeg", DataFormatId::UInt8}, {"bmp", DataFormatId::UInt8}, {"exr", DataFormatId::Float32}, {"hdr", DataFormatId::Float32}}; ////////////////////// Templates /////////////////////////////////////////////////// // Single channel images template <typename T> struct CImgToVoidConvert { static void* convert(void* dst, CImg<T>* img) { // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format // (RRRRGGGGBBBB). // Permute from planer to interleaved format, does we need to specify cxyz as input instead // of xyzc if (img->spectrum() > 1) { img->permute_axes("cxyz"); } if (!dst) { T* dstAlloc = new T[img->size()]; dst = static_cast<void*>(dstAlloc); } const void* src = static_cast<const void*>(img->data()); std::memcpy(dst, src, img->size() * sizeof(T)); return dst; } }; // Single channel images template <typename T> struct LayerToCImg { static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) { // Single channel means we can do xyzc, as no permutation is needed auto img = util::make_unique<CImg<T>>(static_cast<const T*>(inputLayerRAM->getData()), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, 1, false); return img; } }; // Multiple channel images template <typename T, template <typename, glm::precision> class G> struct LayerToCImg<G<T, glm::defaultp>> { static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) { auto dataFormat = inputLayerRAM->getDataFormat(); auto typedDataPtr = static_cast<const G<T, glm::defaultp>*>(inputLayerRAM->getData()); // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format // (RRRRGGGGBBBB). // Permute from interleaved to planer format, does we need to specify yzcx as input instead // of cxyz auto img = util::make_unique<CImg<T>>( glm::value_ptr(*typedDataPtr), dataFormat->getComponents(), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, false); if (permute) img->permute_axes("yzcx"); return img; } }; struct CImgNormalizedLayerDispatcher { using type = std::unique_ptr<std::vector<unsigned char>>; template <typename T> std::unique_ptr<std::vector<unsigned char>> dispatch(const LayerRAM* inputLayer) { auto img = LayerToCImg<typename T::type>::convert(inputLayer, false); CImg<unsigned char> normalizedImg = img->get_normalize(0, 255); normalizedImg.mirror('z'); auto data = util::make_unique<std::vector<unsigned char>>( &normalizedImg[0], &normalizedImg[normalizedImg.size()]); return data; } }; struct CImgLoadLayerDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, uvec2& dimensions, DataFormatId& formatId, const DataFormatBase* dataFormat, bool rescaleToDim) { using P = typename T::primitive; CImg<P> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); if (rescaleToDim) { img.resize(dimensions.x, dimensions.y, -100, -100, 3); } else { dimensions = uvec2(img.width(), img.height()); } auto loadedDataFormat = DataFormatBase::get( dataFormat->getNumericType(), components, sizeof(P) * 8); if (loadedDataFormat) { formatId = loadedDataFormat->getId(); } else { throw Exception("CImgLoadLayerDispatcher, could not find proper data type"); } // Image is up-side-down img.mirror('y'); return CImgToVoidConvert<P>::convert(dst, &img); } }; struct CImgSaveLayerDispatcher { using type = void; template <typename T> void dispatch(const char* filePath, const LayerRAM* inputLayer) { auto img = LayerToCImg<typename T::type>::convert(inputLayer); // Should rescale values based on output format i.e. PNG/JPG is 0-255, HDR different. const DataFormatBase* outFormat = DataFloat32::get(); std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { outFormat = DataFormatBase::get(extToBaseTypeMap_[fileExtension]); } // Image is up-side-down img->mirror('y'); const DataFormatBase* inFormat = inputLayer->getDataFormat(); double inMin = inFormat->getMin(); double inMax = inFormat->getMax(); double outMin = outFormat->getMin(); double outMax = outFormat->getMax(); // Special treatment for float data types: // For float input images, we assume that the range is [0,1] (which is the same as rendered // in a Canvas) // For float output images, we normalize to [0,1] // Note that no normalization is performed if both input and output are float images if (inFormat->getNumericType() == NumericType::Float) { inMin = 0.0; inMax = 1.0; } if (outFormat->getNumericType() == NumericType::Float) { outMin = 0.0; outMax = 1.0; } // The image values should be rescaled if the ranges of the input and output are different if (inMin != outMin || inMax != outMax) { typename T::primitive* data = img->data(); double scale = (outMax - outMin) / (inMax - inMin); for (size_t i = 0; i < img->size(); i++) { auto dataValue = glm::clamp(static_cast<double>(data[i]), inMin, inMax); data[i] = static_cast<typename T::primitive>((dataValue - inMin) * scale + outMin); } } try { img->save(filePath); } catch (CImgIOException& e) { throw DataWriterException("Failed to save image to: " + std::string(filePath), IvwContext); } } }; struct CImgRescaleLayerDispatcher { using type = void*; template <typename T> void* dispatch(const LayerRAM* inputLayerRAM, uvec2 dst_dim) { auto img = LayerToCImg<typename T::type>::convert(inputLayerRAM); img->resize(dst_dim.x, dst_dim.y, -100, -100, 3); return CImgToVoidConvert<typename T::primitive>::convert(nullptr, img.get()); } }; struct CImgLoadVolumeDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, size3_t& dimensions, DataFormatId& formatId, const DataFormatBase* dataFormat) { CImg<typename T::primitive> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); dimensions = size3_t(img.width(), img.height(), img.depth()); const DataFormatBase* loadedDataFormat = DataFormatBase::get( dataFormat->getNumericType(), components, sizeof(typename T::primitive) * 8); if (loadedDataFormat) formatId = loadedDataFormat->getId(); else throw Exception("CImgLoadVolumeDispatcher, could not find proper data type"); // Image is up-side-down img.mirror('y'); return CImgToVoidConvert<typename T::primitive>::convert(dst, &img); } }; ////////////////////// CImgUtils /////////////////////////////////////////////////// void* CImgUtils::loadLayerData(void* dst, const std::string& filePath, uvec2& dimensions, DataFormatId& formatId, bool rescaleToDim) { std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatId::Float32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadLayerDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat, rescaleToDim); } void* CImgUtils::loadVolumeData(void* dst, const std::string& filePath, size3_t& dimensions, DataFormatId& formatId) { std::string fileExtension = filesystem::getFileExtension(filePath); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatId::Float32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadVolumeDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat); } void CImgUtils::saveLayer(const std::string& filePath, const Layer* inputLayer) { CImgSaveLayerDispatcher disp; const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); inputLayer->getDataFormat()->dispatch(disp, filePath.c_str(), inputLayerRam); } std::unique_ptr<std::vector<unsigned char>> CImgUtils::saveLayerToBuffer(std::string& fileType, const Layer* inputLayer) { const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); fileType = "raw"; // Can only produce raw output CImgNormalizedLayerDispatcher disp; return inputLayer->getDataFormat()->dispatch(disp, inputLayerRam); } void* CImgUtils::rescaleLayer(const Layer* inputLayer, uvec2 dst_dim) { const LayerRAM* layerRam = inputLayer->getRepresentation<LayerRAM>(); return rescaleLayerRAM(layerRam, dst_dim); } void* CImgUtils::rescaleLayerRAM(const LayerRAM* srcLayerRam, uvec2 dst_dim) { CImgRescaleLayerDispatcher disp; return srcLayerRam->getDataFormat()->dispatch(disp, srcLayerRam, dst_dim); } } // namespace #include <warn/pop> <commit_msg>CIMG: Use of lower case for file extensions, if loading an image with JPG as file extension it did not find a the default one (eg Float32) which produced incorrect results.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/cimg/cimgutils.h> #include <inviwo/core/datastructures/image/layerramprecision.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/io/datawriter.h> #include <algorithm> #include <warn/push> #include <warn/ignore/all> #define cimg_verbosity 0 //Disable all cimg output #define cimg_display 0 // Do not use any gui stuff #include <modules/cimg/ext/cimg/CImg.h> #include <warn/pop> #include <warn/push> #include <warn/ignore/switch-enum> #include <warn/ignore/conversion> #if (_MSC_VER) #pragma warning(disable : 4146) #pragma warning(disable : 4197) #pragma warning(disable : 4297) #pragma warning(disable : 4267) #pragma warning(disable : 4293) #endif // Added in Cimg.h below struct type<float>... /*#include <limits> #include <half/half.hpp> template<> struct type < half_float::half > { static const char* string() { static const char *const s = "half"; return s; } static bool is_float() { return true; } static bool is_inf(const half_float::half val) { #ifdef isinf return (bool)isinf(val); #else return !is_nan(val) && (val<cimg::type<half_float::half>::min() || val>cimg::type<half_float::half>::max()); #endif } static bool is_nan(const half_float::half val) { #ifdef isnan return (bool)isnan(val); #else return !(val == val); #endif } static half_float::half min() { return std::numeric_limits<half_float::half>::min(); } static half_float::half max() { return std::numeric_limits<half_float::half>::max(); } static half_float::half inf() { return (half_float::half)cimg::type<double>::inf(); } static half_float::half nan() { return (half_float::half)cimg::type<double>::nan(); } static half_float::half cut(const double val) { return val<(double)min() ? min() : val>(double)max() ? max() : (half_float::half)val; } static const char* format() { return "%.16g"; } static double format(const half_float::half val) { return (double)val; } }; */ using namespace cimg_library; namespace inviwo { std::unordered_map<std::string, DataFormatId> extToBaseTypeMap_ = { {"png", DataFormatId::UInt8}, {"jpg", DataFormatId::UInt8}, {"jpeg", DataFormatId::UInt8}, {"bmp", DataFormatId::UInt8}, {"exr", DataFormatId::Float32}, {"hdr", DataFormatId::Float32}}; ////////////////////// Templates /////////////////////////////////////////////////// // Single channel images template <typename T> struct CImgToVoidConvert { static void* convert(void* dst, CImg<T>* img) { // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format // (RRRRGGGGBBBB). // Permute from planer to interleaved format, does we need to specify cxyz as input instead // of xyzc if (img->spectrum() > 1) { img->permute_axes("cxyz"); } if (!dst) { T* dstAlloc = new T[img->size()]; dst = static_cast<void*>(dstAlloc); } const void* src = static_cast<const void*>(img->data()); std::memcpy(dst, src, img->size() * sizeof(T)); return dst; } }; // Single channel images template <typename T> struct LayerToCImg { static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) { // Single channel means we can do xyzc, as no permutation is needed auto img = util::make_unique<CImg<T>>(static_cast<const T*>(inputLayerRAM->getData()), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, 1, false); return img; } }; // Multiple channel images template <typename T, template <typename, glm::precision> class G> struct LayerToCImg<G<T, glm::defaultp>> { static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) { auto dataFormat = inputLayerRAM->getDataFormat(); auto typedDataPtr = static_cast<const G<T, glm::defaultp>*>(inputLayerRAM->getData()); // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format // (RRRRGGGGBBBB). // Permute from interleaved to planer format, does we need to specify yzcx as input instead // of cxyz auto img = util::make_unique<CImg<T>>( glm::value_ptr(*typedDataPtr), dataFormat->getComponents(), inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, false); if (permute) img->permute_axes("yzcx"); return img; } }; struct CImgNormalizedLayerDispatcher { using type = std::unique_ptr<std::vector<unsigned char>>; template <typename T> std::unique_ptr<std::vector<unsigned char>> dispatch(const LayerRAM* inputLayer) { auto img = LayerToCImg<typename T::type>::convert(inputLayer, false); CImg<unsigned char> normalizedImg = img->get_normalize(0, 255); normalizedImg.mirror('z'); auto data = util::make_unique<std::vector<unsigned char>>( &normalizedImg[0], &normalizedImg[normalizedImg.size()]); return data; } }; struct CImgLoadLayerDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, uvec2& dimensions, DataFormatId& formatId, const DataFormatBase* dataFormat, bool rescaleToDim) { using P = typename T::primitive; CImg<P> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); if (rescaleToDim) { img.resize(dimensions.x, dimensions.y, -100, -100, 3); } else { dimensions = uvec2(img.width(), img.height()); } auto loadedDataFormat = DataFormatBase::get( dataFormat->getNumericType(), components, sizeof(P) * 8); if (loadedDataFormat) { formatId = loadedDataFormat->getId(); } else { throw Exception("CImgLoadLayerDispatcher, could not find proper data type"); } // Image is up-side-down img.mirror('y'); return CImgToVoidConvert<P>::convert(dst, &img); } }; struct CImgSaveLayerDispatcher { using type = void; template <typename T> void dispatch(const char* filePath, const LayerRAM* inputLayer) { auto img = LayerToCImg<typename T::type>::convert(inputLayer); // Should rescale values based on output format i.e. PNG/JPG is 0-255, HDR different. const DataFormatBase* outFormat = DataFloat32::get(); std::string fileExtension = toLower(filesystem::getFileExtension(filePath)); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { outFormat = DataFormatBase::get(extToBaseTypeMap_[fileExtension]); } // Image is up-side-down img->mirror('y'); const DataFormatBase* inFormat = inputLayer->getDataFormat(); double inMin = inFormat->getMin(); double inMax = inFormat->getMax(); double outMin = outFormat->getMin(); double outMax = outFormat->getMax(); // Special treatment for float data types: // For float input images, we assume that the range is [0,1] (which is the same as rendered // in a Canvas) // For float output images, we normalize to [0,1] // Note that no normalization is performed if both input and output are float images if (inFormat->getNumericType() == NumericType::Float) { inMin = 0.0; inMax = 1.0; } if (outFormat->getNumericType() == NumericType::Float) { outMin = 0.0; outMax = 1.0; } // The image values should be rescaled if the ranges of the input and output are different if (inMin != outMin || inMax != outMax) { typename T::primitive* data = img->data(); double scale = (outMax - outMin) / (inMax - inMin); for (size_t i = 0; i < img->size(); i++) { auto dataValue = glm::clamp(static_cast<double>(data[i]), inMin, inMax); data[i] = static_cast<typename T::primitive>((dataValue - inMin) * scale + outMin); } } try { img->save(filePath); } catch (CImgIOException& e) { throw DataWriterException("Failed to save image to: " + std::string(filePath), IvwContext); } } }; struct CImgRescaleLayerDispatcher { using type = void*; template <typename T> void* dispatch(const LayerRAM* inputLayerRAM, uvec2 dst_dim) { auto img = LayerToCImg<typename T::type>::convert(inputLayerRAM); img->resize(dst_dim.x, dst_dim.y, -100, -100, 3); return CImgToVoidConvert<typename T::primitive>::convert(nullptr, img.get()); } }; struct CImgLoadVolumeDispatcher { using type = void*; template <typename T> void* dispatch(void* dst, const char* filePath, size3_t& dimensions, DataFormatId& formatId, const DataFormatBase* dataFormat) { CImg<typename T::primitive> img(filePath); size_t components = static_cast<size_t>(img.spectrum()); dimensions = size3_t(img.width(), img.height(), img.depth()); const DataFormatBase* loadedDataFormat = DataFormatBase::get( dataFormat->getNumericType(), components, sizeof(typename T::primitive) * 8); if (loadedDataFormat) formatId = loadedDataFormat->getId(); else throw Exception("CImgLoadVolumeDispatcher, could not find proper data type"); // Image is up-side-down img.mirror('y'); return CImgToVoidConvert<typename T::primitive>::convert(dst, &img); } }; ////////////////////// CImgUtils /////////////////////////////////////////////////// void* CImgUtils::loadLayerData(void* dst, const std::string& filePath, uvec2& dimensions, DataFormatId& formatId, bool rescaleToDim) { std::string fileExtension = toLower(filesystem::getFileExtension(filePath)); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatId::Float32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadLayerDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat, rescaleToDim); } void* CImgUtils::loadVolumeData(void* dst, const std::string& filePath, size3_t& dimensions, DataFormatId& formatId) { std::string fileExtension = toLower(filesystem::getFileExtension(filePath)); if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) { formatId = extToBaseTypeMap_[fileExtension]; } else { formatId = DataFormatId::Float32; } const DataFormatBase* dataFormat = DataFormatBase::get(formatId); CImgLoadVolumeDispatcher disp; return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat); } void CImgUtils::saveLayer(const std::string& filePath, const Layer* inputLayer) { CImgSaveLayerDispatcher disp; const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); inputLayer->getDataFormat()->dispatch(disp, filePath.c_str(), inputLayerRam); } std::unique_ptr<std::vector<unsigned char>> CImgUtils::saveLayerToBuffer(std::string& fileType, const Layer* inputLayer) { const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>(); fileType = "raw"; // Can only produce raw output CImgNormalizedLayerDispatcher disp; return inputLayer->getDataFormat()->dispatch(disp, inputLayerRam); } void* CImgUtils::rescaleLayer(const Layer* inputLayer, uvec2 dst_dim) { const LayerRAM* layerRam = inputLayer->getRepresentation<LayerRAM>(); return rescaleLayerRAM(layerRam, dst_dim); } void* CImgUtils::rescaleLayerRAM(const LayerRAM* srcLayerRam, uvec2 dst_dim) { CImgRescaleLayerDispatcher disp; return srcLayerRam->getDataFormat()->dispatch(disp, srcLayerRam, dst_dim); } } // namespace #include <warn/pop> <|endoftext|>
<commit_before>#include "StdAfx.h" #include "ByteStream.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post 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 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 http://www.klauspost.com */ namespace RawSpeed { ByteStream::ByteStream(const uchar8* _buffer, uint32 _size) : buffer(_buffer), size(_size), off(0) { } ByteStream::ByteStream(const ByteStream *b) : buffer(b->buffer), size(b->size), off(b->off) { } ByteStream::~ByteStream(void) { } uint32 ByteStream::peekByte() { return buffer[off]; } void ByteStream::skipBytes(uint32 nbytes) { off += nbytes; if (off > size) throw IOException("Skipped out of buffer"); } uchar8 ByteStream::getByte() { if (off >= size) throw IOException("getByte:Out of buffer read"); return buffer[off++]; } ushort16 ByteStream::getShort() { if (off + 1 >= size) throw IOException("getShort: Out of buffer read"); return *(ushort16*)&buffer[off+=4]; uint32 a = buffer[off++]; uint32 b = buffer[off++]; // !!! ENDIAN SWAP return (a << 8) | b; } int ByteStream::getInt() { if (off + 4 >= size) throw IOException("getInt:Out of buffer read"); return *(int*)&buffer[off+=4]; } void ByteStream::setAbsoluteOffset(uint32 offset) { if (offset >= size) throw IOException("setAbsoluteOffset:Offset set out of buffer"); off = offset; } void ByteStream::skipToMarker() { int c = 0; while (!(buffer[off] == 0xFF && buffer[off+1] != 0)) { off++; c++; if (off >= size) throw IOException("No marker found inside rest of buffer"); } // _RPT1(0,"Skipped %u bytes.\n", c); } } // namespace RawSpeed <commit_msg>Fix byte stream in host endianness.<commit_after>#include "StdAfx.h" #include "ByteStream.h" /* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post 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 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 http://www.klauspost.com */ namespace RawSpeed { ByteStream::ByteStream(const uchar8* _buffer, uint32 _size) : buffer(_buffer), size(_size), off(0) { } ByteStream::ByteStream(const ByteStream *b) : buffer(b->buffer), size(b->size), off(b->off) { } ByteStream::~ByteStream(void) { } uint32 ByteStream::peekByte() { return buffer[off]; } void ByteStream::skipBytes(uint32 nbytes) { off += nbytes; if (off > size) throw IOException("Skipped out of buffer"); } uchar8 ByteStream::getByte() { if (off >= size) throw IOException("getByte:Out of buffer read"); off++; return buffer[off-1]; } ushort16 ByteStream::getShort() { if (off + 1 >= size) throw IOException("getShort: Out of buffer read"); off +=2; return *(ushort16*)&buffer[off-2]; } int ByteStream::getInt() { if (off + 4 >= size) throw IOException("getInt:Out of buffer read"); off+=4; return *(int*)&buffer[off-4]; } void ByteStream::setAbsoluteOffset(uint32 offset) { if (offset >= size) throw IOException("setAbsoluteOffset:Offset set out of buffer"); off = offset; } void ByteStream::skipToMarker() { int c = 0; while (!(buffer[off] == 0xFF && buffer[off+1] != 0)) { off++; c++; if (off >= size) throw IOException("No marker found inside rest of buffer"); } // _RPT1(0,"Skipped %u bytes.\n", c); } } // namespace RawSpeed <|endoftext|>
<commit_before>/** * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1. * * @author FirstSanny */ #include <iostream> #include <fstream> #include <utility> #include <vector> #include <climits> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/named_function_params.hpp> namespace { const char* FILEEND = ".gph"; } // declaring print using std::cout; using std::endl; using std::cerr; using std::string; typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> graph; typedef boost::graph_traits < graph >::vertex_descriptor vertex_descriptor; int readFirstLine(int edgeCount, string& line) { return edgeCount; } /** add's fileending and opens the via ifstream */ std::ifstream openFile(char* argv[]) { string filename = argv[1]; filename += FILEEND; cout << "Going to parse the file " << filename << endl; std::ifstream fileStream; fileStream.open(filename.c_str(), std::ios::in); return fileStream; } /** Creates a Map for boost, cause a normal vector.begin() doesn't work */ boost::iterator_property_map<__gnu_cxx:: __normal_iterator <int*,std::vector<int,std::allocator<int> > > ,boost::vec_adj_list_vertex_id_map<boost::no_property,unsigned long int> ,int,int&> getBoostMap(std::vector<int> directions, graph& g) { return boost::make_iterator_property_map(directions.begin(), boost::get(boost::vertex_index, g)); } /** Reading in a Graphfile, computes the longest shortest path */ int main(int argn, char *argv[]) { if (argn <= 1) { cerr << "ERROR : There was no filename" << endl; return 1; } std::ifstream fileStream = openFile(argv); if ( (fileStream.rdstate()) != 0 ){ std::perror("ERROR : Encoutered Problem opening file"); return 1; } string line; unsigned int edgeCount; unsigned int vertexCount; if(std::getline(fileStream, line)){ sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount); cout << "Vertexcount: " << vertexCount << endl; cout << "Edgecount: " << edgeCount << endl; line.clear(); } else { cerr << "ERROR : File was empty" << endl; return 1; } std::vector<std::pair<int, int>> edges; std::vector<int> weights; cout << "Reading edges..." << endl; while (getline(fileStream, line)) { int start; int end; int weight; int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight); if (count != 3) { line.clear(); continue; } edges.push_back(std::make_pair(start, end)); weights.push_back(weight); line.clear(); } cout << "Creating graph..." << endl; graph g{edges.begin(), edges.end(), weights.begin(), vertexCount}; std::vector<vertex_descriptor> directions(vertexCount); std::vector<int> weightMap(vertexCount); cout << "Compute shortest paths via Dijkstra..." << endl; boost::dijkstra_shortest_paths(g, 1, boost::predecessor_map(// boost::make_iterator_property_map(directions.begin(), boost::get(boost::vertex_index, g))) // .distance_map(// boost::make_iterator_property_map(weightMap.begin(), boost::get(boost::vertex_index, g)))); cout << "Search longest shortest path..." << endl; int vertex = 1; int distance = 0; for(unsigned int i=2; i<=vertexCount; i++){ if(weightMap[i]>distance){ distance = weightMap[i]; vertex = i; } } cout << "RESULT VERTEX " << vertex << '\n'; cout << "RESULT DIST " << distance << '\n'; return 0; } <commit_msg>ex6 via boost libary<commit_after>/** * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1. * * @author FirstSanny */ #include <iostream> #include <fstream> #include <utility> #include <vector> #include <climits> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <boost/graph/named_function_params.hpp> #include <boost/timer/timer.hpp> namespace { const char* FILEEND = ".gph"; } // declaring print using std::cout; using std::endl; using std::cerr; using std::string; typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> graph; typedef boost::graph_traits < graph >::vertex_descriptor vertex_descriptor; int readFirstLine(int edgeCount, string& line) { return edgeCount; } /** add's fileending and opens the via ifstream */ std::ifstream openFile(char* argv[]) { string filename = argv[1]; filename += FILEEND; cout << "Going to parse the file " << filename << endl; std::ifstream fileStream; fileStream.open(filename.c_str(), std::ios::in); return fileStream; } /** Reading in a Graphfile, computes the longest shortest path */ int main(int argn, char *argv[]) { boost::timer::auto_cpu_timer t; if (argn <= 1) { cerr << "ERROR : There was no filename" << endl; return 1; } std::ifstream fileStream = openFile(argv); if ( (fileStream.rdstate()) != 0 ){ std::perror("ERROR : Encoutered Problem opening file"); return 1; } string line; unsigned int edgeCount; unsigned int vertexCount; if(std::getline(fileStream, line)){ sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount); cout << "Vertexcount: " << vertexCount << endl; cout << "Edgecount: " << edgeCount << endl; line.clear(); vertexCount++; } else { cerr << "ERROR : File was empty" << endl; return 1; } std::vector<std::pair<int, int>> edges(edgeCount); std::vector<int> weights(edgeCount); cout << "Reading edges..." << endl; while (getline(fileStream, line)) { int start; int end; int weight; int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight); if (count != 3) { line.clear(); continue; } edges.push_back(std::make_pair(start, end)); weights.push_back(weight); line.clear(); } cout << "Creating graph..." << endl; graph g{edges.begin(), edges.end(), weights.begin(), vertexCount}; std::vector<vertex_descriptor> directions(vertexCount); std::vector<int> weightMap(vertexCount); cout << "Compute shortest paths via Dijkstra..." << endl; boost::dijkstra_shortest_paths(g, 1, boost::predecessor_map(// boost::make_iterator_property_map(directions.begin(), boost::get(boost::vertex_index, g))) // .distance_map(// boost::make_iterator_property_map(weightMap.begin(), boost::get(boost::vertex_index, g)))); cout << "Search longest shortest path..." << endl; int vertex = 1; int distance = 0; for(unsigned int i=2; i<=vertexCount; i++){ if(weightMap[i]>distance){ distance = weightMap[i]; vertex = i; } } cout << "RESULT VERTEX " << vertex << '\n'; cout << "RESULT DIST " << distance << '\n'; return 0; } <|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. * **************************************************************************/ //------------------------------------------------------- // Implementation of the TPC transformation class // // Origin: Marian Ivanov [email protected] // Magnus Mager // // Class for tranformation of the coordinate frame // Transformation // local coordinate frame (sector, padrow, pad, timebine) ==> // rotated global (tracking) cooridnate frame (sector, lx,ly,lz) // // Unisochronity - (substract time0 - pad by pad) // Drift velocity - Currently common drift velocity - functionality of AliTPCParam // ExB effect - // // Time of flight correction - // - Depends on the vertex position // - by default // // Usage: // AliTPCclustererMI::AddCluster // AliTPCtrackerMI::Transform // //------------------------------------------------------- /* To test it: cdb=AliCDBManager::Instance() cdb->SetDefaultStorage("local:///u/mmager/mycalib1") c=AliTPCcalibDB::Instance() c->SetRun(0) Double_t x[]={1.0,2.0,3.0} Int_t i[]={4} AliTPCTransform trafo trafo.Transform(x,i,0,1) */ /* $Id$ */ #include "AliTPCROC.h" #include "AliTPCCalPad.h" #include "AliTPCCalROC.h" #include "AliTPCcalibDB.h" #include "AliTPCParam.h" #include "TMath.h" #include "AliLog.h" #include "AliTPCExB.h" #include "TGeoMatrix.h" #include "AliTPCTransform.h" ClassImp(AliTPCTransform) AliTPCTransform::AliTPCTransform(): AliTransform() { // // Speed it up a bit! // for (Int_t i=0;i<18;++i) { Double_t alpha=TMath::DegToRad()*(10.+20.*(i%18)); fSins[i]=TMath::Sin(alpha); fCoss[i]=TMath::Cos(alpha); } fPrimVtx[0]=0; fPrimVtx[1]=0; fPrimVtx[2]=0; } AliTPCTransform::~AliTPCTransform() { // // Destructor // } void AliTPCTransform::SetPrimVertex(Double_t *vtx){ // // // fPrimVtx[0]=vtx[0]; fPrimVtx[1]=vtx[1]; fPrimVtx[2]=vtx[2]; } void AliTPCTransform::Transform(Double_t *x,Int_t *i,UInt_t /*time*/, Int_t /*coordinateType*/) { // input: x[0] - pad row // x[1] - pad // x[2] - time in us // i[0] - sector // output: x[0] - x (all in the rotated global coordinate frame) // x[1] - y // x[2] - z // // primvtx - position of the primary vertex // used for the TOF correction // TOF of particle calculated assuming the speed-of-light and // line approximation // Int_t row=TMath::Nint(x[0]); Int_t pad=TMath::Nint(x[1]); Int_t sector=i[0]; AliTPCcalibDB* calib=AliTPCcalibDB::Instance(); // AliTPCCalPad * time0TPC = calib->GetPadTime0(); AliTPCParam * param = calib->GetParameters(); if (!time0TPC){ AliFatal("Time unisochronity missing"); } if (!param){ AliFatal("Parameters missing"); } Double_t xx[3]; // Apply Time0 correction - Pad by pad fluctuation // x[2]-=time0TPC->GetCalROC(sector)->GetValue(row,pad); // // Tranform from pad - time coordinate system to the rotated global (tracking) system // Local2RotatedGlobal(sector,x); // // // // Alignment //TODO: calib->GetParameters()->GetClusterMatrix(sector)->LocalToMaster(x,xx); RotatedGlobal2Global(sector,x); // // // ExB correction // calib->GetExB()->Correct(x,xx); // // Time of flight correction // const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector(); Float_t sign=1; if (sector < kNIS) { sign = (sector < kNIS/2) ? 1 : -1; } else { sign = ((sector-kNIS) < kNOS/2) ? 1 : -1; } Float_t deltaDr =0; Float_t dist=0; dist+=(fPrimVtx[0]-x[0])*(fPrimVtx[0]-x[0]); dist+=(fPrimVtx[1]-x[1])*(fPrimVtx[1]-x[1]); dist+=(fPrimVtx[0]-x[2])*(fPrimVtx[0]-x[2]); dist = TMath::Sqrt(dist); // drift length correction because of TOF // the drift velocity is in cm/s therefore multiplication by 0.01 deltaDr = (dist*(0.01*param->GetDriftV()))/TMath::C(); xx[2]+=sign*deltaDr; // Global2RotatedGlobal(sector,xx); // x[0]=xx[0];x[1]=xx[1];x[2]=xx[2]; } void AliTPCTransform::Local2RotatedGlobal(Int_t sector, Double_t *x) const { // // // Tranform coordinate from // row, pad, time to x,y,z // // Drift Velocity // Current implementation - common drift velocity - for full chamber // TODO: use a map or parametrisation! // // // AliTPCcalibDB* calib=AliTPCcalibDB::Instance(); AliTPCParam * param = calib->GetParameters(); if (!param){ AliFatal("Parameters missing"); } Int_t row=TMath::Nint(x[0]); // Int_t pad=TMath::Nint(x[1]); // const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector(); Double_t sign = 1.; Double_t zwidth = param->GetZWidth(); Double_t padWidth = 0; Double_t padLength = 0; Double_t maxPad = 0; // if (sector < kNIS) { maxPad = param->GetNPadsLow(row); sign = (sector < kNIS/2) ? 1 : -1; padLength = param->GetPadPitchLength(sector,row); padWidth = param->GetPadPitchWidth(sector); } else { maxPad = param->GetNPadsUp(row); sign = ((sector-kNIS) < kNOS/2) ? 1 : -1; padLength = param->GetPadPitchLength(sector,row); padWidth = param->GetPadPitchWidth(sector); } // // X coordinate x[0] = param->GetPadRowRadii(sector,row); // padrow X position - ideal // // Y coordinate // x[1]=(x[1]-0.5*maxPad)*padWidth; // pads are mirrorred on C-side if (sector%36>17){ x[1]*=-1; } // // // Z coordinate // x[2]*= zwidth; // tranform time bin to the distance to the ROC x[2]-= 3.*param->GetZSigma() + param->GetNTBinsL1()*zwidth; // subtract the time offsets x[2] = sign*( param->GetZLength(sector) - x[2]); } void AliTPCTransform::RotatedGlobal2Global(Int_t sector,Double_t *x) const { // // transform possition rotated global to the global // Double_t cos,sin; GetCosAndSin(sector,cos,sin); Double_t tmp=x[0]; x[0]= cos*tmp-sin*x[1]; x[1]=+sin*tmp+cos*x[1]; } void AliTPCTransform::Global2RotatedGlobal(Int_t sector,Double_t *x) const { // // tranform possition Global2RotatedGlobal // Double_t cos,sin; GetCosAndSin(sector,cos,sin); Double_t tmp=x[0]; x[0]= cos*tmp+sin*x[1]; x[1]= -sin*tmp+cos*x[1]; } void AliTPCTransform::GetCosAndSin(Int_t sector,Double_t &cos, Double_t &sin) const { cos=fCoss[sector%18]; sin=fSins[sector%18]; } <commit_msg>Bug fix - Use the proper z vertex for TOF correction - dist+=(fPrimVtx[0]-x[2])*(fPrimVtx[0]-x[2]); + dist+=(fPrimVtx[2]-x[2])*(fPrimVtx[2]-x[2]);<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. * **************************************************************************/ //------------------------------------------------------- // Implementation of the TPC transformation class // // Origin: Marian Ivanov [email protected] // Magnus Mager // // Class for tranformation of the coordinate frame // Transformation // local coordinate frame (sector, padrow, pad, timebine) ==> // rotated global (tracking) cooridnate frame (sector, lx,ly,lz) // // Unisochronity - (substract time0 - pad by pad) // Drift velocity - Currently common drift velocity - functionality of AliTPCParam // ExB effect - // // Time of flight correction - // - Depends on the vertex position // - by default // // Usage: // AliTPCclustererMI::AddCluster // AliTPCtrackerMI::Transform // //------------------------------------------------------- /* To test it: cdb=AliCDBManager::Instance() cdb->SetDefaultStorage("local:///u/mmager/mycalib1") c=AliTPCcalibDB::Instance() c->SetRun(0) Double_t x[]={1.0,2.0,3.0} Int_t i[]={4} AliTPCTransform trafo trafo.Transform(x,i,0,1) */ /* $Id$ */ #include "AliTPCROC.h" #include "AliTPCCalPad.h" #include "AliTPCCalROC.h" #include "AliTPCcalibDB.h" #include "AliTPCParam.h" #include "TMath.h" #include "AliLog.h" #include "AliTPCExB.h" #include "TGeoMatrix.h" #include "AliTPCTransform.h" ClassImp(AliTPCTransform) AliTPCTransform::AliTPCTransform(): AliTransform() { // // Speed it up a bit! // for (Int_t i=0;i<18;++i) { Double_t alpha=TMath::DegToRad()*(10.+20.*(i%18)); fSins[i]=TMath::Sin(alpha); fCoss[i]=TMath::Cos(alpha); } fPrimVtx[0]=0; fPrimVtx[1]=0; fPrimVtx[2]=0; } AliTPCTransform::~AliTPCTransform() { // // Destructor // } void AliTPCTransform::SetPrimVertex(Double_t *vtx){ // // // fPrimVtx[0]=vtx[0]; fPrimVtx[1]=vtx[1]; fPrimVtx[2]=vtx[2]; } void AliTPCTransform::Transform(Double_t *x,Int_t *i,UInt_t /*time*/, Int_t /*coordinateType*/) { // input: x[0] - pad row // x[1] - pad // x[2] - time in us // i[0] - sector // output: x[0] - x (all in the rotated global coordinate frame) // x[1] - y // x[2] - z // // primvtx - position of the primary vertex // used for the TOF correction // TOF of particle calculated assuming the speed-of-light and // line approximation // Int_t row=TMath::Nint(x[0]); Int_t pad=TMath::Nint(x[1]); Int_t sector=i[0]; AliTPCcalibDB* calib=AliTPCcalibDB::Instance(); // AliTPCCalPad * time0TPC = calib->GetPadTime0(); AliTPCParam * param = calib->GetParameters(); if (!time0TPC){ AliFatal("Time unisochronity missing"); } if (!param){ AliFatal("Parameters missing"); } Double_t xx[3]; // Apply Time0 correction - Pad by pad fluctuation // x[2]-=time0TPC->GetCalROC(sector)->GetValue(row,pad); // // Tranform from pad - time coordinate system to the rotated global (tracking) system // Local2RotatedGlobal(sector,x); // // // // Alignment //TODO: calib->GetParameters()->GetClusterMatrix(sector)->LocalToMaster(x,xx); RotatedGlobal2Global(sector,x); // // // ExB correction // calib->GetExB()->Correct(x,xx); // // Time of flight correction // const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector(); Float_t sign=1; if (sector < kNIS) { sign = (sector < kNIS/2) ? 1 : -1; } else { sign = ((sector-kNIS) < kNOS/2) ? 1 : -1; } Float_t deltaDr =0; Float_t dist=0; dist+=(fPrimVtx[0]-x[0])*(fPrimVtx[0]-x[0]); dist+=(fPrimVtx[1]-x[1])*(fPrimVtx[1]-x[1]); dist+=(fPrimVtx[2]-x[2])*(fPrimVtx[2]-x[2]); dist = TMath::Sqrt(dist); // drift length correction because of TOF // the drift velocity is in cm/s therefore multiplication by 0.01 deltaDr = (dist*(0.01*param->GetDriftV()))/TMath::C(); xx[2]+=sign*deltaDr; // Global2RotatedGlobal(sector,xx); // x[0]=xx[0];x[1]=xx[1];x[2]=xx[2]; } void AliTPCTransform::Local2RotatedGlobal(Int_t sector, Double_t *x) const { // // // Tranform coordinate from // row, pad, time to x,y,z // // Drift Velocity // Current implementation - common drift velocity - for full chamber // TODO: use a map or parametrisation! // // // AliTPCcalibDB* calib=AliTPCcalibDB::Instance(); AliTPCParam * param = calib->GetParameters(); if (!param){ AliFatal("Parameters missing"); } Int_t row=TMath::Nint(x[0]); // Int_t pad=TMath::Nint(x[1]); // const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector(); Double_t sign = 1.; Double_t zwidth = param->GetZWidth(); Double_t padWidth = 0; Double_t padLength = 0; Double_t maxPad = 0; // if (sector < kNIS) { maxPad = param->GetNPadsLow(row); sign = (sector < kNIS/2) ? 1 : -1; padLength = param->GetPadPitchLength(sector,row); padWidth = param->GetPadPitchWidth(sector); } else { maxPad = param->GetNPadsUp(row); sign = ((sector-kNIS) < kNOS/2) ? 1 : -1; padLength = param->GetPadPitchLength(sector,row); padWidth = param->GetPadPitchWidth(sector); } // // X coordinate x[0] = param->GetPadRowRadii(sector,row); // padrow X position - ideal // // Y coordinate // x[1]=(x[1]-0.5*maxPad)*padWidth; // pads are mirrorred on C-side if (sector%36>17){ x[1]*=-1; } // // // Z coordinate // x[2]*= zwidth; // tranform time bin to the distance to the ROC x[2]-= 3.*param->GetZSigma() + param->GetNTBinsL1()*zwidth; // subtract the time offsets x[2] = sign*( param->GetZLength(sector) - x[2]); } void AliTPCTransform::RotatedGlobal2Global(Int_t sector,Double_t *x) const { // // transform possition rotated global to the global // Double_t cos,sin; GetCosAndSin(sector,cos,sin); Double_t tmp=x[0]; x[0]= cos*tmp-sin*x[1]; x[1]=+sin*tmp+cos*x[1]; } void AliTPCTransform::Global2RotatedGlobal(Int_t sector,Double_t *x) const { // // tranform possition Global2RotatedGlobal // Double_t cos,sin; GetCosAndSin(sector,cos,sin); Double_t tmp=x[0]; x[0]= cos*tmp+sin*x[1]; x[1]= -sin*tmp+cos*x[1]; } void AliTPCTransform::GetCosAndSin(Int_t sector,Double_t &cos, Double_t &sin) const { cos=fCoss[sector%18]; sin=fSins[sector%18]; } <|endoftext|>
<commit_before>void recTPC2007(Int_t type, const char *filename="data.root") { // .L $ALICE_ROOT/TPC/macros/recTPC2007.C // recTPC2007(0,"rfio:/castor/cern.ch/alice/data/2007/12/16/11/07000013151011.20.root") //recTPC2007(0,"alien:///alice/data/2007/LHC07w_TPC/000012674/raw/07000012674011.90.root") // recTPC2007(0,"/data/test2007/07000012674011/07000012674011.90.root") // // Set path to calibration data // // type variable = 0 - cosmic test // = 1 - laser test // // Set reconstruction parameters //// //gSystem->Load("/afs/cern.ch/alice/tpctest/root/HEAD/lib/libRAliEn.so"); //gSystem->Load("$ROOTSYS/lib/libXrdClient.so") TGrid::Connect("alien://"); // AliLog::SetClassDebugLevel("AliTPCclusterer",2); AliTPCRecoParam * tpcRecoParam = 0; if (type==0) tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE); if (type>0) tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE); tpcRecoParam->SetTimeInterval(60,940); tpcRecoParam->Dump(); // // // tpcRecoParam->SetMinMaxCutAbs(4.); // tpcRecoParam->SetMinLeftRightCutAbs(6.); // tpcRecoParam->SetMinUpDownCutAbs(7.); // tpcRecoParam->SetMinMaxCutSigma(4.); // tpcRecoParam->SetMinLeftRightCutSigma(6.); // tpcRecoParam->SetMinUpDownCutSigma(7.); // // AliTPCReconstructor::SetRecoParam(tpcRecoParam); AliTPCReconstructor::SetStreamLevel(100); // AliReconstruction rec; rec.SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/"); rec.SetWriteESDfriend(kTRUE); rec.SetInput(filename); rec.SetRunReconstruction("TPC"); rec.SetEquipmentIdMap("EquipmentIdMap.data"); // rec.SetOption("TPC","PedestalSubtraction OldRCUFormat"); rec.SetFillESD("TPC"); rec.SetFillTriggerESD(kFALSE); rec.SetRunVertexFinder(kFALSE); rec.SetCleanESD(kFALSE); rec.Run(); } <commit_msg>delete obsolete macro<commit_after><|endoftext|>
<commit_before> #include <limits> #include <cassert> #include <type_traits> // // CppCon 2014: Walter E. Brown "Modern Template Metaprogramming: A Compendium" // // ~ https://www.youtube.com/watch?v=Am2is2QCvxY // ~ https://www.youtube.com/watch?v=a0FliKwcwXE // namespace meta { template <int N> struct Abs { static_assert(N != std::numeric_limits<int>::max(), "Out of range!"); static constexpr auto value = (N > 0) ? N : -N; }; constexpr int abs(const int n) { assert(n != std::numeric_limits<int>::max()); return (n > 0) ? n : -n; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <int Base, int Exponent> struct Power { static_assert(Exponent >= 0, "Fractions are not allowed!"); static constexpr auto value = Power<Base, Exponent - 1>::value * Base; }; template <int Base> struct Power <Base, 1> { static constexpr auto value = Base; }; template <int Base> struct Power <Base, 0> { static_assert(Base != 0, "Indeterminate form are not allowed!"); static constexpr auto value = 1; }; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type, Type Constant> struct integral_constant { static constexpr auto value = Constant; }; template <bool Boolean> using bool_constant = integral_constant <bool, Boolean>; using true_type = bool_constant < true>; using false_type = bool_constant <false>; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> struct identity { using type = Type; }; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> struct remove_const : identity<Type> { }; template <typename Type> struct remove_const <const Type> : identity<Type> { }; template <typename Type> using remove_const_t = typename remove_const<Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> struct remove_volatile : identity<Type> { }; template <typename Type> struct remove_volatile <volatile Type> : identity<Type> { }; template <typename Type> using remove_volatile_t = typename remove_volatile<Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> using remove_cv = remove_volatile<typename remove_const<Type>::type>; template <typename Type> using remove_cv_t = typename remove_cv<Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <bool Condition, typename ThenType, typename ElseType> struct conditional; template <typename ThenType, typename ElseType> struct conditional<true, ThenType, ElseType> : identity<ThenType> { }; template <typename ThenType, typename ElseType> struct conditional<false, ThenType, ElseType> : identity<ElseType> { }; template <bool Condition, typename ThenType, typename ElseType> using conditional_t = typename conditional<Condition, ThenType, ElseType>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <bool Condition, typename Type> struct enable_if; template <typename Type> struct enable_if <true, Type> : identity<Type> { }; template <typename Type> struct enable_if <false, Type> { }; template <bool Condition, typename Type> using enable_if_t = typename enable_if<Condition, Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // /* * * * * * * * * * * * * * * * * * * * * * * * * * * SFINAE --> Substitution Failure Is Not An Error * * * * * * * * * * * * * * * * * * * * * * * * * * */ template <typename T> enable_if_t<std::is_integral<T>::value, char> foo (const T) { return 'i'; // overload for integral types } template <typename T> enable_if_t<std::is_floating_point<T>::value, char> foo (const T) { return 'f'; // overload for floating point types } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename FirstType, typename SecondType> struct is_same : false_type { }; template <typename Type> struct is_same <Type, Type> : true_type { }; template <typename FirstType, typename SecondType> constexpr auto is_same_v = is_same<FirstType, SecondType>::value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> using is_void = is_same<typename remove_cv<Type>::type, void>; template <typename Type> constexpr auto is_void_v = is_void<Type>::value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename ...> using void_t = void; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type, typename = void> struct has_type_member : false_type { }; template <typename Type> struct has_type_member <Type, void_t<typename Type::type>> : true_type { }; template <typename Type> constexpr auto has_type_member_v = has_type_member<Type>::value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type, typename = void> struct has_value_member : false_type { }; template <typename Type> struct has_value_member <Type, void_t<decltype(Type::value)>> : true_type { }; template <typename Type> constexpr auto has_value_member_v = has_value_member<Type>::value; } namespace assert { template <typename FirstType, typename SecondType> struct same_types { static_assert ( std::is_same<FirstType, SecondType>::value, "Types have to be the same!" ); }; template <auto FirstValue, auto SecondValue> struct equal_values { static_assert ( FirstValue == SecondValue, "Values have to be the equal!" ); }; } namespace { struct Foo { using type = Foo; }; struct Bar { static constexpr auto value = Foo { }; }; } int main() { assert::equal_values<meta::Abs<-9>::value, 9>(); assert::equal_values<meta::Abs<+7>::value, 7>(); assert::equal_values<meta::abs(-9), 9>(); assert::equal_values<meta::abs(+7), 7>(); assert::equal_values<meta::Power< 2, 8>::value, 256>(); assert::equal_values<meta::Power<-5, 3>::value,-125>(); assert::equal_values<meta::Power< 0, 3>::value, 0>(); assert::equal_values<meta::Power< 3, 0>::value, 1>(); assert::equal_values<meta::Power<11, 1>::value, 11>(); assert::equal_values<meta::integral_constant<int, 7>::value, 7>(); assert::same_types<decltype(meta::integral_constant<char, '$'>::value), const char>(); assert::same_types<meta::remove_const_t<const int>, int>(); assert::same_types<meta::remove_const_t<volatile int>, volatile int>(); assert::same_types<meta::remove_volatile_t<volatile int>, int>(); assert::same_types<meta::remove_volatile_t<const int>, const int>(); assert::same_types<meta::remove_cv_t< int>, int>(); assert::same_types<meta::remove_cv_t< volatile int>, int>(); assert::same_types<meta::remove_cv_t<const int>, int>(); assert::same_types<meta::remove_cv_t<const volatile int>, int>(); assert::same_types<meta::conditional_t< true, char, long>, char>(); assert::same_types<meta::conditional_t<false, char, long>, long>(); assert::same_types<meta::enable_if_t<true, char>, char>(); assert(meta::foo(5) == 'i'); assert(meta::foo(5.0) == 'f'); assert::equal_values<meta::is_same_v<char, char>, true>(); assert::equal_values<meta::is_same_v<char, long>, false>(); assert::equal_values<meta::is_void_v< void>, true>(); assert::equal_values<meta::is_void_v<const void>, true>(); assert::equal_values<meta::is_void_v< volatile void>, true>(); assert::equal_values<meta::is_void_v<const volatile void>, true>(); assert::equal_values<meta::is_void_v< long>, false>(); assert::equal_values<meta::has_type_member_v<Foo>, true>(); assert::equal_values<meta::has_type_member_v<Bar>, false>(); assert::equal_values<meta::has_value_member_v<Bar>, true>(); assert::equal_values<meta::has_value_member_v<Foo>, false>(); return 0; } <commit_msg>Metaprogramming -> Added constexpr to both foo() overloads.<commit_after> #include <limits> #include <cassert> #include <type_traits> // // CppCon 2014: Walter E. Brown "Modern Template Metaprogramming: A Compendium" // // ~ https://www.youtube.com/watch?v=Am2is2QCvxY // ~ https://www.youtube.com/watch?v=a0FliKwcwXE // namespace meta { template <int N> struct Abs { static_assert(N != std::numeric_limits<int>::max(), "Out of range!"); static constexpr auto value = (N > 0) ? N : -N; }; constexpr int abs(const int n) { assert(n != std::numeric_limits<int>::max()); return (n > 0) ? n : -n; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <int Base, int Exponent> struct Power { static_assert(Exponent >= 0, "Fractions are not allowed!"); static constexpr auto value = Power<Base, Exponent - 1>::value * Base; }; template <int Base> struct Power <Base, 1> { static constexpr auto value = Base; }; template <int Base> struct Power <Base, 0> { static_assert(Base != 0, "Indeterminate form are not allowed!"); static constexpr auto value = 1; }; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type, Type Constant> struct integral_constant { static constexpr auto value = Constant; }; template <bool Boolean> using bool_constant = integral_constant <bool, Boolean>; using true_type = bool_constant < true>; using false_type = bool_constant <false>; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> struct identity { using type = Type; }; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> struct remove_const : identity<Type> { }; template <typename Type> struct remove_const <const Type> : identity<Type> { }; template <typename Type> using remove_const_t = typename remove_const<Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> struct remove_volatile : identity<Type> { }; template <typename Type> struct remove_volatile <volatile Type> : identity<Type> { }; template <typename Type> using remove_volatile_t = typename remove_volatile<Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> using remove_cv = remove_volatile<typename remove_const<Type>::type>; template <typename Type> using remove_cv_t = typename remove_cv<Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <bool Condition, typename ThenType, typename ElseType> struct conditional; template <typename ThenType, typename ElseType> struct conditional<true, ThenType, ElseType> : identity<ThenType> { }; template <typename ThenType, typename ElseType> struct conditional<false, ThenType, ElseType> : identity<ElseType> { }; template <bool Condition, typename ThenType, typename ElseType> using conditional_t = typename conditional<Condition, ThenType, ElseType>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <bool Condition, typename Type> struct enable_if; template <typename Type> struct enable_if <true, Type> : identity<Type> { }; template <typename Type> struct enable_if <false, Type> { }; template <bool Condition, typename Type> using enable_if_t = typename enable_if<Condition, Type>::type; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // /* * * * * * * * * * * * * * * * * * * * * * * * * * * SFINAE --> Substitution Failure Is Not An Error * * * * * * * * * * * * * * * * * * * * * * * * * * */ template <typename T> constexpr enable_if_t<std::is_integral<T>::value, char> foo (const T) { return 'i'; // overload for integral types } template <typename T> constexpr enable_if_t<std::is_floating_point<T>::value, char> foo (const T) { return 'f'; // overload for floating point types } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename FirstType, typename SecondType> struct is_same : false_type { }; template <typename Type> struct is_same <Type, Type> : true_type { }; template <typename FirstType, typename SecondType> constexpr auto is_same_v = is_same<FirstType, SecondType>::value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type> using is_void = is_same<typename remove_cv<Type>::type, void>; template <typename Type> constexpr auto is_void_v = is_void<Type>::value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename ...> using void_t = void; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type, typename = void> struct has_type_member : false_type { }; template <typename Type> struct has_type_member <Type, void_t<typename Type::type>> : true_type { }; template <typename Type> constexpr auto has_type_member_v = has_type_member<Type>::value; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // template <typename Type, typename = void> struct has_value_member : false_type { }; template <typename Type> struct has_value_member <Type, void_t<decltype(Type::value)>> : true_type { }; template <typename Type> constexpr auto has_value_member_v = has_value_member<Type>::value; } namespace assert { template <typename FirstType, typename SecondType> struct same_types { static_assert ( std::is_same<FirstType, SecondType>::value, "Types have to be the same!" ); }; template <auto FirstValue, auto SecondValue> struct equal_values { static_assert ( FirstValue == SecondValue, "Values have to be the equal!" ); }; } namespace { struct Foo { using type = Foo; }; struct Bar { static constexpr auto value = Foo { }; }; } int main() { assert::equal_values<meta::Abs<-9>::value, 9>(); assert::equal_values<meta::Abs<+7>::value, 7>(); assert::equal_values<meta::abs(-9), 9>(); assert::equal_values<meta::abs(+7), 7>(); assert::equal_values<meta::Power< 2, 8>::value, 256>(); assert::equal_values<meta::Power<-5, 3>::value,-125>(); assert::equal_values<meta::Power< 0, 3>::value, 0>(); assert::equal_values<meta::Power< 3, 0>::value, 1>(); assert::equal_values<meta::Power<11, 1>::value, 11>(); assert::equal_values<meta::integral_constant<int, 7>::value, 7>(); assert::same_types<decltype(meta::integral_constant<char, '$'>::value), const char>(); assert::same_types<meta::remove_const_t<const int>, int>(); assert::same_types<meta::remove_const_t<volatile int>, volatile int>(); assert::same_types<meta::remove_volatile_t<volatile int>, int>(); assert::same_types<meta::remove_volatile_t<const int>, const int>(); assert::same_types<meta::remove_cv_t< int>, int>(); assert::same_types<meta::remove_cv_t< volatile int>, int>(); assert::same_types<meta::remove_cv_t<const int>, int>(); assert::same_types<meta::remove_cv_t<const volatile int>, int>(); assert::same_types<meta::conditional_t< true, char, long>, char>(); assert::same_types<meta::conditional_t<false, char, long>, long>(); assert::same_types<meta::enable_if_t<true, char>, char>(); assert::equal_values<meta::foo(5 ), 'i'>(); assert::equal_values<meta::foo(5.0), 'f'>(); assert::equal_values<meta::is_same_v<char, char>, true>(); assert::equal_values<meta::is_same_v<char, long>, false>(); assert::equal_values<meta::is_void_v< void>, true>(); assert::equal_values<meta::is_void_v<const void>, true>(); assert::equal_values<meta::is_void_v< volatile void>, true>(); assert::equal_values<meta::is_void_v<const volatile void>, true>(); assert::equal_values<meta::is_void_v< long>, false>(); assert::equal_values<meta::has_type_member_v<Foo>, true>(); assert::equal_values<meta::has_type_member_v<Bar>, false>(); assert::equal_values<meta::has_value_member_v<Bar>, true>(); assert::equal_values<meta::has_value_member_v<Foo>, false>(); return 0; } <|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. #include <ctime> #include <functional> #include <nix/valid/validator.hpp> #include <nix/valid/checks.hpp> #include <nix/valid/conditions.hpp> #include <nix/valid/validate.hpp> #include <nix.hpp> #include "TestValidate.hpp" using namespace nix; using namespace valid; using namespace std; void TestValidate::setUp() { startup_time = time(NULL); } void TestValidate::tearDown() { return; } void TestValidate::test() { // dummy class to test empty checks class fooC { public: std::string getFoo () const { return std::string("I'm not empty!"); }; std::string getBar () const { return std::string(); }; }; std::vector<std::string> vect = {"foo", "bar"}; std::vector<std::string> vect2; fooC foobar; // NOTE: we can't test nix specific checks since nix & validation // structs cannot be included together valid::Result myResult = validator({ could(vect, &std::vector<std::string>::empty, notFalse(), { must(vect, &std::vector<std::string>::size, notSmaller(2), "some msg") }), must(vect, &std::vector<std::string>::size, notSmaller(2), "some msg"), must(vect, &std::vector<std::string>::size, isSmaller(2), "some msg"), should(vect, &std::vector<std::string>::size, notGreater(2), "some msg"), should(vect, &std::vector<std::string>::size, isGreater(0), "some msg"), must(vect, &std::vector<std::string>::size, notEqual<size_t>(0), "some msg"), should(vect, &std::vector<std::string>::size, isEqual<size_t>(2), "some msg"), must(vect2, &std::vector<std::string>::size, isFalse(), "some msg"), must(foobar, &fooC::getFoo, notEmpty(), "some msg"), should(foobar, &fooC::getBar, isEmpty(), "some msg") }); CPPUNIT_ASSERT(myResult.hasWarnings() == false); CPPUNIT_ASSERT(myResult.hasErrors() == false); } <commit_msg>Small fixes to TestValidate<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. #include <ctime> #include <functional> #include <nix/valid/validator.hpp> #include <nix/valid/checks.hpp> #include <nix/valid/conditions.hpp> #include <nix/valid/validate.hpp> #include <nix.hpp> #include "TestValidate.hpp" using namespace nix; using namespace valid; using namespace std; void TestValidate::setUp() { startup_time = time(NULL); } void TestValidate::tearDown() { return; } void TestValidate::test() { // dummy class to test empty checks class fooC { public: std::string getFoo () const { return std::string("I'm not empty!"); }; std::string getBar () const { return std::string(); }; }; std::vector<std::string> vect = {"foo", "bar"}; std::vector<std::string> vect2; fooC foobar; // NOTE: we can't test nix specific checks since nix & validation // structs cannot be included together valid::Result myResult = validator({ could(vect, &std::vector<std::string>::empty, isFalse(), { must(vect, &std::vector<std::string>::size, notSmaller(2), "notSmaller(2)") }), must(vect, &std::vector<std::string>::size, notSmaller(2), "notSmaller(2)"), must(vect2, &std::vector<std::string>::size, isSmaller(2), "isSmaller(2)"), should(vect, &std::vector<std::string>::size, notGreater(2), "notGreater(2)"), should(vect, &std::vector<std::string>::size, isGreater(0), "isGreater(0)"), must(vect, &std::vector<std::string>::size, notEqual<size_t>(0), "notEqual<size_t>(0)"), should(vect, &std::vector<std::string>::size, isEqual<size_t>(2), "isEqual<size_t>(2)"), must(vect2, &std::vector<std::string>::size, isFalse(), "isFalse()"), must(foobar, &fooC::getFoo, notEmpty(), "notEmpty()"), should(foobar, &fooC::getBar, isEmpty(), "isEmpty()") }); // uncomment this to have debug info // std::cout << myResult; CPPUNIT_ASSERT(myResult.hasWarnings() == false); CPPUNIT_ASSERT(myResult.hasErrors() == false); } <|endoftext|>
<commit_before>#include <mlopen.h> #include "test.hpp" #include <vector> #include <array> #include <iterator> #include <algorithm> #include <numeric> #include <memory> #include <utility> #include <iostream> #include <cmath> #include <mlopen/tensor.hpp> #include <mlopen/convolution.hpp> #include <mlopen/returns.hpp> #include <mlopen/each_args.hpp> #include <limits> #include <thread> #include "network_data.hpp" template<class F> struct protect_fn { F f; protect_fn(F x) : f(std::move(x)) {} template<class... Ts> auto operator()(Ts&&... xs) const MLOPEN_RETURNS (f(std::forward<Ts>(xs)...)); }; template<class F> protect_fn<F> protect(F f) { return {std::move(f)}; } template<class F> void par_for(int n, F f) { const auto threadsize = std::thread::hardware_concurrency(); if (n < threadsize) { for(int i=0;i<n;i++) f(i); } else { std::vector<std::thread> threads(threadsize); const int grainsize = n / threads.size(); int work = 0; std::generate(threads.begin(), threads.end(), [&] { int start = work; int last = std::min(n, work+grainsize); // std::cout << "work, last: " << work << ", " << last << std::endl; assert((last - start) <= grainsize); assert((last - start) > 0); auto result = std::thread([&f, start, last] { for(int i=start;i<last;i++) { f(i); } }); work += grainsize; return result; }); // TODO: Should be in destructor for(auto&& t:threads) { if (t.joinable()) t.join(); } } } // Multidimensional for loop struct ford_impl { template<class F, class T> void operator()(F f, T x) const { for(T i=0;i<x;i++) f(i); } template<class F, class T, class... Ts> void operator()(F f, T x, Ts... xs) const { #if (defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9) // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914 // This reverses the order of evaluation (*this)([&](Ts... is) { (*this)(std::bind(protect(f), std::placeholders::_1, is...), x); }, xs...); #else (*this)([&](T i) { (*this)([&](Ts... is) { f(i, is...); }, xs...); }, x); #endif } }; template<class... Ts> auto ford(Ts... xs) MLOPEN_RETURNS ( std::bind(ford_impl{}, std::placeholders::_1, xs...) ); struct par_ford_impl { template<class F, class T, class... Ts> void operator()(F f, T x, Ts... xs) const { #if (defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9) // No parallelism for gcc 4.8 ford(x, xs...)(f); #else par_for(x, [&](T i) { ford(xs...)([&](Ts... is) { f(i, is...); }); }); #endif } }; template<class... Ts> auto par_ford(Ts... xs) MLOPEN_RETURNS ( std::bind(par_ford_impl{}, std::placeholders::_1, xs...) ); template<class T> struct tensor { mlopen::TensorDescriptor desc; std::vector<T> data; tensor(int n, int c, int h, int w) : desc(mlopenFloat, {n,c,h,w}), data(n*c*h*w) {} tensor(mlopen::TensorDescriptor rhs) : desc(std::move(rhs)) { data.resize(desc.GetElementSize()); } template<class G> tensor& generate(G g) & { this->generate_impl(g); return *this; } template<class G> tensor&& generate(G g) && { this->generate_impl(g); return std::move(*this); } template<class G> void generate_impl(G g) { auto iterator = data.begin(); this->for_each([&](int i, int j, int k, int m) { assert(iterator < data.end()); *iterator = g(i, j, k, m); ++iterator; }); } template<class F> void for_each(F f) const { int n, c, h, w; std::tie(n, c, h, w) = mlopen::tie4(desc.GetLengths()); ford(n, c, h, w)(std::move(f)); } template<class F> void par_for_each(F f) const { int n, c, h, w; std::tie(n, c, h, w) = mlopen::tie4(desc.GetLengths()); par_ford(n, c, h, w)(std::move(f)); } T& operator()(int n, int c, int h, int w) { assert(this->desc.GetIndex(n, c, h, w) < data.size()); return this->data[this->desc.GetIndex(n, c, h, w)]; } const T& operator()(int n, int c, int h, int w) const { assert(this->desc.GetIndex(n, c, h, w) < data.size()); return this->data[this->desc.GetIndex(n, c, h, w)]; } }; struct tensor_generate { template<class Tensor, class G> Tensor&& operator()(Tensor&& t, G g) const { return std::forward<Tensor>(t.generate(g)); } }; template<class T> tensor<T> get_output_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& weights) { return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)}; } template<class T> std::vector<T> forward_conv(const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int bias = 0) { auto out = get_output_tensor(filter, input, weights); int in_n, in_c, in_h, in_w; std::tie(in_n, in_c, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_h, wei_w; std::tie(std::ignore, std::ignore, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); out.par_for_each([&](int o, int w, int i, int j) { int in_off_h = i * filter.v; int in_off_w = j * filter.u; T acc = bias; for(int k = 0; k < in_c; k++) { // in_channels (RGB) for(int x = 0; x < wei_h; x++) { int in_x = in_off_h - filter.pad_h + x; if(in_x >= 0 && in_x < in_h) { for(int y = 0; y < wei_w; y++) { int in_y = in_off_w - filter.pad_w + y; if(in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * weights(w, k, x, y); } } } } } out(o, w, i, j) = acc; }); return out.data; } template<class T> std::vector<T> forward_conv(mlopen::Handle& handle, const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto out = get_output_tensor(filter, input, weights); auto in_dev = handle.Write(input.data); auto wei_dev = handle.Write(weights.data); auto out_dev = handle.Create<T>(out.data.size()); int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvFwdAlgorithm(handle, input.desc, in_dev.get(), weights.desc, wei_dev.get(), out.desc, out_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, NULL, 10, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionForward(handle, &alpha, input.desc, in_dev.get(), weights.desc, wei_dev.get(), mlopenConvolutionFwdAlgoDirect, &beta, out.desc, out_dev.get(), NULL, 0); out.data = handle.Read<T>(out_dev, out.data.size()); return out.data; } struct float_equal_fn { template<class T> bool operator()(T x, T y) const { return std::fabs(x - y) < std::max(std::numeric_limits<T>::epsilon() * std::max(x, y), std::numeric_limits<T>::epsilon()); } }; template<class R1, class R2> bool float_equal_range(R1&& r1, R2&& r2) { return std::distance(r1.begin(), r1.end()) == std::distance(r2.begin(), r2.end()) && std::equal(r1.begin(), r1.end(), r2.begin(), float_equal_fn{}); } template<class R1, class R2, class Op> float accumulate_difference(R1&& r1, R2&& r2, Op op) { return std::inner_product(r1.begin(), r1.end(), r2.begin(), 0.0, op, [](float x, float y) { return std::fabs(x - y); } ); } template<class T> void verify_forward_conv(mlopen::Handle& handle, const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int bias = 0) { auto out_cpu = forward_conv(input, weights, filter, bias); auto out_gpu = forward_conv(handle, input, weights, filter, bias); int size = std::distance(out_cpu.begin(), out_cpu.end()); CHECK(std::distance(out_cpu.begin(), out_cpu.end()) == std::distance(out_gpu.begin(), out_gpu.end())); if (!float_equal_range(out_cpu, out_gpu)) { std::cout << "FAILED: " << std::endl; std::cout << "Average difference: " << (accumulate_difference(out_cpu, out_gpu, std::plus<float>()) / size) << std::endl; std::cout << "Max difference: " << (accumulate_difference(out_cpu, out_gpu, [](float x, float y) { return std::max(x, y); })) << std::endl; } // CHECK(out_cpu == out_gpu); } struct cross_args_apply { template<class F, class T, class... Ts> void operator()(F f, T&& x, Ts&&... xs) const { mlopen::each_args(std::bind(f, std::forward<T>(x), std::placeholders::_1), std::forward<Ts>(xs)...); } }; template<class F, class... Ts> void cross_args(F f, Ts&&... xs) { mlopen::each_args( std::bind(cross_args_apply{}, protect(std::move(f)), std::placeholders::_1, std::forward<Ts>(xs)...), std::forward<Ts>(xs)...); } template<class T> struct verify_both { template<class G1, class G2> void operator()(mlopen::Handle& handle, G1 g1, G2 g2) const { visit_network<T>([&](mlopen::TensorDescriptor input_desc, mlopen::TensorDescriptor weights_desc) { auto input = tensor<T>{std::move(input_desc)}.generate(g1); auto weights = tensor<T>{std::move(weights_desc)}.generate(g2); mlopen::ConvolutionDescriptor filter{1, 1}; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; verify_forward_conv(handle, input, weights, filter); }); } }; template<class T, class... Gs> void verify_all(mlopen::Handle& handle, Gs... gs) { cross_args( std::bind(verify_both<T>{}, std::ref(handle), std::placeholders::_1, std::placeholders::_2), gs...); } template<class T, class G> void verify_one(mlopen::Handle& handle, G g) { auto input = tensor<T>{16, 32, 8, 8}.generate(g); auto weights = tensor<T>{64, 32, 5, 5}.generate(g); mlopen::ConvolutionDescriptor filter{1, 1}; verify_forward_conv(handle, input, weights, filter); } int main() { mlopen::Handle handle; auto g0 = [](int, int, int, int) { return 0; }; auto g1 = [](int, int, int, int) { return 1; }; auto g_id = [](int, int, int h, int w) { return h == w ? 1 : 0; }; auto g = [](int n, int c, int h, int w) { double x = (547*n+701*c+877*h+1049*w+173)%1223; return x/691.0; }; (void)g0; (void)g1; (void)g_id; (void)g; #if MLOPEN_TEST_ALL printf("verify_all\n"); verify_all<float>(handle, g0,g1, g_id, g); #else printf("verify_one\n"); verify_one<float>(handle, g); #endif } <commit_msg>Simplify forwarding<commit_after>#include <mlopen.h> #include "test.hpp" #include <vector> #include <array> #include <iterator> #include <algorithm> #include <numeric> #include <memory> #include <utility> #include <iostream> #include <cmath> #include <mlopen/tensor.hpp> #include <mlopen/convolution.hpp> #include <mlopen/returns.hpp> #include <mlopen/each_args.hpp> #include <limits> #include <thread> #include "network_data.hpp" template<class F> struct protect_fn { F f; protect_fn(F x) : f(std::move(x)) {} template<class... Ts> auto operator()(Ts&&... xs) const MLOPEN_RETURNS (f(std::forward<Ts>(xs)...)); }; template<class F> protect_fn<F> protect(F f) { return {std::move(f)}; } template<class F> void par_for(int n, F f) { const auto threadsize = std::thread::hardware_concurrency(); if (n < threadsize) { for(int i=0;i<n;i++) f(i); } else { std::vector<std::thread> threads(threadsize); const int grainsize = n / threads.size(); int work = 0; std::generate(threads.begin(), threads.end(), [&] { int start = work; int last = std::min(n, work+grainsize); // std::cout << "work, last: " << work << ", " << last << std::endl; assert((last - start) <= grainsize); assert((last - start) > 0); auto result = std::thread([&f, start, last] { for(int i=start;i<last;i++) { f(i); } }); work += grainsize; return result; }); // TODO: Should be in destructor for(auto&& t:threads) { if (t.joinable()) t.join(); } } } // Multidimensional for loop struct ford_impl { template<class F, class T> void operator()(F f, T x) const { for(T i=0;i<x;i++) f(i); } template<class F, class T, class... Ts> void operator()(F f, T x, Ts... xs) const { #if (defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9) // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914 // This reverses the order of evaluation (*this)([&](Ts... is) { (*this)(std::bind(protect(f), std::placeholders::_1, is...), x); }, xs...); #else (*this)([&](T i) { (*this)([&](Ts... is) { f(i, is...); }, xs...); }, x); #endif } }; template<class... Ts> auto ford(Ts... xs) MLOPEN_RETURNS ( std::bind(ford_impl{}, std::placeholders::_1, xs...) ); struct par_ford_impl { template<class F, class T, class... Ts> void operator()(F f, T x, Ts... xs) const { #if (defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9) // No parallelism for gcc 4.8 ford(x, xs...)(f); #else par_for(x, [&](T i) { ford(xs...)([&](Ts... is) { f(i, is...); }); }); #endif } }; template<class... Ts> auto par_ford(Ts... xs) MLOPEN_RETURNS ( std::bind(par_ford_impl{}, std::placeholders::_1, xs...) ); template<class T> struct tensor { mlopen::TensorDescriptor desc; std::vector<T> data; tensor(int n, int c, int h, int w) : desc(mlopenFloat, {n,c,h,w}), data(n*c*h*w) {} tensor(mlopen::TensorDescriptor rhs) : desc(std::move(rhs)) { data.resize(desc.GetElementSize()); } template<class G> tensor& generate(G g) & { this->generate_impl(g); return *this; } template<class G> tensor&& generate(G g) && { this->generate_impl(g); return std::move(*this); } template<class G> void generate_impl(G g) { auto iterator = data.begin(); this->for_each([&](int i, int j, int k, int m) { assert(iterator < data.end()); *iterator = g(i, j, k, m); ++iterator; }); } template<class F> void for_each(F f) const { int n, c, h, w; std::tie(n, c, h, w) = mlopen::tie4(desc.GetLengths()); ford(n, c, h, w)(std::move(f)); } template<class F> void par_for_each(F f) const { int n, c, h, w; std::tie(n, c, h, w) = mlopen::tie4(desc.GetLengths()); par_ford(n, c, h, w)(std::move(f)); } T& operator()(int n, int c, int h, int w) { assert(this->desc.GetIndex(n, c, h, w) < data.size()); return this->data[this->desc.GetIndex(n, c, h, w)]; } const T& operator()(int n, int c, int h, int w) const { assert(this->desc.GetIndex(n, c, h, w) < data.size()); return this->data[this->desc.GetIndex(n, c, h, w)]; } }; struct tensor_generate { template<class Tensor, class G> Tensor&& operator()(Tensor&& t, G g) const { return std::forward<Tensor>(t.generate(g)); } }; template<class T> tensor<T> get_output_tensor(const mlopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& weights) { return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)}; } template<class T> std::vector<T> forward_conv(const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int bias = 0) { auto out = get_output_tensor(filter, input, weights); int in_n, in_c, in_h, in_w; std::tie(in_n, in_c, in_h, in_w) = mlopen::tie4(input.desc.GetLengths()); int wei_h, wei_w; std::tie(std::ignore, std::ignore, wei_h, wei_w) = mlopen::tie4(weights.desc.GetLengths()); out.par_for_each([&](int o, int w, int i, int j) { int in_off_h = i * filter.v; int in_off_w = j * filter.u; T acc = bias; ford(in_c, wei_h, wei_w)([&](int k, int x, int y) { int in_x = in_off_h - filter.pad_h + x; int in_y = in_off_w - filter.pad_w + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * weights(w, k, x, y); } }); out(o, w, i, j) = acc; }); return out.data; } template<class T> std::vector<T> forward_conv(mlopen::Handle& handle, const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int /* bias */ = 0) { auto out = get_output_tensor(filter, input, weights); auto in_dev = handle.Write(input.data); auto wei_dev = handle.Write(weights.data); auto out_dev = handle.Create<T>(out.data.size()); int ret_algo_count; mlopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvFwdAlgorithm(handle, input.desc, in_dev.get(), weights.desc, wei_dev.get(), out.desc, out_dev.get(), 1, &ret_algo_count, &perf, mlopenConvolutionFastest, NULL, 10, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionForward(handle, &alpha, input.desc, in_dev.get(), weights.desc, wei_dev.get(), mlopenConvolutionFwdAlgoDirect, &beta, out.desc, out_dev.get(), NULL, 0); out.data = handle.Read<T>(out_dev, out.data.size()); return out.data; } struct float_equal_fn { template<class T> bool operator()(T x, T y) const { return std::fabs(x - y) < std::max(std::numeric_limits<T>::epsilon() * std::max(x, y), std::numeric_limits<T>::epsilon()); } }; template<class R1, class R2> bool float_equal_range(R1&& r1, R2&& r2) { return std::distance(r1.begin(), r1.end()) == std::distance(r2.begin(), r2.end()) && std::equal(r1.begin(), r1.end(), r2.begin(), float_equal_fn{}); } template<class R1, class R2, class Op> float accumulate_difference(R1&& r1, R2&& r2, Op op) { return std::inner_product(r1.begin(), r1.end(), r2.begin(), 0.0, op, [](float x, float y) { return std::fabs(x - y); } ); } template<class T> void verify_forward_conv(mlopen::Handle& handle, const tensor<T>& input, const tensor<T>& weights, const mlopen::ConvolutionDescriptor& filter, int bias = 0) { auto out_cpu = forward_conv(input, weights, filter, bias); auto out_gpu = forward_conv(handle, input, weights, filter, bias); int size = std::distance(out_cpu.begin(), out_cpu.end()); CHECK(std::distance(out_cpu.begin(), out_cpu.end()) == std::distance(out_gpu.begin(), out_gpu.end())); if (!float_equal_range(out_cpu, out_gpu)) { std::cout << "FAILED: " << std::endl; std::cout << "Average difference: " << (accumulate_difference(out_cpu, out_gpu, std::plus<float>()) / size) << std::endl; std::cout << "Max difference: " << (accumulate_difference(out_cpu, out_gpu, [](float x, float y) { return std::max(x, y); })) << std::endl; } // CHECK(out_cpu == out_gpu); } struct cross_args_apply { template<class F, class T, class... Ts> void operator()(F f, T&& x, Ts&&... xs) const { mlopen::each_args(std::bind(f, std::forward<T>(x), std::placeholders::_1), std::forward<Ts>(xs)...); } }; template<class F, class... Ts> void cross_args(F f, Ts&&... xs) { mlopen::each_args( std::bind(cross_args_apply{}, protect(std::move(f)), std::placeholders::_1, std::forward<Ts>(xs)...), std::forward<Ts>(xs)...); } template<class T> struct verify_both { template<class G1, class G2> void operator()(mlopen::Handle& handle, G1 g1, G2 g2) const { visit_network<T>([&](mlopen::TensorDescriptor input_desc, mlopen::TensorDescriptor weights_desc) { auto input = tensor<T>{std::move(input_desc)}.generate(g1); auto weights = tensor<T>{std::move(weights_desc)}.generate(g2); mlopen::ConvolutionDescriptor filter{1, 1}; std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; verify_forward_conv(handle, input, weights, filter); }); } }; template<class T, class... Gs> void verify_all(mlopen::Handle& handle, Gs... gs) { cross_args( std::bind(verify_both<T>{}, std::ref(handle), std::placeholders::_1, std::placeholders::_2), gs...); } template<class T, class G> void verify_one(mlopen::Handle& handle, G g) { auto input = tensor<T>{16, 32, 8, 8}.generate(g); auto weights = tensor<T>{64, 32, 5, 5}.generate(g); mlopen::ConvolutionDescriptor filter{1, 1}; verify_forward_conv(handle, input, weights, filter); } int main() { mlopen::Handle handle; auto g0 = [](int, int, int, int) { return 0; }; auto g1 = [](int, int, int, int) { return 1; }; auto g_id = [](int, int, int h, int w) { return h == w ? 1 : 0; }; auto g = [](int n, int c, int h, int w) { double x = (547*n+701*c+877*h+1049*w+173)%1223; return x/691.0; }; (void)g0; (void)g1; (void)g_id; (void)g; #if MLOPEN_TEST_ALL printf("verify_all\n"); verify_all<float>(handle, g0,g1, g_id, g); #else printf("verify_one\n"); verify_one<float>(handle, g); #endif } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "tcframe_test_commons.cpp" #include "tcframe/problem.hpp" using tcframe::BaseProblem; class MyProblem : public BaseProblem { protected: void Config() { setSlug("foo"); setTimeLimit(2); setMemoryLimit(256); } void InputFormat() { } void OutputFormat() { } }; TEST(ProblemTest, DefaultOptions) { BaseProblem* problem = new DefaultProblem(); EXPECT_EQ("problem", problem->getSlug()); EXPECT_EQ(0, problem->getTimeLimit()); EXPECT_EQ(0, problem->getMemoryLimit()); } TEST(ProblemTest, MyOptions) { BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); EXPECT_EQ("foo", problem->getSlug()); EXPECT_EQ(2, problem->getTimeLimit()); EXPECT_EQ(256, problem->getMemoryLimit()); } <commit_msg>Add Problem's command-line options tests<commit_after>#include "gtest/gtest.h" #include "tcframe_test_commons.cpp" #include "tcframe/problem.hpp" using tcframe::BaseProblem; class MyProblem : public BaseProblem { protected: void Config() { setSlug("foo"); setTimeLimit(2); setMemoryLimit(256); } void InputFormat() { } void OutputFormat() { } }; TEST(ProblemTest, DefaultOptions) { BaseProblem* problem = new DefaultProblem(); EXPECT_EQ("problem", problem->getSlug()); EXPECT_EQ(0, problem->getTimeLimit()); EXPECT_EQ(0, problem->getMemoryLimit()); } TEST(ProblemTest, MyOptions) { BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); EXPECT_EQ("foo", problem->getSlug()); EXPECT_EQ(2, problem->getTimeLimit()); EXPECT_EQ(256, problem->getMemoryLimit()); } TEST(ProblemTest, CommandLineOptions) { char* argv[] = {(char*) "<runner>", (char*)"--slug=bar", (char*)"--time-limit=3", (char*)"--memory-limit=64"}; BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); problem->applyProblemCommandLineOptions(4, argv); EXPECT_EQ("bar", problem->getSlug()); EXPECT_EQ(3, problem->getTimeLimit()); EXPECT_EQ(64, problem->getMemoryLimit()); } TEST(ProblemTest, CommandLineOptionsWithNos) { char* argv[] = {(char*) "<runner>", (char*)"--no-time-limit", (char*)"--no-memory-limit"}; BaseProblem* problem = new MyProblem(); problem->applyProblemConfiguration(); problem->applyProblemCommandLineOptions(3, argv); EXPECT_EQ("foo", problem->getSlug()); EXPECT_EQ(0, problem->getTimeLimit()); EXPECT_EQ(0, problem->getMemoryLimit()); } <|endoftext|>
<commit_before>// Copyright 2016-2020 Francesco Biscani ([email protected]) // // This file is part of the mp++ library. // // 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 <cstdint> #include <tuple> #include <mp++/integer.hpp> #include <mp++/real128.hpp> #include "catch.hpp" using namespace mppp; using int_t = integer<1>; TEST_CASE("real128 get_ieee()") { std::uint_least8_t sign; std::uint_least16_t exp; std::uint_least64_t hi; std::uint_least64_t lo; std::tie(sign, exp, hi, lo) = real128{}.get_ieee(); REQUIRE(!sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128{-0.}.get_ieee(); REQUIRE(sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128{42}.get_ieee(); REQUIRE(!sign); REQUIRE(exp == 16388ul); REQUIRE(hi == 10ull << (48 - 5)); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128{-42}.get_ieee(); REQUIRE(sign); REQUIRE(exp == 16388ul); REQUIRE(hi == 10ull << (48 - 5)); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128_nan().get_ieee(); REQUIRE(exp == 32767ul); REQUIRE((!hi || !lo)); std::tie(sign, exp, hi, lo) = real128_inf().get_ieee(); REQUIRE(!sign); REQUIRE(exp == 32767ul); REQUIRE((!hi && !lo)); std::tie(sign, exp, hi, lo) = (-real128_inf()).get_ieee(); REQUIRE(sign); REQUIRE(exp == 32767ul); REQUIRE((!hi && !lo)); std::tie(sign, exp, hi, lo) = real128{"1.189731495357231765085759326628007e4932"}.get_ieee(); REQUIRE(!sign); REQUIRE(exp == 32766ul); REQUIRE(hi == std::uint_least64_t(-1) % (1ull << 48)); REQUIRE(lo == std::uint_least64_t(-1) % (int_t(1) << 64)); std::tie(sign, exp, hi, lo) = real128{"-1.189731495357231765085759326628007e4932"}.get_ieee(); REQUIRE(sign); REQUIRE(exp == 32766ul); REQUIRE(hi == std::uint_least64_t(-1) % (1ull << 48)); REQUIRE(lo == std::uint_least64_t(-1) % (int_t(1) << 64)); std::tie(sign, exp, hi, lo) = real128{"6.47517511943802511092443895822764655e-4966"}.get_ieee(); REQUIRE(!sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(lo == 1u); std::tie(sign, exp, hi, lo) = real128{"-6.47517511943802511092443895822764655e-4966"}.get_ieee(); REQUIRE(sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(lo == 1u); } <commit_msg>Fix bug in the real128 test suite.<commit_after>// Copyright 2016-2020 Francesco Biscani ([email protected]) // // This file is part of the mp++ library. // // 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 <cstdint> #include <tuple> #include <mp++/integer.hpp> #include <mp++/real128.hpp> #include "catch.hpp" using namespace mppp; using int_t = integer<1>; TEST_CASE("real128 get_ieee()") { std::uint_least8_t sign; std::uint_least16_t exp; std::uint_least64_t hi; std::uint_least64_t lo; std::tie(sign, exp, hi, lo) = real128{}.get_ieee(); REQUIRE(!sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128{-0.}.get_ieee(); REQUIRE(sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128{42}.get_ieee(); REQUIRE(!sign); REQUIRE(exp == 16388ul); REQUIRE(hi == 10ull << (48 - 5)); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128{-42}.get_ieee(); REQUIRE(sign); REQUIRE(exp == 16388ul); REQUIRE(hi == 10ull << (48 - 5)); REQUIRE(!lo); std::tie(sign, exp, hi, lo) = real128_nan().get_ieee(); REQUIRE(exp == 32767ul); REQUIRE((hi || lo)); std::tie(sign, exp, hi, lo) = real128_inf().get_ieee(); REQUIRE(!sign); REQUIRE(exp == 32767ul); REQUIRE((!hi && !lo)); std::tie(sign, exp, hi, lo) = (-real128_inf()).get_ieee(); REQUIRE(sign); REQUIRE(exp == 32767ul); REQUIRE((!hi && !lo)); std::tie(sign, exp, hi, lo) = real128{"1.189731495357231765085759326628007e4932"}.get_ieee(); REQUIRE(!sign); REQUIRE(exp == 32766ul); REQUIRE(hi == std::uint_least64_t(-1) % (1ull << 48)); REQUIRE(lo == std::uint_least64_t(-1) % (int_t(1) << 64)); std::tie(sign, exp, hi, lo) = real128{"-1.189731495357231765085759326628007e4932"}.get_ieee(); REQUIRE(sign); REQUIRE(exp == 32766ul); REQUIRE(hi == std::uint_least64_t(-1) % (1ull << 48)); REQUIRE(lo == std::uint_least64_t(-1) % (int_t(1) << 64)); std::tie(sign, exp, hi, lo) = real128{"6.47517511943802511092443895822764655e-4966"}.get_ieee(); REQUIRE(!sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(lo == 1u); std::tie(sign, exp, hi, lo) = real128{"-6.47517511943802511092443895822764655e-4966"}.get_ieee(); REQUIRE(sign); REQUIRE(!exp); REQUIRE(!hi); REQUIRE(lo == 1u); } <|endoftext|>
<commit_before>#include "MS5837.h" #include <Wire.h> #define MS5837_ADDR 0x76 #define MS5837_RESET 0x1E #define MS5837_ADC_READ 0x00 #define MS5837_PROM_READ 0xA0 #define MS5837_CONVERT_D1_8192 0x4A #define MS5837_CONVERT_D2_8192 0x5A const float MS5837::Pa = 100.0f; const float MS5837::bar = 0.001f; const float MS5837::mbar = 1.0f; const uint8_t MS5837::MS5837_30BA = 0; const uint8_t MS5837::MS5837_02BA = 1; MS5837::MS5837() { fluidDensity = 1029; } bool MS5837::init() { // Reset the MS5837, per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_RESET); Wire.endTransmission(); // Wait for reset to complete delay(10); // Read calibration values and CRC for ( uint8_t i = 0 ; i < 7 ; i++ ) { Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_PROM_READ+i*2); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,2); C[i] = (Wire.read() << 8) | Wire.read(); } // Verify that data is correct with CRC uint8_t crcRead = C[0] >> 12; uint8_t crcCalculated = crc4(C); if ( crcCalculated == crcRead ) { return true; // Initialization success } return false; // CRC fail } void MS5837::setModel(uint8_t model) { _model = model; } void MS5837::setFluidDensity(float density) { fluidDensity = density; } void MS5837::read() { // Request D1 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D1_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D1 = 0; D1 = Wire.read(); D1 = (D1 << 8) | Wire.read(); D1 = (D1 << 8) | Wire.read(); // Request D2 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D2_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D2 = 0; D2 = Wire.read(); D2 = (D2 << 8) | Wire.read(); D2 = (D2 << 8) | Wire.read(); calculate(); } void MS5837::calculate() { // Given C1-C6 and D1, D2, calculated TEMP and P // Do conversion first and then second order temp compensation int32_t dT = 0; int64_t SENS = 0; int64_t OFF = 0; int32_t SENSi = 0; int32_t OFFi = 0; int32_t Ti = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Terms called dT = D2-uint32_t(C[5])*256l; if ( _model == MS5837_02BA ) { SENS = int64_t(C[1])*65536l+(int64_t(C[3])*dT)/128l; OFF = int64_t(C[2])*131072l+(int64_t(C[4])*dT)/64l; P = (D1*SENS/(2097152l)-OFF)/(32768l); } else { SENS = int64_t(C[1])*32768l+(int64_t(C[3])*dT)/256l; OFF = int64_t(C[2])*65536l+(int64_t(C[4])*dT)/128l; P = (D1*SENS/(2097152l)-OFF)/(8192l); } // Temp conversion TEMP = 2000l+int64_t(dT)*C[6]/8388608LL; //Second order compensation if ( _model == MS5837_02BA ) { if((TEMP/100)<20){ //Low temp Ti = (11*int64_t(dT)*int64_t(dT))/(34359738368LL); OFFi = (31*(TEMP-2000)*(TEMP-2000))/8; SENSi = (63*(TEMP-2000)*(TEMP-2000))/32; } } else { if((TEMP/100)<20){ //Low temp Ti = (3*int64_t(dT)*int64_t(dT))/(8589934592LL); OFFi = (3*(TEMP-2000)*(TEMP-2000))/2; SENSi = (5*(TEMP-2000)*(TEMP-2000))/8; if((TEMP/100)<-15){ //Very low temp OFFi = OFFi+7*(TEMP+1500l)*(TEMP+1500l); SENSi = SENSi+4*(TEMP+1500l)*(TEMP+1500l); } } else if((TEMP/100)>=20){ //High temp Ti = 2*(dT*dT)/(137438953472LL); OFFi = (1*(TEMP-2000)*(TEMP-2000))/16; SENSi = 0; } } OFF2 = OFF-OFFi; //Calculate pressure and temp second order SENS2 = SENS-SENSi; TEMP = (TEMP-Ti); if ( _model == MS5837_02BA ) { P = (((D1*SENS2)/2097152l-OFF2)/32768l); } else { P = (((D1*SENS2)/2097152l-OFF2)/8192l); } } float MS5837::pressure(float conversion) { if ( _model == MS5837_02BA ) { return P*conversion/100.0f; } else { return P*conversion/10.0f; } } float MS5837::temperature() { return TEMP/100.0f; } float MS5837::depth() { return (pressure(MS5837::Pa)-101300)/(fluidDensity*9.80665); } float MS5837::altitude() { return (1-pow((pressure()/1013.25),.190284))*145366.45*.3048; } uint8_t MS5837::crc4(uint16_t n_prom[]) { uint16_t n_rem = 0; n_prom[0] = ((n_prom[0]) & 0x0FFF); n_prom[7] = 0; for ( uint8_t i = 0 ; i < 16; i++ ) { if ( i%2 == 1 ) { n_rem ^= (uint16_t)((n_prom[i>>1]) & 0x00FF); } else { n_rem ^= (uint16_t)(n_prom[i>>1] >> 8); } for ( uint8_t n_bit = 8 ; n_bit > 0 ; n_bit-- ) { if ( n_rem & 0x8000 ) { n_rem = (n_rem << 1) ^ 0x3000; } else { n_rem = (n_rem << 1); } } } n_rem = ((n_rem >> 12) & 0x000F); return n_rem ^ 0x00; } <commit_msg>ms5837: add comment about depth calculation<commit_after>#include "MS5837.h" #include <Wire.h> #define MS5837_ADDR 0x76 #define MS5837_RESET 0x1E #define MS5837_ADC_READ 0x00 #define MS5837_PROM_READ 0xA0 #define MS5837_CONVERT_D1_8192 0x4A #define MS5837_CONVERT_D2_8192 0x5A const float MS5837::Pa = 100.0f; const float MS5837::bar = 0.001f; const float MS5837::mbar = 1.0f; const uint8_t MS5837::MS5837_30BA = 0; const uint8_t MS5837::MS5837_02BA = 1; MS5837::MS5837() { fluidDensity = 1029; } bool MS5837::init() { // Reset the MS5837, per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_RESET); Wire.endTransmission(); // Wait for reset to complete delay(10); // Read calibration values and CRC for ( uint8_t i = 0 ; i < 7 ; i++ ) { Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_PROM_READ+i*2); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,2); C[i] = (Wire.read() << 8) | Wire.read(); } // Verify that data is correct with CRC uint8_t crcRead = C[0] >> 12; uint8_t crcCalculated = crc4(C); if ( crcCalculated == crcRead ) { return true; // Initialization success } return false; // CRC fail } void MS5837::setModel(uint8_t model) { _model = model; } void MS5837::setFluidDensity(float density) { fluidDensity = density; } void MS5837::read() { // Request D1 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D1_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D1 = 0; D1 = Wire.read(); D1 = (D1 << 8) | Wire.read(); D1 = (D1 << 8) | Wire.read(); // Request D2 conversion Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_CONVERT_D2_8192); Wire.endTransmission(); delay(20); // Max conversion time per datasheet Wire.beginTransmission(MS5837_ADDR); Wire.write(MS5837_ADC_READ); Wire.endTransmission(); Wire.requestFrom(MS5837_ADDR,3); D2 = 0; D2 = Wire.read(); D2 = (D2 << 8) | Wire.read(); D2 = (D2 << 8) | Wire.read(); calculate(); } void MS5837::calculate() { // Given C1-C6 and D1, D2, calculated TEMP and P // Do conversion first and then second order temp compensation int32_t dT = 0; int64_t SENS = 0; int64_t OFF = 0; int32_t SENSi = 0; int32_t OFFi = 0; int32_t Ti = 0; int64_t OFF2 = 0; int64_t SENS2 = 0; // Terms called dT = D2-uint32_t(C[5])*256l; if ( _model == MS5837_02BA ) { SENS = int64_t(C[1])*65536l+(int64_t(C[3])*dT)/128l; OFF = int64_t(C[2])*131072l+(int64_t(C[4])*dT)/64l; P = (D1*SENS/(2097152l)-OFF)/(32768l); } else { SENS = int64_t(C[1])*32768l+(int64_t(C[3])*dT)/256l; OFF = int64_t(C[2])*65536l+(int64_t(C[4])*dT)/128l; P = (D1*SENS/(2097152l)-OFF)/(8192l); } // Temp conversion TEMP = 2000l+int64_t(dT)*C[6]/8388608LL; //Second order compensation if ( _model == MS5837_02BA ) { if((TEMP/100)<20){ //Low temp Ti = (11*int64_t(dT)*int64_t(dT))/(34359738368LL); OFFi = (31*(TEMP-2000)*(TEMP-2000))/8; SENSi = (63*(TEMP-2000)*(TEMP-2000))/32; } } else { if((TEMP/100)<20){ //Low temp Ti = (3*int64_t(dT)*int64_t(dT))/(8589934592LL); OFFi = (3*(TEMP-2000)*(TEMP-2000))/2; SENSi = (5*(TEMP-2000)*(TEMP-2000))/8; if((TEMP/100)<-15){ //Very low temp OFFi = OFFi+7*(TEMP+1500l)*(TEMP+1500l); SENSi = SENSi+4*(TEMP+1500l)*(TEMP+1500l); } } else if((TEMP/100)>=20){ //High temp Ti = 2*(dT*dT)/(137438953472LL); OFFi = (1*(TEMP-2000)*(TEMP-2000))/16; SENSi = 0; } } OFF2 = OFF-OFFi; //Calculate pressure and temp second order SENS2 = SENS-SENSi; TEMP = (TEMP-Ti); if ( _model == MS5837_02BA ) { P = (((D1*SENS2)/2097152l-OFF2)/32768l); } else { P = (((D1*SENS2)/2097152l-OFF2)/8192l); } } float MS5837::pressure(float conversion) { if ( _model == MS5837_02BA ) { return P*conversion/100.0f; } else { return P*conversion/10.0f; } } float MS5837::temperature() { return TEMP/100.0f; } // The pressure sensor measures absolute pressure, so it will measure the atmospheric pressure + water pressure // We subtract the atmospheric pressure to calculate the depth with only the water pressure // The average atmospheric pressure of 101300 pascal is used for the calcuation, but atmospheric pressure varies // If the atmospheric pressure is not 101300 at the time of reading, the depth reported will be offset // In order to calculate the correct depth, the actual atmospheric pressure should be measured once in air, and // that value should subtracted for subsequent depth calculations. float MS5837::depth() { return (pressure(MS5837::Pa)-101300)/(fluidDensity*9.80665); } float MS5837::altitude() { return (1-pow((pressure()/1013.25),.190284))*145366.45*.3048; } uint8_t MS5837::crc4(uint16_t n_prom[]) { uint16_t n_rem = 0; n_prom[0] = ((n_prom[0]) & 0x0FFF); n_prom[7] = 0; for ( uint8_t i = 0 ; i < 16; i++ ) { if ( i%2 == 1 ) { n_rem ^= (uint16_t)((n_prom[i>>1]) & 0x00FF); } else { n_rem ^= (uint16_t)(n_prom[i>>1] >> 8); } for ( uint8_t n_bit = 8 ; n_bit > 0 ; n_bit-- ) { if ( n_rem & 0x8000 ) { n_rem = (n_rem << 1) ^ 0x3000; } else { n_rem = (n_rem << 1); } } } n_rem = ((n_rem >> 12) & 0x000F); return n_rem ^ 0x00; } <|endoftext|>
<commit_before>// This is free and unencumbered software released into the public domain. // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // For more information, please refer to <http://unlicense.org/> // C++ implementation of Dmitry Vyukov's non-intrusive lock free unbounded MPSC queue // http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue /* * File: MPSCQueue.hpp * Author: Barath Kannan * This is an adaptation of https://github.com/mstump/queues/blob/master/include/mpsc-queue.hpp * The queue has been modified such that it can also be used as a blocking queue * Aligned storage was removed, was causing segmentation faults and didn't improve performance * Created on 14 June 2016, 1:14 AM */ #ifndef MPSCQUEUE_HPP #define MPSCQUEUE_HPP #include <atomic> #include <shared_mutex> #include <condition_variable> #include <chrono> #include <thread> #include <assert.h> namespace BSignals{ namespace details{ template<typename T> class MPSCQueue{ public: MPSCQueue() : _head(new buffer_node_t), _tail(_head.load(std::memory_order_relaxed)){ buffer_node_t* front = _head.load(std::memory_order_relaxed); front->next.store(nullptr, std::memory_order_relaxed); } ~MPSCQueue(){ T output; while (this->dequeue(output)) {} buffer_node_t* front = _head.load(std::memory_order_relaxed); delete front; } void enqueue(const T& input){ buffer_node_t* node = (new buffer_node_t); node->data = input; node->next.store(nullptr, std::memory_order_relaxed); buffer_node_t* prev_head = _head.exchange(node, std::memory_order_acq_rel); prev_head->next.store(node, std::memory_order_release); std::shared_lock<std::shared_timed_mutex> lock(_mutex); if (waitingReader){ _cv.notify_one(); } } bool dequeue(T& output){ buffer_node_t* tail = _tail.load(std::memory_order_relaxed); buffer_node_t* next = tail->next.load(std::memory_order_acquire); if (next == nullptr) { return false; } output = next->data; _tail.store(next, std::memory_order_release); delete tail; return true; } void blockingDequeue(T& output){ std::unique_lock<std::shared_timed_mutex> lock(_mutex); waitingReader = true; while (!dequeue(output)){ _cv.wait(lock); } waitingReader = false; } private: struct buffer_node_t{ T data; std::atomic<buffer_node_t*> next; }; std::atomic<buffer_node_t*> _head; std::atomic<buffer_node_t*> _tail; std::shared_timed_mutex _mutex; std::condition_variable_any _cv; bool waitingReader{false}; MPSCQueue(const MPSCQueue&) {} void operator=(const MPSCQueue&) {} }; }} #endif <commit_msg>clean up, format consistency<commit_after>// This is free and unencumbered software released into the public domain. // Anyone is free to copy, modify, publish, use, compile, sell, or // distribute this software, either in source code form or as a compiled // binary, for any purpose, commercial or non-commercial, and by any // means. // In jurisdictions that recognize copyright laws, the author or authors // of this software dedicate any and all copyright interest in the // software to the public domain. We make this dedication for the benefit // of the public at large and to the detriment of our heirs and // successors. We intend this dedication to be an overt act of // relinquishment in perpetuity of all present and future rights to this // software under copyright law. // 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR // OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // For more information, please refer to <http://unlicense.org/> // C++ implementation of Dmitry Vyukov's non-intrusive lock free unbounded MPSC queue // http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue /* * File: MPSCQueue.hpp * Author: Barath Kannan * This is an adaptation of https://github.com/mstump/queues/blob/master/include/mpsc-queue.hpp * The queue has been modified such that it can also be used as a blocking queue * Aligned storage was removed, was causing segmentation faults and didn't improve performance * Created on 14 June 2016, 1:14 AM */ #ifndef MPSCQUEUE_HPP #define MPSCQUEUE_HPP #include <atomic> #include <shared_mutex> #include <condition_variable> #include <chrono> #include <thread> #include <assert.h> namespace BSignals{ namespace details{ template<typename T> class MPSCQueue{ public: MPSCQueue() : _head(new listNode), _tail(_head.load(std::memory_order_relaxed)){} ~MPSCQueue(){ T output; while (this->dequeue(output)) {} listNode* front = _head.load(std::memory_order_relaxed); delete front; } void enqueue(const T& input){ listNode* node = new listNode{input}; listNode* prev_head = _head.exchange(node, std::memory_order_acq_rel); prev_head->next.store(node, std::memory_order_release); std::shared_lock<std::shared_timed_mutex> lock(_mutex); if (waitingReader) _cv.notify_one(); } bool dequeue(T& output){ listNode* tail = _tail.load(std::memory_order_relaxed); listNode* next = tail->next.load(std::memory_order_acquire); if (next == nullptr) return false; output = next->data; _tail.store(next, std::memory_order_release); delete tail; return true; } void blockingDequeue(T& output){ std::unique_lock<std::shared_timed_mutex> lock(_mutex); waitingReader = true; while (!dequeue(output)){ _cv.wait(lock); } waitingReader = false; } private: struct listNode{ T data; std::atomic<listNode*> next{nullptr}; }; std::atomic<listNode*> _head; std::atomic<listNode*> _tail; std::shared_timed_mutex _mutex; std::condition_variable_any _cv; bool waitingReader{false}; MPSCQueue(const MPSCQueue&) {} void operator=(const MPSCQueue&) {} }; }} #endif <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Algorithm.hpp> #include <string> // Functions args bool NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<bool>) { return instance.CheckBoolean(index); } double NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<double>) { return instance.CheckNumber(index); } float NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<float>) { return instance.CheckNumber(index); } int NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<int>) { return instance.CheckInteger(index); } std::string NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<std::string>) { return instance.CheckString(index); } NzString NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<NzString>) { return instance.CheckString(index); } template<typename T> T NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<const T&>) { return NzLuaImplQueryArg(instance, index, NzTypeTag<T>()); } template<typename T> std::enable_if_t<std::is_unsigned<T>::value, T> NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<T>) { return static_cast<T>(NzLuaImplQueryArg(instance, index, NzTypeTag<typename std::make_signed<T>::type>())); } // Function returns int NzLuaImplReplyVal(NzLuaInstance& instance, bool&& val, NzTypeTag<bool>) { instance.PushBoolean(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, double&& val, NzTypeTag<double>) { instance.PushNumber(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, float&& val, NzTypeTag<float>) { instance.PushNumber(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, int&& val, NzTypeTag<int>) { instance.PushInteger(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, std::string&& val, NzTypeTag<std::string>) { instance.PushString(val.c_str(), val.size()); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, NzString&& val, NzTypeTag<NzString>) { instance.PushString(std::move(val)); return 1; } template<typename T1, typename T2> int NzLuaImplReplyVal(NzLuaInstance& instance, std::pair<T1, T2>&& val, NzTypeTag<std::pair<T1, T2>>) { int retVal = 0; retVal += NzLuaImplReplyVal(instance, std::move(val.first), NzTypeTag<T1>()); retVal += NzLuaImplReplyVal(instance, std::move(val.second), NzTypeTag<T2>()); return retVal; } template<typename T> std::enable_if_t<std::is_unsigned<T>::value, int> NzLuaImplReplyVal(NzLuaInstance& instance, T&& val, NzTypeTag<T>) { using SignedT = typename std::make_signed<T>::type; return NzLuaImplReplyVal(instance, val, NzTypeTag<SignedT>()); } template<typename... Args> class NzLuaImplFunctionProxy { public: NzLuaImplFunctionProxy(NzLuaInstance& instance) : m_instance(instance) { } template<unsigned int N, typename ArgType> void ProcessArgs() { std::get<N>(m_args) = std::move(NzLuaImplQueryArg(m_instance, N+1, NzTypeTag<ArgType>())); } template<int N, typename ArgType1, typename ArgType2, typename... Rest> void ProcessArgs() { ProcessArgs<N, ArgType1>(); ProcessArgs<N+1, ArgType2, Rest...>(); } void ProcessArgs() { ProcessArgs<0, Args...>(); } int Invoke(void (*func)(Args...)) { NzApply(func, m_args); return 0; } template<typename Ret> int Invoke(Ret (*func)(Args...)) { return NzLuaImplReplyVal(m_instance, std::move(NzApply(func, m_args)), NzTypeTag<decltype(NzApply(func, m_args))>()); } private: NzLuaInstance& m_instance; std::tuple<Args...> m_args; }; template<typename R, typename... Args> void NzLuaInstance::PushFunction(R(*func)(Args...)) { PushFunction([func](NzLuaInstance& instance) -> int { NzLuaImplFunctionProxy<Args...> handler(instance); handler.ProcessArgs(); return handler.Invoke(func); }); } <commit_msg>Lua/LuaInstance: Fix warning + optimizations<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Lua scripting module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Algorithm.hpp> #include <string> // Functions args bool NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<bool>) { return instance.CheckBoolean(index); } double NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<double>) { return instance.CheckNumber(index); } float NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<float>) { return static_cast<float>(instance.CheckNumber(index)); } int NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<int>) { return static_cast<int>(instance.CheckInteger(index)); } std::string NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<std::string>) { std::size_t strLength = 0; const char* str = instance.CheckString(index, &strLength); return std::string(str, strLength); } NzString NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<NzString>) { std::size_t strLength = 0; const char* str = instance.CheckString(index, &strLength); return NzString(str, strLength); } template<typename T> T NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<const T&>) { return NzLuaImplQueryArg(instance, index, NzTypeTag<T>()); } template<typename T> std::enable_if_t<std::is_unsigned<T>::value, T> NzLuaImplQueryArg(NzLuaInstance& instance, unsigned int index, NzTypeTag<T>) { return static_cast<T>(NzLuaImplQueryArg(instance, index, NzTypeTag<typename std::make_signed<T>::type>())); } // Function returns int NzLuaImplReplyVal(NzLuaInstance& instance, bool&& val, NzTypeTag<bool>) { instance.PushBoolean(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, double&& val, NzTypeTag<double>) { instance.PushNumber(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, float&& val, NzTypeTag<float>) { instance.PushNumber(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, int&& val, NzTypeTag<int>) { instance.PushInteger(val); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, std::string&& val, NzTypeTag<std::string>) { instance.PushString(val.c_str(), val.size()); return 1; } int NzLuaImplReplyVal(NzLuaInstance& instance, NzString&& val, NzTypeTag<NzString>) { instance.PushString(std::move(val)); return 1; } template<typename T1, typename T2> int NzLuaImplReplyVal(NzLuaInstance& instance, std::pair<T1, T2>&& val, NzTypeTag<std::pair<T1, T2>>) { int retVal = 0; retVal += NzLuaImplReplyVal(instance, std::move(val.first), NzTypeTag<T1>()); retVal += NzLuaImplReplyVal(instance, std::move(val.second), NzTypeTag<T2>()); return retVal; } template<typename T> std::enable_if_t<std::is_unsigned<T>::value, int> NzLuaImplReplyVal(NzLuaInstance& instance, T&& val, NzTypeTag<T>) { using SignedT = typename std::make_signed<T>::type; return NzLuaImplReplyVal(instance, val, NzTypeTag<SignedT>()); } template<typename... Args> class NzLuaImplFunctionProxy { public: NzLuaImplFunctionProxy(NzLuaInstance& instance) : m_instance(instance) { } template<unsigned int N, typename ArgType> void ProcessArgs() { std::get<N>(m_args) = std::move(NzLuaImplQueryArg(m_instance, N+1, NzTypeTag<ArgType>())); } template<int N, typename ArgType1, typename ArgType2, typename... Rest> void ProcessArgs() { ProcessArgs<N, ArgType1>(); ProcessArgs<N+1, ArgType2, Rest...>(); } void ProcessArgs() { ProcessArgs<0, Args...>(); } int Invoke(void (*func)(Args...)) { NzApply(func, m_args); return 0; } template<typename Ret> int Invoke(Ret (*func)(Args...)) { return NzLuaImplReplyVal(m_instance, std::move(NzApply(func, m_args)), NzTypeTag<decltype(NzApply(func, m_args))>()); } private: NzLuaInstance& m_instance; std::tuple<Args...> m_args; }; template<typename R, typename... Args> void NzLuaInstance::PushFunction(R(*func)(Args...)) { PushFunction([func](NzLuaInstance& instance) -> int { NzLuaImplFunctionProxy<Args...> handler(instance); handler.ProcessArgs(); return handler.Invoke(func); }); } <|endoftext|>
<commit_before><commit_msg>coverity#1269591 Uncaught exception<commit_after><|endoftext|>
<commit_before>#pragma once #include "clam/config.h" namespace clam { //// // Base numerical domains for user options //// enum CrabDomain { INTERVALS , INTERVALS_CONGRUENCES , BOXES , DIS_INTERVALS /*, ZONES_SPARSE_DBM*/ , ZONES_SPLIT_DBM , TERMS_INTERVALS , TERMS_DIS_INTERVALS //TERMS_INTERVALS x ZONES_SPLIT_DBM , TERMS_ZONES //(#live vars<threshold ? TERMS_INTERVALSxZONES_SPLIT_DBM, INTERVALS) , ADAPT_TERMS_ZONES , OCT , PK , WRAPPED_INTERVALS }; //// // Kind of checker //// enum assert_check_kind_t { NOCHECKS = 0, ASSERTION = 1, NULLITY = 2 }; /** * Class to set analysis options **/ struct AnalysisParams { CrabDomain dom; #ifndef TOP_DOWN_INTER_ANALYSIS CrabDomain sum_dom; #endif bool run_backward; bool run_liveness; bool run_inter; #ifdef TOP_DOWN_INTER_ANALYSIS unsigned int max_calling_contexts; #endif unsigned relational_threshold; unsigned widening_delay; unsigned narrowing_iters; unsigned widening_jumpset; bool stats; bool print_invars; bool print_preconds; bool print_unjustified_assumptions; bool print_summaries; bool store_invariants; bool keep_shadow_vars; assert_check_kind_t check; unsigned check_verbose; AnalysisParams() : dom(INTERVALS), #ifndef TOP_DOWN_INTER_ANALYSIS sum_dom(ZONES_SPLIT_DBM), #endif run_backward(false), run_liveness(false), run_inter(false), #ifdef TOP_DOWN_INTER_ANALYSIS max_calling_contexts(UINT_MAX), #endif relational_threshold(10000), widening_delay(1), narrowing_iters(10), widening_jumpset(0), stats(false), print_invars(false), print_preconds(false), print_unjustified_assumptions(false), print_summaries(false), store_invariants(true), keep_shadow_vars(false), check(NOCHECKS), check_verbose(0) { } std::string abs_dom_to_str() const; #ifndef TOP_DOWN_INTER_ANALYSIS std::string sum_abs_dom_to_str() const; #endif }; } // end namespace clam <commit_msg>Fix compilation problems<commit_after>#pragma once #include "clam/config.h" #include <climits> #include <string> namespace clam { //// // Base numerical domains for user options //// enum CrabDomain { INTERVALS , INTERVALS_CONGRUENCES , BOXES , DIS_INTERVALS /*, ZONES_SPARSE_DBM*/ , ZONES_SPLIT_DBM , TERMS_INTERVALS , TERMS_DIS_INTERVALS //TERMS_INTERVALS x ZONES_SPLIT_DBM , TERMS_ZONES //(#live vars<threshold ? TERMS_INTERVALSxZONES_SPLIT_DBM, INTERVALS) , ADAPT_TERMS_ZONES , OCT , PK , WRAPPED_INTERVALS }; //// // Kind of checker //// enum assert_check_kind_t { NOCHECKS = 0, ASSERTION = 1, NULLITY = 2 }; /** * Class to set analysis options **/ struct AnalysisParams { CrabDomain dom; #ifndef TOP_DOWN_INTER_ANALYSIS CrabDomain sum_dom; #endif bool run_backward; bool run_liveness; bool run_inter; #ifdef TOP_DOWN_INTER_ANALYSIS unsigned int max_calling_contexts; #endif unsigned relational_threshold; unsigned widening_delay; unsigned narrowing_iters; unsigned widening_jumpset; bool stats; bool print_invars; bool print_preconds; bool print_unjustified_assumptions; bool print_summaries; bool store_invariants; bool keep_shadow_vars; assert_check_kind_t check; unsigned check_verbose; AnalysisParams() : dom(INTERVALS), #ifndef TOP_DOWN_INTER_ANALYSIS sum_dom(ZONES_SPLIT_DBM), #endif run_backward(false), run_liveness(false), run_inter(false), #ifdef TOP_DOWN_INTER_ANALYSIS max_calling_contexts(UINT_MAX), #endif relational_threshold(10000), widening_delay(1), narrowing_iters(10), widening_jumpset(0), stats(false), print_invars(false), print_preconds(false), print_unjustified_assumptions(false), print_summaries(false), store_invariants(true), keep_shadow_vars(false), check(NOCHECKS), check_verbose(0) { } std::string abs_dom_to_str() const; #ifndef TOP_DOWN_INTER_ANALYSIS std::string sum_abs_dom_to_str() const; #endif }; } // end namespace clam <|endoftext|>
<commit_before>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee++ -- C Trampoline Support * * This file provides support for C trampolines, that is, converting C++ * functionals to pairs of C function pointers and @c void*. See * make_c_trampoline() for details. * * This file has no dependencies on any other part of IronBee or IronBee++. * * @author Christopher Alfeld <[email protected]> */ #ifndef __IBPP__C_TRAMPOLINE__ #define __IBPP__C_TRAMPOLINE__ #include <boost/any.hpp> #include <boost/function.hpp> #include <boost/preprocessor/arithmetic/add.hpp> #include <boost/preprocessor/arithmetic/sub.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/repetition.hpp> #ifndef IRONBEEPP_C_TRAMPOLINE_MAX_ARGS /** * Maximum number of arguments of a function passed to make_c_trampoline(). * * Can be defined before this file is included to change how many arguments * are supported. The length of this file post-preprocessing is linear in the * value. * * Defaults to 10. */ #define IRONBEEPP_C_TRAMPOLINE_MAX_ARGS 10 #endif namespace IronBee { /// @cond Internal namespace c_trampoline_implementation { //! Generates member of boost::function that contains type of argument @a n. #define CT_ARG(n) BOOST_PP_CAT(BOOST_PP_CAT(arg, n), _type) //! Pulls type of argument @a n into current class. #define CT_ARG_USING(z, n, unused) \ typedef typename type_of_function::CT_ARG(n) BOOST_PP_CAT(type_of_arg, n); //! Defines a partial specialization of make_c_trampoline_helper for n-1 args. #define CT_TOP(n) \ template <> \ struct make_c_trampoline_helper<BOOST_PP_SUB(n, 1)> \ { \ template <typename F> \ struct impl { \ typedef boost::function<F> type_of_function; \ typedef typename type_of_function::result_type type_of_result; \ BOOST_PP_REPEAT_FROM_TO(1, n, CT_ARG_USING, ~) \ typedef type_of_result(*type_of_cptr)( \ BOOST_PP_ENUM_SHIFTED_PARAMS(n, type_of_arg), \ void* \ ); \ typedef std::pair<type_of_cptr, void*> type_of_pair; \ \ static type_of_result trampoline( \ BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(n, type_of_arg, a), \ void* cdata \ ) \ { \ return boost::any_cast<type_of_function>( \ *reinterpret_cast<boost::any*>(cdata) \ )( \ BOOST_PP_ENUM_SHIFTED_PARAMS(n, a) \ ); \ } \ }; \ }; /** * Helper struct for make_c_trampoline(). * * When @a N is between 1 and IRONBEEPP_C_TRAMPOLINE_MAX_ARGS, this struct * will contain an internal template @c impl, templated on the function * signature. The @c impl template will define: * * - @c type_of_cptr -- Function pointer type. * - @c type_of_pair -- Pair of @c type_of_cptr and @c void*. * - @c trampoline -- Static trampoline function. * * See implementation of make_c_trampoline() for details on usage. * * @tparam N Arity of function to make trampoline for. */ template <int N> struct make_c_trampoline_helper { // Error case. }; #ifndef DOXYGEN_SKIP #include <boost/preprocessor/iteration/local.hpp> #define BOOST_PP_LOCAL_MACRO(n) CT_TOP(BOOST_PP_ADD(n, 1)) #define BOOST_PP_LOCAL_LIMITS (1, IRONBEEPP_C_TRAMPOLINE_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #endif #undef CT_ARG #undef CT_ARG_USING #undef CT_TOP } // c_trampoline_impl /// @endcond /** * Convert a C++ functional of signature @a F into a C trampoline. * * Example: * * @code * std::pair<int(*)(int, int, void*), void*> trampoline = * IronBee::make_c_trampoline<int(int, int)>( * std::plus<int>() * ); * int x = trampoline.first(1, 2, trampoline.second); * assert(x == 3); * IronBee::delete_c_trampoline(x.second); * * // C++11 example. * auto trampoline = * IronBee::make_c_trampoline<int(int, int)( * [](int a, int b) {return a + b;} * ); * int x = trampoline.first(1, 2, trampoline.second); * assert(x == 3); * IronBee::delete_c_trampoline(x.second); * @endcode * * @tparam F Signature of @a f. In many cases the compiler will not be able * to deduce @a F from @a f and it will need to be explicitly * specified. Supports any number of arguments up to * IRONBEEPP_C_TRAMPOLINE_MAX_ARGS which defaults to 10 but can be * modified by defining before this file is included. * @param[in] f Function to convert. * @return pair of function pointer and @c void*. Function pointer points to * function with same return type as @a F initial arguments identical * to @a F, plus a final void* argument. When passed the @c void* * portion to the final argument, will evaluate @a f with arguments * and return result. Caller is responsible for calling * delete_c_trampoline() on @c void* portion to reclaim memory. */ template <typename F> typename c_trampoline_implementation::make_c_trampoline_helper< boost::function<F>::arity >::template impl<F>::type_of_pair make_c_trampoline(boost::function<F> f) { return std::make_pair( &c_trampoline_implementation::make_c_trampoline_helper< boost::function<F>::arity >::template impl<F>::trampoline, new boost::any(f) ); } /** * Reclaim memory from a trampoline. * * @param[in] cdata @c void* portion of a trampoline returned from * make_c_trampoline(). */ void delete_c_trampoline(void* cdata) { delete reinterpret_cast<boost::any*>(cdata); } } // IronBee #endif <commit_msg>ironbee++/c_trampoline: Fix potential symbol collision.<commit_after>/***************************************************************************** * Licensed to Qualys, Inc. (QUALYS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * QUALYS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ****************************************************************************/ /** * @file * @brief IronBee++ -- C Trampoline Support * * This file provides support for C trampolines, that is, converting C++ * functionals to pairs of C function pointers and @c void*. See * make_c_trampoline() for details. * * This file has no dependencies on any other part of IronBee or IronBee++. * * @author Christopher Alfeld <[email protected]> */ #ifndef __IBPP__C_TRAMPOLINE__ #define __IBPP__C_TRAMPOLINE__ #include <boost/any.hpp> #include <boost/function.hpp> #include <boost/preprocessor/arithmetic/add.hpp> #include <boost/preprocessor/arithmetic/sub.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/repetition.hpp> #ifndef IRONBEEPP_C_TRAMPOLINE_MAX_ARGS /** * Maximum number of arguments of a function passed to make_c_trampoline(). * * Can be defined before this file is included to change how many arguments * are supported. The length of this file post-preprocessing is linear in the * value. * * Defaults to 10. */ #define IRONBEEPP_C_TRAMPOLINE_MAX_ARGS 10 #endif namespace IronBee { /// @cond Internal namespace c_trampoline_implementation { //! Generates member of boost::function that contains type of argument @a n. #define CT_ARG(n) BOOST_PP_CAT(BOOST_PP_CAT(arg, n), _type) //! Pulls type of argument @a n into current class. #define CT_ARG_USING(z, n, unused) \ typedef typename type_of_function::CT_ARG(n) BOOST_PP_CAT(type_of_arg, n); //! Defines a partial specialization of make_c_trampoline_helper for n-1 args. #define CT_TOP(n) \ template <> \ struct make_c_trampoline_helper<BOOST_PP_SUB(n, 1)> \ { \ template <typename F> \ struct impl { \ typedef boost::function<F> type_of_function; \ typedef typename type_of_function::result_type type_of_result; \ BOOST_PP_REPEAT_FROM_TO(1, n, CT_ARG_USING, ~) \ typedef type_of_result(*type_of_cptr)( \ BOOST_PP_ENUM_SHIFTED_PARAMS(n, type_of_arg), \ void* \ ); \ typedef std::pair<type_of_cptr, void*> type_of_pair; \ \ static type_of_result trampoline( \ BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(n, type_of_arg, a), \ void* cdata \ ) \ { \ return boost::any_cast<type_of_function>( \ *reinterpret_cast<boost::any*>(cdata) \ )( \ BOOST_PP_ENUM_SHIFTED_PARAMS(n, a) \ ); \ } \ }; \ }; /** * Helper struct for make_c_trampoline(). * * When @a N is between 1 and IRONBEEPP_C_TRAMPOLINE_MAX_ARGS, this struct * will contain an internal template @c impl, templated on the function * signature. The @c impl template will define: * * - @c type_of_cptr -- Function pointer type. * - @c type_of_pair -- Pair of @c type_of_cptr and @c void*. * - @c trampoline -- Static trampoline function. * * See implementation of make_c_trampoline() for details on usage. * * @tparam N Arity of function to make trampoline for. */ template <int N> struct make_c_trampoline_helper { // Error case. }; #ifndef DOXYGEN_SKIP #include <boost/preprocessor/iteration/local.hpp> #define BOOST_PP_LOCAL_MACRO(n) CT_TOP(BOOST_PP_ADD(n, 1)) #define BOOST_PP_LOCAL_LIMITS (1, IRONBEEPP_C_TRAMPOLINE_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #endif #undef CT_ARG #undef CT_ARG_USING #undef CT_TOP } // c_trampoline_impl /// @endcond /** * Convert a C++ functional of signature @a F into a C trampoline. * * Example: * * @code * std::pair<int(*)(int, int, void*), void*> trampoline = * IronBee::make_c_trampoline<int(int, int)>( * std::plus<int>() * ); * int x = trampoline.first(1, 2, trampoline.second); * assert(x == 3); * IronBee::delete_c_trampoline(x.second); * * // C++11 example. * auto trampoline = * IronBee::make_c_trampoline<int(int, int)( * [](int a, int b) {return a + b;} * ); * int x = trampoline.first(1, 2, trampoline.second); * assert(x == 3); * IronBee::delete_c_trampoline(x.second); * @endcode * * @tparam F Signature of @a f. In many cases the compiler will not be able * to deduce @a F from @a f and it will need to be explicitly * specified. Supports any number of arguments up to * IRONBEEPP_C_TRAMPOLINE_MAX_ARGS which defaults to 10 but can be * modified by defining before this file is included. * @param[in] f Function to convert. * @return pair of function pointer and @c void*. Function pointer points to * function with same return type as @a F initial arguments identical * to @a F, plus a final void* argument. When passed the @c void* * portion to the final argument, will evaluate @a f with arguments * and return result. Caller is responsible for calling * delete_c_trampoline() on @c void* portion to reclaim memory. */ template <typename F> typename c_trampoline_implementation::make_c_trampoline_helper< boost::function<F>::arity >::template impl<F>::type_of_pair make_c_trampoline(boost::function<F> f) { return std::make_pair( &c_trampoline_implementation::make_c_trampoline_helper< boost::function<F>::arity >::template impl<F>::trampoline, new boost::any(f) ); } /** * Reclaim memory from a trampoline. * * @param[in] cdata @c void* portion of a trampoline returned from * make_c_trampoline(). */ inline void delete_c_trampoline(void* cdata) { delete reinterpret_cast<boost::any*>(cdata); } } // IronBee #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_FACTORY_HPP #define FEATURE_FACTORY_HPP #include <mapnik/feature.hpp> namespace mapnik { struct feature_factory { static Feature* create (int fid) { return new Feature(fid); } }; } #endif //FEATURE_FACTORY_HPP <commit_msg>+ use boost::make_shared to improve shared_ptr allocation locality<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_FACTORY_HPP #define FEATURE_FACTORY_HPP #include <mapnik/feature.hpp> #include <boost/make_shared.hpp> //#include <boost/pool/pool_alloc.hpp> namespace mapnik { struct feature_factory { static boost::shared_ptr<Feature> create (int fid) { //return boost::allocate_shared<Feature>(boost::pool_allocator<Feature>(),fid); //return boost::allocate_shared<Feature>(boost::fast_pool_allocator<Feature>(),fid); return boost::make_shared<Feature>(fid); } }; } #endif //FEATURE_FACTORY_HPP <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #pragma once #include <string> #include <functional> #include <boost/config.hpp> #include <windows.h> #include <tlhelp32.h> namespace hadesmem { class Process; #if defined(HADESMEM_GCC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) class Module { public: Module(Process const& process, HMODULE handle); Module(Process const& process, std::wstring const& path); Module(Process const& process, MODULEENTRY32 const& entry); HMODULE GetHandle() const BOOST_NOEXCEPT; DWORD GetSize() const BOOST_NOEXCEPT; std::wstring GetName() const BOOST_NOEXCEPT; std::wstring GetPath() const BOOST_NOEXCEPT; FARPROC FindProcedure(std::string const& Name) const; FARPROC FindProcedure(WORD Ordinal) const; bool operator==(Module const& other) const BOOST_NOEXCEPT; bool operator!=(Module const& other) const BOOST_NOEXCEPT; bool operator<(Module const& other) const BOOST_NOEXCEPT; bool operator<=(Module const& other) const BOOST_NOEXCEPT; bool operator>(Module const& other) const BOOST_NOEXCEPT; bool operator>=(Module const& other) const BOOST_NOEXCEPT; private: void Initialize(HMODULE handle); void Initialize(std::wstring const& path); void Initialize(MODULEENTRY32 const& entry); void InitializeIf(std::function<bool (MODULEENTRY32 const&)> const& check_func); FARPROC FindProcedureInternal(LPCSTR name) const; Process const* process_; HMODULE handle_; DWORD size_; std::wstring name_; std::wstring path_; }; #if defined(HADESMEM_GCC) #pragma GCC diagnostic pop #endif // #if defined(HADESMEM_GCC) } <commit_msg>* [module] Explained warning being suppressed.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #pragma once #include <string> #include <functional> #include <boost/config.hpp> #include <windows.h> #include <tlhelp32.h> namespace hadesmem { class Process; // hadesmem::Module causes the following warning under GCC: // error: 'class hadesmem::Module' has pointer data members // but does not override 'hadesmem::Module(const hadesmem::Module&)' // or 'operator=(const hadesmem::Module&)' [-Werror=effc++] // This can be ignored because the pointer data members are non-owning // and shared pointers. #if defined(HADESMEM_GCC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) class Module { public: Module(Process const& process, HMODULE handle); Module(Process const& process, std::wstring const& path); Module(Process const& process, MODULEENTRY32 const& entry); HMODULE GetHandle() const BOOST_NOEXCEPT; DWORD GetSize() const BOOST_NOEXCEPT; std::wstring GetName() const BOOST_NOEXCEPT; std::wstring GetPath() const BOOST_NOEXCEPT; FARPROC FindProcedure(std::string const& Name) const; FARPROC FindProcedure(WORD Ordinal) const; bool operator==(Module const& other) const BOOST_NOEXCEPT; bool operator!=(Module const& other) const BOOST_NOEXCEPT; bool operator<(Module const& other) const BOOST_NOEXCEPT; bool operator<=(Module const& other) const BOOST_NOEXCEPT; bool operator>(Module const& other) const BOOST_NOEXCEPT; bool operator>=(Module const& other) const BOOST_NOEXCEPT; private: void Initialize(HMODULE handle); void Initialize(std::wstring const& path); void Initialize(MODULEENTRY32 const& entry); void InitializeIf(std::function<bool (MODULEENTRY32 const&)> const& check_func); FARPROC FindProcedureInternal(LPCSTR name) const; Process const* process_; HMODULE handle_; DWORD size_; std::wstring name_; std::wstring path_; }; #if defined(HADESMEM_GCC) #pragma GCC diagnostic pop #endif // #if defined(HADESMEM_GCC) } <|endoftext|>
<commit_before>#pragma once #include <quote/pp/cat.hpp> #include <quote/pp/size.hpp> #include <quote/pp/tuple_element.hpp> #include <quote/pp/tuple_cons.hpp> #include <quote/pp/tuple_car.hpp> #include <quote/pp/tuple_cdr.hpp> #if !defined(QUOTE_PP_TUPLE_FOREACH) # define QUOTE_PP_TUPLE_FOREACH(macro, data, tuple) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_FOREACH_I_, QUOTE_PP_SIZE tuple)(macro, data, tuple) #endif #define QUOTE_PP_TUPLE_FOREACH_I_0(macro, data, tuple) () #define QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, QUOTE_PP_TUPLE_ELEMENT(0, tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, elm) \ QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm) #define QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm) \ (macro(data, elm)) #define QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, elm, rest) \ QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest) #define QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, elm), \ QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, rest)),) #define QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, elm, rest) \ QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) #define QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, elm), \ QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, rest)),) #define QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, tuple) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, QUOTE_PP_TUPLE_ELEMENT(0, tuple)), \ QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, QUOTE_PP_TUPLE_CDR(tuple))),) #define QUOTE_PP_TUPLE_FOREACH_I_5(macro, data, tuple) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, QUOTE_PP_TUPLE_ELEMENT(0, tuple)), \ QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, QUOTE_PP_TUPLE_CDR(tuple))),) <commit_msg>fix QUOTE_PP_TUPLE_FOREACH<commit_after>#pragma once #include <quote/pp/cat.hpp> #include <quote/pp/size.hpp> #include <quote/pp/tuple_element.hpp> #include <quote/pp/tuple_cons.hpp> #include <quote/pp/tuple_car.hpp> #include <quote/pp/tuple_cdr.hpp> #if !defined(QUOTE_PP_TUPLE_FOREACH) # define QUOTE_PP_TUPLE_FOREACH(macro, data, tuple) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_FOREACH_I_, QUOTE_PP_SIZE tuple)(macro, data, tuple) #endif #define QUOTE_PP_TUPLE_FOREACH_I_0(macro, data, tuple) () #define QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, QUOTE_PP_TUPLE_ELEMENT(0, tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_1(macro, data, elm) \ QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm) #define QUOTE_PP_TUPLE_FOREACH_III_1(macro, data, elm) \ (macro(data, elm)) #define QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_2(macro, data, elm, rest) \ QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest) #define QUOTE_PP_TUPLE_FOREACH_III_2(macro, data, elm, rest) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, elm), \ QUOTE_PP_TUPLE_FOREACH_I_1(macro, data, rest)),) #define QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_3(macro, data, elm, rest) \ QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) #define QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, elm), \ QUOTE_PP_TUPLE_FOREACH_I_2(macro, data, rest)),) #define QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_4(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_4(macro, data, elm, rest) \ QUOTE_PP_TUPLE_FOREACH_III_4(macro, data, elm, rest) #define QUOTE_PP_TUPLE_FOREACH_III_4(macro, data, elm, rest) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, elm), \ QUOTE_PP_TUPLE_FOREACH_I_3(macro, data, rest)),) #define QUOTE_PP_TUPLE_FOREACH_I_5(macro, data, tuple) \ QUOTE_PP_TUPLE_FOREACH_II_5(macro, data, QUOTE_PP_TUPLE_CAR(tuple), QUOTE_PP_TUPLE_CDR(tuple)) #define QUOTE_PP_TUPLE_FOREACH_II_5(macro, data, elm, rest) \ QUOTE_PP_TUPLE_FOREACH_III_3(macro, data, elm, rest) #define QUOTE_PP_TUPLE_FOREACH_III_5(macro, data, elm, rest) \ QUOTE_PP_CAT(QUOTE_PP_TUPLE_CONS( \ macro(data, elm), \ QUOTE_PP_TUPLE_FOREACH_I_4(macro, data, rest)),) <|endoftext|>
<commit_before>/** * @file LLRenderNavPrim.cpp * @brief Renderable primitives used by the pathing library * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llrendernavprim.h" #include "llerror.h" #include "llglheaders.h" #include "llvertexbuffer.h" #include "llglslshader.h" //============================================================================= LLRenderNavPrim gRenderNav; //============================================================================= void LLRenderNavPrim::renderSegment( const LLVector3& start, const LLVector3& end, int color, bool overlayMode ) const { LLGLSLShader::sNoFixedFunction = false; LLGLEnable smooth(GL_LINE_SMOOTH); LLColor4 colorA( color ); glLineWidth(1.5f); gGL.color3fv( colorA.mV ); gGL.begin(LLRender::LINES); { gGL.vertex3fv( start.mV ); gGL.vertex3fv( end.mV ); } gGL.end(); gGL.flush(); LLGLSLShader::sNoFixedFunction = true; LLGLDisable smoothout(GL_LINE_SMOOTH); glLineWidth(1.0f); } //============================================================================= void LLRenderNavPrim::renderTri( const LLVector3& a, const LLVector3& b, const LLVector3& c, int color, bool overlayMode ) const { glLineWidth(1.5f); if ( overlayMode ) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } else { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } LLGLDisable cull(GL_CULL_FACE); LLColor4 colorA( color ); colorA*=1.25f; gGL.color4fv( colorA.mV ); LLGLSLShader::sNoFixedFunction = false; gGL.begin(LLRender::TRIANGLES); { gGL.vertex3fv( a.mV ); gGL.vertex3fv( b.mV ); gGL.vertex3fv( c.mV ); } gGL.end(); gGL.flush(); glLineWidth(1.0f); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); LLGLSLShader::sNoFixedFunction = true; } //============================================================================= void LLRenderNavPrim::renderNavMeshVB( LLVertexBuffer* pVBO, int vertCnt ) { LLGLSUIDefault gls_ui; LLGLEnable depth( GL_DEPTH_TEST ); LLGLEnable cull( GL_CULL_FACE ); glLineWidth(1.5f); LLGLSLShader::sNoFixedFunction = false; //pass 1 filled pVBO->setBuffer( LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR | LLVertexBuffer::MAP_NORMAL ); pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt ); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); LLGLEnable smooth(GL_LINE_SMOOTH); //pass 2 outlined pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt ); LLGLSLShader::sNoFixedFunction = true; glLineWidth(1.0f); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); LLGLDisable smoothout(GL_LINE_SMOOTH); } //============================================================================= void LLRenderNavPrim::renderStar( const LLVector3& center, const float scale, int color ) const { for (int k=0; k<3; k++) { LLVector3 star, pt1, pt2; star = LLVector3( 0.0f,0.0f,0.0f); star[k] = 0.5f; pt1 = center + star; pt2 = center - star; renderSegment( pt1, pt2, color, false ); } } //============================================================================= <commit_msg>Path-266: Navmesh is backfaced culled<commit_after>/** * @file LLRenderNavPrim.cpp * @brief Renderable primitives used by the pathing library * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llrendernavprim.h" #include "llerror.h" #include "llglheaders.h" #include "llvertexbuffer.h" #include "llglslshader.h" //============================================================================= LLRenderNavPrim gRenderNav; //============================================================================= void LLRenderNavPrim::renderSegment( const LLVector3& start, const LLVector3& end, int color, bool overlayMode ) const { LLGLSLShader::sNoFixedFunction = false; LLGLEnable smooth(GL_LINE_SMOOTH); LLColor4 colorA( color ); glLineWidth(1.5f); gGL.color3fv( colorA.mV ); gGL.begin(LLRender::LINES); { gGL.vertex3fv( start.mV ); gGL.vertex3fv( end.mV ); } gGL.end(); gGL.flush(); LLGLSLShader::sNoFixedFunction = true; LLGLDisable smoothout(GL_LINE_SMOOTH); glLineWidth(1.0f); } //============================================================================= void LLRenderNavPrim::renderTri( const LLVector3& a, const LLVector3& b, const LLVector3& c, int color, bool overlayMode ) const { glLineWidth(1.5f); if ( overlayMode ) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } else { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); } LLGLEnable cull(GL_CULL_FACE); LLColor4 colorA( color ); colorA*=1.25f; gGL.color4fv( colorA.mV ); LLGLSLShader::sNoFixedFunction = false; gGL.begin(LLRender::TRIANGLES); { gGL.vertex3fv( a.mV ); gGL.vertex3fv( b.mV ); gGL.vertex3fv( c.mV ); } gGL.end(); gGL.flush(); glLineWidth(1.0f); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); LLGLSLShader::sNoFixedFunction = true; } //============================================================================= void LLRenderNavPrim::renderNavMeshVB( LLVertexBuffer* pVBO, int vertCnt ) { LLGLSUIDefault gls_ui; LLGLEnable depth( GL_DEPTH_TEST ); LLGLEnable cull( GL_CULL_FACE ); glLineWidth(1.5f); LLGLSLShader::sNoFixedFunction = false; //pass 1 filled pVBO->setBuffer( LLVertexBuffer::MAP_VERTEX | LLVertexBuffer::MAP_COLOR | LLVertexBuffer::MAP_NORMAL ); pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt ); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); LLGLEnable smooth(GL_LINE_SMOOTH); //pass 2 outlined pVBO->drawArrays( LLRender::TRIANGLES, 0, vertCnt ); LLGLSLShader::sNoFixedFunction = true; glLineWidth(1.0f); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); LLGLDisable smoothout(GL_LINE_SMOOTH); } //============================================================================= void LLRenderNavPrim::renderStar( const LLVector3& center, const float scale, int color ) const { for (int k=0; k<3; k++) { LLVector3 star, pt1, pt2; star = LLVector3( 0.0f,0.0f,0.0f); star[k] = 0.5f; pt1 = center + star; pt2 = center - star; renderSegment( pt1, pt2, color, false ); } } //============================================================================= <|endoftext|>
<commit_before>/** * @file llimconversation.cpp * @brief LLIMConversation class implements the common behavior of LNearbyChatBar * @brief and LLIMFloater for hosting both in LLIMContainer * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llimconversation.h" #include "llchatentry.h" #include "llchathistory.h" #include "lldraghandle.h" #include "llfloaterreg.h" #include "llimfloater.h" #include "llimfloatercontainer.h" // to replace separate IM Floaters with multifloater container #include "lllayoutstack.h" #include "llnearbychat.h" const F32 REFRESH_INTERVAL = 0.2f; LLIMConversation::LLIMConversation(const LLUUID& session_id) : LLTransientDockableFloater(NULL, true, session_id) , LLEventTimer(REFRESH_INTERVAL) , mIsP2PChat(false) , mExpandCollapseBtn(NULL) , mTearOffBtn(NULL) , mCloseBtn(NULL) , mSessionID(session_id) , mParticipantList(NULL) , mChatHistory(NULL) , mInputEditor(NULL) , mInputEditorTopPad(0) { mCommitCallbackRegistrar.add("IMSession.Menu.Action", boost::bind(&LLIMConversation::onIMSessionMenuItemClicked, this, _2)); // mCommitCallbackRegistrar.add("IMSession.ExpCollapseBtn.Click", // boost::bind(&LLIMConversation::onSlide, this)); // mCommitCallbackRegistrar.add("IMSession.CloseBtn.Click", // boost::bind(&LLFloater::onClickClose, this)); mCommitCallbackRegistrar.add("IMSession.TearOffBtn.Click", boost::bind(&LLIMConversation::onTearOffClicked, this)); mEnableCallbackRegistrar.add("IMSession.Menu.CompactExpandedModes.CheckItem", boost::bind(&LLIMConversation::onIMCompactExpandedMenuItemCheck, this, _2)); mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.CheckItem", boost::bind(&LLIMConversation::onIMShowModesMenuItemCheck, this, _2)); mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.Enable", boost::bind(&LLIMConversation::onIMShowModesMenuItemEnable, this, _2)); } LLIMConversation::~LLIMConversation() { if (mParticipantList) { delete mParticipantList; mParticipantList = NULL; } } BOOL LLIMConversation::postBuild() { mCloseBtn = getChild<LLButton>("close_btn"); mCloseBtn->setCommitCallback(boost::bind(&LLFloater::onClickClose, this)); mExpandCollapseBtn = getChild<LLButton>("expand_collapse_btn"); mExpandCollapseBtn->setClickedCallback(boost::bind(&LLIMConversation::onSlide, this)); mParticipantListPanel = getChild<LLLayoutPanel>("speakers_list_panel"); mTearOffBtn = getChild<LLButton>("tear_off_btn"); mTearOffBtn->setCommitCallback(boost::bind(&LLIMConversation::onTearOffClicked, this)); mChatHistory = getChild<LLChatHistory>("chat_history"); mInputEditor = getChild<LLChatEntry>("chat_editor"); mInputEditor->setTextExpandedCallback(boost::bind(&LLIMConversation::reshapeChatHistory, this)); mInputEditorTopPad = mChatHistory->getRect().mBottom - mInputEditor->getRect().mTop; if (!getTornOff()) { setOpenPositioning(LLFloaterEnums::POSITIONING_RELATIVE); } buildParticipantList(); if (isChatMultiTab()) { if (mIsNearbyChat) { setCanClose(FALSE); } return LLFloater::postBuild(); } else { return LLDockableFloater::postBuild(); } } BOOL LLIMConversation::tick() { // This check is needed until LLFloaterReg::removeInstance() is synchronized with deleting the floater // via LLMortician::updateClass(), to avoid calling dead instances. See LLFloater::destroy(). if (isDead()) return false; // Need to resort the participant list if it's in sort by recent speaker order. if (mParticipantList) { mParticipantList->update(); } return false; } void LLIMConversation::buildParticipantList() { if (mIsNearbyChat) { LLLocalSpeakerMgr* speaker_manager = LLLocalSpeakerMgr::getInstance(); mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false); } else { // for group and ad-hoc chat we need to include agent into list if(!mIsP2PChat && !mParticipantList && mSessionID.notNull()) { LLSpeakerMgr* speaker_manager = LLIMModel::getInstance()->getSpeakerManager(mSessionID); mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false); } } } void LLIMConversation::onSortMenuItemClicked(const LLSD& userdata) { // TODO: Check this code when sort order menu will be added. (EM) if (!mParticipantList) { return; } std::string chosen_item = userdata.asString(); if (chosen_item == "sort_name") { mParticipantList->setSortOrder(LLParticipantList::E_SORT_BY_NAME); } } void LLIMConversation::onIMSessionMenuItemClicked(const LLSD& userdata) { std::string item = userdata.asString(); if (item == "compact_view" || item == "expanded_view") { gSavedSettings.setBOOL("PlainTextChatHistory", item == "compact_view"); } else { bool prev_value = gSavedSettings.getBOOL(item); gSavedSettings.setBOOL(item, !prev_value); } LLIMConversation::processChatHistoryStyleUpdate(); } bool LLIMConversation::onIMCompactExpandedMenuItemCheck(const LLSD& userdata) { std::string item = userdata.asString(); bool is_plain_text_mode = gSavedSettings.getBOOL("PlainTextChatHistory"); return is_plain_text_mode? item == "compact_view" : item == "expanded_view"; } bool LLIMConversation::onIMShowModesMenuItemCheck(const LLSD& userdata) { return gSavedSettings.getBOOL(userdata.asString()); } // enable/disable states for the "show time" and "show names" items of the show-modes menu bool LLIMConversation::onIMShowModesMenuItemEnable(const LLSD& userdata) { std::string item = userdata.asString(); bool plain_text = gSavedSettings.getBOOL("PlainTextChatHistory"); bool is_not_names = (item != "IMShowNamesForP2PConv"); return (plain_text && (is_not_names || mIsP2PChat)); } void LLIMConversation::updateHeaderAndToolbar() { bool is_hosted = getHost() != NULL; if (is_hosted) { for (S32 i = 0; i < BUTTON_COUNT; i++) { if (mButtons[i]) { // Hide the standard header buttons in a docked IM floater. mButtons[i]->setVisible(false); } } } // Participant list should be visible only in torn off floaters. bool is_participant_list_visible = !is_hosted && gSavedSettings.getBOOL("IMShowControlPanel") && !mIsP2PChat; mParticipantListPanel->setVisible(is_participant_list_visible); // Display collapse image (<<) if the floater is hosted // or if it is torn off but has an open control panel. bool is_expanded = is_hosted || is_participant_list_visible; mExpandCollapseBtn->setImageOverlay(getString(is_expanded ? "collapse_icon" : "expand_icon")); // The button (>>) should be disabled for torn off P2P conversations. mExpandCollapseBtn->setEnabled(is_hosted || !mIsP2PChat); if (mDragHandle) { // toggle floater's drag handle and title visibility mDragHandle->setVisible(!is_hosted); } mTearOffBtn->setImageOverlay(getString(is_hosted ? "tear_off_icon" : "return_icon")); mCloseBtn->setVisible(is_hosted && !mIsNearbyChat); enableDisableCallBtn(); showTranslationCheckbox(); } void LLIMConversation::reshapeChatHistory() { LLRect chat_rect = mChatHistory->getRect(); LLRect input_rect = mInputEditor->getRect(); int delta_height = chat_rect.mBottom - (input_rect.mTop + mInputEditorTopPad); chat_rect.setLeftTopAndSize(chat_rect.mLeft, chat_rect.mTop, chat_rect.getWidth(), chat_rect.getHeight() + delta_height); mChatHistory->setShape(chat_rect); } void LLIMConversation::showTranslationCheckbox(BOOL show) { getChild<LLUICtrl>("translate_chat_checkbox_lp")->setVisible(mIsNearbyChat? show : FALSE); } // static void LLIMConversation::processChatHistoryStyleUpdate() { LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("impanel"); for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin(); iter != inst_list.end(); ++iter) { LLIMFloater* floater = dynamic_cast<LLIMFloater*>(*iter); if (floater) { floater->reloadMessages(); } } LLNearbyChat* nearby_chat = LLNearbyChat::getInstance(); if (nearby_chat) { nearby_chat->reloadMessages(); } } void LLIMConversation::updateCallBtnState(bool callIsActive) { getChild<LLButton>("voice_call_btn")->setImageOverlay( callIsActive? getString("call_btn_stop") : getString("call_btn_start")); enableDisableCallBtn(); } void LLIMConversation::onSlide(LLIMConversation* self) { LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(self->getHost()); if (host_floater) { // Hide the messages pane if a floater is hosted in the Conversations host_floater->collapseMessagesPane(true); } else ///< floater is torn off { if (!self->mIsP2PChat) { bool expand = !self->mParticipantListPanel->getVisible(); // Expand/collapse the IM control panel self->mParticipantListPanel->setVisible(expand); gSavedSettings.setBOOL("IMShowControlPanel", expand); self->mExpandCollapseBtn->setImageOverlay(self->getString(expand ? "collapse_icon" : "expand_icon")); } } } /*virtual*/ void LLIMConversation::onOpen(const LLSD& key) { LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(getHost()); if (host_floater) { // Show the messages pane when opening a floater hosted in the Conversations host_floater->collapseMessagesPane(false); } updateHeaderAndToolbar(); } // virtual void LLIMConversation::onClose(bool app_quitting) { // Always suppress the IM from the conversations list on close if present for any reason if (LLIMConversation::isChatMultiTab()) { LLIMFloaterContainer* im_box = LLIMFloaterContainer::findInstance(); if (im_box) { im_box->removeConversationListItem(mSessionID); } } } void LLIMConversation::onTearOffClicked() { onClickTearOff(this); updateHeaderAndToolbar(); } // static bool LLIMConversation::isChatMultiTab() { // Restart is required in order to change chat window type. return true; } <commit_msg>CHUI-168 FIXED Added call of updateHeaderAndToolbar from postBuild for correct floater's title and standard buttons showing at start<commit_after>/** * @file llimconversation.cpp * @brief LLIMConversation class implements the common behavior of LNearbyChatBar * @brief and LLIMFloater for hosting both in LLIMContainer * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llimconversation.h" #include "llchatentry.h" #include "llchathistory.h" #include "lldraghandle.h" #include "llfloaterreg.h" #include "llimfloater.h" #include "llimfloatercontainer.h" // to replace separate IM Floaters with multifloater container #include "lllayoutstack.h" #include "llnearbychat.h" const F32 REFRESH_INTERVAL = 0.2f; LLIMConversation::LLIMConversation(const LLUUID& session_id) : LLTransientDockableFloater(NULL, true, session_id) , LLEventTimer(REFRESH_INTERVAL) , mIsP2PChat(false) , mExpandCollapseBtn(NULL) , mTearOffBtn(NULL) , mCloseBtn(NULL) , mSessionID(session_id) , mParticipantList(NULL) , mChatHistory(NULL) , mInputEditor(NULL) , mInputEditorTopPad(0) { mCommitCallbackRegistrar.add("IMSession.Menu.Action", boost::bind(&LLIMConversation::onIMSessionMenuItemClicked, this, _2)); // mCommitCallbackRegistrar.add("IMSession.ExpCollapseBtn.Click", // boost::bind(&LLIMConversation::onSlide, this)); // mCommitCallbackRegistrar.add("IMSession.CloseBtn.Click", // boost::bind(&LLFloater::onClickClose, this)); mCommitCallbackRegistrar.add("IMSession.TearOffBtn.Click", boost::bind(&LLIMConversation::onTearOffClicked, this)); mEnableCallbackRegistrar.add("IMSession.Menu.CompactExpandedModes.CheckItem", boost::bind(&LLIMConversation::onIMCompactExpandedMenuItemCheck, this, _2)); mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.CheckItem", boost::bind(&LLIMConversation::onIMShowModesMenuItemCheck, this, _2)); mEnableCallbackRegistrar.add("IMSession.Menu.ShowModes.Enable", boost::bind(&LLIMConversation::onIMShowModesMenuItemEnable, this, _2)); } LLIMConversation::~LLIMConversation() { if (mParticipantList) { delete mParticipantList; mParticipantList = NULL; } } BOOL LLIMConversation::postBuild() { mCloseBtn = getChild<LLButton>("close_btn"); mCloseBtn->setCommitCallback(boost::bind(&LLFloater::onClickClose, this)); mExpandCollapseBtn = getChild<LLButton>("expand_collapse_btn"); mExpandCollapseBtn->setClickedCallback(boost::bind(&LLIMConversation::onSlide, this)); mParticipantListPanel = getChild<LLLayoutPanel>("speakers_list_panel"); mTearOffBtn = getChild<LLButton>("tear_off_btn"); mTearOffBtn->setCommitCallback(boost::bind(&LLIMConversation::onTearOffClicked, this)); mChatHistory = getChild<LLChatHistory>("chat_history"); mInputEditor = getChild<LLChatEntry>("chat_editor"); mInputEditor->setTextExpandedCallback(boost::bind(&LLIMConversation::reshapeChatHistory, this)); mInputEditorTopPad = mChatHistory->getRect().mBottom - mInputEditor->getRect().mTop; if (!getTornOff()) { setOpenPositioning(LLFloaterEnums::POSITIONING_RELATIVE); } buildParticipantList(); updateHeaderAndToolbar(); if (isChatMultiTab()) { if (mIsNearbyChat) { setCanClose(FALSE); } return LLFloater::postBuild(); } else { return LLDockableFloater::postBuild(); } } BOOL LLIMConversation::tick() { // This check is needed until LLFloaterReg::removeInstance() is synchronized with deleting the floater // via LLMortician::updateClass(), to avoid calling dead instances. See LLFloater::destroy(). if (isDead()) return false; // Need to resort the participant list if it's in sort by recent speaker order. if (mParticipantList) { mParticipantList->update(); } return false; } void LLIMConversation::buildParticipantList() { if (mIsNearbyChat) { LLLocalSpeakerMgr* speaker_manager = LLLocalSpeakerMgr::getInstance(); mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false); } else { // for group and ad-hoc chat we need to include agent into list if(!mIsP2PChat && !mParticipantList && mSessionID.notNull()) { LLSpeakerMgr* speaker_manager = LLIMModel::getInstance()->getSpeakerManager(mSessionID); mParticipantList = new LLParticipantList(speaker_manager, getChild<LLAvatarList>("speakers_list"), true, false); } } } void LLIMConversation::onSortMenuItemClicked(const LLSD& userdata) { // TODO: Check this code when sort order menu will be added. (EM) if (!mParticipantList) { return; } std::string chosen_item = userdata.asString(); if (chosen_item == "sort_name") { mParticipantList->setSortOrder(LLParticipantList::E_SORT_BY_NAME); } } void LLIMConversation::onIMSessionMenuItemClicked(const LLSD& userdata) { std::string item = userdata.asString(); if (item == "compact_view" || item == "expanded_view") { gSavedSettings.setBOOL("PlainTextChatHistory", item == "compact_view"); } else { bool prev_value = gSavedSettings.getBOOL(item); gSavedSettings.setBOOL(item, !prev_value); } LLIMConversation::processChatHistoryStyleUpdate(); } bool LLIMConversation::onIMCompactExpandedMenuItemCheck(const LLSD& userdata) { std::string item = userdata.asString(); bool is_plain_text_mode = gSavedSettings.getBOOL("PlainTextChatHistory"); return is_plain_text_mode? item == "compact_view" : item == "expanded_view"; } bool LLIMConversation::onIMShowModesMenuItemCheck(const LLSD& userdata) { return gSavedSettings.getBOOL(userdata.asString()); } // enable/disable states for the "show time" and "show names" items of the show-modes menu bool LLIMConversation::onIMShowModesMenuItemEnable(const LLSD& userdata) { std::string item = userdata.asString(); bool plain_text = gSavedSettings.getBOOL("PlainTextChatHistory"); bool is_not_names = (item != "IMShowNamesForP2PConv"); return (plain_text && (is_not_names || mIsP2PChat)); } void LLIMConversation::updateHeaderAndToolbar() { bool is_hosted = getHost() != NULL; if (is_hosted) { for (S32 i = 0; i < BUTTON_COUNT; i++) { if (mButtons[i]) { // Hide the standard header buttons in a docked IM floater. mButtons[i]->setVisible(false); } } } // Participant list should be visible only in torn off floaters. bool is_participant_list_visible = !is_hosted && gSavedSettings.getBOOL("IMShowControlPanel") && !mIsP2PChat; mParticipantListPanel->setVisible(is_participant_list_visible); // Display collapse image (<<) if the floater is hosted // or if it is torn off but has an open control panel. bool is_expanded = is_hosted || is_participant_list_visible; mExpandCollapseBtn->setImageOverlay(getString(is_expanded ? "collapse_icon" : "expand_icon")); // The button (>>) should be disabled for torn off P2P conversations. mExpandCollapseBtn->setEnabled(is_hosted || !mIsP2PChat); if (mDragHandle) { // toggle floater's drag handle and title visibility mDragHandle->setVisible(!is_hosted); } mTearOffBtn->setImageOverlay(getString(is_hosted ? "tear_off_icon" : "return_icon")); mCloseBtn->setVisible(is_hosted && !mIsNearbyChat); enableDisableCallBtn(); showTranslationCheckbox(); } void LLIMConversation::reshapeChatHistory() { LLRect chat_rect = mChatHistory->getRect(); LLRect input_rect = mInputEditor->getRect(); int delta_height = chat_rect.mBottom - (input_rect.mTop + mInputEditorTopPad); chat_rect.setLeftTopAndSize(chat_rect.mLeft, chat_rect.mTop, chat_rect.getWidth(), chat_rect.getHeight() + delta_height); mChatHistory->setShape(chat_rect); } void LLIMConversation::showTranslationCheckbox(BOOL show) { getChild<LLUICtrl>("translate_chat_checkbox_lp")->setVisible(mIsNearbyChat? show : FALSE); } // static void LLIMConversation::processChatHistoryStyleUpdate() { LLFloaterReg::const_instance_list_t& inst_list = LLFloaterReg::getFloaterList("impanel"); for (LLFloaterReg::const_instance_list_t::const_iterator iter = inst_list.begin(); iter != inst_list.end(); ++iter) { LLIMFloater* floater = dynamic_cast<LLIMFloater*>(*iter); if (floater) { floater->reloadMessages(); } } LLNearbyChat* nearby_chat = LLNearbyChat::getInstance(); if (nearby_chat) { nearby_chat->reloadMessages(); } } void LLIMConversation::updateCallBtnState(bool callIsActive) { getChild<LLButton>("voice_call_btn")->setImageOverlay( callIsActive? getString("call_btn_stop") : getString("call_btn_start")); enableDisableCallBtn(); } void LLIMConversation::onSlide(LLIMConversation* self) { LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(self->getHost()); if (host_floater) { // Hide the messages pane if a floater is hosted in the Conversations host_floater->collapseMessagesPane(true); } else ///< floater is torn off { if (!self->mIsP2PChat) { bool expand = !self->mParticipantListPanel->getVisible(); // Expand/collapse the IM control panel self->mParticipantListPanel->setVisible(expand); gSavedSettings.setBOOL("IMShowControlPanel", expand); self->mExpandCollapseBtn->setImageOverlay(self->getString(expand ? "collapse_icon" : "expand_icon")); } } } /*virtual*/ void LLIMConversation::onOpen(const LLSD& key) { LLIMFloaterContainer* host_floater = dynamic_cast<LLIMFloaterContainer*>(getHost()); if (host_floater) { // Show the messages pane when opening a floater hosted in the Conversations host_floater->collapseMessagesPane(false); } updateHeaderAndToolbar(); } // virtual void LLIMConversation::onClose(bool app_quitting) { // Always suppress the IM from the conversations list on close if present for any reason if (LLIMConversation::isChatMultiTab()) { LLIMFloaterContainer* im_box = LLIMFloaterContainer::findInstance(); if (im_box) { im_box->removeConversationListItem(mSessionID); } } } void LLIMConversation::onTearOffClicked() { onClickTearOff(this); updateHeaderAndToolbar(); } // static bool LLIMConversation::isChatMultiTab() { // Restart is required in order to change chat window type. return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // // vie_autotest_linux.cc // #include "vie_autotest_linux.h" #include <string> #include "vie_autotest_defines.h" #include "vie_autotest_main.h" #include "engine_configurations.h" #include "critical_section_wrapper.h" #include "thread_wrapper.h" ViEAutoTestWindowManager::ViEAutoTestWindowManager() : _hdsp1(NULL), _hdsp2(NULL) { } ViEAutoTestWindowManager::~ViEAutoTestWindowManager() { TerminateWindows(); } void* ViEAutoTestWindowManager::GetWindow1() { return reinterpret_cast<void*>(_hwnd1); } void* ViEAutoTestWindowManager::GetWindow2() { return reinterpret_cast<void*>(_hwnd2); } int ViEAutoTestWindowManager::TerminateWindows() { if (_hdsp1) { ViEDestroyWindow(&_hwnd1, _hdsp1); _hdsp1 = NULL; } if (_hdsp2) { ViEDestroyWindow(&_hwnd2, _hdsp2); _hdsp2 = NULL; } return 0; } int ViEAutoTestWindowManager::CreateWindows(AutoTestRect window1Size, AutoTestRect window2Size, void* window1Title, void* window2Title) { ViECreateWindow(&_hwnd1, &_hdsp1, window1Size.origin.x, window1Size.origin.y, window1Size.size.width, window1Size.size.height, reinterpret_cast<char*>(window1Title)); ViECreateWindow(&_hwnd2, &_hdsp2, window2Size.origin.x, window2Size.origin.y, window2Size.size.width, window2Size.size.height, reinterpret_cast<char*>(window2Title)); return 0; } int ViEAutoTestWindowManager::ViECreateWindow(Window *outWindow, Display **outDisplay, int xpos, int ypos, int width, int height, char* title) { int screen; XEvent evnt; XSetWindowAttributes xswa; // window attribute struct XVisualInfo vinfo; // screen visual info struct unsigned long mask; // attribute mask // get connection handle to xserver Display* _display = XOpenDisplay(NULL); // get screen number screen = DefaultScreen(_display); // put desired visual info for the screen in vinfo // TODO(unknown): more display settings should be allowed if (XMatchVisualInfo(_display, screen, 24, TrueColor, &vinfo) != 0) { // printf( "Screen visual info match!\n" ); } // set window attributes xswa.colormap = XCreateColormap(_display, DefaultRootWindow(_display), vinfo.visual, AllocNone); xswa.event_mask = StructureNotifyMask | ExposureMask; xswa.background_pixel = 0; xswa.border_pixel = 0; // value mask for attributes mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; Window _window = XCreateWindow(_display, DefaultRootWindow(_display), xpos, ypos, width, height, 0, vinfo.depth, InputOutput, vinfo.visual, mask, &xswa); // Set window name XStoreName(_display, _window, title); XSetIconName(_display, _window, title); // make x report events for mask XSelectInput(_display, _window, StructureNotifyMask); // map the window to the display XMapWindow(_display, _window); // wait for map event do { XNextEvent(_display, &evnt); } while (evnt.type != MapNotify || evnt.xmap.event != _window); *outWindow = _window; *outDisplay = _display; return 0; } int ViEAutoTestWindowManager::ViEDestroyWindow(Window *window, Display *display) { XUnmapWindow(display, *window); XDestroyWindow(display, *window); XSync(display, false); return 0; } bool ViEAutoTestWindowManager::SetTopmostWindow() { return 0; } int main(int argc, char** argv) { ViEAutoTestMain auto_test; return auto_test.RunTests(argc, argv); } <commit_msg>Made vie_auto_test more robust in Linux when the X environment is broken.<commit_after>/* * Copyright (c) 2011 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // // vie_autotest_linux.cc // #include "vie_autotest_linux.h" #include <string> #include "vie_autotest_defines.h" #include "vie_autotest_main.h" #include "engine_configurations.h" #include "critical_section_wrapper.h" #include "thread_wrapper.h" ViEAutoTestWindowManager::ViEAutoTestWindowManager() : _hdsp1(NULL), _hdsp2(NULL) { } ViEAutoTestWindowManager::~ViEAutoTestWindowManager() { TerminateWindows(); } void* ViEAutoTestWindowManager::GetWindow1() { return reinterpret_cast<void*>(_hwnd1); } void* ViEAutoTestWindowManager::GetWindow2() { return reinterpret_cast<void*>(_hwnd2); } int ViEAutoTestWindowManager::TerminateWindows() { if (_hdsp1) { ViEDestroyWindow(&_hwnd1, _hdsp1); _hdsp1 = NULL; } if (_hdsp2) { ViEDestroyWindow(&_hwnd2, _hdsp2); _hdsp2 = NULL; } return 0; } int ViEAutoTestWindowManager::CreateWindows(AutoTestRect window1Size, AutoTestRect window2Size, void* window1Title, void* window2Title) { ViECreateWindow(&_hwnd1, &_hdsp1, window1Size.origin.x, window1Size.origin.y, window1Size.size.width, window1Size.size.height, reinterpret_cast<char*>(window1Title)); ViECreateWindow(&_hwnd2, &_hdsp2, window2Size.origin.x, window2Size.origin.y, window2Size.size.width, window2Size.size.height, reinterpret_cast<char*>(window2Title)); return 0; } int ViEAutoTestWindowManager::ViECreateWindow(Window *out_window, Display **out_display, int x_pos, int y_pos, int width, int height, char* title) { Display* display = XOpenDisplay(NULL); if (display == NULL) { // There's no point to continue if this happens: nothing will work anyway. printf("Failed to connect to X server: X environment likely broken\n"); exit(-1); } int screen = DefaultScreen(display); // Try to establish a 24-bit TrueColor display // (our environment must allow this). XVisualInfo visual_info; if (XMatchVisualInfo(display, screen, 24, TrueColor, &visual_info) == 0) { printf("Failed to establish 24-bit TrueColor in X environment.\n"); exit(-1); } // Create suitable window attributes. XSetWindowAttributes window_attributes; window_attributes.colormap = XCreateColormap( display, DefaultRootWindow(display), visual_info.visual, AllocNone); window_attributes.event_mask = StructureNotifyMask | ExposureMask; window_attributes.background_pixel = 0; window_attributes.border_pixel = 0; unsigned long attribute_mask = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask; Window _window = XCreateWindow(display, DefaultRootWindow(display), x_pos, y_pos, width, height, 0, visual_info.depth, InputOutput, visual_info.visual, attribute_mask, &window_attributes); // Set window name. XStoreName(display, _window, title); XSetIconName(display, _window, title); // Make x report events for mask. XSelectInput(display, _window, StructureNotifyMask); // Map the window to the display. XMapWindow(display, _window); // Wait for map event. XEvent event; do { XNextEvent(display, &event); } while (event.type != MapNotify || event.xmap.event != _window); *out_window = _window; *out_display = display; return 0; } int ViEAutoTestWindowManager::ViEDestroyWindow(Window *window, Display *display) { XUnmapWindow(display, *window); XDestroyWindow(display, *window); XSync(display, false); return 0; } bool ViEAutoTestWindowManager::SetTopmostWindow() { return 0; } int main(int argc, char** argv) { ViEAutoTestMain auto_test; return auto_test.RunTests(argc, argv); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <mpi.h> #include <vector> #include "geopm.h" #include "ModelRegion.hpp" __attribute__((noinline)) void setup(std::vector<double> &aa_vec, std::vector<double> &bb_vec, std::vector<double> &cc_vec) { #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { aa_vec[idx] = 0.0; aa_vec[idx] = 1.0; aa_vec[idx] = 2.0; } } __attribute__((noinline)) void triad_with_post(std::vector<double> &aa_vec, const std::vector<double> &bb_vec, const std::vector<double> &cc_vec) { double scalar = 3.0; #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { geopm_tprof_post(); aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx]; } } __attribute__((noinline)) void triad_no_post(std::vector<double> &aa_vec, const std::vector<double> &bb_vec, const std::vector<double> &cc_vec) { double scalar = 3.0; #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx]; } } __attribute__((noinline)) void warmup(std::vector<double> &aa_vec, const std::vector<double> &bb_vec, const std::vector<double> &cc_vec) { double scalar = 3.0; #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx]; } } __attribute__((noinline)) void loop_dgemm_with_post(double big_o, int count) { #pragma omp parallel { std::shared_ptr<geopm::ModelRegion> dgemm_model( geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false)); #pragma omp for for (size_t idx = 0; idx < count; ++idx) { geopm_tprof_post(); dgemm_model->run(); } } } __attribute__((noinline)) void loop_dgemm_no_post(double big_o, int count) { #pragma omp parallel { std::shared_ptr<geopm::ModelRegion> dgemm_model( geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false)); #pragma omp for for (size_t idx = 0; idx < count; ++idx) { dgemm_model->run(); } } } __attribute__((noinline)) void loop_dgemm_warmup(double big_o, int count) { #pragma omp parallel { std::shared_ptr<geopm::ModelRegion> dgemm_model( geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false)); #pragma omp for for (size_t idx = 0; idx < count; ++idx) { dgemm_model->run(); } } } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int vec_size = 134217728; // 1 GiB std::vector<double> aa_vec(vec_size); std::vector<double> bb_vec(vec_size); std::vector<double> cc_vec(vec_size); MPI_Barrier(MPI_COMM_WORLD); setup(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); warmup(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); triad_with_post(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); triad_no_post(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); loop_dgemm_warmup(0.01, 100); MPI_Barrier(MPI_COMM_WORLD); loop_dgemm_with_post(0.01, 10000); MPI_Barrier(MPI_COMM_WORLD); loop_dgemm_no_post(0.01, 10000); MPI_Finalize(); return 0; } <commit_msg>Fix signed / unsigned comparison<commit_after>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <mpi.h> #include <vector> #include "geopm.h" #include "ModelRegion.hpp" __attribute__((noinline)) void setup(std::vector<double> &aa_vec, std::vector<double> &bb_vec, std::vector<double> &cc_vec) { #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { aa_vec[idx] = 0.0; aa_vec[idx] = 1.0; aa_vec[idx] = 2.0; } } __attribute__((noinline)) void triad_with_post(std::vector<double> &aa_vec, const std::vector<double> &bb_vec, const std::vector<double> &cc_vec) { double scalar = 3.0; #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { geopm_tprof_post(); aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx]; } } __attribute__((noinline)) void triad_no_post(std::vector<double> &aa_vec, const std::vector<double> &bb_vec, const std::vector<double> &cc_vec) { double scalar = 3.0; #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx]; } } __attribute__((noinline)) void warmup(std::vector<double> &aa_vec, const std::vector<double> &bb_vec, const std::vector<double> &cc_vec) { double scalar = 3.0; #pragma omp parallel for for (size_t idx = 0; idx < aa_vec.size(); ++idx) { aa_vec[idx] = bb_vec[idx] + scalar * cc_vec[idx]; } } __attribute__((noinline)) void loop_dgemm_with_post(double big_o, int count) { #pragma omp parallel { std::shared_ptr<geopm::ModelRegion> dgemm_model( geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false)); #pragma omp for for (int idx = 0; idx < count; ++idx) { geopm_tprof_post(); dgemm_model->run(); } } } __attribute__((noinline)) void loop_dgemm_no_post(double big_o, int count) { #pragma omp parallel { std::shared_ptr<geopm::ModelRegion> dgemm_model( geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false)); #pragma omp for for (int idx = 0; idx < count; ++idx) { dgemm_model->run(); } } } __attribute__((noinline)) void loop_dgemm_warmup(double big_o, int count) { #pragma omp parallel { std::shared_ptr<geopm::ModelRegion> dgemm_model( geopm::ModelRegion::model_region("dgemm-unmarked", big_o, false)); #pragma omp for for (int idx = 0; idx < count; ++idx) { dgemm_model->run(); } } } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int vec_size = 134217728; // 1 GiB std::vector<double> aa_vec(vec_size); std::vector<double> bb_vec(vec_size); std::vector<double> cc_vec(vec_size); MPI_Barrier(MPI_COMM_WORLD); setup(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); warmup(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); triad_with_post(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); triad_no_post(aa_vec, bb_vec, cc_vec); MPI_Barrier(MPI_COMM_WORLD); loop_dgemm_warmup(0.01, 100); MPI_Barrier(MPI_COMM_WORLD); loop_dgemm_with_post(0.01, 10000); MPI_Barrier(MPI_COMM_WORLD); loop_dgemm_no_post(0.01, 10000); MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>// Copyright 2020 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 <array> #include <cstdio> #include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> #include "iree/base/api.h" #include "iree/base/internal/file_io.h" #include "iree/base/internal/flags.h" #include "iree/base/status_cc.h" #include "iree/base/tracing.h" #include "iree/hal/api.h" #include "iree/hal/drivers/init.h" #include "iree/modules/hal/module.h" #include "iree/tools/utils/vm_util.h" #include "iree/vm/api.h" #include "iree/vm/bytecode_module.h" #include "iree/vm/ref_cc.h" IREE_FLAG(string, module_file, "-", "File containing the module to load that contains the entry " "function. Defaults to stdin."); IREE_FLAG(string, entry_function, "", "Name of a function contained in the module specified by module_file " "to run."); IREE_FLAG(string, driver, "vmvx", "Backend driver to use."); static iree_status_t parse_function_input(iree_string_view_t flag_name, void* storage, iree_string_view_t value) { auto* list = (std::vector<std::string>*)storage; list->push_back(std::string(value.data, value.size)); return iree_ok_status(); } static void print_function_input(iree_string_view_t flag_name, void* storage, FILE* file) { auto* list = (std::vector<std::string>*)storage; if (list->empty()) { fprintf(file, "# --%.*s=\n", (int)flag_name.size, flag_name.data); } else { for (size_t i = 0; i < list->size(); ++i) { fprintf(file, "--%.*s=\"%s\"\n", (int)flag_name.size, flag_name.data, list->at(i).c_str()); } } } static std::vector<std::string> FLAG_function_inputs; IREE_FLAG_CALLBACK( parse_function_input, print_function_input, &FLAG_function_inputs, function_input, "An input value or buffer of the format:\n" " [shape]xtype=[value]\n" " 2x2xi32=1 2 3 4\n" "Optionally, brackets may be used to separate the element values:\n" " 2x2xi32=[[1 2][3 4]]\n" "Each occurrence of the flag indicates an input in the order they were\n" "specified on the command line."); namespace iree { namespace { iree_status_t GetModuleContentsFromFlags(std::string* out_contents) { IREE_TRACE_SCOPE0("GetModuleContentsFromFlags"); auto module_file = std::string(FLAG_module_file); if (module_file == "-") { *out_contents = std::string{std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>()}; } else { IREE_RETURN_IF_ERROR(GetFileContents(module_file.c_str(), out_contents)); } return iree_ok_status(); } iree_status_t Run() { IREE_TRACE_SCOPE0("iree-run-module"); IREE_RETURN_IF_ERROR(iree_hal_module_register_types(), "registering HAL types"); iree_vm_instance_t* instance = nullptr; IREE_RETURN_IF_ERROR( iree_vm_instance_create(iree_allocator_system(), &instance), "creating instance"); std::string module_data; IREE_RETURN_IF_ERROR(GetModuleContentsFromFlags(&module_data)); iree_vm_module_t* input_module = nullptr; IREE_RETURN_IF_ERROR(iree_vm_bytecode_module_create( iree_make_const_byte_span((void*)module_data.data(), module_data.size()), iree_allocator_null(), iree_allocator_system(), &input_module)); iree_hal_device_t* device = nullptr; IREE_RETURN_IF_ERROR(CreateDevice(FLAG_driver, &device)); iree_vm_module_t* hal_module = nullptr; IREE_RETURN_IF_ERROR( iree_hal_module_create(device, iree_allocator_system(), &hal_module)); iree_vm_context_t* context = nullptr; // Order matters. The input module will likely be dependent on the hal module. std::array<iree_vm_module_t*, 2> modules = {hal_module, input_module}; IREE_RETURN_IF_ERROR(iree_vm_context_create_with_modules( instance, modules.data(), modules.size(), iree_allocator_system(), &context), "creating context"); std::string function_name = std::string(FLAG_entry_function); iree_vm_function_t function; if (function_name.empty()) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "no --entry_function= specified"); } else { IREE_RETURN_IF_ERROR( input_module->lookup_function( input_module->self, IREE_VM_FUNCTION_LINKAGE_EXPORT, iree_string_view_t{function_name.data(), function_name.size()}, &function), "looking up function '%s'", function_name.c_str()); } vm::ref<iree_vm_list_t> inputs; IREE_CHECK_OK(ParseToVariantList( iree_hal_device_allocator(device), iree::span<const std::string>{FLAG_function_inputs.data(), FLAG_function_inputs.size()}, &inputs)); vm::ref<iree_vm_list_t> outputs; IREE_RETURN_IF_ERROR(iree_vm_list_create(/*element_type=*/nullptr, 16, iree_allocator_system(), &outputs)); std::cout << "EXEC @" << function_name << "\n"; IREE_RETURN_IF_ERROR( iree_vm_invoke(context, function, /*policy=*/nullptr, inputs.get(), outputs.get(), iree_allocator_system()), "invoking function '%s'", function_name.c_str()); IREE_RETURN_IF_ERROR(PrintVariantList(outputs.get()), "printing results"); inputs.reset(); outputs.reset(); iree_vm_module_release(hal_module); iree_vm_module_release(input_module); iree_hal_device_release(device); iree_vm_context_release(context); iree_vm_instance_release(instance); return iree_ok_status(); } } // namespace extern "C" int main(int argc, char** argv) { iree_flags_parse_checked(IREE_FLAGS_PARSE_MODE_DEFAULT, &argc, &argv); IREE_CHECK_OK(iree_hal_register_all_available_drivers( iree_hal_driver_registry_default())); IREE_CHECK_OK(Run()); return 0; } } // namespace iree <commit_msg>Update iree-run-module to error out with more than one positional argument. (#6334)<commit_after>// Copyright 2020 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 <array> #include <cstdio> #include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> #include "iree/base/api.h" #include "iree/base/internal/file_io.h" #include "iree/base/internal/flags.h" #include "iree/base/status_cc.h" #include "iree/base/tracing.h" #include "iree/hal/api.h" #include "iree/hal/drivers/init.h" #include "iree/modules/hal/module.h" #include "iree/tools/utils/vm_util.h" #include "iree/vm/api.h" #include "iree/vm/bytecode_module.h" #include "iree/vm/ref_cc.h" IREE_FLAG(string, module_file, "-", "File containing the module to load that contains the entry " "function. Defaults to stdin."); IREE_FLAG(string, entry_function, "", "Name of a function contained in the module specified by module_file " "to run."); IREE_FLAG(string, driver, "vmvx", "Backend driver to use."); static iree_status_t parse_function_input(iree_string_view_t flag_name, void* storage, iree_string_view_t value) { auto* list = (std::vector<std::string>*)storage; list->push_back(std::string(value.data, value.size)); return iree_ok_status(); } static void print_function_input(iree_string_view_t flag_name, void* storage, FILE* file) { auto* list = (std::vector<std::string>*)storage; if (list->empty()) { fprintf(file, "# --%.*s=\n", (int)flag_name.size, flag_name.data); } else { for (size_t i = 0; i < list->size(); ++i) { fprintf(file, "--%.*s=\"%s\"\n", (int)flag_name.size, flag_name.data, list->at(i).c_str()); } } } static std::vector<std::string> FLAG_function_inputs; IREE_FLAG_CALLBACK( parse_function_input, print_function_input, &FLAG_function_inputs, function_input, "An input value or buffer of the format:\n" " [shape]xtype=[value]\n" " 2x2xi32=1 2 3 4\n" "Optionally, brackets may be used to separate the element values:\n" " 2x2xi32=[[1 2][3 4]]\n" "Each occurrence of the flag indicates an input in the order they were\n" "specified on the command line."); namespace iree { namespace { iree_status_t GetModuleContentsFromFlags(std::string* out_contents) { IREE_TRACE_SCOPE0("GetModuleContentsFromFlags"); auto module_file = std::string(FLAG_module_file); if (module_file == "-") { *out_contents = std::string{std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>()}; } else { IREE_RETURN_IF_ERROR(GetFileContents(module_file.c_str(), out_contents)); } return iree_ok_status(); } iree_status_t Run() { IREE_TRACE_SCOPE0("iree-run-module"); IREE_RETURN_IF_ERROR(iree_hal_module_register_types(), "registering HAL types"); iree_vm_instance_t* instance = nullptr; IREE_RETURN_IF_ERROR( iree_vm_instance_create(iree_allocator_system(), &instance), "creating instance"); std::string module_data; IREE_RETURN_IF_ERROR(GetModuleContentsFromFlags(&module_data)); iree_vm_module_t* input_module = nullptr; IREE_RETURN_IF_ERROR(iree_vm_bytecode_module_create( iree_make_const_byte_span((void*)module_data.data(), module_data.size()), iree_allocator_null(), iree_allocator_system(), &input_module)); iree_hal_device_t* device = nullptr; IREE_RETURN_IF_ERROR(CreateDevice(FLAG_driver, &device)); iree_vm_module_t* hal_module = nullptr; IREE_RETURN_IF_ERROR( iree_hal_module_create(device, iree_allocator_system(), &hal_module)); iree_vm_context_t* context = nullptr; // Order matters. The input module will likely be dependent on the hal module. std::array<iree_vm_module_t*, 2> modules = {hal_module, input_module}; IREE_RETURN_IF_ERROR(iree_vm_context_create_with_modules( instance, modules.data(), modules.size(), iree_allocator_system(), &context), "creating context"); std::string function_name = std::string(FLAG_entry_function); iree_vm_function_t function; if (function_name.empty()) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "no --entry_function= specified"); } else { IREE_RETURN_IF_ERROR( input_module->lookup_function( input_module->self, IREE_VM_FUNCTION_LINKAGE_EXPORT, iree_string_view_t{function_name.data(), function_name.size()}, &function), "looking up function '%s'", function_name.c_str()); } vm::ref<iree_vm_list_t> inputs; IREE_CHECK_OK(ParseToVariantList( iree_hal_device_allocator(device), iree::span<const std::string>{FLAG_function_inputs.data(), FLAG_function_inputs.size()}, &inputs)); vm::ref<iree_vm_list_t> outputs; IREE_RETURN_IF_ERROR(iree_vm_list_create(/*element_type=*/nullptr, 16, iree_allocator_system(), &outputs)); std::cout << "EXEC @" << function_name << "\n"; IREE_RETURN_IF_ERROR( iree_vm_invoke(context, function, /*policy=*/nullptr, inputs.get(), outputs.get(), iree_allocator_system()), "invoking function '%s'", function_name.c_str()); IREE_RETURN_IF_ERROR(PrintVariantList(outputs.get()), "printing results"); inputs.reset(); outputs.reset(); iree_vm_module_release(hal_module); iree_vm_module_release(input_module); iree_hal_device_release(device); iree_vm_context_release(context); iree_vm_instance_release(instance); return iree_ok_status(); } } // namespace extern "C" int main(int argc, char** argv) { iree_flags_parse_checked(IREE_FLAGS_PARSE_MODE_DEFAULT, &argc, &argv); if (argc > 1) { // Avoid iree-run-module spinning endlessly on stdin if the user uses single // dashes for flags. std::cout << "Error: unexpected positional argument (expected none)." " Did you use pass a flag with a single dash ('-')?" " Use '--' instead.\n"; return 1; } IREE_CHECK_OK(iree_hal_register_all_available_drivers( iree_hal_driver_registry_default())); IREE_CHECK_OK(Run()); return 0; } } // namespace iree <|endoftext|>
<commit_before>/* \author Geoffrey Biggs */ #include <iostream> #include <boost/thread/thread.hpp> #include "pcl/common/common_headers.h" #include "pcl/common/common_headers.h" #include "pcl/features/normal_3d.h" #include "pcl/io/pcd_io.h" #include "pcl/visualization/pcl_visualizer.h" #include <pcl/console/parse.h> // -------------- // -----Help----- // -------------- void printUsage (const char* progName) { std::cout << "\n\nUsage: "<<progName<<" [options]\n\n" << "Options:\n" << "-------------------------------------------\n" << "-h this help\n" << "-s Simple visualisation example\n" << "-r RGB colour visualisation example\n" << "-c Custom colour visualisation example\n" << "-n Normals visualisation example\n" << "-a Shapes visualisation example\n" << "-v Viewports example\n" << "\n\n"; } boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); viewer->addPointCloud (cloud, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> customColourVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 0, 255, 0); viewer->addPointCloud<pcl::PointXYZ> (cloud, single_color, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> normalsVis ( pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals) { // -------------------------------------------------------- // -----Open 3D viewer and add point cloud and normals----- // -------------------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals, 10, 0.05, "normals"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> shapesVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); //------------------------------------ //-----Add shapes at cloud points----- //------------------------------------ viewer->addLine<pcl::PointXYZRGB> (cloud->points[0], cloud->points[cloud->size() - 1], "line"); viewer->addSphere (cloud->points[0], 0.2, 0.5, 0.5, 0.0, "sphere"); //--------------------------------------- //-----Add shapes at other locations----- //--------------------------------------- pcl::ModelCoefficients coeffs; coeffs.values.push_back (0.0); coeffs.values.push_back (0.0); coeffs.values.push_back (1.0); coeffs.values.push_back (0.0); viewer->addPlane (coeffs, "plane"); coeffs.values.clear (); coeffs.values.push_back (0.3); coeffs.values.push_back (0.3); coeffs.values.push_back (0.0); coeffs.values.push_back (0.0); coeffs.values.push_back (1.0); coeffs.values.push_back (0.0); coeffs.values.push_back (5.0); viewer->addCone (coeffs, "cone"); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> viewportsVis ( pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals1, pcl::PointCloud<pcl::Normal>::ConstPtr normals2) { // -------------------------------------------------------- // -----Open 3D viewer and add point cloud and normals----- // -------------------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->initCameraParameters (); int v1(0); viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1); viewer->setBackgroundColor (0, 0, 0, v1); viewer->addText("Radius: 0.01", 10, 10, "v1 text", v1); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud1", v1); int v2(0); viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2); viewer->setBackgroundColor (0.3, 0.3, 0.3, v2); viewer->addText("Radius: 0.1", 10, 10, "v2 text", v2); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> single_color(cloud, 0, 255, 0); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, single_color, "sample cloud2", v2); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud1"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud2"); viewer->addCoordinateSystem (1.0); viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals1, 10, 0.05, "normals1", v1); viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals2, 10, 0.05, "normals2", v2); return (viewer); } // -------------- // -----Main----- // -------------- int main (int argc, char** argv) { // -------------------------------------- // -----Parse Command Line Arguments----- // -------------------------------------- if (pcl::console::find_argument (argc, argv, "-h") >= 0) { printUsage (argv[0]); return 0; } bool simple(false), rgb(false), custom_c(false), normals(false), shapes(false), viewports(false); if (pcl::console::find_argument (argc, argv, "-s") >= 0) { simple = true; std::cout << "Simple visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-c") >= 0) { custom_c = true; std::cout << "Custom colour visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-r") >= 0) { rgb = true; std::cout << "RGB colour visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-n") >= 0) { normals = true; std::cout << "Normals visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-a") >= 0) { shapes = true; std::cout << "Shapes visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-v") >= 0) { viewports = true; std::cout << "Viewports example\n"; } else { printUsage (argv[0]); return 0; } // ------------------------------------ // -----Create example point cloud----- // ------------------------------------ pcl::PointCloud<pcl::PointXYZ>::Ptr basic_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>); std::cout << "Genarating example point clouds.\n\n"; // We're going to make an ellipse extruded along the z-axis. The colour for // the XYZRGB cloud will gradually go from red to green to blue. uint8_t r(255), g(15), b(15); for (float z(-1.0); z <= 1.0; z += 0.05) { for (float angle(0.0); angle <= 360.0; angle += 5.0) { pcl::PointXYZ basic_point; basic_point.x = 0.5 * cosf (pcl::deg2rad(angle)); basic_point.y = sinf (pcl::deg2rad(angle)); basic_point.z = z; basic_cloud_ptr->points.push_back(basic_point); pcl::PointXYZRGB point; point.x = basic_point.x; point.y = basic_point.y; point.z = basic_point.z; uint32_t rgb = (static_cast<uint32_t>(r) << 16 | static_cast<uint32_t>(g) << 8 | static_cast<uint32_t>(b)); point.rgb = *reinterpret_cast<float*>(&rgb); point_cloud_ptr->points.push_back (point); } if (z < 0.0) { r -= 12; g += 12; } else { g -= 12; b += 12; } } basic_cloud_ptr->width = basic_cloud_ptr->points.size (); basic_cloud_ptr->height = 1; point_cloud_ptr->width = point_cloud_ptr->points.size (); point_cloud_ptr->height = 1; // ---------------------------------------------------------------- // -----Calculate surface normals with a search radius of 0.05----- // ---------------------------------------------------------------- pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne; ne.setInputCloud (point_cloud_ptr); pcl::KdTreeFLANN<pcl::PointXYZRGB>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZRGB> ()); ne.setSearchMethod (tree); pcl::PointCloud<pcl::Normal>::Ptr cloud_normals1 (new pcl::PointCloud<pcl::Normal>); ne.setRadiusSearch (0.05); ne.compute (*cloud_normals1); // --------------------------------------------------------------- // -----Calculate surface normals with a search radius of 0.1----- // --------------------------------------------------------------- pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>); ne.setRadiusSearch (0.1); ne.compute (*cloud_normals2); boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer; if (simple) { viewer = simpleVis(basic_cloud_ptr); } else if (rgb) { viewer = rgbVis(point_cloud_ptr); } else if (custom_c) { viewer = customColourVis(basic_cloud_ptr); } else if (normals) { viewer = normalsVis(point_cloud_ptr, cloud_normals2); } else if (shapes) { viewer = shapesVis(point_cloud_ptr); } else if (viewports) { viewer = viewportsVis(point_cloud_ptr, cloud_normals1, cloud_normals2); } //-------------------- // -----Main loop----- //-------------------- while (!viewer->wasStopped ()) { viewer->spinOnce (100); boost::this_thread::sleep (boost::posix_time::microseconds (100000)); } } <commit_msg>changed name of file back to original<commit_after>/* \author Geoffrey Biggs */ #include <iostream> #include <boost/thread/thread.hpp> #include "pcl/common/common_headers.h" #include "pcl/common/common_headers.h" #include "pcl/features/normal_3d.h" #include "pcl/io/pcd_io.h" #include "pcl/visualization/pcl_visualizer.h" #include <pcl/console/parse.h> // -------------- // -----Help----- // -------------- void printUsage (const char* progName) { std::cout << "\n\nUsage: "<<progName<<" [options]\n\n" << "Options:\n" << "-------------------------------------------\n" << "-h this help\n" << "-s Simple visualisation example\n" << "-r RGB colour visualisation example\n" << "-c Custom colour visualisation example\n" << "-n Normals visualisation example\n" << "-a Shapes visualisation example\n" << "-v Viewports example\n" << "\n\n"; } boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> customColourVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> single_color(cloud, 0, 255, 0); viewer->addPointCloud<pcl::PointXYZ> (cloud, single_color, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> normalsVis ( pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals) { // -------------------------------------------------------- // -----Open 3D viewer and add point cloud and normals----- // -------------------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals, 10, 0.05, "normals"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> shapesVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); viewer->addCoordinateSystem (1.0); viewer->initCameraParameters (); //------------------------------------ //-----Add shapes at cloud points----- //------------------------------------ viewer->addLine<pcl::PointXYZRGB> (cloud->points[0], cloud->points[cloud->size() - 1], "line"); viewer->addSphere (cloud->points[0], 0.2, 0.5, 0.5, 0.0, "sphere"); //--------------------------------------- //-----Add shapes at other locations----- //--------------------------------------- pcl::ModelCoefficients coeffs; coeffs.values.push_back (0.0); coeffs.values.push_back (0.0); coeffs.values.push_back (1.0); coeffs.values.push_back (0.0); viewer->addPlane (coeffs, "plane"); coeffs.values.clear (); coeffs.values.push_back (0.3); coeffs.values.push_back (0.3); coeffs.values.push_back (0.0); coeffs.values.push_back (0.0); coeffs.values.push_back (1.0); coeffs.values.push_back (0.0); coeffs.values.push_back (5.0); viewer->addCone (coeffs, "cone"); return (viewer); } boost::shared_ptr<pcl::visualization::PCLVisualizer> viewportsVis ( pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals1, pcl::PointCloud<pcl::Normal>::ConstPtr normals2) { // -------------------------------------------------------- // -----Open 3D viewer and add point cloud and normals----- // -------------------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->initCameraParameters (); int v1(0); viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1); viewer->setBackgroundColor (0, 0, 0, v1); viewer->addText("Radius: 0.01", 10, 10, "v1 text", v1); pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud1", v1); int v2(0); viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2); viewer->setBackgroundColor (0.3, 0.3, 0.3, v2); viewer->addText("Radius: 0.1", 10, 10, "v2 text", v2); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> single_color(cloud, 0, 255, 0); viewer->addPointCloud<pcl::PointXYZRGB> (cloud, single_color, "sample cloud2", v2); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud1"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud2"); viewer->addCoordinateSystem (1.0); viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals1, 10, 0.05, "normals1", v1); viewer->addPointCloudNormals<pcl::PointXYZRGB, pcl::Normal> (cloud, normals2, 10, 0.05, "normals2", v2); return (viewer); } // -------------- // -----Main----- // -------------- int main (int argc, char** argv) { // -------------------------------------- // -----Parse Command Line Arguments----- // -------------------------------------- if (pcl::console::find_argument (argc, argv, "-h") >= 0) { printUsage (argv[0]); return 0; } bool simple(false), rgb(false), custom_c(false), normals(false), shapes(false), viewports(false); if (pcl::console::find_argument (argc, argv, "-s") >= 0) { simple = true; std::cout << "Simple visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-c") >= 0) { custom_c = true; std::cout << "Custom colour visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-r") >= 0) { rgb = true; std::cout << "RGB colour visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-n") >= 0) { normals = true; std::cout << "Normals visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-a") >= 0) { shapes = true; std::cout << "Shapes visualisation example\n"; } else if (pcl::console::find_argument (argc, argv, "-v") >= 0) { viewports = true; std::cout << "Viewports example\n"; } else { printUsage (argv[0]); return 0; } // ------------------------------------ // -----Create example point cloud----- // ------------------------------------ pcl::PointCloud<pcl::PointXYZ>::Ptr basic_cloud_ptr (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZRGB>::Ptr point_cloud_ptr (new pcl::PointCloud<pcl::PointXYZRGB>); std::cout << "Genarating example point clouds.\n\n"; // We're going to make an ellipse extruded along the z-axis. The colour for // the XYZRGB cloud will gradually go from red to green to blue. uint8_t r(255), g(15), b(15); for (float z(-1.0); z <= 1.0; z += 0.05) { for (float angle(0.0); angle <= 360.0; angle += 5.0) { pcl::PointXYZ basic_point; basic_point.x = 0.5 * cosf (pcl::deg2rad(angle)); basic_point.y = sinf (pcl::deg2rad(angle)); basic_point.z = z; basic_cloud_ptr->points.push_back(basic_point); pcl::PointXYZRGB point; point.x = basic_point.x; point.y = basic_point.y; point.z = basic_point.z; uint32_t rgb = (static_cast<uint32_t>(r) << 16 | static_cast<uint32_t>(g) << 8 | static_cast<uint32_t>(b)); point.rgb = *reinterpret_cast<float*>(&rgb); point_cloud_ptr->points.push_back (point); } if (z < 0.0) { r -= 12; g += 12; } else { g -= 12; b += 12; } } basic_cloud_ptr->width = basic_cloud_ptr->points.size (); basic_cloud_ptr->height = 1; point_cloud_ptr->width = point_cloud_ptr->points.size (); point_cloud_ptr->height = 1; // ---------------------------------------------------------------- // -----Calculate surface normals with a search radius of 0.05----- // ---------------------------------------------------------------- pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> ne; ne.setInputCloud (point_cloud_ptr); pcl::KdTreeFLANN<pcl::PointXYZRGB>::Ptr tree (new pcl::KdTreeFLANN<pcl::PointXYZRGB> ()); ne.setSearchMethod (tree); pcl::PointCloud<pcl::Normal>::Ptr cloud_normals1 (new pcl::PointCloud<pcl::Normal>); ne.setRadiusSearch (0.05); ne.compute (*cloud_normals1); // --------------------------------------------------------------- // -----Calculate surface normals with a search radius of 0.1----- // --------------------------------------------------------------- pcl::PointCloud<pcl::Normal>::Ptr cloud_normals2 (new pcl::PointCloud<pcl::Normal>); ne.setRadiusSearch (0.1); ne.compute (*cloud_normals2); boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer; if (simple) { viewer = simpleVis(basic_cloud_ptr); } else if (rgb) { viewer = rgbVis(point_cloud_ptr); } else if (custom_c) { viewer = customColourVis(basic_cloud_ptr); } else if (normals) { viewer = normalsVis(point_cloud_ptr, cloud_normals2); } else if (shapes) { viewer = shapesVis(point_cloud_ptr); } else if (viewports) { viewer = viewportsVis(point_cloud_ptr, cloud_normals1, cloud_normals2); } //-------------------- // -----Main loop----- //-------------------- while (!viewer->wasStopped ()) { viewer->spinOnce (100); boost::this_thread::sleep (boost::posix_time::microseconds (100000)); } } <|endoftext|>
<commit_before>#include "srs_figure_rtmp_chunk.h" #include "../app/srs_figure_app_log.h" using namespace srs_rtmp_chunk; rtmp_chunk::rtmp_chunk(unsigned long lChunkStreamID,unsigned char cMessageType,long lTimeStamp): mChunkBasicHeader(basic_header_error), mpBasicHeader(nullptr), mTimeStamp(lTimeStamp), mMessageStreamID(0), mMessageStreamType(cMessageType), mChunkStreamID(lChunkStreamID), max_chunk_data_size(128) { // format mpBasicHeader if(mChunkStreamID < 64) { mpBasicHeader = new char[1]; mpBasicHeader[0] = mChunkStreamID; } else if(mChunkStreamID < 319) { mpBasicHeader = new char[2]; mChunkBasicHeader = basic_header_type1; mpBasicHeader[0] = 0; mpBasicHeader[1] = mChunkStreamID - 64; } else if(mChunkStreamID <= 65599) { mpBasicHeader = new char[3]; mChunkBasicHeader = basic_header_type2; mpBasicHeader[0] = 1; if(mChunkStreamID % 256 < 64) { mpBasicHeader[2] = mChunkStreamID / 256 - 1; mpBasicHeader[1] = mChunkStreamID - mpBasicHeader[2] * 256 - 64; } else { mpBasicHeader[2] = mChunkStreamID / 256; mpBasicHeader[1] = mChunkStreamID - mpBasicHeader[2] * 256 - 64; } } else { mChunkBasicHeader = basic_header_error; srs_figure_log::getInstance()->log("Error","rtmp chunk create","fail to initalize chunk header,the chunk stream ID %d is out of range",mChunkStreamID); } } rtmp_chunk::~rtmp_chunk() { if(mpBasicHeader != nullptr) delete[] mpBasicHeader; } std::vector<std::string> rtmp_chunk::AssembleOneDataChunk(std::string pMsg,enChunkDataType chunkType,enMessageCtrlTypeID msgCtrlTypeID, long MsgStreamID,long timeStamp) { mChunkList.clear(); if(mChunkBasicHeader ==basic_header_error) return mChunkList; if(pMsg.size() > max_chunk_data_size) { int loopTimes = pMsg.size() / max_chunk_data_size; // the first package, we should set the message header as type 0 std::string chunkPackage_0,chunkHeader_0; AssembleDataHeader(chunkHeader_0,THIRD_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader_0.size() > 0) { chunkPackage_0 += chunkHeader_0; chunkPackage_0 += pMsg.substr(0,max_chunk_data_size-1); mChunkList.push_back(chunkPackage_0); } // middle package the message header is type 3 int i = 1; for(i = 1; i < loopTimes; i++)// const size aka max_chunk_data_size { std::string chunkPackage,chunkHeader; AssembleDataHeader(chunkHeader,THIRD_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader.size() > 0) { chunkPackage += chunkHeader; chunkPackage += pMsg.substr(i * max_chunk_data_size,(i+1) * max_chunk_data_size-1); mChunkList.push_back(chunkPackage); } } // the last package, the chunkdata size is not const and message header is type 3 std::string chunkPackage,chunkHeader; AssembleDataHeader(chunkHeader,THIRD_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader.size() > 0) { chunkPackage += chunkHeader; chunkPackage += pMsg.substr(i * max_chunk_data_size-1,pMsg.size()); mChunkList.push_back(chunkPackage); } } else { // message header is type 0 std::string chunkPackage,chunkHeader; AssembleDataHeader(chunkHeader,ZEARO_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader.size() > 0) { chunkPackage += chunkHeader; chunkPackage += pMsg; mChunkList.push_back(chunkPackage); } } return mChunkList; } long rtmp_chunk::AssembleDataHeader(std::string& msg ,chunk_state chunkState,enChunkDataType ChunkType,enMessageCtrlTypeID msgCtrlTypeID, long MsgStreamID,long timeStamp) { char* pMessageHeader = nullptr; int msgSize = 0,timeForWrite = 0; char* p = nullptr; switch(chunkState) { case ZEARO_CHUNK: // FMT is 0 mpBasicHeader[0] = mpBasicHeader[0] & 0x3F; pMessageHeader = new char[11]; // write timestamp 3 bytes timeForWrite = timeStamp < 0xFFFFFF ? timeStamp:0xFFFFFF; p = (char*)&timeForWrite; pMessageHeader[0] = p[0]; pMessageHeader[1] = p[1]; pMessageHeader[2] = p[2]; // write message length 3 bytes p = (char*)&msgSize; pMessageHeader[3] = p[0]; pMessageHeader[4] = p[1]; pMessageHeader[5] = p[2]; //message type id, 1 bytes pMessageHeader[6] = ChunkType == VIDEO_DATA_CHUNK ? 9 :(ChunkType == AUDIO_DATA_CHUNK ? 8 : msgCtrlTypeID); //message stream ID; p = (char*)MsgStreamID; pMessageHeader[7] = p[0]; pMessageHeader[8] = p[1]; pMessageHeader[9] = p[2]; pMessageHeader[10] = p[3]; break; case FIRST_CHUNK: // FMT is 1 mpBasicHeader[0] = (mpBasicHeader[0] & 0x3F) | 0x80; pMessageHeader = new char[3]; break; case SECOND_CHUNK: // FMT is 2 mpBasicHeader[0] = (mpBasicHeader[0] & 0x3F) | 0xC0; break; case THIRD_CHUNK: // FMT is 3 mpBasicHeader[0] = (mpBasicHeader[0] & 0x3F) | 0xF0; break; } //make up the chunk header msg += mpBasicHeader; msg += pMessageHeader; // judge for extern timestamp // if(pMessageHeader != nullptr) delete[] pMessageHeader; return RESULT_OK; } std::vector<std::string> rtmp_chunk::AssembleOneControlChunk(enMessageCtrlTypeID msgCtrlTypeID, long MsgStreamID,long acknowledgementSize ,char limitType) { mChunkList.clear(); // In this situation we send only on chunk package std::string strPayload; char* tmp = nullptr; switch(msgCtrlTypeID) { case MESSAGE_CONTROL_TYPE_1: // get chunk size tmp = (char*)&max_chunk_data_size; tmp[0] &=0x7F; strPayload = tmp; break; case MESSAGE_CONTROL_TYPE_2: // abort message tmp = (char*)&mChunkStreamID; strPayload = tmp; break; case MESSAGE_CONTROL_TYPE_3: case MESSAGE_CONTROL_TYPE_5: // acknowledgement tmp = (char*)&acknowledgementSize; strPayload = tmp; break; case MESSAGE_CONTROL_TYPE_6: tmp = (char*)&acknowledgementSize; strPayload = tmp; strPayload += limitType; break; default: return mChunkList; } return AssembleOneDataChunk(strPayload,MESSAGE_CONTROL_CHUNK,msgCtrlTypeID,MsgStreamID); } void rtmp_chunk::DecodeOndeDataChunk(std::string pMsg) { int chunk_stream_id = 0; const char* cpMsg = pMsg.c_str(); // decode basic header int bhType = cpMsg[0] & 0x3F;// judge the basic header type if(bhType == 0)// 2 bytes { chunk_stream_id = 256 * pMsg[2] + pMsg[1] + 64; } else if(bhType == 1)// 3 bytes { chunk_stream_id = pMsg[1] + 64; } else// 1 bytes { chunk_stream_id = pMsg[0] & 0x3F; } switch(pMsg[0] & 0xC0) { case 0: break; case 1: break; case 2: break; case 3: break; default: srs_figure_log::getInstance()->log("Error","decodeChunk","get error chunk package"); return; } // decode chunk header // get payload } <commit_msg>finish decoding one chunk<commit_after>#include "srs_figure_rtmp_chunk.h" #include "../app/srs_figure_app_log.h" using namespace srs_rtmp_chunk; rtmp_chunk::rtmp_chunk(unsigned long lChunkStreamID,unsigned char cMessageType,long lTimeStamp): mChunkBasicHeader(basic_header_error), mpBasicHeader(nullptr), mTimeStamp(lTimeStamp), mMessageStreamID(0), mMessageStreamType(cMessageType), mChunkStreamID(lChunkStreamID), max_chunk_data_size(128) { // format mpBasicHeader if(mChunkStreamID < 64) { mpBasicHeader = new char[1]; mpBasicHeader[0] = mChunkStreamID; } else if(mChunkStreamID < 319) { mpBasicHeader = new char[2]; mChunkBasicHeader = basic_header_type1; mpBasicHeader[0] = 0; mpBasicHeader[1] = mChunkStreamID - 64; } else if(mChunkStreamID <= 65599) { mpBasicHeader = new char[3]; mChunkBasicHeader = basic_header_type2; mpBasicHeader[0] = 1; if(mChunkStreamID % 256 < 64) { mpBasicHeader[2] = mChunkStreamID / 256 - 1; mpBasicHeader[1] = mChunkStreamID - mpBasicHeader[2] * 256 - 64; } else { mpBasicHeader[2] = mChunkStreamID / 256; mpBasicHeader[1] = mChunkStreamID - mpBasicHeader[2] * 256 - 64; } } else { mChunkBasicHeader = basic_header_error; srs_figure_log::getInstance()->log("Error","rtmp chunk create","fail to initalize chunk header,the chunk stream ID %d is out of range",mChunkStreamID); } } rtmp_chunk::~rtmp_chunk() { if(mpBasicHeader != nullptr) delete[] mpBasicHeader; } std::vector<std::string> rtmp_chunk::AssembleOneDataChunk(std::string pMsg,enChunkDataType chunkType,enMessageCtrlTypeID msgCtrlTypeID, long MsgStreamID,long timeStamp) { mChunkList.clear(); if(mChunkBasicHeader ==basic_header_error) return mChunkList; if(pMsg.size() > max_chunk_data_size) { int loopTimes = pMsg.size() / max_chunk_data_size; // the first package, we should set the message header as type 0 std::string chunkPackage_0,chunkHeader_0; AssembleDataHeader(chunkHeader_0,THIRD_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader_0.size() > 0) { chunkPackage_0 += chunkHeader_0; chunkPackage_0 += pMsg.substr(0,max_chunk_data_size-1); mChunkList.push_back(chunkPackage_0); } // middle package the message header is type 3 int i = 1; for(i = 1; i < loopTimes; i++)// const size aka max_chunk_data_size { std::string chunkPackage,chunkHeader; AssembleDataHeader(chunkHeader,THIRD_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader.size() > 0) { chunkPackage += chunkHeader; chunkPackage += pMsg.substr(i * max_chunk_data_size,(i+1) * max_chunk_data_size-1); mChunkList.push_back(chunkPackage); } } // the last package, the chunkdata size is not const and message header is type 3 std::string chunkPackage,chunkHeader; AssembleDataHeader(chunkHeader,THIRD_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader.size() > 0) { chunkPackage += chunkHeader; chunkPackage += pMsg.substr(i * max_chunk_data_size-1,pMsg.size()); mChunkList.push_back(chunkPackage); } } else { // message header is type 0 std::string chunkPackage,chunkHeader; AssembleDataHeader(chunkHeader,ZEARO_CHUNK,chunkType,msgCtrlTypeID,MsgStreamID,timeStamp); if(chunkHeader.size() > 0) { chunkPackage += chunkHeader; chunkPackage += pMsg; mChunkList.push_back(chunkPackage); } } return mChunkList; } long rtmp_chunk::AssembleDataHeader(std::string& msg ,chunk_state chunkState,enChunkDataType ChunkType,enMessageCtrlTypeID msgCtrlTypeID, long MsgStreamID,long timeStamp) { char* pMessageHeader = nullptr; int msgSize = 0,timeForWrite = 0; char* p = nullptr; switch(chunkState) { case ZEARO_CHUNK: // FMT is 0 mpBasicHeader[0] = mpBasicHeader[0] & 0x3F; pMessageHeader = new char[11]; // write timestamp 3 bytes timeForWrite = timeStamp < 0xFFFFFF ? timeStamp:0xFFFFFF; p = (char*)&timeForWrite; pMessageHeader[0] = p[0]; pMessageHeader[1] = p[1]; pMessageHeader[2] = p[2]; // write message length 3 bytes p = (char*)&msgSize; pMessageHeader[3] = p[0]; pMessageHeader[4] = p[1]; pMessageHeader[5] = p[2]; //message type id, 1 bytes pMessageHeader[6] = ChunkType == VIDEO_DATA_CHUNK ? 9 :(ChunkType == AUDIO_DATA_CHUNK ? 8 : msgCtrlTypeID); //message stream ID; p = (char*)MsgStreamID; pMessageHeader[7] = p[0]; pMessageHeader[8] = p[1]; pMessageHeader[9] = p[2]; pMessageHeader[10] = p[3]; break; case FIRST_CHUNK: // FMT is 1 mpBasicHeader[0] = (mpBasicHeader[0] & 0x3F) | 0x80; pMessageHeader = new char[3]; break; case SECOND_CHUNK: // FMT is 2 mpBasicHeader[0] = (mpBasicHeader[0] & 0x3F) | 0xC0; break; case THIRD_CHUNK: // FMT is 3 mpBasicHeader[0] = (mpBasicHeader[0] & 0x3F) | 0xF0; break; } //make up the chunk header msg += mpBasicHeader; msg += pMessageHeader; // judge for extern timestamp // if(pMessageHeader != nullptr) delete[] pMessageHeader; return RESULT_OK; } std::vector<std::string> rtmp_chunk::AssembleOneControlChunk(enMessageCtrlTypeID msgCtrlTypeID, long MsgStreamID,long acknowledgementSize ,char limitType) { mChunkList.clear(); // In this situation we send only on chunk package std::string strPayload; char* tmp = nullptr; switch(msgCtrlTypeID) { case MESSAGE_CONTROL_TYPE_1: // get chunk size tmp = (char*)&max_chunk_data_size; tmp[0] &=0x7F; strPayload = tmp; break; case MESSAGE_CONTROL_TYPE_2: // abort message tmp = (char*)&mChunkStreamID; strPayload = tmp; break; case MESSAGE_CONTROL_TYPE_3: case MESSAGE_CONTROL_TYPE_5: // acknowledgement tmp = (char*)&acknowledgementSize; strPayload = tmp; break; case MESSAGE_CONTROL_TYPE_6: tmp = (char*)&acknowledgementSize; strPayload = tmp; strPayload += limitType; break; default: return mChunkList; } return AssembleOneDataChunk(strPayload,MESSAGE_CONTROL_CHUNK,msgCtrlTypeID,MsgStreamID); } void rtmp_chunk::DecodeOndeDataChunk(std::string pMsg) { int chunk_stream_id = 0,offset = 0; const char* cpMsg = pMsg.c_str(); // extra info int32_t timestamp = 0; int32_t messageLength = 0; char messageTypeId = 0; int32_t messageStreamID = 0; int32_t messageHeaderType = 0; std::string payload = ""; // decode basic header int bhType = cpMsg[0] & 0x3F;// judge the basic header type if(bhType == 0)// 2 bytes { chunk_stream_id = 256 * pMsg[2] + pMsg[1] + 64; offset += 2; } else if(bhType == 1)// 3 bytes { chunk_stream_id = pMsg[1] + 64; offset += 3; } else// 1 bytes { chunk_stream_id = pMsg[0] & 0x3F; offset += 1; } char* pMsgHeader = nullptr; char* tmp = nullptr; messageHeaderType = pMsg[0] & 0xC0; switch(messageHeaderType) { case 0: pMsgHeader = new char[11]; memcpy(pMsgHeader,cpMsg+offset,11); // time stamp tmp = (char*)&timestamp; tmp[2] = pMsgHeader[0]; tmp[1] = pMsgHeader[1]; tmp[0] = pMsgHeader[2]; // message stream lenght tmp = (char*)&messageLength; tmp[2] = pMsgHeader[3]; tmp[1] = pMsgHeader[4]; tmp[0] = pMsgHeader[5]; // message type id messageTypeId = pMsgHeader[6]; // message stream id tmp = (char*)&messageStreamID; tmp[3] = pMsgHeader[7]; tmp[2] = pMsgHeader[8]; tmp[1] = pMsgHeader[9]; tmp[0] = pMsgHeader[10]; offset += 11; break; case 1: pMsgHeader = new char[7]; memcpy(pMsgHeader,cpMsg+offset,7); offset += 7; // time stamp tmp = (char*)&timestamp; tmp[2] = pMsgHeader[0]; tmp[1] = pMsgHeader[1]; tmp[0] = pMsgHeader[2]; // message stream lenght tmp = (char*)&messageLength; tmp[2] = pMsgHeader[3]; tmp[1] = pMsgHeader[4]; tmp[0] = pMsgHeader[5]; // message type id messageTypeId = pMsgHeader[6]; break; case 2: pMsgHeader = new char[3]; memcpy(pMsgHeader,cpMsg+offset,3); offset += 3; // time stamp tmp = (char*)&timestamp; tmp[2] = pMsgHeader[0]; tmp[1] = pMsgHeader[1]; tmp[0] = pMsgHeader[2]; break; case 3: break; default: srs_figure_log::getInstance()->log("Error","decodeChunk","get error chunk package"); return; } payload += &pMsgHeader[offset]; if(chunk_stream_id == 2) { // control message const char* pPayload = payload.c_str(); int32_t getChunkStreamID = 0; int32_t getSequenceNum = 0; int32_t getAcknowledgeSize = 0; char getLimitType = 0; switch (messageTypeId) { case 1: tmp = (char*)&max_chunk_data_size; tmp [3] = pPayload[0]; tmp [2] = pPayload[1]; tmp [1] = pPayload[2]; tmp [0] = pPayload[3]; break; case 2: tmp = (char*)&getChunkStreamID; tmp [3] = pPayload[0]; tmp [2] = pPayload[1]; tmp [1] = pPayload[2]; tmp [0] = pPayload[3]; break; case 3: tmp = (char*)&getSequenceNum; tmp [3] = pPayload[0]; tmp [2] = pPayload[1]; tmp [1] = pPayload[2]; tmp [0] = pPayload[3]; break; case 5: tmp = (char*)&getAcknowledgeSize; tmp [3] = pPayload[0]; tmp [2] = pPayload[1]; tmp [1] = pPayload[2]; tmp [0] = pPayload[3]; break; case 6: tmp = (char*)&getAcknowledgeSize; tmp [3] = pPayload[0]; tmp [2] = pPayload[1]; tmp [1] = pPayload[2]; tmp [0] = pPayload[3]; getLimitType = pPayload[4]; break; } } // get payload if(pMsgHeader != nullptr) delete[] pMsgHeader; } <|endoftext|>
<commit_before>// // File: RenderCommandEncoder.cpp // Author: Hongtae Kim ([email protected]) // // Copyright (c) 2016-2017 Hongtae Kim. All rights reserved. // #include "../GraphicsAPI.h" #if DKGL_ENABLE_VULKAN #include "RenderCommandEncoder.h" #include "Texture.h" #include "GraphicsDevice.h" using namespace DKFramework; using namespace DKFramework::Private::Vulkan; RenderCommandEncoder::Resources::Resources(CommandBuffer* b) : cb(b) , framebuffer(VK_NULL_HANDLE) , renderPass(VK_NULL_HANDLE) , commandBuffer(VK_NULL_HANDLE) { } RenderCommandEncoder::Resources::~Resources(void) { GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(cb->Queue()->Device()); VkDevice device = dev->device; if (renderPass) vkDestroyRenderPass(device, renderPass, nullptr); if (framebuffer) vkDestroyFramebuffer(device, framebuffer, nullptr); if (commandBuffer) cb->ReleaseEncodingBuffer(commandBuffer); } RenderCommandEncoder::RenderCommandEncoder(VkCommandBuffer vcb, CommandBuffer* cb, const DKRenderPassDescriptor& desc) : commandBuffer(cb) { resources = DKOBJECT_NEW Resources(cb); resources->commandBuffer = vcb; DKASSERT_DEBUG(resources->commandBuffer); uint32_t frameWidth = 0; uint32_t frameHeight = 0; DKArray<VkAttachmentDescription> attachments; attachments.Reserve(desc.colorAttachments.Count() + 1); DKArray<VkAttachmentReference> colorReferences; colorReferences.Reserve(desc.colorAttachments.Count()); DKArray<VkImageView> framebufferImageViews; framebufferImageViews.Reserve(desc.colorAttachments.Count() + 1); DKArray<VkClearValue> attachmentClearValues; attachmentClearValues.Reserve(desc.colorAttachments.Count() + 1); for (const DKRenderPassColorAttachmentDescriptor& colorAttachment : desc.colorAttachments) { const Texture* rt = colorAttachment.renderTarget.SafeCast<Texture>(); if (rt) { AddWaitSemaphore(rt->waitSemaphore, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); AddSignalSemaphore(rt->signalSemaphore); VkAttachmentDescription attachment = {}; attachment.format = rt->format; attachment.samples = VK_SAMPLE_COUNT_1_BIT; switch (colorAttachment.loadAction) { case DKRenderPassAttachmentDescriptor::LoadActionLoad: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; break; case DKRenderPassAttachmentDescriptor::LoadActionClear: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; break; default: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; break; } switch (colorAttachment.storeAction) { case DKRenderPassAttachmentDescriptor::StoreActionDontCare: attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; break; case DKRenderPassAttachmentDescriptor::StoreActionStore: attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; break; } attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference attachmentReference = {}; attachmentReference.attachment = static_cast<uint32_t>(attachments.Count()); attachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachments.Add(attachment); colorReferences.Add(attachmentReference); framebufferImageViews.Add(rt->imageView); VkClearValue clearValue = {}; clearValue.color = { colorAttachment.clearColor.r, colorAttachment.clearColor.g, colorAttachment.clearColor.b, colorAttachment.clearColor.a }; attachmentClearValues.Add(clearValue); frameWidth = (frameWidth > 0) ? Min(frameWidth, rt->Width()) : rt->Width(); frameHeight = (frameHeight > 0) ? Min(frameHeight, rt->Height()) : rt->Height(); } } VkAttachmentReference depthStencilReference = {}; depthStencilReference.attachment = VK_ATTACHMENT_UNUSED; depthStencilReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; if (desc.depthStencilAttachment.renderTarget) { const DKRenderPassDepthStencilAttachmentDescriptor& depthStencilAttachment = desc.depthStencilAttachment; const Texture* rt = depthStencilAttachment.renderTarget.SafeCast<Texture>(); if (rt) { AddWaitSemaphore(rt->waitSemaphore, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); AddSignalSemaphore(rt->signalSemaphore); VkAttachmentDescription attachment = {}; attachment.format = rt->format; attachment.samples = VK_SAMPLE_COUNT_1_BIT; switch (depthStencilAttachment.loadAction) { case DKRenderPassAttachmentDescriptor::LoadActionLoad: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; break; case DKRenderPassAttachmentDescriptor::LoadActionClear: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; break; default: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; break; } switch (depthStencilAttachment.storeAction) { case DKRenderPassAttachmentDescriptor::StoreActionDontCare: attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; break; case DKRenderPassAttachmentDescriptor::StoreActionStore: attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; break; } attachment.stencilLoadOp = attachment.loadOp; attachment.stencilStoreOp = attachment.storeOp; attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; depthStencilReference.attachment = static_cast<uint32_t>(attachments.Count()); attachments.Add(attachment); framebufferImageViews.Add(rt->imageView); VkClearValue clearValue = {}; clearValue.depthStencil.depth = depthStencilAttachment.clearDepth; clearValue.depthStencil.stencil = depthStencilAttachment.clearStencil; attachmentClearValues.Add(clearValue); frameWidth = (frameWidth > 0) ? Min(frameWidth, rt->Width()) : rt->Width(); frameHeight = (frameHeight > 0) ? Min(frameHeight, rt->Height()) : rt->Height(); } } VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = static_cast<uint32_t>(colorReferences.Count()); subpassDescription.pColorAttachments = colorReferences; subpassDescription.pDepthStencilAttachment = &depthStencilReference; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; subpassDescription.pResolveAttachments = nullptr; VkRenderPassCreateInfo renderPassCreateInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; renderPassCreateInfo.attachmentCount = static_cast<uint32_t>(attachments.Count()); renderPassCreateInfo.pAttachments = attachments; renderPassCreateInfo.subpassCount = 1; renderPassCreateInfo.pSubpasses = &subpassDescription; GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(commandBuffer->Queue()->Device()); VkDevice device = dev->device; VkResult err = vkCreateRenderPass(device, &renderPassCreateInfo, nullptr, &resources->renderPass); if (err != VK_SUCCESS) { DKLogE("ERROR: vkCreateRenderPass failed: %s", VkResultCStr(err)); DKASSERT(err == VK_SUCCESS); } VkFramebufferCreateInfo frameBufferCreateInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; frameBufferCreateInfo.renderPass = resources->renderPass; frameBufferCreateInfo.attachmentCount = static_cast<uint32_t>(framebufferImageViews.Count()); frameBufferCreateInfo.pAttachments = framebufferImageViews; frameBufferCreateInfo.width = frameWidth; frameBufferCreateInfo.height = frameHeight; frameBufferCreateInfo.layers = 1; err = vkCreateFramebuffer(device, &frameBufferCreateInfo, nullptr, &resources->framebuffer); if (err != VK_SUCCESS) { DKLogE("ERROR: vkCreateFramebuffer failed: %s", VkResultCStr(err)); DKASSERT(err == VK_SUCCESS); } VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; vkBeginCommandBuffer(resources->commandBuffer, &commandBufferBeginInfo); VkRenderPassBeginInfo renderPassBeginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; renderPassBeginInfo.renderPass = resources->renderPass; renderPassBeginInfo.clearValueCount = static_cast<uint32_t>(attachmentClearValues.Count()); renderPassBeginInfo.pClearValues = attachmentClearValues; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = frameWidth; renderPassBeginInfo.renderArea.extent.height = frameHeight; renderPassBeginInfo.framebuffer = resources->framebuffer; vkCmdBeginRenderPass(resources->commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = {}; viewport.height = (float)frameHeight; viewport.width = (float)frameWidth; viewport.minDepth = (float) 0.0f; viewport.maxDepth = (float) 1.0f; vkCmdSetViewport(resources->commandBuffer, 0, 1, &viewport); } RenderCommandEncoder::~RenderCommandEncoder(void) { resources = NULL; } void RenderCommandEncoder::AddWaitSemaphore(VkSemaphore semaphore, VkPipelineStageFlags flags) { if (semaphore != VK_NULL_HANDLE) { if (!semaphorePipelineStageMasks.Insert(semaphore, flags)) semaphorePipelineStageMasks.Value(semaphore) |= flags; } } void RenderCommandEncoder::AddSignalSemaphore(VkSemaphore semaphore) { if (semaphore != VK_NULL_HANDLE) signalSemaphores.Insert(semaphore); } void RenderCommandEncoder::EndEncoding(void) { vkCmdEndRenderPass(resources->commandBuffer); VkResult err = vkEndCommandBuffer(resources->commandBuffer); if (err != VK_SUCCESS) { DKLogE("ERROR: vkEndCommandBuffer failed: %s", VkResultCStr(err)); DKASSERT(err == VK_SUCCESS); } VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &resources->commandBuffer; resources->waitSemaphores.Reserve(semaphorePipelineStageMasks.Count()); resources->waitStageMasks.Reserve(semaphorePipelineStageMasks.Count()); semaphorePipelineStageMasks.EnumerateForward([&](decltype(semaphorePipelineStageMasks)::Pair& pair) { resources->waitSemaphores.Add(pair.key); resources->waitStageMasks.Add(pair.value); }); resources->signalSemaphores.Reserve(signalSemaphores.Count()); signalSemaphores.EnumerateForward([&](VkSemaphore semaphore) { resources->signalSemaphores.Add(semaphore); }); DKASSERT_DEBUG(resources->waitSemaphores.Count() == resources->waitStageMasks.Count()); submitInfo.waitSemaphoreCount = resources->waitSemaphores.Count(); submitInfo.pWaitSemaphores = resources->waitSemaphores; submitInfo.pWaitDstStageMask = resources->waitStageMasks; submitInfo.signalSemaphoreCount = resources->signalSemaphores.Count(); submitInfo.pSignalSemaphores = resources->signalSemaphores; commandBuffer->Submit(submitInfo, DKFunction([=](DKObject<Resources> res) { res = NULL; })->Invocation(resources)); resources = NULL; semaphorePipelineStageMasks.Clear(); signalSemaphores.Clear(); } DKCommandBuffer* RenderCommandEncoder::Buffer(void) { return commandBuffer; } #endif //#if DKGL_ENABLE_VULKAN <commit_msg>no message<commit_after>// // File: RenderCommandEncoder.cpp // Author: Hongtae Kim ([email protected]) // // Copyright (c) 2016-2017 Hongtae Kim. All rights reserved. // #include "../GraphicsAPI.h" #if DKGL_ENABLE_VULKAN #include "RenderCommandEncoder.h" #include "Texture.h" #include "GraphicsDevice.h" using namespace DKFramework; using namespace DKFramework::Private::Vulkan; RenderCommandEncoder::Resources::Resources(CommandBuffer* b) : cb(b) , framebuffer(VK_NULL_HANDLE) , renderPass(VK_NULL_HANDLE) , commandBuffer(VK_NULL_HANDLE) { } RenderCommandEncoder::Resources::~Resources(void) { GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(cb->Queue()->Device()); VkDevice device = dev->device; if (renderPass) vkDestroyRenderPass(device, renderPass, nullptr); if (framebuffer) vkDestroyFramebuffer(device, framebuffer, nullptr); if (commandBuffer) cb->ReleaseEncodingBuffer(commandBuffer); } RenderCommandEncoder::RenderCommandEncoder(VkCommandBuffer vcb, CommandBuffer* cb, const DKRenderPassDescriptor& desc) : commandBuffer(cb) { resources = DKOBJECT_NEW Resources(cb); resources->commandBuffer = vcb; DKASSERT_DEBUG(resources->commandBuffer); uint32_t frameWidth = 0; uint32_t frameHeight = 0; DKArray<VkAttachmentDescription> attachments; attachments.Reserve(desc.colorAttachments.Count() + 1); DKArray<VkAttachmentReference> colorReferences; colorReferences.Reserve(desc.colorAttachments.Count()); DKArray<VkImageView> framebufferImageViews; framebufferImageViews.Reserve(desc.colorAttachments.Count() + 1); DKArray<VkClearValue> attachmentClearValues; attachmentClearValues.Reserve(desc.colorAttachments.Count() + 1); for (const DKRenderPassColorAttachmentDescriptor& colorAttachment : desc.colorAttachments) { const Texture* rt = colorAttachment.renderTarget.SafeCast<Texture>(); if (rt) { AddWaitSemaphore(rt->waitSemaphore, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); AddSignalSemaphore(rt->signalSemaphore); VkAttachmentDescription attachment = {}; attachment.format = rt->format; attachment.samples = VK_SAMPLE_COUNT_1_BIT; // 1 sample per pixel switch (colorAttachment.loadAction) { case DKRenderPassAttachmentDescriptor::LoadActionLoad: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; break; case DKRenderPassAttachmentDescriptor::LoadActionClear: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; break; default: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; break; } switch (colorAttachment.storeAction) { case DKRenderPassAttachmentDescriptor::StoreActionDontCare: attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; break; case DKRenderPassAttachmentDescriptor::StoreActionStore: attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; break; } attachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; attachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; VkAttachmentReference attachmentReference = {}; attachmentReference.attachment = static_cast<uint32_t>(attachments.Count()); attachmentReference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; attachments.Add(attachment); colorReferences.Add(attachmentReference); framebufferImageViews.Add(rt->imageView); VkClearValue clearValue = {}; clearValue.color = { colorAttachment.clearColor.r, colorAttachment.clearColor.g, colorAttachment.clearColor.b, colorAttachment.clearColor.a }; attachmentClearValues.Add(clearValue); frameWidth = (frameWidth > 0) ? Min(frameWidth, rt->Width()) : rt->Width(); frameHeight = (frameHeight > 0) ? Min(frameHeight, rt->Height()) : rt->Height(); } } VkAttachmentReference depthStencilReference = {}; depthStencilReference.attachment = VK_ATTACHMENT_UNUSED; depthStencilReference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; if (desc.depthStencilAttachment.renderTarget) { const DKRenderPassDepthStencilAttachmentDescriptor& depthStencilAttachment = desc.depthStencilAttachment; const Texture* rt = depthStencilAttachment.renderTarget.SafeCast<Texture>(); if (rt) { AddWaitSemaphore(rt->waitSemaphore, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); AddSignalSemaphore(rt->signalSemaphore); VkAttachmentDescription attachment = {}; attachment.format = rt->format; attachment.samples = VK_SAMPLE_COUNT_1_BIT; switch (depthStencilAttachment.loadAction) { case DKRenderPassAttachmentDescriptor::LoadActionLoad: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD; break; case DKRenderPassAttachmentDescriptor::LoadActionClear: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; break; default: attachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; break; } switch (depthStencilAttachment.storeAction) { case DKRenderPassAttachmentDescriptor::StoreActionDontCare: attachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; break; case DKRenderPassAttachmentDescriptor::StoreActionStore: attachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE; break; } attachment.stencilLoadOp = attachment.loadOp; attachment.stencilStoreOp = attachment.storeOp; attachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; attachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; depthStencilReference.attachment = static_cast<uint32_t>(attachments.Count()); attachments.Add(attachment); framebufferImageViews.Add(rt->imageView); VkClearValue clearValue = {}; clearValue.depthStencil.depth = depthStencilAttachment.clearDepth; clearValue.depthStencil.stencil = depthStencilAttachment.clearStencil; attachmentClearValues.Add(clearValue); frameWidth = (frameWidth > 0) ? Min(frameWidth, rt->Width()) : rt->Width(); frameHeight = (frameHeight > 0) ? Min(frameHeight, rt->Height()) : rt->Height(); } } VkSubpassDescription subpassDescription = {}; subpassDescription.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; subpassDescription.colorAttachmentCount = static_cast<uint32_t>(colorReferences.Count()); subpassDescription.pColorAttachments = colorReferences; subpassDescription.pDepthStencilAttachment = &depthStencilReference; subpassDescription.inputAttachmentCount = 0; subpassDescription.pInputAttachments = nullptr; subpassDescription.preserveAttachmentCount = 0; subpassDescription.pPreserveAttachments = nullptr; subpassDescription.pResolveAttachments = nullptr; VkRenderPassCreateInfo renderPassCreateInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO }; renderPassCreateInfo.attachmentCount = static_cast<uint32_t>(attachments.Count()); renderPassCreateInfo.pAttachments = attachments; renderPassCreateInfo.subpassCount = 1; renderPassCreateInfo.pSubpasses = &subpassDescription; GraphicsDevice* dev = (GraphicsDevice*)DKGraphicsDeviceInterface::Instance(commandBuffer->Queue()->Device()); VkDevice device = dev->device; VkResult err = vkCreateRenderPass(device, &renderPassCreateInfo, nullptr, &resources->renderPass); if (err != VK_SUCCESS) { DKLogE("ERROR: vkCreateRenderPass failed: %s", VkResultCStr(err)); DKASSERT(err == VK_SUCCESS); } VkFramebufferCreateInfo frameBufferCreateInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO }; frameBufferCreateInfo.renderPass = resources->renderPass; frameBufferCreateInfo.attachmentCount = static_cast<uint32_t>(framebufferImageViews.Count()); frameBufferCreateInfo.pAttachments = framebufferImageViews; frameBufferCreateInfo.width = frameWidth; frameBufferCreateInfo.height = frameHeight; frameBufferCreateInfo.layers = 1; err = vkCreateFramebuffer(device, &frameBufferCreateInfo, nullptr, &resources->framebuffer); if (err != VK_SUCCESS) { DKLogE("ERROR: vkCreateFramebuffer failed: %s", VkResultCStr(err)); DKASSERT(err == VK_SUCCESS); } VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; vkBeginCommandBuffer(resources->commandBuffer, &commandBufferBeginInfo); VkRenderPassBeginInfo renderPassBeginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; renderPassBeginInfo.renderPass = resources->renderPass; renderPassBeginInfo.clearValueCount = static_cast<uint32_t>(attachmentClearValues.Count()); renderPassBeginInfo.pClearValues = attachmentClearValues; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = frameWidth; renderPassBeginInfo.renderArea.extent.height = frameHeight; renderPassBeginInfo.framebuffer = resources->framebuffer; vkCmdBeginRenderPass(resources->commandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = {}; viewport.height = (float)frameHeight; viewport.width = (float)frameWidth; viewport.minDepth = (float) 0.0f; viewport.maxDepth = (float) 1.0f; vkCmdSetViewport(resources->commandBuffer, 0, 1, &viewport); } RenderCommandEncoder::~RenderCommandEncoder(void) { resources = NULL; } void RenderCommandEncoder::AddWaitSemaphore(VkSemaphore semaphore, VkPipelineStageFlags flags) { if (semaphore != VK_NULL_HANDLE) { if (!semaphorePipelineStageMasks.Insert(semaphore, flags)) semaphorePipelineStageMasks.Value(semaphore) |= flags; } } void RenderCommandEncoder::AddSignalSemaphore(VkSemaphore semaphore) { if (semaphore != VK_NULL_HANDLE) signalSemaphores.Insert(semaphore); } void RenderCommandEncoder::EndEncoding(void) { vkCmdEndRenderPass(resources->commandBuffer); VkResult err = vkEndCommandBuffer(resources->commandBuffer); if (err != VK_SUCCESS) { DKLogE("ERROR: vkEndCommandBuffer failed: %s", VkResultCStr(err)); DKASSERT(err == VK_SUCCESS); } VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO }; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &resources->commandBuffer; resources->waitSemaphores.Reserve(semaphorePipelineStageMasks.Count()); resources->waitStageMasks.Reserve(semaphorePipelineStageMasks.Count()); semaphorePipelineStageMasks.EnumerateForward([&](decltype(semaphorePipelineStageMasks)::Pair& pair) { resources->waitSemaphores.Add(pair.key); resources->waitStageMasks.Add(pair.value); }); resources->signalSemaphores.Reserve(signalSemaphores.Count()); signalSemaphores.EnumerateForward([&](VkSemaphore semaphore) { resources->signalSemaphores.Add(semaphore); }); DKASSERT_DEBUG(resources->waitSemaphores.Count() == resources->waitStageMasks.Count()); submitInfo.waitSemaphoreCount = resources->waitSemaphores.Count(); submitInfo.pWaitSemaphores = resources->waitSemaphores; submitInfo.pWaitDstStageMask = resources->waitStageMasks; submitInfo.signalSemaphoreCount = resources->signalSemaphores.Count(); submitInfo.pSignalSemaphores = resources->signalSemaphores; commandBuffer->Submit(submitInfo, DKFunction([=](DKObject<Resources> res) { res = NULL; })->Invocation(resources)); resources = NULL; semaphorePipelineStageMasks.Clear(); signalSemaphores.Clear(); } DKCommandBuffer* RenderCommandEncoder::Buffer(void) { return commandBuffer; } #endif //#if DKGL_ENABLE_VULKAN <|endoftext|>
<commit_before>/** @file * * @ingroup dspSoundFileLib * * @brief Tests for the #TTSoundfile class * * @details Tests the core functions of the TTSoundfile class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfile.h" #include "TTUnitTest.h" /* #define TESTFILE "/Users/nathanwolek/Desktop/geese_clip.aif" #define TESTNUMCHANNELS 2 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 88202 #define TESTDURATIONINSECONDS 2.00004535 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" */ /* */ #define TESTFILE "/Volumes/Storage/Audio/200604femf15/pitched/ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" /* */ /* #define TESTFILE "/Volumes/Storage/Audio/200604femf15/ambience/street.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 4750848 #define TESTDURATIONINSECONDS 107.728980 #define TESTTITLE "UF Street" #define TESTARTIST "MPG" #define TESTDATE "2006" #define TESTANNOTATION "" */ TTErr TTSoundfile::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; { TTTestLog("\n"); TTTestLog("Testing TTSoundfile Basics..."); TTSoundfilePtr soundfile = NULL; TTErr err; // TEST 0: instantiate the object to a pointer TTBoolean result0 = { TTObjectBaseInstantiate("soundfile", (TTObjectBasePtr*)&soundfile, kTTValNONE) == kTTErrNone}; TTTestAssertion("instantiates successfully", result0, testAssertionCount, errorCount); // TEST 1: set the filepath TTBoolean result1 = { soundfile->setFilePath(TT(TESTFILE)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: reports correct number of channels TTColumnID return2 = soundfile->getNumChannels(); TTBoolean result2 = { return2 == TESTNUMCHANNELS }; TTTestAssertion("reports the correct number of channels", result2, testAssertionCount, errorCount); if(!result2) { TTTestLog("Expected a value of %i, but returned value was %i", TESTNUMCHANNELS, return2); } // TEST 3: reports correct sample rate TTFloat64 return3 = soundfile->getSampleRate(); TTBoolean result3 = TTTestFloatEquivalence(return3, TESTSAMPLERATE, true, 0.0000001); TTTestAssertion("reports the correct sample rate", result3, testAssertionCount, errorCount); if(!result3) { TTTestLog("Expected a value of %f, but returned value was %f", TESTSAMPLERATE, return3); } // TEST 4: reports correct duration in samples TTRowID return4 = soundfile->getLengthInSamples(); TTBoolean result4 = { return4 == TESTDURATIONINSAMPLES }; TTTestAssertion("reports the correct duration in samples", result4, testAssertionCount, errorCount); if(!result4) { TTTestLog("Expected a value of %i, but returned value was %i", TESTDURATIONINSAMPLES, return4); } // TEST 5: reports correct duration in seconds TTFloat64 return5 = soundfile->getLengthInSeconds(); TTBoolean result5 = TTTestFloatEquivalence(return5, TESTDURATIONINSECONDS, true, 0.0000001); TTTestAssertion("reports the correct duration in seconds", result5, testAssertionCount, errorCount); if(!result5) { TTTestLog("Expected a value of %f, but returned value was %f", TESTDURATIONINSECONDS, return5); } TTTestLog("\n"); TTTestLog("Testing TTSoundfile Metadata..."); // TEST 6: reports correct title from metadata TTSymbol return6 = soundfile->getTitle(); TTTestLog("Expected metadata title:"); TTTestLog(TESTTITLE); TTTestLog("Returned metadata title:"); TTTestLog(return6.c_str()); // TEST 7: reports correct artist from metadata TTSymbol return7 = soundfile->getArtist(); TTTestLog("Expected metadata artist:"); TTTestLog(TESTARTIST); TTTestLog("Returned metadata artist:"); TTTestLog(return7.c_str()); // TEST 8: reports correct title from metadata TTSymbol return8 = soundfile->getDate(); TTTestLog("Expected metadata date:"); TTTestLog(TESTDATE); TTTestLog("Returned metadata date:"); TTTestLog(return8.c_str()); // TEST 9: reports correct artist from metadata TTSymbol return9 = soundfile->getAnnotation(); TTTestLog("Expected metadata comment:"); TTTestLog(TESTANNOTATION); TTTestLog("Returned metadata comment:"); TTTestLog(return9.c_str()); TTTestLog("\n"); TTTestLog("Testing peek method on first 10 sample values..."); TTSampleValue return10; TTErr error10; for (int channel=0;channel<return2;channel++) { TTTestLog("Channel %i", channel); for (int sample=0;sample<10;sample++) { error10 = soundfile->peek(sample,channel,return10); if (error10 == kTTErrNone) { TTTestLog("peek sample %i returned the value %f", sample, return10); } else { TTTestLog("peek returned an error for sample %i", sample); } } } } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <commit_msg>created very basic test of the peeki() method<commit_after>/** @file * * @ingroup dspSoundFileLib * * @brief Tests for the #TTSoundfile class * * @details Tests the core functions of the TTSoundfile class in order to ensure that things are working after a build. It also demostrate how to make calls to common methods within the class.@n * IMPORTANT NOTE: Because POSIX filepaths will be specific to your system, it is important to change the TESTFILE definitions in this file to match a local absolute address. The related TEST definitions should also be set to match the attribution of the file which can be obtained via your sound file editor of choice. * * @authors Nathan Wolek * * @copyright Copyright © 2013 by Nathan Wolek @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfile.h" #include "TTUnitTest.h" /* #define TESTFILE "/Users/nathanwolek/Desktop/geese_clip.aif" #define TESTNUMCHANNELS 2 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 88202 #define TESTDURATIONINSECONDS 2.00004535 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" */ /* */ #define TESTFILE "/Volumes/Storage/Audio/200604femf15/pitched/ding_b2.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 39493 #define TESTDURATIONINSECONDS 0.89553288 #define TESTTITLE "" #define TESTARTIST "" #define TESTDATE "" #define TESTANNOTATION "" /* */ /* #define TESTFILE "/Volumes/Storage/Audio/200604femf15/ambience/street.aiff" #define TESTNUMCHANNELS 1 #define TESTSAMPLERATE 44100 #define TESTDURATIONINSAMPLES 4750848 #define TESTDURATIONINSECONDS 107.728980 #define TESTTITLE "UF Street" #define TESTARTIST "MPG" #define TESTDATE "2006" #define TESTANNOTATION "" */ TTErr TTSoundfile::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; { TTTestLog("\n"); TTTestLog("Testing TTSoundfile Basics..."); TTSoundfilePtr soundfile = NULL; TTErr err; // TEST 0: instantiate the object to a pointer TTBoolean result0 = { TTObjectBaseInstantiate("soundfile", (TTObjectBasePtr*)&soundfile, kTTValNONE) == kTTErrNone}; TTTestAssertion("instantiates successfully", result0, testAssertionCount, errorCount); // TEST 1: set the filepath TTBoolean result1 = { soundfile->setFilePath(TT(TESTFILE)) == kTTErrNone }; TTTestAssertion("setFilePath operates successfully", result1, testAssertionCount, errorCount); // TEST 2: reports correct number of channels TTColumnID return2 = soundfile->getNumChannels(); TTBoolean result2 = { return2 == TESTNUMCHANNELS }; TTTestAssertion("reports the correct number of channels", result2, testAssertionCount, errorCount); if(!result2) { TTTestLog("Expected a value of %i, but returned value was %i", TESTNUMCHANNELS, return2); } // TEST 3: reports correct sample rate TTFloat64 return3 = soundfile->getSampleRate(); TTBoolean result3 = TTTestFloatEquivalence(return3, TESTSAMPLERATE, true, 0.0000001); TTTestAssertion("reports the correct sample rate", result3, testAssertionCount, errorCount); if(!result3) { TTTestLog("Expected a value of %f, but returned value was %f", TESTSAMPLERATE, return3); } // TEST 4: reports correct duration in samples TTRowID return4 = soundfile->getLengthInSamples(); TTBoolean result4 = { return4 == TESTDURATIONINSAMPLES }; TTTestAssertion("reports the correct duration in samples", result4, testAssertionCount, errorCount); if(!result4) { TTTestLog("Expected a value of %i, but returned value was %i", TESTDURATIONINSAMPLES, return4); } // TEST 5: reports correct duration in seconds TTFloat64 return5 = soundfile->getLengthInSeconds(); TTBoolean result5 = TTTestFloatEquivalence(return5, TESTDURATIONINSECONDS, true, 0.0000001); TTTestAssertion("reports the correct duration in seconds", result5, testAssertionCount, errorCount); if(!result5) { TTTestLog("Expected a value of %f, but returned value was %f", TESTDURATIONINSECONDS, return5); } TTTestLog("\n"); TTTestLog("Testing TTSoundfile Metadata..."); // TEST 6: reports correct title from metadata TTSymbol return6 = soundfile->getTitle(); TTTestLog("Expected metadata title:"); TTTestLog(TESTTITLE); TTTestLog("Returned metadata title:"); TTTestLog(return6.c_str()); // TEST 7: reports correct artist from metadata TTSymbol return7 = soundfile->getArtist(); TTTestLog("Expected metadata artist:"); TTTestLog(TESTARTIST); TTTestLog("Returned metadata artist:"); TTTestLog(return7.c_str()); // TEST 8: reports correct title from metadata TTSymbol return8 = soundfile->getDate(); TTTestLog("Expected metadata date:"); TTTestLog(TESTDATE); TTTestLog("Returned metadata date:"); TTTestLog(return8.c_str()); // TEST 9: reports correct artist from metadata TTSymbol return9 = soundfile->getAnnotation(); TTTestLog("Expected metadata comment:"); TTTestLog(TESTANNOTATION); TTTestLog("Returned metadata comment:"); TTTestLog(return9.c_str()); TTTestLog("\n"); TTTestLog("Testing peek method on first 10 sample values..."); TTSampleValue return10; TTErr error10; for (int channel=0;channel<return2;channel++) { TTTestLog("Channel %i", channel); for (int sample=0;sample<10;sample++) { error10 = soundfile->peek(sample,channel,return10); if (error10 == kTTErrNone) { TTTestLog("peek sample %i returned the value %f", sample, return10); } else { TTTestLog("peek returned an error for sample %i", sample); } } } TTTestLog("\n"); TTTestLog("Testing peeki between samples 2 & 3..."); TTSampleValue return11; TTErr error11; TTFloat64 floatIndex; for (int channel=0;channel<return2;channel++) { TTTestLog("Channel %i", channel); for (int sample=0;sample<11;sample++) { floatIndex = 2 + sample*0.1; error11 = soundfile->peeki(floatIndex,channel,return11); if (error11 == kTTErrNone) { TTTestLog("peek sample %f returned the value %f", floatIndex, return11); } else { TTTestLog("peek returned an error for sample %f", floatIndex); } } } } return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); } <|endoftext|>
<commit_before>#include "PackNode.h" #include "PackIDMgr.h" #include "typedef.h" #include <simp/NodeFactory.h> namespace esprpacker { PackNode::PackNode() : m_node_id(-1) , m_pkg_id(-1) { } uint32_t PackNode::GetID() const { return simp::NodeID::ComposeID(m_pkg_id, m_node_id); } void PackNode::SetFilepath(const std::string& filepath) const { m_filepath = filepath; } void PackNode::SetID(const std::string& filepath, bool force_curr) const { PackIDMgr::Instance()->QueryID(filepath, m_pkg_id, m_node_id, m_filepath == SPRITE_FILEPATH, force_curr); } }<commit_msg>[FIXED] pack node id<commit_after>#include "PackNode.h" #include "PackIDMgr.h" #include "typedef.h" #include <simp/NodeFactory.h> namespace esprpacker { PackNode::PackNode() : m_node_id(-1) , m_pkg_id(-1) { } uint32_t PackNode::GetID() const { return simp::NodeID::ComposeID(m_pkg_id, m_node_id); } void PackNode::SetFilepath(const std::string& filepath) const { m_filepath = filepath; } void PackNode::SetID(const std::string& filepath, bool force_curr) const { PackIDMgr::Instance()->QueryID(filepath, m_pkg_id, m_node_id, m_filepath != SPRITE_FILEPATH, force_curr); } }<|endoftext|>
<commit_before> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "FireSimulator.h" #include "../World.h" #include "../BlockID.h" #include "../Defines.h" #include "../Chunk.h" // Easy switch for turning on debugging logging: #if 0 #define FLOG LOGD #else #define FLOG(...) #endif #define MAX_CHANCE_REPLACE_FUEL 100000 #define MAX_CHANCE_FLAMMABILITY 100000 static const struct { int x, y, z; } gCrossCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; static const struct { int x, y, z; } gNeighborCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 1, 0}, { 0, -1, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFireSimulator: cFireSimulator::cFireSimulator(cWorld & a_World, cIniFile & a_IniFile) : cSimulator(a_World) { // Read params from the ini file: m_BurnStepTimeFuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeFuel", 500); m_BurnStepTimeNonfuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeNonfuel", 100); m_Flammability = a_IniFile.GetValueSetI("FireSimulator", "Flammability", 50); m_ReplaceFuelChance = a_IniFile.GetValueSetI("FireSimulator", "ReplaceFuelChance", 50000); } cFireSimulator::~cFireSimulator() { } void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk) { cCoordWithIntList & Data = a_Chunk->GetFireSimulatorData(); int NumMSecs = (int)a_Dt; for (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();) { int idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z); BLOCKTYPE BlockType = a_Chunk->GetBlock(idx); if (!IsAllowedBlock(BlockType)) { // The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire) FLOG("FS: Removing block {%d, %d, %d}", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); itr = Data.erase(itr); continue; } // Try to spread the fire: TrySpreadFire(a_Chunk, itr->x, itr->y, itr->z); itr->Data -= NumMSecs; if (itr->Data >= 0) { // Not yet, wait for it longer ++itr; continue; } // Burn out the fire one step by increasing the meta: /* FLOG("FS: Fire at {%d, %d, %d} is stepping", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); */ NIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx); if (BlockMeta == 0x0f) { // The fire burnt out completely FLOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); a_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0); RemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z); itr = Data.erase(itr); continue; } a_Chunk->SetMeta(idx, BlockMeta + 1); itr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z); // TODO: Add some randomness into this } // for itr - Data[] } bool cFireSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_FIRE); } bool cFireSimulator::IsFuel(BLOCKTYPE a_BlockType) { switch (a_BlockType) { case E_BLOCK_PLANKS: case E_BLOCK_LEAVES: case E_BLOCK_LOG: case E_BLOCK_WOOL: case E_BLOCK_BOOKCASE: case E_BLOCK_FENCE: case E_BLOCK_TNT: case E_BLOCK_VINES: { return true; } } return false; } bool cFireSimulator::IsForever(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_NETHERRACK); } void cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { if ((a_Chunk == NULL) || !a_Chunk->IsValid()) { return; } int RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width; int RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width; BLOCKTYPE BlockType = a_Chunk->GetBlock(RelX, a_BlockY, RelZ); if (!IsAllowedBlock(BlockType)) { return; } // Check for duplicates: cFireSimulatorChunkData & ChunkData = a_Chunk->GetFireSimulatorData(); for (cCoordWithIntList::iterator itr = ChunkData.begin(), end = ChunkData.end(); itr != end; ++itr) { if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ)) { // Already present, skip adding return; } } // for itr - ChunkData[] FLOG("FS: Adding block {%d, %d, %d}", a_BlockX, a_BlockY, a_BlockZ); ChunkData.push_back(cCoordWithInt(RelX, a_BlockY, RelZ, 100)); } int cFireSimulator::GetBurnStepTime(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { bool IsBlockBelowSolid = false; if (a_RelY > 0) { BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ); if (IsForever(BlockBelow)) { // Is burning atop of netherrack, burn forever (re-check in 10 sec) return 10000; } if (IsFuel(BlockBelow)) { return m_BurnStepTimeFuel; } IsBlockBelowSolid = g_BlockIsSolid[BlockBelow]; } for (int i = 0; i < ARRAYCOUNT(gCrossCoords); i++) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (a_Chunk->UnboundedRelGetBlock(a_RelX + gCrossCoords[i].x, a_RelY, a_RelZ + gCrossCoords[i].z, BlockType, BlockMeta)) { if (IsFuel(BlockType)) { return m_BurnStepTimeFuel; } } } // for i - gCrossCoords[] if (!IsBlockBelowSolid && (a_RelY >= 0)) { // Checked through everything, nothing was flammable // If block below isn't solid, we can't have fire, it would be a non-fueled fire // SetBlock just to make sure fire doesn't spawn a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); return 0; } return m_BurnStepTimeNonfuel; } void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { /* if (m_World.GetTickRandomNumber(10000) > 100) { // Make the chance to spread 100x smaller return; } */ for (int x = a_RelX - 1; x <= a_RelX + 1; x++) { for (int z = a_RelZ - 1; z <= a_RelZ + 1; z++) { for (int y = a_RelY - 1; y <= a_RelY + 2; y++) // flames spread up one more block than around { // No need to check the coords for equality with the parent block, // it cannot catch fire anyway (because it's not an air block) if (m_World.GetTickRandomNumber(MAX_CHANCE_FLAMMABILITY) > m_Flammability) { continue; } // Start the fire in the neighbor {x, y, z} /* FLOG("FS: Trying to start fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); */ if (CanStartFireInBlock(a_Chunk, x, y, z)) { FLOG("FS: Starting new fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); a_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0); } } // for y } // for z } // for x } void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { for (int i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_Chunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta)) { // Neighbor not accessible, ignore it continue; } if (!IsFuel(BlockType)) { continue; } bool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance); a_Chunk->UnboundedRelSetBlock( a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, ShouldReplaceFuel ? E_BLOCK_FIRE : E_BLOCK_AIR, 0 ); } // for i - Coords[] } bool cFireSimulator::CanStartFireInBlock(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_NearChunk->UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockType, BlockMeta)) { // The chunk is not accessible return false; } if (BlockType != E_BLOCK_AIR) { // Only an air block can be replaced by a fire block return false; } for (int i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { if (!a_NearChunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta)) { // Neighbor inaccessible, skip it while evaluating continue; } if (IsFuel(BlockType)) { return true; } } // for i - Coords[] return false; } <commit_msg>Fire no longer goes out when on top of nether rack<commit_after> #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "FireSimulator.h" #include "../World.h" #include "../BlockID.h" #include "../Defines.h" #include "../Chunk.h" // Easy switch for turning on debugging logging: #if 0 #define FLOG LOGD #else #define FLOG(...) #endif #define MAX_CHANCE_REPLACE_FUEL 100000 #define MAX_CHANCE_FLAMMABILITY 100000 static const struct { int x, y, z; } gCrossCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; static const struct { int x, y, z; } gNeighborCoords[] = { { 1, 0, 0}, {-1, 0, 0}, { 0, 1, 0}, { 0, -1, 0}, { 0, 0, 1}, { 0, 0, -1}, } ; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cFireSimulator: cFireSimulator::cFireSimulator(cWorld & a_World, cIniFile & a_IniFile) : cSimulator(a_World) { // Read params from the ini file: m_BurnStepTimeFuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeFuel", 500); m_BurnStepTimeNonfuel = a_IniFile.GetValueSetI("FireSimulator", "BurnStepTimeNonfuel", 100); m_Flammability = a_IniFile.GetValueSetI("FireSimulator", "Flammability", 50); m_ReplaceFuelChance = a_IniFile.GetValueSetI("FireSimulator", "ReplaceFuelChance", 50000); } cFireSimulator::~cFireSimulator() { } void cFireSimulator::SimulateChunk(float a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk) { cCoordWithIntList & Data = a_Chunk->GetFireSimulatorData(); int NumMSecs = (int)a_Dt; for (cCoordWithIntList::iterator itr = Data.begin(); itr != Data.end();) { int idx = cChunkDef::MakeIndexNoCheck(itr->x, itr->y, itr->z); int idb = cChunkDef::MakeIndexNoCheck(itr->x, itr->y - 1, itr->z); BLOCKTYPE BlockType = a_Chunk->GetBlock(idx); BLOCKTYPE Burnee = a_Chunk->GetBlock(idb); if (!IsAllowedBlock(BlockType)) { // The block is no longer eligible (not a fire block anymore; a player probably placed a block over the fire) FLOG("FS: Removing block {%d, %d, %d}", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); itr = Data.erase(itr); continue; } // Try to spread the fire: TrySpreadFire(a_Chunk, itr->x, itr->y, itr->z); itr->Data -= NumMSecs; if (itr->Data >= 0) { // Not yet, wait for it longer ++itr; continue; } // Burn out the fire one step by increasing the meta: /* FLOG("FS: Fire at {%d, %d, %d} is stepping", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); */ NIBBLETYPE BlockMeta = a_Chunk->GetMeta(idx); if (BlockMeta == 0x0f) { // The fire burnt out completely FLOG("FS: Fire at {%d, %d, %d} burnt out, removing the fire block", itr->x + a_ChunkX * cChunkDef::Width, itr->y, itr->z + a_ChunkZ * cChunkDef::Width ); a_Chunk->SetBlock(itr->x, itr->y, itr->z, E_BLOCK_AIR, 0); RemoveFuelNeighbors(a_Chunk, itr->x, itr->y, itr->z); itr = Data.erase(itr); continue; } if(Burnee != E_BLOCK_NETHERRACK) { a_Chunk->SetMeta(idx, BlockMeta + 1); } itr->Data = GetBurnStepTime(a_Chunk, itr->x, itr->y, itr->z); // TODO: Add some randomness into this } // for itr - Data[] } bool cFireSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_FIRE); } bool cFireSimulator::IsFuel(BLOCKTYPE a_BlockType) { switch (a_BlockType) { case E_BLOCK_PLANKS: case E_BLOCK_LEAVES: case E_BLOCK_LOG: case E_BLOCK_WOOL: case E_BLOCK_BOOKCASE: case E_BLOCK_FENCE: case E_BLOCK_TNT: case E_BLOCK_VINES: { return true; } } return false; } bool cFireSimulator::IsForever(BLOCKTYPE a_BlockType) { return (a_BlockType == E_BLOCK_NETHERRACK); } void cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { if ((a_Chunk == NULL) || !a_Chunk->IsValid()) { return; } int RelX = a_BlockX - a_Chunk->GetPosX() * cChunkDef::Width; int RelZ = a_BlockZ - a_Chunk->GetPosZ() * cChunkDef::Width; BLOCKTYPE BlockType = a_Chunk->GetBlock(RelX, a_BlockY, RelZ); if (!IsAllowedBlock(BlockType)) { return; } // Check for duplicates: cFireSimulatorChunkData & ChunkData = a_Chunk->GetFireSimulatorData(); for (cCoordWithIntList::iterator itr = ChunkData.begin(), end = ChunkData.end(); itr != end; ++itr) { if ((itr->x == RelX) && (itr->y == a_BlockY) && (itr->z == RelZ)) { // Already present, skip adding return; } } // for itr - ChunkData[] FLOG("FS: Adding block {%d, %d, %d}", a_BlockX, a_BlockY, a_BlockZ); ChunkData.push_back(cCoordWithInt(RelX, a_BlockY, RelZ, 100)); } int cFireSimulator::GetBurnStepTime(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { bool IsBlockBelowSolid = false; if (a_RelY > 0) { BLOCKTYPE BlockBelow = a_Chunk->GetBlock(a_RelX, a_RelY - 1, a_RelZ); if (IsForever(BlockBelow)) { // Is burning atop of netherrack, burn forever (re-check in 10 sec) return 10000; } if (IsFuel(BlockBelow)) { return m_BurnStepTimeFuel; } IsBlockBelowSolid = g_BlockIsSolid[BlockBelow]; } for (int i = 0; i < ARRAYCOUNT(gCrossCoords); i++) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (a_Chunk->UnboundedRelGetBlock(a_RelX + gCrossCoords[i].x, a_RelY, a_RelZ + gCrossCoords[i].z, BlockType, BlockMeta)) { if (IsFuel(BlockType)) { return m_BurnStepTimeFuel; } } } // for i - gCrossCoords[] if (!IsBlockBelowSolid && (a_RelY >= 0)) { // Checked through everything, nothing was flammable // If block below isn't solid, we can't have fire, it would be a non-fueled fire // SetBlock just to make sure fire doesn't spawn a_Chunk->SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); return 0; } return m_BurnStepTimeNonfuel; } void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { /* if (m_World.GetTickRandomNumber(10000) > 100) { // Make the chance to spread 100x smaller return; } */ for (int x = a_RelX - 1; x <= a_RelX + 1; x++) { for (int z = a_RelZ - 1; z <= a_RelZ + 1; z++) { for (int y = a_RelY - 1; y <= a_RelY + 2; y++) // flames spread up one more block than around { // No need to check the coords for equality with the parent block, // it cannot catch fire anyway (because it's not an air block) if (m_World.GetTickRandomNumber(MAX_CHANCE_FLAMMABILITY) > m_Flammability) { continue; } // Start the fire in the neighbor {x, y, z} /* FLOG("FS: Trying to start fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); */ if (CanStartFireInBlock(a_Chunk, x, y, z)) { FLOG("FS: Starting new fire at {%d, %d, %d}.", x + a_Chunk->GetPosX() * cChunkDef::Width, y, z + a_Chunk->GetPosZ() * cChunkDef::Width ); a_Chunk->UnboundedRelSetBlock(x, y, z, E_BLOCK_FIRE, 0); } } // for y } // for z } // for x } void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { for (int i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_Chunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta)) { // Neighbor not accessible, ignore it continue; } if (!IsFuel(BlockType)) { continue; } bool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance); a_Chunk->UnboundedRelSetBlock( a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, ShouldReplaceFuel ? E_BLOCK_FIRE : E_BLOCK_AIR, 0 ); } // for i - Coords[] } bool cFireSimulator::CanStartFireInBlock(cChunk * a_NearChunk, int a_RelX, int a_RelY, int a_RelZ) { BLOCKTYPE BlockType; NIBBLETYPE BlockMeta; if (!a_NearChunk->UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockType, BlockMeta)) { // The chunk is not accessible return false; } if (BlockType != E_BLOCK_AIR) { // Only an air block can be replaced by a fire block return false; } for (int i = 0; i < ARRAYCOUNT(gNeighborCoords); i++) { if (!a_NearChunk->UnboundedRelGetBlock(a_RelX + gNeighborCoords[i].x, a_RelY + gNeighborCoords[i].y, a_RelZ + gNeighborCoords[i].z, BlockType, BlockMeta)) { // Neighbor inaccessible, skip it while evaluating continue; } if (IsFuel(BlockType)) { return true; } } // for i - Coords[] return false; } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <map> #include <unordered_map> #include <vector> #include <string> #include "dict.h" #include "dictglobal.h" using Dict = std::unordered_map<std::string, std::string>; using IdentificatorType = unsigned long; namespace { #ifndef NDEBUG const bool debug = false; #else const bool debug = true; #endif IdentificatorType dictCounter = 0; std::map<IdentificatorType, Dict>& dicts() { static std::map<IdentificatorType, Dict> dicts; return dicts; } std::string parse_char_param(const char* param) { if (param != NULL) { std::string paramStr(param); return "\"" + paramStr + "\""; } else return "NULL"; } void function_called_msg(std::string funcName, std::string params) { if (debug) std::cerr << funcName << "(" << params << ")" << std::endl; } void dict_new_msg(IdentificatorType id) { if (debug) std::cerr << "dict_new: dict " << id << " has been created" << std::endl; } void dict_delete_success_msg(IdentificatorType id) { if (debug) std::cerr << "dict_delete: dict " << id << " has been deleted" << std::endl; } void dict_delete_error_msg() { if (debug) std::cerr << "dict_delete: an attempt to remove the Global Dictionary" << std::endl; } void dict_description_msg(IdentificatorType id) { if (debug) { if (id != dict_global()) std::cerr << "dict " << id; else std::cerr << "the Global Dictionary"; } } void dict_size_msg(IdentificatorType id, size_t size) { if (debug) { std::cerr << "dict_size: "; dict_description_msg(id); std::cerr << " contains " << size << " element(s)" << std::endl; } } void dict_insert_success_msg(IdentificatorType id, std::string key, std::string value) { if (debug) { std::cerr << "dict_insert: "; dict_description_msg(id); std::cerr << ", the pair (" << key << ", " << value << ")" << "has been inserted" << std::endl; } } void dict_insert_error_msg(IdentificatorType id, std::string param) { if (debug) std::cerr << "dict_insert: dict " << id << " an attempt to insert NULL " << param << std::endl; } void dict_not_found_msg(std::string funcName, IdentificatorType id) { if (debug) std::cerr << funcName << ": dict " << id << " does not exist" << "\n"; } void key_not_found_msg(std::string funcName, IdentificatorType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << " does not contain the key " << key << "\"\n"; } void key_removed_msg(std::string funcName, IdentificatorType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << ", the key \"" << key << "\" has been removed\n"; } void value_found_msg(std::string funcName, IdentificatorType id, const char* key, std::string value) { if (debug) std::cerr << funcName << ": dict " << id << ", the key \"" << key << "\" has the value \"" << value << "\"\n"; } void dict_copied_msg(std::string funcName, IdentificatorType src_id, IdentificatorType dst_id) { if (debug) std::cerr << funcName << ": dict " << src_id << " has been copied into dict " << dst_id << "\n"; } void search_global_dict_msg(std::string funcName) { if (debug) std::cerr << funcName << ": looking up the Global Dictionary\n"; } void dict_cleared_msg(std::string funcName, IdentificatorType id) { if (debug) std::cerr << funcName << ": dict " << id << " has been cleared\n"; } } IdentificatorType dict_new() { function_called_msg("dict_new", ""); dicts().insert(std::make_pair(++dictCounter, Dict())); dict_new_msg(dictCounter); return dictCounter; } void dict_delete(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_delete", ss.str()); auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (id == dict_global()) { dict_delete_error_msg(); } else { dicts().erase(id); dict_delete_success_msg(id); } } } size_t dict_size(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_size", ss.str()); auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { size_t dictSize = dictionaryIt->second.size(); dict_size_msg(id, dictSize); return dictSize; } else { dict_not_found_msg("dict_size", id); return 0; } } void dict_insert(unsigned long id, const char* key, const char* value) { std::stringstream ss; std::string keyDescription, valueDescription; keyDescription = parse_char_param(key); valueDescription = parse_char_param(value); ss << id << ", " << keyDescription << ", " << valueDescription; function_called_msg("dict_insert", ss.str()); auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (key == NULL) { dict_insert_error_msg(id, "key"); } else if (value == NULL) { dict_insert_error_msg(id, "value"); } else { // TODO: check if global dict (size constraint!) std::string keyStr(key); std::string valueStr(value); dictionaryIt->second.insert(std::make_pair(keyStr, valueStr)); dict_insert_success_msg(id, keyDescription, valueDescription); } } else dict_not_found_msg("dict_insert", id); } void dict_remove(IdentificatorType id, const char* key) { auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (dictionaryIt->second.erase(key) > 0) { key_removed_msg("dict_remove", id, key); } else { key_not_found_msg("dict_remove", id, key); } } else { dict_not_found_msg("dict_remove", id); } } const char* dict_find(IdentificatorType id, const char* key) { auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { auto stringIt = dictionaryIt->second.find(key); if (stringIt != dictionaryIt->second.end()) { value_found_msg("dict_find", id, key, stringIt->second); return stringIt->second.c_str(); } else { key_not_found_msg("dict_find", id, key); } } else { dict_not_found_msg("dict_find", id); } search_global_dict_msg("dict_find"); auto stringIt = dicts().at(dict_global()).find(key); if (stringIt != dicts().at(dict_global()).end()) { value_found_msg("dict_find", dict_global(), key, stringIt->second); return stringIt->second.c_str(); } else { key_not_found_msg("dict_find", dict_global(), key); } return NULL; } void dict_clear(IdentificatorType id) { auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { dict_cleared_msg("dict_clear", id); dictionaryIt->second.clear(); } else { dict_not_found_msg("dict_clear", id); } } void dict_copy(IdentificatorType src_id, IdentificatorType dst_id) { auto srcDictionaryIt = dicts().find(src_id); auto dstDictionaryIt = dicts().find(dst_id); if (srcDictionaryIt != dicts().end() && dstDictionaryIt != dicts().end()) { // do not copy if destination dictionary is dictglobal and amount of keys exceeds size // copy contents } } <commit_msg>Deutsch -> English<commit_after>#include <iostream> #include <sstream> #include <map> #include <unordered_map> #include <vector> #include <string> #include "dict.h" #include "dictglobal.h" using Dict = std::unordered_map<std::string, std::string>; using IdentifierType = unsigned long; namespace { #ifndef NDEBUG const bool debug = false; #else const bool debug = true; #endif IdentifierType dictCounter = 0; std::map<IdentifierType, Dict>& dicts() { static std::map<IdentifierType, Dict> dicts; return dicts; } std::string parse_char_param(const char* param) { if (param != NULL) { std::string paramStr(param); return "\"" + paramStr + "\""; } else return "NULL"; } void function_called_msg(std::string funcName, std::string params) { if (debug) std::cerr << funcName << "(" << params << ")" << std::endl; } void dict_new_msg(IdentifierType id) { if (debug) std::cerr << "dict_new: dict " << id << " has been created" << std::endl; } void dict_delete_success_msg(IdentifierType id) { if (debug) std::cerr << "dict_delete: dict " << id << " has been deleted" << std::endl; } void dict_delete_error_msg() { if (debug) std::cerr << "dict_delete: an attempt to remove the Global Dictionary" << std::endl; } void dict_description_msg(IdentifierType id) { if (debug) { if (id != dict_global()) std::cerr << "dict " << id; else std::cerr << "the Global Dictionary"; } } void dict_size_msg(IdentifierType id, size_t size) { if (debug) { std::cerr << "dict_size: "; dict_description_msg(id); std::cerr << " contains " << size << " element(s)" << std::endl; } } void dict_insert_success_msg(IdentifierType id, std::string key, std::string value) { if (debug) { std::cerr << "dict_insert: "; dict_description_msg(id); std::cerr << ", the pair (" << key << ", " << value << ")" << "has been inserted" << std::endl; } } void dict_insert_error_msg(IdentifierType id, std::string param) { if (debug) std::cerr << "dict_insert: dict " << id << " an attempt to insert NULL " << param << std::endl; } void dict_not_found_msg(std::string funcName, IdentifierType id) { if (debug) std::cerr << funcName << ": dict " << id << " does not exist" << "\n"; } void key_not_found_msg(std::string funcName, IdentifierType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << " does not contain the key " << key << "\"\n"; } void key_removed_msg(std::string funcName, IdentifierType id, const char* key) { if (debug) std::cerr << funcName << ": dict " << id << ", the key \"" << key << "\" has been removed\n"; } void value_found_msg(std::string funcName, IdentifierType id, const char* key, std::string value) { if (debug) std::cerr << funcName << ": dict " << id << ", the key \"" << key << "\" has the value \"" << value << "\"\n"; } void dict_copied_msg(std::string funcName, IdentifierType src_id, IdentifierType dst_id) { if (debug) std::cerr << funcName << ": dict " << src_id << " has been copied into dict " << dst_id << "\n"; } void search_global_dict_msg(std::string funcName) { if (debug) std::cerr << funcName << ": looking up the Global Dictionary\n"; } void dict_cleared_msg(std::string funcName, IdentifierType id) { if (debug) std::cerr << funcName << ": dict " << id << " has been cleared\n"; } } IdentifierType dict_new() { function_called_msg("dict_new", ""); dicts().insert(std::make_pair(++dictCounter, Dict())); dict_new_msg(dictCounter); return dictCounter; } void dict_delete(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_delete", ss.str()); auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (id == dict_global()) { dict_delete_error_msg(); } else { dicts().erase(id); dict_delete_success_msg(id); } } } size_t dict_size(unsigned long id) { std::stringstream ss; ss << id; function_called_msg("dict_size", ss.str()); auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { size_t dictSize = dictionaryIt->second.size(); dict_size_msg(id, dictSize); return dictSize; } else { dict_not_found_msg("dict_size", id); return 0; } } void dict_insert(unsigned long id, const char* key, const char* value) { std::stringstream ss; std::string keyDescription, valueDescription; keyDescription = parse_char_param(key); valueDescription = parse_char_param(value); ss << id << ", " << keyDescription << ", " << valueDescription; function_called_msg("dict_insert", ss.str()); auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (key == NULL) { dict_insert_error_msg(id, "key"); } else if (value == NULL) { dict_insert_error_msg(id, "value"); } else { // TODO: check if global dict (size constraint!) std::string keyStr(key); std::string valueStr(value); dictionaryIt->second.insert(std::make_pair(keyStr, valueStr)); dict_insert_success_msg(id, keyDescription, valueDescription); } } else dict_not_found_msg("dict_insert", id); } void dict_remove(IdentifierType id, const char* key) { auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { if (dictionaryIt->second.erase(key) > 0) { key_removed_msg("dict_remove", id, key); } else { key_not_found_msg("dict_remove", id, key); } } else { dict_not_found_msg("dict_remove", id); } } const char* dict_find(IdentifierType id, const char* key) { auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { auto stringIt = dictionaryIt->second.find(key); if (stringIt != dictionaryIt->second.end()) { value_found_msg("dict_find", id, key, stringIt->second); return stringIt->second.c_str(); } else { key_not_found_msg("dict_find", id, key); } } else { dict_not_found_msg("dict_find", id); } search_global_dict_msg("dict_find"); auto stringIt = dicts().at(dict_global()).find(key); if (stringIt != dicts().at(dict_global()).end()) { value_found_msg("dict_find", dict_global(), key, stringIt->second); return stringIt->second.c_str(); } else { key_not_found_msg("dict_find", dict_global(), key); } return NULL; } void dict_clear(IdentifierType id) { auto dictionaryIt = dicts().find(id); if (dictionaryIt != dicts().end()) { dict_cleared_msg("dict_clear", id); dictionaryIt->second.clear(); } else { dict_not_found_msg("dict_clear", id); } } void dict_copy(IdentifierType src_id, IdentifierType dst_id) { auto srcDictionaryIt = dicts().find(src_id); auto dstDictionaryIt = dicts().find(dst_id); if (srcDictionaryIt != dicts().end() && dstDictionaryIt != dicts().end()) { // do not copy if destination dictionary is dictglobal and amount of keys exceeds size // copy contents } } <|endoftext|>
<commit_before>// // Created by Yihung Lee on 10/31/17. // #include "gtest/gtest.h" #include "LeetCodeHeaders.hpp" ArrayQuiz aq; TEST (ArrayTest, findDuplicate) { std::vector<int> vec{1, 2, 3, 4, 5, 6, 5, 7, 8, 9}; EXPECT_EQ(5, aq.findDuplicate(vec)); } TEST (ArrayTest, lengthOfLongestSubstring) { cout << "\nLongest Substring Without Repeating Characters\n"; string s1 = "abcabcbb"; cout << aq.lengthOfLongestSubstring(s1) << endl; // string s2 = "bbbbb"; // cout << aq.lengthOfLongestSubstring(s2) << endl; // string s3 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~"; // cout << aq.lengthOfLongestSubstring(s3) << endl; }<commit_msg>test case<commit_after>// // Created by Yihung Lee on 10/31/17. // #include "gtest/gtest.h" #include "LeetCodeHeaders.hpp" ArrayQuiz aq; TEST (ArrayTest, findDuplicate) { std::vector<int> vec{1, 2, 3, 4, 5, 6, 5, 7, 8, 9}; EXPECT_EQ(5, aq.findDuplicate(vec)); } TEST (ArrayTest, lengthOfLongestSubstring) { cout << "\nLongest Substring Without Repeating Characters\n"; string s1 = "abcabcbb"; EXPECT_EQ(3, aq.lengthOfLongestSubstring(s1)); string s2 = "bbbbb"; EXPECT_EQ(1, aq.lengthOfLongestSubstring(s2)); string s3 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\\\"#$%&'()*+,-./:;<=>?@[\\\\]^_`{|}~"; EXPECT_EQ(86, aq.lengthOfLongestSubstring(s3)); }<|endoftext|>
<commit_before>// Copyright 2020 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 "iree_tf_compiler/TF/Passes.h" #include "mlir-hlo/Dialect/mhlo/IR/chlo_ops.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h" #include "mlir/Dialect/Linalg/IR/LinalgOps.h" #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/Shape/IR/Shape.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/Pass.h" #include "mlir/Support/LLVM.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/lower_tf.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" namespace mlir { namespace iree_integrations { namespace TF { // This is a customized version of the TF to XLA lowering in: // tensorflow/compiler/mlir/xla/transforms/legalize_tf.cc // It does not require the same number of options as we can hardcode as the pass // the IREE requires. class ConvertToMHLOPass : public PassWrapper<ConvertToMHLOPass, FunctionPass> { void getDependentDialects(DialectRegistry &registry) const override { registry.insert<mlir::linalg::LinalgDialect, mlir::TF::TensorFlowDialect, mlir::tf_executor::TensorFlowExecutorDialect, mlir::tf_device::TensorFlowDeviceDialect, mlir::tf_saved_model::TensorFlowSavedModelDialect, chlo::HloClientDialect, mhlo::MhloDialect, shape::ShapeDialect, StandardOpsDialect>(); } public: ConvertToMHLOPass() = default; ConvertToMHLOPass(const ConvertToMHLOPass &) {} void runOnFunction() override { auto op = getFunction(); MLIRContext *context = op.getContext(); // Lower TF Patterns must be separate from canonocalization patterns as // they are sometimes inversions of eachother. OwningRewritePatternList lowerTfPatterns(&getContext()); mlir::TF::PopulateLoweringTFPatterns(context, &lowerTfPatterns); OwningRewritePatternList canonicalizePatterns(&getContext()); for (auto *op : context->getRegisteredOperations()) { op->getCanonicalizationPatterns(canonicalizePatterns, context); } OwningRewritePatternList patterns(&getContext()); // Note that the `OperationConverter` orders patterns lexicographically by: // 1) Ascending legalization depth (i.e., minimum number of patterns // necessary to arrive at conversion target). // 2) Descending pattern benefit. // 3) Order of patterns in `OwningRewritePatternList`. // Add TF->HLO legalization patterns. mhlo::PopulateLegalizeTfPatterns(context, &patterns); // TF::PopulateLoweringTFPatterns(context, &patterns); // ConstantLike op is convenient to create splat constants, but is // canonicalized to plain HLO constant if statically shaped. Add the // canonicalization pattern to pattern list to enable multi-hop lowering. chlo::ConstantLikeOp::getCanonicalizationPatterns(patterns, context); ConversionTarget target(*context); target.addLegalDialect<chlo::HloClientDialect>(); target.addLegalDialect<mhlo::MhloDialect>(); target.addLegalDialect<mlir::StandardOpsDialect>(); target.addLegalDialect<shape::ShapeDialect>(); target.addLegalDialect<tensor::TensorDialect>(); target.addLegalOp<mlir::CallOp>(); target.addLegalOp<mlir::tensor::CastOp>(); target.addLegalOp<mlir::memref::DimOp>(); // TODO(suderman): Enable logicistic op for lowering once the op is // supported in IREE. Also, remove the numerically unstable ConvertSigmoidOp // pattern in the legalize-tf pass. target.addIllegalOp<mhlo::LogisticOp>(); DenseSet<Operation *> prevUnconvertedOps; DenseSet<Operation *> unconvertedOps; FrozenRewritePatternSet frozenPatterns(std::move(patterns)); FrozenRewritePatternSet frozenCanonicalizePatterns( std::move(canonicalizePatterns)); FrozenRewritePatternSet frozenTfPatterns(std::move(lowerTfPatterns)); while (true) { if (failed( applyPatternsAndFoldGreedily(op, frozenCanonicalizePatterns))) { return signalPassFailure(); } if (failed(applyPatternsAndFoldGreedily(op, frozenTfPatterns))) { return signalPassFailure(); } if (failed(applyPartialConversion(op, target, frozenPatterns, &unconvertedOps))) { return signalPassFailure(); } if (prevUnconvertedOps == unconvertedOps) break; prevUnconvertedOps = std::move(unconvertedOps); } } private: Option<bool> allow_partial_conversion_{ *this, "allow-partial-conversion", llvm::cl::desc("Allow operations that can't be legalized."), llvm::cl::init(false)}; Option<bool> legalize_chlo_{ *this, "legalize-chlo", llvm::cl::desc( "Also legalizes intermediate chlo ops to hlo (default true)"), llvm::cl::init(false)}; Option<bool> use_tf2xla_fallback_{ *this, "use-tf2xla-fallback", llvm::cl::desc( "Also use TF2XLA fallback for legalization (default false)"), llvm::cl::init(false)}; Option<std::string> device_type_{ *this, "device-type", llvm::cl::desc( "The device type used by TF2XLA fallback. Must be specified if " "use-tf2xla-fallback is true, otherwise not used."), llvm::cl::init("INVALID_DEVICE_TYPE")}; }; std::unique_ptr<FunctionPass> createConvertToMHLOPass() { return std::make_unique<ConvertToMHLOPass>(); } static PassRegistration<ConvertToMHLOPass> pass( "iree-tf-convert-to-mhlo", "Converts from TensorFlow to the XLA MHLO dialect"); } // namespace TF } // namespace iree_integrations } // namespace mlir <commit_msg>Switch Softmax and LogSoftmax ops to be expansions instead of TF->HLO legalizations.<commit_after>// Copyright 2020 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 "iree_tf_compiler/TF/Passes.h" #include "mlir-hlo/Dialect/mhlo/IR/chlo_ops.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h" #include "mlir/Dialect/Linalg/IR/LinalgOps.h" #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/Shape/IR/Shape.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/IR/BuiltinOps.h" #include "mlir/Pass/Pass.h" #include "mlir/Support/LLVM.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_executor.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" #include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h" #include "tensorflow/compiler/mlir/tensorflow/transforms/lower_tf.h" #include "tensorflow/compiler/mlir/xla/transforms/passes.h" namespace mlir { namespace iree_integrations { namespace TF { // This is a customized version of the TF to XLA lowering in: // tensorflow/compiler/mlir/xla/transforms/legalize_tf.cc // It does not require the same number of options as we can hardcode as the pass // the IREE requires. class ConvertToMHLOPass : public PassWrapper<ConvertToMHLOPass, FunctionPass> { void getDependentDialects(DialectRegistry &registry) const override { registry.insert<mlir::linalg::LinalgDialect, mlir::TF::TensorFlowDialect, mlir::tf_executor::TensorFlowExecutorDialect, mlir::tf_device::TensorFlowDeviceDialect, mlir::tf_saved_model::TensorFlowSavedModelDialect, chlo::HloClientDialect, mhlo::MhloDialect, shape::ShapeDialect, StandardOpsDialect>(); } public: ConvertToMHLOPass() = default; ConvertToMHLOPass(const ConvertToMHLOPass &) {} void runOnFunction() override { auto op = getFunction(); MLIRContext *context = op.getContext(); // Lower TF Patterns must be separate from canonocalization patterns as // they are sometimes inversions of eachother. OwningRewritePatternList lowerTfPatterns(&getContext()); mlir::TF::PopulateTFLoweringBeforeHLOPatterns(context, &lowerTfPatterns); OwningRewritePatternList canonicalizePatterns(&getContext()); for (auto *op : context->getRegisteredOperations()) { op->getCanonicalizationPatterns(canonicalizePatterns, context); } OwningRewritePatternList patterns(&getContext()); // Note that the `OperationConverter` orders patterns lexicographically by: // 1) Ascending legalization depth (i.e., minimum number of patterns // necessary to arrive at conversion target). // 2) Descending pattern benefit. // 3) Order of patterns in `OwningRewritePatternList`. // Add TF->HLO legalization patterns. mhlo::PopulateLegalizeTfPatterns(context, &patterns); // TF::PopulateLoweringTFPatterns(context, &patterns); // ConstantLike op is convenient to create splat constants, but is // canonicalized to plain HLO constant if statically shaped. Add the // canonicalization pattern to pattern list to enable multi-hop lowering. chlo::ConstantLikeOp::getCanonicalizationPatterns(patterns, context); ConversionTarget target(*context); target.addLegalDialect<chlo::HloClientDialect>(); target.addLegalDialect<mhlo::MhloDialect>(); target.addLegalDialect<mlir::StandardOpsDialect>(); target.addLegalDialect<shape::ShapeDialect>(); target.addLegalDialect<tensor::TensorDialect>(); target.addLegalOp<mlir::CallOp>(); target.addLegalOp<mlir::tensor::CastOp>(); target.addLegalOp<mlir::memref::DimOp>(); // TODO(suderman): Enable logicistic op for lowering once the op is // supported in IREE. Also, remove the numerically unstable ConvertSigmoidOp // pattern in the legalize-tf pass. target.addIllegalOp<mhlo::LogisticOp>(); DenseSet<Operation *> prevUnconvertedOps; DenseSet<Operation *> unconvertedOps; FrozenRewritePatternSet frozenPatterns(std::move(patterns)); FrozenRewritePatternSet frozenCanonicalizePatterns( std::move(canonicalizePatterns)); FrozenRewritePatternSet frozenTfPatterns(std::move(lowerTfPatterns)); while (true) { if (failed( applyPatternsAndFoldGreedily(op, frozenCanonicalizePatterns))) { return signalPassFailure(); } if (failed(applyPatternsAndFoldGreedily(op, frozenTfPatterns))) { return signalPassFailure(); } if (failed(applyPartialConversion(op, target, frozenPatterns, &unconvertedOps))) { return signalPassFailure(); } if (prevUnconvertedOps == unconvertedOps) break; prevUnconvertedOps = std::move(unconvertedOps); } } private: Option<bool> allow_partial_conversion_{ *this, "allow-partial-conversion", llvm::cl::desc("Allow operations that can't be legalized."), llvm::cl::init(false)}; Option<bool> legalize_chlo_{ *this, "legalize-chlo", llvm::cl::desc( "Also legalizes intermediate chlo ops to hlo (default true)"), llvm::cl::init(false)}; Option<bool> use_tf2xla_fallback_{ *this, "use-tf2xla-fallback", llvm::cl::desc( "Also use TF2XLA fallback for legalization (default false)"), llvm::cl::init(false)}; Option<std::string> device_type_{ *this, "device-type", llvm::cl::desc( "The device type used by TF2XLA fallback. Must be specified if " "use-tf2xla-fallback is true, otherwise not used."), llvm::cl::init("INVALID_DEVICE_TYPE")}; }; std::unique_ptr<FunctionPass> createConvertToMHLOPass() { return std::make_unique<ConvertToMHLOPass>(); } static PassRegistration<ConvertToMHLOPass> pass( "iree-tf-convert-to-mhlo", "Converts from TensorFlow to the XLA MHLO dialect"); } // namespace TF } // namespace iree_integrations } // namespace mlir <|endoftext|>
<commit_before>/* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, TU Wien http://www.iue.tuwien.ac.at ----------------- ViennaFVM - The Vienna Finite Volume Method Library ----------------- authors: Karl Rupp [email protected] (add your name here) license: To be discussed, see file LICENSE in the ViennaFVM base directory ======================================================================= */ //#define VIENNAFVM_DEBUG // Define NDEBUG to get any reasonable performance with ublas: #define NDEBUG #define VIENNAMINI_DEBUG // include necessary system headers #include <iostream> // ViennaMini main include: #include "viennamini/simulator.hpp" // Vienna Includes #include "viennamaterials/library.hpp" #include "viennamaterials/kernels/pugixml.hpp" /** @brief Structure the device by assigning 'roles', such as 'Oxide' to a segment. Also, assign a doping to the semiconductor regions */ template<typename Domain, typename Segmentation, typename Storage> void prepare(viennamini::device<Domain, Segmentation, Storage>& device) { const int source = 0; const int channel = 1; const int drain = 2; const int oxide = 3; const int gate_contact = 4; const int body = 5; const int body_contact = 6; const int source_contact = 7; const int drain_contact = 8; // Segment 0: Source device.assign_name (source, "source"); device.assign_material (source, "Si"); device.assign_semiconductor (source, 1.E24, 1.E8); // ND, NA // Segment 1: Channel device.assign_name (channel, "channel"); device.assign_material (channel, "Si"); device.assign_semiconductor (channel, 1.E17, 1.E15); // Segment 2: Drain device.assign_name (drain, "drain"); device.assign_material (drain, "Si"); device.assign_semiconductor (drain, 1.E24, 1.E8); // Segment 3: Oxide device.assign_name (oxide, "oxide"); device.assign_material (oxide, "HfO2"); device.assign_oxide (oxide); // Segment 4: Gate Contact device.assign_name (gate_contact, "gate_contact"); device.assign_material (gate_contact, "Cu"); device.assign_contact (gate_contact); // Segment 5: Body device.assign_name (body, "body"); device.assign_material (body, "Si"); device.assign_semiconductor (body, 1.E17, 1.E15); // Segment 6: Body Contact device.assign_name (body_contact, "body_contact"); device.assign_material (body_contact, "Cu"); device.assign_contact (body_contact); // Segment 7: Source Contact device.assign_name (source_contact, "source_contact"); device.assign_material (source_contact, "Cu"); device.assign_contact (source_contact); // Segment 8: Drain Contact device.assign_name (drain_contact, "drain_contact"); device.assign_material (drain_contact, "Cu"); device.assign_contact (drain_contact); } /** @brief Assign actual values to the dirichlet contacts */ void prepare_boundary_conditions(viennamini::config& config) { const int gate_contact = 4; const int body_contact = 6; const int source_contact = 7; const int drain_contact = 8; // Segment 4: Gate Contact config.assign_contact(gate_contact, 0.3, 0.0); // segment id, contact potential, workfunction // Segment 6: Body Contact config.assign_contact(body_contact, 0.0, 0.0); // Segment 7: Source Contact config.assign_contact(source_contact, 0.0, 0.0); // Segment 8: Drain Contact config.assign_contact(drain_contact, 0.3, 0.0); } /** @brief Scales the entire simulation domain (device) by the provided factor. This is accomplished by multiplying all point coordinates with this factor. */ template <typename DomainType> void scale_domain(DomainType & domain, double factor) { typedef typename viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type VertexType; typedef typename viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type VertexContainer; typedef typename viennagrid::result_of::iterator<VertexContainer>::type VertexIterator; VertexContainer vertices = viennagrid::elements<VertexType>(domain); for ( VertexIterator vit = vertices.begin(); vit != vertices.end(); ++vit ) { viennagrid::point(domain, *vit) *= factor; } } int main() { typedef double numeric_type; typedef viennagrid::domain_t< viennagrid::config::triangular_2d > domain_type; typedef viennagrid::result_of::segmentation<domain_type>::type segmentation_type; typedef segmentation_type::segment_type segment_type; typedef viennadata::storage<> storage_type; // // Create a domain from file // domain_type domain; segmentation_type segments(domain); storage_type storage; try { viennagrid::io::netgen_reader my_reader; my_reader(domain, segments, "../examples/data/half-trigate-2.mesh"); } catch (...) { std::cerr << "File-Reader failed. Aborting program..." << std::endl; return EXIT_FAILURE; } // // scale to nanometer // scale_domain(domain, 1e-9); // // Prepare material library // typedef vmat::Library<vmat::tag::pugixml>::type material_library_type; material_library_type matlib; matlib.load("../external/ViennaMaterials/database/materials.xml"); // // Create a device and a config object // typedef viennamini::device<domain_type, segmentation_type, storage_type> device_type; device_type device(domain, segments, storage); viennamini::config config; // // Prepare device, i.e., assign doping and segment roles, // e.g., oxide, semiconductor, contact // prepare(device); // // Assign contact values // prepare_boundary_conditions(config); // // Set simulation parameters // config.temperature() = 300; config.damping() = 0.3; config.linear_breaktol() = 1.0E-13; config.linear_iterations() = 500; config.nonlinear_iterations() = 100; config.nonlinear_breaktol() = 1.0E-3; config.initial_guess_smoothing_iterations() = 6; // // Create a simulator object // typedef viennamini::simulator<device_type, material_library_type> simulator_type; simulator_type simulator(device, matlib, config); // // Run the simulation // simulator(); // Write results to vtk files simulator.write_result("trigate"); std::cout << "********************************************" << std::endl; std::cout << "* MOSFET simulation finished successfully! *" << std::endl; std::cout << "********************************************" << std::endl; return EXIT_SUCCESS; } <commit_msg>fixed trigate example: the test domain type was wrong (still doesn't converge)<commit_after>/* ======================================================================= Copyright (c) 2011, Institute for Microelectronics, TU Wien http://www.iue.tuwien.ac.at ----------------- ViennaFVM - The Vienna Finite Volume Method Library ----------------- authors: Karl Rupp [email protected] (add your name here) license: To be discussed, see file LICENSE in the ViennaFVM base directory ======================================================================= */ //#define VIENNAFVM_DEBUG // Define NDEBUG to get any reasonable performance with ublas: #define NDEBUG #define VIENNAMINI_DEBUG // include necessary system headers #include <iostream> // ViennaMini main include: #include "viennamini/simulator.hpp" // Vienna Includes #include "viennamaterials/library.hpp" #include "viennamaterials/kernels/pugixml.hpp" #include "viennagrid/io/vtk_writer.hpp" /** @brief Structure the device by assigning 'roles', such as 'Oxide' to a segment. Also, assign a doping to the semiconductor regions */ template<typename Domain, typename Segmentation, typename Storage> void prepare(viennamini::device<Domain, Segmentation, Storage>& device) { const int source = 0; const int channel = 1; const int drain = 2; const int oxide = 3; const int gate_contact = 4; const int body = 5; const int body_contact = 6; const int source_contact = 7; const int drain_contact = 8; // Segment 0: Source device.assign_name (source, "source"); device.assign_material (source, "Si"); device.assign_semiconductor (source, 1.E24, 1.E8); // ND, NA // Segment 1: Channel device.assign_name (channel, "channel"); device.assign_material (channel, "Si"); device.assign_semiconductor (channel, 1.E17, 1.E15); // Segment 2: Drain device.assign_name (drain, "drain"); device.assign_material (drain, "Si"); device.assign_semiconductor (drain, 1.E24, 1.E8); // Segment 3: Oxide device.assign_name (oxide, "oxide"); device.assign_material (oxide, "HfO2"); device.assign_oxide (oxide); // Segment 4: Gate Contact device.assign_name (gate_contact, "gate_contact"); device.assign_material (gate_contact, "Cu"); device.assign_contact (gate_contact); // Segment 5: Body device.assign_name (body, "body"); device.assign_material (body, "Si"); device.assign_semiconductor (body, 1.E17, 1.E15); // Segment 6: Body Contact device.assign_name (body_contact, "body_contact"); device.assign_material (body_contact, "Cu"); device.assign_contact (body_contact); // Segment 7: Source Contact device.assign_name (source_contact, "source_contact"); device.assign_material (source_contact, "Cu"); device.assign_contact (source_contact); // Segment 8: Drain Contact device.assign_name (drain_contact, "drain_contact"); device.assign_material (drain_contact, "Cu"); device.assign_contact (drain_contact); } /** @brief Assign actual values to the dirichlet contacts */ void prepare_boundary_conditions(viennamini::config& config) { const int gate_contact = 4; const int body_contact = 6; const int source_contact = 7; const int drain_contact = 8; // Segment 4: Gate Contact config.assign_contact(gate_contact, 0.3, 0.0); // segment id, contact potential, workfunction // Segment 6: Body Contact config.assign_contact(body_contact, 0.0, 0.0); // Segment 7: Source Contact config.assign_contact(source_contact, 0.0, 0.0); // Segment 8: Drain Contact config.assign_contact(drain_contact, 0.3, 0.0); } /** @brief Scales the entire simulation domain (device) by the provided factor. This is accomplished by multiplying all point coordinates with this factor. */ template <typename DomainType> void scale_domain(DomainType & domain, double factor) { typedef typename viennagrid::result_of::element<DomainType, viennagrid::vertex_tag>::type VertexType; typedef typename viennagrid::result_of::element_range<DomainType, viennagrid::vertex_tag>::type VertexContainer; typedef typename viennagrid::result_of::iterator<VertexContainer>::type VertexIterator; VertexContainer vertices = viennagrid::elements<VertexType>(domain); for ( VertexIterator vit = vertices.begin(); vit != vertices.end(); ++vit ) { viennagrid::point(domain, *vit) *= factor; } } int main(int argc, char* argv[]) { typedef double numeric_type; typedef viennagrid::domain_t< viennagrid::config::tetrahedral_3d > domain_type; typedef viennagrid::result_of::segmentation<domain_type>::type segmentation_type; typedef segmentation_type::segment_type segment_type; typedef viennadata::storage<> storage_type; // // Create a domain from file // domain_type domain; segmentation_type segments(domain); storage_type storage; try { viennagrid::io::netgen_reader my_reader; my_reader(domain, segments, "../examples/data/half-trigate-2.mesh"); } catch (...) { std::cerr << "File-Reader failed. Aborting program..." << std::endl; return EXIT_FAILURE; } // // scale to nanometer // scale_domain(domain, 1e-9); // // Prepare material library // typedef vmat::Library<vmat::tag::pugixml>::type material_library_type; material_library_type matlib; matlib.load("../external/ViennaMaterials/database/materials.xml"); // // Create a device and a config object // typedef viennamini::device<domain_type, segmentation_type, storage_type> device_type; device_type device(domain, segments, storage); viennamini::config config; // // Prepare device, i.e., assign doping and segment roles, // e.g., oxide, semiconductor, contact // prepare(device); // // Assign contact values // prepare_boundary_conditions(config); // // Set simulation parameters // config.temperature() = 300; config.damping() = 0.3; config.linear_breaktol() = 1.0E-13; config.linear_iterations() = 500; config.nonlinear_iterations() = 100; config.nonlinear_breaktol() = 1.0E-3; config.initial_guess_smoothing_iterations() = 6; // // Create a simulator object // typedef viennamini::simulator<device_type, material_library_type> simulator_type; simulator_type simulator(device, matlib, config); // // Run the simulation // simulator(); // Write results to vtk files simulator.write_result("trigate"); std::cout << "********************************************" << std::endl; std::cout << "* MOSFET simulation finished successfully! *" << std::endl; std::cout << "********************************************" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright 2019-2022 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "QueryManagerD3D12.hpp" #include <algorithm> #include "D3D12TypeConversions.hpp" #include "GraphicsAccessories.hpp" #include "CommandContext.hpp" #include "Align.hpp" #include "RenderDeviceD3D12Impl.hpp" namespace Diligent { static Uint32 GetQueryDataSize(QUERY_TYPE QueryType) { // clang-format off switch (QueryType) { case QUERY_TYPE_OCCLUSION: case QUERY_TYPE_BINARY_OCCLUSION: case QUERY_TYPE_TIMESTAMP: case QUERY_TYPE_DURATION: return sizeof(Uint64); break; case QUERY_TYPE_PIPELINE_STATISTICS: return sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS); break; static_assert(QUERY_TYPE_NUM_TYPES == 6, "Not all QUERY_TYPE enum values are tested"); default: UNEXPECTED("Unexpected query type"); return 0; } // clang-format on } void QueryManagerD3D12::QueryHeapInfo::Init(ID3D12Device* pd3d12Device, const D3D12_QUERY_HEAP_DESC& d3d12HeapDesc, QUERY_TYPE QueryType, Uint32& CurrResolveBufferOffset) { VERIFY_EXPR(!m_pd3d12QueryHeap); m_Type = QueryType; m_QueryCount = d3d12HeapDesc.Count; auto hr = pd3d12Device->CreateQueryHeap(&d3d12HeapDesc, __uuidof(m_pd3d12QueryHeap), reinterpret_cast<void**>(&m_pd3d12QueryHeap)); CHECK_D3D_RESULT_THROW(hr, "Failed to create D3D12 query heap"); // AlignedDestinationBufferOffset must be a multiple of 8 bytes. // https://microsoft.github.io/DirectX-Specs/d3d/CountersAndQueries.html#resolvequerydata m_AlignedQueryDataSize = AlignUp(GetQueryDataSize(QueryType), Uint32{8}); m_ResolveBufferBaseOffset = CurrResolveBufferOffset; CurrResolveBufferOffset += m_AlignedQueryDataSize * m_QueryCount; m_AvailableQueries.resize(m_QueryCount); for (Uint32 i = 0; i < m_QueryCount; ++i) m_AvailableQueries[i] = i; } Uint32 QueryManagerD3D12::QueryHeapInfo::Allocate() { Uint32 Index = InvalidIndex; std::lock_guard<std::mutex> Lock{m_AvailableQueriesMtx}; if (!m_AvailableQueries.empty()) { Index = m_AvailableQueries.back(); m_AvailableQueries.pop_back(); m_MaxAllocatedQueries = std::max(m_MaxAllocatedQueries, m_QueryCount - static_cast<Uint32>(m_AvailableQueries.size())); } return Index; } void QueryManagerD3D12::QueryHeapInfo::Release(Uint32 Index) { VERIFY(Index < m_QueryCount, "Query index ", Index, " is out of range"); std::lock_guard<std::mutex> Lock{m_AvailableQueriesMtx}; VERIFY(std::find(m_AvailableQueries.begin(), m_AvailableQueries.end(), Index) == m_AvailableQueries.end(), "Index ", Index, " already present in available queries list"); m_AvailableQueries.push_back(Index); } QueryManagerD3D12::QueryHeapInfo::~QueryHeapInfo() { if (m_AvailableQueries.size() != m_QueryCount) { auto OutstandingQueries = m_QueryCount - m_AvailableQueries.size(); if (OutstandingQueries == 1) { LOG_ERROR_MESSAGE("One query of type ", GetQueryTypeString(m_Type), " has not been returned to the query manager"); } else { LOG_ERROR_MESSAGE(OutstandingQueries, " queries of type ", GetQueryTypeString(m_Type), " have not been returned to the query manager"); } } } QueryManagerD3D12::QueryManagerD3D12(RenderDeviceD3D12Impl* pDeviceD3D12Impl, const Uint32 QueryHeapSizes[], SoftwareQueueIndex CommandQueueId, HardwareQueueIndex HwQueueInd) : m_CommandQueueId{CommandQueueId} { const auto& DevInfo = pDeviceD3D12Impl->GetDeviceInfo(); auto* pd3d12Device = pDeviceD3D12Impl->GetD3D12Device(); Uint32 ResolveBufferOffset = 0; for (Uint32 query_type = QUERY_TYPE_UNDEFINED + 1; query_type < QUERY_TYPE_NUM_TYPES; ++query_type) { const auto QueryType = static_cast<QUERY_TYPE>(query_type); // clang-format off static_assert(QUERY_TYPE_OCCLUSION == 1, "Unexpected value of QUERY_TYPE_OCCLUSION. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_BINARY_OCCLUSION == 2, "Unexpected value of QUERY_TYPE_BINARY_OCCLUSION. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_TIMESTAMP == 3, "Unexpected value of QUERY_TYPE_TIMESTAMP. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_PIPELINE_STATISTICS== 4, "Unexpected value of QUERY_TYPE_PIPELINE_STATISTICS. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_DURATION == 5, "Unexpected value of QUERY_TYPE_DURATION. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_NUM_TYPES == 6, "Unexpected value of QUERY_TYPE_NUM_TYPES. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); // clang-format on // Time and duration queries are supported in all queues if (QueryType == QUERY_TYPE_TIMESTAMP || QueryType == QUERY_TYPE_DURATION) { if (HwQueueInd == D3D12HWQueueIndex_Copy && !DevInfo.Features.TransferQueueTimestampQueries) continue; // Not supported in transfer queue } // Other queries are only supported in graphics queue else if (HwQueueInd != D3D12HWQueueIndex_Graphics) continue; D3D12_QUERY_HEAP_DESC d3d12HeapDesc{}; d3d12HeapDesc.Type = QueryTypeToD3D12QueryHeapType(QueryType, HwQueueInd); d3d12HeapDesc.Count = QueryHeapSizes[QueryType]; if (QueryType == QUERY_TYPE_DURATION) d3d12HeapDesc.Count *= 2; auto& HeapInfo = m_Heaps[QueryType]; HeapInfo.Init(pd3d12Device, d3d12HeapDesc, QueryType, ResolveBufferOffset); VERIFY_EXPR(!HeapInfo.IsNull() && HeapInfo.GetType() == QueryType && HeapInfo.GetQueryCount() == d3d12HeapDesc.Count); } D3D12_RESOURCE_DESC D3D12BuffDesc = {}; D3D12BuffDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; D3D12BuffDesc.Alignment = 0; D3D12BuffDesc.Width = ResolveBufferOffset; D3D12BuffDesc.Height = 1; D3D12BuffDesc.DepthOrArraySize = 1; D3D12BuffDesc.MipLevels = 1; D3D12BuffDesc.Format = DXGI_FORMAT_UNKNOWN; D3D12BuffDesc.SampleDesc.Count = 1; D3D12BuffDesc.SampleDesc.Quality = 0; // Layout must be D3D12_TEXTURE_LAYOUT_ROW_MAJOR, as buffer memory layouts are // understood by applications and row-major texture data is commonly marshaled through buffers. D3D12BuffDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; D3D12BuffDesc.Flags = D3D12_RESOURCE_FLAG_NONE; D3D12_HEAP_PROPERTIES HeapProps = {}; HeapProps.Type = D3D12_HEAP_TYPE_READBACK; HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; HeapProps.CreationNodeMask = 1; HeapProps.VisibleNodeMask = 1; // The destination buffer of a query resolve operation must be in the D3D12_RESOURCE_USAGE_COPY_DEST state. // ResolveQueryData works with all heap types (default, upload, readback). // https://microsoft.github.io/DirectX-Specs/d3d/CountersAndQueries.html#resolvequerydata auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &D3D12BuffDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(m_pd3d12ResolveBuffer), reinterpret_cast<void**>(static_cast<ID3D12Resource**>(&m_pd3d12ResolveBuffer))); if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create D3D12 resolve buffer"); } QueryManagerD3D12::~QueryManagerD3D12() { std::stringstream QueryUsageSS; QueryUsageSS << "D3D12 query manager peak usage:"; for (Uint32 query_type = QUERY_TYPE_UNDEFINED + 1; query_type < QUERY_TYPE_NUM_TYPES; ++query_type) { const auto QueryType = static_cast<QUERY_TYPE>(query_type); const auto& HeapInfo = m_Heaps[QueryType]; if (HeapInfo.IsNull()) continue; QueryUsageSS << std::endl << std::setw(30) << std::left << GetQueryTypeString(QueryType) << ": " << std::setw(4) << std::right << HeapInfo.GetMaxAllocatedQueries() << '/' << std::setw(4) << HeapInfo.GetQueryCount(); } LOG_INFO_MESSAGE(QueryUsageSS.str()); } Uint32 QueryManagerD3D12::AllocateQuery(QUERY_TYPE Type) { return m_Heaps[Type].Allocate(); } void QueryManagerD3D12::ReleaseQuery(QUERY_TYPE Type, Uint32 Index) { m_Heaps[Type].Release(Index); } void QueryManagerD3D12::BeginQuery(CommandContext& Ctx, QUERY_TYPE Type, Uint32 Index) const { const auto d3d12QueryType = QueryTypeToD3D12QueryType(Type); const auto& HeapInfo = m_Heaps[Type]; VERIFY_EXPR(HeapInfo.GetType() == Type); VERIFY(Index < HeapInfo.GetQueryCount(), "Query index ", Index, " is out of range"); Ctx.BeginQuery(HeapInfo.GetD3D12QueryHeap(), d3d12QueryType, Index); } void QueryManagerD3D12::EndQuery(CommandContext& Ctx, QUERY_TYPE Type, Uint32 Index) const { const auto d3d12QueryType = QueryTypeToD3D12QueryType(Type); const auto& HeapInfo = m_Heaps[Type]; VERIFY_EXPR(HeapInfo.GetType() == Type); VERIFY(Index < HeapInfo.GetQueryCount(), "Query index ", Index, " is out of range"); Ctx.EndQuery(HeapInfo.GetD3D12QueryHeap(), d3d12QueryType, Index); // https://microsoft.github.io/DirectX-Specs/d3d/CountersAndQueries.html#resolvequerydata Ctx.ResolveQueryData(HeapInfo.GetD3D12QueryHeap(), d3d12QueryType, Index, 1, m_pd3d12ResolveBuffer, HeapInfo.GetResolveBufferOffset(Index)); } void QueryManagerD3D12::ReadQueryData(QUERY_TYPE Type, Uint32 Index, void* pDataPtr, Uint32 DataSize) const { const auto& HeapInfo = m_Heaps[Type]; VERIFY_EXPR(HeapInfo.GetType() == Type); const auto QueryDataSize = GetQueryDataSize(Type); VERIFY_EXPR(QueryDataSize == DataSize); const auto Offset = HeapInfo.GetResolveBufferOffset(Index); D3D12_RANGE ReadRange; ReadRange.Begin = Offset; ReadRange.End = SIZE_T{Offset} + SIZE_T{QueryDataSize}; void* pBufferData = nullptr; // The pointer returned by Map is never offset by any values in pReadRange. m_pd3d12ResolveBuffer->Map(0, &ReadRange, &pBufferData); memcpy(pDataPtr, reinterpret_cast<const Uint8*>(pBufferData) + Offset, QueryDataSize); m_pd3d12ResolveBuffer->Unmap(0, nullptr); } } // namespace Diligent <commit_msg>QueryManagerD3D12: fixed zero-size buffer initialization<commit_after>/* * Copyright 2019-2022 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "QueryManagerD3D12.hpp" #include <algorithm> #include "D3D12TypeConversions.hpp" #include "GraphicsAccessories.hpp" #include "CommandContext.hpp" #include "Align.hpp" #include "RenderDeviceD3D12Impl.hpp" namespace Diligent { static Uint32 GetQueryDataSize(QUERY_TYPE QueryType) { // clang-format off switch (QueryType) { case QUERY_TYPE_OCCLUSION: case QUERY_TYPE_BINARY_OCCLUSION: case QUERY_TYPE_TIMESTAMP: case QUERY_TYPE_DURATION: return sizeof(Uint64); break; case QUERY_TYPE_PIPELINE_STATISTICS: return sizeof(D3D12_QUERY_DATA_PIPELINE_STATISTICS); break; static_assert(QUERY_TYPE_NUM_TYPES == 6, "Not all QUERY_TYPE enum values are tested"); default: UNEXPECTED("Unexpected query type"); return 0; } // clang-format on } void QueryManagerD3D12::QueryHeapInfo::Init(ID3D12Device* pd3d12Device, const D3D12_QUERY_HEAP_DESC& d3d12HeapDesc, QUERY_TYPE QueryType, Uint32& CurrResolveBufferOffset) { VERIFY_EXPR(!m_pd3d12QueryHeap); m_Type = QueryType; m_QueryCount = d3d12HeapDesc.Count; auto hr = pd3d12Device->CreateQueryHeap(&d3d12HeapDesc, __uuidof(m_pd3d12QueryHeap), reinterpret_cast<void**>(&m_pd3d12QueryHeap)); CHECK_D3D_RESULT_THROW(hr, "Failed to create D3D12 query heap"); // AlignedDestinationBufferOffset must be a multiple of 8 bytes. // https://microsoft.github.io/DirectX-Specs/d3d/CountersAndQueries.html#resolvequerydata m_AlignedQueryDataSize = AlignUp(GetQueryDataSize(QueryType), Uint32{8}); m_ResolveBufferBaseOffset = CurrResolveBufferOffset; CurrResolveBufferOffset += m_AlignedQueryDataSize * m_QueryCount; m_AvailableQueries.resize(m_QueryCount); for (Uint32 i = 0; i < m_QueryCount; ++i) m_AvailableQueries[i] = i; } Uint32 QueryManagerD3D12::QueryHeapInfo::Allocate() { Uint32 Index = InvalidIndex; std::lock_guard<std::mutex> Lock{m_AvailableQueriesMtx}; if (!m_AvailableQueries.empty()) { Index = m_AvailableQueries.back(); m_AvailableQueries.pop_back(); m_MaxAllocatedQueries = std::max(m_MaxAllocatedQueries, m_QueryCount - static_cast<Uint32>(m_AvailableQueries.size())); } return Index; } void QueryManagerD3D12::QueryHeapInfo::Release(Uint32 Index) { VERIFY(Index < m_QueryCount, "Query index ", Index, " is out of range"); std::lock_guard<std::mutex> Lock{m_AvailableQueriesMtx}; VERIFY(std::find(m_AvailableQueries.begin(), m_AvailableQueries.end(), Index) == m_AvailableQueries.end(), "Index ", Index, " already present in available queries list"); m_AvailableQueries.push_back(Index); } QueryManagerD3D12::QueryHeapInfo::~QueryHeapInfo() { if (m_AvailableQueries.size() != m_QueryCount) { auto OutstandingQueries = m_QueryCount - m_AvailableQueries.size(); if (OutstandingQueries == 1) { LOG_ERROR_MESSAGE("One query of type ", GetQueryTypeString(m_Type), " has not been returned to the query manager"); } else { LOG_ERROR_MESSAGE(OutstandingQueries, " queries of type ", GetQueryTypeString(m_Type), " have not been returned to the query manager"); } } } QueryManagerD3D12::QueryManagerD3D12(RenderDeviceD3D12Impl* pDeviceD3D12Impl, const Uint32 QueryHeapSizes[], SoftwareQueueIndex CommandQueueId, HardwareQueueIndex HwQueueInd) : m_CommandQueueId{CommandQueueId} { const auto& DevInfo = pDeviceD3D12Impl->GetDeviceInfo(); auto* pd3d12Device = pDeviceD3D12Impl->GetD3D12Device(); Uint32 ResolveBufferOffset = 0; for (Uint32 query_type = QUERY_TYPE_UNDEFINED + 1; query_type < QUERY_TYPE_NUM_TYPES; ++query_type) { const auto QueryType = static_cast<QUERY_TYPE>(query_type); // clang-format off static_assert(QUERY_TYPE_OCCLUSION == 1, "Unexpected value of QUERY_TYPE_OCCLUSION. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_BINARY_OCCLUSION == 2, "Unexpected value of QUERY_TYPE_BINARY_OCCLUSION. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_TIMESTAMP == 3, "Unexpected value of QUERY_TYPE_TIMESTAMP. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_PIPELINE_STATISTICS== 4, "Unexpected value of QUERY_TYPE_PIPELINE_STATISTICS. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_DURATION == 5, "Unexpected value of QUERY_TYPE_DURATION. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); static_assert(QUERY_TYPE_NUM_TYPES == 6, "Unexpected value of QUERY_TYPE_NUM_TYPES. EngineD3D12CreateInfo::QueryPoolSizes must be updated"); // clang-format on // Time and duration queries are supported in all queues if (QueryType == QUERY_TYPE_TIMESTAMP || QueryType == QUERY_TYPE_DURATION) { if (HwQueueInd == D3D12HWQueueIndex_Copy && !DevInfo.Features.TransferQueueTimestampQueries) continue; // Not supported in transfer queue } // Other queries are only supported in graphics queue else if (HwQueueInd != D3D12HWQueueIndex_Graphics) continue; D3D12_QUERY_HEAP_DESC d3d12HeapDesc{}; d3d12HeapDesc.Type = QueryTypeToD3D12QueryHeapType(QueryType, HwQueueInd); d3d12HeapDesc.Count = QueryHeapSizes[QueryType]; if (QueryType == QUERY_TYPE_DURATION) d3d12HeapDesc.Count *= 2; auto& HeapInfo = m_Heaps[QueryType]; HeapInfo.Init(pd3d12Device, d3d12HeapDesc, QueryType, ResolveBufferOffset); VERIFY_EXPR(!HeapInfo.IsNull() && HeapInfo.GetType() == QueryType && HeapInfo.GetQueryCount() == d3d12HeapDesc.Count); } if (ResolveBufferOffset > 0) { D3D12_RESOURCE_DESC D3D12BuffDesc{}; D3D12BuffDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; D3D12BuffDesc.Alignment = 0; D3D12BuffDesc.Width = ResolveBufferOffset; D3D12BuffDesc.Height = 1; D3D12BuffDesc.DepthOrArraySize = 1; D3D12BuffDesc.MipLevels = 1; D3D12BuffDesc.Format = DXGI_FORMAT_UNKNOWN; D3D12BuffDesc.SampleDesc.Count = 1; D3D12BuffDesc.SampleDesc.Quality = 0; // Layout must be D3D12_TEXTURE_LAYOUT_ROW_MAJOR, as buffer memory layouts are // understood by applications and row-major texture data is commonly marshaled through buffers. D3D12BuffDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; D3D12BuffDesc.Flags = D3D12_RESOURCE_FLAG_NONE; D3D12_HEAP_PROPERTIES HeapProps{}; HeapProps.Type = D3D12_HEAP_TYPE_READBACK; HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; HeapProps.CreationNodeMask = 1; HeapProps.VisibleNodeMask = 1; // The destination buffer of a query resolve operation must be in the D3D12_RESOURCE_USAGE_COPY_DEST state. // ResolveQueryData works with all heap types (default, upload, readback). // https://microsoft.github.io/DirectX-Specs/d3d/CountersAndQueries.html#resolvequerydata auto hr = pd3d12Device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &D3D12BuffDesc, D3D12_RESOURCE_STATE_COPY_DEST, nullptr, __uuidof(m_pd3d12ResolveBuffer), reinterpret_cast<void**>(static_cast<ID3D12Resource**>(&m_pd3d12ResolveBuffer))); if (FAILED(hr)) LOG_ERROR_AND_THROW("Failed to create D3D12 resolve buffer"); } } QueryManagerD3D12::~QueryManagerD3D12() { std::stringstream QueryUsageSS; QueryUsageSS << "D3D12 query manager peak usage:"; for (Uint32 query_type = QUERY_TYPE_UNDEFINED + 1; query_type < QUERY_TYPE_NUM_TYPES; ++query_type) { const auto QueryType = static_cast<QUERY_TYPE>(query_type); const auto& HeapInfo = m_Heaps[QueryType]; if (HeapInfo.IsNull()) continue; QueryUsageSS << std::endl << std::setw(30) << std::left << GetQueryTypeString(QueryType) << ": " << std::setw(4) << std::right << HeapInfo.GetMaxAllocatedQueries() << '/' << std::setw(4) << HeapInfo.GetQueryCount(); } LOG_INFO_MESSAGE(QueryUsageSS.str()); } Uint32 QueryManagerD3D12::AllocateQuery(QUERY_TYPE Type) { return m_Heaps[Type].Allocate(); } void QueryManagerD3D12::ReleaseQuery(QUERY_TYPE Type, Uint32 Index) { m_Heaps[Type].Release(Index); } void QueryManagerD3D12::BeginQuery(CommandContext& Ctx, QUERY_TYPE Type, Uint32 Index) const { const auto d3d12QueryType = QueryTypeToD3D12QueryType(Type); const auto& HeapInfo = m_Heaps[Type]; VERIFY_EXPR(HeapInfo.GetType() == Type); VERIFY(Index < HeapInfo.GetQueryCount(), "Query index ", Index, " is out of range"); Ctx.BeginQuery(HeapInfo.GetD3D12QueryHeap(), d3d12QueryType, Index); } void QueryManagerD3D12::EndQuery(CommandContext& Ctx, QUERY_TYPE Type, Uint32 Index) const { const auto d3d12QueryType = QueryTypeToD3D12QueryType(Type); const auto& HeapInfo = m_Heaps[Type]; VERIFY_EXPR(HeapInfo.GetType() == Type); VERIFY(Index < HeapInfo.GetQueryCount(), "Query index ", Index, " is out of range"); Ctx.EndQuery(HeapInfo.GetD3D12QueryHeap(), d3d12QueryType, Index); // https://microsoft.github.io/DirectX-Specs/d3d/CountersAndQueries.html#resolvequerydata Ctx.ResolveQueryData(HeapInfo.GetD3D12QueryHeap(), d3d12QueryType, Index, 1, m_pd3d12ResolveBuffer, HeapInfo.GetResolveBufferOffset(Index)); } void QueryManagerD3D12::ReadQueryData(QUERY_TYPE Type, Uint32 Index, void* pDataPtr, Uint32 DataSize) const { const auto& HeapInfo = m_Heaps[Type]; VERIFY_EXPR(HeapInfo.GetType() == Type); const auto QueryDataSize = GetQueryDataSize(Type); VERIFY_EXPR(QueryDataSize == DataSize); const auto Offset = HeapInfo.GetResolveBufferOffset(Index); D3D12_RANGE ReadRange; ReadRange.Begin = Offset; ReadRange.End = SIZE_T{Offset} + SIZE_T{QueryDataSize}; void* pBufferData = nullptr; // The pointer returned by Map is never offset by any values in pReadRange. m_pd3d12ResolveBuffer->Map(0, &ReadRange, &pBufferData); memcpy(pDataPtr, reinterpret_cast<const Uint8*>(pBufferData) + Offset, QueryDataSize); m_pd3d12ResolveBuffer->Unmap(0, nullptr); } } // namespace Diligent <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTestHierarchicalDataReader.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. =========================================================================*/ #include "vtkTestHierarchicalDataReader.h" #include "vtkAMRBox.h" #include "vtkCompositeDataPipeline.h" #include "vtkExecutive.h" #include "vtkHierarchicalBoxDataSet.h" #include "vtkHierarchicalDataInformation.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkUniformGrid.h" #include "vtkXMLImageDataReader.h" vtkCxxRevisionMacro(vtkTestHierarchicalDataReader, "1.6"); vtkStandardNewMacro(vtkTestHierarchicalDataReader); vtkTestHierarchicalDataReader::vtkTestHierarchicalDataReader() { this->FileName = 0; this->SetNumberOfInputPorts(0); } vtkTestHierarchicalDataReader::~vtkTestHierarchicalDataReader() { this->SetFileName(0); } // Provide information about the dataset: // * Number of levels // * Number of boxes / level // * AMRBox (extent) of each box int vtkTestHierarchicalDataReader::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if (!this->Superclass::RequestInformation(request, inputVector, outputVector)) { return 0; } const int numLevels = 3; int numBlocks[numLevels] = { 1, 1, 14 }; vtkHierarchicalDataInformation* compInfo = vtkHierarchicalDataInformation::New(); compInfo->SetNumberOfLevels(numLevels); int i; for (i=0; i<numLevels; i++) { compInfo->SetNumberOfDataSets(i, numBlocks[i]); } vtkInformation* info = outputVector->GetInformationObject(0); info->Set( vtkCompositeDataPipeline::COMPOSITE_DATA_INFORMATION(), compInfo); info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); vtkXMLImageDataReader* reader = vtkXMLImageDataReader::New(); for (i=0; i<16; i++) { // Here we load the 16 separate files (each containing // an image dataset -uniform rectilinear grid-) char* fstr = this->GetBlockFileName(i); reader->SetFileName(fstr); reader->UpdateInformation(); delete[] fstr; // Each sub-dataset in a vtkHierarchicalBoxDataSet has an associated // vtkAMRBox. This is similar to extent but is stored externally // since it is possible to have sub-dataset nodes with NULL // vtkUniformGrid pointers. vtkAMRBox box; // This is a hack (do not do this at home). Normally, the // region (box) information should be available in the file. // In this case, since there is no such information available, // we obtain it by looking at each image data's extent. // -- begin hack int extent[6]; double spacing[3]; double origin[3]; vtkInformation* outInfo = reader->GetExecutive()->GetOutputInformation(0); outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); outInfo->Get(vtkDataObject::SPACING(), spacing); outInfo->Get(vtkDataObject::ORIGIN(), origin); int j; for (j=0; j<3; j++) { int num = static_cast<int>(floor(origin[j]/spacing[j] + 0.5)); box.LoCorner[j] = num + extent[2*j]; box.HiCorner[j] = num + extent[2*j+1] - 1; } int level; int dsindex; this->GetBlockIdx(i, level, dsindex); vtkInformation* subInfo = compInfo->GetInformation(level, dsindex); subInfo->Set(vtkHierarchicalBoxDataSet::BOX(), box.LoCorner[0], box.LoCorner[1], box.LoCorner[2], box.HiCorner[0], box.HiCorner[1], box.HiCorner[2]); } reader->Delete(); compInfo->Delete(); return 1; } int vtkTestHierarchicalDataReader::SetUpdateBlocks( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { vtkInformation* info = outputVector->GetInformationObject(0); if (!info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) || !info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES())) { vtkErrorMacro("Expected information not found. " "Cannot provide update extent."); return 0; } vtkHierarchicalDataInformation* compInfo = vtkHierarchicalDataInformation::SafeDownCast( info->Get(vtkCompositeDataPipeline::COMPOSITE_DATA_INFORMATION())); if (!compInfo) { vtkErrorMacro("Expected information not found. " "Cannot provide update extent."); return 0; } vtkHierarchicalDataInformation* updateInfo = vtkHierarchicalDataInformation::New(); info->Set( vtkCompositeDataPipeline::UPDATE_BLOCKS(), updateInfo); updateInfo->SetNumberOfLevels(compInfo->GetNumberOfLevels()); unsigned int updatePiece = static_cast<unsigned int>( info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER())); unsigned int updateNumPieces = static_cast<unsigned int>( info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES())); unsigned int numLevels = updateInfo->GetNumberOfLevels(); for (unsigned int j=0; j<numLevels; j++) { updateInfo->SetNumberOfDataSets(j, compInfo->GetNumberOfDataSets(j)); unsigned int numBlocks = updateInfo->GetNumberOfDataSets(j); unsigned int numBlocksPerPiece = 1; if (updateNumPieces < numBlocks) { numBlocksPerPiece = numBlocks / updateNumPieces; } unsigned int minBlock = numBlocksPerPiece*updatePiece; unsigned int maxBlock = numBlocksPerPiece*(updatePiece+1); if (updatePiece == updateNumPieces - 1) { maxBlock = numBlocks; } for (unsigned int i=minBlock; i<maxBlock; i++) { vtkInformation* blockInfo = updateInfo->GetInformation(j, i); blockInfo->Set(vtkCompositeDataPipeline::MARKED_FOR_UPDATE(), 1); } } updateInfo->Delete(); return 1; } int vtkTestHierarchicalDataReader::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { int i; if (!this->FileName) { return 0; } vtkInformation* info = outputVector->GetInformationObject(0); vtkDataObject* doOutput = info->Get(vtkCompositeDataSet::COMPOSITE_DATA_SET()); vtkHierarchicalBoxDataSet* hb = vtkHierarchicalBoxDataSet::SafeDownCast(doOutput); if (!hb) { return 0; } vtkHierarchicalDataInformation* compInfo = vtkHierarchicalDataInformation::SafeDownCast( info->Get(vtkCompositeDataPipeline::COMPOSITE_DATA_INFORMATION())); hb->SetHierarchicalDataInformation(compInfo); // Since there is no AMR reader avaible yet, we will load a // collection of VTK files and create our own vtkHierarchicalBoxDataSet. // To create the files, I loaded a Chombo file with an experimental // Chombo reader and wrote the datasets separately. vtkXMLImageDataReader* reader = vtkXMLImageDataReader::New(); for (i=0; i<16; i++) { // Here we load the 16 separate files (each containing // an image dataset -uniform rectilinear grid-) char* fstr = this->GetBlockFileName(i); reader->SetFileName(fstr); // We have to update since we are working without a VTK pipeline. // This will read the file and the output of the reader will be // a valid image data. reader->Update(); delete[] fstr; // We now create a vtkUniformGrid. This is essentially a simple // vtkImageData (not a sub-class though) with blanking. Since // VTK readers do not know vtkUniformGrid, we simply create our // own by copying from the image data. vtkUniformGrid* ug = vtkUniformGrid::New(); ug->ShallowCopy(reader->GetOutput()); int level; int dsindex; this->GetBlockIdx(i, level, dsindex); // Given the level, index and box, add the sub-dataset to // hierarchical dataset. hb->SetDataSet(level, dsindex, ug); ug->Delete(); } reader->Delete(); // I hard-coded the refinement ratios. These should normally // be available in the file. hb->SetRefinementRatio(0, 2); hb->SetRefinementRatio(1, 2); // This call generates visibility (blanking) arrays that mask // regions of lower level datasets that overlap with regions // of higher level datasets (it is assumed that, when available, // higher level information should always be used instead of // lower level information) hb->GenerateVisibilityArrays(); return 1; } void vtkTestHierarchicalDataReader::GetBlockIdx( int blockId, int& level, int& dsindex) { // Similarly, the level of each sub-dataset is normally // available in the file. Since this is not the case, I // hard-coded this into the example program. // Level 0 = { 0 }, Level 1 = { 1 }, // Level 2 = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } if (blockId == 0) { level = 0; dsindex = 0; } else if (blockId == 1) { level = 1; dsindex = 0; } else { level = 2; dsindex = blockId-2; } } char* vtkTestHierarchicalDataReader::GetBlockFileName(int blockId) { size_t len = strlen(this->FileName); size_t pos; for (pos=0; pos<len; pos++) { if (this->FileName[pos] == '.') { break; } } char* fname = new char[pos+1]; strncpy(fname, this->FileName, pos); fname[pos] = '\0'; // Here we load the 16 separate files (each containing // an image dataset -uniform rectilinear grid-) char* fstr = new char [strlen(fname) + strlen(".vti") + 10]; sprintf(fstr,"%s_%i.vti",fname, blockId); delete[] fname; return fstr; } int vtkTestHierarchicalDataReader::FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataObject"); info->Set(vtkCompositeDataPipeline::COMPOSITE_DATA_TYPE_NAME(), "vtkHierarchicalBoxDataSet"); return 1; } void vtkTestHierarchicalDataReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; } <commit_msg>COMP: Fix several test failures and warnings for VJ dashboards... Details, including comments and related file lists, follow.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTestHierarchicalDataReader.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. =========================================================================*/ #include "vtkTestHierarchicalDataReader.h" #include "vtkAMRBox.h" #include "vtkCompositeDataPipeline.h" #include "vtkExecutive.h" #include "vtkHierarchicalBoxDataSet.h" #include "vtkHierarchicalDataInformation.h" #include "vtkImageData.h" #include "vtkInformation.h" #include "vtkInformationIntegerVectorKey.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkUniformGrid.h" #include "vtkXMLImageDataReader.h" vtkCxxRevisionMacro(vtkTestHierarchicalDataReader, "1.7"); vtkStandardNewMacro(vtkTestHierarchicalDataReader); vtkTestHierarchicalDataReader::vtkTestHierarchicalDataReader() { this->FileName = 0; this->SetNumberOfInputPorts(0); } vtkTestHierarchicalDataReader::~vtkTestHierarchicalDataReader() { this->SetFileName(0); } // Provide information about the dataset: // * Number of levels // * Number of boxes / level // * AMRBox (extent) of each box int vtkTestHierarchicalDataReader::RequestInformation( vtkInformation* request, vtkInformationVector** inputVector, vtkInformationVector* outputVector) { if (!this->Superclass::RequestInformation(request, inputVector, outputVector)) { return 0; } const int numLevels = 3; int numBlocks[numLevels] = { 1, 1, 14 }; vtkHierarchicalDataInformation* compInfo = vtkHierarchicalDataInformation::New(); compInfo->SetNumberOfLevels(numLevels); int i; for (i=0; i<numLevels; i++) { compInfo->SetNumberOfDataSets(i, numBlocks[i]); } vtkInformation* info = outputVector->GetInformationObject(0); info->Set( vtkCompositeDataPipeline::COMPOSITE_DATA_INFORMATION(), compInfo); info->Set( vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1); vtkXMLImageDataReader* reader = vtkXMLImageDataReader::New(); for (i=0; i<16; i++) { // Here we load the 16 separate files (each containing // an image dataset -uniform rectilinear grid-) char* fstr = this->GetBlockFileName(i); reader->SetFileName(fstr); reader->UpdateInformation(); delete[] fstr; // Each sub-dataset in a vtkHierarchicalBoxDataSet has an associated // vtkAMRBox. This is similar to extent but is stored externally // since it is possible to have sub-dataset nodes with NULL // vtkUniformGrid pointers. vtkAMRBox box; // This is a hack (do not do this at home). Normally, the // region (box) information should be available in the file. // In this case, since there is no such information available, // we obtain it by looking at each image data's extent. // -- begin hack int extent[6]; double spacing[3]; double origin[3]; vtkInformation* outInfo = reader->GetExecutive()->GetOutputInformation(0); outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), extent); outInfo->Get(vtkDataObject::SPACING(), spacing); outInfo->Get(vtkDataObject::ORIGIN(), origin); int j; for (j=0; j<3; j++) { int num = static_cast<int>(floor(origin[j]/spacing[j] + 0.5)); box.LoCorner[j] = num + extent[2*j]; box.HiCorner[j] = num + extent[2*j+1] - 1; } int level; int dsindex; this->GetBlockIdx(i, level, dsindex); vtkInformation* subInfo = compInfo->GetInformation(level, dsindex); subInfo->Set(vtkHierarchicalBoxDataSet::BOX(), box.LoCorner[0], box.LoCorner[1], box.LoCorner[2], box.HiCorner[0], box.HiCorner[1], box.HiCorner[2]); } reader->Delete(); compInfo->Delete(); return 1; } int vtkTestHierarchicalDataReader::SetUpdateBlocks( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { vtkInformation* info = outputVector->GetInformationObject(0); if (!info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) || !info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES())) { vtkErrorMacro("Expected information not found. " "Cannot provide update extent."); return 0; } vtkHierarchicalDataInformation* compInfo = vtkHierarchicalDataInformation::SafeDownCast( info->Get(vtkCompositeDataPipeline::COMPOSITE_DATA_INFORMATION())); if (!compInfo) { vtkErrorMacro("Expected information not found. " "Cannot provide update extent."); return 0; } vtkHierarchicalDataInformation* updateInfo = vtkHierarchicalDataInformation::New(); info->Set( vtkCompositeDataPipeline::UPDATE_BLOCKS(), updateInfo); updateInfo->SetNumberOfLevels(compInfo->GetNumberOfLevels()); unsigned int updatePiece = static_cast<unsigned int>( info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER())); unsigned int updateNumPieces = static_cast<unsigned int>( info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES())); unsigned int numLevels = updateInfo->GetNumberOfLevels(); for (unsigned int j=0; j<numLevels; j++) { updateInfo->SetNumberOfDataSets(j, compInfo->GetNumberOfDataSets(j)); unsigned int numBlocks = updateInfo->GetNumberOfDataSets(j); unsigned int numBlocksPerPiece = 1; if (updateNumPieces < numBlocks) { numBlocksPerPiece = numBlocks / updateNumPieces; } unsigned int minBlock = numBlocksPerPiece*updatePiece; unsigned int maxBlock = numBlocksPerPiece*(updatePiece+1); if (updatePiece == updateNumPieces - 1) { maxBlock = numBlocks; } for (unsigned int i=minBlock; i<maxBlock; i++) { vtkInformation* blockInfo = updateInfo->GetInformation(j, i); blockInfo->Set(vtkCompositeDataPipeline::MARKED_FOR_UPDATE(), 1); } } updateInfo->Delete(); return 1; } int vtkTestHierarchicalDataReader::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { int i; if (!this->FileName) { return 0; } vtkInformation* info = outputVector->GetInformationObject(0); vtkDataObject* doOutput = info->Get(vtkCompositeDataSet::COMPOSITE_DATA_SET()); vtkHierarchicalBoxDataSet* hb = vtkHierarchicalBoxDataSet::SafeDownCast(doOutput); if (!hb) { return 0; } vtkHierarchicalDataInformation* compInfo = vtkHierarchicalDataInformation::SafeDownCast( info->Get(vtkCompositeDataPipeline::COMPOSITE_DATA_INFORMATION())); hb->SetHierarchicalDataInformation(compInfo); // Since there is no AMR reader avaible yet, we will load a // collection of VTK files and create our own vtkHierarchicalBoxDataSet. // To create the files, I loaded a Chombo file with an experimental // Chombo reader and wrote the datasets separately. vtkXMLImageDataReader* reader = vtkXMLImageDataReader::New(); for (i=0; i<16; i++) { // Here we load the 16 separate files (each containing // an image dataset -uniform rectilinear grid-) char* fstr = this->GetBlockFileName(i); reader->SetFileName(fstr); // We have to update since we are working without a VTK pipeline. // This will read the file and the output of the reader will be // a valid image data. reader->Update(); delete[] fstr; // We now create a vtkUniformGrid. This is essentially a simple // vtkImageData (not a sub-class though) with blanking. Since // VTK readers do not know vtkUniformGrid, we simply create our // own by copying from the image data. vtkUniformGrid* ug = vtkUniformGrid::New(); ug->ShallowCopy(reader->GetOutput()); int level; int dsindex; this->GetBlockIdx(i, level, dsindex); // Given the level, index and box, add the sub-dataset to // hierarchical dataset. hb->SetDataSet(level, dsindex, ug); ug->Delete(); } reader->Delete(); // I hard-coded the refinement ratios. These should normally // be available in the file. hb->SetRefinementRatio(0, 2); hb->SetRefinementRatio(1, 2); // This call generates visibility (blanking) arrays that mask // regions of lower level datasets that overlap with regions // of higher level datasets (it is assumed that, when available, // higher level information should always be used instead of // lower level information) hb->GenerateVisibilityArrays(); return 1; } void vtkTestHierarchicalDataReader::GetBlockIdx( int blockId, int& level, int& dsindex) { // Similarly, the level of each sub-dataset is normally // available in the file. Since this is not the case, I // hard-coded this into the example program. // Level 0 = { 0 }, Level 1 = { 1 }, // Level 2 = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } if (blockId == 0) { level = 0; dsindex = 0; } else if (blockId == 1) { level = 1; dsindex = 0; } else { level = 2; dsindex = blockId-2; } } char* vtkTestHierarchicalDataReader::GetBlockFileName(int blockId) { size_t len = strlen(this->FileName); size_t pos; // Search from the tail end of the filename until we // find a '.' indicating an extension, or we find a // path separator or the beginning of the string. for (pos=len-1; pos!=0; --pos) { if (this->FileName[pos] == '.') { break; } if (1==pos || this->FileName[pos] == '/') { // No extension on this->FileName; use the whole // thing as the base name pos= len; break; } } char* fname = new char[pos+1]; strncpy(fname, this->FileName, pos); fname[pos] = '\0'; // Here we load the 16 separate files (each containing // an image dataset -uniform rectilinear grid-) char* fstr = new char [strlen(fname) + strlen(".vti") + 10]; sprintf(fstr,"%s_%i.vti",fname, blockId); delete[] fname; return fstr; } int vtkTestHierarchicalDataReader::FillOutputPortInformation( int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataObject"); info->Set(vtkCompositeDataPipeline::COMPOSITE_DATA_TYPE_NAME(), "vtkHierarchicalBoxDataSet"); return 1; } void vtkTestHierarchicalDataReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "File Name: " << (this->FileName ? this->FileName : "(none)") << "\n"; } <|endoftext|>
<commit_before>// Ouzel by Elviss Strazdins #ifndef OUZEL_FORMATS_INI_HPP #define OUZEL_FORMATS_INI_HPP #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <iterator> #include <map> #include <stdexcept> #include <string> #include <vector> namespace ouzel::ini { class ParseError final: public std::logic_error { public: using std::logic_error::logic_error; }; class Section final { public: using Values = std::map<std::string, std::string>; Section() = default; explicit Section(const std::string& initName): name(initName) { } Values::iterator begin() noexcept { return values.begin(); } Values::iterator end() noexcept { return values.end(); } Values::const_iterator begin() const noexcept { return values.begin(); } Values::const_iterator end() const noexcept { return values.end(); } const std::string& getName() const noexcept { return name; } void setName(const std::string& newName) { name = newName; } const Values& getValues() const noexcept { return values; } bool hasValue(const std::string& key) const { return values.find(key) != values.end(); } std::string& operator[](const std::string& key) { return values[key]; } std::string operator[](const std::string& key) const { if (const auto valueIterator = values.find(key); valueIterator != values.end()) return valueIterator->second; return std::string(); } const std::string& getValue(const std::string& key, const std::string& defaultValue = {}) const { if (const auto valueIterator = values.find(key); valueIterator != values.end()) return valueIterator->second; return defaultValue; } void setValue(const std::string& key, const std::string& value) { values[key] = value; } void deleteValue(const std::string& key) { if (const auto valueIterator = values.find(key); valueIterator != values.end()) values.erase(valueIterator); } std::size_t getSize() const noexcept { return values.size(); } private: std::string name; Values values; }; class Data final { public: using Sections = std::map<std::string, Section>; Data() = default; const Sections& getSections() const noexcept { return sections; } Sections::iterator begin() noexcept { return sections.begin(); } Sections::iterator end() noexcept { return sections.end(); } Sections::const_iterator begin() const noexcept { return sections.begin(); } Sections::const_iterator end() const noexcept { return sections.end(); } bool hasSection(const std::string& name) const { const auto sectionIterator = sections.find(name); return sectionIterator != sections.end(); } Section& operator[](const std::string& name) { return sections[name]; } Section operator[](const std::string& name) const { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; return Section(); } void eraseSection(const std::string& name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) sections.erase(sectionIterator); } std::size_t getSize() const noexcept { return sections.size(); } private: Sections sections; }; inline namespace detail { constexpr std::array<std::uint8_t, 3> utf8ByteOrderMark = {0xEF, 0xBB, 0xBF}; } template <class Iterator> Data parse(Iterator begin, Iterator end) { class Parser final { public: static Data parse(Iterator begin, Iterator end) { Data result; std::string section; for (auto iterator = hasByteOrderMark(begin, end) ? begin + 3 : begin; iterator != end;) { if (isWhitespace(static_cast<char>(*iterator)) || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') // line starts with a whitespace ++iterator; // skip the white space else if (static_cast<char>(*iterator) == '[') // section { ++iterator; // skip the left bracket bool parsedSection = false; for (;;) { if (iterator == end || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { if (!parsedSection) throw ParseError{"Unexpected end of section"}; ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon if (!parsedSection) throw ParseError{"Unexpected comment"}; while (iterator != end) { if (static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { ++iterator; // skip the newline break; } ++iterator; } break; } else if (static_cast<char>(*iterator) == ']') parsedSection = true; else if (static_cast<char>(*iterator) != ' ' && static_cast<char>(*iterator) != '\t') { if (parsedSection) throw ParseError{"Unexpected character after section"}; } if (!parsedSection) section.push_back(static_cast<char>(*iterator)); ++iterator; } trim(section); if (section.empty()) throw ParseError{"Invalid section name"}; result[section] = Section{}; } else if (static_cast<char>(*iterator) == ';') // comment { while (++iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } } } else // key, value pair { std::string key; std::string value; bool parsedKey = false; while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == '=') { if (!parsedKey) parsedKey = true; else throw ParseError{"Unexpected character"}; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } ++iterator; } break; } else { if (!parsedKey) key.push_back(static_cast<char>(*iterator)); else value.push_back(static_cast<char>(*iterator)); } ++iterator; } if (key.empty()) throw ParseError{"Invalid key name"}; trim(key); trim(value); result[section][key] = value; } } return result; } private: static bool hasByteOrderMark(Iterator begin, Iterator end) noexcept { for (const auto b : utf8ByteOrderMark) if (begin == end || static_cast<char>(*begin) != b) return false; else ++begin; return true; } static constexpr bool isWhitespace(const char c) noexcept { return c == ' ' || c == '\t'; } static std::string& leftTrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char c) noexcept {return !isWhitespace(c);})); return s; } static std::string& rightTrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](char c) noexcept {return !isWhitespace(c);}).base(), s.end()); return s; } static std::string& trim(std::string& s) { return leftTrim(rightTrim(s)); } }; return Parser::parse(begin, end); } inline Data parse(const char* data) { auto end = data; while (*end) ++end; return parse(data, end); } template <class T> Data parse(const T& data) { return parse(std::begin(data), std::end(data)); } inline std::string encode(const Data& data, bool byteOrderMark = false) { std::string result; if (byteOrderMark) result.assign(utf8ByteOrderMark.begin(), utf8ByteOrderMark.end()); for (const auto& [name, section] : data) { if (!name.empty()) { result.push_back('['); result.insert(result.end(), name.begin(), name.end()); result.push_back(']'); result.push_back('\n'); } for (const auto& [key, value] : section) { result.insert(result.end(), key.begin(), key.end()); result.push_back('='); result.insert(result.end(), value.begin(), value.end()); result.push_back('\n'); } } return result; } } #endif // OUZEL_FORMATS_INI_HPP <commit_msg>Pass string_view to ini functions<commit_after>// Ouzel by Elviss Strazdins #ifndef OUZEL_FORMATS_INI_HPP #define OUZEL_FORMATS_INI_HPP #include <algorithm> #include <array> #include <cstdint> #include <functional> #include <map> #include <stdexcept> #include <string> #include <string_view> namespace ouzel::ini { class ParseError final: public std::logic_error { public: using std::logic_error::logic_error; }; using Values = std::map<std::string, std::string, std::less<>>; class Section final { public: Section() = default; explicit Section(const std::string& initName): name(initName) { } auto begin() noexcept { return values.begin(); } auto end() noexcept { return values.end(); } auto begin() const noexcept { return values.begin(); } auto end() const noexcept { return values.end(); } const std::string& getName() const noexcept { return name; } void setName(const std::string& newName) { name = newName; } const Values& getValues() const noexcept { return values; } bool hasValue(const std::string_view key) const { return values.find(key) != values.end(); } std::string& operator[](const std::string_view key) { if (const auto valueIterator = values.find(key); valueIterator != values.end()) return valueIterator->second; else { const auto& [newIterator, success] = values.insert({std::string{key}, std::string{}}); (void)success; return newIterator->second; } } std::string operator[](const std::string_view key) const { if (const auto valueIterator = values.find(key); valueIterator != values.end()) return valueIterator->second; return std::string(); } const std::string& getValue(const std::string_view key, const std::string& defaultValue = {}) const { if (const auto valueIterator = values.find(key); valueIterator != values.end()) return valueIterator->second; return defaultValue; } void setValue(const std::string_view key, const std::string& value) { values.insert({std::string{key}, value}); } void deleteValue(const std::string_view key) { if (const auto valueIterator = values.find(key); valueIterator != values.end()) values.erase(valueIterator); } std::size_t getSize() const noexcept { return values.size(); } private: std::string name; Values values; }; class Data final { public: using Sections = std::map<std::string, Section, std::less<>>; Data() = default; const Sections& getSections() const noexcept { return sections; } auto begin() noexcept { return sections.begin(); } auto end() noexcept { return sections.end(); } auto begin() const noexcept { return sections.begin(); } auto end() const noexcept { return sections.end(); } bool hasSection(const std::string_view name) const { return sections.find(name) != sections.end(); } Section& operator[](const std::string_view name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; else { const auto& [newIterator, success] = sections.insert({std::string{name}, Section{}}); (void)success; return newIterator->second; } } Section operator[](const std::string_view name) const { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) return sectionIterator->second; return Section{}; } void eraseSection(const std::string_view name) { if (const auto sectionIterator = sections.find(name); sectionIterator != sections.end()) sections.erase(sectionIterator); } std::size_t getSize() const noexcept { return sections.size(); } private: Sections sections; }; inline namespace detail { constexpr std::array<std::uint8_t, 3> utf8ByteOrderMark = {0xEF, 0xBB, 0xBF}; } template <class Iterator> Data parse(Iterator begin, Iterator end) { class Parser final { public: static Data parse(Iterator begin, Iterator end) { Data result; std::string section; for (auto iterator = hasByteOrderMark(begin, end) ? begin + 3 : begin; iterator != end;) { if (isWhitespace(static_cast<char>(*iterator)) || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') // line starts with a whitespace ++iterator; // skip the white space else if (static_cast<char>(*iterator) == '[') // section { ++iterator; // skip the left bracket bool parsedSection = false; for (;;) { if (iterator == end || static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { if (!parsedSection) throw ParseError{"Unexpected end of section"}; ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon if (!parsedSection) throw ParseError{"Unexpected comment"}; while (iterator != end) { if (static_cast<char>(*iterator) == '\n' || static_cast<char>(*iterator) == '\r') { ++iterator; // skip the newline break; } ++iterator; } break; } else if (static_cast<char>(*iterator) == ']') parsedSection = true; else if (static_cast<char>(*iterator) != ' ' && static_cast<char>(*iterator) != '\t') { if (parsedSection) throw ParseError{"Unexpected character after section"}; } if (!parsedSection) section.push_back(static_cast<char>(*iterator)); ++iterator; } trim(section); if (section.empty()) throw ParseError{"Invalid section name"}; result[section] = Section{}; } else if (static_cast<char>(*iterator) == ';') // comment { while (++iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } } } else // key, value pair { std::string key; std::string value; bool parsedKey = false; while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } else if (static_cast<char>(*iterator) == '=') { if (!parsedKey) parsedKey = true; else throw ParseError{"Unexpected character"}; } else if (static_cast<char>(*iterator) == ';') { ++iterator; // skip the semicolon while (iterator != end) { if (static_cast<char>(*iterator) == '\r' || static_cast<char>(*iterator) == '\n') { ++iterator; // skip the newline break; } ++iterator; } break; } else { if (!parsedKey) key.push_back(static_cast<char>(*iterator)); else value.push_back(static_cast<char>(*iterator)); } ++iterator; } if (key.empty()) throw ParseError{"Invalid key name"}; trim(key); trim(value); result[section][key] = value; } } return result; } private: static bool hasByteOrderMark(Iterator begin, Iterator end) noexcept { for (const auto b : utf8ByteOrderMark) if (begin == end || static_cast<std::uint8_t>(*begin) != b) return false; else ++begin; return true; } static constexpr bool isWhitespace(const char c) noexcept { return c == ' ' || c == '\t'; } static std::string& leftTrim(std::string& s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](char c) noexcept {return !isWhitespace(c);})); return s; } static std::string& rightTrim(std::string& s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](char c) noexcept {return !isWhitespace(c);}).base(), s.end()); return s; } static std::string& trim(std::string& s) { return leftTrim(rightTrim(s)); } }; return Parser::parse(begin, end); } inline Data parse(const char* data) { auto end = data; while (*end) ++end; return parse(data, end); } template <class T> Data parse(const T& data) { return parse(std::begin(data), std::end(data)); } inline std::string encode(const Data& data, bool byteOrderMark = false) { std::string result; if (byteOrderMark) result.assign(utf8ByteOrderMark.begin(), utf8ByteOrderMark.end()); for (const auto& [name, section] : data) { if (!name.empty()) { result.push_back('['); result.insert(result.end(), name.begin(), name.end()); result.push_back(']'); result.push_back('\n'); } for (const auto& [key, value] : section) { result.insert(result.end(), key.begin(), key.end()); result.push_back('='); result.insert(result.end(), value.begin(), value.end()); result.push_back('\n'); } } return result; } } #endif // OUZEL_FORMATS_INI_HPP <|endoftext|>
<commit_before>// // Copyright (c) 2019, University of Edinburgh // 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 nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <exotica_core/tools/box_qp.h> #include <exotica_core/tools/box_qp_old.h> #include <exotica_ddp_solver/control_limited_ddp_solver.h> REGISTER_MOTIONSOLVER_TYPE("ControlLimitedDDPSolver", exotica::ControlLimitedDDPSolver) namespace exotica { void ControlLimitedDDPSolver::Instantiate(const ControlLimitedDDPSolverInitializer& init) { parameters_ = init; base_parameters_ = AbstractDDPSolverInitializer(ControlLimitedDDPSolverInitializer(parameters_)); } void ControlLimitedDDPSolver::BackwardPass() { const Eigen::MatrixXd& control_limits = dynamics_solver_->get_control_limits(); Vx_ = prob_->GetStateCostJacobian(T_ - 1); Vxx_ = prob_->GetStateCostHessian(T_ - 1); // concatenation axis for tensor products // See https://eigen.tuxfamily.org/dox-devel/unsupported/eigen_tensors.html#title14 Eigen::array<Eigen::IndexPair<int>, 1> dims = {Eigen::IndexPair<int>(1, 0)}; for (int t = T_ - 2; t >= 0; t--) { Eigen::VectorXd x = prob_->get_X(t), u = prob_->get_U(t); dynamics_solver_->ComputeDerivatives(x, u); Eigen::MatrixXd fx = dynamics_solver_->get_fx() * dynamics_solver_->get_dt() + Eigen::MatrixXd::Identity(dynamics_solver_->get_num_state_derivative(), dynamics_solver_->get_num_state_derivative()); Eigen::MatrixXd fu = dynamics_solver_->get_fu() * dynamics_solver_->get_dt(); Qx_ = dt_ * prob_->GetStateCostJacobian(t) + fx.transpose() * Vx_; // lx + fx @ Vx_ Qu_ = dt_ * prob_->GetControlCostJacobian(t) + fu.transpose() * Vx_; if (parameters_.UseSecondOrderDynamics) { // clang-format off Eigen::Tensor<double, 1> Vx_tensor = Eigen::TensorMap<Eigen::Tensor<double, 1>>(Vx_.data(), NDX_); Qxx_ = dt_ * prob_->GetStateCostHessian(t) + fx.transpose() * Vxx_ * fx + Eigen::TensorToMatrix( (Eigen::Tensor<double, 2>)dynamics_solver_->fxx(x, u).contract(Vx_tensor, dims), NDX_, NDX_ ) * dt_; Quu_ = dt_ * prob_->GetControlCostHessian() + fu.transpose() * Vxx_ * fu + Eigen::TensorToMatrix( (Eigen::Tensor<double, 2>)dynamics_solver_->fuu(x, u).contract(Vx_tensor, dims), NU_, NU_ ) * dt_; Qux_ = dt_ * prob_->GetStateControlCostHessian() + fu.transpose() * Vxx_ * fx + Eigen::TensorToMatrix((Eigen::Tensor<double, 2>)dynamics_solver_->fxu(x, u).contract(Vx_tensor, dims), NU_, NDX_ ) * dt_; // clang-format on } else { Qxx_ = dt_ * prob_->GetStateCostHessian(t) + fx.transpose() * Vxx_ * fx; Quu_ = dt_ * prob_->GetControlCostHessian() + fu.transpose() * Vxx_ * fu; // NOTE: Qux = Qxu for all robotics systems I have seen // this might need to be changed later on Qux_ = dt_ * prob_->GetStateControlCostHessian() + fu.transpose() * Vxx_ * fx; } Eigen::VectorXd low_limit = control_limits.col(0) - u, high_limit = control_limits.col(1) - u; BoxQPSolution boxqp_sol = ExoticaBoxQP(Quu_, Qu_, low_limit, high_limit, u, 0.1, 100, 1e-5, lambda_); Quu_inv_.setZero(); for (unsigned int i = 0; i < boxqp_sol.free_idx.size(); ++i) for (unsigned int j = 0; j < boxqp_sol.free_idx.size(); ++j) Quu_inv_(boxqp_sol.free_idx[i], boxqp_sol.free_idx[j]) = boxqp_sol.Hff_inv(i, j); // Compute controls K_gains_[t] = -Quu_inv_ * Qux_; k_gains_[t] = boxqp_sol.x; for (unsigned int j = 0; j < boxqp_sol.clamped_idx.size(); ++j) K_gains_[t](boxqp_sol.clamped_idx[j]) = 0; Vx_ = Qx_ - K_gains_[t].transpose() * Quu_ * k_gains_[t]; Vxx_ = Qxx_ - K_gains_[t].transpose() * Quu_ * K_gains_[t]; } } } // namespace exotica <commit_msg>[exotica_ddp_solver] ControlLimitedDDPSolver: Add state regularization<commit_after>// // Copyright (c) 2019, University of Edinburgh // 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 nor the names of its contributors may be used to // endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // #include <exotica_core/tools/box_qp.h> #include <exotica_core/tools/box_qp_old.h> #include <exotica_ddp_solver/control_limited_ddp_solver.h> REGISTER_MOTIONSOLVER_TYPE("ControlLimitedDDPSolver", exotica::ControlLimitedDDPSolver) namespace exotica { void ControlLimitedDDPSolver::Instantiate(const ControlLimitedDDPSolverInitializer& init) { parameters_ = init; base_parameters_ = AbstractDDPSolverInitializer(ControlLimitedDDPSolverInitializer(parameters_)); } void ControlLimitedDDPSolver::BackwardPass() { const Eigen::MatrixXd& control_limits = dynamics_solver_->get_control_limits(); Vx_ = prob_->GetStateCostJacobian(T_ - 1); Vxx_ = prob_->GetStateCostHessian(T_ - 1); // concatenation axis for tensor products // See https://eigen.tuxfamily.org/dox-devel/unsupported/eigen_tensors.html#title14 Eigen::array<Eigen::IndexPair<int>, 1> dims = {Eigen::IndexPair<int>(1, 0)}; for (int t = T_ - 2; t >= 0; t--) { Eigen::VectorXd x = prob_->get_X(t), u = prob_->get_U(t); dynamics_solver_->ComputeDerivatives(x, u); Eigen::MatrixXd fx = dynamics_solver_->get_fx() * dynamics_solver_->get_dt() + Eigen::MatrixXd::Identity(dynamics_solver_->get_num_state_derivative(), dynamics_solver_->get_num_state_derivative()); Eigen::MatrixXd fu = dynamics_solver_->get_fu() * dynamics_solver_->get_dt(); Qx_ = dt_ * prob_->GetStateCostJacobian(t) + fx.transpose() * Vx_; // lx + fx @ Vx_ Qu_ = dt_ * prob_->GetControlCostJacobian(t) + fu.transpose() * Vx_; // State regularization Vxx_.diagonal().array() += lambda_; if (parameters_.UseSecondOrderDynamics) { // clang-format off Eigen::Tensor<double, 1> Vx_tensor = Eigen::TensorMap<Eigen::Tensor<double, 1>>(Vx_.data(), NDX_); Qxx_ = dt_ * prob_->GetStateCostHessian(t) + fx.transpose() * Vxx_ * fx + Eigen::TensorToMatrix( (Eigen::Tensor<double, 2>)dynamics_solver_->fxx(x, u).contract(Vx_tensor, dims), NDX_, NDX_ ) * dt_; Quu_ = dt_ * prob_->GetControlCostHessian() + fu.transpose() * Vxx_ * fu + Eigen::TensorToMatrix( (Eigen::Tensor<double, 2>)dynamics_solver_->fuu(x, u).contract(Vx_tensor, dims), NU_, NU_ ) * dt_; Qux_ = dt_ * prob_->GetStateControlCostHessian() + fu.transpose() * Vxx_ * fx + Eigen::TensorToMatrix((Eigen::Tensor<double, 2>)dynamics_solver_->fxu(x, u).contract(Vx_tensor, dims), NU_, NDX_ ) * dt_; // clang-format on } else { Qxx_ = dt_ * prob_->GetStateCostHessian(t) + fx.transpose() * Vxx_ * fx; Quu_ = dt_ * prob_->GetControlCostHessian() + fu.transpose() * Vxx_ * fu; // NOTE: Qux = Qxu for all robotics systems I have seen // this might need to be changed later on Qux_ = dt_ * prob_->GetStateControlCostHessian() + fu.transpose() * Vxx_ * fx; } Eigen::VectorXd low_limit = control_limits.col(0) - u, high_limit = control_limits.col(1) - u; // BoxQPSolution boxqp_sol = BoxQP(Quu_, Qu_, low_limit, high_limit, u, 0.1, 100, 1e-5, 1e-12); // BoxQPSolution boxqp_sol = ExoticaBoxQP(Quu_, Qu_, low_limit, high_limit, u, 0.1, 100, 1e-5, 1e-12); // Timer t2; // Quu_.diagonal().array() += lambda_; BoxQPSolution boxqp_sol = ExoticaBoxQP(Quu_, Qu_, low_limit, high_limit, u, 0.1, 100, 1e-5, lambda_); // double t2_taken = t2.GetDuration(); // Timer t1; // BoxQPSolution boxqp_sol_new = BoxQP(Quu_, Qu_, low_limit, high_limit, u, 0.1, 100, 1e-5, parameters_.RegularizationRate); // double t1_taken = t1.GetDuration(); // HIGHLIGHT("New=" << t1_taken << ", old=" << t2_taken); Quu_inv_.setZero(); for (unsigned int i = 0; i < boxqp_sol.free_idx.size(); ++i) for (unsigned int j = 0; j < boxqp_sol.free_idx.size(); ++j) Quu_inv_(boxqp_sol.free_idx[i], boxqp_sol.free_idx[j]) = boxqp_sol.Hff_inv(i, j); // Compute controls K_gains_[t] = -Quu_inv_ * Qux_; k_gains_[t] = boxqp_sol.x; for (unsigned int j = 0; j < boxqp_sol.clamped_idx.size(); ++j) K_gains_[t](boxqp_sol.clamped_idx[j]) = 0; Vx_ = Qx_ - K_gains_[t].transpose() * Quu_ * k_gains_[t]; Vxx_ = Qxx_ - K_gains_[t].transpose() * Quu_ * K_gains_[t]; } } } // namespace exotica <|endoftext|>
<commit_before>/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <sstream> #include <round/core/Registry.h> using namespace std; using namespace Round; BOOST_AUTO_TEST_SUITE(registry) BOOST_AUTO_TEST_CASE(RQLRregistryBasicMethodTest) { std::string val; time_t ts; std::stringstream ss; std::string sval; time_t tval; Registry reg; BOOST_CHECK_EQUAL(reg.getKey(&sval), false); BOOST_CHECK_EQUAL(reg.getValue(&sval), false); BOOST_CHECK_EQUAL(reg.getTimestamp(tval), false); BOOST_CHECK_EQUAL(reg.getLogicalTimestamp(tval), false); time(&ts); ss << "key" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg.setKey(val), true); BOOST_CHECK_EQUAL(reg.getKey(&sval), true); BOOST_CHECK_EQUAL(val.compare(sval), 0); time(&ts); ss << "val" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg.setValue(val), true); BOOST_CHECK_EQUAL(reg.getValue(&sval), true); BOOST_CHECK_EQUAL(val.compare(sval), 0); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg.setTimestamp(ts), true); BOOST_CHECK_EQUAL(reg.getTimestamp(tval), true); BOOST_CHECK_EQUAL(tval, ts); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg.setLogicalTimestamp(ts), true); BOOST_CHECK_EQUAL(reg.getLogicalTimestamp(tval), true); BOOST_CHECK_EQUAL(tval, ts); } BOOST_AUTO_TEST_CASE(RQLRregistryEqualsTest) { std::string val; time_t ts; std::stringstream ss; std::string sval; Registry reg01; time(&ts); ss << "key" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg01.setKey(val), true); time(&ts); ss << "val" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg01.setValue(val), true); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg01.setTimestamp(ts), true); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg01.setLogicalTimestamp(ts), true); Registry reg02; BOOST_CHECK_EQUAL(reg01.equals(reg02), false); BOOST_CHECK_EQUAL(reg01.equalsWithTimestamp(reg02), false); reg02 = reg01; BOOST_CHECK_EQUAL(reg01.equals(reg02), true); BOOST_CHECK_EQUAL(reg01.equalsWithTimestamp(reg02), true); } BOOST_AUTO_TEST_CASE(RQLRregistryMapMethodTest) { RegistryMap regMap; BOOST_CHECK_EQUAL(regMap.size(), 0); for (int n=0; n<10; n++) { std::stringstream ss; time_t ts; time(&ts); ss << ts; std::string key = "key" + ss.str(); std::string val = "val" + ss.str(); Registry inReg; BOOST_CHECK_EQUAL(inReg.setKey(key), true); BOOST_CHECK_EQUAL(inReg.setValue(val), true); BOOST_CHECK_EQUAL(inReg.setTimestamp(ts), true); BOOST_CHECK_EQUAL(inReg.setLogicalTimestamp(ts), true); BOOST_CHECK_EQUAL(regMap.size(), n); BOOST_CHECK_EQUAL(regMap.set(inReg), true); BOOST_CHECK_EQUAL(regMap.size(), (n+1)); Registry outReg; BOOST_CHECK_EQUAL(inReg.equals(inReg), true); BOOST_CHECK_EQUAL(inReg.equalsWithTimestamp(inReg), true); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>* Updated tests for Registry.<commit_after>/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <sstream> #include <round/core/Registry.h> using namespace std; using namespace Round; BOOST_AUTO_TEST_SUITE(registry) BOOST_AUTO_TEST_CASE(RQLRregistryBasicMethodTest) { std::string val; time_t ts; std::stringstream ss; std::string sval; time_t tval; Registry reg; BOOST_CHECK_EQUAL(reg.getKey(&sval), false); BOOST_CHECK_EQUAL(reg.getValue(&sval), false); BOOST_CHECK_EQUAL(reg.getTimestamp(tval), false); BOOST_CHECK_EQUAL(reg.getLogicalTimestamp(tval), false); time(&ts); ss << "key" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg.setKey(val), true); BOOST_CHECK_EQUAL(reg.getKey(&sval), true); BOOST_CHECK_EQUAL(val.compare(sval), 0); time(&ts); ss << "val" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg.setValue(val), true); BOOST_CHECK_EQUAL(reg.getValue(&sval), true); BOOST_CHECK_EQUAL(val.compare(sval), 0); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg.setTimestamp(ts), true); BOOST_CHECK_EQUAL(reg.getTimestamp(tval), true); BOOST_CHECK_EQUAL(tval, ts); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg.setLogicalTimestamp(ts), true); BOOST_CHECK_EQUAL(reg.getLogicalTimestamp(tval), true); BOOST_CHECK_EQUAL(tval, ts); } BOOST_AUTO_TEST_CASE(RQLRregistryEqualsTest) { std::string val; time_t ts; std::stringstream ss; std::string sval; Registry reg01; time(&ts); ss << "key" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg01.setKey(val), true); time(&ts); ss << "val" << ts; val = ss.str(); BOOST_CHECK_EQUAL(reg01.setValue(val), true); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg01.setTimestamp(ts), true); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(reg01.setLogicalTimestamp(ts), true); Registry reg02; BOOST_CHECK_EQUAL(reg01.equals(reg02), false); BOOST_CHECK_EQUAL(reg01.equalsWithTimestamp(reg02), false); reg02 = reg01; BOOST_CHECK_EQUAL(reg01.equals(reg02), true); BOOST_CHECK_EQUAL(reg01.equalsWithTimestamp(reg02), true); } BOOST_AUTO_TEST_CASE(RQLRregistryMapMethodTest) { RegistryMap regMap; BOOST_CHECK_EQUAL(regMap.size(), 0); for (int n=0; n<10; n++) { std::stringstream ss; time_t ts; Registry inReg; time(&ts); ts += rand(); ss << ts; std::string key = "key" + ss.str(); std::string val = "val" + ss.str(); BOOST_CHECK_EQUAL(inReg.setKey(key), true); BOOST_CHECK_EQUAL(inReg.setValue(val), true); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(inReg.setTimestamp(ts), true); time(&ts); ts += rand(); BOOST_CHECK_EQUAL(inReg.setLogicalTimestamp(ts), true); BOOST_CHECK_EQUAL(regMap.size(), n); BOOST_CHECK_EQUAL(regMap.set(inReg), true); BOOST_CHECK_EQUAL(regMap.size(), (n+1)); Registry outReg; BOOST_CHECK_EQUAL(inReg.equals(inReg), true); BOOST_CHECK_EQUAL(inReg.equalsWithTimestamp(inReg), true); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/// Common commands for all bitstreams /// /// (c) Koheron #ifndef __DRIVERS_COMMON_HPP__ #define __DRIVERS_COMMON_HPP__ #include <array> #include <drivers/dev_mem.hpp> #include <drivers/wr_register.hpp> #include <drivers/addresses.hpp> #include <drivers/init.hpp> class Common { public: Common(Klib::DevMem& dev_mem_); ~Common(); int Open(); #pragma tcp-server exclude void Close(); std::array<uint32_t, BITSTREAM_ID_SIZE> get_bitstream_id(); uint64_t get_dna(); void set_led(uint32_t value); uint32_t get_led(); void ip_on_leds(); void load_settings() { Init init(dev_mem); init.load_settings(); }; enum Status { CLOSED, OPENED, FAILED }; #pragma tcp-server is_failed bool IsFailed() const {return status == FAILED;} private: Klib::DevMem& dev_mem; int status; std::array<uint32_t, BITSTREAM_ID_SIZE> bitstream_id; // Memory maps IDs Klib::MemMapID config_map; Klib::MemMapID status_map; }; #endif // __DRIVERS_COMMON_HPP__<commit_msg>add ip_on_leds to init<commit_after>/// Common commands for all bitstreams /// /// (c) Koheron #ifndef __DRIVERS_COMMON_HPP__ #define __DRIVERS_COMMON_HPP__ #include <array> #include <drivers/dev_mem.hpp> #include <drivers/wr_register.hpp> #include <drivers/addresses.hpp> #include <drivers/init.hpp> class Common { public: Common(Klib::DevMem& dev_mem_); ~Common(); int Open(); #pragma tcp-server exclude void Close(); std::array<uint32_t, BITSTREAM_ID_SIZE> get_bitstream_id(); uint64_t get_dna(); void set_led(uint32_t value); uint32_t get_led(); void ip_on_leds(); void init() { ip_on_leds(); Init init(dev_mem); init.load_settings(); }; enum Status { CLOSED, OPENED, FAILED }; #pragma tcp-server is_failed bool IsFailed() const {return status == FAILED;} private: Klib::DevMem& dev_mem; int status; std::array<uint32_t, BITSTREAM_ID_SIZE> bitstream_id; // Memory maps IDs Klib::MemMapID config_map; Klib::MemMapID status_map; }; #endif // __DRIVERS_COMMON_HPP__<|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_DISPATCHSEMAPHORE_HPP #define OUZEL_GRAPHICS_DISPATCHSEMAPHORE_HPP #include <stdexcept> #include <dispatch/dispatch.h> namespace ouzel::graphics::metal { class DispatchSemaphore final { public: explicit DispatchSemaphore(long value): semaphore{dispatch_semaphore_create(value)} { if (!semaphore) throw std::runtime_error("Failed to create dispatch semaphore"); } ~DispatchSemaphore() { if (semaphore) dispatch_release(semaphore); } DispatchSemaphore(DispatchSemaphore&& other) noexcept: semaphore{other.semaphore} { other.semaphore = nullptr; } DispatchSemaphore(const DispatchSemaphore& other): semaphore{other.semaphore} { if (semaphore) dispatch_retain(semaphore); } DispatchSemaphore& operator=(DispatchSemaphore&& other) noexcept { if (this == &other) return *this; semaphore = other.semaphore; other.semaphore = nullptr; return *this; } DispatchSemaphore& operator=(const DispatchSemaphore& other) { if (this == &other) return *this; if (semaphore) dispatch_release(semaphore); semaphore = other.semaphore; if (semaphore) dispatch_retain(semaphore); return *this; } operator dispatch_semaphore_t() const noexcept { return semaphore; } private: dispatch_semaphore_t semaphore = nullptr; }; } #endif // OUZEL_GRAPHICS_DISPATCHSEMAPHORE_HPP <commit_msg>Fix memory leak in the move assignment operator of DispatchSemaphore<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #ifndef OUZEL_GRAPHICS_DISPATCHSEMAPHORE_HPP #define OUZEL_GRAPHICS_DISPATCHSEMAPHORE_HPP #include <stdexcept> #include <dispatch/dispatch.h> namespace ouzel::graphics::metal { class DispatchSemaphore final { public: explicit DispatchSemaphore(long value): semaphore{dispatch_semaphore_create(value)} { if (!semaphore) throw std::runtime_error("Failed to create dispatch semaphore"); } ~DispatchSemaphore() { if (semaphore) dispatch_release(semaphore); } DispatchSemaphore(DispatchSemaphore&& other) noexcept: semaphore{other.semaphore} { other.semaphore = nullptr; } DispatchSemaphore(const DispatchSemaphore& other): semaphore{other.semaphore} { if (semaphore) dispatch_retain(semaphore); } DispatchSemaphore& operator=(DispatchSemaphore&& other) noexcept { if (this == &other) return *this; if (semaphore) dispatch_release(semaphore); semaphore = other.semaphore; other.semaphore = nullptr; return *this; } DispatchSemaphore& operator=(const DispatchSemaphore& other) { if (this == &other) return *this; if (semaphore) dispatch_release(semaphore); semaphore = other.semaphore; if (semaphore) dispatch_retain(semaphore); return *this; } operator dispatch_semaphore_t() const noexcept { return semaphore; } private: dispatch_semaphore_t semaphore = nullptr; }; } #endif // OUZEL_GRAPHICS_DISPATCHSEMAPHORE_HPP <|endoftext|>
<commit_before>#include "WavSource.h" #define DR_WAV_IMPLEMENTATION #include <HgSound/dr_wav.h> #include <include/ThreadPool.h> namespace HgSound { ThreadPool ioThreads(2); BufferedWavSource::~BufferedWavSource() { delete[] m_samples; } StreamingWavSource::~StreamingWavSource() { } SamplePacket BufferedWavSource::getNextSamples(IAudioSourceState& state) const { SamplePacket p; p.sampleCount = m_count; p.sampleBytes = 4; p.audioSamples = (char*)m_samples; p.hasMorePackets = false; return p; } void BufferedWavSource::initializeState(std::unique_ptr<IAudioSourceState>& state) const { state.reset(); //buffered sources don't have a state } void StreamingWavSource::initializeState(std::unique_ptr<IAudioSourceState>& state) const { auto tmp = std::make_unique<StreamingWavSource::State>(); tmp->open(m_path.c_str()); state = std::move(tmp); } SamplePacket Decode(StreamingWavSource::State* state) { SamplePacket p; drwav* wav = state->get_drwav(); drwav_uint64 framesToRead = wav->sampleRate / 10; // 1/10th of a second auto samplesCount = framesToRead * wav->channels; auto buffer = state->getBackBuffer(); size_t framesDecoded = drwav_read_pcm_frames_f32(wav, framesToRead, buffer); state->swapBuffers(); p.sampleBytes = 4; p.sampleCount = framesDecoded * wav->channels; p.audioSamples = (char*)buffer; p.hasMorePackets = !(framesDecoded < framesToRead); return p; } SamplePacket StreamingWavSource::getNextSamples(IAudioSourceState& s) const { auto state = reinterpret_cast<StreamingWavSource::State*>(&s); SamplePacket r; //if the future is not ready replay the previous samples if (state->nextToPlay.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { return state->currentPlaying; } r = state->nextToPlay.get(); state->currentPlaying = r; state->nextToPlay = ioThreads.enqueue([state] { return Decode(state); }); return r; } StreamingWavSource::State::~State() { drwav_uninit(&m_wav); if (m_frontBuffer) delete[] m_frontBuffer; if (m_backBuffer) delete[] m_backBuffer; } void StreamingWavSource::State::open(const char* path) { auto wav = get_drwav(); if (!drwav_init_file(wav, path, nullptr)) { fprintf(stderr, "Could not open wave file \"%s\"\n", path); return; } drwav_uint64 framesToRead = wav->sampleRate / 10; // 1/10th of a second auto samplesCount = framesToRead * wav->channels; m_frontBuffer = new float[samplesCount](); m_backBuffer = new float[samplesCount](); auto state = this; nextToPlay = ioThreads.enqueue([state] { return Decode(state); }); nextToPlay.wait(); } }<commit_msg>wait for thread to return before destroying<commit_after>#include "WavSource.h" #define DR_WAV_IMPLEMENTATION #include <HgSound/dr_wav.h> #include <include/ThreadPool.h> namespace HgSound { ThreadPool ioThreads(2); BufferedWavSource::~BufferedWavSource() { delete[] m_samples; } StreamingWavSource::~StreamingWavSource() { } SamplePacket BufferedWavSource::getNextSamples(IAudioSourceState& state) const { SamplePacket p; p.sampleCount = m_count; p.sampleBytes = 4; p.audioSamples = (char*)m_samples; p.hasMorePackets = false; return p; } void BufferedWavSource::initializeState(std::unique_ptr<IAudioSourceState>& state) const { state.reset(); //buffered sources don't have a state } void StreamingWavSource::initializeState(std::unique_ptr<IAudioSourceState>& state) const { auto tmp = std::make_unique<StreamingWavSource::State>(); tmp->open(m_path.c_str()); state = std::move(tmp); } SamplePacket Decode(StreamingWavSource::State* state) { SamplePacket p; drwav* wav = state->get_drwav(); drwav_uint64 framesToRead = wav->sampleRate / 10; // 1/10th of a second auto samplesCount = framesToRead * wav->channels; auto buffer = state->getBackBuffer(); size_t framesDecoded = drwav_read_pcm_frames_f32(wav, framesToRead, buffer); state->swapBuffers(); p.sampleBytes = 4; p.sampleCount = framesDecoded * wav->channels; p.audioSamples = (char*)buffer; p.hasMorePackets = !(framesDecoded < framesToRead); return p; } SamplePacket StreamingWavSource::getNextSamples(IAudioSourceState& s) const { auto state = reinterpret_cast<StreamingWavSource::State*>(&s); SamplePacket r; //if the future is not ready replay the previous samples if (state->nextToPlay.wait_for(std::chrono::seconds(0)) != std::future_status::ready) { return state->currentPlaying; } r = state->nextToPlay.get(); state->currentPlaying = r; state->nextToPlay = ioThreads.enqueue([state] { return Decode(state); }); return r; } StreamingWavSource::State::~State() { if (nextToPlay.valid()) { //if the future is valid, then wait for the IO thread to return. keep state valid. nextToPlay.wait(); } drwav_uninit(&m_wav); if (m_frontBuffer) delete[] m_frontBuffer; if (m_backBuffer) delete[] m_backBuffer; } void StreamingWavSource::State::open(const char* path) { auto wav = get_drwav(); if (!drwav_init_file(wav, path, nullptr)) { fprintf(stderr, "Could not open wave file \"%s\"\n", path); return; } drwav_uint64 framesToRead = wav->sampleRate / 10; // 1/10th of a second auto samplesCount = framesToRead * wav->channels; m_frontBuffer = new float[samplesCount](); m_backBuffer = new float[samplesCount](); auto state = this; nextToPlay = ioThreads.enqueue([state] { return Decode(state); }); nextToPlay.wait(); } }<|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } const Frame* Planning::GetFrame() const { return frame_.get(); } const hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); } bool Planning::InitFrame(const uint32_t sequence_num) { frame_.reset(new Frame(sequence_num)); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return false; } common::TrajectoryPoint point; frame_->SetVehicleInitPose(VehicleState::instance()->pose()); frame_->SetRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction"; } if (!frame_->Init()) { AERROR << "failed to init frame"; return false; } frame_->RecordInputDebug(); return true; } Status Planning::Init() { pnc_map_.reset(new hdmap::PncMap(FLAGS_map_filename)); Frame::SetMap(pnc_map_.get()); if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) { AERROR << "failed to load planning config file " << FLAGS_planning_config_file; return Status( ErrorCode::PLANNING_ERROR, "failed to load planning config file: " + FLAGS_planning_config_file); } if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } // TODO(all) temporarily use the offline routing data. if (!AdapterManager::GetRoutingResponse()->HasReceived()) { if (!AdapterManager::GetRoutingResponse()->FeedFile( FLAGS_offline_routing_file)) { auto error_msg = common::util::StrCat( "Failed to load offline routing file ", FLAGS_offline_routing_file); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } else { AWARN << "Using offline routing file " << FLAGS_offline_routing_file; } } if (AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } Status Planning::Start() { static ros::Rate loop_rate(FLAGS_planning_loop_rate); while (ros::ok()) { RunOnce(); FrameHistory::instance()->Add(frame_->sequence_num(), std::move(frame_)); ros::spinOnce(); loop_rate.sleep(); } return Status::OK(); } void Planning::RunOnce() { AdapterManager::Observe(); if (AdapterManager::GetLocalization()->Empty()) { AERROR << "Localization is not available; skip the planning cycle"; return; } if (AdapterManager::GetChassis()->Empty()) { AERROR << "Chassis is not available; skip the planning cycle"; return; } if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "RoutingResponse is not available; skip the planning cycle"; return; } // FIXME(all): enable prediction check when perception and prediction is // ready. // if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { // AERROR << "Prediction is not available; skip the planning cycle"; // return; // } AINFO << "Start planning ..."; const double start_timestamp = apollo::common::time::ToSecond(Clock::Now()); // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::VehicleState::instance()->Update(localization, chassis); const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; if (!InitFrame(frame_num)) { AERROR << "Init frame failed"; return; } bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; bool res_planning = Plan(is_auto_mode, start_timestamp, planning_cycle_time); const double end_timestamp = apollo::common::time::ToSecond(Clock::Now()); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; auto trajectory_pb = frame_->MutableADCTrajectory(); trajectory_pb->mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb->latency_stats().DebugString(); if (res_planning) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(start_timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); ADEBUG << "Planning succeeded:" << trajectory_pb->header().DebugString(); } else { AERROR << "Planning failed"; } } void Planning::Stop() {} bool Planning::Plan(const bool is_on_auto_mode, const double current_time_stamp, const double planning_cycle_time) { const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_on_auto_mode, current_time_stamp, planning_cycle_time, last_publishable_trajectory_); frame_->SetPlanningStartPoint(stitching_trajectory.back()); auto trajectory_pb = frame_->MutableADCTrajectory(); if (FLAGS_enable_record_debug) { trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_init_point() ->CopyFrom(stitching_trajectory.back()); } frame_->AlignPredictionTime(current_time_stamp); PublishableTrajectory publishable_trajectory; auto status = planner_->Plan(stitching_trajectory.back(), frame_.get(), &publishable_trajectory); if (status != Status::OK()) { AERROR << "planner failed to make a driving plan"; last_publishable_trajectory_.Clear(); return false; } publishable_trajectory.PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); publishable_trajectory.set_header_time(current_time_stamp); publishable_trajectory.PopulateTrajectoryProtobuf(trajectory_pb); trajectory_pb->set_is_replan(stitching_trajectory.size() == 1); // update last publishable trajectory; last_publishable_trajectory_ = std::move(publishable_trajectory); return true; } } // namespace planning } // namespace apollo <commit_msg>planning: fix planning crash by mis-using move.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } const Frame* Planning::GetFrame() const { return frame_.get(); } const hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); } bool Planning::InitFrame(const uint32_t sequence_num) { frame_.reset(new Frame(sequence_num)); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return false; } common::TrajectoryPoint point; frame_->SetVehicleInitPose(VehicleState::instance()->pose()); frame_->SetRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction"; } if (!frame_->Init()) { AERROR << "failed to init frame"; return false; } frame_->RecordInputDebug(); return true; } Status Planning::Init() { pnc_map_.reset(new hdmap::PncMap(FLAGS_map_filename)); Frame::SetMap(pnc_map_.get()); if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) { AERROR << "failed to load planning config file " << FLAGS_planning_config_file; return Status( ErrorCode::PLANNING_ERROR, "failed to load planning config file: " + FLAGS_planning_config_file); } if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } // TODO(all) temporarily use the offline routing data. if (!AdapterManager::GetRoutingResponse()->HasReceived()) { if (!AdapterManager::GetRoutingResponse()->FeedFile( FLAGS_offline_routing_file)) { auto error_msg = common::util::StrCat( "Failed to load offline routing file ", FLAGS_offline_routing_file); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } else { AWARN << "Using offline routing file " << FLAGS_offline_routing_file; } } if (AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } Status Planning::Start() { static ros::Rate loop_rate(FLAGS_planning_loop_rate); while (ros::ok()) { RunOnce(); if (frame_) { auto seq_num = frame_->sequence_num(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } ros::spinOnce(); loop_rate.sleep(); } return Status::OK(); } void Planning::RunOnce() { AdapterManager::Observe(); if (AdapterManager::GetLocalization()->Empty()) { AERROR << "Localization is not available; skip the planning cycle"; return; } if (AdapterManager::GetChassis()->Empty()) { AERROR << "Chassis is not available; skip the planning cycle"; return; } if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "RoutingResponse is not available; skip the planning cycle"; return; } // FIXME(all): enable prediction check when perception and prediction is // ready. // if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { // AERROR << "Prediction is not available; skip the planning cycle"; // return; // } AINFO << "Start planning ..."; const double start_timestamp = apollo::common::time::ToSecond(Clock::Now()); // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::VehicleState::instance()->Update(localization, chassis); const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; if (!InitFrame(frame_num)) { AERROR << "Init frame failed"; return; } bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; bool res_planning = Plan(is_auto_mode, start_timestamp, planning_cycle_time); const double end_timestamp = apollo::common::time::ToSecond(Clock::Now()); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; auto trajectory_pb = frame_->MutableADCTrajectory(); trajectory_pb->mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb->latency_stats().DebugString(); if (res_planning) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(start_timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); ADEBUG << "Planning succeeded:" << trajectory_pb->header().DebugString(); } else { AERROR << "Planning failed"; } } void Planning::Stop() {} bool Planning::Plan(const bool is_on_auto_mode, const double current_time_stamp, const double planning_cycle_time) { const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_on_auto_mode, current_time_stamp, planning_cycle_time, last_publishable_trajectory_); frame_->SetPlanningStartPoint(stitching_trajectory.back()); auto trajectory_pb = frame_->MutableADCTrajectory(); if (FLAGS_enable_record_debug) { trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_init_point() ->CopyFrom(stitching_trajectory.back()); } frame_->AlignPredictionTime(current_time_stamp); PublishableTrajectory publishable_trajectory; auto status = planner_->Plan(stitching_trajectory.back(), frame_.get(), &publishable_trajectory); if (status != Status::OK()) { AERROR << "planner failed to make a driving plan"; last_publishable_trajectory_.Clear(); return false; } publishable_trajectory.PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); publishable_trajectory.set_header_time(current_time_stamp); publishable_trajectory.PopulateTrajectoryProtobuf(trajectory_pb); trajectory_pb->set_is_replan(stitching_trajectory.size() == 1); // update last publishable trajectory; last_publishable_trajectory_ = std::move(publishable_trajectory); return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include <thread> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } const Frame* Planning::GetFrame() const { return frame_.get(); } const hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); } bool Planning::InitFrame(const uint32_t sequence_num) { frame_.reset(new Frame(sequence_num)); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return false; } common::TrajectoryPoint point; frame_->SetVehicleInitPose(VehicleState::instance()->pose()); frame_->SetRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction done."; } if (!frame_->Init(config_)) { AERROR << "failed to init frame"; return false; } frame_->RecordInputDebug(); return true; } void Planning::SetConfig(const PlanningConfig& config) { config_ = config; } Status Planning::Init() { pnc_map_.reset(new hdmap::PncMap(apollo::hdmap::BaseMapFile())); Frame::SetMap(pnc_map_.get()); if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) { AERROR << "failed to load planning config file " << FLAGS_planning_config_file; return Status( ErrorCode::PLANNING_ERROR, "failed to load planning config file: " + FLAGS_planning_config_file); } if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } Status Planning::Start() { static ros::Rate loop_rate(FLAGS_planning_loop_rate); while (ros::ok()) { RunOnce(); if (frame_) { auto seq_num = frame_->sequence_num(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } ros::spinOnce(); loop_rate.sleep(); } return Status::OK(); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb, double timestamp) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::RunOnce() { AdapterManager::Observe(); ADCTrajectory not_ready_pb; auto* not_ready = not_ready_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (AdapterManager::GetLocalization()->Empty()) { AERROR << "Localization is not available; skip the planning cycle"; not_ready->set_reason("localization not ready"); PublishPlanningPb(&not_ready_pb); return; } if (AdapterManager::GetChassis()->Empty()) { AERROR << "Chassis is not available; skip the planning cycle"; not_ready->set_reason("chassis not ready"); PublishPlanningPb(&not_ready_pb); return; } if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "RoutingResponse is not available; skip the planning cycle"; not_ready->set_reason("routing not ready"); PublishPlanningPb(&not_ready_pb); return; } if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { AERROR << "Prediction is not available; skip the planning cycle"; not_ready->set_reason("prediction not ready"); PublishPlanningPb(&not_ready_pb); return; } const double start_timestamp = Clock::NowInSecond(); // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::Status status = common::VehicleState::instance()->Update(localization, chassis); if (!status.ok()) { AERROR << "Update VehicleState failed."; not_ready->set_reason("Update VehicleState failed."); status.Save(not_ready_pb.mutable_header()->mutable_status()); PublishPlanningPb(&not_ready_pb); return; } const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; if (!InitFrame(frame_num)) { AERROR << "Init frame failed"; return; } bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; status = Plan(is_auto_mode, start_timestamp, planning_cycle_time); const double end_timestamp = Clock::NowInSecond(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; auto trajectory_pb = frame_->MutableADCTrajectory(); trajectory_pb->mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb->latency_stats().DebugString(); if (status.ok()) { PublishPlanningPb(trajectory_pb, start_timestamp); ADEBUG << "Planning succeeded:" << trajectory_pb->header().DebugString(); } else { status.Save(trajectory_pb->mutable_header()->mutable_status()); PublishPlanningPb(trajectory_pb, start_timestamp); AERROR << "Planning failed"; } } void Planning::Stop() {} common::Status Planning::Plan(const bool is_on_auto_mode, const double current_time_stamp, const double planning_cycle_time) { const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_on_auto_mode, current_time_stamp, planning_cycle_time, last_publishable_trajectory_); frame_->SetPlanningStartPoint(stitching_trajectory.back()); auto trajectory_pb = frame_->MutableADCTrajectory(); if (FLAGS_enable_record_debug) { trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_init_point() ->CopyFrom(stitching_trajectory.back()); } frame_->AlignPredictionTime(current_time_stamp); std::vector<std::unique_ptr<std::thread>> threads; for (auto& reference_line_info : frame_->reference_line_info()) { threads.emplace_back( new std::thread([this, stitching_trajectory, &reference_line_info] { auto status = this->planner_->Plan( stitching_trajectory.back(), frame_.get(), &reference_line_info); if (!status.ok()) { AERROR << "planner failed to make a driving plan."; } })); } for (const auto& thread : threads) { if (thread->joinable()) { thread->join(); } } const ReferenceLineInfo* best_reference_line = frame_->FindDriveReferenceLineInfo(); if (!best_reference_line) { std::string msg("planner failed to make a driving plan"); AERROR << msg; last_publishable_trajectory_.Clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } auto* ptr_debug = frame_->MutableADCTrajectory()->mutable_debug(); auto* ptr_latency_stats = frame_->MutableADCTrajectory()->mutable_latency_stats(); ptr_debug->CopyFrom(best_reference_line->debug()); ptr_latency_stats->CopyFrom(best_reference_line->latency_stats()); // Add debug information. if (FLAGS_enable_record_debug) { auto* reference_line = ptr_debug->mutable_planning_data()->add_path(); reference_line->set_name("planning_reference_line"); const auto& reference_points = best_reference_line->reference_line().reference_points(); for (const auto& reference_point : reference_points) { auto* path_point = reference_line->add_path_point(); path_point->set_x(reference_point.x()); path_point->set_y(reference_point.y()); path_point->set_theta(reference_point.heading()); path_point->set_kappa(reference_point.kappa()); path_point->set_dkappa(reference_point.dkappa()); } } PublishableTrajectory publishable_trajectory( current_time_stamp, best_reference_line->trajectory()); publishable_trajectory.PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); publishable_trajectory.set_header_time(current_time_stamp); publishable_trajectory.PopulateTrajectoryProtobuf(trajectory_pb); trajectory_pb->set_is_replan(stitching_trajectory.size() == 1); // update last publishable trajectory; last_publishable_trajectory_ = std::move(publishable_trajectory); return Status::OK(); } } // namespace planning } // namespace apollo <commit_msg>planning: fix debug merge problem.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/planning/planning.h" #include <algorithm> #include <thread> #include "google/protobuf/repeated_field.h" #include "modules/common/adapters/adapter_manager.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/planner/em/em_planner.h" #include "modules/planning/planner/rtk/rtk_replay_planner.h" #include "modules/planning/trajectory_stitcher/trajectory_stitcher.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; using apollo::common::TrajectoryPoint; using apollo::common::VehicleState; using apollo::common::adapter::AdapterManager; using apollo::common::time::Clock; std::string Planning::Name() const { return "planning"; } void Planning::RegisterPlanners() { planner_factory_.Register( PlanningConfig::RTK, []() -> Planner* { return new RTKReplayPlanner(); }); planner_factory_.Register(PlanningConfig::EM, []() -> Planner* { return new EMPlanner(); }); } const Frame* Planning::GetFrame() const { return frame_.get(); } const hdmap::PncMap* Planning::GetPncMap() const { return pnc_map_.get(); } bool Planning::InitFrame(const uint32_t sequence_num) { frame_.reset(new Frame(sequence_num)); if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "Routing is empty"; return false; } common::TrajectoryPoint point; frame_->SetVehicleInitPose(VehicleState::instance()->pose()); frame_->SetRoutingResponse( AdapterManager::GetRoutingResponse()->GetLatestObserved()); if (FLAGS_enable_prediction && !AdapterManager::GetPrediction()->Empty()) { const auto& prediction = AdapterManager::GetPrediction()->GetLatestObserved(); frame_->SetPrediction(prediction); ADEBUG << "Get prediction done."; } if (!frame_->Init(config_)) { AERROR << "failed to init frame"; return false; } frame_->RecordInputDebug(); return true; } void Planning::SetConfig(const PlanningConfig& config) { config_ = config; } Status Planning::Init() { pnc_map_.reset(new hdmap::PncMap(apollo::hdmap::BaseMapFile())); Frame::SetMap(pnc_map_.get()); if (!apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file, &config_)) { AERROR << "failed to load planning config file " << FLAGS_planning_config_file; return Status( ErrorCode::PLANNING_ERROR, "failed to load planning config file: " + FLAGS_planning_config_file); } if (!AdapterManager::Initialized()) { AdapterManager::Init(FLAGS_adapter_config_path); } if (AdapterManager::GetLocalization() == nullptr) { std::string error_msg("Localization is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetChassis() == nullptr) { std::string error_msg("Chassis is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetRoutingResponse() == nullptr) { std::string error_msg("RoutingResponse is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } if (AdapterManager::GetPrediction() == nullptr) { std::string error_msg("Prediction is not registered"); AERROR << error_msg; return Status(ErrorCode::PLANNING_ERROR, error_msg); } RegisterPlanners(); planner_ = planner_factory_.CreateObject(config_.planner_type()); if (!planner_) { return Status( ErrorCode::PLANNING_ERROR, "planning is not initialized with config : " + config_.DebugString()); } return planner_->Init(config_); } Status Planning::Start() { static ros::Rate loop_rate(FLAGS_planning_loop_rate); while (ros::ok()) { RunOnce(); if (frame_) { auto seq_num = frame_->sequence_num(); FrameHistory::instance()->Add(seq_num, std::move(frame_)); } ros::spinOnce(); loop_rate.sleep(); } return Status::OK(); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::PublishPlanningPb(ADCTrajectory* trajectory_pb, double timestamp) { AdapterManager::FillPlanningHeader("planning", trajectory_pb); trajectory_pb->mutable_header()->set_timestamp_sec(timestamp); // TODO(all): integrate reverse gear trajectory_pb->set_gear(canbus::Chassis::GEAR_DRIVE); AdapterManager::PublishPlanning(*trajectory_pb); } void Planning::RunOnce() { AdapterManager::Observe(); ADCTrajectory not_ready_pb; auto* not_ready = not_ready_pb.mutable_decision() ->mutable_main_decision() ->mutable_not_ready(); if (AdapterManager::GetLocalization()->Empty()) { AERROR << "Localization is not available; skip the planning cycle"; not_ready->set_reason("localization not ready"); PublishPlanningPb(&not_ready_pb); return; } if (AdapterManager::GetChassis()->Empty()) { AERROR << "Chassis is not available; skip the planning cycle"; not_ready->set_reason("chassis not ready"); PublishPlanningPb(&not_ready_pb); return; } if (AdapterManager::GetRoutingResponse()->Empty()) { AERROR << "RoutingResponse is not available; skip the planning cycle"; not_ready->set_reason("routing not ready"); PublishPlanningPb(&not_ready_pb); return; } if (FLAGS_enable_prediction && AdapterManager::GetPrediction()->Empty()) { AERROR << "Prediction is not available; skip the planning cycle"; not_ready->set_reason("prediction not ready"); PublishPlanningPb(&not_ready_pb); return; } const double start_timestamp = Clock::NowInSecond(); // localization const auto& localization = AdapterManager::GetLocalization()->GetLatestObserved(); ADEBUG << "Get localization:" << localization.DebugString(); // chassis const auto& chassis = AdapterManager::GetChassis()->GetLatestObserved(); ADEBUG << "Get chassis:" << chassis.DebugString(); common::Status status = common::VehicleState::instance()->Update(localization, chassis); if (!status.ok()) { AERROR << "Update VehicleState failed."; not_ready->set_reason("Update VehicleState failed."); status.Save(not_ready_pb.mutable_header()->mutable_status()); PublishPlanningPb(&not_ready_pb); return; } const double planning_cycle_time = 1.0 / FLAGS_planning_loop_rate; const uint32_t frame_num = AdapterManager::GetPlanning()->GetSeqNum() + 1; if (!InitFrame(frame_num)) { AERROR << "Init frame failed"; return; } bool is_auto_mode = chassis.driving_mode() == chassis.COMPLETE_AUTO_DRIVE; status = Plan(is_auto_mode, start_timestamp, planning_cycle_time); const double end_timestamp = Clock::NowInSecond(); const double time_diff_ms = (end_timestamp - start_timestamp) * 1000; auto trajectory_pb = frame_->MutableADCTrajectory(); trajectory_pb->mutable_latency_stats()->set_total_time_ms(time_diff_ms); ADEBUG << "Planning latency: " << trajectory_pb->latency_stats().DebugString(); if (status.ok()) { PublishPlanningPb(trajectory_pb, start_timestamp); ADEBUG << "Planning succeeded:" << trajectory_pb->header().DebugString(); } else { status.Save(trajectory_pb->mutable_header()->mutable_status()); PublishPlanningPb(trajectory_pb, start_timestamp); AERROR << "Planning failed"; } } void Planning::Stop() {} common::Status Planning::Plan(const bool is_on_auto_mode, const double current_time_stamp, const double planning_cycle_time) { const auto& stitching_trajectory = TrajectoryStitcher::ComputeStitchingTrajectory( is_on_auto_mode, current_time_stamp, planning_cycle_time, last_publishable_trajectory_); frame_->SetPlanningStartPoint(stitching_trajectory.back()); auto trajectory_pb = frame_->MutableADCTrajectory(); if (FLAGS_enable_record_debug) { trajectory_pb->mutable_debug() ->mutable_planning_data() ->mutable_init_point() ->CopyFrom(stitching_trajectory.back()); } frame_->AlignPredictionTime(current_time_stamp); std::vector<std::unique_ptr<std::thread>> threads; for (auto& reference_line_info : frame_->reference_line_info()) { threads.emplace_back( new std::thread([this, stitching_trajectory, &reference_line_info] { auto status = this->planner_->Plan( stitching_trajectory.back(), frame_.get(), &reference_line_info); if (!status.ok()) { AERROR << "planner failed to make a driving plan."; } })); } for (const auto& thread : threads) { if (thread->joinable()) { thread->join(); } } const ReferenceLineInfo* best_reference_line = frame_->FindDriveReferenceLineInfo(); if (!best_reference_line) { std::string msg("planner failed to make a driving plan"); AERROR << msg; last_publishable_trajectory_.Clear(); return Status(ErrorCode::PLANNING_ERROR, msg); } auto* ptr_debug = frame_->MutableADCTrajectory()->mutable_debug(); auto* ptr_latency_stats = frame_->MutableADCTrajectory()->mutable_latency_stats(); ptr_debug->MergeFrom(best_reference_line->debug()); ptr_latency_stats->MergeFrom(best_reference_line->latency_stats()); // Add debug information. if (FLAGS_enable_record_debug) { auto* reference_line = ptr_debug->mutable_planning_data()->add_path(); reference_line->set_name("planning_reference_line"); const auto& reference_points = best_reference_line->reference_line().reference_points(); for (const auto& reference_point : reference_points) { auto* path_point = reference_line->add_path_point(); path_point->set_x(reference_point.x()); path_point->set_y(reference_point.y()); path_point->set_theta(reference_point.heading()); path_point->set_kappa(reference_point.kappa()); path_point->set_dkappa(reference_point.dkappa()); } } PublishableTrajectory publishable_trajectory( current_time_stamp, best_reference_line->trajectory()); publishable_trajectory.PrependTrajectoryPoints( stitching_trajectory.begin(), stitching_trajectory.end() - 1); publishable_trajectory.set_header_time(current_time_stamp); publishable_trajectory.PopulateTrajectoryProtobuf(trajectory_pb); trajectory_pb->set_is_replan(stitching_trajectory.size() == 1); // update last publishable trajectory; last_publishable_trajectory_ = std::move(publishable_trajectory); return Status::OK(); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleRubberBandZoom.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. =========================================================================*/ #include "vtkInteractorStyleRubberBandZoom.h" #include "vtkCamera.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkUnsignedCharArray.h" vtkStandardNewMacro(vtkInteractorStyleRubberBandZoom); vtkInteractorStyleRubberBandZoom::vtkInteractorStyleRubberBandZoom() { this->StartPosition[0] = this->StartPosition[1] = 0; this->EndPosition[0] = this->EndPosition[1] = 0; this->Moving = 0; this->PixelArray = vtkUnsignedCharArray::New(); } vtkInteractorStyleRubberBandZoom::~vtkInteractorStyleRubberBandZoom() { this->PixelArray->Delete(); } void vtkInteractorStyleRubberBandZoom::OnMouseMove() { if (!this->Interactor || !this->Moving) { return; } this->EndPosition[0] = this->Interactor->GetEventPosition()[0]; this->EndPosition[1] = this->Interactor->GetEventPosition()[1]; int *size = this->Interactor->GetRenderWindow()->GetSize(); if (this->EndPosition[0] > (size[0]-1)) { this->EndPosition[0] = size[0]-1; } if (this->EndPosition[0] < 0) { this->EndPosition[0] = 0; } if (this->EndPosition[1] > (size[1]-1)) { this->EndPosition[1] = size[1]-1; } if (this->EndPosition[1] < 0) { this->EndPosition[1] = 0; } vtkUnsignedCharArray *tmpPixelArray = vtkUnsignedCharArray::New(); tmpPixelArray->DeepCopy(this->PixelArray); unsigned char *pixels = tmpPixelArray->GetPointer(0); int min[2], max[2]; min[0] = this->StartPosition[0] <= this->EndPosition[0] ? this->StartPosition[0] : this->EndPosition[0]; min[1] = this->StartPosition[1] <= this->EndPosition[1] ? this->StartPosition[1] : this->EndPosition[1]; max[0] = this->EndPosition[0] > this->StartPosition[0] ? this->EndPosition[0] : this->StartPosition[0]; max[1] = this->EndPosition[1] > this->StartPosition[1] ? this->EndPosition[1] : this->StartPosition[1]; int i; for (i = min[0]; i <= max[0]; i++) { pixels[3*(min[1]*size[0]+i)] = 255 ^ pixels[3*(min[1]*size[0]+i)]; pixels[3*(min[1]*size[0]+i)+1] = 255 ^ pixels[3*(min[1]*size[0]+i)+1]; pixels[3*(min[1]*size[0]+i)+2] = 255 ^ pixels[3*(min[1]*size[0]+i)+2]; pixels[3*(max[1]*size[0]+i)] = 255 ^ pixels[3*(max[1]*size[0]+i)]; pixels[3*(max[1]*size[0]+i)+1] = 255 ^ pixels[3*(max[1]*size[0]+i)+1]; pixels[3*(max[1]*size[0]+i)+2] = 255 ^ pixels[3*(max[1]*size[0]+i)+2]; } for (i = min[1]+1; i < max[1]; i++) { pixels[3*(i*size[0]+min[0])] = 255 ^ pixels[3*(i*size[0]+min[0])]; pixels[3*(i*size[0]+min[0])+1] = 255 ^ pixels[3*(i*size[0]+min[0])+1]; pixels[3*(i*size[0]+min[0])+2] = 255 ^ pixels[3*(i*size[0]+min[0])+2]; pixels[3*(i*size[0]+max[0])] = 255 ^ pixels[3*(i*size[0]+max[0])]; pixels[3*(i*size[0]+max[0])+1] = 255 ^ pixels[3*(i*size[0]+max[0])+1]; pixels[3*(i*size[0]+max[0])+2] = 255 ^ pixels[3*(i*size[0]+max[0])+2]; } this->Interactor->GetRenderWindow()->SetPixelData(0, 0, size[0]-1, size[1]-1, pixels, 1); tmpPixelArray->Delete(); } void vtkInteractorStyleRubberBandZoom::OnLeftButtonDown() { if (!this->Interactor) { return; } this->Moving = 1; vtkRenderWindow *renWin = this->Interactor->GetRenderWindow(); this->StartPosition[0] = this->Interactor->GetEventPosition()[0]; this->StartPosition[1] = this->Interactor->GetEventPosition()[1]; this->EndPosition[0] = this->StartPosition[0]; this->EndPosition[1] = this->StartPosition[1]; this->PixelArray->Initialize(); this->PixelArray->SetNumberOfComponents(3); int *size = renWin->GetSize(); this->PixelArray->SetNumberOfTuples(size[0]*size[1]); renWin->GetPixelData(0, 0, size[0]-1, size[1]-1, 1, this->PixelArray); this->FindPokedRenderer(this->StartPosition[0], this->StartPosition[1]); } void vtkInteractorStyleRubberBandZoom::OnLeftButtonUp() { if (!this->Interactor || !this->Moving) { return; } if ( (this->StartPosition[0] != this->EndPosition[0]) || (this->StartPosition[1] != this->EndPosition[1]) ) { this->Zoom(); } this->Moving = 0; } void vtkInteractorStyleRubberBandZoom::Zoom() { int width, height; width = abs(this->EndPosition[0] - this->StartPosition[0]); height = abs(this->EndPosition[1] - this->StartPosition[1]); int *size = this->CurrentRenderer->GetSize(); int *origin = this->CurrentRenderer->GetOrigin(); vtkCamera *cam = this->CurrentRenderer->GetActiveCamera(); int min[2]; double rbcenter[3]; min[0] = this->StartPosition[0] < this->EndPosition[0] ? this->StartPosition[0] : this->EndPosition[0]; min[1] = this->StartPosition[1] < this->EndPosition[1] ? this->StartPosition[1] : this->EndPosition[1]; rbcenter[0] = min[0] + 0.5*width; rbcenter[1] = min[1] + 0.5*height; rbcenter[2] = 0; this->CurrentRenderer->SetDisplayPoint(rbcenter); this->CurrentRenderer->DisplayToView(); this->CurrentRenderer->ViewToWorld(); double invw; double worldRBCenter[4]; this->CurrentRenderer->GetWorldPoint(worldRBCenter); invw = 1.0/worldRBCenter[3]; worldRBCenter[0] *= invw; worldRBCenter[1] *= invw; worldRBCenter[2] *= invw; double winCenter[3]; winCenter[0] = origin[0] + 0.5*size[0]; winCenter[1] = origin[1] + 0.5*size[1]; winCenter[2] = 0; this->CurrentRenderer->SetDisplayPoint(winCenter); this->CurrentRenderer->DisplayToView(); this->CurrentRenderer->ViewToWorld(); double worldWinCenter[4]; this->CurrentRenderer->GetWorldPoint(worldWinCenter); invw = 1.0/worldWinCenter[3]; worldWinCenter[0] *= invw; worldWinCenter[1] *= invw; worldWinCenter[2] *= invw; double translation[3]; translation[0] = worldRBCenter[0] - worldWinCenter[0]; translation[1] = worldRBCenter[1] - worldWinCenter[1]; translation[2] = worldRBCenter[2] - worldWinCenter[2]; double pos[3], fp[3]; cam->GetPosition(pos); cam->GetFocalPoint(fp); pos[0] += translation[0]; pos[1] += translation[1]; pos[2] += translation[2]; fp[0] += translation[0]; fp[1] += translation[1]; fp[2] += translation[2]; cam->SetPosition(pos); cam->SetFocalPoint(fp); double zoomFactor; if (width > height) { zoomFactor = size[0] / static_cast<double>(width); } else { zoomFactor = size[1] / static_cast<double>(height); } if (cam->GetParallelProjection()) { cam->Zoom(zoomFactor); } else { // In perspective mode, zoom in by moving the camera closer. Because we are // moving the camera closer, we have to be careful to try to adjust the // clipping planes to best match the actual position they were in before. double initialDistance = cam->GetDistance(); cam->Dolly(zoomFactor); double finalDistance = cam->GetDistance(); double deltaDistance = initialDistance - finalDistance; double clippingRange[2]; cam->GetClippingRange(clippingRange); clippingRange[0] -= deltaDistance; clippingRange[1] -= deltaDistance; // Correct bringing clipping planes too close or behind camera. if (clippingRange[1] <= 0.0) { clippingRange[1] = 0.001; } // This near plane check comes from vtkRenderer::ResetCameraClippingRange() if (clippingRange[0] < 0.001*clippingRange[1]) { clippingRange[0] = 0.001*clippingRange[1]; } cam->SetClippingRange(clippingRange); } this->Interactor->Render(); } void vtkInteractorStyleRubberBandZoom::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } <commit_msg>Add missing Frame() call on the renderWindow<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkInteractorStyleRubberBandZoom.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. =========================================================================*/ #include "vtkInteractorStyleRubberBandZoom.h" #include "vtkCamera.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkUnsignedCharArray.h" vtkStandardNewMacro(vtkInteractorStyleRubberBandZoom); vtkInteractorStyleRubberBandZoom::vtkInteractorStyleRubberBandZoom() { this->StartPosition[0] = this->StartPosition[1] = 0; this->EndPosition[0] = this->EndPosition[1] = 0; this->Moving = 0; this->PixelArray = vtkUnsignedCharArray::New(); } vtkInteractorStyleRubberBandZoom::~vtkInteractorStyleRubberBandZoom() { this->PixelArray->Delete(); } void vtkInteractorStyleRubberBandZoom::OnMouseMove() { if (!this->Interactor || !this->Moving) { return; } this->EndPosition[0] = this->Interactor->GetEventPosition()[0]; this->EndPosition[1] = this->Interactor->GetEventPosition()[1]; int *size = this->Interactor->GetRenderWindow()->GetSize(); if (this->EndPosition[0] > (size[0]-1)) { this->EndPosition[0] = size[0]-1; } if (this->EndPosition[0] < 0) { this->EndPosition[0] = 0; } if (this->EndPosition[1] > (size[1]-1)) { this->EndPosition[1] = size[1]-1; } if (this->EndPosition[1] < 0) { this->EndPosition[1] = 0; } vtkUnsignedCharArray *tmpPixelArray = vtkUnsignedCharArray::New(); tmpPixelArray->DeepCopy(this->PixelArray); unsigned char *pixels = tmpPixelArray->GetPointer(0); int min[2], max[2]; min[0] = this->StartPosition[0] <= this->EndPosition[0] ? this->StartPosition[0] : this->EndPosition[0]; min[1] = this->StartPosition[1] <= this->EndPosition[1] ? this->StartPosition[1] : this->EndPosition[1]; max[0] = this->EndPosition[0] > this->StartPosition[0] ? this->EndPosition[0] : this->StartPosition[0]; max[1] = this->EndPosition[1] > this->StartPosition[1] ? this->EndPosition[1] : this->StartPosition[1]; int i; for (i = min[0]; i <= max[0]; i++) { pixels[3*(min[1]*size[0]+i)] = 255 ^ pixels[3*(min[1]*size[0]+i)]; pixels[3*(min[1]*size[0]+i)+1] = 255 ^ pixels[3*(min[1]*size[0]+i)+1]; pixels[3*(min[1]*size[0]+i)+2] = 255 ^ pixels[3*(min[1]*size[0]+i)+2]; pixels[3*(max[1]*size[0]+i)] = 255 ^ pixels[3*(max[1]*size[0]+i)]; pixels[3*(max[1]*size[0]+i)+1] = 255 ^ pixels[3*(max[1]*size[0]+i)+1]; pixels[3*(max[1]*size[0]+i)+2] = 255 ^ pixels[3*(max[1]*size[0]+i)+2]; } for (i = min[1]+1; i < max[1]; i++) { pixels[3*(i*size[0]+min[0])] = 255 ^ pixels[3*(i*size[0]+min[0])]; pixels[3*(i*size[0]+min[0])+1] = 255 ^ pixels[3*(i*size[0]+min[0])+1]; pixels[3*(i*size[0]+min[0])+2] = 255 ^ pixels[3*(i*size[0]+min[0])+2]; pixels[3*(i*size[0]+max[0])] = 255 ^ pixels[3*(i*size[0]+max[0])]; pixels[3*(i*size[0]+max[0])+1] = 255 ^ pixels[3*(i*size[0]+max[0])+1]; pixels[3*(i*size[0]+max[0])+2] = 255 ^ pixels[3*(i*size[0]+max[0])+2]; } this->Interactor->GetRenderWindow()->SetPixelData(0, 0, size[0]-1, size[1]-1, pixels, 1); this->Interactor->GetRenderWindow()->Frame(); tmpPixelArray->Delete(); } void vtkInteractorStyleRubberBandZoom::OnLeftButtonDown() { if (!this->Interactor) { return; } this->Moving = 1; vtkRenderWindow *renWin = this->Interactor->GetRenderWindow(); this->StartPosition[0] = this->Interactor->GetEventPosition()[0]; this->StartPosition[1] = this->Interactor->GetEventPosition()[1]; this->EndPosition[0] = this->StartPosition[0]; this->EndPosition[1] = this->StartPosition[1]; this->PixelArray->Initialize(); this->PixelArray->SetNumberOfComponents(3); int *size = renWin->GetSize(); this->PixelArray->SetNumberOfTuples(size[0]*size[1]); renWin->GetPixelData(0, 0, size[0]-1, size[1]-1, 1, this->PixelArray); this->FindPokedRenderer(this->StartPosition[0], this->StartPosition[1]); } void vtkInteractorStyleRubberBandZoom::OnLeftButtonUp() { if (!this->Interactor || !this->Moving) { return; } if ( (this->StartPosition[0] != this->EndPosition[0]) || (this->StartPosition[1] != this->EndPosition[1]) ) { this->Zoom(); } this->Moving = 0; } void vtkInteractorStyleRubberBandZoom::Zoom() { int width, height; width = abs(this->EndPosition[0] - this->StartPosition[0]); height = abs(this->EndPosition[1] - this->StartPosition[1]); int *size = this->CurrentRenderer->GetSize(); int *origin = this->CurrentRenderer->GetOrigin(); vtkCamera *cam = this->CurrentRenderer->GetActiveCamera(); int min[2]; double rbcenter[3]; min[0] = this->StartPosition[0] < this->EndPosition[0] ? this->StartPosition[0] : this->EndPosition[0]; min[1] = this->StartPosition[1] < this->EndPosition[1] ? this->StartPosition[1] : this->EndPosition[1]; rbcenter[0] = min[0] + 0.5*width; rbcenter[1] = min[1] + 0.5*height; rbcenter[2] = 0; this->CurrentRenderer->SetDisplayPoint(rbcenter); this->CurrentRenderer->DisplayToView(); this->CurrentRenderer->ViewToWorld(); double invw; double worldRBCenter[4]; this->CurrentRenderer->GetWorldPoint(worldRBCenter); invw = 1.0/worldRBCenter[3]; worldRBCenter[0] *= invw; worldRBCenter[1] *= invw; worldRBCenter[2] *= invw; double winCenter[3]; winCenter[0] = origin[0] + 0.5*size[0]; winCenter[1] = origin[1] + 0.5*size[1]; winCenter[2] = 0; this->CurrentRenderer->SetDisplayPoint(winCenter); this->CurrentRenderer->DisplayToView(); this->CurrentRenderer->ViewToWorld(); double worldWinCenter[4]; this->CurrentRenderer->GetWorldPoint(worldWinCenter); invw = 1.0/worldWinCenter[3]; worldWinCenter[0] *= invw; worldWinCenter[1] *= invw; worldWinCenter[2] *= invw; double translation[3]; translation[0] = worldRBCenter[0] - worldWinCenter[0]; translation[1] = worldRBCenter[1] - worldWinCenter[1]; translation[2] = worldRBCenter[2] - worldWinCenter[2]; double pos[3], fp[3]; cam->GetPosition(pos); cam->GetFocalPoint(fp); pos[0] += translation[0]; pos[1] += translation[1]; pos[2] += translation[2]; fp[0] += translation[0]; fp[1] += translation[1]; fp[2] += translation[2]; cam->SetPosition(pos); cam->SetFocalPoint(fp); double zoomFactor; if (width > height) { zoomFactor = size[0] / static_cast<double>(width); } else { zoomFactor = size[1] / static_cast<double>(height); } if (cam->GetParallelProjection()) { cam->Zoom(zoomFactor); } else { // In perspective mode, zoom in by moving the camera closer. Because we are // moving the camera closer, we have to be careful to try to adjust the // clipping planes to best match the actual position they were in before. double initialDistance = cam->GetDistance(); cam->Dolly(zoomFactor); double finalDistance = cam->GetDistance(); double deltaDistance = initialDistance - finalDistance; double clippingRange[2]; cam->GetClippingRange(clippingRange); clippingRange[0] -= deltaDistance; clippingRange[1] -= deltaDistance; // Correct bringing clipping planes too close or behind camera. if (clippingRange[1] <= 0.0) { clippingRange[1] = 0.001; } // This near plane check comes from vtkRenderer::ResetCameraClippingRange() if (clippingRange[0] < 0.001*clippingRange[1]) { clippingRange[0] = 0.001*clippingRange[1]; } cam->SetClippingRange(clippingRange); } this->Interactor->Render(); } void vtkInteractorStyleRubberBandZoom::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } <|endoftext|>
<commit_before>#include <Fqd.hpp> using namespace flink; using namespace eeros::hal; Fqd::Fqd(std::string id, void* libHandle, std::string device, uint32_t subDeviceNumber, uint32_t channel, double scale, double offset, double rangeMin, double rangeMax, std::string unit, bool getDelta) : ScalableInput<double>(id, libHandle, scale, offset, rangeMin, rangeMax, unit), channel(channel), prevPos(0), getDelta(getDelta) { FlinkDevice *dev = FlinkDevice::getDevice(device); this->subdeviceHandle = flink_get_subdevice_by_id(dev->getDeviceHandle(), subDeviceNumber); reset(); } double Fqd::get() { uint32_t data = 0; flink_counter_get_count(subdeviceHandle, channel, &data); int16_t newPos = static_cast<uint16_t>(data); int16_t deltaPos = newPos - prevPos; prevPos = newPos; double delta = deltaPos / scale + offset; pos += delta; if (getDelta) return delta; else return pos; } void Fqd::reset() { flink_subdevice_reset(subdeviceHandle); // TODO only reset counter, not the subdevice! pos = 0; } extern "C"{ eeros::hal::ScalableInput<double> *createFqd(std::string id, void* libHandle, std::string device, uint32_t subDeviceNumber, uint32_t channel, double scale, double offset, double rangeMin, double rangeMax, std::string unit){ return new flink::Fqd(id, libHandle, device, subDeviceNumber, channel, scale, offset, rangeMin, rangeMax, unit); } void resetFqd(flink::Fqd *obj){ obj->reset(); } } <commit_msg>fix reset fqd<commit_after>#include <Fqd.hpp> using namespace flink; using namespace eeros::hal; Fqd::Fqd(std::string id, void* libHandle, std::string device, uint32_t subDeviceNumber, uint32_t channel, double scale, double offset, double rangeMin, double rangeMax, std::string unit, bool getDelta) : ScalableInput<double>(id, libHandle, scale, offset, rangeMin, rangeMax, unit), channel(channel), prevPos(0), getDelta(getDelta) { FlinkDevice *dev = FlinkDevice::getDevice(device); this->subdeviceHandle = flink_get_subdevice_by_id(dev->getDeviceHandle(), subDeviceNumber); reset(); } double Fqd::get() { uint32_t data = 0; flink_counter_get_count(subdeviceHandle, channel, &data); int16_t newPos = static_cast<uint16_t>(data); int16_t deltaPos = newPos - prevPos; prevPos = newPos; double delta = deltaPos / scale + offset; pos += delta; if (getDelta) return delta; else return pos; } void Fqd::reset() { flink_subdevice_reset(subdeviceHandle); // TODO only reset counter, not the subdevice! pos = 0; prevPos = 0; } extern "C"{ eeros::hal::ScalableInput<double> *createFqd(std::string id, void* libHandle, std::string device, uint32_t subDeviceNumber, uint32_t channel, double scale, double offset, double rangeMin, double rangeMax, std::string unit){ return new flink::Fqd(id, libHandle, device, subDeviceNumber, channel, scale, offset, rangeMin, rangeMax, unit); } void resetFqd(flink::Fqd *obj){ obj->reset(); } } <|endoftext|>
<commit_before>#include "text_shape.hpp" #include "../drape/shader_def.hpp" #include "../drape/attribute_provider.hpp" #include "../drape/glstate.hpp" #include "../drape/batcher.hpp" #include "../drape/texture_set_holder.hpp" #include "../base/math.hpp" #include "../base/logging.hpp" #include "../base/stl_add.hpp" #include "../base/string_utils.hpp" #include "../std/algorithm.hpp" #include "../std/vector.hpp" using m2::PointF; namespace df { namespace { static uint32_t const ListStride = 24; static float const realFontSize = 20.0f; void SetColor(vector<float> &dst, float const * ar, int index) { uint32_t const colorArraySize = 4; uint32_t const baseListIndex = ListStride * index; for (uint32_t i = 0; i < 6; ++i) memcpy(&dst[baseListIndex + colorArraySize * i], ar, colorArraySize * sizeof(float)); } template <typename T> void QuadStripToList(vector<T> & dst, vector<T> & src, int32_t index) { static const int32_t dstStride = 6; static const int32_t srcStride = 4; const int32_t baseDstIndex = index * dstStride; const int32_t baseSrcIndex = index * srcStride; dst[baseDstIndex] = src[baseSrcIndex]; dst[baseDstIndex + 1] = src[baseSrcIndex + 1]; dst[baseDstIndex + 2] = src[baseSrcIndex + 2]; dst[baseDstIndex + 3] = src[baseSrcIndex + 1]; dst[baseDstIndex + 4] = src[baseSrcIndex + 3]; dst[baseDstIndex + 5] = src[baseSrcIndex + 2]; } PointF GetShift(dp::Anchor anchor, float width, float height) { switch(anchor) { case dp::Center: return PointF(-width / 2.0f, -height / 2.0f); case dp::Left: return PointF(0.0f, -height / 2.0f); case dp::Right: return PointF(-width, -height / 2.0f); case dp::Top: return PointF(-width / 2.0f, -height); case dp::Bottom: return PointF(-width / 2.0f, 0); case dp::LeftTop: return PointF(0.0f, -height); case dp::RightTop: return PointF(-width, -height); case dp::LeftBottom: return PointF(0.0f, 0.0f); case dp::RightBottom: return PointF(-width, 0.0f); default: return PointF(0.0f, 0.0f); } } struct Vertex { Vertex() {} Vertex(m2::PointF const & pos, m2::PointF const & dir) : m_position(pos), m_direction(dir) {} Vertex(float posX, float posY, float dirX = 0.0f, float dirY = 0.0f) : m_position(posX, posY), m_direction(dirX, dirY) {} m2::PointF m_position; m2::PointF m_direction; }; struct TexCoord { TexCoord() {} TexCoord(m2::PointF const & tex, float index = 0.0f, float depth = 0.0f) : m_texCoord(tex), m_index(index), m_depth(depth) {} TexCoord(float texX, float texY, float index = 0.0f, float depth = 0.0f) : m_texCoord(texX, texY), m_index(index), m_depth(depth) {} m2::PointF m_texCoord; float m_index; float m_depth; }; } TextShape::TextShape(m2::PointF const & basePoint, TextViewParams const & params) : m_basePoint(basePoint), m_params(params) { } void TextShape::AddGeometryWithTheSameTextureSet(int setNum, int letterCount, bool auxText, float maxTextLength, PointF const & anchorDelta, RefPointer<Batcher> batcher, RefPointer<TextureSetHolder> textures) const { strings::UniString text; float fontSize; Color base, outline; float needOutline; if(auxText) { text = strings::MakeUniString(m_params.m_secondaryText); fontSize = m_params.m_secondaryTextFont.m_size; base = m_params.m_secondaryTextFont.m_color; outline = m_params.m_secondaryTextFont.m_outlineColor; needOutline = m_params.m_secondaryTextFont.m_needOutline; } else { text = strings::MakeUniString(m_params.m_primaryText); fontSize = m_params.m_primaryTextFont.m_size; base = m_params.m_primaryTextFont.m_color; outline = m_params.m_primaryTextFont.m_outlineColor; needOutline = m_params.m_primaryTextFont.m_needOutline; } int const numVert = letterCount * 4; vector<Vertex> vertex(numVert); vector<TexCoord> texture(numVert); float stride = 0.0f; int textureSet; TextureSetHolder::GlyphRegion region; for(int i = 0, j = 0 ; i < text.size() ; i++) { textures->GetGlyphRegion(text[i], region); float xOffset, yOffset, advance; region.GetMetrics(xOffset, yOffset, advance); float const aspect = fontSize / realFontSize; advance *= aspect; if (region.GetTextureNode().m_textureSet != setNum) { stride += advance; continue; } textureSet = region.GetTextureNode().m_textureSet; m2::RectF const rect = region.GetTexRect(); float const textureNum = (region.GetTextureNode().m_textureOffset << 1) + needOutline; m2::PointU pixelSize; region.GetPixelSize(pixelSize); float const h = pixelSize.y * aspect; float const w = pixelSize.x * aspect; yOffset *= aspect; xOffset *= aspect; PointF const leftBottom(stride - xOffset + anchorDelta.x, yOffset + anchorDelta.y); PointF const rightBottom(stride + w - xOffset + anchorDelta.x, yOffset + anchorDelta.y); PointF const leftTop(stride - xOffset + anchorDelta.x, yOffset + h + anchorDelta.y); PointF const rightTop(stride + w - xOffset + anchorDelta.x, yOffset + h + anchorDelta.y); int index = j * 4; vertex[index++] = Vertex(m_basePoint, leftTop); vertex[index++] = Vertex(m_basePoint, leftBottom); vertex[index++] = Vertex(m_basePoint, rightTop); vertex[index++] = Vertex(m_basePoint, rightBottom); index = j * 4; texture[index++] = TexCoord(rect.minX(), rect.maxY(), textureNum, m_params.m_depth); texture[index++] = TexCoord(rect.minX(), rect.minY(), textureNum, m_params.m_depth); texture[index++] = TexCoord(rect.maxX(), rect.maxY(), textureNum, m_params.m_depth); texture[index++] = TexCoord(rect.maxX(), rect.minY(), textureNum, m_params.m_depth); j++; stride += advance; } vector<Vertex> vertex2(numVert * 3 / 2); vector<TexCoord> texture2(numVert * 3 / 2); vector<float> color(numVert * 6); vector<float> color2(numVert * 6); float clr1[4], clr2[4]; Convert(base, clr1[0], clr1[1], clr1[2], clr1[3]); Convert(outline, clr2[0], clr2[1], clr2[2], clr2[3]); for(int i = 0; i < letterCount ; i++) { QuadStripToList(vertex2, vertex, i); QuadStripToList(texture2, texture, i); SetColor(color, clr1, i); SetColor(color2, clr2, i); } GLState state(gpu::FONT_PROGRAM, GLState::OverlayLayer); state.SetTextureSet(textureSet); state.SetBlending(Blending(true)); AttributeProvider provider(4, 6*letterCount); { BindingInfo position(1); BindingDecl & decl = position.GetBindingDecl(0); decl.m_attributeName = "a_position"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(0, position, MakeStackRefPointer((void*)&vertex2[0])); } { BindingInfo texcoord(1); BindingDecl & decl = texcoord.GetBindingDecl(0); decl.m_attributeName = "a_texcoord"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(1, texcoord, MakeStackRefPointer((void*)&texture2[0])); } { BindingInfo base_color(1); BindingDecl & decl = base_color.GetBindingDecl(0); decl.m_attributeName = "a_color"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(2, base_color, MakeStackRefPointer((void*)&color[0])); } { BindingInfo outline_color(1); BindingDecl & decl = outline_color.GetBindingDecl(0); decl.m_attributeName = "a_outline_color"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(3, outline_color, MakeStackRefPointer((void*)&color2[0])); } float const bbY = m_params.m_primaryTextFont.m_size + m_params.m_secondaryTextFont.m_size; OverlayHandle * handle = new SquareHandle(m_params.m_featureID, m_params.m_anchor, m_basePoint, m2::PointD(maxTextLength, bbY), m_params.m_depth); //handle->SetIsVisible(true); batcher->InsertTriangleList(state, MakeStackRefPointer(&provider), MovePointer(handle)); } void TextShape::Draw(RefPointer<Batcher> batcher, RefPointer<TextureSetHolder> textures) const { strings::UniString const text = strings::MakeUniString(m_params.m_primaryText); int const size = text.size(); float const fontSize = m_params.m_primaryTextFont.m_size; float textLength = 0.0f; int const maxTextureSetCount = textures->GetMaxTextureSet(); buffer_vector<int, 16> sizes(maxTextureSetCount); for (int i = 0 ; i < size ; i++) { TextureSetHolder::GlyphRegion region; textures->GetGlyphRegion(text[i], region); ++sizes[region.GetTextureNode().m_textureSet]; float xOffset, yOffset, advance; region.GetMetrics(xOffset, yOffset, advance); textLength += advance * fontSize / realFontSize; } if (m_params.m_secondaryText.empty()) { PointF const anchorDelta = GetShift(m_params.m_anchor, textLength, fontSize) + m_params.m_primaryOffset; for(int i = 0; i < maxTextureSetCount ; ++i) { if (sizes[i]) AddGeometryWithTheSameTextureSet(i, sizes[i], false, textLength, anchorDelta, batcher, textures); } return; } strings::UniString const auxText = strings::MakeUniString(m_params.m_secondaryText); int const auxSize = auxText.size(); float const auxFontSize = m_params.m_secondaryTextFont.m_size; float auxTextLength = 0.0f; buffer_vector<int, 16> auxSizes(maxTextureSetCount); for (int i = 0 ; i < auxSize ; i++) { TextureSetHolder::GlyphRegion region; textures->GetGlyphRegion(auxText[i], region); ++auxSizes[region.GetTextureNode().m_textureSet]; float xOffset, yOffset, advance; region.GetMetrics(xOffset, yOffset, advance); auxTextLength += advance * auxFontSize / realFontSize; } float const length = max(textLength, auxTextLength); PointF const anchorDelta = GetShift(m_params.m_anchor, length, fontSize + auxFontSize); float dx = textLength > auxTextLength ? 0.0f : (auxTextLength - textLength) / 2.0f; PointF const textDelta = PointF(dx, auxFontSize) + anchorDelta + m_params.m_primaryOffset; dx = textLength > auxTextLength ? (textLength - auxTextLength) / 2.0f : 0.0f; PointF const auxTextDelta = PointF(dx, 0.0f) + anchorDelta + m_params.m_primaryOffset; for (int i = 0; i < maxTextureSetCount ; ++i) { if (sizes[i]) AddGeometryWithTheSameTextureSet(i, sizes[i], false, length, textDelta, batcher, textures); if (auxSizes[i]) AddGeometryWithTheSameTextureSet(i, auxSizes[i], true, length, auxTextDelta, batcher, textures); } } } //end of df namespace <commit_msg>fixed xOffset<commit_after>#include "text_shape.hpp" #include "../drape/shader_def.hpp" #include "../drape/attribute_provider.hpp" #include "../drape/glstate.hpp" #include "../drape/batcher.hpp" #include "../drape/texture_set_holder.hpp" #include "../base/math.hpp" #include "../base/logging.hpp" #include "../base/stl_add.hpp" #include "../base/string_utils.hpp" #include "../std/algorithm.hpp" #include "../std/vector.hpp" using m2::PointF; namespace df { namespace { static uint32_t const ListStride = 24; static float const realFontSize = 20.0f; void SetColor(vector<float> &dst, float const * ar, int index) { uint32_t const colorArraySize = 4; uint32_t const baseListIndex = ListStride * index; for (uint32_t i = 0; i < 6; ++i) memcpy(&dst[baseListIndex + colorArraySize * i], ar, colorArraySize * sizeof(float)); } template <typename T> void QuadStripToList(vector<T> & dst, vector<T> & src, int32_t index) { static const int32_t dstStride = 6; static const int32_t srcStride = 4; const int32_t baseDstIndex = index * dstStride; const int32_t baseSrcIndex = index * srcStride; dst[baseDstIndex] = src[baseSrcIndex]; dst[baseDstIndex + 1] = src[baseSrcIndex + 1]; dst[baseDstIndex + 2] = src[baseSrcIndex + 2]; dst[baseDstIndex + 3] = src[baseSrcIndex + 1]; dst[baseDstIndex + 4] = src[baseSrcIndex + 3]; dst[baseDstIndex + 5] = src[baseSrcIndex + 2]; } PointF GetShift(dp::Anchor anchor, float width, float height) { switch(anchor) { case dp::Center: return PointF(-width / 2.0f, -height / 2.0f); case dp::Left: return PointF(0.0f, -height / 2.0f); case dp::Right: return PointF(-width, -height / 2.0f); case dp::Top: return PointF(-width / 2.0f, -height); case dp::Bottom: return PointF(-width / 2.0f, 0); case dp::LeftTop: return PointF(0.0f, -height); case dp::RightTop: return PointF(-width, -height); case dp::LeftBottom: return PointF(0.0f, 0.0f); case dp::RightBottom: return PointF(-width, 0.0f); default: return PointF(0.0f, 0.0f); } } struct Vertex { Vertex() {} Vertex(m2::PointF const & pos, m2::PointF const & dir) : m_position(pos), m_direction(dir) {} Vertex(float posX, float posY, float dirX = 0.0f, float dirY = 0.0f) : m_position(posX, posY), m_direction(dirX, dirY) {} m2::PointF m_position; m2::PointF m_direction; }; struct TexCoord { TexCoord() {} TexCoord(m2::PointF const & tex, float index = 0.0f, float depth = 0.0f) : m_texCoord(tex), m_index(index), m_depth(depth) {} TexCoord(float texX, float texY, float index = 0.0f, float depth = 0.0f) : m_texCoord(texX, texY), m_index(index), m_depth(depth) {} m2::PointF m_texCoord; float m_index; float m_depth; }; } TextShape::TextShape(m2::PointF const & basePoint, TextViewParams const & params) : m_basePoint(basePoint), m_params(params) { } void TextShape::AddGeometryWithTheSameTextureSet(int setNum, int letterCount, bool auxText, float maxTextLength, PointF const & anchorDelta, RefPointer<Batcher> batcher, RefPointer<TextureSetHolder> textures) const { strings::UniString text; float fontSize; Color base, outline; float needOutline; if(auxText) { text = strings::MakeUniString(m_params.m_secondaryText); fontSize = m_params.m_secondaryTextFont.m_size; base = m_params.m_secondaryTextFont.m_color; outline = m_params.m_secondaryTextFont.m_outlineColor; needOutline = m_params.m_secondaryTextFont.m_needOutline; } else { text = strings::MakeUniString(m_params.m_primaryText); fontSize = m_params.m_primaryTextFont.m_size; base = m_params.m_primaryTextFont.m_color; outline = m_params.m_primaryTextFont.m_outlineColor; needOutline = m_params.m_primaryTextFont.m_needOutline; } int const numVert = letterCount * 4; vector<Vertex> vertex(numVert); vector<TexCoord> texture(numVert); float stride = 0.0f; int textureSet; TextureSetHolder::GlyphRegion region; for(int i = 0, j = 0 ; i < text.size() ; i++) { textures->GetGlyphRegion(text[i], region); float xOffset, yOffset, advance; region.GetMetrics(xOffset, yOffset, advance); float const aspect = fontSize / realFontSize; advance *= aspect; if (region.GetTextureNode().m_textureSet != setNum) { stride += advance; continue; } textureSet = region.GetTextureNode().m_textureSet; m2::RectF const rect = region.GetTexRect(); float const textureNum = (region.GetTextureNode().m_textureOffset << 1) + needOutline; m2::PointU pixelSize; region.GetPixelSize(pixelSize); float const h = pixelSize.y * aspect; float const w = pixelSize.x * aspect; yOffset *= aspect; xOffset *= aspect; PointF const leftBottom(stride + xOffset + anchorDelta.x, yOffset + anchorDelta.y); PointF const rightBottom(stride + w + xOffset + anchorDelta.x, yOffset + anchorDelta.y); PointF const leftTop(stride + xOffset + anchorDelta.x, yOffset + h + anchorDelta.y); PointF const rightTop(stride + w + xOffset + anchorDelta.x, yOffset + h + anchorDelta.y); int index = j * 4; vertex[index++] = Vertex(m_basePoint, leftTop); vertex[index++] = Vertex(m_basePoint, leftBottom); vertex[index++] = Vertex(m_basePoint, rightTop); vertex[index++] = Vertex(m_basePoint, rightBottom); index = j * 4; texture[index++] = TexCoord(rect.minX(), rect.maxY(), textureNum, m_params.m_depth); texture[index++] = TexCoord(rect.minX(), rect.minY(), textureNum, m_params.m_depth); texture[index++] = TexCoord(rect.maxX(), rect.maxY(), textureNum, m_params.m_depth); texture[index++] = TexCoord(rect.maxX(), rect.minY(), textureNum, m_params.m_depth); j++; stride += advance; } vector<Vertex> vertex2(numVert * 3 / 2); vector<TexCoord> texture2(numVert * 3 / 2); vector<float> color(numVert * 6); vector<float> color2(numVert * 6); float clr1[4], clr2[4]; Convert(base, clr1[0], clr1[1], clr1[2], clr1[3]); Convert(outline, clr2[0], clr2[1], clr2[2], clr2[3]); for(int i = 0; i < letterCount ; i++) { QuadStripToList(vertex2, vertex, i); QuadStripToList(texture2, texture, i); SetColor(color, clr1, i); SetColor(color2, clr2, i); } GLState state(gpu::FONT_PROGRAM, GLState::OverlayLayer); state.SetTextureSet(textureSet); state.SetBlending(Blending(true)); AttributeProvider provider(4, 6*letterCount); { BindingInfo position(1); BindingDecl & decl = position.GetBindingDecl(0); decl.m_attributeName = "a_position"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(0, position, MakeStackRefPointer((void*)&vertex2[0])); } { BindingInfo texcoord(1); BindingDecl & decl = texcoord.GetBindingDecl(0); decl.m_attributeName = "a_texcoord"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(1, texcoord, MakeStackRefPointer((void*)&texture2[0])); } { BindingInfo base_color(1); BindingDecl & decl = base_color.GetBindingDecl(0); decl.m_attributeName = "a_color"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(2, base_color, MakeStackRefPointer((void*)&color[0])); } { BindingInfo outline_color(1); BindingDecl & decl = outline_color.GetBindingDecl(0); decl.m_attributeName = "a_outline_color"; decl.m_componentCount = 4; decl.m_componentType = gl_const::GLFloatType; decl.m_offset = 0; decl.m_stride = 0; provider.InitStream(3, outline_color, MakeStackRefPointer((void*)&color2[0])); } float const bbY = m_params.m_primaryTextFont.m_size + m_params.m_secondaryTextFont.m_size; OverlayHandle * handle = new SquareHandle(m_params.m_featureID, m_params.m_anchor, m_basePoint, m2::PointD(maxTextLength, bbY), m_params.m_depth); //handle->SetIsVisible(true); batcher->InsertTriangleList(state, MakeStackRefPointer(&provider), MovePointer(handle)); } void TextShape::Draw(RefPointer<Batcher> batcher, RefPointer<TextureSetHolder> textures) const { strings::UniString const text = strings::MakeUniString(m_params.m_primaryText); int const size = text.size(); float const fontSize = m_params.m_primaryTextFont.m_size; float textLength = 0.0f; int const maxTextureSetCount = textures->GetMaxTextureSet(); buffer_vector<int, 16> sizes(maxTextureSetCount); for (int i = 0 ; i < size ; i++) { TextureSetHolder::GlyphRegion region; textures->GetGlyphRegion(text[i], region); ++sizes[region.GetTextureNode().m_textureSet]; float xOffset, yOffset, advance; region.GetMetrics(xOffset, yOffset, advance); textLength += advance * fontSize / realFontSize; } if (m_params.m_secondaryText.empty()) { PointF const anchorDelta = GetShift(m_params.m_anchor, textLength, fontSize) + m_params.m_primaryOffset; for(int i = 0; i < maxTextureSetCount ; ++i) { if (sizes[i]) AddGeometryWithTheSameTextureSet(i, sizes[i], false, textLength, anchorDelta, batcher, textures); } return; } strings::UniString const auxText = strings::MakeUniString(m_params.m_secondaryText); int const auxSize = auxText.size(); float const auxFontSize = m_params.m_secondaryTextFont.m_size; float auxTextLength = 0.0f; buffer_vector<int, 16> auxSizes(maxTextureSetCount); for (int i = 0 ; i < auxSize ; i++) { TextureSetHolder::GlyphRegion region; textures->GetGlyphRegion(auxText[i], region); ++auxSizes[region.GetTextureNode().m_textureSet]; float xOffset, yOffset, advance; region.GetMetrics(xOffset, yOffset, advance); auxTextLength += advance * auxFontSize / realFontSize; } float const length = max(textLength, auxTextLength); PointF const anchorDelta = GetShift(m_params.m_anchor, length, fontSize + auxFontSize); float dx = textLength > auxTextLength ? 0.0f : (auxTextLength - textLength) / 2.0f; PointF const textDelta = PointF(dx, auxFontSize) + anchorDelta + m_params.m_primaryOffset; dx = textLength > auxTextLength ? (textLength - auxTextLength) / 2.0f : 0.0f; PointF const auxTextDelta = PointF(dx, 0.0f) + anchorDelta + m_params.m_primaryOffset; for (int i = 0; i < maxTextureSetCount ; ++i) { if (sizes[i]) AddGeometryWithTheSameTextureSet(i, sizes[i], false, length, textDelta, batcher, textures); if (auxSizes[i]) AddGeometryWithTheSameTextureSet(i, auxSizes[i], true, length, auxTextDelta, batcher, textures); } } } //end of df namespace <|endoftext|>
<commit_before>// Copyright (c) 2010 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. // This file implements the ViewGLContext and PbufferGLContext classes. #include <dlfcn.h> #include <GL/glew.h> #include <GL/glxew.h> #include <GL/glx.h> #include <GL/osmew.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "app/x11_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_context_osmesa.h" namespace gfx { typedef GLXContext GLContextHandle; typedef GLXPbuffer PbufferHandle; // This class is a wrapper around a GL context that renders directly to a // window. class ViewGLContext : public GLContext { public: explicit ViewGLContext(gfx::PluginWindowHandle window) : window_(window), context_(NULL) { DCHECK(window); } // Initializes the GL context. bool Initialize(bool multisampled); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: gfx::PluginWindowHandle window_; GLContextHandle context_; DISALLOW_COPY_AND_ASSIGN(ViewGLContext); }; // This class is a wrapper around a GL context used for offscreen rendering. // It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful // rendering. class PbufferGLContext : public GLContext { public: explicit PbufferGLContext() : context_(NULL), pbuffer_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; PbufferHandle pbuffer_; DISALLOW_COPY_AND_ASSIGN(PbufferGLContext); }; // Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower... class PixmapGLContext : public GLContext { public: explicit PixmapGLContext() : context_(NULL), pixmap_(0), glx_pixmap_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; Pixmap pixmap_; GLXPixmap glx_pixmap_; DISALLOW_COPY_AND_ASSIGN(PixmapGLContext); }; // scoped_ptr functor for XFree(). Use as follows: // scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...); // where "XVisualInfo" is any X type that is freed with XFree. class ScopedPtrXFree { public: void operator()(void* x) const { ::XFree(x); } }; // Some versions of NVIDIA's GL libGL.so include a broken version of // dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically // load it, and use glew to dynamically resolve symbols. // See http://code.google.com/p/chromium/issues/detail?id=16800 static bool InitializeOneOff() { static bool initialized = false; if (initialized) return true; osmewInit(); if (!OSMesaCreateContext) { void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); if (!handle) { LOG(ERROR) << "Could not find libGL.so.1"; return false; } // Initializes context-independent parts of GLEW if (glxewInit() != GLEW_OK) { LOG(ERROR) << "glxewInit failed"; return false; } // glxewContextInit really only needs a display connection to // complete, and we don't want to have to create an OpenGL context // just to get access to GLX 1.3 entry points to create pbuffers. // We therefore added a glxewContextInitWithDisplay entry point. Display* display = x11_util::GetXDisplay(); if (glxewContextInitWithDisplay(display) != GLEW_OK) { LOG(ERROR) << "glxewContextInit failed"; return false; } } initialized = true; return true; } bool ViewGLContext::Initialize(bool multisampled) { if (multisampled) { LOG(WARNING) << "Multisampling not implemented."; } Display* display = x11_util::GetXDisplay(); XWindowAttributes attributes; XGetWindowAttributes(display, window_, &attributes); XVisualInfo visual_info_template; visual_info_template.visualid = XVisualIDFromVisual(attributes.visual); int visual_info_count = 0; scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list( XGetVisualInfo(display, VisualIDMask, &visual_info_template, &visual_info_count)); DCHECK(visual_info_list.get()); DCHECK_GT(visual_info_count, 0); context_ = NULL; for (int i = 0; i < visual_info_count; ++i) { context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True); if (context_) break; } if (!context_) { LOG(ERROR) << "Couldn't create GL context."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void ViewGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } } bool ViewGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, window_, context_) != True) { glXDestroyContext(display, context_); context_ = 0; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool ViewGLContext::IsCurrent() { return glXGetCurrentDrawable() == window_ && glXGetCurrentContext() == context_; } bool ViewGLContext::IsOffscreen() { return false; } void ViewGLContext::SwapBuffers() { Display* display = x11_util::GetXDisplay(); glXSwapBuffers(display, window_); } gfx::Size ViewGLContext::GetSize() { XWindowAttributes attributes; Display* display = x11_util::GetXDisplay(); XGetWindowAttributes(display, window_, &attributes); return gfx::Size(attributes.width, attributes.height); } void* ViewGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window, bool multisampled) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { // TODO(apatrick): Support OSMesa rendering to a window on Linux. NOTREACHED() << "OSMesa rendering to a window is not yet implemented."; return NULL; } else { scoped_ptr<ViewGLContext> context(new ViewGLContext(window)); if (!context->Initialize(multisampled)) return NULL; return context.release(); } } bool PbufferGLContext::Initialize(void* shared_handle) { if (!glXChooseFBConfig || !glXCreateNewContext || !glXCreatePbuffer || !glXDestroyPbuffer) { LOG(ERROR) << "Pbuffer support not available."; return false; } static const int config_attributes[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DOUBLEBUFFER, 0, 0 }; Display* display = x11_util::GetXDisplay(); int nelements = 0; // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient. scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config( glXChooseFBConfig(display, 0, config_attributes, &nelements)); if (!config.get()) { LOG(ERROR) << "glXChooseFBConfig failed."; return false; } if (!nelements) { LOG(ERROR) << "glXChooseFBConfig returned 0 elements."; return false; } context_ = glXCreateNewContext(display, config.get()[0], GLX_RGBA_TYPE, static_cast<GLContextHandle>(shared_handle), True); if (!context_) { LOG(ERROR) << "glXCreateNewContext failed."; return false; } static const int pbuffer_attributes[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0 }; pbuffer_ = glXCreatePbuffer(display, config.get()[0], pbuffer_attributes); if (!pbuffer_) { Destroy(); LOG(ERROR) << "glXCreatePbuffer failed."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PbufferGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (pbuffer_) { glXDestroyPbuffer(display, pbuffer_); pbuffer_ = 0; } } bool PbufferGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, pbuffer_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PbufferGLContext::IsCurrent() { return glXGetCurrentDrawable() == pbuffer_ && glXGetCurrentContext() == context_; } bool PbufferGLContext::IsOffscreen() { return true; } void PbufferGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer."; } gfx::Size PbufferGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pbuffer."; return gfx::Size(1, 1); } void* PbufferGLContext::GetHandle() { return context_; } bool PixmapGLContext::Initialize(void* shared_handle) { LOG(INFO) << "GL context: using pixmaps."; if (!glXChooseVisual || !glXCreateGLXPixmap || !glXDestroyGLXPixmap) { LOG(ERROR) << "Pixmap support not available."; return false; } static int attributes[] = { GLX_RGBA, 0 }; Display* display = x11_util::GetXDisplay(); int screen = DefaultScreen(display); scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info( glXChooseVisual(display, screen, attributes)); if (!visual_info.get()) { LOG(ERROR) << "glXChooseVisual failed."; return false; } context_ = glXCreateContext(display, visual_info.get(), static_cast<GLContextHandle>(shared_handle), True); if (!context_) { LOG(ERROR) << "glXCreateContext failed."; return false; } pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1, visual_info->depth); if (!pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_); if (!glx_pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PixmapGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (glx_pixmap_) { glXDestroyGLXPixmap(display, glx_pixmap_); glx_pixmap_ = 0; } if (pixmap_) { XFreePixmap(display, pixmap_); pixmap_ = 0; } } bool PixmapGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, glx_pixmap_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PixmapGLContext::IsCurrent() { return glXGetCurrentDrawable() == glx_pixmap_ && glXGetCurrentContext() == context_; } bool PixmapGLContext::IsOffscreen() { return true; } void PixmapGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pixmap."; } gfx::Size PixmapGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pixmap."; return gfx::Size(1, 1); } void* PixmapGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } else { scoped_ptr<PbufferGLContext> context(new PbufferGLContext); if (context->Initialize(shared_handle)) return context.release(); scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext); if (context_pixmap->Initialize(shared_handle)) return context_pixmap.release(); return NULL; } } } // namespace gfx <commit_msg>Added warning if GLX version is less than 1.3. Pbuffers need GLX 1.3 and the pixmap fallback for 1.2 does not work on all systems. TEST=try BUG=none<commit_after>// Copyright (c) 2010 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. // This file implements the ViewGLContext and PbufferGLContext classes. #include <dlfcn.h> #include <GL/glew.h> #include <GL/glxew.h> #include <GL/glx.h> #include <GL/osmew.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include "app/x11_util.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "app/gfx/gl/gl_context.h" #include "app/gfx/gl/gl_context_osmesa.h" namespace gfx { typedef GLXContext GLContextHandle; typedef GLXPbuffer PbufferHandle; // This class is a wrapper around a GL context that renders directly to a // window. class ViewGLContext : public GLContext { public: explicit ViewGLContext(gfx::PluginWindowHandle window) : window_(window), context_(NULL) { DCHECK(window); } // Initializes the GL context. bool Initialize(bool multisampled); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: gfx::PluginWindowHandle window_; GLContextHandle context_; DISALLOW_COPY_AND_ASSIGN(ViewGLContext); }; // This class is a wrapper around a GL context used for offscreen rendering. // It is initially backed by a 1x1 pbuffer. Use it to create an FBO to do useful // rendering. class PbufferGLContext : public GLContext { public: explicit PbufferGLContext() : context_(NULL), pbuffer_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; PbufferHandle pbuffer_; DISALLOW_COPY_AND_ASSIGN(PbufferGLContext); }; // Backup context if Pbuffers (GLX 1.3) aren't supported. May run slower... class PixmapGLContext : public GLContext { public: explicit PixmapGLContext() : context_(NULL), pixmap_(0), glx_pixmap_(0) { } // Initializes the GL context. bool Initialize(void* shared_handle); virtual void Destroy(); virtual bool MakeCurrent(); virtual bool IsCurrent(); virtual bool IsOffscreen(); virtual void SwapBuffers(); virtual gfx::Size GetSize(); virtual void* GetHandle(); private: GLContextHandle context_; Pixmap pixmap_; GLXPixmap glx_pixmap_; DISALLOW_COPY_AND_ASSIGN(PixmapGLContext); }; // scoped_ptr functor for XFree(). Use as follows: // scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> foo(...); // where "XVisualInfo" is any X type that is freed with XFree. class ScopedPtrXFree { public: void operator()(void* x) const { ::XFree(x); } }; // Some versions of NVIDIA's GL libGL.so include a broken version of // dlopen/dlsym, and so linking it into chrome breaks it. So we dynamically // load it, and use glew to dynamically resolve symbols. // See http://code.google.com/p/chromium/issues/detail?id=16800 static bool InitializeOneOff() { static bool initialized = false; if (initialized) return true; osmewInit(); if (!OSMesaCreateContext) { void* handle = dlopen("libGL.so.1", RTLD_LAZY | RTLD_GLOBAL); if (!handle) { LOG(ERROR) << "Could not find libGL.so.1"; return false; } // Initializes context-independent parts of GLEW if (glxewInit() != GLEW_OK) { LOG(ERROR) << "glxewInit failed"; return false; } // glxewContextInit really only needs a display connection to // complete, and we don't want to have to create an OpenGL context // just to get access to GLX 1.3 entry points to create pbuffers. // We therefore added a glxewContextInitWithDisplay entry point. Display* display = x11_util::GetXDisplay(); if (glxewContextInitWithDisplay(display) != GLEW_OK) { LOG(ERROR) << "glxewContextInit failed"; return false; } int major, minor; if (!glXQueryVersion(display, &major, &minor)) { LOG(ERROR) << "glxQueryVersion failed"; return false; } if (major == 1 && minor < 3) { LOG(WARNING) << "GLX 1.3 or later is recommended."; } } initialized = true; return true; } bool ViewGLContext::Initialize(bool multisampled) { if (multisampled) { LOG(WARNING) << "Multisampling not implemented."; } Display* display = x11_util::GetXDisplay(); XWindowAttributes attributes; XGetWindowAttributes(display, window_, &attributes); XVisualInfo visual_info_template; visual_info_template.visualid = XVisualIDFromVisual(attributes.visual); int visual_info_count = 0; scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info_list( XGetVisualInfo(display, VisualIDMask, &visual_info_template, &visual_info_count)); DCHECK(visual_info_list.get()); DCHECK_GT(visual_info_count, 0); context_ = NULL; for (int i = 0; i < visual_info_count; ++i) { context_ = glXCreateContext(display, visual_info_list.get() + i, 0, True); if (context_) break; } if (!context_) { LOG(ERROR) << "Couldn't create GL context."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void ViewGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } } bool ViewGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, window_, context_) != True) { glXDestroyContext(display, context_); context_ = 0; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool ViewGLContext::IsCurrent() { return glXGetCurrentDrawable() == window_ && glXGetCurrentContext() == context_; } bool ViewGLContext::IsOffscreen() { return false; } void ViewGLContext::SwapBuffers() { Display* display = x11_util::GetXDisplay(); glXSwapBuffers(display, window_); } gfx::Size ViewGLContext::GetSize() { XWindowAttributes attributes; Display* display = x11_util::GetXDisplay(); XGetWindowAttributes(display, window_, &attributes); return gfx::Size(attributes.width, attributes.height); } void* ViewGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateViewGLContext(gfx::PluginWindowHandle window, bool multisampled) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { // TODO(apatrick): Support OSMesa rendering to a window on Linux. NOTREACHED() << "OSMesa rendering to a window is not yet implemented."; return NULL; } else { scoped_ptr<ViewGLContext> context(new ViewGLContext(window)); if (!context->Initialize(multisampled)) return NULL; return context.release(); } } bool PbufferGLContext::Initialize(void* shared_handle) { if (!glXChooseFBConfig || !glXCreateNewContext || !glXCreatePbuffer || !glXDestroyPbuffer) { LOG(ERROR) << "Pbuffer support not available."; return false; } static const int config_attributes[] = { GLX_DRAWABLE_TYPE, GLX_PBUFFER_BIT, GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DOUBLEBUFFER, 0, 0 }; Display* display = x11_util::GetXDisplay(); int nelements = 0; // TODO(kbr): figure out whether hardcoding screen to 0 is sufficient. scoped_ptr_malloc<GLXFBConfig, ScopedPtrXFree> config( glXChooseFBConfig(display, 0, config_attributes, &nelements)); if (!config.get()) { LOG(ERROR) << "glXChooseFBConfig failed."; return false; } if (!nelements) { LOG(ERROR) << "glXChooseFBConfig returned 0 elements."; return false; } context_ = glXCreateNewContext(display, config.get()[0], GLX_RGBA_TYPE, static_cast<GLContextHandle>(shared_handle), True); if (!context_) { LOG(ERROR) << "glXCreateNewContext failed."; return false; } static const int pbuffer_attributes[] = { GLX_PBUFFER_WIDTH, 1, GLX_PBUFFER_HEIGHT, 1, 0 }; pbuffer_ = glXCreatePbuffer(display, config.get()[0], pbuffer_attributes); if (!pbuffer_) { Destroy(); LOG(ERROR) << "glXCreatePbuffer failed."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PbufferGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (pbuffer_) { glXDestroyPbuffer(display, pbuffer_); pbuffer_ = 0; } } bool PbufferGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, pbuffer_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PbufferGLContext::IsCurrent() { return glXGetCurrentDrawable() == pbuffer_ && glXGetCurrentContext() == context_; } bool PbufferGLContext::IsOffscreen() { return true; } void PbufferGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pbuffer."; } gfx::Size PbufferGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pbuffer."; return gfx::Size(1, 1); } void* PbufferGLContext::GetHandle() { return context_; } bool PixmapGLContext::Initialize(void* shared_handle) { LOG(INFO) << "GL context: using pixmaps."; if (!glXChooseVisual || !glXCreateGLXPixmap || !glXDestroyGLXPixmap) { LOG(ERROR) << "Pixmap support not available."; return false; } static int attributes[] = { GLX_RGBA, 0 }; Display* display = x11_util::GetXDisplay(); int screen = DefaultScreen(display); scoped_ptr_malloc<XVisualInfo, ScopedPtrXFree> visual_info( glXChooseVisual(display, screen, attributes)); if (!visual_info.get()) { LOG(ERROR) << "glXChooseVisual failed."; return false; } context_ = glXCreateContext(display, visual_info.get(), static_cast<GLContextHandle>(shared_handle), True); if (!context_) { LOG(ERROR) << "glXCreateContext failed."; return false; } pixmap_ = XCreatePixmap(display, RootWindow(display, screen), 1, 1, visual_info->depth); if (!pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } glx_pixmap_ = glXCreateGLXPixmap(display, visual_info.get(), pixmap_); if (!glx_pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } if (!MakeCurrent()) { Destroy(); LOG(ERROR) << "Couldn't make context current for initialization."; return false; } if (!InitializeGLEW()) { Destroy(); return false; } if (!InitializeCommon()) { Destroy(); return false; } return true; } void PixmapGLContext::Destroy() { Display* display = x11_util::GetXDisplay(); Bool result = glXMakeCurrent(display, 0, 0); // glXMakeCurrent isn't supposed to fail when unsetting the context, unless // we have pending draws on an invalid window - which shouldn't be the case // here. DCHECK(result); if (context_) { glXDestroyContext(display, context_); context_ = NULL; } if (glx_pixmap_) { glXDestroyGLXPixmap(display, glx_pixmap_); glx_pixmap_ = 0; } if (pixmap_) { XFreePixmap(display, pixmap_); pixmap_ = 0; } } bool PixmapGLContext::MakeCurrent() { if (IsCurrent()) { return true; } Display* display = x11_util::GetXDisplay(); if (glXMakeCurrent(display, glx_pixmap_, context_) != True) { glXDestroyContext(display, context_); context_ = NULL; LOG(ERROR) << "Couldn't make context current."; return false; } return true; } bool PixmapGLContext::IsCurrent() { return glXGetCurrentDrawable() == glx_pixmap_ && glXGetCurrentContext() == context_; } bool PixmapGLContext::IsOffscreen() { return true; } void PixmapGLContext::SwapBuffers() { NOTREACHED() << "Attempted to call SwapBuffers on a pixmap."; } gfx::Size PixmapGLContext::GetSize() { NOTREACHED() << "Should not be requesting size of this pixmap."; return gfx::Size(1, 1); } void* PixmapGLContext::GetHandle() { return context_; } GLContext* GLContext::CreateOffscreenGLContext(void* shared_handle) { if (!InitializeOneOff()) return NULL; if (OSMesaCreateContext) { scoped_ptr<OSMesaGLContext> context(new OSMesaGLContext); if (!context->Initialize(shared_handle)) return NULL; return context.release(); } else { scoped_ptr<PbufferGLContext> context(new PbufferGLContext); if (context->Initialize(shared_handle)) return context.release(); scoped_ptr<PixmapGLContext> context_pixmap(new PixmapGLContext); if (context_pixmap->Initialize(shared_handle)) return context_pixmap.release(); return NULL; } } } // namespace gfx <|endoftext|>
<commit_before>/*============================================================================== Copyright (c) Kapteyn Astronomical Institute University of Groningen, Groningen, Netherlands. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute, and was supported through the European Research Council grant nr. 291531. ==============================================================================*/ // MRMLDisplayableManager includes #include "vtkMRMLAstroBeamDisplayableManager.h" // MRML includes #include <vtkMRMLAbstractViewNode.h> #include <vtkMRMLAstroVolumeDisplayNode.h> #include <vtkMRMLAstroVolumeNode.h> #include <vtkMRMLLogic.h> #include <vtkMRMLSliceLayerLogic.h> #include <vtkMRMLSliceLogic.h> #include <vtkMRMLSliceNode.h> #include <vtkMRMLViewNode.h> // VTK includes #include <vtkActor2D.h> #include <vtkActor2DCollection.h> #include <vtkAxisActor2D.h> #include <vtkCamera.h> #include <vtkCellArray.h> #include <vtkGeneralTransform.h> #include <vtkMatrix4x4.h> #include <vtkNew.h> #include <vtkObjectFactory.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty2D.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkPolyDataMapper2D.h> #include <vtkLine.h> #include <vtksys/SystemTools.hxx> #include <vtkTransform.h> // STD includes #include <sstream> // SlicerQt includes #include <qSlicerApplication.h> // vtkSlicer includes #include <vtkSlicerApplicationLogic.h> // Constants static const int RENDERER_LAYER = 1; // layer ID where the orientation marker will be displayed const double PI_2 = PI * 0.5; //--------------------------------------------------------------------------- class vtkAstroBeamRendererUpdateObserver : public vtkCommand { public: static vtkAstroBeamRendererUpdateObserver *New() { return new vtkAstroBeamRendererUpdateObserver; } vtkAstroBeamRendererUpdateObserver() { this->DisplayableManager = 0; } virtual void Execute(vtkObject* vtkNotUsed(wdg), unsigned long vtkNotUsed(event), void* vtkNotUsed(calldata)) { if (this->DisplayableManager) { this->DisplayableManager->UpdateFromRenderer(); } } vtkWeakPointer<vtkMRMLAstroBeamDisplayableManager> DisplayableManager; }; namespace { //---------------------------------------------------------------------------- template <typename T> T StringToNumber(const char* num) { std::stringstream ss; ss << num; T result; return ss >> result ? result : 0; } //---------------------------------------------------------------------------- double StringToDouble(const char* str) { return StringToNumber<double>(str); } }// end namespace //--------------------------------------------------------------------------- vtkStandardNewMacro(vtkMRMLAstroBeamDisplayableManager); //--------------------------------------------------------------------------- class vtkMRMLAstroBeamDisplayableManager::vtkInternal { public: vtkInternal(vtkMRMLAstroBeamDisplayableManager * external); ~vtkInternal(); void SetupMarkerRenderer(); void AddRendererUpdateObserver(vtkRenderer* renderer); void RemoveRendererUpdateObserver(); void SetupBeam(); void UpdateBeam(); void ShowActors(bool show); vtkSmartPointer<vtkRenderer> MarkerRenderer; vtkSmartPointer<vtkAstroBeamRendererUpdateObserver> RendererUpdateObserver; vtkSmartPointer<vtkPoints> beamPoints; vtkSmartPointer<vtkCellArray> beamCellArray; vtkSmartPointer<vtkPolyData> beamPolyData; vtkSmartPointer<vtkActor2D> beamActor; vtkSmartPointer<vtkPolyDataMapper2D> beamMapper; vtkSmartPointer<vtkCollection> col; int RendererUpdateObservationId; vtkWeakPointer<vtkRenderer> ObservedRenderer; bool ActorsAddedToRenderer; vtkMRMLAstroBeamDisplayableManager* External; qSlicerApplication* app; }; //--------------------------------------------------------------------------- // vtkInternal methods //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::vtkInternal::vtkInternal(vtkMRMLAstroBeamDisplayableManager * external) { this->External = external; this->RendererUpdateObserver = vtkSmartPointer<vtkAstroBeamRendererUpdateObserver>::New(); this->RendererUpdateObserver->DisplayableManager = this->External; this->RendererUpdateObservationId = 0; this->ActorsAddedToRenderer = false; this->MarkerRenderer = vtkSmartPointer<vtkRenderer>::New(); this->beamPoints = vtkSmartPointer<vtkPoints>::New(); this->beamCellArray = vtkSmartPointer<vtkCellArray>::New(); this->beamPolyData = vtkSmartPointer<vtkPolyData>::New(); this->beamActor = vtkSmartPointer<vtkActor2D>::New(); this->beamMapper = vtkSmartPointer<vtkPolyDataMapper2D>::New(); this->col = vtkSmartPointer<vtkCollection>::New(); this->app = 0; } //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::vtkInternal::~vtkInternal() { RemoveRendererUpdateObserver(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::ShowActors(bool show) { if (this->ActorsAddedToRenderer == show) { // no change return; } if (show) { this->MarkerRenderer->AddViewProp(this->beamActor); } else { this->MarkerRenderer->RemoveViewProp(this->beamActor); } this->ActorsAddedToRenderer = show; } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::AddRendererUpdateObserver(vtkRenderer* renderer) { RemoveRendererUpdateObserver(); if (renderer) { this->ObservedRenderer = renderer; this->RendererUpdateObservationId = renderer->AddObserver(vtkCommand::StartEvent, this->RendererUpdateObserver); } } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::RemoveRendererUpdateObserver() { if (this->ObservedRenderer) { this->ObservedRenderer->RemoveObserver(this->RendererUpdateObservationId); this->RendererUpdateObservationId = 0; this->ObservedRenderer = NULL; } } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::SetupMarkerRenderer() { vtkRenderer* renderer = this->External->GetRenderer(); if (renderer==NULL) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroBeamDisplayableManager" "::vtkInternal::SetupMarkerRenderer() failed: renderer is invalid"); return; } this->MarkerRenderer->InteractiveOff(); vtkRenderWindow* renderWindow = renderer->GetRenderWindow(); if (renderWindow->GetNumberOfLayers() < RENDERER_LAYER+1) { renderWindow->SetNumberOfLayers( RENDERER_LAYER+1 ); } this->MarkerRenderer->SetLayer(RENDERER_LAYER); renderWindow->AddRenderer(this->MarkerRenderer); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::SetupBeam() { this->beamActor->PickableOff(); this->beamActor->DragableOff(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::UpdateBeam() { // clean the attributes before updating this->beamPoints->Initialize(); this->beamPoints->Squeeze(); this->beamCellArray->Initialize(); this->beamCellArray->Squeeze(); vtkMRMLAbstractViewNode* viewNode = vtkMRMLAbstractViewNode::SafeDownCast (this->External->GetMRMLDisplayableNode()); if (!viewNode) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroBeamDisplayableManager::UpdateBeam()" " failed: view node is invalid."); this->ShowActors(false); return; } vtkMRMLSliceNode* sliceNode = vtkMRMLSliceNode::SafeDownCast(viewNode); if (!sliceNode) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroBeamDisplayableManager::UpdateBeam()" " failed: displayable node is invalid."); this->ShowActors(false); return; } if (!sliceNode->GetAttribute("SlicerAstro.Beam")) { return; } if (sliceNode->GetOrientation().compare("XY") || !strcmp(sliceNode->GetAttribute("SlicerAstro.Beam"), "off")) { this->ShowActors(false); return; } // get the Logics this->app = qSlicerApplication::application(); vtkMRMLSliceLogic* sliceLogic = this->app->applicationLogic()->GetSliceLogic(sliceNode); if (!sliceLogic) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroTwoDAxesDisplayableManager::UpdateAxes()" " failed: sliceLogic node is invalid."); this->ShowActors(false); return; } this->col->AddItem(sliceLogic->GetBackgroundLayer()); this->col->AddItem(sliceLogic->GetForegroundLayer()); this->col->AddItem(sliceLogic->GetLabelLayer()); bool hasVolume = false; for (int layer = 0; layer < this->col->GetNumberOfItems(); layer++) { vtkMRMLSliceLayerLogic* sliceLayerLogic = vtkMRMLSliceLayerLogic::SafeDownCast (this->col->GetItemAsObject(layer)); if(!sliceLayerLogic) { return; } vtkMRMLAstroVolumeNode* volumeNode = vtkMRMLAstroVolumeNode::SafeDownCast (sliceLayerLogic->GetVolumeNode()); if (!volumeNode) { continue; } if (!strcmp(volumeNode->GetAttribute("SlicerAstro.BMAJ"), "UNDEFINED") || !strcmp(volumeNode->GetAttribute("SlicerAstro.BMIN"), "UNDEFINED") || !strcmp(volumeNode->GetAttribute("SlicerAstro.BPA"), "UNDEFINED")) { continue; } hasVolume = true; sliceNode->UpdateMatrices(); sliceLayerLogic->UpdateTransforms(); vtkNew<vtkTransform> transform; double BPA = StringToDouble(volumeNode->GetAttribute("SlicerAstro.BPA")); transform->RotateZ(BPA); const double degtorad = atan(1.) / 45.; vtkGeneralTransform* ijkToXY = sliceLayerLogic->GetXYToIJKTransform(); ijkToXY->Inverse(); double BMAJ = StringToDouble(volumeNode->GetAttribute("SlicerAstro.BMAJ")); double BMIN = StringToDouble(volumeNode->GetAttribute("SlicerAstro.BMIN")); double CDELT1 = StringToDouble(volumeNode->GetAttribute("SlicerAstro.CDELT1")); double CDELT2 = StringToDouble(volumeNode->GetAttribute("SlicerAstro.CDELT2")); double NAXIS1 = StringToDouble(volumeNode->GetAttribute("SlicerAstro.NAXIS1")); double aCosPixel = BMAJ * cos(BPA * degtorad) / CDELT1; double aSinPixel = BMAJ * sin(BPA * degtorad) / CDELT2; double a = sqrt(aCosPixel * aCosPixel + aSinPixel * aSinPixel); double bCosPixel = BMIN * cos((BPA + 90) * degtorad) / CDELT1; double bSinPixel = BMIN * sin((BPA + 90) * degtorad) / CDELT2; double b = sqrt(bCosPixel * bCosPixel + bSinPixel * bSinPixel); double centerX = NAXIS1 - a * 3; double centerY = b * 3; double ijk[3], xy[3]; // add points for (int ii = 0; ii <= 60; ii++) { double rot = ii * (2 * PI / 60.); ijk[0] = a * cos(rot); ijk[1] = b * sin(rot); ijk[2] = 0.; transform->TransformPoint(ijk, ijk); ijk[0] += centerX; ijk[1] += centerY; ijkToXY->TransformPoint(ijk, xy); this->beamPoints->InsertPoint(ii, xy[0], xy[1], 0); } int n = this->beamPoints->GetNumberOfPoints(); // unify the points with lines std::vector<vtkSmartPointer<vtkLine> > lines; for (int ii = 0; ii < n - 1; ii++) { vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New(); lines.push_back(line); } for (int ii = 0; ii < n - 1; ii++) { lines[ii]->GetPointIds()->SetId(0, ii); lines[ii]->GetPointIds()->SetId(1, ii + 1); } // create the cellArray for (int ii = 0; ii < n - 1; ii++) { this->beamCellArray->InsertNextCell(lines[ii]); } // setup the mapper and actor this->beamPolyData->SetPoints(this->beamPoints); this->beamPolyData->SetLines(this->beamCellArray); this->beamMapper->SetInputData(this->beamPolyData); this->beamActor->SetMapper(this->beamMapper); this->beamActor->GetProperty()->SetLineWidth(1.5); this->MarkerRenderer->AddActor2D(this->beamActor); this->ShowActors(true); break; } if (!hasVolume) { this->ShowActors(false); } } //--------------------------------------------------------------------------- // vtkMRMLRulerDisplayableManager methods //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::vtkMRMLAstroBeamDisplayableManager() { this->Internal = new vtkInternal(this); } //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::~vtkMRMLAstroBeamDisplayableManager() { delete this->Internal; } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::Create() { this->Internal->SetupMarkerRenderer(); this->Internal->SetupBeam(); this->Superclass::Create(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::UpdateFromViewNode() { // View node is changed, which may mean that either the marker type (visibility), size, or orientation is changed this->Internal->UpdateBeam(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::OnMRMLDisplayableNodeModifiedEvent(vtkObject* vtkNotUsed(caller)) { // view node is changed this->UpdateFromViewNode(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::UpdateFromRenderer() { // Rendering is performed, so let's re-render the marker with up-to-date orientation this->Internal->UpdateBeam(); } <commit_msg>BUG: fix transform copy in Beam display manager<commit_after>/*============================================================================== Copyright (c) Kapteyn Astronomical Institute University of Groningen, Groningen, Netherlands. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Davide Punzo, Kapteyn Astronomical Institute, and was supported through the European Research Council grant nr. 291531. ==============================================================================*/ // MRMLDisplayableManager includes #include "vtkMRMLAstroBeamDisplayableManager.h" // MRML includes #include <vtkMRMLAbstractViewNode.h> #include <vtkMRMLAstroVolumeDisplayNode.h> #include <vtkMRMLAstroVolumeNode.h> #include <vtkMRMLLogic.h> #include <vtkMRMLSliceLayerLogic.h> #include <vtkMRMLSliceLogic.h> #include <vtkMRMLSliceNode.h> #include <vtkMRMLViewNode.h> // VTK includes #include <vtkActor2D.h> #include <vtkActor2DCollection.h> #include <vtkAxisActor2D.h> #include <vtkCamera.h> #include <vtkCellArray.h> #include <vtkGeneralTransform.h> #include <vtkMatrix4x4.h> #include <vtkNew.h> #include <vtkObjectFactory.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty2D.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkPolyDataMapper2D.h> #include <vtkLine.h> #include <vtksys/SystemTools.hxx> #include <vtkTransform.h> // STD includes #include <sstream> // SlicerQt includes #include <qSlicerApplication.h> // vtkSlicer includes #include <vtkSlicerApplicationLogic.h> // Constants static const int RENDERER_LAYER = 1; // layer ID where the orientation marker will be displayed const double PI_2 = PI * 0.5; //--------------------------------------------------------------------------- class vtkAstroBeamRendererUpdateObserver : public vtkCommand { public: static vtkAstroBeamRendererUpdateObserver *New() { return new vtkAstroBeamRendererUpdateObserver; } vtkAstroBeamRendererUpdateObserver() { this->DisplayableManager = 0; } virtual void Execute(vtkObject* vtkNotUsed(wdg), unsigned long vtkNotUsed(event), void* vtkNotUsed(calldata)) { if (this->DisplayableManager) { this->DisplayableManager->UpdateFromRenderer(); } } vtkWeakPointer<vtkMRMLAstroBeamDisplayableManager> DisplayableManager; }; namespace { //---------------------------------------------------------------------------- template <typename T> T StringToNumber(const char* num) { std::stringstream ss; ss << num; T result; return ss >> result ? result : 0; } //---------------------------------------------------------------------------- double StringToDouble(const char* str) { return StringToNumber<double>(str); } }// end namespace //--------------------------------------------------------------------------- vtkStandardNewMacro(vtkMRMLAstroBeamDisplayableManager); //--------------------------------------------------------------------------- class vtkMRMLAstroBeamDisplayableManager::vtkInternal { public: vtkInternal(vtkMRMLAstroBeamDisplayableManager * external); ~vtkInternal(); void SetupMarkerRenderer(); void AddRendererUpdateObserver(vtkRenderer* renderer); void RemoveRendererUpdateObserver(); void SetupBeam(); void UpdateBeam(); void ShowActors(bool show); vtkSmartPointer<vtkRenderer> MarkerRenderer; vtkSmartPointer<vtkAstroBeamRendererUpdateObserver> RendererUpdateObserver; vtkSmartPointer<vtkPoints> beamPoints; vtkSmartPointer<vtkCellArray> beamCellArray; vtkSmartPointer<vtkPolyData> beamPolyData; vtkSmartPointer<vtkActor2D> beamActor; vtkSmartPointer<vtkPolyDataMapper2D> beamMapper; vtkSmartPointer<vtkCollection> col; int RendererUpdateObservationId; vtkWeakPointer<vtkRenderer> ObservedRenderer; bool ActorsAddedToRenderer; vtkMRMLAstroBeamDisplayableManager* External; qSlicerApplication* app; }; //--------------------------------------------------------------------------- // vtkInternal methods //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::vtkInternal::vtkInternal(vtkMRMLAstroBeamDisplayableManager * external) { this->External = external; this->RendererUpdateObserver = vtkSmartPointer<vtkAstroBeamRendererUpdateObserver>::New(); this->RendererUpdateObserver->DisplayableManager = this->External; this->RendererUpdateObservationId = 0; this->ActorsAddedToRenderer = false; this->MarkerRenderer = vtkSmartPointer<vtkRenderer>::New(); this->beamPoints = vtkSmartPointer<vtkPoints>::New(); this->beamCellArray = vtkSmartPointer<vtkCellArray>::New(); this->beamPolyData = vtkSmartPointer<vtkPolyData>::New(); this->beamActor = vtkSmartPointer<vtkActor2D>::New(); this->beamMapper = vtkSmartPointer<vtkPolyDataMapper2D>::New(); this->col = vtkSmartPointer<vtkCollection>::New(); this->app = 0; } //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::vtkInternal::~vtkInternal() { RemoveRendererUpdateObserver(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::ShowActors(bool show) { if (this->ActorsAddedToRenderer == show) { // no change return; } if (show) { this->MarkerRenderer->AddViewProp(this->beamActor); } else { this->MarkerRenderer->RemoveViewProp(this->beamActor); } this->ActorsAddedToRenderer = show; } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::AddRendererUpdateObserver(vtkRenderer* renderer) { RemoveRendererUpdateObserver(); if (renderer) { this->ObservedRenderer = renderer; this->RendererUpdateObservationId = renderer->AddObserver(vtkCommand::StartEvent, this->RendererUpdateObserver); } } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::RemoveRendererUpdateObserver() { if (this->ObservedRenderer) { this->ObservedRenderer->RemoveObserver(this->RendererUpdateObservationId); this->RendererUpdateObservationId = 0; this->ObservedRenderer = NULL; } } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::SetupMarkerRenderer() { vtkRenderer* renderer = this->External->GetRenderer(); if (renderer==NULL) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroBeamDisplayableManager" "::vtkInternal::SetupMarkerRenderer() failed: renderer is invalid"); return; } this->MarkerRenderer->InteractiveOff(); vtkRenderWindow* renderWindow = renderer->GetRenderWindow(); if (renderWindow->GetNumberOfLayers() < RENDERER_LAYER+1) { renderWindow->SetNumberOfLayers( RENDERER_LAYER+1 ); } this->MarkerRenderer->SetLayer(RENDERER_LAYER); renderWindow->AddRenderer(this->MarkerRenderer); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::SetupBeam() { this->beamActor->PickableOff(); this->beamActor->DragableOff(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::vtkInternal::UpdateBeam() { // clean the attributes before updating this->beamPoints->Initialize(); this->beamPoints->Squeeze(); this->beamCellArray->Initialize(); this->beamCellArray->Squeeze(); vtkMRMLAbstractViewNode* viewNode = vtkMRMLAbstractViewNode::SafeDownCast (this->External->GetMRMLDisplayableNode()); if (!viewNode) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroBeamDisplayableManager::UpdateBeam()" " failed: view node is invalid."); this->ShowActors(false); return; } vtkMRMLSliceNode* sliceNode = vtkMRMLSliceNode::SafeDownCast(viewNode); if (!sliceNode) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroBeamDisplayableManager::UpdateBeam()" " failed: displayable node is invalid."); this->ShowActors(false); return; } if (!sliceNode->GetAttribute("SlicerAstro.Beam")) { return; } if (sliceNode->GetOrientation().compare("XY") || !strcmp(sliceNode->GetAttribute("SlicerAstro.Beam"), "off")) { this->ShowActors(false); return; } // get the Logics this->app = qSlicerApplication::application(); vtkMRMLSliceLogic* sliceLogic = this->app->applicationLogic()->GetSliceLogic(sliceNode); if (!sliceLogic) { vtkErrorWithObjectMacro(this->External, "vtkMRMLAstroTwoDAxesDisplayableManager::UpdateAxes()" " failed: sliceLogic node is invalid."); this->ShowActors(false); return; } this->col->AddItem(sliceLogic->GetBackgroundLayer()); this->col->AddItem(sliceLogic->GetForegroundLayer()); this->col->AddItem(sliceLogic->GetLabelLayer()); bool hasVolume = false; for (int layer = 0; layer < this->col->GetNumberOfItems(); layer++) { vtkMRMLSliceLayerLogic* sliceLayerLogic = vtkMRMLSliceLayerLogic::SafeDownCast (this->col->GetItemAsObject(layer)); if(!sliceLayerLogic) { return; } vtkMRMLAstroVolumeNode* volumeNode = vtkMRMLAstroVolumeNode::SafeDownCast (sliceLayerLogic->GetVolumeNode()); if (!volumeNode) { continue; } if (!strcmp(volumeNode->GetAttribute("SlicerAstro.BMAJ"), "UNDEFINED") || !strcmp(volumeNode->GetAttribute("SlicerAstro.BMIN"), "UNDEFINED") || !strcmp(volumeNode->GetAttribute("SlicerAstro.BPA"), "UNDEFINED")) { continue; } hasVolume = true; sliceNode->UpdateMatrices(); sliceLayerLogic->UpdateTransforms(); vtkNew<vtkTransform> transform; double BPA = StringToDouble(volumeNode->GetAttribute("SlicerAstro.BPA")); transform->RotateZ(BPA); const double degtorad = atan(1.) / 45.; vtkNew<vtkGeneralTransform> ijkToXY; ijkToXY->DeepCopy(sliceLayerLogic->GetXYToIJKTransform()); ijkToXY->Inverse(); double BMAJ = StringToDouble(volumeNode->GetAttribute("SlicerAstro.BMAJ")); double BMIN = StringToDouble(volumeNode->GetAttribute("SlicerAstro.BMIN")); double CDELT1 = StringToDouble(volumeNode->GetAttribute("SlicerAstro.CDELT1")); double CDELT2 = StringToDouble(volumeNode->GetAttribute("SlicerAstro.CDELT2")); double NAXIS1 = StringToDouble(volumeNode->GetAttribute("SlicerAstro.NAXIS1")); double aCosPixel = BMAJ * cos(BPA * degtorad) / CDELT1; double aSinPixel = BMAJ * sin(BPA * degtorad) / CDELT2; double a = sqrt(aCosPixel * aCosPixel + aSinPixel * aSinPixel); double bCosPixel = BMIN * cos((BPA + 90) * degtorad) / CDELT1; double bSinPixel = BMIN * sin((BPA + 90) * degtorad) / CDELT2; double b = sqrt(bCosPixel * bCosPixel + bSinPixel * bSinPixel); double centerX = NAXIS1 - a * 3; double centerY = b * 3; double ijk[3], xy[3]; // add points for (int ii = 0; ii <= 60; ii++) { double rot = ii * (2 * PI / 60.); ijk[0] = a * cos(rot); ijk[1] = b * sin(rot); ijk[2] = 0.; transform->TransformPoint(ijk, ijk); ijk[0] += centerX; ijk[1] += centerY; ijkToXY->TransformPoint(ijk, xy); this->beamPoints->InsertPoint(ii, xy[0], xy[1], 0); } int n = this->beamPoints->GetNumberOfPoints(); // unify the points with lines std::vector<vtkSmartPointer<vtkLine> > lines; for (int ii = 0; ii < n - 1; ii++) { vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New(); lines.push_back(line); } for (int ii = 0; ii < n - 1; ii++) { lines[ii]->GetPointIds()->SetId(0, ii); lines[ii]->GetPointIds()->SetId(1, ii + 1); } // create the cellArray for (int ii = 0; ii < n - 1; ii++) { this->beamCellArray->InsertNextCell(lines[ii]); } // setup the mapper and actor this->beamPolyData->SetPoints(this->beamPoints); this->beamPolyData->SetLines(this->beamCellArray); this->beamMapper->SetInputData(this->beamPolyData); this->beamActor->SetMapper(this->beamMapper); this->beamActor->GetProperty()->SetLineWidth(1.5); this->MarkerRenderer->AddActor2D(this->beamActor); this->ShowActors(true); break; } if (!hasVolume) { this->ShowActors(false); } } //--------------------------------------------------------------------------- // vtkMRMLRulerDisplayableManager methods //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::vtkMRMLAstroBeamDisplayableManager() { this->Internal = new vtkInternal(this); } //--------------------------------------------------------------------------- vtkMRMLAstroBeamDisplayableManager::~vtkMRMLAstroBeamDisplayableManager() { delete this->Internal; } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::Create() { this->Internal->SetupMarkerRenderer(); this->Internal->SetupBeam(); this->Superclass::Create(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::UpdateFromViewNode() { // View node is changed, which may mean that either the marker type (visibility), size, or orientation is changed this->Internal->UpdateBeam(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::OnMRMLDisplayableNodeModifiedEvent(vtkObject* vtkNotUsed(caller)) { // view node is changed this->UpdateFromViewNode(); } //--------------------------------------------------------------------------- void vtkMRMLAstroBeamDisplayableManager::UpdateFromRenderer() { // Rendering is performed, so let's re-render the marker with up-to-date orientation this->Internal->UpdateBeam(); } <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2013-2017 Igor Mironchik 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 \warning If you are including this file you should include command.hpp too. */ #ifndef ARGS__GROUPS_HPP__INCLUDED #define ARGS__GROUPS_HPP__INCLUDED // Args include. #include "group_iface.hpp" #include "types.hpp" // C++ include. #include <algorithm> namespace Args { // // OnlyOneGroup // //! Group of args where only one argument can be defined. class OnlyOneGroup final : public GroupIface { public: template< typename T > explicit OnlyOneGroup( T && name, bool required = false ) : GroupIface( std::forward< T > ( name ), required ) { } virtual ~OnlyOneGroup() { } //! \return Is this argument defined? bool isDefined() const override { for( const auto & arg : children() ) { if( arg->isDefined() ) return true; } return false; } protected: /*! Check correctness of the argument before parsing. Implementation of this method must add his flag and name to the flags and names. */ void checkCorrectnessBeforeParsing( //! All known flags. StringList & flags, //! All known names. StringList & names ) const override { GroupIface::checkCorrectnessBeforeParsing( flags, names ); for( const auto & arg : children() ) { if( arg->isRequired() ) throw BaseException( String( SL( "Required argument \"" ) ) + arg->name() + SL( "\" is not allowed to be in OnlyOne group \"" ) + name() + SL( "\"." ) ); } } //! Check correctness of the argument after parsing. void checkCorrectnessAfterParsing() const override { GroupIface::checkCorrectnessAfterParsing(); ArgIface * defined = nullptr; for( const auto & arg : children() ) { if( arg->isDefined() ) { if( defined ) throw BaseException( String( SL( "Only one argument can " "be defined in OnlyOne group \"" ) ) + name() + SL( "\". " ) + SL( "Whereas defined \"" ) + defined->name() + SL( "\" and \"" ) + arg->name() + SL( "\"." ) ); else defined = arg; } } } }; // class OnlyOneGroup // // AllOfGroup // //! Group of args where all arguments should be defined. class AllOfGroup final : public GroupIface { public: template< typename T > explicit AllOfGroup( T && name, bool required = false ) : GroupIface( std::forward< T > ( name ), required ) { } virtual ~AllOfGroup() { } //! \return Is this argument defined? bool isDefined() const override { for( const auto & arg : children() ) { if( !arg->isDefined() ) return false; } return true; } protected: /*! Check correctness of the argument before parsing. Implementation of this method must add his flag and name to the flags and names. */ void checkCorrectnessBeforeParsing( //! All known flags. StringList & flags, //! All known names. StringList & names ) const override { GroupIface::checkCorrectnessBeforeParsing( flags, names ); for( const auto & arg : children() ) { if( arg->isRequired() ) throw BaseException( String( SL( "Required argument \"" ) ) + arg->name() + SL( "\" is not allowed to " ) + SL( "be in AllOf group \"" ) + name() + SL( "\"." ) ); } } //! Check correctness of the argument after parsing. void checkCorrectnessAfterParsing() const override { GroupIface::checkCorrectnessAfterParsing(); bool defined = false; const bool all = std::all_of( children().cbegin(), children().cend(), [ & ] ( const auto & arg ) { if( arg->isDefined() ) defined = true; return arg->isDefined(); } ); if( defined && !all ) throw BaseException( String( SL( "All arguments in " "AllOf group \"" ) ) + name() + SL( "\" should be defined." ) ); } }; // class AllOfGroup // // AtLeastOneGroup // //! Group of args where at least one argument should be defined. class AtLeastOneGroup final : public GroupIface { public: template< typename T > explicit AtLeastOneGroup( T && name, bool required = false ) : GroupIface( std::forward< T > ( name ), required ) { } virtual ~AtLeastOneGroup() { } //! \return Is this argument defined? bool isDefined() const override { for( const auto & arg : children() ) { if( arg->isDefined() ) return true; } return false; } protected: /*! Check correctness of the argument before parsing. Implementation of this method must add his flag and name to the flags and names. */ void checkCorrectnessBeforeParsing( //! All known flags. StringList & flags, //! All known names. StringList & names ) const override { GroupIface::checkCorrectnessBeforeParsing( flags, names ); for( const auto & arg : children() ) { if( arg->isRequired() ) throw BaseException( String( SL( "Required argument \"" ) ) + arg->name() + SL( "\" is not allowed to " ) + SL( "be in AtLeastOne group \"" ) + name() + SL( "\"." ) ); } } }; // class AtLeastOneGroup } /* namespace Args */ #endif // ARGS__GROUPS_HPP__INCLUDED <commit_msg>Replaced some code with std algorithms.<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2013-2017 Igor Mironchik 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 \warning If you are including this file you should include command.hpp too. */ #ifndef ARGS__GROUPS_HPP__INCLUDED #define ARGS__GROUPS_HPP__INCLUDED // Args include. #include "group_iface.hpp" #include "types.hpp" // C++ include. #include <algorithm> namespace Args { // // OnlyOneGroup // //! Group of args where only one argument can be defined. class OnlyOneGroup final : public GroupIface { public: template< typename T > explicit OnlyOneGroup( T && name, bool required = false ) : GroupIface( std::forward< T > ( name ), required ) { } virtual ~OnlyOneGroup() { } //! \return Is this argument defined? bool isDefined() const override { return std::any_of( children().cbegin(), children().cend(), [] ( const auto & arg ) { return arg->isDefined(); } ); } protected: /*! Check correctness of the argument before parsing. Implementation of this method must add his flag and name to the flags and names. */ void checkCorrectnessBeforeParsing( //! All known flags. StringList & flags, //! All known names. StringList & names ) const override { GroupIface::checkCorrectnessBeforeParsing( flags, names ); for( const auto & arg : children() ) { if( arg->isRequired() ) throw BaseException( String( SL( "Required argument \"" ) ) + arg->name() + SL( "\" is not allowed to be in OnlyOne group \"" ) + name() + SL( "\"." ) ); } } //! Check correctness of the argument after parsing. void checkCorrectnessAfterParsing() const override { GroupIface::checkCorrectnessAfterParsing(); ArgIface * defined = nullptr; for( const auto & arg : children() ) { if( arg->isDefined() ) { if( defined ) throw BaseException( String( SL( "Only one argument can " "be defined in OnlyOne group \"" ) ) + name() + SL( "\". " ) + SL( "Whereas defined \"" ) + defined->name() + SL( "\" and \"" ) + arg->name() + SL( "\"." ) ); else defined = arg; } } } }; // class OnlyOneGroup // // AllOfGroup // //! Group of args where all arguments should be defined. class AllOfGroup final : public GroupIface { public: template< typename T > explicit AllOfGroup( T && name, bool required = false ) : GroupIface( std::forward< T > ( name ), required ) { } virtual ~AllOfGroup() { } //! \return Is this argument defined? bool isDefined() const override { return !std::any_of( children().cbegin(), children().cend(), [] ( const auto & arg ) { return !arg->isDefined(); } ); } protected: /*! Check correctness of the argument before parsing. Implementation of this method must add his flag and name to the flags and names. */ void checkCorrectnessBeforeParsing( //! All known flags. StringList & flags, //! All known names. StringList & names ) const override { GroupIface::checkCorrectnessBeforeParsing( flags, names ); for( const auto & arg : children() ) { if( arg->isRequired() ) throw BaseException( String( SL( "Required argument \"" ) ) + arg->name() + SL( "\" is not allowed to " ) + SL( "be in AllOf group \"" ) + name() + SL( "\"." ) ); } } //! Check correctness of the argument after parsing. void checkCorrectnessAfterParsing() const override { GroupIface::checkCorrectnessAfterParsing(); bool defined = false; const bool all = std::all_of( children().cbegin(), children().cend(), [ & ] ( const auto & arg ) { if( arg->isDefined() ) defined = true; return arg->isDefined(); } ); if( defined && !all ) throw BaseException( String( SL( "All arguments in " "AllOf group \"" ) ) + name() + SL( "\" should be defined." ) ); } }; // class AllOfGroup // // AtLeastOneGroup // //! Group of args where at least one argument should be defined. class AtLeastOneGroup final : public GroupIface { public: template< typename T > explicit AtLeastOneGroup( T && name, bool required = false ) : GroupIface( std::forward< T > ( name ), required ) { } virtual ~AtLeastOneGroup() { } //! \return Is this argument defined? bool isDefined() const override { return std::any_of( children().cbegin(), children().cend(), [] ( const auto & arg ) { return arg->isDefined(); } ); } protected: /*! Check correctness of the argument before parsing. Implementation of this method must add his flag and name to the flags and names. */ void checkCorrectnessBeforeParsing( //! All known flags. StringList & flags, //! All known names. StringList & names ) const override { GroupIface::checkCorrectnessBeforeParsing( flags, names ); for( const auto & arg : children() ) { if( arg->isRequired() ) throw BaseException( String( SL( "Required argument \"" ) ) + arg->name() + SL( "\" is not allowed to " ) + SL( "be in AtLeastOne group \"" ) + name() + SL( "\"." ) ); } } }; // class AtLeastOneGroup } /* namespace Args */ #endif // ARGS__GROUPS_HPP__INCLUDED <|endoftext|>
<commit_before>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <gsl/gsl_version.h> #include "app.h" #include "progressbar.h" #include "file/path.h" #include "file/config.h" //#define NUM_DEFAULT_OPTIONS 5 namespace MR { namespace { const char* busy[] = { ". ", " . ", " . ", " . ", " .", " . ", " . ", " . " }; void display_func_cmdline (ProgressInfo& p) { if (p.as_percentage) fprintf (stderr, "\r%s: %s %3zu%%", App::name().c_str(), p.text.c_str(), size_t(p.value)); else fprintf (stderr, "\r%s: %s %s", App::name().c_str(), p.text.c_str(), busy[p.value%8]); } void done_func_cmdline (ProgressInfo& p) { if (p.as_percentage) fprintf (stderr, "\r%s: %s %3u%%\n", App::name().c_str(), p.text.c_str(), 100); else fprintf (stderr, "\r%s: %s - ok\n", App::name().c_str(), p.text.c_str()); } } void cmdline_print (const std::string& msg) { std::cout << msg; } void cmdline_error (const std::string& msg) { if (App::log_level) std::cerr << App::name() << ": " << msg << "\n"; } void cmdline_info (const std::string& msg) { if (App::log_level > 1) std::cerr << App::name() << " [INFO]: " << msg << "\n"; } void cmdline_debug (const std::string& msg) { if (App::log_level > 2) std::cerr << App::name() << " [DEBUG]: " << msg << "\n"; } namespace { void print_formatted_paragraph (const std::string& header, const std::string& text, int header_indent, int indent, int width) { int current = fprintf (stderr, "%-*s%-*s", header_indent, "", indent-header_indent-1, header.c_str()); std::string::size_type start = 0, end; bool newline = false; do { end = start; while (!isspace(text [end]) && end < text.size()) end++; std::string token (text.substr (start, end-start)); if (newline || current + (int) token.size() + 1 >= width) current = fprintf (stderr, "\n%*s%s", indent, "", token.c_str()) - 1; else current += fprintf (stderr, " %s", token.c_str()); newline = text[end] == '\n'; start = end + 1; } while (end < text.size()); fprintf (stderr, "\n"); } } #define HELP_WIDTH 80 #define HELP_PURPOSE_INDENT 0, 4, HELP_WIDTH #define HELP_ARG_INDENT 8, 20, HELP_WIDTH #define HELP_OPTION_INDENT 2, 20, HELP_WIDTH #define HELP_OPTION_ARG_INDENT 20, 24, HELP_WIDTH int App::log_level = 1; std::string App::application_name; const char** App::command_description = NULL; const Argument* App::command_arguments = NULL; const Option* App::command_options = NULL; const size_t* App::version = NULL; const char* App::copyright = NULL; const char* App::author = NULL; const Option App::default_options[] = { Option ("info", "display information messages."), Option ("quiet", "do not display information messages or progress status."), Option ("debug", "display debugging messages."), Option ("help", "display this information page and exit."), Option ("version", "display version information and exit."), Option() }; const Option* App::match_option (const char* stub) const { std::vector<const Option*> candidates; std::string root (stub); for (const Option* opt = command_options; *opt; ++opt) if (root.compare (0, root.size(), opt->id, root.size()) == 0) candidates.push_back (opt); for (const Option* opt = default_options; *opt; ++opt) if (root.compare (0, root.size(), opt->id, root.size()) == 0) candidates.push_back (opt); if (candidates.size() == 0) return (NULL); if (candidates.size() == 1) return (candidates[0]); for (std::vector<const Option*>::const_iterator opt = candidates.begin(); opt != candidates.end(); ++opt) if (root == (*opt)->id) return (*opt); root = "several matches possible for option \"-" + root + "\": \"-" + candidates[0]->id; for (std::vector<const Option*>::const_iterator opt = candidates.begin()+1; opt != candidates.end(); ++opt) root += std::string (", \"-") + (*opt)->id + "\""; throw Exception (root); } App::App (int argc, char** argv, const char** cmd_desc, const MR::Argument* cmd_args, const MR::Option* cmd_opts, const size_t* cmd_version, const char* cmd_author, const char* cmd_copyright) { #ifdef WINDOWS // force stderr to be unbuffered, and stdout to be line-buffered: setvbuf (stderr, NULL, _IONBF, 0); setvbuf (stdout, NULL, _IOLBF, 0); #endif command_description = cmd_desc; command_arguments = cmd_args; command_options = cmd_opts; author = cmd_author; version = cmd_version; copyright = cmd_copyright; if (argc == 2) { if (strcmp (argv[1], "__print_full_usage__") == 0) { print_full_usage (); throw (0); } } application_name = Path::basename (argv[0]); #ifdef WINDOWS if (Path::has_suffix (application_name, ".exe")) application_name.erase (application_name.size()-4); #endif log_level = 1; ProgressBar::display_func = display_func_cmdline; ProgressBar::done_func = done_func_cmdline; print = cmdline_print; error = cmdline_error; info = cmdline_info; debug = cmdline_debug; sort_arguments (argc, argv); srand (time (NULL)); File::Config::init (); } App::~App () { } void App::sort_arguments (int argc, char** argv) { for (int n = 1; n < argc; n++) { const char* arg = argv[n]; if (arg[0] == '-' && arg[1] && !isdigit(arg[1]) && arg[1] != '.') { while (*arg == '-') arg++; const Option* opt = match_option (arg); if (!opt) throw Exception (std::string ("unknown option \"-") + arg + "\""); else if (opt == default_options) { // info if (log_level < 2) log_level = 2; } else if (opt == default_options+1) { // quiet log_level = 0; ProgressBar::display = false; } else if (opt == default_options+2) { // debug log_level = 3; } else if (opt == default_options+3) { // help print_help (); throw 0; } else if (opt == default_options+4) { // version std::printf ( "== %s %zu.%zu.%zu ==\n" "%d bit %s version, built " __DATE__ " against MRtrix %zu.%zu.%zu, using GSL %s\n" "Author: %s\n" "%s\n", App::name().c_str(), version[0], version[1], version[2], int(8*sizeof(size_t)), #ifdef NDEBUG "release" #else "debug" #endif , mrtrix_major_version, mrtrix_minor_version, mrtrix_micro_version, gsl_version, ( author ? author : "J-Donald Tournier ([email protected])" ), ( copyright ? copyright : "Copyright (C) 2008 Brain Research Institute, Melbourne, Australia.\n" "This is free software; see the source for copying conditions.\n" "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." ) ); throw 0; } else { // command option if (n + int(opt->args.size()) >= argc) throw Exception (std::string ("not enough parameters to option \"-") + opt->id + "\""); option.push_back (ParsedOption (opt->id, argv+n+1)); } } else argument.push_back (argv[n]); } } void App::parse_arguments () { size_t num_args_required = 0, num_command_arguments = 0; bool has_optional_arguments = false; for (const Argument* arg = App::command_arguments; *arg; arg++) { num_command_arguments++; if (arg->flags & Optional) has_optional_arguments = true; else num_args_required++; if (arg->flags & AllowMultiple) has_optional_arguments = true; } if (has_optional_arguments && num_args_required > argument.size()) throw Exception ("expected at least " + str (num_args_required) + " arguments (" + str(argument.size()) + " supplied)"); if (!has_optional_arguments && num_args_required != argument.size()) throw Exception ("expected exactly " + str (num_args_required) + " arguments (" + str (argument.size()) + " supplied)"); size_t optional_argument = std::numeric_limits<size_t>::max(); for (size_t n = 0; n < argument.size(); n++) { if (n < optional_argument) if (command_arguments[n].flags & (Optional | AllowMultiple) ) optional_argument = n; size_t index = n; if (n >= optional_argument) { if (int(num_args_required - optional_argument) < int(argument.size()-n)) index = optional_argument; else index = num_args_required - argument.size() + n + (command_arguments[optional_argument].flags & Optional ? 1 : 0); } if (index >= num_command_arguments) throw Exception ("too many arguments"); command_arguments[index].check (argument[n]); } for (const Option* opt = command_options; *opt; ++opt) { size_t count = 0; for (std::vector<ParsedOption>::const_iterator popt = option.begin(); popt != option.end(); ++popt) if (popt->id == opt->id) count++; if (count < 1 && !(opt->flags & Optional)) throw Exception (std::string ("mandatory option \"") + opt->id + "\" must be specified"); if (count > 1 && !(opt->flags & AllowMultiple)) throw Exception (std::string ("multiple instances of option \"") + opt->id + "\" are not allowed"); } } void App::print_help () const { fprintf (stderr, "%s: part of the MRtrix package\n\n", App::name().c_str()); if (command_description[0]) { print_formatted_paragraph ("", command_description[0], HELP_PURPOSE_INDENT); fprintf (stderr, "\n"); for (const char** p = command_description+1; *p; p++) { print_formatted_paragraph ("", *p, HELP_PURPOSE_INDENT); fprintf (stderr, "\n"); } } else fprintf (stderr, "(no description available)\n\n"); fprintf (stderr, "SYNTAX: %s [ options ]", App::name().c_str()); for (const Argument* arg = command_arguments; *arg; ++arg) { if (arg->flags & Optional) fprintf (stderr, " ["); fprintf (stderr, " %s", arg->id); if (arg->flags & AllowMultiple) { if (!(arg->flags & Optional)) fprintf (stderr, " [ %s", arg->id); fprintf (stderr, " ..."); } if (arg->flags & (Optional | AllowMultiple)) fprintf (stderr, " ]"); } fprintf (stderr, "\n\n"); for (const Argument* arg = command_arguments; *arg; ++arg) print_formatted_paragraph (std::string("- ") + arg->id + " ", arg->desc, HELP_ARG_INDENT); fprintf (stderr, "\n"); fprintf (stderr, "OPTIONS:\n\n"); for (const Option* opt = command_options; *opt; ++opt) { std::string text ("-"); text += opt->id; for (std::vector<Argument>::const_iterator optarg = opt->args.begin(); optarg != opt->args.end(); ++optarg) text += std::string (" ") + optarg->id; print_formatted_paragraph (text + " ", opt->desc, HELP_OPTION_INDENT); // TODO: add argument defaults like this: //print_formatted_paragraph (text + " ", opt->desc + opt->arg_defaults(), HELP_OPTION_INDENT); fprintf (stderr, "\n"); } fprintf (stderr, "Standard options:\n"); for (const Option* opt = default_options; *opt; ++opt) print_formatted_paragraph (std::string("-") + opt->id, opt->desc, HELP_OPTION_INDENT); fprintf (stderr, "\n"); } void App::print_full_usage () const { for (const char** p = command_description; *p; p++) std::cout << *p << "\n"; for (const Argument* arg = command_arguments; arg; ++arg) arg->print_usage(); for (const Option* opt = command_options; opt; ++opt) opt->print_usage(); for (const Option* opt = default_options; opt; ++opt) opt->print_usage(); } } <commit_msg>fix bug in updated command-line parsing interface<commit_after>/* Copyright 2008 Brain Research Institute, Melbourne, Australia Written by J-Donald Tournier, 27/06/08. This file is part of MRtrix. MRtrix is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MRtrix 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 MRtrix. If not, see <http://www.gnu.org/licenses/>. */ #include <gsl/gsl_version.h> #include "app.h" #include "debug.h" #include "progressbar.h" #include "file/path.h" #include "file/config.h" //#define NUM_DEFAULT_OPTIONS 5 namespace MR { namespace { const char* busy[] = { ". ", " . ", " . ", " . ", " .", " . ", " . ", " . " }; void display_func_cmdline (ProgressInfo& p) { if (p.as_percentage) fprintf (stderr, "\r%s: %s %3zu%%", App::name().c_str(), p.text.c_str(), size_t(p.value)); else fprintf (stderr, "\r%s: %s %s", App::name().c_str(), p.text.c_str(), busy[p.value%8]); } void done_func_cmdline (ProgressInfo& p) { if (p.as_percentage) fprintf (stderr, "\r%s: %s %3u%%\n", App::name().c_str(), p.text.c_str(), 100); else fprintf (stderr, "\r%s: %s - ok\n", App::name().c_str(), p.text.c_str()); } } void cmdline_print (const std::string& msg) { std::cout << msg; } void cmdline_error (const std::string& msg) { if (App::log_level) std::cerr << App::name() << ": " << msg << "\n"; } void cmdline_info (const std::string& msg) { if (App::log_level > 1) std::cerr << App::name() << " [INFO]: " << msg << "\n"; } void cmdline_debug (const std::string& msg) { if (App::log_level > 2) std::cerr << App::name() << " [DEBUG]: " << msg << "\n"; } namespace { void print_formatted_paragraph (const std::string& header, const std::string& text, int header_indent, int indent, int width) { int current = fprintf (stderr, "%-*s%-*s", header_indent, "", indent-header_indent-1, header.c_str()); std::string::size_type start = 0, end; bool newline = false; do { end = start; while (!isspace(text [end]) && end < text.size()) end++; std::string token (text.substr (start, end-start)); if (newline || current + (int) token.size() + 1 >= width) current = fprintf (stderr, "\n%*s%s", indent, "", token.c_str()) - 1; else current += fprintf (stderr, " %s", token.c_str()); newline = text[end] == '\n'; start = end + 1; } while (end < text.size()); fprintf (stderr, "\n"); } } #define HELP_WIDTH 80 #define HELP_PURPOSE_INDENT 0, 4, HELP_WIDTH #define HELP_ARG_INDENT 8, 20, HELP_WIDTH #define HELP_OPTION_INDENT 2, 20, HELP_WIDTH #define HELP_OPTION_ARG_INDENT 20, 24, HELP_WIDTH int App::log_level = 1; std::string App::application_name; const char** App::command_description = NULL; const Argument* App::command_arguments = NULL; const Option* App::command_options = NULL; const size_t* App::version = NULL; const char* App::copyright = NULL; const char* App::author = NULL; const Option App::default_options[] = { Option ("info", "display information messages."), Option ("quiet", "do not display information messages or progress status."), Option ("debug", "display debugging messages."), Option ("help", "display this information page and exit."), Option ("version", "display version information and exit."), Option() }; const Option* App::match_option (const char* stub) const { std::vector<const Option*> candidates; std::string root (stub); for (const Option* opt = command_options; *opt; ++opt) if (root.compare (0, root.size(), opt->id, root.size()) == 0) candidates.push_back (opt); for (const Option* opt = default_options; *opt; ++opt) if (root.compare (0, root.size(), opt->id, root.size()) == 0) candidates.push_back (opt); if (candidates.size() == 0) return (NULL); if (candidates.size() == 1) return (candidates[0]); for (std::vector<const Option*>::const_iterator opt = candidates.begin(); opt != candidates.end(); ++opt) if (root == (*opt)->id) return (*opt); root = "several matches possible for option \"-" + root + "\": \"-" + candidates[0]->id; for (std::vector<const Option*>::const_iterator opt = candidates.begin()+1; opt != candidates.end(); ++opt) root += std::string (", \"-") + (*opt)->id + "\""; throw Exception (root); } App::App (int argc, char** argv, const char** cmd_desc, const MR::Argument* cmd_args, const MR::Option* cmd_opts, const size_t* cmd_version, const char* cmd_author, const char* cmd_copyright) { #ifdef WINDOWS // force stderr to be unbuffered, and stdout to be line-buffered: setvbuf (stderr, NULL, _IONBF, 0); setvbuf (stdout, NULL, _IOLBF, 0); #endif command_description = cmd_desc; command_arguments = cmd_args; command_options = cmd_opts; author = cmd_author; version = cmd_version; copyright = cmd_copyright; if (argc == 2) { if (strcmp (argv[1], "__print_full_usage__") == 0) { print_full_usage (); throw (0); } } application_name = Path::basename (argv[0]); #ifdef WINDOWS if (Path::has_suffix (application_name, ".exe")) application_name.erase (application_name.size()-4); #endif log_level = 1; ProgressBar::display_func = display_func_cmdline; ProgressBar::done_func = done_func_cmdline; print = cmdline_print; error = cmdline_error; info = cmdline_info; debug = cmdline_debug; sort_arguments (argc, argv); srand (time (NULL)); File::Config::init (); } App::~App () { } void App::sort_arguments (int argc, char** argv) { for (int n = 1; n < argc; n++) { const char* arg = argv[n]; if (arg[0] == '-' && arg[1] && !isdigit(arg[1]) && arg[1] != '.') { while (*arg == '-') arg++; const Option* opt = match_option (arg); if (!opt) throw Exception (std::string ("unknown option \"-") + arg + "\""); else if (opt == default_options) { // info if (log_level < 2) log_level = 2; } else if (opt == default_options+1) { // quiet log_level = 0; ProgressBar::display = false; } else if (opt == default_options+2) { // debug log_level = 3; } else if (opt == default_options+3) { // help print_help (); throw 0; } else if (opt == default_options+4) { // version std::printf ( "== %s %zu.%zu.%zu ==\n" "%d bit %s version, built " __DATE__ " against MRtrix %zu.%zu.%zu, using GSL %s\n" "Author: %s\n" "%s\n", App::name().c_str(), version[0], version[1], version[2], int(8*sizeof(size_t)), #ifdef NDEBUG "release" #else "debug" #endif , mrtrix_major_version, mrtrix_minor_version, mrtrix_micro_version, gsl_version, ( author ? author : "J-Donald Tournier ([email protected])" ), ( copyright ? copyright : "Copyright (C) 2008 Brain Research Institute, Melbourne, Australia.\n" "This is free software; see the source for copying conditions.\n" "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." ) ); throw 0; } else { // command option if (n + int(opt->args.size()) >= argc) throw Exception (std::string ("not enough parameters to option \"-") + opt->id + "\""); option.push_back (ParsedOption (opt->id, argv+n+1)); n += opt->args.size(); } } else { argument.push_back (argv[n]); VAR (argv[n]); } } } void App::parse_arguments () { size_t num_args_required = 0, num_command_arguments = 0; bool has_optional_arguments = false; for (const Argument* arg = App::command_arguments; *arg; arg++) { num_command_arguments++; if (arg->flags & Optional) has_optional_arguments = true; else num_args_required++; if (arg->flags & AllowMultiple) has_optional_arguments = true; } if (has_optional_arguments && num_args_required > argument.size()) throw Exception ("expected at least " + str (num_args_required) + " arguments (" + str(argument.size()) + " supplied)"); if (!has_optional_arguments && num_args_required != argument.size()) throw Exception ("expected exactly " + str (num_args_required) + " arguments (" + str (argument.size()) + " supplied)"); size_t optional_argument = std::numeric_limits<size_t>::max(); for (size_t n = 0; n < argument.size(); n++) { if (n < optional_argument) if (command_arguments[n].flags & (Optional | AllowMultiple) ) optional_argument = n; size_t index = n; if (n >= optional_argument) { if (int(num_args_required - optional_argument) < int(argument.size()-n)) index = optional_argument; else index = num_args_required - argument.size() + n + (command_arguments[optional_argument].flags & Optional ? 1 : 0); } if (index >= num_command_arguments) throw Exception ("too many arguments"); command_arguments[index].check (argument[n]); } for (const Option* opt = command_options; *opt; ++opt) { size_t count = 0; for (std::vector<ParsedOption>::const_iterator popt = option.begin(); popt != option.end(); ++popt) if (popt->id == opt->id) count++; if (count < 1 && !(opt->flags & Optional)) throw Exception (std::string ("mandatory option \"") + opt->id + "\" must be specified"); if (count > 1 && !(opt->flags & AllowMultiple)) throw Exception (std::string ("multiple instances of option \"") + opt->id + "\" are not allowed"); } } void App::print_help () const { fprintf (stderr, "%s: part of the MRtrix package\n\n", App::name().c_str()); if (command_description[0]) { print_formatted_paragraph ("", command_description[0], HELP_PURPOSE_INDENT); fprintf (stderr, "\n"); for (const char** p = command_description+1; *p; p++) { print_formatted_paragraph ("", *p, HELP_PURPOSE_INDENT); fprintf (stderr, "\n"); } } else fprintf (stderr, "(no description available)\n\n"); fprintf (stderr, "SYNTAX: %s [ options ]", App::name().c_str()); for (const Argument* arg = command_arguments; *arg; ++arg) { if (arg->flags & Optional) fprintf (stderr, " ["); fprintf (stderr, " %s", arg->id); if (arg->flags & AllowMultiple) { if (!(arg->flags & Optional)) fprintf (stderr, " [ %s", arg->id); fprintf (stderr, " ..."); } if (arg->flags & (Optional | AllowMultiple)) fprintf (stderr, " ]"); } fprintf (stderr, "\n\n"); for (const Argument* arg = command_arguments; *arg; ++arg) print_formatted_paragraph (std::string("- ") + arg->id + " ", arg->desc, HELP_ARG_INDENT); fprintf (stderr, "\n"); fprintf (stderr, "OPTIONS:\n\n"); for (const Option* opt = command_options; *opt; ++opt) { std::string text ("-"); text += opt->id; for (std::vector<Argument>::const_iterator optarg = opt->args.begin(); optarg != opt->args.end(); ++optarg) text += std::string (" ") + optarg->id; print_formatted_paragraph (text + " ", opt->desc, HELP_OPTION_INDENT); // TODO: add argument defaults like this: //print_formatted_paragraph (text + " ", opt->desc + opt->arg_defaults(), HELP_OPTION_INDENT); fprintf (stderr, "\n"); } fprintf (stderr, "Standard options:\n"); for (const Option* opt = default_options; *opt; ++opt) print_formatted_paragraph (std::string("-") + opt->id, opt->desc, HELP_OPTION_INDENT); fprintf (stderr, "\n"); } void App::print_full_usage () const { for (const char** p = command_description; *p; p++) std::cout << *p << "\n"; for (const Argument* arg = command_arguments; arg; ++arg) arg->print_usage(); for (const Option* opt = command_options; opt; ++opt) opt->print_usage(); for (const Option* opt = default_options; opt; ++opt) opt->print_usage(); } } <|endoftext|>
<commit_before>#ifndef COFFEE_MILL_COMMON_DEFERED_READER_HPP #define COFFEE_MILL_COMMON_DEFERED_READER_HPP #include <mill/common/Trajectory.hpp> #include <string_view> #include <optional> #include <iterator> #include <cstddef> namespace mill { class ReaderIterator; class ReaderIteratorSentinel; class DeferedReaderBase { public: using trajectory_type = Trajectory; using snapshot_type = Snapshot; using particle_type = Particle; using vector_type = Particle::vector_type; using attribute_container_type = trajectory_type::attribute_container_type; public: virtual ~DeferedReaderBase() = default; virtual attribute_container_type read_header() = 0; virtual trajectory_type read() = 0; virtual std::optional<snapshot_type> read_frame() = 0; virtual std::optional<snapshot_type> read_frame(const std::size_t idx) = 0; ReaderIterator begin(); ReaderIteratorSentinel end(); virtual void rewind() = 0; virtual bool is_eof() const noexcept = 0; virtual std::size_t current() const noexcept = 0; virtual std::string_view file_name() const noexcept = 0; }; class ReaderIterator { public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = Snapshot; using reference = value_type&; using pointer = value_type*; public: explicit ReaderIterator(DeferedReaderBase& reader) : current_(reader.read_frame()), reader_(std::addressof(reader)) {} ~ReaderIterator() = default; ReaderIterator(const ReaderIterator&) = default; ReaderIterator(ReaderIterator&&) = default; ReaderIterator& operator=(const ReaderIterator&) = default; ReaderIterator& operator=(ReaderIterator&&) = default; value_type& operator*() { if(!current_) { using namespace std::literals::string_literals; throw std::out_of_range("ReaderIterator: "s + std::string(reader_->file_name()) + " does not have any more snapshot"s); } return *current_; } value_type* operator->() { if(!current_) { using namespace std::literals::string_literals; throw std::out_of_range("ReaderIterator: "s + std::string(reader_->file_name()) + " does not have any more snapshot"s); } return std::addressof(*current_); } ReaderIterator& operator++() { current_ = reader_->read_frame(); return *this; } ReaderIterator operator++(int) { current_ = reader_->read_frame(); return *this; } bool has_value() const noexcept {return current_.has_value();} bool is_eof() const noexcept {return reader_->is_eof();} std::size_t current() const noexcept {return reader_->current();} std::string_view file_name() const noexcept {return reader_->file_name();} private: std::optional<value_type> current_; DeferedReaderBase* reader_; }; inline bool operator==(const ReaderIterator& lhs, const ReaderIterator& rhs) { return std::make_tuple(lhs.is_eof(), lhs.current(), lhs.file_name()) == std::make_tuple(rhs.is_eof(), rhs.current(), rhs.file_name()); } inline bool operator!=(const ReaderIterator& lhs, const ReaderIterator& rhs) { return !(lhs == rhs); } class ReaderIteratorSentinel { public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = Snapshot; using reference = value_type&; using pointer = value_type*; public: explicit ReaderIteratorSentinel(DeferedReaderBase& reader) : file_name_(reader.file_name()) {} bool is_eof() const noexcept {return true;} std::string_view file_name() const noexcept {return file_name_;} private: std::string_view file_name_; }; inline bool operator==( const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs) { return lhs.file_name() == rhs.file_name(); } inline bool operator!=( const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs) { return !(lhs == rhs); } inline bool operator==(const ReaderIterator& lhs, const ReaderIteratorSentinel& rhs) { return (not lhs.has_value()) && (lhs.file_name() == rhs.file_name()); } inline bool operator==(const ReaderIteratorSentinel& lhs, const ReaderIterator& rhs) { return (not rhs.has_value()) && (lhs.file_name() == rhs.file_name()); } inline bool operator!=(const ReaderIterator& lhs, const ReaderIteratorSentinel& rhs) { return !(lhs == rhs); } inline bool operator!=(const ReaderIteratorSentinel& lhs, const ReaderIterator& rhs) { return !(lhs == rhs); } inline ReaderIterator DeferedReaderBase::begin() { return ReaderIterator(*this); } inline ReaderIteratorSentinel DeferedReaderBase::end() { return ReaderIteratorSentinel(*this); } } // mill #endif// COFFEE_MILL_COMMON_DEFERED_READER_HPP <commit_msg>:bug: fix iterator increment method<commit_after>#ifndef COFFEE_MILL_COMMON_DEFERED_READER_HPP #define COFFEE_MILL_COMMON_DEFERED_READER_HPP #include <mill/common/Trajectory.hpp> #include <string_view> #include <optional> #include <iterator> #include <cstddef> namespace mill { class ReaderIterator; class ReaderIteratorSentinel; class DeferedReaderBase { public: using trajectory_type = Trajectory; using snapshot_type = Snapshot; using particle_type = Particle; using vector_type = Particle::vector_type; using attribute_container_type = trajectory_type::attribute_container_type; public: virtual ~DeferedReaderBase() = default; virtual attribute_container_type read_header() = 0; virtual trajectory_type read() = 0; virtual std::optional<snapshot_type> read_frame() = 0; virtual std::optional<snapshot_type> read_frame(const std::size_t idx) = 0; ReaderIterator begin(); ReaderIteratorSentinel end(); virtual void rewind() = 0; virtual bool is_eof() const noexcept = 0; virtual std::size_t current() const noexcept = 0; virtual std::string_view file_name() const noexcept = 0; }; class ReaderIterator { public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = Snapshot; using reference = value_type&; using pointer = value_type*; public: explicit ReaderIterator(DeferedReaderBase& reader) : current_(reader.read_frame()), reader_(std::addressof(reader)) {} ~ReaderIterator() = default; ReaderIterator(const ReaderIterator&) = default; ReaderIterator(ReaderIterator&&) = default; ReaderIterator& operator=(const ReaderIterator&) = default; ReaderIterator& operator=(ReaderIterator&&) = default; value_type& operator*() { if(!current_) { using namespace std::literals::string_literals; throw std::out_of_range("ReaderIterator: "s + std::string(reader_->file_name()) + " does not have any more snapshot"s); } return *current_; } value_type* operator->() { if(!current_) { using namespace std::literals::string_literals; throw std::out_of_range("ReaderIterator: "s + std::string(reader_->file_name()) + " does not have any more snapshot"s); } return std::addressof(*current_); } ReaderIterator& operator++() { current_ = reader_->read_frame(); return *this; } ReaderIterator operator++(int) { const auto self(*this); current_ = reader_->read_frame(); return self; } bool has_value() const noexcept {return current_.has_value();} bool is_eof() const noexcept {return reader_->is_eof();} std::size_t current() const noexcept {return reader_->current();} std::string_view file_name() const noexcept {return reader_->file_name();} private: std::optional<value_type> current_; DeferedReaderBase* reader_; }; inline bool operator==(const ReaderIterator& lhs, const ReaderIterator& rhs) { return std::make_tuple(lhs.is_eof(), lhs.current(), lhs.file_name()) == std::make_tuple(rhs.is_eof(), rhs.current(), rhs.file_name()); } inline bool operator!=(const ReaderIterator& lhs, const ReaderIterator& rhs) { return !(lhs == rhs); } class ReaderIteratorSentinel { public: using iterator_category = std::input_iterator_tag; using difference_type = std::ptrdiff_t; using value_type = Snapshot; using reference = value_type&; using pointer = value_type*; public: explicit ReaderIteratorSentinel(DeferedReaderBase& reader) : file_name_(reader.file_name()) {} bool is_eof() const noexcept {return true;} std::string_view file_name() const noexcept {return file_name_;} private: std::string_view file_name_; }; inline bool operator==( const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs) { return lhs.file_name() == rhs.file_name(); } inline bool operator!=( const ReaderIteratorSentinel& lhs, const ReaderIteratorSentinel& rhs) { return !(lhs == rhs); } inline bool operator==(const ReaderIterator& lhs, const ReaderIteratorSentinel& rhs) { return (not lhs.has_value()) && (lhs.file_name() == rhs.file_name()); } inline bool operator==(const ReaderIteratorSentinel& lhs, const ReaderIterator& rhs) { return (not rhs.has_value()) && (lhs.file_name() == rhs.file_name()); } inline bool operator!=(const ReaderIterator& lhs, const ReaderIteratorSentinel& rhs) { return !(lhs == rhs); } inline bool operator!=(const ReaderIteratorSentinel& lhs, const ReaderIterator& rhs) { return !(lhs == rhs); } inline ReaderIterator DeferedReaderBase::begin() { return ReaderIterator(*this); } inline ReaderIteratorSentinel DeferedReaderBase::end() { return ReaderIteratorSentinel(*this); } } // mill #endif// COFFEE_MILL_COMMON_DEFERED_READER_HPP <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkEuler3DTransform_hxx #define itkEuler3DTransform_hxx #include "itkEuler3DTransform.h" namespace itk { // Constructor with default arguments template<typename TParametersValueType> Euler3DTransform<TParametersValueType> ::Euler3DTransform() : Superclass(ParametersDimension) { m_ComputeZYX = false; m_AngleX = m_AngleY = m_AngleZ = NumericTraits<ScalarType>::ZeroValue(); this->m_FixedParameters.SetSize(SpaceDimension+1); this->m_FixedParameters.Fill(0.0); } // Constructor with default arguments template<typename TParametersValueType> Euler3DTransform<TParametersValueType> ::Euler3DTransform(const MatrixType & matrix, const OutputPointType & offset) { m_ComputeZYX = false; this->SetMatrix(matrix); OffsetType off; off[0] = offset[0]; off[1] = offset[1]; off[2] = offset[2]; this->SetOffset(off); this->m_FixedParameters.SetSize(SpaceDimension+1); this->m_FixedParameters.Fill(0.0); } // Constructor with arguments template<typename TParametersValueType> Euler3DTransform<TParametersValueType> ::Euler3DTransform(unsigned int parametersDimension) : Superclass(parametersDimension) { m_ComputeZYX = false; m_AngleX = m_AngleY = m_AngleZ = NumericTraits<ScalarType>::ZeroValue(); this->m_FixedParameters.SetSize(SpaceDimension+1); this->m_FixedParameters.Fill(0.0); } // Set Angles template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetVarRotation(ScalarType angleX, ScalarType angleY, ScalarType angleZ) { this->m_AngleX = angleX; this->m_AngleY = angleY; this->m_AngleZ = angleZ; } // Set Parameters template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetParameters(const ParametersType & parameters) { itkDebugMacro(<< "Setting parameters " << parameters); // Save parameters. Needed for proper operation of TransformUpdateParameters. if( &parameters != &(this->m_Parameters) ) { this->m_Parameters = parameters; } // Set angles with parameters m_AngleX = parameters[0]; m_AngleY = parameters[1]; m_AngleZ = parameters[2]; this->ComputeMatrix(); // Transfer the translation part OutputVectorType newTranslation; newTranslation[0] = parameters[3]; newTranslation[1] = parameters[4]; newTranslation[2] = parameters[5]; this->SetVarTranslation(newTranslation); this->ComputeOffset(); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); itkDebugMacro(<< "After setting parameters "); } // Get Parameters template<typename TParametersValueType> const typename Euler3DTransform<TParametersValueType>::ParametersType & Euler3DTransform<TParametersValueType> ::GetParameters(void) const { this->m_Parameters[0] = m_AngleX; this->m_Parameters[1] = m_AngleY; this->m_Parameters[2] = m_AngleZ; this->m_Parameters[3] = this->GetTranslation()[0]; this->m_Parameters[4] = this->GetTranslation()[1]; this->m_Parameters[5] = this->GetTranslation()[2]; return this->m_Parameters; } template<typename TParametersValueType> const typename Euler3DTransform<TParametersValueType>::FixedParametersType & Euler3DTransform<TParametersValueType> ::GetFixedParameters() const { // Call the superclass GetFixedParameters so that it fills the // array, we ignore the returned data and add the additional // information to the updated array. Superclass::GetFixedParameters(); this->m_FixedParameters[3] = this-> m_ComputeZYX; return this->m_FixedParameters; } template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetFixedParameters(const FixedParametersType & parameters) { InputPointType c; for( unsigned int i = 0; i < InputSpaceDimension; i++ ) { c[i] = this->m_FixedParameters[i] = parameters[i]; } this->SetCenter(c); //conditional is here for backwards compatibility: the //m_ComputeZYX flag was not serialized so it may or may //not be included as part of the fixed parameters if( parameters.Size() == 4 ) { this->m_FixedParameters[3] = parameters[3]; this->SetComputeZYX(this->m_FixedParameters[3]); } } // Set Rotational Part template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetRotation(ScalarType angleX, ScalarType angleY, ScalarType angleZ) { m_AngleX = angleX; m_AngleY = angleY; m_AngleZ = angleZ; this->ComputeMatrix(); this->ComputeOffset(); } // Compose template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetIdentity(void) { Superclass::SetIdentity(); m_AngleX = 0; m_AngleY = 0; m_AngleZ = 0; } // Compute angles from the rotation matrix template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::ComputeMatrixParameters(void) { if( m_ComputeZYX ) { m_AngleY = -std::asin(this->GetMatrix()[2][0]); double C = std::cos(m_AngleY); if( std::fabs(C) > 0.00005 ) { double x = this->GetMatrix()[2][2] / C; double y = this->GetMatrix()[2][1] / C; m_AngleX = std::atan2(y, x); x = this->GetMatrix()[0][0] / C; y = this->GetMatrix()[1][0] / C; m_AngleZ = std::atan2(y, x); } else { m_AngleX = NumericTraits<ScalarType>::ZeroValue(); double x = this->GetMatrix()[1][1]; double y = -this->GetMatrix()[0][1]; m_AngleZ = std::atan2(y, x); } } else { m_AngleX = std::asin(this->GetMatrix()[2][1]); double A = std::cos(m_AngleX); if( std::fabs(A) > 0.00005 ) { double x = this->GetMatrix()[2][2] / A; double y = -this->GetMatrix()[2][0] / A; m_AngleY = std::atan2(y, x); x = this->GetMatrix()[1][1] / A; y = -this->GetMatrix()[0][1] / A; m_AngleZ = std::atan2(y, x); } else { m_AngleZ = NumericTraits<ScalarType>::ZeroValue(); double x = this->GetMatrix()[0][0]; double y = this->GetMatrix()[1][0]; m_AngleY = std::atan2(y, x); } } this->ComputeMatrix(); } // Compute the matrix template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::ComputeMatrix(void) { // need to check if angles are in the right order const ScalarType cx = std::cos(m_AngleX); const ScalarType sx = std::sin(m_AngleX); const ScalarType cy = std::cos(m_AngleY); const ScalarType sy = std::sin(m_AngleY); const ScalarType cz = std::cos(m_AngleZ); const ScalarType sz = std::sin(m_AngleZ); const ScalarType one = NumericTraits<ScalarType>::OneValue(); const ScalarType zero = NumericTraits<ScalarType>::ZeroValue(); Matrix<TParametersValueType, 3, 3> RotationX; RotationX[0][0] = one; RotationX[0][1] = zero; RotationX[0][2] = zero; RotationX[1][0] = zero; RotationX[1][1] = cx; RotationX[1][2] = -sx; RotationX[2][0] = zero; RotationX[2][1] = sx; RotationX[2][2] = cx; Matrix<TParametersValueType, 3, 3> RotationY; RotationY[0][0] = cy; RotationY[0][1] = zero; RotationY[0][2] = sy; RotationY[1][0] = zero; RotationY[1][1] = one; RotationY[1][2] = zero; RotationY[2][0] = -sy; RotationY[2][1] = zero; RotationY[2][2] = cy; Matrix<TParametersValueType, 3, 3> RotationZ; RotationZ[0][0] = cz; RotationZ[0][1] = -sz; RotationZ[0][2] = zero; RotationZ[1][0] = sz; RotationZ[1][1] = cz; RotationZ[1][2] = zero; RotationZ[2][0] = zero; RotationZ[2][1] = zero; RotationZ[2][2] = one; /** Aply the rotation first around Y then X then Z */ if( m_ComputeZYX ) { this->SetVarMatrix(RotationZ * RotationY * RotationX); } else { // Like VTK transformation order this->SetVarMatrix(RotationZ * RotationX * RotationY); } } template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { // need to check if angles are in the right order const double cx = std::cos(m_AngleX); const double sx = std::sin(m_AngleX); const double cy = std::cos(m_AngleY); const double sy = std::sin(m_AngleY); const double cz = std::cos(m_AngleZ); const double sz = std::sin(m_AngleZ); jacobian.SetSize( 3, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); const double px = p[0] - this->GetCenter()[0]; const double py = p[1] - this->GetCenter()[1]; const double pz = p[2] - this->GetCenter()[2]; if( m_ComputeZYX ) { jacobian[0][0] = ( cz * sy * cx + sz * sx ) * py + ( -cz * sy * sx + sz * cx ) * pz; jacobian[1][0] = ( sz * sy * cx - cz * sx ) * py + ( -sz * sy * sx - cz * cx ) * pz; jacobian[2][0] = ( cy * cx ) * py + ( -cy * sx ) * pz; jacobian[0][1] = ( -cz * sy ) * px + ( cz * cy * sx ) * py + ( cz * cy * cx ) * pz; jacobian[1][1] = ( -sz * sy ) * px + ( sz * cy * sx ) * py + ( sz * cy * cx ) * pz; jacobian[2][1] = ( -cy ) * px + ( -sy * sx ) * py + ( -sy * cx ) * pz; jacobian[0][2] = ( -sz * cy ) * px + ( -sz * sy * sx - cz * cx ) * py + ( -sz * sy * cx + cz * sx ) * pz; jacobian[1][2] = ( cz * cy ) * px + ( cz * sy * sx - sz * cx ) * py + ( cz * sy * cx + sz * sx ) * pz; jacobian[2][2] = 0; } else { jacobian[0][0] = ( -sz * cx * sy ) * px + ( sz * sx ) * py + ( sz * cx * cy ) * pz; jacobian[1][0] = ( cz * cx * sy ) * px + ( -cz * sx ) * py + ( -cz * cx * cy ) * pz; jacobian[2][0] = ( sx * sy ) * px + ( cx ) * py + ( -sx * cy ) * pz; jacobian[0][1] = ( -cz * sy - sz * sx * cy ) * px + ( cz * cy - sz * sx * sy ) * pz; jacobian[1][1] = ( -sz * sy + cz * sx * cy ) * px + ( sz * cy + cz * sx * sy ) * pz; jacobian[2][1] = ( -cx * cy ) * px + ( -cx * sy ) * pz; jacobian[0][2] = ( -sz * cy - cz * sx * sy ) * px + ( -cz * cx ) * py + ( -sz * sy + cz * sx * cy ) * pz; jacobian[1][2] = ( cz * cy - sz * sx * sy ) * px + ( -sz * cx ) * py + ( cz * sy + sz * sx * cy ) * pz; jacobian[2][2] = 0; } // compute derivatives for the translation part unsigned int blockOffset = 3; for( unsigned int dim = 0; dim < SpaceDimension; dim++ ) { jacobian[dim][blockOffset + dim] = 1.0; } } template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetComputeZYX (const bool flag) { if( this->m_ComputeZYX != flag ) { this->m_ComputeZYX = flag; this->ComputeMatrix(); // The meaning of the parameters has changed so the transform // has been modified even if the parameter values have not. this->Modified(); } } // Print self template<typename TParametersValueType> void Euler3DTransform<TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Euler's angles: AngleX=" << m_AngleX << " AngleY=" << m_AngleY << " AngleZ=" << m_AngleZ << std::endl; os << indent << "m_ComputeZYX = " << m_ComputeZYX << std::endl; } } // namespace #endif <commit_msg>COMP: fix warning about implicit double to bool conversion<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkEuler3DTransform_hxx #define itkEuler3DTransform_hxx #include "itkEuler3DTransform.h" namespace itk { // Constructor with default arguments template<typename TParametersValueType> Euler3DTransform<TParametersValueType> ::Euler3DTransform() : Superclass(ParametersDimension) { m_ComputeZYX = false; m_AngleX = m_AngleY = m_AngleZ = NumericTraits<ScalarType>::ZeroValue(); this->m_FixedParameters.SetSize(SpaceDimension+1); this->m_FixedParameters.Fill(0.0); } // Constructor with default arguments template<typename TParametersValueType> Euler3DTransform<TParametersValueType> ::Euler3DTransform(const MatrixType & matrix, const OutputPointType & offset) { m_ComputeZYX = false; this->SetMatrix(matrix); OffsetType off; off[0] = offset[0]; off[1] = offset[1]; off[2] = offset[2]; this->SetOffset(off); this->m_FixedParameters.SetSize(SpaceDimension+1); this->m_FixedParameters.Fill(0.0); } // Constructor with arguments template<typename TParametersValueType> Euler3DTransform<TParametersValueType> ::Euler3DTransform(unsigned int parametersDimension) : Superclass(parametersDimension) { m_ComputeZYX = false; m_AngleX = m_AngleY = m_AngleZ = NumericTraits<ScalarType>::ZeroValue(); this->m_FixedParameters.SetSize(SpaceDimension+1); this->m_FixedParameters.Fill(0.0); } // Set Angles template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetVarRotation(ScalarType angleX, ScalarType angleY, ScalarType angleZ) { this->m_AngleX = angleX; this->m_AngleY = angleY; this->m_AngleZ = angleZ; } // Set Parameters template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetParameters(const ParametersType & parameters) { itkDebugMacro(<< "Setting parameters " << parameters); // Save parameters. Needed for proper operation of TransformUpdateParameters. if( &parameters != &(this->m_Parameters) ) { this->m_Parameters = parameters; } // Set angles with parameters m_AngleX = parameters[0]; m_AngleY = parameters[1]; m_AngleZ = parameters[2]; this->ComputeMatrix(); // Transfer the translation part OutputVectorType newTranslation; newTranslation[0] = parameters[3]; newTranslation[1] = parameters[4]; newTranslation[2] = parameters[5]; this->SetVarTranslation(newTranslation); this->ComputeOffset(); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); itkDebugMacro(<< "After setting parameters "); } // Get Parameters template<typename TParametersValueType> const typename Euler3DTransform<TParametersValueType>::ParametersType & Euler3DTransform<TParametersValueType> ::GetParameters(void) const { this->m_Parameters[0] = m_AngleX; this->m_Parameters[1] = m_AngleY; this->m_Parameters[2] = m_AngleZ; this->m_Parameters[3] = this->GetTranslation()[0]; this->m_Parameters[4] = this->GetTranslation()[1]; this->m_Parameters[5] = this->GetTranslation()[2]; return this->m_Parameters; } template<typename TParametersValueType> const typename Euler3DTransform<TParametersValueType>::FixedParametersType & Euler3DTransform<TParametersValueType> ::GetFixedParameters() const { // Call the superclass GetFixedParameters so that it fills the // array, we ignore the returned data and add the additional // information to the updated array. Superclass::GetFixedParameters(); this->m_FixedParameters[3] = this->m_ComputeZYX ? 1.0 : 0.0; return this->m_FixedParameters; } template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetFixedParameters(const FixedParametersType & parameters) { InputPointType c; for( unsigned int i = 0; i < InputSpaceDimension; i++ ) { c[i] = this->m_FixedParameters[i] = parameters[i]; } this->SetCenter(c); //conditional is here for backwards compatibility: the //m_ComputeZYX flag was not serialized so it may or may //not be included as part of the fixed parameters if( parameters.Size() == 4 ) { this->m_FixedParameters[3] = parameters[3]; this->SetComputeZYX(this->m_FixedParameters[3] != 0.0); } } // Set Rotational Part template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetRotation(ScalarType angleX, ScalarType angleY, ScalarType angleZ) { m_AngleX = angleX; m_AngleY = angleY; m_AngleZ = angleZ; this->ComputeMatrix(); this->ComputeOffset(); } // Compose template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetIdentity(void) { Superclass::SetIdentity(); m_AngleX = 0; m_AngleY = 0; m_AngleZ = 0; } // Compute angles from the rotation matrix template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::ComputeMatrixParameters(void) { if( m_ComputeZYX ) { m_AngleY = -std::asin(this->GetMatrix()[2][0]); double C = std::cos(m_AngleY); if( std::fabs(C) > 0.00005 ) { double x = this->GetMatrix()[2][2] / C; double y = this->GetMatrix()[2][1] / C; m_AngleX = std::atan2(y, x); x = this->GetMatrix()[0][0] / C; y = this->GetMatrix()[1][0] / C; m_AngleZ = std::atan2(y, x); } else { m_AngleX = NumericTraits<ScalarType>::ZeroValue(); double x = this->GetMatrix()[1][1]; double y = -this->GetMatrix()[0][1]; m_AngleZ = std::atan2(y, x); } } else { m_AngleX = std::asin(this->GetMatrix()[2][1]); double A = std::cos(m_AngleX); if( std::fabs(A) > 0.00005 ) { double x = this->GetMatrix()[2][2] / A; double y = -this->GetMatrix()[2][0] / A; m_AngleY = std::atan2(y, x); x = this->GetMatrix()[1][1] / A; y = -this->GetMatrix()[0][1] / A; m_AngleZ = std::atan2(y, x); } else { m_AngleZ = NumericTraits<ScalarType>::ZeroValue(); double x = this->GetMatrix()[0][0]; double y = this->GetMatrix()[1][0]; m_AngleY = std::atan2(y, x); } } this->ComputeMatrix(); } // Compute the matrix template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::ComputeMatrix(void) { // need to check if angles are in the right order const ScalarType cx = std::cos(m_AngleX); const ScalarType sx = std::sin(m_AngleX); const ScalarType cy = std::cos(m_AngleY); const ScalarType sy = std::sin(m_AngleY); const ScalarType cz = std::cos(m_AngleZ); const ScalarType sz = std::sin(m_AngleZ); const ScalarType one = NumericTraits<ScalarType>::OneValue(); const ScalarType zero = NumericTraits<ScalarType>::ZeroValue(); Matrix<TParametersValueType, 3, 3> RotationX; RotationX[0][0] = one; RotationX[0][1] = zero; RotationX[0][2] = zero; RotationX[1][0] = zero; RotationX[1][1] = cx; RotationX[1][2] = -sx; RotationX[2][0] = zero; RotationX[2][1] = sx; RotationX[2][2] = cx; Matrix<TParametersValueType, 3, 3> RotationY; RotationY[0][0] = cy; RotationY[0][1] = zero; RotationY[0][2] = sy; RotationY[1][0] = zero; RotationY[1][1] = one; RotationY[1][2] = zero; RotationY[2][0] = -sy; RotationY[2][1] = zero; RotationY[2][2] = cy; Matrix<TParametersValueType, 3, 3> RotationZ; RotationZ[0][0] = cz; RotationZ[0][1] = -sz; RotationZ[0][2] = zero; RotationZ[1][0] = sz; RotationZ[1][1] = cz; RotationZ[1][2] = zero; RotationZ[2][0] = zero; RotationZ[2][1] = zero; RotationZ[2][2] = one; /** Aply the rotation first around Y then X then Z */ if( m_ComputeZYX ) { this->SetVarMatrix(RotationZ * RotationY * RotationX); } else { // Like VTK transformation order this->SetVarMatrix(RotationZ * RotationX * RotationY); } } template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::ComputeJacobianWithRespectToParameters(const InputPointType & p, JacobianType & jacobian) const { // need to check if angles are in the right order const double cx = std::cos(m_AngleX); const double sx = std::sin(m_AngleX); const double cy = std::cos(m_AngleY); const double sy = std::sin(m_AngleY); const double cz = std::cos(m_AngleZ); const double sz = std::sin(m_AngleZ); jacobian.SetSize( 3, this->GetNumberOfLocalParameters() ); jacobian.Fill(0.0); const double px = p[0] - this->GetCenter()[0]; const double py = p[1] - this->GetCenter()[1]; const double pz = p[2] - this->GetCenter()[2]; if( m_ComputeZYX ) { jacobian[0][0] = ( cz * sy * cx + sz * sx ) * py + ( -cz * sy * sx + sz * cx ) * pz; jacobian[1][0] = ( sz * sy * cx - cz * sx ) * py + ( -sz * sy * sx - cz * cx ) * pz; jacobian[2][0] = ( cy * cx ) * py + ( -cy * sx ) * pz; jacobian[0][1] = ( -cz * sy ) * px + ( cz * cy * sx ) * py + ( cz * cy * cx ) * pz; jacobian[1][1] = ( -sz * sy ) * px + ( sz * cy * sx ) * py + ( sz * cy * cx ) * pz; jacobian[2][1] = ( -cy ) * px + ( -sy * sx ) * py + ( -sy * cx ) * pz; jacobian[0][2] = ( -sz * cy ) * px + ( -sz * sy * sx - cz * cx ) * py + ( -sz * sy * cx + cz * sx ) * pz; jacobian[1][2] = ( cz * cy ) * px + ( cz * sy * sx - sz * cx ) * py + ( cz * sy * cx + sz * sx ) * pz; jacobian[2][2] = 0; } else { jacobian[0][0] = ( -sz * cx * sy ) * px + ( sz * sx ) * py + ( sz * cx * cy ) * pz; jacobian[1][0] = ( cz * cx * sy ) * px + ( -cz * sx ) * py + ( -cz * cx * cy ) * pz; jacobian[2][0] = ( sx * sy ) * px + ( cx ) * py + ( -sx * cy ) * pz; jacobian[0][1] = ( -cz * sy - sz * sx * cy ) * px + ( cz * cy - sz * sx * sy ) * pz; jacobian[1][1] = ( -sz * sy + cz * sx * cy ) * px + ( sz * cy + cz * sx * sy ) * pz; jacobian[2][1] = ( -cx * cy ) * px + ( -cx * sy ) * pz; jacobian[0][2] = ( -sz * cy - cz * sx * sy ) * px + ( -cz * cx ) * py + ( -sz * sy + cz * sx * cy ) * pz; jacobian[1][2] = ( cz * cy - sz * sx * sy ) * px + ( -sz * cx ) * py + ( cz * sy + sz * sx * cy ) * pz; jacobian[2][2] = 0; } // compute derivatives for the translation part unsigned int blockOffset = 3; for( unsigned int dim = 0; dim < SpaceDimension; dim++ ) { jacobian[dim][blockOffset + dim] = 1.0; } } template<typename TParametersValueType> void Euler3DTransform<TParametersValueType> ::SetComputeZYX (const bool flag) { if( this->m_ComputeZYX != flag ) { this->m_ComputeZYX = flag; this->ComputeMatrix(); // The meaning of the parameters has changed so the transform // has been modified even if the parameter values have not. this->Modified(); } } // Print self template<typename TParametersValueType> void Euler3DTransform<TParametersValueType>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Euler's angles: AngleX=" << m_AngleX << " AngleY=" << m_AngleY << " AngleZ=" << m_AngleZ << std::endl; os << indent << "m_ComputeZYX = " << m_ComputeZYX << std::endl; } } // namespace #endif <|endoftext|>
<commit_before>/* Copyright 2019 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/compiler/jit/tests/auto_clustering_test_helper.h" #include "absl/strings/numbers.h" #include "tensorflow/compiler/jit/mark_for_compilation_pass.h" #include "tensorflow/compiler/jit/xla_cluster_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/common_runtime/graph_constructor.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/io/random_inputstream.h" #include "tensorflow/core/lib/io/zlib_compression_options.h" #include "tensorflow/core/lib/io/zlib_inputstream.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" #include "tensorflow/core/util/port.h" #include "tensorflow/tools/optimization/optimization_pass_runner.h" namespace tensorflow { namespace { StatusOr<string> SummarizeClustering(const GraphDef& auto_clustered_graph_def) { testing::ResetClusterSequenceNumber(); Graph graph(OpRegistry::Global()); GraphConstructorOptions graph_opts; graph_opts.expect_device_spec = true; graph_opts.allow_internal_ops = true; TF_RETURN_IF_ERROR( ConvertGraphDefToGraph(graph_opts, auto_clustered_graph_def, &graph)); // cluster_id -> (operation name -> # of operations) const int kNoCluster = -1; std::map<int, std::map<string, int>> clusters; std::map<int, int> cluster_size; int clustered_nodes = 0; for (Node* n : graph.op_nodes()) { int cluster = kNoCluster; if (absl::optional<absl::string_view> maybe_cluster = GetXlaClusterForNode(*n)) { maybe_cluster->remove_prefix(absl::string_view("cluster_").size()); TF_RET_CHECK(absl::SimpleAtoi(*maybe_cluster, &cluster)); clustered_nodes++; } clusters[cluster][n->type_string()]++; cluster_size[cluster]++; } string result = absl::StrCat("Clustered nodes: ", clustered_nodes, "\nUnclustered nodes: ", cluster_size[kNoCluster], "\nNumber of clusters: ", clusters.size() - 1, "\n\n"); for (const auto& pair : clusters) { if (pair.first == kNoCluster) { absl::StrAppend(&result, "unclustered"); } else { absl::StrAppend(&result, "cluster ", pair.first); } absl::StrAppend(&result, " size ", cluster_size[pair.first], "\n"); for (const auto& ops_and_counts : pair.second) { absl::StrAppend(&result, " ", ops_and_counts.first, " ", ops_and_counts.second, "\n"); } } return result; } Status AssertGraphDefIsUnclustered(const GraphDef& graphdef) { const char* kXlaClusterAttr = "_XlaCluster"; const char* kXlaAlreadyClusteredAttr = "_XlaAlreadyClustered"; for (const NodeDef& node : graphdef.node()) { if (node.attr().count(kXlaClusterAttr) || node.attr().count(kXlaAlreadyClusteredAttr)) { return errors::InvalidArgument( "Input files are already clustered, you probably copied in " "mark_for_compilation_<n>.pbtxt when you should have copied in " "before_mark_for_compilation_<n>.pbtxt"); } } return Status::OK(); } Status ReadTextProtoFromString(Env* env, const string& data, ::tensorflow::protobuf::Message* proto) { if (!::tensorflow::protobuf::TextFormat::ParseFromString(data, proto)) { return errors::DataLoss("Can't parse input data as text proto"); } return Status::OK(); } } // namespace Status AutoClusteringTest::RunAutoClusteringTestImpl( GraphDef graphdef, absl::string_view golden_summary_file_path) { if (!IsGoogleCudaEnabled()) { // There is some slight change in the clustering decisions under // --config=cuda. I have not looked closely at why that is happening, but // most likely some of the partial declustering passes behave differently // with --config=cuda because of different HostMemory. So for now only test // the non-CUDA config, under the assumption that regressions with // --config=cuda would also be detected as regressions without // --config=cuda. LOG(INFO) << "Not running " << ::testing::UnitTest::GetInstance()->current_test_info()->name() << " since test was not built with --config=cuda"; return Status::OK(); } TF_RETURN_IF_ERROR(AssertGraphDefIsUnclustered(graphdef)); OptimizationPassRunner runner; TF_RETURN_IF_ERROR(runner.SetJitLevel(tensorflow::OptimizerOptions::ON_2)); TF_RETURN_IF_ERROR(runner.AddCpus(32)); TF_RETURN_IF_ERROR(runner.AddGpus(8)); for (absl::string_view auto_clustering_pass : {"CloneConstantsForBetterClusteringPass", "MarkForCompilationPass", "IncreaseDynamismForAutoJitPass", "PartiallyDeclusterPass"}) { GraphDef next; TF_RETURN_IF_ERROR( runner.Run(auto_clustering_pass, std::move(graphdef), &next)); graphdef = std::move(next); } TF_ASSIGN_OR_RETURN(string clustering_summary, SummarizeClustering(graphdef)); // To update golden files flip this to true and run // // bazel test --test_strategy=local \ // tensorflow/compiler/jit/tests:auto_clustering_test bool update_golden = false; if (update_golden) { TF_RETURN_IF_ERROR(WriteStringToFile( Env::Default(), string(golden_summary_file_path), clustering_summary)); } string golden_file_contents; TF_RETURN_IF_ERROR(ReadFileToString( Env::Default(), string(golden_summary_file_path), &golden_file_contents)); EXPECT_EQ(golden_file_contents, clustering_summary); return Status::OK(); } Status AutoClusteringTest::RunAutoClusteringTestWithPbtxt( absl::string_view pbtxt_file_path, absl::string_view golden_summary_file_path) { GraphDef graphdef; TF_RETURN_IF_ERROR( ReadTextProto(Env::Default(), string(pbtxt_file_path), &graphdef)); return RunAutoClusteringTestImpl(std::move(graphdef), golden_summary_file_path); } Status AutoClusteringTest::RunAutoClusteringTestWithGzippedPbtxt( absl::string_view gzipped_pbtxt_file_path, absl::string_view golden_summary_file_path) { Env* env = Env::Default(); std::unique_ptr<RandomAccessFile> file_reader; TF_RETURN_IF_ERROR( env->NewRandomAccessFile(string(gzipped_pbtxt_file_path), &file_reader)); std::unique_ptr<io::RandomAccessInputStream> input_stream( new io::RandomAccessInputStream(file_reader.get())); constexpr int k_buffer_size = 256 << 10; // 256kb io::ZlibInputStream in(input_stream.get(), /*input_buffer_bytes=*/k_buffer_size, /*output_buffer_bytes=*/k_buffer_size, io::ZlibCompressionOptions::GZIP()); tstring decompressed_pbtxt_string; Status s = in.ReadNBytes(INT_MAX, &decompressed_pbtxt_string); if (!s.ok() && !errors::IsOutOfRange(s)) { // OutOfRange is fine since we set the number of read bytes to INT_MAX. // Only return other kinds of errors. return s; } GraphDef graphdef; TF_RETURN_IF_ERROR(ReadTextProtoFromString( Env::Default(), decompressed_pbtxt_string, &graphdef)); return RunAutoClusteringTestImpl(std::move(graphdef), golden_summary_file_path); } #if defined(PLATFORM_GOOGLE) Status BenchmarkMarkForCompilation(absl::string_view graph_def_path, benchmark::State& state) { GraphDef graph_def; TF_RETURN_IF_ERROR( ReadTextProto(Env::Default(), string(graph_def_path), &graph_def)); OptimizationPassRunner runner; TF_RETURN_IF_ERROR(runner.SetJitLevel(tensorflow::OptimizerOptions::ON_2)); TF_RETURN_IF_ERROR(runner.AddCpus(32)); TF_RETURN_IF_ERROR(runner.AddGpus(8)); for (auto _ : state) { StopBenchmarkTiming(); GraphDef result; GraphDef graph_def_copy = graph_def; StartBenchmarkTiming(); TF_RETURN_IF_ERROR(runner.Run("MarkForCompilationPass", std::move(graph_def_copy), &result)); } return Status::OK(); } #endif // PLATFORM_GOOGLE } // namespace tensorflow <commit_msg>Remove calls to deprecated Stop/Start timer functions in benchmarks.<commit_after>/* Copyright 2019 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/compiler/jit/tests/auto_clustering_test_helper.h" #include "absl/strings/numbers.h" #include "tensorflow/compiler/jit/mark_for_compilation_pass.h" #include "tensorflow/compiler/jit/xla_cluster_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/common_runtime/graph_constructor.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/io/random_inputstream.h" #include "tensorflow/core/lib/io/zlib_compression_options.h" #include "tensorflow/core/lib/io/zlib_inputstream.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" #include "tensorflow/core/util/port.h" #include "tensorflow/tools/optimization/optimization_pass_runner.h" namespace tensorflow { namespace { StatusOr<string> SummarizeClustering(const GraphDef& auto_clustered_graph_def) { testing::ResetClusterSequenceNumber(); Graph graph(OpRegistry::Global()); GraphConstructorOptions graph_opts; graph_opts.expect_device_spec = true; graph_opts.allow_internal_ops = true; TF_RETURN_IF_ERROR( ConvertGraphDefToGraph(graph_opts, auto_clustered_graph_def, &graph)); // cluster_id -> (operation name -> # of operations) const int kNoCluster = -1; std::map<int, std::map<string, int>> clusters; std::map<int, int> cluster_size; int clustered_nodes = 0; for (Node* n : graph.op_nodes()) { int cluster = kNoCluster; if (absl::optional<absl::string_view> maybe_cluster = GetXlaClusterForNode(*n)) { maybe_cluster->remove_prefix(absl::string_view("cluster_").size()); TF_RET_CHECK(absl::SimpleAtoi(*maybe_cluster, &cluster)); clustered_nodes++; } clusters[cluster][n->type_string()]++; cluster_size[cluster]++; } string result = absl::StrCat("Clustered nodes: ", clustered_nodes, "\nUnclustered nodes: ", cluster_size[kNoCluster], "\nNumber of clusters: ", clusters.size() - 1, "\n\n"); for (const auto& pair : clusters) { if (pair.first == kNoCluster) { absl::StrAppend(&result, "unclustered"); } else { absl::StrAppend(&result, "cluster ", pair.first); } absl::StrAppend(&result, " size ", cluster_size[pair.first], "\n"); for (const auto& ops_and_counts : pair.second) { absl::StrAppend(&result, " ", ops_and_counts.first, " ", ops_and_counts.second, "\n"); } } return result; } Status AssertGraphDefIsUnclustered(const GraphDef& graphdef) { const char* kXlaClusterAttr = "_XlaCluster"; const char* kXlaAlreadyClusteredAttr = "_XlaAlreadyClustered"; for (const NodeDef& node : graphdef.node()) { if (node.attr().count(kXlaClusterAttr) || node.attr().count(kXlaAlreadyClusteredAttr)) { return errors::InvalidArgument( "Input files are already clustered, you probably copied in " "mark_for_compilation_<n>.pbtxt when you should have copied in " "before_mark_for_compilation_<n>.pbtxt"); } } return Status::OK(); } Status ReadTextProtoFromString(Env* env, const string& data, ::tensorflow::protobuf::Message* proto) { if (!::tensorflow::protobuf::TextFormat::ParseFromString(data, proto)) { return errors::DataLoss("Can't parse input data as text proto"); } return Status::OK(); } } // namespace Status AutoClusteringTest::RunAutoClusteringTestImpl( GraphDef graphdef, absl::string_view golden_summary_file_path) { if (!IsGoogleCudaEnabled()) { // There is some slight change in the clustering decisions under // --config=cuda. I have not looked closely at why that is happening, but // most likely some of the partial declustering passes behave differently // with --config=cuda because of different HostMemory. So for now only test // the non-CUDA config, under the assumption that regressions with // --config=cuda would also be detected as regressions without // --config=cuda. LOG(INFO) << "Not running " << ::testing::UnitTest::GetInstance()->current_test_info()->name() << " since test was not built with --config=cuda"; return Status::OK(); } TF_RETURN_IF_ERROR(AssertGraphDefIsUnclustered(graphdef)); OptimizationPassRunner runner; TF_RETURN_IF_ERROR(runner.SetJitLevel(tensorflow::OptimizerOptions::ON_2)); TF_RETURN_IF_ERROR(runner.AddCpus(32)); TF_RETURN_IF_ERROR(runner.AddGpus(8)); for (absl::string_view auto_clustering_pass : {"CloneConstantsForBetterClusteringPass", "MarkForCompilationPass", "IncreaseDynamismForAutoJitPass", "PartiallyDeclusterPass"}) { GraphDef next; TF_RETURN_IF_ERROR( runner.Run(auto_clustering_pass, std::move(graphdef), &next)); graphdef = std::move(next); } TF_ASSIGN_OR_RETURN(string clustering_summary, SummarizeClustering(graphdef)); // To update golden files flip this to true and run // // bazel test --test_strategy=local \ // tensorflow/compiler/jit/tests:auto_clustering_test bool update_golden = false; if (update_golden) { TF_RETURN_IF_ERROR(WriteStringToFile( Env::Default(), string(golden_summary_file_path), clustering_summary)); } string golden_file_contents; TF_RETURN_IF_ERROR(ReadFileToString( Env::Default(), string(golden_summary_file_path), &golden_file_contents)); EXPECT_EQ(golden_file_contents, clustering_summary); return Status::OK(); } Status AutoClusteringTest::RunAutoClusteringTestWithPbtxt( absl::string_view pbtxt_file_path, absl::string_view golden_summary_file_path) { GraphDef graphdef; TF_RETURN_IF_ERROR( ReadTextProto(Env::Default(), string(pbtxt_file_path), &graphdef)); return RunAutoClusteringTestImpl(std::move(graphdef), golden_summary_file_path); } Status AutoClusteringTest::RunAutoClusteringTestWithGzippedPbtxt( absl::string_view gzipped_pbtxt_file_path, absl::string_view golden_summary_file_path) { Env* env = Env::Default(); std::unique_ptr<RandomAccessFile> file_reader; TF_RETURN_IF_ERROR( env->NewRandomAccessFile(string(gzipped_pbtxt_file_path), &file_reader)); std::unique_ptr<io::RandomAccessInputStream> input_stream( new io::RandomAccessInputStream(file_reader.get())); constexpr int k_buffer_size = 256 << 10; // 256kb io::ZlibInputStream in(input_stream.get(), /*input_buffer_bytes=*/k_buffer_size, /*output_buffer_bytes=*/k_buffer_size, io::ZlibCompressionOptions::GZIP()); tstring decompressed_pbtxt_string; Status s = in.ReadNBytes(INT_MAX, &decompressed_pbtxt_string); if (!s.ok() && !errors::IsOutOfRange(s)) { // OutOfRange is fine since we set the number of read bytes to INT_MAX. // Only return other kinds of errors. return s; } GraphDef graphdef; TF_RETURN_IF_ERROR(ReadTextProtoFromString( Env::Default(), decompressed_pbtxt_string, &graphdef)); return RunAutoClusteringTestImpl(std::move(graphdef), golden_summary_file_path); } #if defined(PLATFORM_GOOGLE) Status BenchmarkMarkForCompilation(absl::string_view graph_def_path, benchmark::State& state) { GraphDef graph_def; TF_RETURN_IF_ERROR( ReadTextProto(Env::Default(), string(graph_def_path), &graph_def)); OptimizationPassRunner runner; TF_RETURN_IF_ERROR(runner.SetJitLevel(tensorflow::OptimizerOptions::ON_2)); TF_RETURN_IF_ERROR(runner.AddCpus(32)); TF_RETURN_IF_ERROR(runner.AddGpus(8)); for (auto _ : state) { state.PauseTiming(); GraphDef result; GraphDef graph_def_copy = graph_def; state.ResumeTiming(); TF_RETURN_IF_ERROR(runner.Run("MarkForCompilationPass", std::move(graph_def_copy), &result)); } return Status::OK(); } #endif // PLATFORM_GOOGLE } // namespace tensorflow <|endoftext|>
<commit_before>/* Copyright 2017 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/compiler/xla/service/gpu/gpu_layout_assignment.h" #include <memory> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/gpu/gpu_options.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { using stream_executor::dnn::DataLayout; using stream_executor::dnn::FilterLayout; static bool IsVoltaOrLater(const se::StreamExecutor& stream_executor) { int major, minor; CHECK(stream_executor.GetDeviceDescription().cuda_compute_capability(&major, &minor)); return major >= 7; } // Returns (input, filter, output) layouts. static std::tuple<DataLayout, FilterLayout, DataLayout> HeuristicLayoutAssignment(const HloInstruction* instr, stream_executor::StreamExecutor* stream_executor) { // DataLayout and FilterLayout uses weird enum names. Translations: // N <=> Batch or Output // C <=> Depth or Input // H <=> Y // W <=> X // // Therefore kOutputInputYX means NHWC; kBatchDepthYX means NCHW. // As of today, our empirical evidence is that cudnn 7.0 is faster on V100 x // fp16 with the mostly-NHWC layout. The heuristic may change as cudnn version // changes, as well as the hardware updates. if (!(instr->operand(0)->shape().element_type() == xla::PrimitiveType::F16 && IsVoltaOrLater(*stream_executor))) { return std::make_tuple(DataLayout::kBatchDepthYX, FilterLayout::kOutputInputYX, DataLayout::kBatchDepthYX); } VLOG(2) << "Using heuristic to figure out layouts for " << instr->ToString(); // For BackwardInput that has stride, full NHWC layouts run significantly // slower than (NHWC, NCHW, NCHW) or (NHWC, NCHW, NHWC). // // TODO(timshen): more closely compare (NHWC, NCHW, NCHW) and (NHWC, NCHW, // NHWC). if (instr->custom_call_target() == kCudnnConvBackwardInputCallTarget && window_util::HasStride(instr->window())) { return std::make_tuple(DataLayout::kBatchYXDepth, FilterLayout::kOutputInputYX, DataLayout::kBatchDepthYX); } return std::make_tuple(DataLayout::kBatchYXDepth, FilterLayout::kOutputYXInput, DataLayout::kBatchYXDepth); } // Adds layout constraints on the cudnn custom-call instruction. The layout // constraints are represented in terms of minor_to_major fields of both // operands and the output shape. Depending on the underlying algorithm, one of // { NCHW, NHWC } ^ 3 = 8 different layout combinations may be chosen. Status GpuLayoutAssignment::AddBackendConstraintsToDnnConvCustomCall( HloInstruction* instr, LayoutConstraints* constraints) { CHECK(IsCustomCallToDnnConvolution(*instr)) << instr->ToString(); Shape input_shape; Shape filter_shape; Shape output_shape; const auto& target = instr->custom_call_target(); if (target == kCudnnConvForwardCallTarget) { input_shape = instr->operand(0)->shape(); filter_shape = instr->operand(1)->shape(); output_shape = instr->shape().tuple_shapes(0); } else if (target == kCudnnConvBackwardInputCallTarget) { input_shape = instr->shape().tuple_shapes(0); filter_shape = instr->operand(1)->shape(); output_shape = instr->operand(0)->shape(); } else if (target == kCudnnConvBackwardFilterCallTarget) { input_shape = instr->operand(0)->shape(); filter_shape = instr->shape().tuple_shapes(0); output_shape = instr->operand(1)->shape(); } else { LOG(FATAL) << "Unexpected custom call target: " << instr->custom_call_target(); } { DataLayout input; FilterLayout filter; DataLayout output; if (ConvUseLayoutHeuristic(instr->GetModule()->config())) { std::tie(input, filter, output) = HeuristicLayoutAssignment(instr, stream_executor_); } else { input = DataLayout::kBatchDepthYX; filter = FilterLayout::kOutputInputYX; output = DataLayout::kBatchDepthYX; } TF_ASSIGN_OR_RETURN( std::tie(*input_shape.mutable_layout(), *filter_shape.mutable_layout(), *output_shape.mutable_layout()), StreamExecutorConvLayoutsToXlaLayouts( instr->convolution_dimension_numbers(), input, filter, output)); } // The custom call returns a tuple of (actual_result, scratch_buffer); // call_result_buf is the logical buffer for actual_result, the thing that // contains the result of the conv call. TF_ASSIGN_OR_RETURN(const LogicalBuffer* call_result_buf, constraints->points_to_analysis().GetBufferDefinedAt( instr, /*index=*/{0})); // Set layouts of the instructions' shapes. if (target == kCudnnConvForwardCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout(input_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(filter_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(output_shape.layout(), *call_result_buf)); } else if (target == kCudnnConvBackwardInputCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout(output_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(filter_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(input_shape.layout(), *call_result_buf)); } else if (target == kCudnnConvBackwardFilterCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout(input_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(output_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(filter_shape.layout(), *call_result_buf)); } else { LOG(FATAL) << "Unexpected custom call target: " << instr->custom_call_target(); } return Status::OK(); } Status GpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { // Add convolution constraints in reverse postorder that the earliest // convolution layout propagates first. This reduces the likelihood of fusion // nodes with copies. auto post_order = constraints->computation()->MakeInstructionPostOrder(); for (auto iterator = post_order.rbegin(); iterator != post_order.rend(); ++iterator) { HloInstruction* instruction = *iterator; if (IsCustomCallToDnnConvolution(*instruction)) { TF_RETURN_IF_ERROR( AddBackendConstraintsToDnnConvCustomCall(instruction, constraints)); } } return Status::OK(); } bool GpuLayoutAssignment::CustomCallRequiresMajorFirstLayout( const HloInstruction* instruction) { // - Inputs to cudnn batchnorm custom calls don't need the major-first layout // (i.e. {n, n-1, ...0}) -- we can handle any layout. // - Inputs to cudnn convolution require custom layouts handled in // AddBackendConstraints. return !IsCustomCallToDnnBatchNorm(*instruction) && !IsCustomCallToDnnConvolution(*instruction); } Status GpuLayoutAssignment::PropagateOperandConstraint( const OperandLayoutConstraint& layout_constraint, LayoutConstraints* constraints) { const HloInstruction* instruction = layout_constraint.instruction(); // cudnn batchnorm forward inference's result must have the same layout as its // operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget && layout_constraint.operand_no() == 0) { TF_RETURN_IF_ERROR(constraints->SetInstructionLayout( layout_constraint.shape_layout().shape(), instruction)); } // cudnn batchnorm forward training returns a tuple {output, mean, // inverse-stddev}. mean and inverse-stddev are rank 1 and so have only one // possible layout, but output is not (necessarily) rank 1, and, like in // batchnorm forward inference, must have the same layout as operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && layout_constraint.operand_no() == 0) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); } // Like forward training, cudnn batchnorm backward returns a tuple {output, // mean, inverse-stddev}, and its operand 0 and 'output' must have the same // layout. In addition, its operand 0 and operand 4 -- the 'operand' and // 'grad_output' parameters -- must have the same layout. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && (layout_constraint.operand_no() == 0 || layout_constraint.operand_no() == 4)) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); int64 operand_to_set = layout_constraint.operand_no() == 0 ? 4 : 0; TF_RETURN_IF_ERROR(constraints->SetOperandLayout( layout_constraint.shape_layout().shape(), instruction, operand_to_set)); } return LayoutAssignment::PropagateOperandConstraint(layout_constraint, constraints); } Status GpuLayoutAssignment::PropagateBufferConstraint( const BufferLayoutConstraint& buffer_constraint, LayoutConstraints* constraints) { const LogicalBuffer& buf = buffer_constraint.buffer(); const HloInstruction* instruction = buf.instruction(); Shape shape_with_layout = buf.shape(); *shape_with_layout.mutable_layout() = buffer_constraint.layout(); // Propagate output constraints to the operands of cudnn batchnorm ops. This // is the same as PropagateOperandConstraint, just in the other direction. We // need to both to fulfill our contract to LayoutAssignment. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && buf.index() == ShapeIndex({0})) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && buf.index() == ShapeIndex({0})) { // batchnorm backward has two operands, "operand" and "grad_output" whose // layouts must both match that of the result at tuple-index 0. TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/4)); } return LayoutAssignment::PropagateBufferConstraint(buffer_constraint, constraints); } } // namespace gpu } // namespace xla <commit_msg>Fix a typo in comment to mention kOutputInputYX means NCHW<commit_after>/* Copyright 2017 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/compiler/xla/service/gpu/gpu_layout_assignment.h" #include <memory> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/gpu/gpu_options.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { using stream_executor::dnn::DataLayout; using stream_executor::dnn::FilterLayout; static bool IsVoltaOrLater(const se::StreamExecutor& stream_executor) { int major, minor; CHECK(stream_executor.GetDeviceDescription().cuda_compute_capability(&major, &minor)); return major >= 7; } // Returns (input, filter, output) layouts. static std::tuple<DataLayout, FilterLayout, DataLayout> HeuristicLayoutAssignment(const HloInstruction* instr, stream_executor::StreamExecutor* stream_executor) { // DataLayout and FilterLayout uses weird enum names. Translations: // N <=> Batch or Output // C <=> Depth or Input // H <=> Y // W <=> X // // Therefore kOutputInputYX and kBatchDepthYX mean NCHW. // As of today, our empirical evidence is that cudnn 7.0 is faster on V100 x // fp16 with the mostly-NHWC layout. The heuristic may change as cudnn version // changes, as well as the hardware updates. if (!(instr->operand(0)->shape().element_type() == xla::PrimitiveType::F16 && IsVoltaOrLater(*stream_executor))) { return std::make_tuple(DataLayout::kBatchDepthYX, FilterLayout::kOutputInputYX, DataLayout::kBatchDepthYX); } VLOG(2) << "Using heuristic to figure out layouts for " << instr->ToString(); // For BackwardInput that has stride, full NHWC layouts run significantly // slower than (NHWC, NCHW, NCHW) or (NHWC, NCHW, NHWC). // // TODO(timshen): more closely compare (NHWC, NCHW, NCHW) and (NHWC, NCHW, // NHWC). if (instr->custom_call_target() == kCudnnConvBackwardInputCallTarget && window_util::HasStride(instr->window())) { return std::make_tuple(DataLayout::kBatchYXDepth, FilterLayout::kOutputInputYX, DataLayout::kBatchDepthYX); } return std::make_tuple(DataLayout::kBatchYXDepth, FilterLayout::kOutputYXInput, DataLayout::kBatchYXDepth); } // Adds layout constraints on the cudnn custom-call instruction. The layout // constraints are represented in terms of minor_to_major fields of both // operands and the output shape. Depending on the underlying algorithm, one of // { NCHW, NHWC } ^ 3 = 8 different layout combinations may be chosen. Status GpuLayoutAssignment::AddBackendConstraintsToDnnConvCustomCall( HloInstruction* instr, LayoutConstraints* constraints) { CHECK(IsCustomCallToDnnConvolution(*instr)) << instr->ToString(); Shape input_shape; Shape filter_shape; Shape output_shape; const auto& target = instr->custom_call_target(); if (target == kCudnnConvForwardCallTarget) { input_shape = instr->operand(0)->shape(); filter_shape = instr->operand(1)->shape(); output_shape = instr->shape().tuple_shapes(0); } else if (target == kCudnnConvBackwardInputCallTarget) { input_shape = instr->shape().tuple_shapes(0); filter_shape = instr->operand(1)->shape(); output_shape = instr->operand(0)->shape(); } else if (target == kCudnnConvBackwardFilterCallTarget) { input_shape = instr->operand(0)->shape(); filter_shape = instr->shape().tuple_shapes(0); output_shape = instr->operand(1)->shape(); } else { LOG(FATAL) << "Unexpected custom call target: " << instr->custom_call_target(); } { DataLayout input; FilterLayout filter; DataLayout output; if (ConvUseLayoutHeuristic(instr->GetModule()->config())) { std::tie(input, filter, output) = HeuristicLayoutAssignment(instr, stream_executor_); } else { input = DataLayout::kBatchDepthYX; filter = FilterLayout::kOutputInputYX; output = DataLayout::kBatchDepthYX; } TF_ASSIGN_OR_RETURN( std::tie(*input_shape.mutable_layout(), *filter_shape.mutable_layout(), *output_shape.mutable_layout()), StreamExecutorConvLayoutsToXlaLayouts( instr->convolution_dimension_numbers(), input, filter, output)); } // The custom call returns a tuple of (actual_result, scratch_buffer); // call_result_buf is the logical buffer for actual_result, the thing that // contains the result of the conv call. TF_ASSIGN_OR_RETURN(const LogicalBuffer* call_result_buf, constraints->points_to_analysis().GetBufferDefinedAt( instr, /*index=*/{0})); // Set layouts of the instructions' shapes. if (target == kCudnnConvForwardCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout(input_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(filter_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(output_shape.layout(), *call_result_buf)); } else if (target == kCudnnConvBackwardInputCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout(output_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(filter_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(input_shape.layout(), *call_result_buf)); } else if (target == kCudnnConvBackwardFilterCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout(input_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(output_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(filter_shape.layout(), *call_result_buf)); } else { LOG(FATAL) << "Unexpected custom call target: " << instr->custom_call_target(); } return Status::OK(); } Status GpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { // Add convolution constraints in reverse postorder that the earliest // convolution layout propagates first. This reduces the likelihood of fusion // nodes with copies. auto post_order = constraints->computation()->MakeInstructionPostOrder(); for (auto iterator = post_order.rbegin(); iterator != post_order.rend(); ++iterator) { HloInstruction* instruction = *iterator; if (IsCustomCallToDnnConvolution(*instruction)) { TF_RETURN_IF_ERROR( AddBackendConstraintsToDnnConvCustomCall(instruction, constraints)); } } return Status::OK(); } bool GpuLayoutAssignment::CustomCallRequiresMajorFirstLayout( const HloInstruction* instruction) { // - Inputs to cudnn batchnorm custom calls don't need the major-first layout // (i.e. {n, n-1, ...0}) -- we can handle any layout. // - Inputs to cudnn convolution require custom layouts handled in // AddBackendConstraints. return !IsCustomCallToDnnBatchNorm(*instruction) && !IsCustomCallToDnnConvolution(*instruction); } Status GpuLayoutAssignment::PropagateOperandConstraint( const OperandLayoutConstraint& layout_constraint, LayoutConstraints* constraints) { const HloInstruction* instruction = layout_constraint.instruction(); // cudnn batchnorm forward inference's result must have the same layout as its // operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget && layout_constraint.operand_no() == 0) { TF_RETURN_IF_ERROR(constraints->SetInstructionLayout( layout_constraint.shape_layout().shape(), instruction)); } // cudnn batchnorm forward training returns a tuple {output, mean, // inverse-stddev}. mean and inverse-stddev are rank 1 and so have only one // possible layout, but output is not (necessarily) rank 1, and, like in // batchnorm forward inference, must have the same layout as operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && layout_constraint.operand_no() == 0) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); } // Like forward training, cudnn batchnorm backward returns a tuple {output, // mean, inverse-stddev}, and its operand 0 and 'output' must have the same // layout. In addition, its operand 0 and operand 4 -- the 'operand' and // 'grad_output' parameters -- must have the same layout. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && (layout_constraint.operand_no() == 0 || layout_constraint.operand_no() == 4)) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); int64 operand_to_set = layout_constraint.operand_no() == 0 ? 4 : 0; TF_RETURN_IF_ERROR(constraints->SetOperandLayout( layout_constraint.shape_layout().shape(), instruction, operand_to_set)); } return LayoutAssignment::PropagateOperandConstraint(layout_constraint, constraints); } Status GpuLayoutAssignment::PropagateBufferConstraint( const BufferLayoutConstraint& buffer_constraint, LayoutConstraints* constraints) { const LogicalBuffer& buf = buffer_constraint.buffer(); const HloInstruction* instruction = buf.instruction(); Shape shape_with_layout = buf.shape(); *shape_with_layout.mutable_layout() = buffer_constraint.layout(); // Propagate output constraints to the operands of cudnn batchnorm ops. This // is the same as PropagateOperandConstraint, just in the other direction. We // need to both to fulfill our contract to LayoutAssignment. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && buf.index() == ShapeIndex({0})) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && buf.index() == ShapeIndex({0})) { // batchnorm backward has two operands, "operand" and "grad_output" whose // layouts must both match that of the result at tuple-index 0. TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/4)); } return LayoutAssignment::PropagateBufferConstraint(buffer_constraint, constraints); } } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // File: minterface.hpp // // Desc: Interface for Data Mining. // // Copyright (c) 2014-2018. veyesys.com All rights reserved. //------------------------------------------------------------------------------ #ifndef __M_INTERFACE_HPP__ #define __M_INTERFACE_HPP__ #include "utility.hpp" #include "videotype.hpp" #include "miningtype.hpp" using namespace std; typedef enum __MiningRetType { MINING_RET_MOT = 1, MINING_RET_OBJS, MINING_RET_LAST }MiningRetType; typedef enum __MModuleFlag { MM_MOT = 1, MM_TRACK = 2, MM_PEOPLE_CNT = 4, MM_ALPR = 8, MM_LAST }MModuleFlag; typedef enum __MMReqStream { MM_STREAM_MAIN = 1, MM_STREAM_SUB = 2, MM_STREAM_MAIN_RAW = 4, MM_STREAM_SUB_RAW = 8, MM_STREAM_SEQ = 16, MM_STREAM_LAST }MMReqStream; typedef struct __MiningRet { MiningRetType ret; union { VeObjGroup objs; VeMotionBox mot; } data; }MiningRet; #ifdef WIN32 typedef void (__cdecl * MiningCallbackFunctionPtr)(MiningRet& ret, void * pParam); #else typedef void ( * MiningCallbackFunctionPtr)(MiningRet& ret, void * pParam); #endif class MiningInterface { public: MiningInterface() {} virtual ~MiningInterface() {} public: /* Process decoded or compressed data */ virtual BOOL Process(VideoFrame& frame) = 0; virtual BOOL ProcessRaw(RawFrame& frame) = 0; virtual BOOL ProcessSeq(VideoSeqFrame& seq) = 0; /* Get the stream type of this module */ virtual BOOL GetReqStream(MMReqStream& type) = 0; virtual BOOL RegRetCallback(MiningCallbackFunctionPtr pCallback, void * pParam) = 0; virtual BOOL UnRegDataCallback(void * pParam) = 0; virtual u32 GetFlags() = 0; virtual astring GetVersion() = 0; virtual u32 GetId() = 0; }; /* Create MiningInterface from the module MiningCreateDevice function */ typedef MiningInterface * (*MiningCreateDeviceFunc)(u32 id); #ifdef __cplusplus extern "C" { #endif VE_LIBRARY_API MiningInterface * MiningCreateDevice(u32 id); #ifdef __cplusplus } #endif #endif /* __M_INTERFACE_HPP__ */ <commit_msg>fix a build error<commit_after>//------------------------------------------------------------------------------ // File: minterface.hpp // // Desc: Interface for Data Mining. // // Copyright (c) 2014-2018. veyesys.com All rights reserved. //------------------------------------------------------------------------------ #ifndef __M_INTERFACE_HPP__ #define __M_INTERFACE_HPP__ #include "utility.hpp" #include "videotype.hpp" #include "hdfsrecsession.hpp" #include "miningtype.hpp" using namespace std; typedef enum __MiningRetType { MINING_RET_MOT = 1, MINING_RET_OBJS, MINING_RET_LAST }MiningRetType; typedef enum __MModuleFlag { MM_MOT = 1, MM_TRACK = 2, MM_PEOPLE_CNT = 4, MM_ALPR = 8, MM_LAST }MModuleFlag; typedef enum __MMReqStream { MM_STREAM_MAIN = 1, MM_STREAM_SUB = 2, MM_STREAM_MAIN_RAW = 4, MM_STREAM_SUB_RAW = 8, MM_STREAM_SEQ = 16, MM_STREAM_LAST }MMReqStream; typedef struct __MiningRet { MiningRetType ret; union { VeObjGroup objs; VeMotionBox mot; } data; }MiningRet; #ifdef WIN32 typedef void (__cdecl * MiningCallbackFunctionPtr)(MiningRet& ret, void * pParam); #else typedef void ( * MiningCallbackFunctionPtr)(MiningRet& ret, void * pParam); #endif class MiningInterface { public: MiningInterface() {} virtual ~MiningInterface() {} public: /* Process decoded or compressed data */ virtual BOOL Process(VideoFrame& frame) = 0; virtual BOOL ProcessRaw(RawFrame& frame) = 0; virtual BOOL ProcessSeq(VideoSeqFrame& seq) = 0; /* Get the stream type of this module */ virtual BOOL GetReqStream(MMReqStream& type) = 0; virtual BOOL RegRetCallback(MiningCallbackFunctionPtr pCallback, void * pParam) = 0; virtual BOOL UnRegDataCallback(void * pParam) = 0; virtual u32 GetFlags() = 0; virtual astring GetVersion() = 0; virtual u32 GetId() = 0; }; /* Create MiningInterface from the module MiningCreateDevice function */ typedef MiningInterface * (*MiningCreateDeviceFunc)(u32 id); #ifdef __cplusplus extern "C" { #endif VE_LIBRARY_API MiningInterface * MiningCreateDevice(u32 id); #ifdef __cplusplus } #endif #endif /* __M_INTERFACE_HPP__ */ <|endoftext|>
<commit_before>/* Copyright 2017 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/compiler/xla/service/gpu/gpu_layout_assignment.h" #include <memory> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { using se::dnn::DataLayout; using se::dnn::FilterLayout; // Returns (input, filter, output) layouts. static std::tuple<DataLayout, FilterLayout, DataLayout> HeuristicLayoutAssignment(const HloInstruction* instr, se::StreamExecutor* stream_executor) { // DataLayout and FilterLayout uses weird enum names. Translations: // N <=> Batch or Output // C <=> Depth or Input // H <=> Y // W <=> X // // Therefore kOutputInputYX and kBatchDepthYX mean NCHW. // // If you have trouble keeping these straight, consider that all that matters // is the location of the channel dim: Is it major (NCHW), or minor (NHWC)? constexpr auto kAllNCHW = std::make_tuple(DataLayout::kBatchDepthYX, FilterLayout::kOutputInputYX, DataLayout::kBatchDepthYX); constexpr auto kAllNHWC = std::make_tuple(DataLayout::kBatchYXDepth, FilterLayout::kOutputYXInput, DataLayout::kBatchYXDepth); // If we're not Volta or not fp16, the decision is easy: Use NCHW. if (!(instr->operand(0)->shape().element_type() == xla::PrimitiveType::F16 && IsVoltaOrLater(*stream_executor))) { return kAllNCHW; } VLOG(2) << "Using heuristic to figure out layouts for " << instr->ToString(); // Empirically we've found with Volta and cudnn 7 that backward-input convs // with stride are significantly faster with NCHW layouts. // // We could have used a mixed layout combination, e.g. (NHWC, NCHW, NCHW), // which on paper gives good performance. However, there are two observations: // * a mixed layout combination is more cuDNN-bug prone, based on empirical // envidence. // * we've also observed that for mixed layouts, cuDNN transposes data back // and forth from a different layout combination. If we end up with // transposes anyway, we prefer to have them in XLA, as they can be fused. // TODO(timshen): Figure out the exact condition. This may be achieved by // auto-tuning layouts offline. if (instr->custom_call_target() == kCudnnConvBackwardInputCallTarget && window_util::HasStride(instr->window())) { return kAllNCHW; } // For other Volta f16 convolutions, use NHWC. return kAllNHWC; } // Adds layout constraints on the cudnn custom-call instruction. The layout // constraints are represented in terms of minor_to_major fields of both // operands and the output shape. Depending on the underlying algorithm, one of // { NCHW, NHWC } ^ 3 = 8 different layout combinations may be chosen. Status GpuLayoutAssignment::AddBackendConstraintsToDnnConvCustomCall( HloCustomCallInstruction* instr, LayoutConstraints* constraints) { Shape lhs_shape = instr->operand(0)->shape(); Shape rhs_shape = instr->operand(1)->shape(); Shape result_shape = instr->shape().tuple_shapes(0); Shape* input_shape; Shape* filter_shape; Shape* output_shape; TF_ASSIGN_OR_RETURN(auto kind, GetCudnnConvKind(instr)); switch (kind) { case CudnnConvKind::kForward: case CudnnConvKind::kForwardActivation: input_shape = &lhs_shape; filter_shape = &rhs_shape; output_shape = &result_shape; break; case CudnnConvKind::kBackwardInput: input_shape = &result_shape; filter_shape = &rhs_shape; output_shape = &lhs_shape; break; case CudnnConvKind::kBackwardFilter: input_shape = &lhs_shape; filter_shape = &result_shape; output_shape = &rhs_shape; break; } { DataLayout input; FilterLayout filter; DataLayout output; std::tie(input, filter, output) = HeuristicLayoutAssignment(instr, stream_executor_); TF_ASSIGN_OR_RETURN( std::tie(*input_shape->mutable_layout(), *filter_shape->mutable_layout(), *output_shape->mutable_layout()), StreamExecutorConvLayoutsToXlaLayouts( instr->convolution_dimension_numbers(), input, filter, output)); } // The custom call returns a tuple of (actual_result, scratch_buffer); // call_result_buf is the logical buffer for actual_result, the thing that // contains the result of the conv call. TF_ASSIGN_OR_RETURN(const LogicalBuffer* call_result_buf, constraints->points_to_analysis().GetBufferDefinedAt( instr, /*index=*/{0})); // Set layouts of the instructions' shapes. TF_RETURN_IF_ERROR(constraints->SetOperandLayout(lhs_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(rhs_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(result_shape.layout(), *call_result_buf)); // instr->operand(2), if exists, is the bias buffer. There is no need to // assign layout to it, as it has only one dimension. // instr->opernad(3), if exists, is the side input buffer. if (instr->operand_count() == 4) { if (kind != CudnnConvKind::kForwardActivation) { return InternalError( "Invalid convolution. Conv has a side input, but kind is not fused " "conv forward: %s", instr->ToString()); } // The side input layout must match the output layout. TF_RETURN_IF_ERROR(constraints->SetOperandLayout(*output_shape, instr, 3)); } return Status::OK(); } Status GpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { // Add convolution constraints in reverse postorder that the earliest // convolution layout propagates first. This reduces the likelihood of fusion // nodes with copies. auto post_order = constraints->computation()->MakeInstructionPostOrder(); for (auto iterator = post_order.rbegin(); iterator != post_order.rend(); ++iterator) { HloInstruction* instruction = *iterator; if (IsCustomCallToDnnConvolution(*instruction)) { TF_RETURN_IF_ERROR(AddBackendConstraintsToDnnConvCustomCall( Cast<HloCustomCallInstruction>(instruction), constraints)); } // For batched dot we require the default layout. // TODO(b/112111608): This is overly conservative, the only real restriction // is that batch dimensions must be major. if (instruction->opcode() == HloOpcode::kDot && ImplementedAsGemm(*instruction) && instruction->dot_dimension_numbers().lhs_batch_dimensions_size() > 0) { // Verify that the batch dims come before the row and col dims. const DotDimensionNumbers& dim_nums = instruction->dot_dimension_numbers(); CHECK_EQ(dim_nums.lhs_batch_dimensions_size(), dim_nums.rhs_batch_dimensions_size()); CHECK_EQ(dim_nums.lhs_batch_dimensions_size() + 2, ShapeUtil::Rank(instruction->shape())); for (int64 batch_dim : dim_nums.lhs_batch_dimensions()) { CHECK_LT(batch_dim, ShapeUtil::Rank(instruction->shape()) - 2); } // Set both inputs and the output to default layout. Shape op0_shape = instruction->operand(0)->shape(); LayoutUtil::SetToDefaultLayout(&op0_shape); Shape op1_shape = instruction->operand(1)->shape(); LayoutUtil::SetToDefaultLayout(&op1_shape); Shape output_shape = instruction->shape(); LayoutUtil::SetToDefaultLayout(&output_shape); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(op0_shape, instruction, 0)); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(op1_shape, instruction, 1)); TF_RETURN_IF_ERROR( constraints->SetInstructionLayout(output_shape, instruction)); } else if (instruction->opcode() == HloOpcode::kSort && ShapeUtil::Rank(instruction->operand(0)->shape()) > 1) { // Make sure that all the operands and the output(s) have the same layout. Shape keys_shape = instruction->operand(0)->shape(); Layout keys_layout = LayoutUtil::GetDefaultLayoutForRank(ShapeUtil::Rank(keys_shape)); for (int64 i = 0; i < instruction->operand_count(); ++i) { Shape shape = instruction->operand(i)->shape(); *shape.mutable_layout() = keys_layout; TF_RETURN_IF_ERROR( constraints->SetOperandLayout(shape, instruction, i)); const LogicalBuffer* output_buffer; if (ShapeUtil::IsArray(instruction->shape())) { TF_ASSIGN_OR_RETURN( output_buffer, constraints->points_to_analysis().GetBufferDefinedAt(instruction, {})); } else { TF_ASSIGN_OR_RETURN( output_buffer, constraints->points_to_analysis().GetBufferDefinedAt(instruction, {i})); } TF_RETURN_IF_ERROR( constraints->SetBufferLayout(keys_layout, *output_buffer)); } } } return Status::OK(); } Status GpuLayoutAssignment::PropagateOperandConstraint( const OperandLayoutConstraint& layout_constraint, LayoutConstraints* constraints) { const HloInstruction* instruction = layout_constraint.instruction(); // cudnn batchnorm forward inference's result must have the same layout as its // operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget && layout_constraint.operand_no() == 0) { TF_RETURN_IF_ERROR(constraints->SetInstructionLayout( layout_constraint.shape_layout().shape(), instruction)); } // cudnn batchnorm forward training returns a tuple {output, mean, // inverse-stddev}. mean and inverse-stddev are rank 1 and so have only one // possible layout, but output is not (necessarily) rank 1, and, like in // batchnorm forward inference, must have the same layout as operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && layout_constraint.operand_no() == 0) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); } // Like forward training, cudnn batchnorm backward returns a tuple {output, // mean, inverse-stddev}, and its operand 0 and 'output' must have the same // layout. In addition, its operand 0 and operand 4 -- the 'operand' and // 'grad_output' parameters -- must have the same layout. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && (layout_constraint.operand_no() == 0 || layout_constraint.operand_no() == 4)) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); int64 operand_to_set = layout_constraint.operand_no() == 0 ? 4 : 0; TF_RETURN_IF_ERROR(constraints->SetOperandLayout( layout_constraint.shape_layout().shape(), instruction, operand_to_set)); } return LayoutAssignment::PropagateOperandConstraint(layout_constraint, constraints); } Status GpuLayoutAssignment::PropagateBufferConstraint( const BufferLayoutConstraint& buffer_constraint, LayoutConstraints* constraints) { const LogicalBuffer& buf = buffer_constraint.buffer(); const HloInstruction* instruction = buf.instruction(); Shape shape_with_layout = buf.shape(); *shape_with_layout.mutable_layout() = buffer_constraint.layout(); // Propagate output constraints to the operands of cudnn batchnorm ops. This // is the same as PropagateOperandConstraint, just in the other direction. We // need to both to fulfill our contract to LayoutAssignment. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && buf.index() == ShapeIndex({0})) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && buf.index() == ShapeIndex({0})) { // batchnorm backward has two operands, "operand" and "grad_output" whose // layouts must both match that of the result at tuple-index 0. TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/4)); } return LayoutAssignment::PropagateBufferConstraint(buffer_constraint, constraints); } } // namespace gpu } // namespace xla <commit_msg>For cuDNN >= 7.4, undo the work-around for NHWC with >2 strides for conv backward data.<commit_after>/* Copyright 2017 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/compiler/xla/service/gpu/gpu_layout_assignment.h" #include <memory> #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/gpu/stream_executor_util.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/errors.h" namespace xla { namespace gpu { using se::dnn::DataLayout; using se::dnn::FilterLayout; // Returns (input, filter, output) layouts. static std::tuple<DataLayout, FilterLayout, DataLayout> HeuristicLayoutAssignment(const HloInstruction* instr, se::StreamExecutor* stream_executor) { // DataLayout and FilterLayout uses weird enum names. Translations: // N <=> Batch or Output // C <=> Depth or Input // H <=> Y // W <=> X // // Therefore kOutputInputYX and kBatchDepthYX mean NCHW. // // If you have trouble keeping these straight, consider that all that matters // is the location of the channel dim: Is it major (NCHW), or minor (NHWC)? constexpr auto kAllNCHW = std::make_tuple(DataLayout::kBatchDepthYX, FilterLayout::kOutputInputYX, DataLayout::kBatchDepthYX); constexpr auto kAllNHWC = std::make_tuple(DataLayout::kBatchYXDepth, FilterLayout::kOutputYXInput, DataLayout::kBatchYXDepth); // If we're not Volta or not fp16, the decision is easy: Use NCHW. if (!(instr->operand(0)->shape().element_type() == xla::PrimitiveType::F16 && IsVoltaOrLater(*stream_executor))) { return kAllNCHW; } VLOG(2) << "Using heuristic to figure out layouts for " << instr->ToString(); // Empirically we've found with Volta and cudnn <= 7.3 that backward-input // convs with stride are significantly faster with NCHW layouts. // // We could have used a mixed layout combination, e.g. (NHWC, NCHW, NCHW), // which on paper gives good performance. However, there are two observations: // * a mixed layout combination is more cuDNN-bug prone, based on empirical // envidence. // * we've also observed that for mixed layouts, cuDNN transposes data back // and forth from a different layout combination. If we end up with // transposes anyway, we prefer to have them in XLA, as they can be fused. if (auto* dnn = stream_executor->AsDnn()) { auto version_status = dnn->GetVersion(); if (version_status.ok()) { auto version = version_status.ConsumeValueOrDie(); if (std::make_tuple(version.major_version(), version.minor_version()) <= std::make_tuple(7, 3) && instr->custom_call_target() == kCudnnConvBackwardInputCallTarget && window_util::HasStride(instr->window())) { return kAllNCHW; } } } // For other Volta f16 convolutions, use NHWC. return kAllNHWC; } // Adds layout constraints on the cudnn custom-call instruction. The layout // constraints are represented in terms of minor_to_major fields of both // operands and the output shape. Depending on the underlying algorithm, one of // { NCHW, NHWC } ^ 3 = 8 different layout combinations may be chosen. Status GpuLayoutAssignment::AddBackendConstraintsToDnnConvCustomCall( HloCustomCallInstruction* instr, LayoutConstraints* constraints) { Shape lhs_shape = instr->operand(0)->shape(); Shape rhs_shape = instr->operand(1)->shape(); Shape result_shape = instr->shape().tuple_shapes(0); Shape* input_shape; Shape* filter_shape; Shape* output_shape; TF_ASSIGN_OR_RETURN(auto kind, GetCudnnConvKind(instr)); switch (kind) { case CudnnConvKind::kForward: case CudnnConvKind::kForwardActivation: input_shape = &lhs_shape; filter_shape = &rhs_shape; output_shape = &result_shape; break; case CudnnConvKind::kBackwardInput: input_shape = &result_shape; filter_shape = &rhs_shape; output_shape = &lhs_shape; break; case CudnnConvKind::kBackwardFilter: input_shape = &lhs_shape; filter_shape = &result_shape; output_shape = &rhs_shape; break; } { DataLayout input; FilterLayout filter; DataLayout output; std::tie(input, filter, output) = HeuristicLayoutAssignment(instr, stream_executor_); TF_ASSIGN_OR_RETURN( std::tie(*input_shape->mutable_layout(), *filter_shape->mutable_layout(), *output_shape->mutable_layout()), StreamExecutorConvLayoutsToXlaLayouts( instr->convolution_dimension_numbers(), input, filter, output)); } // The custom call returns a tuple of (actual_result, scratch_buffer); // call_result_buf is the logical buffer for actual_result, the thing that // contains the result of the conv call. TF_ASSIGN_OR_RETURN(const LogicalBuffer* call_result_buf, constraints->points_to_analysis().GetBufferDefinedAt( instr, /*index=*/{0})); // Set layouts of the instructions' shapes. TF_RETURN_IF_ERROR(constraints->SetOperandLayout(lhs_shape, instr, 0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout(rhs_shape, instr, 1)); TF_RETURN_IF_ERROR( constraints->SetBufferLayout(result_shape.layout(), *call_result_buf)); // instr->operand(2), if exists, is the bias buffer. There is no need to // assign layout to it, as it has only one dimension. // instr->opernad(3), if exists, is the side input buffer. if (instr->operand_count() == 4) { if (kind != CudnnConvKind::kForwardActivation) { return InternalError( "Invalid convolution. Conv has a side input, but kind is not fused " "conv forward: %s", instr->ToString()); } // The side input layout must match the output layout. TF_RETURN_IF_ERROR(constraints->SetOperandLayout(*output_shape, instr, 3)); } return Status::OK(); } Status GpuLayoutAssignment::AddBackendConstraints( LayoutConstraints* constraints) { // Add convolution constraints in reverse postorder that the earliest // convolution layout propagates first. This reduces the likelihood of fusion // nodes with copies. auto post_order = constraints->computation()->MakeInstructionPostOrder(); for (auto iterator = post_order.rbegin(); iterator != post_order.rend(); ++iterator) { HloInstruction* instruction = *iterator; if (IsCustomCallToDnnConvolution(*instruction)) { TF_RETURN_IF_ERROR(AddBackendConstraintsToDnnConvCustomCall( Cast<HloCustomCallInstruction>(instruction), constraints)); } // For batched dot we require the default layout. // TODO(b/112111608): This is overly conservative, the only real restriction // is that batch dimensions must be major. if (instruction->opcode() == HloOpcode::kDot && ImplementedAsGemm(*instruction) && instruction->dot_dimension_numbers().lhs_batch_dimensions_size() > 0) { // Verify that the batch dims come before the row and col dims. const DotDimensionNumbers& dim_nums = instruction->dot_dimension_numbers(); CHECK_EQ(dim_nums.lhs_batch_dimensions_size(), dim_nums.rhs_batch_dimensions_size()); CHECK_EQ(dim_nums.lhs_batch_dimensions_size() + 2, ShapeUtil::Rank(instruction->shape())); for (int64 batch_dim : dim_nums.lhs_batch_dimensions()) { CHECK_LT(batch_dim, ShapeUtil::Rank(instruction->shape()) - 2); } // Set both inputs and the output to default layout. Shape op0_shape = instruction->operand(0)->shape(); LayoutUtil::SetToDefaultLayout(&op0_shape); Shape op1_shape = instruction->operand(1)->shape(); LayoutUtil::SetToDefaultLayout(&op1_shape); Shape output_shape = instruction->shape(); LayoutUtil::SetToDefaultLayout(&output_shape); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(op0_shape, instruction, 0)); TF_RETURN_IF_ERROR( constraints->SetOperandLayout(op1_shape, instruction, 1)); TF_RETURN_IF_ERROR( constraints->SetInstructionLayout(output_shape, instruction)); } else if (instruction->opcode() == HloOpcode::kSort && ShapeUtil::Rank(instruction->operand(0)->shape()) > 1) { // Make sure that all the operands and the output(s) have the same layout. Shape keys_shape = instruction->operand(0)->shape(); Layout keys_layout = LayoutUtil::GetDefaultLayoutForRank(ShapeUtil::Rank(keys_shape)); for (int64 i = 0; i < instruction->operand_count(); ++i) { Shape shape = instruction->operand(i)->shape(); *shape.mutable_layout() = keys_layout; TF_RETURN_IF_ERROR( constraints->SetOperandLayout(shape, instruction, i)); const LogicalBuffer* output_buffer; if (ShapeUtil::IsArray(instruction->shape())) { TF_ASSIGN_OR_RETURN( output_buffer, constraints->points_to_analysis().GetBufferDefinedAt(instruction, {})); } else { TF_ASSIGN_OR_RETURN( output_buffer, constraints->points_to_analysis().GetBufferDefinedAt(instruction, {i})); } TF_RETURN_IF_ERROR( constraints->SetBufferLayout(keys_layout, *output_buffer)); } } } return Status::OK(); } Status GpuLayoutAssignment::PropagateOperandConstraint( const OperandLayoutConstraint& layout_constraint, LayoutConstraints* constraints) { const HloInstruction* instruction = layout_constraint.instruction(); // cudnn batchnorm forward inference's result must have the same layout as its // operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget && layout_constraint.operand_no() == 0) { TF_RETURN_IF_ERROR(constraints->SetInstructionLayout( layout_constraint.shape_layout().shape(), instruction)); } // cudnn batchnorm forward training returns a tuple {output, mean, // inverse-stddev}. mean and inverse-stddev are rank 1 and so have only one // possible layout, but output is not (necessarily) rank 1, and, like in // batchnorm forward inference, must have the same layout as operand 0. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && layout_constraint.operand_no() == 0) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); } // Like forward training, cudnn batchnorm backward returns a tuple {output, // mean, inverse-stddev}, and its operand 0 and 'output' must have the same // layout. In addition, its operand 0 and operand 4 -- the 'operand' and // 'grad_output' parameters -- must have the same layout. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && (layout_constraint.operand_no() == 0 || layout_constraint.operand_no() == 4)) { TF_ASSIGN_OR_RETURN(const LogicalBuffer* out_buf, constraints->points_to_analysis().GetBufferDefinedAt( instruction, /*index=*/{0})); TF_RETURN_IF_ERROR(constraints->SetBufferLayout( layout_constraint.shape_layout().layout(), *out_buf)); int64 operand_to_set = layout_constraint.operand_no() == 0 ? 4 : 0; TF_RETURN_IF_ERROR(constraints->SetOperandLayout( layout_constraint.shape_layout().shape(), instruction, operand_to_set)); } return LayoutAssignment::PropagateOperandConstraint(layout_constraint, constraints); } Status GpuLayoutAssignment::PropagateBufferConstraint( const BufferLayoutConstraint& buffer_constraint, LayoutConstraints* constraints) { const LogicalBuffer& buf = buffer_constraint.buffer(); const HloInstruction* instruction = buf.instruction(); Shape shape_with_layout = buf.shape(); *shape_with_layout.mutable_layout() = buffer_constraint.layout(); // Propagate output constraints to the operands of cudnn batchnorm ops. This // is the same as PropagateOperandConstraint, just in the other direction. We // need to both to fulfill our contract to LayoutAssignment. if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardInferenceCallTarget) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormForwardTrainingCallTarget && buf.index() == ShapeIndex({0})) { TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); } if (instruction->opcode() == HloOpcode::kCustomCall && instruction->custom_call_target() == kCudnnBatchNormBackwardCallTarget && buf.index() == ShapeIndex({0})) { // batchnorm backward has two operands, "operand" and "grad_output" whose // layouts must both match that of the result at tuple-index 0. TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/0)); TF_RETURN_IF_ERROR(constraints->SetOperandLayout( shape_with_layout, instruction, /*operand_no=*/4)); } return LayoutAssignment::PropagateBufferConstraint(buffer_constraint, constraints); } } // namespace gpu } // namespace xla <|endoftext|>
<commit_before>/* Copyright 2019 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/compiler/xla/service/mlir_gpu/emission_context.h" #include "absl/strings/substitute.h" #include "mlir/IR/Location.h" // TF:local_config_mlir #include "mlir/IR/MLIRContext.h" // TF:local_config_mlir #include "tensorflow/compiler/xla/service/hlo_instruction.h" namespace xla { namespace mlir_gpu { EmissionContext::EmissionContext(std::unique_ptr<HloModule> module) : module_(std::move(module)), context_() { error_handler_ = [](const ErrorMap& instructions_with_error, HloModule* module) { std::set<const HloComputation*> computations_with_error; for (auto err : instructions_with_error) { computations_with_error.insert(err.first->parent()); } // TODO(tanyabelova): Log the most relevant lines of large computations // only. LOG(ERROR) << module->ToString( HloPrintOptions() .set_format_instruction( // Returns the string representation of `instr` in the following // format. ROOT? instr_name // FAILED: err_0 // FAILED: err_1 // ... [&instructions_with_error](const HloInstruction* instr, const string& instr_name, int indent, bool is_root) { string tab; for (int i = 0; i < indent; i++) { tab += " "; } string result = tab + (is_root ? "ROOT " : "") + instr_name; if (!instructions_with_error.count(instr)) { return result; } for (const string& err : instructions_with_error.at(instr)) { absl::SubstituteAndAppend(&result, "\n$0 FAILED: $1", tab, err); } return result; }) .set_print_computation( [&computations_with_error](const HloComputation* comp) { return computations_with_error.find(comp) != computations_with_error.end(); })); }; registerDiagnosticHandler(); } EmissionContext::EmissionContext( std::unique_ptr<HloModule> module, std::function<void(const ErrorMap&, HloModule*)> callback) : module_(std::move(module)), context_(), error_handler_(callback) { registerDiagnosticHandler(); } EmissionContext::~EmissionContext() { callErrorHandlerCallback(); } mlir::Location EmissionContext::getLocation(const HloInstruction* instr) { return mlir::OpaqueLoc::get<const HloInstruction*>(instr, &context_); } void EmissionContext::addError(const HloInstruction* hlo_instruction, const string& str) { instructions_with_error_[hlo_instruction].push_back(str); } void EmissionContext::setErrorHandler( std::function<void(const ErrorMap&, HloModule*)> callback) { error_handler_ = callback; } std::unique_ptr<HloModule> EmissionContext::releaseHloModule() { callErrorHandlerCallback(); return std::move(module_); } HloModule* EmissionContext::getHloModule() const { return module_.get(); } mlir::MLIRContext* EmissionContext::getContext() { return &context_; } void EmissionContext::registerDiagnosticHandler() { context_.getDiagEngine().registerHandler([&](mlir::Diagnostic& diag) { const HloInstruction* hloInstruction = mlir::OpaqueLoc::getUnderlyingLocationOrNull<const HloInstruction*>( diag.getLocation()); assert(hloInstruction); addError(hloInstruction, diag.str()); return mlir::success(); }); } void EmissionContext::callErrorHandlerCallback() { if (module_.get() && !instructions_with_error_.empty()) { error_handler_(instructions_with_error_, module_.get()); } } } // namespace mlir_gpu } // namespace xla <commit_msg>Refactor formatting lambda.<commit_after>/* Copyright 2019 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/compiler/xla/service/mlir_gpu/emission_context.h" #include "absl/strings/substitute.h" #include "mlir/IR/Location.h" // TF:local_config_mlir #include "mlir/IR/MLIRContext.h" // TF:local_config_mlir #include "tensorflow/compiler/xla/service/hlo_instruction.h" namespace xla { namespace mlir_gpu { EmissionContext::EmissionContext(std::unique_ptr<HloModule> module) : module_(std::move(module)), context_() { error_handler_ = [](const ErrorMap& instructions_with_error, HloModule* module) { std::set<const HloComputation*> computations_with_error; for (auto err : instructions_with_error) { computations_with_error.insert(err.first->parent()); } // TODO(tanyabelova): Log the most relevant lines of large computations // only. LOG(ERROR) << module->ToString( HloPrintOptions() .set_format_instruction( // Returns the string representation of `instr` in the following // format. ROOT? instr_name // FAILED: err_0 // FAILED: err_1 // ... [&instructions_with_error](const HloInstruction* instr, const string& instr_name, int indent, bool is_root) { const string tab(2 * indent, ' '); string result = absl::StrCat(tab, is_root ? "ROOT " : "", instr_name); if (!instructions_with_error.count(instr)) { return result; } for (const string& err : instructions_with_error.at(instr)) { absl::SubstituteAndAppend(&result, "\n$0 FAILED: $1", tab, err); } return result; }) .set_print_computation( [&computations_with_error](const HloComputation* comp) { return computations_with_error.find(comp) != computations_with_error.end(); })); }; registerDiagnosticHandler(); } EmissionContext::EmissionContext( std::unique_ptr<HloModule> module, std::function<void(const ErrorMap&, HloModule*)> callback) : module_(std::move(module)), context_(), error_handler_(callback) { registerDiagnosticHandler(); } EmissionContext::~EmissionContext() { callErrorHandlerCallback(); } mlir::Location EmissionContext::getLocation(const HloInstruction* instr) { return mlir::OpaqueLoc::get<const HloInstruction*>(instr, &context_); } void EmissionContext::addError(const HloInstruction* hlo_instruction, const string& str) { instructions_with_error_[hlo_instruction].push_back(str); } void EmissionContext::setErrorHandler( std::function<void(const ErrorMap&, HloModule*)> callback) { error_handler_ = callback; } std::unique_ptr<HloModule> EmissionContext::releaseHloModule() { callErrorHandlerCallback(); return std::move(module_); } HloModule* EmissionContext::getHloModule() const { return module_.get(); } mlir::MLIRContext* EmissionContext::getContext() { return &context_; } void EmissionContext::registerDiagnosticHandler() { context_.getDiagEngine().registerHandler([&](mlir::Diagnostic& diag) { const HloInstruction* hloInstruction = mlir::OpaqueLoc::getUnderlyingLocationOrNull<const HloInstruction*>( diag.getLocation()); assert(hloInstruction); addError(hloInstruction, diag.str()); return mlir::success(); }); } void EmissionContext::callErrorHandlerCallback() { if (module_.get() && !instructions_with_error_.empty()) { error_handler_(instructions_with_error_, module_.get()); } } } // namespace mlir_gpu } // namespace xla <|endoftext|>
<commit_before>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #include "DcConfiguration.hpp" #include "DefaultAuthorizationProvider.hpp" #include "LocalCluster.hpp" #include "RandomGenerator.hpp" #include "Session.hpp" #include "TelegramServerConfig.hpp" #include "TelegramServerUser.hpp" #include "Utils.hpp" // Test keys #include "keys_data.hpp" #include <QCommandLineParser> #include <QCoreApplication> #include <QDebug> #include <QFile> #include <QStandardPaths> using namespace Telegram::Server; class ConstantAuthCodeProvider : public Authorization::DefaultProvider { public: static QString s_code; protected: Authorization::Code generateCode(Session *session, const QString &identifier) override; }; QString ConstantAuthCodeProvider::s_code = QStringLiteral("11111"); Authorization::Code ConstantAuthCodeProvider::generateCode(Session *session, const QString &identifier) { Authorization::Code code; code.hash = Telegram::RandomGenerator::instance()->generate(8).toHex(); code.code = s_code; code.type = Authorization::Code::Type::Default; qInfo().nospace().noquote() << "sendAppCode(" << identifier << '/' << session->id() << "):" << " hash: " << code.hash << " code: " << code.code; return code; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); a.setOrganizationName(QLatin1String("TelegramQt")); a.setApplicationName(QLatin1String("TelegramTestServer")); const QString persistentKeyFilePath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1Literal("/TelegramTestServer.pem"); Telegram::initialize(); if (!TestKeyData::initKeyFiles()) { qCritical() << "Unable to init RSA key files."; return -1; } const Telegram::RsaKey privateKey = Telegram::RsaKey::fromFile(TestKeyData::privateKeyFileName()); if (!privateKey.isValid()) { qCritical() << "Unable to read RSA key."; return -1; } QCommandLineParser parser; parser.addHelpOption(); QCommandLineOption ipAddressOption(QStringList({ QLatin1String("a"), QLatin1String("address") })); ipAddressOption.setValueName(QLatin1String("ip")); ipAddressOption.setDefaultValue(QLatin1String("127.0.0.1")); parser.addOption(ipAddressOption); QCommandLineOption portOption(QStringList({ QLatin1String("p"), QLatin1String("port") })); portOption.setDescription(QLatin1String("first port")); portOption.setValueName(QLatin1String("port")); portOption.setDefaultValue(QLatin1String("10443")); parser.addOption(portOption); parser.process(a); Telegram::DcConfiguration dcConfig = Config().serverConfiguration(); dcConfig.dcOptions.clear(); for (quint32 i = 0; i < 3; ++i) { Telegram::DcOption dcOption; dcOption.id = i + 1; // A DC that does not accepts any transport considered as invalid in some client. // dcOption.flags = Telegram::DcOption::TcpOnly; dcOption.address = parser.value(ipAddressOption); dcOption.port = static_cast<quint16>(parser.value(portOption).toUInt() + i); dcConfig.dcOptions.append(dcOption); } LocalCluster cluster; cluster.setServerPrivateRsaKey(privateKey); cluster.setServerConfiguration(dcConfig); ConstantAuthCodeProvider authProvider; cluster.setAuthorizationProvider(&authProvider); qInfo() << "Custom auth code provider enabled. The code:" << ConstantAuthCodeProvider::s_code; qInfo() << "Start server with unsafe (not secret) encryption RSA key:"; qInfo() << " Private:" << TestKeyData::privateKeyFileName(); qInfo() << " Public PKCS1:" << TestKeyData::publicKeyPkcs1FileName(); qInfo() << " Public PKCS8:" << TestKeyData::publicKeyPkcs8FileName(); QFile::remove(persistentKeyFilePath); if (QFile::copy(TestKeyData::publicKeyPkcs1FileName(), persistentKeyFilePath)) { qInfo() << " Persistent file location:" << persistentKeyFilePath; } else { qWarning() << "Unable to save the RSA key in a persistent location."; } if (!cluster.start()) { return -2; } int retCode = a.exec(); cluster.stop(); TestKeyData::cleanupKeyFiles(); return retCode; } <commit_msg>TestServer: Add data load on start and autosave every 30 seconds<commit_after>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #include "DcConfiguration.hpp" #include "DefaultAuthorizationProvider.hpp" #include "JsonDataImporter.hpp" #include "LocalCluster.hpp" #include "RandomGenerator.hpp" #include "Session.hpp" #include "TelegramServerConfig.hpp" #include "TelegramServerUser.hpp" #include "Utils.hpp" // Test keys #include "keys_data.hpp" #include <QCommandLineParser> #include <QCoreApplication> #include <QDebug> #include <QFile> #include <QStandardPaths> #include <QTimer> using namespace Telegram::Server; class ConstantAuthCodeProvider : public Authorization::DefaultProvider { public: static QString s_code; protected: Authorization::Code generateCode(Session *session, const QString &identifier) override; }; QString ConstantAuthCodeProvider::s_code = QStringLiteral("11111"); Authorization::Code ConstantAuthCodeProvider::generateCode(Session *session, const QString &identifier) { Authorization::Code code; code.hash = Telegram::RandomGenerator::instance()->generate(8).toHex(); code.code = s_code; code.type = Authorization::Code::Type::Default; qInfo().nospace().noquote() << "sendAppCode(" << identifier << '/' << session->id() << "):" << " hash: " << code.hash << " code: " << code.code; return code; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); a.setOrganizationName(QLatin1String("TelegramQt")); a.setApplicationName(QLatin1String("TelegramTestServer")); const QString persistentKeyFilePath = QStandardPaths::writableLocation(QStandardPaths::TempLocation) + QLatin1Literal("/TelegramTestServer.pem"); Telegram::initialize(); if (!TestKeyData::initKeyFiles()) { qCritical() << "Unable to init RSA key files."; return -1; } const Telegram::RsaKey privateKey = Telegram::RsaKey::fromFile(TestKeyData::privateKeyFileName()); if (!privateKey.isValid()) { qCritical() << "Unable to read RSA key."; return -1; } QCommandLineParser parser; parser.addHelpOption(); QCommandLineOption ipAddressOption(QStringList({ QLatin1String("a"), QLatin1String("address") })); ipAddressOption.setValueName(QLatin1String("ip")); ipAddressOption.setDefaultValue(QLatin1String("127.0.0.1")); parser.addOption(ipAddressOption); QCommandLineOption portOption(QStringList({ QLatin1String("p"), QLatin1String("port") })); portOption.setDescription(QLatin1String("first port")); portOption.setValueName(QLatin1String("port")); portOption.setDefaultValue(QLatin1String("10443")); parser.addOption(portOption); parser.process(a); Telegram::DcConfiguration dcConfig = Config().serverConfiguration(); dcConfig.dcOptions.clear(); for (quint32 i = 0; i < 3; ++i) { Telegram::DcOption dcOption; dcOption.id = i + 1; // A DC that does not accepts any transport considered as invalid in some client. // dcOption.flags = Telegram::DcOption::TcpOnly; dcOption.address = parser.value(ipAddressOption); dcOption.port = static_cast<quint16>(parser.value(portOption).toUInt() + i); dcConfig.dcOptions.append(dcOption); } LocalCluster cluster; cluster.setServerPrivateRsaKey(privateKey); cluster.setServerConfiguration(dcConfig); ConstantAuthCodeProvider authProvider; cluster.setAuthorizationProvider(&authProvider); qInfo() << "Custom auth code provider enabled. The code:" << ConstantAuthCodeProvider::s_code; qInfo() << "Start server with unsafe (not secret) encryption RSA key:"; qInfo() << " Private:" << TestKeyData::privateKeyFileName(); qInfo() << " Public PKCS1:" << TestKeyData::publicKeyPkcs1FileName(); qInfo() << " Public PKCS8:" << TestKeyData::publicKeyPkcs8FileName(); QFile::remove(persistentKeyFilePath); if (QFile::copy(TestKeyData::publicKeyPkcs1FileName(), persistentKeyFilePath)) { qInfo() << " Persistent file location:" << persistentKeyFilePath; } else { qWarning() << "Unable to save the RSA key in a persistent location."; } if (!cluster.start()) { return -2; } JsonDataImporter importer; importer.setBaseDirectory(QLatin1String("TelegramServer/io")); importer.setTarget(&cluster); importer.loadData(); QTimer saveTimer; saveTimer.setInterval(30000); saveTimer.setSingleShot(false); QObject::connect(&saveTimer, &QTimer::timeout, [&importer]() { qInfo() << "Sync server data"; importer.saveData(); }); saveTimer.start(); int retCode = a.exec(); cluster.stop(); importer.saveData(); TestKeyData::cleanupKeyFiles(); return retCode; } <|endoftext|>
<commit_before>#include "BLEPad_UART.h" BLEPad_UART::BLEPad_UART(HardwareSerial &s) { hs = &s; }; int BLEPad_UART::available() { return hs->available(); } void begin(unsigned long baud) { return hs->begin(baud); } size_t BLEPad_UART::write(uint8_t c) { return hs->write(c); } void BLEPad_UART::println(const char data[]) { hs->println(data); } size_t BLEPad_UART::println(int n, int base) { return hs->println(n, base); } int BLEPad_UART::read() { return hs->read(); } <commit_msg>fix syntax<commit_after>#include "BLEPad_UART.h" BLEPad_UART::BLEPad_UART(HardwareSerial *s) { hs = s; }; void BLEPad_UART::begin(unsigned long baud) { hs->begin(baud); } size_t BLEPad_UART::write(uint8_t c) { return hs->write(c); } void BLEPad_UART::println(const char data[]) { hs->println(data); } size_t BLEPad_UART::println(int n, int base) { return hs->println(n, base); } int BLEPad_UART::read() { return hs->read(); } int BLEPad_UART::available() { return hs->available(); } <|endoftext|>
<commit_before>// This file is part of DVS-ROS - the RPG DVS ROS Package #include "dvs_renderer/renderer.h" #include <std_msgs/Float32.h> namespace dvs_renderer { Renderer::Renderer(ros::NodeHandle & nh, ros::NodeHandle nh_private) : nh_(nh), image_tracking_(nh) { got_camera_info_ = false; // get parameters of display method std::string display_method_str; nh_private.param<std::string>("display_method", display_method_str, ""); display_method_ = (display_method_str == std::string("grayscale")) ? GRAYSCALE : RED_BLUE; nh_private.param<bool>("color", color_image_, false); used_last_image_ = false; // setup subscribers and publishers event_sub_ = nh_.subscribe("events", 1, &Renderer::eventsCallback, this); camera_info_sub_ = nh_.subscribe("camera_info", 1, &Renderer::cameraInfoCallback, this); image_transport::ImageTransport it_(nh_); image_sub_ = it_.subscribe("image", 1, &Renderer::imageCallback, this); image_pub_ = it_.advertise("dvs_rendering", 1); undistorted_image_pub_ = it_.advertise("dvs_undistorted", 1); for (int i = 0; i < 2; ++i) for (int k = 0; k < 2; ++k) event_stats_[i].events_counter_[k] = 0; event_stats_[0].dt = 1; event_stats_[0].events_mean_lasttime_ = 0; event_stats_[0].events_mean_[0] = nh_.advertise<std_msgs::Float32>("events_on_mean_1", 1); event_stats_[0].events_mean_[1] = nh_.advertise<std_msgs::Float32>("events_off_mean_1", 1); event_stats_[1].dt = 5; event_stats_[1].events_mean_lasttime_ = 0; event_stats_[1].events_mean_[0] = nh_.advertise<std_msgs::Float32>("events_on_mean_5", 1); event_stats_[1].events_mean_[1] = nh_.advertise<std_msgs::Float32>("events_off_mean_5", 1); } Renderer::~Renderer() { image_pub_.shutdown(); undistorted_image_pub_.shutdown(); } void Renderer::cameraInfoCallback(const sensor_msgs::CameraInfo::ConstPtr& msg) { got_camera_info_ = true; camera_matrix_ = cv::Mat(3, 3, CV_64F); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) camera_matrix_.at<double>(cv::Point(i, j)) = msg->K[i+j*3]; dist_coeffs_ = cv::Mat(msg->D.size(), 1, CV_64F); for (int i = 0; i < msg->D.size(); i++) dist_coeffs_.at<double>(i) = msg->D[i]; } void Renderer::imageCallback(const sensor_msgs::Image::ConstPtr& msg) { image_tracking_.imageCallback(msg); cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // convert to BGR image if (msg->encoding == "rgb8") cv::cvtColor(cv_ptr->image, last_image_, CV_RGB2BGR); if (msg->encoding == "mono8") { if (color_image_) { cv::cvtColor(cv_ptr->image, last_image_, CV_BayerBG2BGR); } else { cv::cvtColor(cv_ptr->image, last_image_, CV_GRAY2BGR); } } std::cout << msg->encoding << std::endl; if (!used_last_image_) { cv_bridge::CvImage cv_image; last_image_.copyTo(cv_image.image); cv_image.encoding = "bgr8"; std::cout << "publish image from callback" << std::endl; image_pub_.publish(cv_image.toImageMsg()); } used_last_image_ = false; } void Renderer::eventsCallback(const dvs_msgs::EventArray::ConstPtr& msg) { for (int i = 0; i < msg->events.size(); ++i) { ++event_stats_[0].events_counter_[msg->events[i].polarity]; ++event_stats_[1].events_counter_[msg->events[i].polarity]; } publishStats(); image_tracking_.eventsCallback(msg); // only create image if at least one subscriber if (image_pub_.getNumSubscribers() > 0) { cv_bridge::CvImage cv_image; if (msg->events.size() > 0) { cv_image.header.stamp = msg->events[msg->events.size()/2].ts; } if (display_method_ == RED_BLUE) { cv_image.encoding = "bgr8"; if (last_image_.rows == msg->height && last_image_.cols == msg->width) { last_image_.copyTo(cv_image.image); used_last_image_ = true; } else { cv_image.image = cv::Mat(msg->height, msg->width, CV_8UC3); cv_image.image = cv::Scalar(0,0,0); } for (int i = 0; i < msg->events.size(); ++i) { const int x = msg->events[i].x; const int y = msg->events[i].y; cv_image.image.at<cv::Vec3b>(cv::Point(x, y)) = ( msg->events[i].polarity == true ? cv::Vec3b(255, 0, 0) : cv::Vec3b(0, 0, 255)); } } else { cv_image.encoding = "mono8"; if (last_image_.rows == msg->height && last_image_.cols == msg->width) { cv::cvtColor(last_image_, cv_image.image, CV_BGR2GRAY); used_last_image_ = true; } else { cv_image.image = cv::Mat(msg->height, msg->width, CV_8U); cv_image.image = cv::Scalar(128); } cv::Mat on_events = cv::Mat(msg->height, msg->width, CV_8U); on_events = cv::Scalar(0); cv::Mat off_events = cv::Mat(msg->height, msg->width, CV_8U); off_events = cv::Scalar(0); // count events per pixels with polarity for (int i = 0; i < msg->events.size(); ++i) { const int x = msg->events[i].x; const int y = msg->events[i].y; if (msg->events[i].polarity == 1) on_events.at<uint8_t>(cv::Point(x, y))++; else off_events.at<uint8_t>(cv::Point(x, y))++; } // scale image cv::normalize(on_events, on_events, 0, 128, cv::NORM_MINMAX, CV_8UC1); cv::normalize(off_events, off_events, 0, 127, cv::NORM_MINMAX, CV_8UC1); cv_image.image += on_events; cv_image.image -= off_events; } image_pub_.publish(cv_image.toImageMsg()); if (got_camera_info_ && undistorted_image_pub_.getNumSubscribers() > 0) { cv_bridge::CvImage cv_image2; cv_image2.encoding = cv_image.encoding; cv::undistort(cv_image.image, cv_image2.image, camera_matrix_, dist_coeffs_); undistorted_image_pub_.publish(cv_image2.toImageMsg()); } } } void Renderer::publishStats() { std_msgs::Float32 msg; ros::Time now = ros::Time::now(); for (int i = 0; i < 2; ++i) { if (event_stats_[i].events_mean_lasttime_ + event_stats_[i].dt <= now.toSec()) { event_stats_[i].events_mean_lasttime_ = now.toSec(); for (int k = 0; k < 2; ++k) { msg.data = (float)event_stats_[i].events_counter_[k] / event_stats_[i].dt; event_stats_[i].events_mean_[k].publish(msg); event_stats_[i].events_counter_[k] = 0; } } } } } // namespace <commit_msg>removing print line<commit_after>// This file is part of DVS-ROS - the RPG DVS ROS Package #include "dvs_renderer/renderer.h" #include <std_msgs/Float32.h> namespace dvs_renderer { Renderer::Renderer(ros::NodeHandle & nh, ros::NodeHandle nh_private) : nh_(nh), image_tracking_(nh) { got_camera_info_ = false; // get parameters of display method std::string display_method_str; nh_private.param<std::string>("display_method", display_method_str, ""); display_method_ = (display_method_str == std::string("grayscale")) ? GRAYSCALE : RED_BLUE; nh_private.param<bool>("color", color_image_, false); used_last_image_ = false; // setup subscribers and publishers event_sub_ = nh_.subscribe("events", 1, &Renderer::eventsCallback, this); camera_info_sub_ = nh_.subscribe("camera_info", 1, &Renderer::cameraInfoCallback, this); image_transport::ImageTransport it_(nh_); image_sub_ = it_.subscribe("image", 1, &Renderer::imageCallback, this); image_pub_ = it_.advertise("dvs_rendering", 1); undistorted_image_pub_ = it_.advertise("dvs_undistorted", 1); for (int i = 0; i < 2; ++i) for (int k = 0; k < 2; ++k) event_stats_[i].events_counter_[k] = 0; event_stats_[0].dt = 1; event_stats_[0].events_mean_lasttime_ = 0; event_stats_[0].events_mean_[0] = nh_.advertise<std_msgs::Float32>("events_on_mean_1", 1); event_stats_[0].events_mean_[1] = nh_.advertise<std_msgs::Float32>("events_off_mean_1", 1); event_stats_[1].dt = 5; event_stats_[1].events_mean_lasttime_ = 0; event_stats_[1].events_mean_[0] = nh_.advertise<std_msgs::Float32>("events_on_mean_5", 1); event_stats_[1].events_mean_[1] = nh_.advertise<std_msgs::Float32>("events_off_mean_5", 1); } Renderer::~Renderer() { image_pub_.shutdown(); undistorted_image_pub_.shutdown(); } void Renderer::cameraInfoCallback(const sensor_msgs::CameraInfo::ConstPtr& msg) { got_camera_info_ = true; camera_matrix_ = cv::Mat(3, 3, CV_64F); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) camera_matrix_.at<double>(cv::Point(i, j)) = msg->K[i+j*3]; dist_coeffs_ = cv::Mat(msg->D.size(), 1, CV_64F); for (int i = 0; i < msg->D.size(); i++) dist_coeffs_.at<double>(i) = msg->D[i]; } void Renderer::imageCallback(const sensor_msgs::Image::ConstPtr& msg) { image_tracking_.imageCallback(msg); cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // convert to BGR image if (msg->encoding == "rgb8") cv::cvtColor(cv_ptr->image, last_image_, CV_RGB2BGR); if (msg->encoding == "mono8") { if (color_image_) { cv::cvtColor(cv_ptr->image, last_image_, CV_BayerBG2BGR); } else { cv::cvtColor(cv_ptr->image, last_image_, CV_GRAY2BGR); } } if (!used_last_image_) { cv_bridge::CvImage cv_image; last_image_.copyTo(cv_image.image); cv_image.encoding = "bgr8"; std::cout << "publish image from callback" << std::endl; image_pub_.publish(cv_image.toImageMsg()); } used_last_image_ = false; } void Renderer::eventsCallback(const dvs_msgs::EventArray::ConstPtr& msg) { for (int i = 0; i < msg->events.size(); ++i) { ++event_stats_[0].events_counter_[msg->events[i].polarity]; ++event_stats_[1].events_counter_[msg->events[i].polarity]; } publishStats(); image_tracking_.eventsCallback(msg); // only create image if at least one subscriber if (image_pub_.getNumSubscribers() > 0) { cv_bridge::CvImage cv_image; if (msg->events.size() > 0) { cv_image.header.stamp = msg->events[msg->events.size()/2].ts; } if (display_method_ == RED_BLUE) { cv_image.encoding = "bgr8"; if (last_image_.rows == msg->height && last_image_.cols == msg->width) { last_image_.copyTo(cv_image.image); used_last_image_ = true; } else { cv_image.image = cv::Mat(msg->height, msg->width, CV_8UC3); cv_image.image = cv::Scalar(0,0,0); } for (int i = 0; i < msg->events.size(); ++i) { const int x = msg->events[i].x; const int y = msg->events[i].y; cv_image.image.at<cv::Vec3b>(cv::Point(x, y)) = ( msg->events[i].polarity == true ? cv::Vec3b(255, 0, 0) : cv::Vec3b(0, 0, 255)); } } else { cv_image.encoding = "mono8"; if (last_image_.rows == msg->height && last_image_.cols == msg->width) { cv::cvtColor(last_image_, cv_image.image, CV_BGR2GRAY); used_last_image_ = true; } else { cv_image.image = cv::Mat(msg->height, msg->width, CV_8U); cv_image.image = cv::Scalar(128); } cv::Mat on_events = cv::Mat(msg->height, msg->width, CV_8U); on_events = cv::Scalar(0); cv::Mat off_events = cv::Mat(msg->height, msg->width, CV_8U); off_events = cv::Scalar(0); // count events per pixels with polarity for (int i = 0; i < msg->events.size(); ++i) { const int x = msg->events[i].x; const int y = msg->events[i].y; if (msg->events[i].polarity == 1) on_events.at<uint8_t>(cv::Point(x, y))++; else off_events.at<uint8_t>(cv::Point(x, y))++; } // scale image cv::normalize(on_events, on_events, 0, 128, cv::NORM_MINMAX, CV_8UC1); cv::normalize(off_events, off_events, 0, 127, cv::NORM_MINMAX, CV_8UC1); cv_image.image += on_events; cv_image.image -= off_events; } image_pub_.publish(cv_image.toImageMsg()); if (got_camera_info_ && undistorted_image_pub_.getNumSubscribers() > 0) { cv_bridge::CvImage cv_image2; cv_image2.encoding = cv_image.encoding; cv::undistort(cv_image.image, cv_image2.image, camera_matrix_, dist_coeffs_); undistorted_image_pub_.publish(cv_image2.toImageMsg()); } } } void Renderer::publishStats() { std_msgs::Float32 msg; ros::Time now = ros::Time::now(); for (int i = 0; i < 2; ++i) { if (event_stats_[i].events_mean_lasttime_ + event_stats_[i].dt <= now.toSec()) { event_stats_[i].events_mean_lasttime_ = now.toSec(); for (int k = 0; k < 2; ++k) { msg.data = (float)event_stats_[i].events_counter_[k] / event_stats_[i].dt; event_stats_[i].events_mean_[k].publish(msg); event_stats_[i].events_counter_[k] = 0; } } } } } // namespace <|endoftext|>
<commit_before>/* * Copyright 2016 Andrei Pangin * * 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 <stdio.h> #include <stdlib.h> #include <cstdint> #include <string.h> #include <signal.h> #include <string> #include <sys/time.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <proto/protocol.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <unordered_set> #include "profiler.h" #include "vmEntry.h" using namespace me::serce::franky; Profiler Profiler::_instance; static void sigprofHandler(int signo, siginfo_t *siginfo, void *ucontext) { Profiler::_instance.recordSample(ucontext); } MethodName::MethodName(jmethodID method) { jclass method_class; jvmtiEnv *jvmti = VM::jvmti(); jvmti->GetMethodName(method, &_name, &_sig, NULL); jvmti->GetMethodDeclaringClass(method, &method_class); jvmti->GetClassSignature(method_class, &_class_sig, NULL); char *s; for (s = _class_sig; *s; s++) { if (*s == '/') *s = '.'; } s[-1] = 0; } MethodName::~MethodName() { jvmtiEnv *jvmti = VM::jvmti(); jvmti->Deallocate((unsigned char *) _name); jvmti->Deallocate((unsigned char *) _sig); jvmti->Deallocate((unsigned char *) _class_sig); } void CallTraceSample::assign(ASGCT_CallTrace *trace) { _call_count = 1; _num_frames = trace->num_frames; for (int i = 0; i < trace->num_frames; i++) { _frames[i] = trace->frames[i]; } } uint64_t Profiler::hashCallTrace(ASGCT_CallTrace *trace) { const uint64_t M = 0xc6a4a7935bd1e995LL; const int R = 47; uint64_t h = trace->num_frames * M; for (int i = 0; i < trace->num_frames; i++) { uint64_t k = ((uint64_t) trace->frames[i].bci << 32) ^(uint64_t) trace->frames[i].method_id; k *= M; k ^= k >> R; k *= M; h ^= k; h *= M; } h ^= h >> R; h *= M; h ^= h >> R; return h; } void Profiler::storeCallTrace(ASGCT_CallTrace *trace) { uint64_t hash = hashCallTrace(trace); int bucket = (int) (hash % MAX_CALLTRACES); int i = bucket; do { if (_hashes[i] == hash && _traces[i]._call_count > 0) { _traces[i]._call_count++; return; } else if (_hashes[i] == 0) { break; } if (++i == MAX_CALLTRACES) i = 0; } while (i != bucket); _hashes[i] = hash; _traces[i].assign(trace); } uint64_t Profiler::hashMethod(jmethodID method) { const uint64_t M = 0xc6a4a7935bd1e995LL; const int R = 17; uint64_t h = (uint64_t) method; h ^= h >> R; h *= M; h ^= h >> R; return h; } void Profiler::storeMethod(jmethodID method) { uint64_t hash = hashMethod(method); int bucket = (int) (hash % MAX_CALLTRACES); int i = bucket; do { if (_methods[i]._method == method) { _methods[i]._call_count++; return; } else if (_methods[i]._method == NULL) { break; } if (++i == MAX_CALLTRACES) i = 0; } while (i != bucket); _methods[i]._call_count = 1; _methods[i]._method = method; } void Profiler::recordSample(void *ucontext) { _calls_total++; JNIEnv *jni = VM::jni(); if (jni == NULL) { _calls_non_java++; return; } ASGCT_CallFrame frames[MAX_FRAMES]; ASGCT_CallTrace trace = {jni, MAX_FRAMES, frames}; AsyncGetCallTrace(&trace, trace.num_frames, ucontext); if (trace.num_frames > 0) { storeCallTrace(&trace); storeMethod(frames[0].method_id); } else if (trace.num_frames == -2) { _calls_gc++; } else if (trace.num_frames == -9) { _calls_deopt++; } else { _calls_unknown++; } } void Profiler::setTimer(long sec, long usec) { bool enabled = sec != 0 || usec != 0; struct sigaction sa; sa.sa_handler = enabled ? NULL : SIG_IGN; sa.sa_sigaction = enabled ? &sigprofHandler : NULL; sa.sa_flags = SA_RESTART | SA_SIGINFO; sigemptyset(&sa.sa_mask); sigaction(SIGPROF, &sa, NULL); struct itimerval itv = {{sec, usec}, {sec, usec}}; setitimer(ITIMER_PROF, &itv, NULL); } void Profiler::start(long interval) { if (_running) return; _running = true; _calls_total = _calls_non_java = _calls_gc = _calls_deopt = _calls_unknown = 0; memset(_hashes, 0, sizeof(_hashes)); memset(_traces, 0, sizeof(_traces)); memset(_methods, 0, sizeof(_methods)); setTimer(interval / 1000, interval * 1000); } void Profiler::stop() { if (!_running) return; _running = false; setTimer(0, 0); } void error(const char *msg) { std::string res = std::string("ERROR") + std::string(msg); perror(res.c_str()); exit(0); } void sendResponse(int sockfd, me::serce::franky::Response &message) { using namespace google::protobuf; using namespace google::protobuf::io; FileOutputStream raw_output(sockfd); google::protobuf::io::CodedOutputStream output(&raw_output); // Write the size. const int size = message.ByteSize(); output.WriteVarint32((uint32) size); uint8_t *buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != NULL) { // Optimization: The message fits in one buffer, so use the faster // direct-to-array serialization path. message.SerializeWithCachedSizesToArray(buffer); } else { // Slightly-slower path when the message is multiple buffers. message.SerializeWithCachedSizes(&output); if (output.HadError()) { error("HAD ERROR"); } } } void Profiler::init(int port) { portno = (uint16_t) port; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { error("opening socket"); } server = gethostbyname("localhost"); if (server == NULL) { error("unable to connect to localhost"); } struct sockaddr_in serv_addr; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { error("connecting"); } Response response; response.set_id(getpid()); response.set_type(Response_ResponseType_INIT); sendResponse(sockfd, response); while (true) { Request request; readRequest(&request); switch (request.type()) { case Request_RequestType_START_PROFILING: start(DEFAULT_INTERVAL); break; case Request_RequestType_STOP_PROFILING: stop(); writeResult(); break; case Request_RequestType_DETACH: close(sockfd); return; default: continue; } } } void Profiler::readRequest(Request *message) { using namespace google::protobuf; using namespace google::protobuf::io; FileInputStream raw_input(sockfd); google::protobuf::io::CodedInputStream input(&raw_input); // Read the size. uint32_t size; if (!input.ReadVarint32(&size)) { error("Error reading variint32"); } // Tell the stream not to read beyond that size. input.PushLimit(size); // Parse the message. if (!message->MergeFromCodedStream(&input)) { error("Error paring message 1"); } if (!input.ConsumedEntireMessage()) { error("Error paring message 2"); } } MethodInfo *fillMethodInfo(MethodInfo *methodInfo, const jmethodID &jmethod) { MethodName mn(jmethod); methodInfo->set_name(mn.name()); methodInfo->set_holder(mn.holder()); methodInfo->set_sig(mn.signature()); return methodInfo; } int64_t jMethodIdToId(jmethodID &jmethod) { return (int64_t) jmethod; } void Profiler::writeResult() { Response response; ProfilingInfo *info = new ProfilingInfo(); info->set_calls_total(_calls_total); info->set_calls_non_java(_calls_non_java); info->set_calls_gc(_calls_gc); info->set_calls_deopt(_calls_deopt); info->set_calls_unknown(_calls_unknown); std::unordered_set<jmethodID> methodIds; saveMethods(info, methodIds); saveCallTraces(info, methodIds); saveMethodIds(info, methodIds); response.set_id(getpid()); response.set_type(Response_ResponseType_PROF_INFO); response.set_allocated_prof_info(info); sendResponse(sockfd, response); } void Profiler::saveCallTraces(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) { qsort(_traces, MAX_CALLTRACES, sizeof(CallTraceSample), CallTraceSample::comparator); int max_traces = MAX_CALLTRACES; for (int i = 0; i < max_traces; i++) { const CallTraceSample &trace = _traces[i]; int samples = trace._call_count; if (samples == 0) break; CallTraceSampleInfo *sampleInfo = info->add_samples(); sampleInfo->set_call_count(trace._call_count); for (int j = 0; j < trace._num_frames; j++) { const ASGCT_CallFrame *frame = &trace._frames[j]; jmethodID jmethod = frame->method_id; if (jmethod != NULL) { CallFrame *callFrame = sampleInfo->add_frame(); callFrame->set_bci(frame->bci); callFrame->set_jmethodid(jMethodIdToId(jmethod)); methods.insert(jmethod); } } } } void Profiler::saveMethods(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) { qsort(_methods, MAX_CALLTRACES, sizeof(MethodSample), MethodSample::comparator); for (int i = 0; i < MAX_CALLTRACES; i++) { int samples = _methods[i]._call_count; if (samples == 0) break; jmethodID jmethod = _methods[i]._method; MethodSampleInfo *sampleInfo = info->add_methods(); sampleInfo->set_call_count(samples); sampleInfo->set_jmethodid(jMethodIdToId(jmethod)); methods.insert(jmethod); } } void Profiler::saveMethodIds(ProfilingInfo *info, std::unordered_set<jmethodID> &methodIds) { for (auto &jmethod: methodIds) { MethodInfo *methodInfo = info->add_methodinfos(); fillMethodInfo(methodInfo, jmethod); } } <commit_msg>fix required field<commit_after>/* * Copyright 2016 Andrei Pangin * * 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 <stdio.h> #include <stdlib.h> #include <cstdint> #include <string.h> #include <signal.h> #include <string> #include <sys/time.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <proto/protocol.pb.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <unordered_set> #include "profiler.h" #include "vmEntry.h" using namespace me::serce::franky; Profiler Profiler::_instance; static void sigprofHandler(int signo, siginfo_t *siginfo, void *ucontext) { Profiler::_instance.recordSample(ucontext); } MethodName::MethodName(jmethodID method) { jclass method_class; jvmtiEnv *jvmti = VM::jvmti(); jvmti->GetMethodName(method, &_name, &_sig, NULL); jvmti->GetMethodDeclaringClass(method, &method_class); jvmti->GetClassSignature(method_class, &_class_sig, NULL); char *s; for (s = _class_sig; *s; s++) { if (*s == '/') *s = '.'; } s[-1] = 0; } MethodName::~MethodName() { jvmtiEnv *jvmti = VM::jvmti(); jvmti->Deallocate((unsigned char *) _name); jvmti->Deallocate((unsigned char *) _sig); jvmti->Deallocate((unsigned char *) _class_sig); } void CallTraceSample::assign(ASGCT_CallTrace *trace) { _call_count = 1; _num_frames = trace->num_frames; for (int i = 0; i < trace->num_frames; i++) { _frames[i] = trace->frames[i]; } } uint64_t Profiler::hashCallTrace(ASGCT_CallTrace *trace) { const uint64_t M = 0xc6a4a7935bd1e995LL; const int R = 47; uint64_t h = trace->num_frames * M; for (int i = 0; i < trace->num_frames; i++) { uint64_t k = ((uint64_t) trace->frames[i].bci << 32) ^(uint64_t) trace->frames[i].method_id; k *= M; k ^= k >> R; k *= M; h ^= k; h *= M; } h ^= h >> R; h *= M; h ^= h >> R; return h; } void Profiler::storeCallTrace(ASGCT_CallTrace *trace) { uint64_t hash = hashCallTrace(trace); int bucket = (int) (hash % MAX_CALLTRACES); int i = bucket; do { if (_hashes[i] == hash && _traces[i]._call_count > 0) { _traces[i]._call_count++; return; } else if (_hashes[i] == 0) { break; } if (++i == MAX_CALLTRACES) i = 0; } while (i != bucket); _hashes[i] = hash; _traces[i].assign(trace); } uint64_t Profiler::hashMethod(jmethodID method) { const uint64_t M = 0xc6a4a7935bd1e995LL; const int R = 17; uint64_t h = (uint64_t) method; h ^= h >> R; h *= M; h ^= h >> R; return h; } void Profiler::storeMethod(jmethodID method) { uint64_t hash = hashMethod(method); int bucket = (int) (hash % MAX_CALLTRACES); int i = bucket; do { if (_methods[i]._method == method) { _methods[i]._call_count++; return; } else if (_methods[i]._method == NULL) { break; } if (++i == MAX_CALLTRACES) i = 0; } while (i != bucket); _methods[i]._call_count = 1; _methods[i]._method = method; } void Profiler::recordSample(void *ucontext) { _calls_total++; JNIEnv *jni = VM::jni(); if (jni == NULL) { _calls_non_java++; return; } ASGCT_CallFrame frames[MAX_FRAMES]; ASGCT_CallTrace trace = {jni, MAX_FRAMES, frames}; AsyncGetCallTrace(&trace, trace.num_frames, ucontext); if (trace.num_frames > 0) { storeCallTrace(&trace); storeMethod(frames[0].method_id); } else if (trace.num_frames == -2) { _calls_gc++; } else if (trace.num_frames == -9) { _calls_deopt++; } else { _calls_unknown++; } } void Profiler::setTimer(long sec, long usec) { bool enabled = sec != 0 || usec != 0; struct sigaction sa; sa.sa_handler = enabled ? NULL : SIG_IGN; sa.sa_sigaction = enabled ? &sigprofHandler : NULL; sa.sa_flags = SA_RESTART | SA_SIGINFO; sigemptyset(&sa.sa_mask); sigaction(SIGPROF, &sa, NULL); struct itimerval itv = {{sec, usec}, {sec, usec}}; setitimer(ITIMER_PROF, &itv, NULL); } void Profiler::start(long interval) { if (_running) return; _running = true; _calls_total = _calls_non_java = _calls_gc = _calls_deopt = _calls_unknown = 0; memset(_hashes, 0, sizeof(_hashes)); memset(_traces, 0, sizeof(_traces)); memset(_methods, 0, sizeof(_methods)); setTimer(interval / 1000, interval * 1000); } void Profiler::stop() { if (!_running) return; _running = false; setTimer(0, 0); } void error(const char *msg) { std::string res = std::string("ERROR") + std::string(msg); perror(res.c_str()); exit(0); } void sendResponse(int sockfd, me::serce::franky::Response &message) { using namespace google::protobuf; using namespace google::protobuf::io; FileOutputStream raw_output(sockfd); google::protobuf::io::CodedOutputStream output(&raw_output); // Write the size. const int size = message.ByteSize(); output.WriteVarint32((uint32) size); uint8_t *buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != NULL) { // Optimization: The message fits in one buffer, so use the faster // direct-to-array serialization path. message.SerializeWithCachedSizesToArray(buffer); } else { // Slightly-slower path when the message is multiple buffers. message.SerializeWithCachedSizes(&output); if (output.HadError()) { error("HAD ERROR"); } } } void Profiler::init(int port) { portno = (uint16_t) port; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { error("opening socket"); } server = gethostbyname("localhost"); if (server == NULL) { error("unable to connect to localhost"); } struct sockaddr_in serv_addr; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { error("connecting"); } Response response; response.set_id(getpid()); response.set_type(Response_ResponseType_INIT); sendResponse(sockfd, response); while (true) { Request request; readRequest(&request); switch (request.type()) { case Request_RequestType_START_PROFILING: start(DEFAULT_INTERVAL); break; case Request_RequestType_STOP_PROFILING: stop(); writeResult(); break; case Request_RequestType_DETACH: close(sockfd); return; default: continue; } } } void Profiler::readRequest(Request *message) { using namespace google::protobuf; using namespace google::protobuf::io; FileInputStream raw_input(sockfd); google::protobuf::io::CodedInputStream input(&raw_input); // Read the size. uint32_t size; if (!input.ReadVarint32(&size)) { error("Error reading variint32"); } // Tell the stream not to read beyond that size. input.PushLimit(size); // Parse the message. if (!message->MergeFromCodedStream(&input)) { error("Error paring message 1"); } if (!input.ConsumedEntireMessage()) { error("Error paring message 2"); } } int64_t jMethodIdToId(const jmethodID &jmethod) { return (int64_t) jmethod; } MethodInfo *fillMethodInfo(MethodInfo *methodInfo, const jmethodID &jmethod) { MethodName mn(jmethod); methodInfo->set_jmethodid(jMethodIdToId(jmethod)); methodInfo->set_name(mn.name()); methodInfo->set_holder(mn.holder()); methodInfo->set_sig(mn.signature()); return methodInfo; } void Profiler::writeResult() { Response response; ProfilingInfo *info = new ProfilingInfo(); info->set_calls_total(_calls_total); info->set_calls_non_java(_calls_non_java); info->set_calls_gc(_calls_gc); info->set_calls_deopt(_calls_deopt); info->set_calls_unknown(_calls_unknown); std::unordered_set<jmethodID> methodIds; saveMethods(info, methodIds); saveCallTraces(info, methodIds); saveMethodIds(info, methodIds); response.set_id(getpid()); response.set_type(Response_ResponseType_PROF_INFO); response.set_allocated_prof_info(info); sendResponse(sockfd, response); } void Profiler::saveCallTraces(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) { qsort(_traces, MAX_CALLTRACES, sizeof(CallTraceSample), CallTraceSample::comparator); int max_traces = MAX_CALLTRACES; for (int i = 0; i < max_traces; i++) { const CallTraceSample &trace = _traces[i]; int samples = trace._call_count; if (samples == 0) break; CallTraceSampleInfo *sampleInfo = info->add_samples(); sampleInfo->set_call_count(trace._call_count); for (int j = 0; j < trace._num_frames; j++) { const ASGCT_CallFrame *frame = &trace._frames[j]; jmethodID jmethod = frame->method_id; if (jmethod != NULL) { CallFrame *callFrame = sampleInfo->add_frame(); callFrame->set_bci(frame->bci); callFrame->set_jmethodid(jMethodIdToId(jmethod)); methods.insert(jmethod); } } } } void Profiler::saveMethods(ProfilingInfo *info, std::unordered_set<jmethodID> &methods) { qsort(_methods, MAX_CALLTRACES, sizeof(MethodSample), MethodSample::comparator); for (int i = 0; i < MAX_CALLTRACES; i++) { int samples = _methods[i]._call_count; if (samples == 0) break; jmethodID jmethod = _methods[i]._method; MethodSampleInfo *sampleInfo = info->add_methods(); sampleInfo->set_call_count(samples); sampleInfo->set_jmethodid(jMethodIdToId(jmethod)); methods.insert(jmethod); } } void Profiler::saveMethodIds(ProfilingInfo *info, std::unordered_set<jmethodID> &methodIds) { for (auto &jmethod: methodIds) { MethodInfo *methodInfo = info->add_methodinfos(); fillMethodInfo(methodInfo, jmethod); } } <|endoftext|>
<commit_before>/*************************************************************************/ /* gd_glue.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifdef MONO_GLUE_ENABLED #include "core/io/marshalls.h" #include "core/os/os.h" #include "core/string/ustring.h" #include "core/variant/array.h" #include "core/variant/variant.h" #include "core/variant/variant_parser.h" #include "../mono_gd/gd_mono_cache.h" #include "../mono_gd/gd_mono_marshal.h" #include "../mono_gd/gd_mono_utils.h" MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) { Variant ret; PackedByteArray varr = GDMonoMarshal::mono_array_to_PackedByteArray(p_bytes); Error err = decode_variant(ret, varr.ptr(), varr.size(), nullptr, p_allow_objects); if (err != OK) { ret = RTR("Not enough bytes for decoding bytes, or invalid format."); } return GDMonoMarshal::variant_to_mono_object(ret); } MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type) { Variant what = GDMonoMarshal::mono_object_to_variant(p_what); const Variant *args[1] = { &what }; Callable::CallError ce; Variant ret = Variant::construct(Variant::Type(p_type), args, 1, ce); ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, nullptr); return GDMonoMarshal::variant_to_mono_object(ret); } int godot_icall_GD_hash(MonoObject *p_var) { return GDMonoMarshal::mono_object_to_variant(p_var).hash(); } MonoObject *godot_icall_GD_instance_from_id(uint64_t p_instance_id) { return GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(ObjectID(p_instance_id))); } void godot_icall_GD_print(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } str += elem_str; } print_line(str); } void godot_icall_GD_printerr(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } str += elem_str; } print_error(str); } void godot_icall_GD_printraw(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } str += elem_str; } OS::get_singleton()->print("%s", str.utf8().get_data()); } void godot_icall_GD_prints(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } if (i) { str += " "; } str += elem_str; } print_line(str); } void godot_icall_GD_printt(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } if (i) { str += "\t"; } str += elem_str; } print_line(str); } float godot_icall_GD_randf() { return Math::randf(); } uint32_t godot_icall_GD_randi() { return Math::rand(); } void godot_icall_GD_randomize() { Math::randomize(); } double godot_icall_GD_randf_range(double from, double to) { return Math::random(from, to); } int32_t godot_icall_GD_randi_range(int32_t from, int32_t to) { return Math::random(from, to); } uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed) { uint32_t ret = Math::rand_from_seed(&seed); *newSeed = seed; return ret; } void godot_icall_GD_seed(uint64_t p_seed) { Math::seed(p_seed); } MonoString *godot_icall_GD_str(MonoArray *p_what) { String str; Array what = GDMonoMarshal::mono_array_to_Array(p_what); for (int i = 0; i < what.size(); i++) { String os = what[i].operator String(); if (i == 0) { str = os; } else { str += os; } } return GDMonoMarshal::mono_string_from_godot(str); } MonoObject *godot_icall_GD_str2var(MonoString *p_str) { Variant ret; VariantParser::StreamString ss; ss.s = GDMonoMarshal::mono_string_to_godot(p_str); String errs; int line; Error err = VariantParser::parse(&ss, ret, errs, line); if (err != OK) { String err_str = "Parse error at line " + itos(line) + ": " + errs + "."; ERR_PRINT(err_str); ret = err_str; } return GDMonoMarshal::variant_to_mono_object(ret); } MonoBoolean godot_icall_GD_type_exists(StringName *p_type) { StringName type = p_type ? *p_type : StringName(); return ClassDB::class_exists(type); } void godot_icall_GD_pusherror(MonoString *p_str) { ERR_PRINT(GDMonoMarshal::mono_string_to_godot(p_str)); } void godot_icall_GD_pushwarning(MonoString *p_str) { WARN_PRINT(GDMonoMarshal::mono_string_to_godot(p_str)); } MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_objects) { Variant var = GDMonoMarshal::mono_object_to_variant(p_var); PackedByteArray barr; int len; Error err = encode_variant(var, nullptr, len, p_full_objects); ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."); barr.resize(len); encode_variant(var, barr.ptrw(), len, p_full_objects); return GDMonoMarshal::PackedByteArray_to_mono_array(barr); } MonoString *godot_icall_GD_var2str(MonoObject *p_var) { String vars; VariantWriter::write_to_string(GDMonoMarshal::mono_object_to_variant(p_var), vars); return GDMonoMarshal::mono_string_from_godot(vars); } uint32_t godot_icall_TypeToVariantType(MonoReflectionType *p_refl_type) { return (uint32_t)GDMonoMarshal::managed_to_variant_type(ManagedType::from_reftype(p_refl_type)); } MonoObject *godot_icall_DefaultGodotTaskScheduler() { return GDMonoCache::cached_data.task_scheduler_handle->get_target(); } void godot_register_gd_icalls() { mono_add_internal_call("Godot.GD::godot_icall_GD_bytes2var", (void *)godot_icall_GD_bytes2var); mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert); mono_add_internal_call("Godot.GD::godot_icall_GD_hash", (void *)godot_icall_GD_hash); mono_add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", (void *)godot_icall_GD_instance_from_id); mono_add_internal_call("Godot.GD::godot_icall_GD_pusherror", (void *)godot_icall_GD_pusherror); mono_add_internal_call("Godot.GD::godot_icall_GD_pushwarning", (void *)godot_icall_GD_pushwarning); mono_add_internal_call("Godot.GD::godot_icall_GD_print", (void *)godot_icall_GD_print); mono_add_internal_call("Godot.GD::godot_icall_GD_printerr", (void *)godot_icall_GD_printerr); mono_add_internal_call("Godot.GD::godot_icall_GD_printraw", (void *)godot_icall_GD_printraw); mono_add_internal_call("Godot.GD::godot_icall_GD_prints", (void *)godot_icall_GD_prints); mono_add_internal_call("Godot.GD::godot_icall_GD_printt", (void *)godot_icall_GD_printt); mono_add_internal_call("Godot.GD::godot_icall_GD_randf", (void *)godot_icall_GD_randf); mono_add_internal_call("Godot.GD::godot_icall_GD_randi", (void *)godot_icall_GD_randi); mono_add_internal_call("Godot.GD::godot_icall_GD_randomize", (void *)godot_icall_GD_randomize); mono_add_internal_call("Godot.GD::godot_icall_GD_randf_range", (void *)godot_icall_GD_randf_range); mono_add_internal_call("Godot.GD::godot_icall_GD_randi_range", (void *)godot_icall_GD_randi_range); mono_add_internal_call("Godot.GD::godot_icall_GD_rand_seed", (void *)godot_icall_GD_rand_seed); mono_add_internal_call("Godot.GD::godot_icall_GD_seed", (void *)godot_icall_GD_seed); mono_add_internal_call("Godot.GD::godot_icall_GD_str", (void *)godot_icall_GD_str); mono_add_internal_call("Godot.GD::godot_icall_GD_str2var", (void *)godot_icall_GD_str2var); mono_add_internal_call("Godot.GD::godot_icall_GD_type_exists", (void *)godot_icall_GD_type_exists); mono_add_internal_call("Godot.GD::godot_icall_GD_var2bytes", (void *)godot_icall_GD_var2bytes); mono_add_internal_call("Godot.GD::godot_icall_GD_var2str", (void *)godot_icall_GD_var2str); mono_add_internal_call("Godot.GD::godot_icall_TypeToVariantType", (void *)godot_icall_TypeToVariantType); // Dispatcher mono_add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", (void *)godot_icall_DefaultGodotTaskScheduler); } #endif // MONO_GLUE_ENABLED <commit_msg>Updated gd_glue.cpp to work with the latest changes in the variant refactoring<commit_after>/*************************************************************************/ /* gd_glue.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifdef MONO_GLUE_ENABLED #include "core/io/marshalls.h" #include "core/os/os.h" #include "core/string/ustring.h" #include "core/variant/array.h" #include "core/variant/variant.h" #include "core/variant/variant_parser.h" #include "../mono_gd/gd_mono_cache.h" #include "../mono_gd/gd_mono_marshal.h" #include "../mono_gd/gd_mono_utils.h" MonoObject *godot_icall_GD_bytes2var(MonoArray *p_bytes, MonoBoolean p_allow_objects) { Variant ret; PackedByteArray varr = GDMonoMarshal::mono_array_to_PackedByteArray(p_bytes); Error err = decode_variant(ret, varr.ptr(), varr.size(), nullptr, p_allow_objects); if (err != OK) { ret = RTR("Not enough bytes for decoding bytes, or invalid format."); } return GDMonoMarshal::variant_to_mono_object(ret); } MonoObject *godot_icall_GD_convert(MonoObject *p_what, int32_t p_type) { Variant what = GDMonoMarshal::mono_object_to_variant(p_what); const Variant *args[1] = { &what }; Callable::CallError ce; Variant ret; Variant::construct(Variant::Type(p_type), ret, args, 1, ce); ERR_FAIL_COND_V(ce.error != Callable::CallError::CALL_OK, nullptr); return GDMonoMarshal::variant_to_mono_object(ret); } int godot_icall_GD_hash(MonoObject *p_var) { return GDMonoMarshal::mono_object_to_variant(p_var).hash(); } MonoObject *godot_icall_GD_instance_from_id(uint64_t p_instance_id) { return GDMonoUtils::unmanaged_get_managed(ObjectDB::get_instance(ObjectID(p_instance_id))); } void godot_icall_GD_print(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } str += elem_str; } print_line(str); } void godot_icall_GD_printerr(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } str += elem_str; } print_error(str); } void godot_icall_GD_printraw(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } str += elem_str; } OS::get_singleton()->print("%s", str.utf8().get_data()); } void godot_icall_GD_prints(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } if (i) { str += " "; } str += elem_str; } print_line(str); } void godot_icall_GD_printt(MonoArray *p_what) { String str; int length = mono_array_length(p_what); for (int i = 0; i < length; i++) { MonoObject *elem = mono_array_get(p_what, MonoObject *, i); MonoException *exc = nullptr; String elem_str = GDMonoMarshal::mono_object_to_variant_string(elem, &exc); if (exc) { GDMonoUtils::set_pending_exception(exc); return; } if (i) { str += "\t"; } str += elem_str; } print_line(str); } float godot_icall_GD_randf() { return Math::randf(); } uint32_t godot_icall_GD_randi() { return Math::rand(); } void godot_icall_GD_randomize() { Math::randomize(); } double godot_icall_GD_randf_range(double from, double to) { return Math::random(from, to); } int32_t godot_icall_GD_randi_range(int32_t from, int32_t to) { return Math::random(from, to); } uint32_t godot_icall_GD_rand_seed(uint64_t seed, uint64_t *newSeed) { uint32_t ret = Math::rand_from_seed(&seed); *newSeed = seed; return ret; } void godot_icall_GD_seed(uint64_t p_seed) { Math::seed(p_seed); } MonoString *godot_icall_GD_str(MonoArray *p_what) { String str; Array what = GDMonoMarshal::mono_array_to_Array(p_what); for (int i = 0; i < what.size(); i++) { String os = what[i].operator String(); if (i == 0) { str = os; } else { str += os; } } return GDMonoMarshal::mono_string_from_godot(str); } MonoObject *godot_icall_GD_str2var(MonoString *p_str) { Variant ret; VariantParser::StreamString ss; ss.s = GDMonoMarshal::mono_string_to_godot(p_str); String errs; int line; Error err = VariantParser::parse(&ss, ret, errs, line); if (err != OK) { String err_str = "Parse error at line " + itos(line) + ": " + errs + "."; ERR_PRINT(err_str); ret = err_str; } return GDMonoMarshal::variant_to_mono_object(ret); } MonoBoolean godot_icall_GD_type_exists(StringName *p_type) { StringName type = p_type ? *p_type : StringName(); return ClassDB::class_exists(type); } void godot_icall_GD_pusherror(MonoString *p_str) { ERR_PRINT(GDMonoMarshal::mono_string_to_godot(p_str)); } void godot_icall_GD_pushwarning(MonoString *p_str) { WARN_PRINT(GDMonoMarshal::mono_string_to_godot(p_str)); } MonoArray *godot_icall_GD_var2bytes(MonoObject *p_var, MonoBoolean p_full_objects) { Variant var = GDMonoMarshal::mono_object_to_variant(p_var); PackedByteArray barr; int len; Error err = encode_variant(var, nullptr, len, p_full_objects); ERR_FAIL_COND_V_MSG(err != OK, nullptr, "Unexpected error encoding variable to bytes, likely unserializable type found (Object or RID)."); barr.resize(len); encode_variant(var, barr.ptrw(), len, p_full_objects); return GDMonoMarshal::PackedByteArray_to_mono_array(barr); } MonoString *godot_icall_GD_var2str(MonoObject *p_var) { String vars; VariantWriter::write_to_string(GDMonoMarshal::mono_object_to_variant(p_var), vars); return GDMonoMarshal::mono_string_from_godot(vars); } uint32_t godot_icall_TypeToVariantType(MonoReflectionType *p_refl_type) { return (uint32_t)GDMonoMarshal::managed_to_variant_type(ManagedType::from_reftype(p_refl_type)); } MonoObject *godot_icall_DefaultGodotTaskScheduler() { return GDMonoCache::cached_data.task_scheduler_handle->get_target(); } void godot_register_gd_icalls() { mono_add_internal_call("Godot.GD::godot_icall_GD_bytes2var", (void *)godot_icall_GD_bytes2var); mono_add_internal_call("Godot.GD::godot_icall_GD_convert", (void *)godot_icall_GD_convert); mono_add_internal_call("Godot.GD::godot_icall_GD_hash", (void *)godot_icall_GD_hash); mono_add_internal_call("Godot.GD::godot_icall_GD_instance_from_id", (void *)godot_icall_GD_instance_from_id); mono_add_internal_call("Godot.GD::godot_icall_GD_pusherror", (void *)godot_icall_GD_pusherror); mono_add_internal_call("Godot.GD::godot_icall_GD_pushwarning", (void *)godot_icall_GD_pushwarning); mono_add_internal_call("Godot.GD::godot_icall_GD_print", (void *)godot_icall_GD_print); mono_add_internal_call("Godot.GD::godot_icall_GD_printerr", (void *)godot_icall_GD_printerr); mono_add_internal_call("Godot.GD::godot_icall_GD_printraw", (void *)godot_icall_GD_printraw); mono_add_internal_call("Godot.GD::godot_icall_GD_prints", (void *)godot_icall_GD_prints); mono_add_internal_call("Godot.GD::godot_icall_GD_printt", (void *)godot_icall_GD_printt); mono_add_internal_call("Godot.GD::godot_icall_GD_randf", (void *)godot_icall_GD_randf); mono_add_internal_call("Godot.GD::godot_icall_GD_randi", (void *)godot_icall_GD_randi); mono_add_internal_call("Godot.GD::godot_icall_GD_randomize", (void *)godot_icall_GD_randomize); mono_add_internal_call("Godot.GD::godot_icall_GD_randf_range", (void *)godot_icall_GD_randf_range); mono_add_internal_call("Godot.GD::godot_icall_GD_randi_range", (void *)godot_icall_GD_randi_range); mono_add_internal_call("Godot.GD::godot_icall_GD_rand_seed", (void *)godot_icall_GD_rand_seed); mono_add_internal_call("Godot.GD::godot_icall_GD_seed", (void *)godot_icall_GD_seed); mono_add_internal_call("Godot.GD::godot_icall_GD_str", (void *)godot_icall_GD_str); mono_add_internal_call("Godot.GD::godot_icall_GD_str2var", (void *)godot_icall_GD_str2var); mono_add_internal_call("Godot.GD::godot_icall_GD_type_exists", (void *)godot_icall_GD_type_exists); mono_add_internal_call("Godot.GD::godot_icall_GD_var2bytes", (void *)godot_icall_GD_var2bytes); mono_add_internal_call("Godot.GD::godot_icall_GD_var2str", (void *)godot_icall_GD_var2str); mono_add_internal_call("Godot.GD::godot_icall_TypeToVariantType", (void *)godot_icall_TypeToVariantType); // Dispatcher mono_add_internal_call("Godot.Dispatcher::godot_icall_DefaultGodotTaskScheduler", (void *)godot_icall_DefaultGodotTaskScheduler); } #endif // MONO_GLUE_ENABLED <|endoftext|>
<commit_before>#include "catch.hpp" #include "kangaru/kangaru.hpp" namespace test_autowire_construct { struct service1 {}; auto service_map(service1 const&) -> kgr::autowire; struct service2 { friend auto service_map(service2 const&) -> kgr::autowire; }; TEST_CASE("autowire can construct a service", "[container]") { SECTION("Without dependency") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value); (void) kgr::container{}.service<kgr::autowired<service1>>(); } SECTION("Without dependency with a friend function") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value); (void) kgr::container{}.service<kgr::autowired<service2>>(); } } } namespace test_autowire_depencency { int nb_s1_constructed; struct service1 { service1() { nb_s1_constructed++; } }; auto service_map(service1 const&) -> kgr::autowire; struct service2 { service1 s1; friend auto service_map(service2 const&) -> kgr::autowire; }; TEST_CASE("autowire can have depencencies", "[container]") { nb_s1_constructed = 0; SECTION("Without dependency") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value); (void) kgr::container{}.service<kgr::autowired<service1>>(); CHECK(nb_s1_constructed == 1); REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value); (void) kgr::container{}.service<kgr::autowired<service2>>(); CHECK(nb_s1_constructed == 2); } } } namespace test_autowire_single { int nb_s1_constructed; struct service1 { service1() { nb_s1_constructed++; } }; auto service_map(service1 const&) -> kgr::autowire_single; struct service2 { service1& s1; friend auto service_map(service2 const&) -> kgr::autowire; }; struct service3 { service3&& s3; friend auto service_map(service3 const&) -> kgr::autowire; }; struct service4 { kgr::container forked; service2 s2; friend auto service_map(service4 const&) -> kgr::autowire; }; struct service5 { kgr::container& ref; friend auto service_map(service5 const&) -> kgr::autowire_service<service5, kgr::autowire>; }; TEST_CASE("autowire single behave as a single service", "[container]") { nb_s1_constructed = 0; REQUIRE(kgr::detail::is_single<kgr::autowired<service1>>::value); kgr::container c; SECTION("When injected as dependency") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value); REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value); auto& s1 = c.service<kgr::autowired<service1>>(); CHECK(nb_s1_constructed == 1); auto s2 = c.service<kgr::autowired<service2>>(); CHECK(nb_s1_constructed == 1); REQUIRE(&s1 == &s2.s1); } SECTION("Cannot inject itself into itself") { REQUIRE(!kgr::detail::is_service_valid<kgr::autowired<service3>>::value); } SECTION("Work with multiple dependencies") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service4>>::value); (void) kgr::container{}.service<kgr::autowired<service4>>(); } } } <commit_msg>Fixed autowire test with msvc<commit_after>#include "catch.hpp" #include "kangaru/kangaru.hpp" namespace test_autowire_construct { struct service1 {}; auto service_map(service1 const&) -> kgr::autowire; struct service2 { friend auto service_map(service2 const&) -> kgr::autowire; }; TEST_CASE("autowire can construct a service", "[container]") { SECTION("Without dependency") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value); (void) kgr::container{}.service<kgr::autowired<service1>>(); } SECTION("Without dependency with a friend function") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value); (void) kgr::container{}.service<kgr::autowired<service2>>(); } } } namespace test_autowire_depencency { int nb_s1_constructed; struct service1 { service1() { nb_s1_constructed++; } }; auto service_map(service1 const&) -> kgr::autowire; struct service2 { service1 s1; friend auto service_map(service2 const&) -> kgr::autowire; }; TEST_CASE("autowire can have depencencies", "[container]") { nb_s1_constructed = 0; SECTION("Without dependency") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value); (void) kgr::container{}.service<kgr::autowired<service1>>(); CHECK(nb_s1_constructed == 1); REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value); (void) kgr::container{}.service<kgr::autowired<service2>>(); CHECK(nb_s1_constructed == 2); } } } namespace test_autowire_single { int nb_s1_constructed; struct service1 { service1() { nb_s1_constructed++; } }; auto service_map(service1 const&) -> kgr::autowire_single; struct service2 { service1& s1; friend auto service_map(service2 const&) -> kgr::autowire; }; struct service3 { service3&& s3; friend auto service_map(service3 const&) -> kgr::autowire; }; struct service4 { service4(kgr::container f, service2 s) : forked{std::move(f)}, s2{std::move(s)} {} kgr::container forked; service2 s2; friend auto service_map(service4 const&) -> kgr::autowire; }; struct service5 { kgr::container& ref; friend auto service_map(service5 const&) -> kgr::autowire_service<service5, kgr::autowire>; }; TEST_CASE("autowire single behave as a single service", "[container]") { nb_s1_constructed = 0; REQUIRE(kgr::detail::is_single<kgr::autowired<service1>>::value); kgr::container c; SECTION("When injected as dependency") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service1>>::value); REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service2>>::value); auto& s1 = c.service<kgr::autowired<service1>>(); CHECK(nb_s1_constructed == 1); auto s2 = c.service<kgr::autowired<service2>>(); CHECK(nb_s1_constructed == 1); REQUIRE(&s1 == &s2.s1); } SECTION("Cannot inject itself into itself") { REQUIRE(!kgr::detail::is_service_valid<kgr::autowired<service3>>::value); } SECTION("Work with multiple dependencies") { REQUIRE(kgr::detail::is_service_valid<kgr::autowired<service4>>::value); (void) kgr::container{}.service<kgr::autowired<service4>>(); } } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #define DLL_SVM_SUPPORT #include "dll/conv_rbm.hpp" #include "dll/dbn.hpp" #include "dll/rectifier_layer.hpp" #include "dll/lcn_layer.hpp" #include "dll/mp_layer.hpp" #include "dll/avgp_layer.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE("unit/cdbn/lcn/mnist/1", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::lcn_layer_desc<9>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("unit/cdbn/lcn/mnist/2", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<7>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::visible<dll::unit_type::GAUSSIAN>, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->template layer_get<3>().learning_rate *= 3.0; dbn->template layer_get<3>().initial_momentum = 0.9; dbn->template layer_get<3>().momentum = 0.9; dbn->pretrain(dataset.training_images, 30); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.5); //Note: This is not very stable } TEST_CASE("unit/cdbn/lcn/mnist/3", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<5>::layer_t , dll::mp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("unit/cdbn/lcn/mnist/4", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<5>::layer_t , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("unit/cdbn/lcn/mnist/5", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<7>::layer_t , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->template layer_get<3>().sigma = 2.0; dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE("unit/cdbn/lcn/mnist/6", "[cdbn][lcn][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::lcn_layer_desc<5>::layer_t , dll::avgp_layer_3d_desc<20, 12, 12, 2, 2, 1>::layer_t , dll::conv_rbm_desc_square<20, 6, 20, 4, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::lcn_layer_desc<3>::layer_t , dll::avgp_layer_3d_desc<20, 4, 4, 2, 2, 1>::layer_t >>::dbn_t; REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_pretrained()); REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_trained()); REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_pretrained()); REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_trained()); auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->template layer_get<1>().sigma = 1.0; dbn->template layer_get<4>().sigma = 1.0; dbn->display(); dbn->pretrain(dataset.training_images, 20); } <commit_msg>Test mixing LCN and dyn<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #define DLL_SVM_SUPPORT #include "dll/dyn_conv_rbm.hpp" #include "dll/conv_rbm.hpp" #include "dll/dbn.hpp" #include "dll/rectifier_layer.hpp" #include "dll/lcn_layer.hpp" #include "dll/mp_layer.hpp" #include "dll/avgp_layer.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE("unit/cdbn/lcn/mnist/1", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::lcn_layer_desc<9>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("unit/cdbn/lcn/mnist/2", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<7>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::visible<dll::unit_type::GAUSSIAN>, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->template layer_get<3>().learning_rate *= 3.0; dbn->template layer_get<3>().initial_momentum = 0.9; dbn->template layer_get<3>().momentum = 0.9; dbn->pretrain(dataset.training_images, 30); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.5); //Note: This is not very stable } TEST_CASE("unit/cdbn/lcn/mnist/3", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<5>::layer_t , dll::mp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("unit/cdbn/lcn/mnist/4", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<5>::layer_t , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("unit/cdbn/lcn/mnist/5", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::conv_rbm_desc_square<20, 12, 20, 10, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::rectifier_layer_desc<>::layer_t , dll::lcn_layer_desc<7>::layer_t , dll::avgp_layer_3d_desc<20, 10, 10, 2, 2, 1>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->template layer_get<3>().sigma = 2.0; dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE("unit/cdbn/lcn/mnist/6", "[cdbn][lcn][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 20, 12, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::lcn_layer_desc<5>::layer_t , dll::avgp_layer_3d_desc<20, 12, 12, 2, 2, 1>::layer_t , dll::conv_rbm_desc_square<20, 6, 20, 4, dll::parallel_mode, dll::momentum, dll::batch_size<10>>::layer_t , dll::lcn_layer_desc<3>::layer_t , dll::avgp_layer_3d_desc<20, 4, 4, 2, 2, 1>::layer_t >>::dbn_t; REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_pretrained()); REQUIRE(!dll::layer_traits<dbn_t::layer_type<1>>::is_trained()); REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_pretrained()); REQUIRE(!dll::layer_traits<dbn_t::layer_type<2>>::is_trained()); auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(150); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->template layer_get<1>().sigma = 1.0; dbn->template layer_get<4>().sigma = 1.0; dbn->display(); dbn->pretrain(dataset.training_images, 20); } TEST_CASE("unit/cdbn/lcn/mnist/7", "[cdbn][lcn][svm][unit]") { using dbn_t = dll::dbn_desc<dll::dbn_layers< dll::dyn_conv_rbm_desc<dll::parallel_mode, dll::momentum>::layer_t , dll::dyn_conv_rbm_desc<dll::parallel_mode, dll::momentum>::layer_t , dll::lcn_layer_desc<9>::layer_t >>::dbn_t; auto dataset = mnist::read_dataset_3d<std::vector, etl::dyn_matrix<double, 3>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->template init_layer<0>(1, 28, 28, 20, 12, 12); dbn->template init_layer<1>(20, 12, 12, 20, 10, 10); dbn->display(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <storage/cache.h> using namespace cheesebase; SCENARIO("Reading and writing to cache.") { GIVEN("A cache") { Cache cache{ "test.db", OpenMode::create_always, 8 }; } } <commit_msg>add simple Cache test case<commit_after>#include "catch.hpp" #include <storage/cache.h> using namespace cheesebase; SCENARIO("Reading and writing to cache.") { GIVEN("A cache") { Cache cache{ "test.db", OpenMode::create_always, 8 }; WHEN("data is written to a page") { const PageNr page{ 5 }; const size_t offset{ 100 }; const std::string test{ "ABCDEFGHIJKLMNOP" }; { auto p = cache.write(page); std::copy(test.begin(), test.end(), p.get_write().data() + offset); } THEN("same data can be read") { auto p = cache.read(page); REQUIRE(std::equal(test.begin(), test.end(), p.get().data() + offset)); } AND_WHEN("many other pages are read") { for (PageNr i = 0; i < 20; ++i) cache.read(i); THEN("same data can sill be read") { auto p = cache.read(page); REQUIRE(std::equal(test.begin(), test.end(), p.get().data() + offset)); } } } } } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file rtfwdsetupwidget.cpp * @author Ruben Dörfel <[email protected]> * @since 0.1.0 * @date May, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Definition of the RtFwdSetupWidget class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "rtfwdsetupwidget.h" //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace RTFWDPLUGIN; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RtFwdSetupWidget::RtFwdSetupWidget(RtFwd* toolbox, QWidget *parent) : QWidget(parent) , m_pRtFwd(toolbox) { m_ui.setupUi(this); // init line edits m_ui.m_qLineEdit_SolName->setText(m_pRtFwd->m_sSolName); m_ui.m_qLineEdit_BemName->setText(m_pRtFwd->m_sBemName); m_ui.m_qLineEdit_SourceName->setText(m_pRtFwd->m_sSourceName); m_ui.m_qLineEdit_MriName->setText(m_pRtFwd->m_sMriName); m_ui.m_qLineEdit_MinDistName->setText(m_pRtFwd->m_sMinDistOutName); m_ui.m_qLineEdit_EEGModelFile->setText(m_pRtFwd->m_sEegModelFile); m_ui.m_qLineEdit_EEGModelName->setText(m_pRtFwd->m_sEegModelName); // init checkboxes m_ui.m_check_bDoAll->setChecked(m_pRtFwd->m_bDoAll); m_ui.m_check_bIncludeEEG->setChecked(m_pRtFwd->m_bIncludeEEG); m_ui.m_check_bIncludeMeg->setChecked(m_pRtFwd->m_bIncludeMEG); m_ui.m_check_bComputeGrad->setChecked(m_pRtFwd->m_bComputeGrad); m_ui.m_check_bAccurate->setChecked(m_pRtFwd->m_bAccurate); m_ui.m_check_bDoAll->setChecked(m_pRtFwd->m_bDoAll); m_ui.m_check_bFixedOri->setChecked(m_pRtFwd->m_bFixedOri); m_ui.m_check_bFilterSpaces->setChecked(m_pRtFwd->m_bFilterSpaces); m_ui.m_check_bMriHeadIdent->setChecked(m_pRtFwd->m_bMriHeadIdent); m_ui.m_check_bUseThreads->setChecked(m_pRtFwd->m_bUseThreads); m_ui.m_check_bUseEquivEeg->setChecked(m_pRtFwd->m_bUseEquivEeg); // init Spin Boxes m_ui.m_doubleSpinBox_dMinDist->setValue(m_pRtFwd->m_fMinDist); m_ui.m_doubleSpinBox_dEegSphereRad->setValue(m_pRtFwd->m_fEegSphereRad); m_ui.m_doubleSpinBox_dVecR0x->setValue(m_pRtFwd->m_vecR0.x()); m_ui.m_doubleSpinBox_dVecR0y->setValue(m_pRtFwd->m_vecR0.y()); m_ui.m_doubleSpinBox_dVecR0z->setValue(m_pRtFwd->m_vecR0.z()); // connec line edits connect(m_ui.m_qLineEdit_SolName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeSolName); connect(m_ui.m_qLineEdit_MinDistName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeMinDistName); // connec spin boxes connect(m_ui.m_doubleSpinBox_dMinDist,static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeMinDist); connect(m_ui.m_doubleSpinBox_dEegSphereRad, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereRad); connect(m_ui.m_doubleSpinBox_dVecR0x, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin); connect(m_ui.m_doubleSpinBox_dVecR0y, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin); connect(m_ui.m_doubleSpinBox_dVecR0z, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin); // connet Bushbuttons connect(m_ui.m_qPushButton_SolNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showFwdDirDialog); connect(m_ui.m_qPushButton_BemNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showBemFileDialog); connect(m_ui.m_qPushButton_SourceNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showSourceFileDialog); connect(m_ui.m_qPushButton_MriNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMriFileDialog); connect(m_ui.m_qPushButton_MinDistOutDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMinDistDirDialog); connect(m_ui.m_qPushButton_EEGModelFileDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelFileDialog); connect(m_ui.m_qPushButton_EEGModelNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelNameDialog); } //============================================================================================================= void RtFwdSetupWidget::showFwdDirDialog() { m_sSolDir = QFileDialog::getExistingDirectory(this, tr("Select Directory to store the forward solution"), QString(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); QString t_sFileName = m_ui.m_qLineEdit_SolName->text(); m_pRtFwd->m_sSolName = m_sSolDir + "/" + t_sFileName; qDebug() << m_pRtFwd->m_sSolName; } //============================================================================================================= void RtFwdSetupWidget::changeSolName() { QString t_sFileName = m_ui.m_qLineEdit_SolName->text(); m_pRtFwd->m_sSolName = m_sSolDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::showSourceFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select Source Space"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_sSourceName = t_sFileName; m_ui.m_qLineEdit_SourceName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showBemFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select Bem Model"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_sBemName = t_sFileName; m_ui.m_qLineEdit_BemName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showMriFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select Mri-Head Transformation"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_sMriName = t_sFileName; m_ui.m_qLineEdit_MriName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showEEGModelFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select EEG model"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_sEegModelFile = t_sFileName; m_ui.m_qLineEdit_EEGModelFile->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showEEGModelNameDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select EEG model name"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_sEegModelName = t_sFileName; m_ui.m_qLineEdit_EEGModelName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showMinDistDirDialog() { m_sMinDistDir = QFileDialog::getExistingDirectory(this, tr("Select output for omitted source space"), QString(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text(); m_pRtFwd->m_sMinDistOutName = m_sMinDistDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::changeMinDistName() { QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text(); m_pRtFwd->m_sMinDistOutName = m_sMinDistDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::changeMinDist() { m_pRtFwd->m_fMinDist = m_ui.m_doubleSpinBox_dMinDist->value(); } //============================================================================================================= void RtFwdSetupWidget::changeEEGSphereRad() { m_pRtFwd->m_fEegSphereRad = m_ui.m_doubleSpinBox_dEegSphereRad->value(); } //============================================================================================================= void RtFwdSetupWidget::changeEEGSphereOrigin() { m_pRtFwd->m_vecR0.x() = m_ui.m_doubleSpinBox_dVecR0x->value(); m_pRtFwd->m_vecR0.y() = m_ui.m_doubleSpinBox_dVecR0y->value(); m_pRtFwd->m_vecR0.z() = m_ui.m_doubleSpinBox_dVecR0z->value(); std::cout << m_pRtFwd->m_vecR0 << std::endl; } //============================================================================================================= RtFwdSetupWidget::~RtFwdSetupWidget() { } <commit_msg>MAINT: replace write values dirctly to m_pSettings<commit_after>//============================================================================================================= /** * @file rtfwdsetupwidget.cpp * @author Ruben Dörfel <[email protected]> * @since 0.1.0 * @date May, 2020 * * @section LICENSE * * Copyright (C) 2020, Ruben Dörfel. 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 MNE-CPP authors 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. * * * @brief Definition of the RtFwdSetupWidget class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "rtfwdsetupwidget.h" //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QDebug> //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace RTFWDPLUGIN; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= RtFwdSetupWidget::RtFwdSetupWidget(RtFwd* toolbox, QWidget *parent) : QWidget(parent) , m_pRtFwd(toolbox) { m_ui.setupUi(this); // init line edits m_ui.m_qLineEdit_SolName->setText(m_pRtFwd->m_pFwdSettings->solname); m_ui.m_qLineEdit_BemName->setText(m_pRtFwd->m_pFwdSettings->bemname); m_ui.m_qLineEdit_SourceName->setText(m_pRtFwd->m_pFwdSettings->srcname); m_ui.m_qLineEdit_MriName->setText(m_pRtFwd->m_pFwdSettings->mriname); m_ui.m_qLineEdit_MinDistName->setText(m_pRtFwd->m_pFwdSettings->mindistoutname); m_ui.m_qLineEdit_EEGModelFile->setText(m_pRtFwd->m_pFwdSettings->eeg_model_file); m_ui.m_qLineEdit_EEGModelName->setText(m_pRtFwd->m_pFwdSettings->eeg_model_name); // init checkboxes m_ui.m_check_bDoAll->setChecked(m_pRtFwd->m_pFwdSettings->do_all); m_ui.m_check_bIncludeEEG->setChecked(m_pRtFwd->m_pFwdSettings->include_eeg); m_ui.m_check_bIncludeMeg->setChecked(m_pRtFwd->m_pFwdSettings->include_meg); m_ui.m_check_bComputeGrad->setChecked(m_pRtFwd->m_pFwdSettings->compute_grad); m_ui.m_check_bAccurate->setChecked(m_pRtFwd->m_pFwdSettings->accurate); m_ui.m_check_bFixedOri->setChecked(m_pRtFwd->m_pFwdSettings->fixed_ori); m_ui.m_check_bFilterSpaces->setChecked(m_pRtFwd->m_pFwdSettings->filter_spaces); m_ui.m_check_bMriHeadIdent->setChecked(m_pRtFwd->m_pFwdSettings->mri_head_ident); m_ui.m_check_bUseThreads->setChecked(m_pRtFwd->m_pFwdSettings->use_threads); m_ui.m_check_bUseEquivEeg->setChecked(m_pRtFwd->m_pFwdSettings->use_equiv_eeg); // init Spin Boxes m_ui.m_doubleSpinBox_dMinDist->setValue(m_pRtFwd->m_pFwdSettings->mindist); m_ui.m_doubleSpinBox_dEegSphereRad->setValue(m_pRtFwd->m_pFwdSettings->eeg_sphere_rad); m_ui.m_doubleSpinBox_dVecR0x->setValue(m_pRtFwd->m_pFwdSettings->r0.x()); m_ui.m_doubleSpinBox_dVecR0y->setValue(m_pRtFwd->m_pFwdSettings->r0.y()); m_ui.m_doubleSpinBox_dVecR0z->setValue(m_pRtFwd->m_pFwdSettings->r0.z()); // connec line edits connect(m_ui.m_qLineEdit_SolName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeSolName); connect(m_ui.m_qLineEdit_MinDistName, &QLineEdit::textChanged, this, &RtFwdSetupWidget::changeMinDistName); // connec spin boxes connect(m_ui.m_doubleSpinBox_dMinDist,static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeMinDist); connect(m_ui.m_doubleSpinBox_dEegSphereRad, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereRad); connect(m_ui.m_doubleSpinBox_dVecR0x, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin); connect(m_ui.m_doubleSpinBox_dVecR0y, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin); connect(m_ui.m_doubleSpinBox_dVecR0z, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &RtFwdSetupWidget::changeEEGSphereOrigin); // connet Bushbuttons connect(m_ui.m_qPushButton_SolNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showFwdDirDialog); connect(m_ui.m_qPushButton_BemNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showBemFileDialog); connect(m_ui.m_qPushButton_SourceNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showSourceFileDialog); connect(m_ui.m_qPushButton_MriNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMriFileDialog); connect(m_ui.m_qPushButton_MinDistOutDialog, &QPushButton::released, this, &RtFwdSetupWidget::showMinDistDirDialog); connect(m_ui.m_qPushButton_EEGModelFileDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelFileDialog); connect(m_ui.m_qPushButton_EEGModelNameDialog, &QPushButton::released, this, &RtFwdSetupWidget::showEEGModelNameDialog); } //============================================================================================================= void RtFwdSetupWidget::showFwdDirDialog() { m_sSolDir = QFileDialog::getExistingDirectory(this, tr("Select Directory to store the forward solution"), QString(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); QString t_sFileName = m_ui.m_qLineEdit_SolName->text(); m_pRtFwd->m_pFwdSettings->solname = m_sSolDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::changeSolName() { QString t_sFileName = m_ui.m_qLineEdit_SolName->text(); m_pRtFwd->m_pFwdSettings->solname = m_sSolDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::showSourceFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select Source Space"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_pFwdSettings->srcname = t_sFileName; m_ui.m_qLineEdit_SourceName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showBemFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select Bem Model"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_pFwdSettings->bemname = t_sFileName; m_ui.m_qLineEdit_BemName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showMriFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select Mri-Head Transformation"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_pFwdSettings->mriname = t_sFileName; m_ui.m_qLineEdit_MriName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showEEGModelFileDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select EEG model"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_pFwdSettings->eeg_model_file = t_sFileName; m_ui.m_qLineEdit_EEGModelFile->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showEEGModelNameDialog() { QString t_sFileName = QFileDialog::getOpenFileName(this, tr("Select EEG model name"), QString(), tr("Fif Files (*.fif)")); m_pRtFwd->m_pFwdSettings->eeg_model_name = t_sFileName; m_ui.m_qLineEdit_EEGModelName->setText(t_sFileName); } //============================================================================================================= void RtFwdSetupWidget::showMinDistDirDialog() { m_sMinDistDir = QFileDialog::getExistingDirectory(this, tr("Select output for omitted source space"), QString(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text(); m_pRtFwd->m_pFwdSettings->mindistoutname = m_sMinDistDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::changeMinDistName() { QString t_sFileName = m_ui.m_qLineEdit_MinDistName->text(); m_pRtFwd->m_pFwdSettings->mindistoutname = m_sMinDistDir + "/" + t_sFileName; } //============================================================================================================= void RtFwdSetupWidget::changeMinDist() { m_pRtFwd->m_pFwdSettings->mindist = m_ui.m_doubleSpinBox_dMinDist->value(); } //============================================================================================================= void RtFwdSetupWidget::changeEEGSphereRad() { m_pRtFwd->m_pFwdSettings->eeg_sphere_rad = m_ui.m_doubleSpinBox_dEegSphereRad->value(); } //============================================================================================================= void RtFwdSetupWidget::changeEEGSphereOrigin() { m_pRtFwd->m_pFwdSettings->r0.x() = m_ui.m_doubleSpinBox_dVecR0x->value(); m_pRtFwd->m_pFwdSettings->r0.y() = m_ui.m_doubleSpinBox_dVecR0y->value(); m_pRtFwd->m_pFwdSettings->r0.z() = m_ui.m_doubleSpinBox_dVecR0z->value(); std::cout << m_pRtFwd->m_vecR0 << std::endl; } //============================================================================================================= RtFwdSetupWidget::~RtFwdSetupWidget() { } <|endoftext|>
<commit_before>/** * (c) 2019 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include <memory> #include <gtest/gtest.h> #include <mega/command.h> #include <mega/json.h> #include <mega/megaapp.h> #include <mega/megaclient.h> #include <mega/types.h> using namespace std; using namespace mega; namespace { class MockApp_CommandGetRegisteredContacts : public MegaApp { public: using DataType = vector<tuple<string, string, string>>; int mCallCount = 0; ErrorCodes mLastError = ErrorCodes::API_EINTERNAL; std::unique_ptr<DataType> mRegisteredContacts; void getregisteredcontacts_result(const ErrorCodes e, DataType* const data) override { ++mCallCount; mLastError = e; if (data) { mRegisteredContacts = std::unique_ptr<DataType>{new DataType{*data}}; } else { assert(e != ErrorCodes::API_OK); } } }; } // anonymous TEST(Commands, CommandGetRegisteredContacts_processResult_happyPath) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"[email protected]","id":"13","ud":"[email protected]"},{"eud":"+64271234567","id":"42","ud":"+64 27 123 4567"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); const vector<tuple<string, string, string>> expected{ {"[email protected]", "13", "[email protected]"}, {"+64271234567", "42", "+64 27 123 4567"}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mRegisteredContacts); ASSERT_EQ(expected, *app.mRegisteredContacts); ASSERT_EQ((long)jsonLength, std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_onlyOneContact) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"[email protected]","id":"13","ud":"[email protected]"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); const vector<tuple<string, string, string>> expected{ {"[email protected]", "13", "[email protected]"}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mRegisteredContacts); ASSERT_EQ(expected, *app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_extraFieldShouldBeIgnored) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"[email protected]","id":"13","ud":"[email protected]","blah":"42"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); const vector<tuple<string, string, string>> expected{ {"[email protected]", "13", "[email protected]"}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mRegisteredContacts); ASSERT_EQ(expected, *app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_invalidResponse) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"[email protected]","id":"13","blah":"[email protected]"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EINTERNAL, app.mLastError); ASSERT_EQ(nullptr, app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_errorCodeReceived) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = "-8"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EEXPIRED, app.mLastError); ASSERT_EQ(nullptr, app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } namespace { class MockApp_CommandGetCountryCallingCodes : public MegaApp { public: using DataType = map<string, vector<string>>; int mCallCount = 0; ErrorCodes mLastError = ErrorCodes::API_EINTERNAL; std::unique_ptr<DataType> mCountryCallingCodes; void getcountrycallingcodes_result(const ErrorCodes e, DataType* const data) override { ++mCallCount; mLastError = e; if (data) { mCountryCallingCodes = std::unique_ptr<DataType>{new DataType{*data}}; } else { assert(e != ErrorCodes::API_OK); } } }; } // anonymous TEST(Commands, CommandGetCountryCallingCodes_processResult_happyPath) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","l":[376]},{"cc":"AE","l":[971,13]},{"cc":"AF","l":[93,13,42]})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); const map<string, vector<string>> expected{ {"AD", {"376"}}, {"AE", {"971", "13"}}, {"AF", {"93", "13", "42"}}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mCountryCallingCodes); ASSERT_EQ(expected, *app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_onlyOneCountry) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","l":[12,376]})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); const map<string, vector<string>> expected{ {"AD", {"12", "376"}}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mCountryCallingCodes); ASSERT_EQ(expected, *app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_extraFieldShouldBeIgnored) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","l":[12,376],"blah":"42"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); const map<string, vector<string>> expected{ {"AD", {"12", "376"}}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mCountryCallingCodes); ASSERT_EQ(expected, *app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_invalidResponse) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","blah":[12,376]})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EINTERNAL, app.mLastError); ASSERT_EQ(nullptr, app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_errorCodeReceived) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = "-8"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EEXPIRED, app.mLastError); ASSERT_EQ(nullptr, app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } <commit_msg>Fix unit tests for `usabd` command (v:1)<commit_after>/** * (c) 2019 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include <memory> #include <gtest/gtest.h> #include <mega/command.h> #include <mega/json.h> #include <mega/megaapp.h> #include <mega/megaclient.h> #include <mega/types.h> using namespace std; using namespace mega; namespace { class MockApp_CommandGetRegisteredContacts : public MegaApp { public: using DataType = vector<tuple<string, string, string>>; int mCallCount = 0; ErrorCodes mLastError = ErrorCodes::API_EINTERNAL; std::unique_ptr<DataType> mRegisteredContacts; void getregisteredcontacts_result(const ErrorCodes e, DataType* const data) override { ++mCallCount; mLastError = e; if (data) { mRegisteredContacts = std::unique_ptr<DataType>{new DataType{*data}}; } else { assert(e != ErrorCodes::API_OK); } } }; } // anonymous TEST(Commands, CommandGetRegisteredContacts_processResult_happyPath) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"Zm9vQG1lZ2EuY28ubno","id":"13","ud":"Zm9vQG1lZ2EuY28ubno"},{"eud":"KzY0MjcxMjM0NTY3","id":"42","ud":"KzY0IDI3IDEyMyA0NTY3"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); const vector<tuple<string, string, string>> expected{ {"[email protected]", "13", "[email protected]"}, {"+64271234567", "42", "+64 27 123 4567"}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mRegisteredContacts); ASSERT_EQ(expected, *app.mRegisteredContacts); ASSERT_EQ((long)jsonLength, std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_onlyOneContact) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"Zm9vQG1lZ2EuY28ubno","id":"13","ud":"Zm9vQG1lZ2EuY28ubno"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); const vector<tuple<string, string, string>> expected{ {"[email protected]", "13", "[email protected]"}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mRegisteredContacts); ASSERT_EQ(expected, *app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_extraFieldShouldBeIgnored) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"Zm9vQG1lZ2EuY28ubno","id":"13","ud":"Zm9vQG1lZ2EuY28ubno","YmxhaA":"42"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); const vector<tuple<string, string, string>> expected{ {"[email protected]", "13", "[email protected]"}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mRegisteredContacts); ASSERT_EQ(expected, *app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_invalidResponse) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = R"({"eud":"Zm9vQG1lZ2EuY28ubno","id":"13","YmxhaA":"42"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EINTERNAL, app.mLastError); ASSERT_EQ(nullptr, app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetRegisteredContacts_processResult_errorCodeReceived) { MockApp_CommandGetRegisteredContacts app; JSON json; json.pos = "-8"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetRegisteredContacts::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EEXPIRED, app.mLastError); ASSERT_EQ(nullptr, app.mRegisteredContacts); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } namespace { class MockApp_CommandGetCountryCallingCodes : public MegaApp { public: using DataType = map<string, vector<string>>; int mCallCount = 0; ErrorCodes mLastError = ErrorCodes::API_EINTERNAL; std::unique_ptr<DataType> mCountryCallingCodes; void getcountrycallingcodes_result(const ErrorCodes e, DataType* const data) override { ++mCallCount; mLastError = e; if (data) { mCountryCallingCodes = std::unique_ptr<DataType>{new DataType{*data}}; } else { assert(e != ErrorCodes::API_OK); } } }; } // anonymous TEST(Commands, CommandGetCountryCallingCodes_processResult_happyPath) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","l":[376]},{"cc":"AE","l":[971,13]},{"cc":"AF","l":[93,13,42]})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); const map<string, vector<string>> expected{ {"AD", {"376"}}, {"AE", {"971", "13"}}, {"AF", {"93", "13", "42"}}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mCountryCallingCodes); ASSERT_EQ(expected, *app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_onlyOneCountry) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","l":[12,376]})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); const map<string, vector<string>> expected{ {"AD", {"12", "376"}}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mCountryCallingCodes); ASSERT_EQ(expected, *app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_extraFieldShouldBeIgnored) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","l":[12,376],"blah":"42"})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); const map<string, vector<string>> expected{ {"AD", {"12", "376"}}, }; ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_OK, app.mLastError); ASSERT_NE(nullptr, app.mCountryCallingCodes); ASSERT_EQ(expected, *app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_invalidResponse) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = R"({"cc":"AD","blah":[12,376]})"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EINTERNAL, app.mLastError); ASSERT_EQ(nullptr, app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } TEST(Commands, CommandGetCountryCallingCodes_processResult_errorCodeReceived) { MockApp_CommandGetCountryCallingCodes app; JSON json; json.pos = "-8"; const auto jsonBegin = json.pos; const auto jsonLength = strlen(json.pos); CommandGetCountryCallingCodes::processResult(app, json); ASSERT_EQ(1, app.mCallCount); ASSERT_EQ(API_EEXPIRED, app.mLastError); ASSERT_EQ(nullptr, app.mCountryCallingCodes); ASSERT_EQ(ptrdiff_t(jsonLength), std::distance(jsonBegin, json.pos)); // assert json has been parsed all the way } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "core/do_with.hh" #include "cql_test_env.hh" #include "cql3/query_processor.hh" #include "cql3/query_options.hh" #include "core/distributed.hh" #include "core/shared_ptr.hh" #include "utils/UUID_gen.hh" #include "message/messaging_service.hh" #include "service/storage_service.hh" class in_memory_cql_env : public cql_test_env { public: static auto constexpr ks_name = "ks"; private: ::shared_ptr<distributed<database>> _db; ::shared_ptr<distributed<cql3::query_processor>> _qp; ::shared_ptr<distributed<service::storage_proxy>> _proxy; private: struct core_local_state { service::client_state client_state; core_local_state() : client_state(service::client_state::for_internal_calls()) { client_state.set_keyspace(ks_name); } future<> stop() { return make_ready_future<>(); } }; distributed<core_local_state> _core_local; private: auto make_query_state() { return ::make_shared<service::query_state>(_core_local.local().client_state); } public: in_memory_cql_env( ::shared_ptr<distributed<database>> db, ::shared_ptr<distributed<cql3::query_processor>> qp, ::shared_ptr<distributed<service::storage_proxy>> proxy) : _db(db) , _qp(qp) , _proxy(proxy) { } virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override { auto qs = make_query_state(); return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {}); } virtual future<::shared_ptr<transport::messages::result_message>> execute_cql( const sstring& text, std::unique_ptr<cql3::query_options> qo) override { auto qs = make_query_state(); auto& lqo = *qo; return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {}); } virtual future<bytes> prepare(sstring query) override { return _qp->invoke_on_all([query, this] (auto& local_qp) { auto qs = this->make_query_state(); return local_qp.prepare(query, *qs).finally([qs] {}).discard_result(); }).then([query, this] { return _qp->local().compute_id(query, ks_name); }); } virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared( bytes id, std::vector<bytes_opt> values) override { auto prepared = _qp->local().get_prepared(id); assert(bool(prepared)); auto stmt = prepared->statement; assert(stmt->get_bound_terms() == values.size()); int32_t protocol_version = 3; auto options = ::make_shared<cql3::query_options>(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false, cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit()); options->prepare(prepared->bound_names); auto qs = make_query_state(); return _qp->local().process_statement(stmt, *qs, *options) .finally([options, qs] {}); } virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override { auto id = utils::UUID_gen::get_time_UUID(); return _db->invoke_on_all([schema_maker, id, this] (database& db) { auto cf_schema = make_lw_shared(schema_maker(ks_name)); cf_schema->set_id(id); auto& ks = db.find_keyspace(ks_name); auto cfg = ks.make_column_family_config(*cf_schema); db.add_column_family(column_family(std::move(cf_schema), std::move(cfg))); }); } virtual future<> require_keyspace_exists(const sstring& ks_name) override { auto& db = _db->local(); assert(db.has_keyspace(ks_name)); return make_ready_future<>(); } virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override { auto& db = _db->local(); assert(db.has_schema(ks_name, table_name)); return make_ready_future<>(); } virtual future<> require_column_has_value(const sstring& table_name, std::vector<boost::any> pk, std::vector<boost::any> ck, const sstring& column_name, boost::any expected) override { auto& db = _db->local(); auto& cf = db.find_column_family(ks_name, table_name); auto schema = cf.schema(); auto pkey = partition_key::from_deeply_exploded(*schema, pk); auto dk = dht::global_partitioner().decorate_key(*schema, pkey); auto shard = db.shard_of(dk._token); return _db->invoke_on(shard, [pkey = std::move(pkey), ck = std::move(ck), ks_name = std::move(ks_name), column_name = std::move(column_name), expected = std::move(expected), table_name = std::move(table_name)] (database& db) mutable { auto& cf = db.find_column_family(ks_name, table_name); auto schema = cf.schema(); return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) { assert(p != nullptr); auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck)); assert(row != nullptr); auto col_def = schema->get_column_definition(utf8_type->decompose(column_name)); assert(col_def != nullptr); const atomic_cell_or_collection* cell = row->find_cell(col_def->id); if (!cell) { assert(((void)"column not set", 0)); } bytes actual; if (!col_def->type->is_multi_cell()) { auto c = cell->as_atomic_cell(); assert(c.is_live()); actual = { c.value().begin(), c.value().end() }; } else { auto c = cell->as_collection_mutation(); auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type); actual = type->to_value(type->deserialize_mutation_form(c), serialization_format::internal()); } assert(col_def->type->equal(actual, col_def->type->decompose(expected))); }); }); } virtual database& local_db() override { return _db->local(); } future<> start() { return _core_local.start().then([this] () { auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name}); return execute_cql(query).discard_result().then([] { return make_ready_future<>(); }); }); } virtual future<> stop() override { return _core_local.stop().then([this] { return _qp->stop().then([this] { return _proxy->stop().then([this] { return _db->stop().then([] { return locator::i_endpoint_snitch::stop_snitch(); }); }); }); }); } }; future<> init_once() { static bool done = false; if (!done) { done = true; return service::init_storage_service().then([] { return net::init_messaging_service("127.0.0.1", db::config::seed_provider_type()).then([] { }); }); } else { return make_ready_future(); } } future<::shared_ptr<cql_test_env>> make_env_for_test() { return init_once().then([] { using namespace locator; return i_endpoint_snitch::create_snitch("org.apache.cassandra.locator.SimpleSnitch").then([] { auto db = ::make_shared<distributed<database>>(); auto cfg = make_lw_shared<db::config>(); cfg->data_file_directories() = {}; return db->start(std::move(*cfg)).then([db] { auto proxy = ::make_shared<distributed<service::storage_proxy>>(); auto qp = ::make_shared<distributed<cql3::query_processor>>(); return proxy->start(std::ref(*db)).then([qp, db, proxy] { return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] { auto env = ::make_shared<in_memory_cql_env>(db, qp, proxy); return env->start().then([env] () -> ::shared_ptr<cql_test_env> { return env; }); }); }); }); }); }); } future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) { return make_env_for_test().then([func = std::move(func)] (auto e) mutable { return do_with(std::move(func), [e] (auto& f) { return f(*e); }).finally([e] { return e->stop().finally([e] {}); }); }); } <commit_msg>tests: Add missing blank line<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #include "core/do_with.hh" #include "cql_test_env.hh" #include "cql3/query_processor.hh" #include "cql3/query_options.hh" #include "core/distributed.hh" #include "core/shared_ptr.hh" #include "utils/UUID_gen.hh" #include "message/messaging_service.hh" #include "service/storage_service.hh" class in_memory_cql_env : public cql_test_env { public: static auto constexpr ks_name = "ks"; private: ::shared_ptr<distributed<database>> _db; ::shared_ptr<distributed<cql3::query_processor>> _qp; ::shared_ptr<distributed<service::storage_proxy>> _proxy; private: struct core_local_state { service::client_state client_state; core_local_state() : client_state(service::client_state::for_internal_calls()) { client_state.set_keyspace(ks_name); } future<> stop() { return make_ready_future<>(); } }; distributed<core_local_state> _core_local; private: auto make_query_state() { return ::make_shared<service::query_state>(_core_local.local().client_state); } public: in_memory_cql_env( ::shared_ptr<distributed<database>> db, ::shared_ptr<distributed<cql3::query_processor>> qp, ::shared_ptr<distributed<service::storage_proxy>> proxy) : _db(db) , _qp(qp) , _proxy(proxy) { } virtual future<::shared_ptr<transport::messages::result_message>> execute_cql(const sstring& text) override { auto qs = make_query_state(); return _qp->local().process(text, *qs, cql3::query_options::DEFAULT).finally([qs] {}); } virtual future<::shared_ptr<transport::messages::result_message>> execute_cql( const sstring& text, std::unique_ptr<cql3::query_options> qo) override { auto qs = make_query_state(); auto& lqo = *qo; return _qp->local().process(text, *qs, lqo).finally([qs, qo = std::move(qo)] {}); } virtual future<bytes> prepare(sstring query) override { return _qp->invoke_on_all([query, this] (auto& local_qp) { auto qs = this->make_query_state(); return local_qp.prepare(query, *qs).finally([qs] {}).discard_result(); }).then([query, this] { return _qp->local().compute_id(query, ks_name); }); } virtual future<::shared_ptr<transport::messages::result_message>> execute_prepared( bytes id, std::vector<bytes_opt> values) override { auto prepared = _qp->local().get_prepared(id); assert(bool(prepared)); auto stmt = prepared->statement; assert(stmt->get_bound_terms() == values.size()); int32_t protocol_version = 3; auto options = ::make_shared<cql3::query_options>(db::consistency_level::ONE, std::experimental::nullopt, std::move(values), false, cql3::query_options::specific_options::DEFAULT, protocol_version, serialization_format::use_32_bit()); options->prepare(prepared->bound_names); auto qs = make_query_state(); return _qp->local().process_statement(stmt, *qs, *options) .finally([options, qs] {}); } virtual future<> create_table(std::function<schema(const sstring&)> schema_maker) override { auto id = utils::UUID_gen::get_time_UUID(); return _db->invoke_on_all([schema_maker, id, this] (database& db) { auto cf_schema = make_lw_shared(schema_maker(ks_name)); cf_schema->set_id(id); auto& ks = db.find_keyspace(ks_name); auto cfg = ks.make_column_family_config(*cf_schema); db.add_column_family(column_family(std::move(cf_schema), std::move(cfg))); }); } virtual future<> require_keyspace_exists(const sstring& ks_name) override { auto& db = _db->local(); assert(db.has_keyspace(ks_name)); return make_ready_future<>(); } virtual future<> require_table_exists(const sstring& ks_name, const sstring& table_name) override { auto& db = _db->local(); assert(db.has_schema(ks_name, table_name)); return make_ready_future<>(); } virtual future<> require_column_has_value(const sstring& table_name, std::vector<boost::any> pk, std::vector<boost::any> ck, const sstring& column_name, boost::any expected) override { auto& db = _db->local(); auto& cf = db.find_column_family(ks_name, table_name); auto schema = cf.schema(); auto pkey = partition_key::from_deeply_exploded(*schema, pk); auto dk = dht::global_partitioner().decorate_key(*schema, pkey); auto shard = db.shard_of(dk._token); return _db->invoke_on(shard, [pkey = std::move(pkey), ck = std::move(ck), ks_name = std::move(ks_name), column_name = std::move(column_name), expected = std::move(expected), table_name = std::move(table_name)] (database& db) mutable { auto& cf = db.find_column_family(ks_name, table_name); auto schema = cf.schema(); return cf.find_partition_slow(pkey).then([schema, ck, column_name, expected] (column_family::const_mutation_partition_ptr p) { assert(p != nullptr); auto row = p->find_row(clustering_key::from_deeply_exploded(*schema, ck)); assert(row != nullptr); auto col_def = schema->get_column_definition(utf8_type->decompose(column_name)); assert(col_def != nullptr); const atomic_cell_or_collection* cell = row->find_cell(col_def->id); if (!cell) { assert(((void)"column not set", 0)); } bytes actual; if (!col_def->type->is_multi_cell()) { auto c = cell->as_atomic_cell(); assert(c.is_live()); actual = { c.value().begin(), c.value().end() }; } else { auto c = cell->as_collection_mutation(); auto type = dynamic_pointer_cast<const collection_type_impl>(col_def->type); actual = type->to_value(type->deserialize_mutation_form(c), serialization_format::internal()); } assert(col_def->type->equal(actual, col_def->type->decompose(expected))); }); }); } virtual database& local_db() override { return _db->local(); } future<> start() { return _core_local.start().then([this] () { auto query = sprint("create keyspace %s with replication = { 'class' : 'org.apache.cassandra.locator.SimpleStrategy', 'replication_factor' : 1 };", sstring{ks_name}); return execute_cql(query).discard_result().then([] { return make_ready_future<>(); }); }); } virtual future<> stop() override { return _core_local.stop().then([this] { return _qp->stop().then([this] { return _proxy->stop().then([this] { return _db->stop().then([] { return locator::i_endpoint_snitch::stop_snitch(); }); }); }); }); } }; future<> init_once() { static bool done = false; if (!done) { done = true; return service::init_storage_service().then([] { return net::init_messaging_service("127.0.0.1", db::config::seed_provider_type()).then([] { }); }); } else { return make_ready_future(); } } future<::shared_ptr<cql_test_env>> make_env_for_test() { return init_once().then([] { using namespace locator; return i_endpoint_snitch::create_snitch("org.apache.cassandra.locator.SimpleSnitch").then([] { auto db = ::make_shared<distributed<database>>(); auto cfg = make_lw_shared<db::config>(); cfg->data_file_directories() = {}; return db->start(std::move(*cfg)).then([db] { auto proxy = ::make_shared<distributed<service::storage_proxy>>(); auto qp = ::make_shared<distributed<cql3::query_processor>>(); return proxy->start(std::ref(*db)).then([qp, db, proxy] { return qp->start(std::ref(*proxy), std::ref(*db)).then([db, proxy, qp] { auto env = ::make_shared<in_memory_cql_env>(db, qp, proxy); return env->start().then([env] () -> ::shared_ptr<cql_test_env> { return env; }); }); }); }); }); }); } future<> do_with_cql_env(std::function<future<>(cql_test_env&)> func) { return make_env_for_test().then([func = std::move(func)] (auto e) mutable { return do_with(std::move(func), [e] (auto& f) { return f(*e); }).finally([e] { return e->stop().finally([e] {}); }); }); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek ([email protected]) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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 UNITTEST_SUPPORT_INCLUDED #define UNITTEST_SUPPORT_INCLUDED // support functions for unit testing #include <boost/cstdint.hpp> #include <string> // verify if two files are the same extern bool compare_files(const std::string& file1, const std::string& file2); struct TestConfig { TestConfig(); static std::string g_data_path; }; #endif <commit_msg>added note about FP compares<commit_after>/****************************************************************************** * Copyright (c) 2011, Michael P. Gerlek ([email protected]) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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 UNITTEST_SUPPORT_INCLUDED #define UNITTEST_SUPPORT_INCLUDED // support functions for unit testing #include <boost/cstdint.hpp> #include <string> // verify if two files are the same extern bool compare_files(const std::string& file1, const std::string& file2); struct TestConfig { TestConfig(); static std::string g_data_path; }; // for comparing to floating point values, use // BOOST_CHECK_CLOSE(a,b,perc) // where perc is a percentage value in the range [0..100] (typically) #endif <|endoftext|>
<commit_before>#include <string> #include <iostream> #include <sstream> #include <stdexcept> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include "SearchParser.h" using namespace xercesc; using namespace std; // Error codes enum { ERROR_ARGS = 1, ERROR_XERCES_INIT, ERROR_PARSE, ERROR_EMPTY_DOCUMENT }; /** * Constructor initializes xerces-C libraries. * The XML tags and attributes which we seek are defined. * The xerces-C DOM parser infrastructure is initialized. */ SearchParser::SearchParser() { try { XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure } catch( XMLException& e ) { char* message = XMLString::transcode( e.getMessage() ); cerr << "XML toolkit initialization error: " << message << endl; XMLString::release( &message ); // throw exception here to return ERROR_XERCES_INIT } // Tags and attributes used in XML file. // Can't call transcode till after Xerces Initialize() TAG_root = XMLString::transcode("feed"); TAG_status = XMLString::transcode("entry"); TAG_text = XMLString::transcode("title"); TAG_user = XMLString::transcode("name"); TAG_username = XMLString::transcode("uri"); //Using the <uri> instead of <author> get us around some encoding bugs:) TAG_image = XMLString::transcode("link"); TAG_date = XMLString::transcode("published"); TAG_id = XMLString::transcode("id"); TAG_error = XMLString::transcode("error"); ATTR_href = XMLString::transcode("href"); m_ConfigFileParser = new XercesDOMParser; tweetPtr = NULL; numberOfEntries = 0; } /** * Class destructor frees memory used to hold the XML tag and * attribute definitions. It als terminates use of the xerces-C * framework. */ SearchParser::~SearchParser() { delete m_ConfigFileParser; XMLString::release( &TAG_root ); XMLString::release( &TAG_status ); XMLString::release( &TAG_text ); XMLString::release( &TAG_username ); XMLString::release( &TAG_user ); XMLString::release( &TAG_image); XMLString::release( &TAG_date ); XMLString::release( &TAG_id ); XMLString::release( &TAG_error ); try { XMLPlatformUtils::Terminate(); // Terminate Xerces } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); cerr << "XML ttolkit teardown error: " << message << endl; XMLString::release( &message ); } for(int i = 0; i < numberOfEntries; i++) { delete tweetPtr[i]; } delete tweetPtr; } int SearchParser::count() { return numberOfEntries; } HTTweet** SearchParser::getTweets() { return tweetPtr; } /** * This function: * - Tests the access and availability of the XML configuration file. * - Configures the xerces-c DOM parser. * - Reads and extracts the pertinent information from the XML config file. * * @param in configFile The text string name of the HLA configuration file. */ void SearchParser::readData(const char *xmlData) throw( std::runtime_error ) { // Configure DOM parser. m_ConfigFileParser->setValidationScheme( XercesDOMParser::Val_Never ); m_ConfigFileParser->setDoNamespaces( false ); m_ConfigFileParser->setDoSchema( false ); m_ConfigFileParser->setLoadExternalDTD( false ); try { // Creating a memory buffer inputsource for the parser const char *chId = std::string("TimeLineData").c_str(); MemBufInputSource memSource((XMLByte *)xmlData, (XMLSize_t)strlen(xmlData)*sizeof(char), chId); std::cout << "Passing buffer to parser" << std::endl; m_ConfigFileParser->parse( memSource ); // no need to free this pointer - owned by the parent parser object DOMDocument* xmlDoc = m_ConfigFileParser->getDocument(); // Get the top-level element: NAme is "root". No attributes for "root" DOMElement* elementRoot = xmlDoc->getDocumentElement(); if( !elementRoot ) { string theName("HaikuTwitter"); string theText("Could not retrieve data. Please check your internet connection."); string theUrl("error"); string theDate(""); tweetPtr = new HTTweet*[1]; tweetPtr[0] = new HTTweet(theName, theText, theUrl, theDate); numberOfEntries++; return; } // Parse XML file for tags of interest: "error" DOMNodeList* statusNodes = elementRoot->getElementsByTagName(TAG_error); for(XMLSize_t i = 0; i < statusNodes->getLength(); i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_error)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); /*Transcode to UTF-8*/ XMLTransService::Codes resValue; XMLByte utf8String[150]; XMLSize_t blabla = 0; XMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor("UTF-8", resValue, 150); t->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw); delete t; string textString((char *)utf8String); string theName("HaikuTwitter"); string theUrl("error"); string theDate(""); tweetPtr = new HTTweet*[1]; tweetPtr[0] = new HTTweet(theName, textString, theUrl, theDate); numberOfEntries++; return; } } } // Parse XML file for tags of interest: "text" statusNodes = elementRoot->getElementsByTagName(TAG_text); XMLSize_t nodeCount = statusNodes->getLength(); tweetPtr = new HTTweet*[nodeCount]; for(XMLSize_t i = 1; i < nodeCount; i++) { //We skip first item (item 0), not interested in atom main title DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_text)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); /*Transcode to UTF-8*/ XMLTransService::Codes resValue; XMLByte utf8String[150]; XMLSize_t blabla = 0; XMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor("UTF-8", resValue, 150); t->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw); delete t; string textString((char *)utf8String); textString.erase(textString.length()-5, 5); //Last three chars is garbage! tweetPtr[numberOfEntries] = new HTTweet(); tweetPtr[numberOfEntries]->setText(textString); numberOfEntries++; } } } nodeCount--; //Because we skipped item(0) // Parse XML file for tags of interest: "id" statusNodes = elementRoot->getElementsByTagName(TAG_id); for(XMLSize_t i = 0; i < nodeCount; i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_id)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); char *rawString = XMLString::transcode(textNode->getWholeText()); //Remove last character, holds ugly symbol. //rawString[strlen(rawString)-5] = '\0'; tweetPtr[i]->setId(atoi(rawString)); delete rawString; } } } // Parse XML file for tags of interest: "screen_name" statusNodes = elementRoot->getElementsByTagName(TAG_username); for(XMLSize_t i = 0; i < nodeCount; i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_username)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); char *rawString = XMLString::transcode(textNode->getWholeText()); /*Remove last 11 or 9 characters, junk.*/ if(i < nodeCount-1) rawString[strlen(rawString)-11] = '\0'; else rawString[strlen(rawString)-9] = '\0'; string textString(rawString+19); //Skip "http://twitter.com/" and we've got the username tweetPtr[i]->setScreenName(textString); delete rawString; } } } // Parse XML file for tags of interest: "link" statusNodes = elementRoot->getElementsByTagName(TAG_image); //Result will give us 5 links in header that we don't care about. //If there is more than 14 entries, we will get a link to the next page, so skip that too. int skipCount = 5; if(nodeCount > 14) skipCount++; for(XMLSize_t i = skipCount; i < (nodeCount*2)+skipCount; i+=2) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_image)) { const XMLCh* href = currentElement->getAttribute(ATTR_href); char *rawString = XMLString::transcode(href); string textString(rawString); tweetPtr[(i-skipCount)/2]->setProfileImageUrl(textString); delete rawString; } } } // Parse XML file for tags of interest: "published" statusNodes = elementRoot->getElementsByTagName(TAG_date); for(XMLSize_t i = 0; i < nodeCount; i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_date)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); char *rawString = XMLString::transcode(textNode->getWholeText()); //Remove last character, holds ugly symbol. rawString[strlen(rawString)-3] = '\0'; string textString(rawString); tweetPtr[i]->setPublishedDate(textString); delete rawString; } } } } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); ostringstream errBuf; errBuf << "Error parsing file: " << message << flush; XMLString::release( &message ); } std::cout << "Done parsing XML" << std::endl; } <commit_msg>Fixed bug that crashed the app when parsing for profile images on certain searches.<commit_after>#include <string> #include <iostream> #include <sstream> #include <stdexcept> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include "SearchParser.h" using namespace xercesc; using namespace std; // Error codes enum { ERROR_ARGS = 1, ERROR_XERCES_INIT, ERROR_PARSE, ERROR_EMPTY_DOCUMENT }; /** * Constructor initializes xerces-C libraries. * The XML tags and attributes which we seek are defined. * The xerces-C DOM parser infrastructure is initialized. */ SearchParser::SearchParser() { try { XMLPlatformUtils::Initialize(); // Initialize Xerces infrastructure } catch( XMLException& e ) { char* message = XMLString::transcode( e.getMessage() ); cerr << "XML toolkit initialization error: " << message << endl; XMLString::release( &message ); // throw exception here to return ERROR_XERCES_INIT } // Tags and attributes used in XML file. // Can't call transcode till after Xerces Initialize() TAG_root = XMLString::transcode("feed"); TAG_status = XMLString::transcode("entry"); TAG_text = XMLString::transcode("title"); TAG_user = XMLString::transcode("name"); TAG_username = XMLString::transcode("uri"); //Using the <uri> instead of <author> get us around some encoding bugs:) TAG_image = XMLString::transcode("link"); TAG_date = XMLString::transcode("published"); TAG_id = XMLString::transcode("id"); TAG_error = XMLString::transcode("error"); ATTR_href = XMLString::transcode("href"); m_ConfigFileParser = new XercesDOMParser; tweetPtr = NULL; numberOfEntries = 0; } /** * Class destructor frees memory used to hold the XML tag and * attribute definitions. It als terminates use of the xerces-C * framework. */ SearchParser::~SearchParser() { delete m_ConfigFileParser; XMLString::release( &TAG_root ); XMLString::release( &TAG_status ); XMLString::release( &TAG_text ); XMLString::release( &TAG_username ); XMLString::release( &TAG_user ); XMLString::release( &TAG_image); XMLString::release( &TAG_date ); XMLString::release( &TAG_id ); XMLString::release( &TAG_error ); try { XMLPlatformUtils::Terminate(); // Terminate Xerces } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); cerr << "XML ttolkit teardown error: " << message << endl; XMLString::release( &message ); } for(int i = 0; i < numberOfEntries; i++) { delete tweetPtr[i]; } delete tweetPtr; } int SearchParser::count() { return numberOfEntries; } HTTweet** SearchParser::getTweets() { return tweetPtr; } /** * This function: * - Tests the access and availability of the XML configuration file. * - Configures the xerces-c DOM parser. * - Reads and extracts the pertinent information from the XML config file. * * @param in configFile The text string name of the HLA configuration file. */ void SearchParser::readData(const char *xmlData) throw( std::runtime_error ) { // Configure DOM parser. m_ConfigFileParser->setValidationScheme( XercesDOMParser::Val_Never ); m_ConfigFileParser->setDoNamespaces( false ); m_ConfigFileParser->setDoSchema( false ); m_ConfigFileParser->setLoadExternalDTD( false ); try { // Creating a memory buffer inputsource for the parser const char *chId = std::string("TimeLineData").c_str(); MemBufInputSource memSource((XMLByte *)xmlData, (XMLSize_t)strlen(xmlData)*sizeof(char), chId); std::cout << "Passing buffer to parser" << std::endl; m_ConfigFileParser->parse( memSource ); // no need to free this pointer - owned by the parent parser object DOMDocument* xmlDoc = m_ConfigFileParser->getDocument(); // Get the top-level element: NAme is "root". No attributes for "root" DOMElement* elementRoot = xmlDoc->getDocumentElement(); if( !elementRoot ) { string theName("HaikuTwitter"); string theText("Could not retrieve data. Please check your internet connection."); string theUrl("error"); string theDate(""); tweetPtr = new HTTweet*[1]; tweetPtr[0] = new HTTweet(theName, theText, theUrl, theDate); numberOfEntries++; return; } // Parse XML file for tags of interest: "error" DOMNodeList* statusNodes = elementRoot->getElementsByTagName(TAG_error); for(XMLSize_t i = 0; i < statusNodes->getLength(); i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_error)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); /*Transcode to UTF-8*/ XMLTransService::Codes resValue; XMLByte utf8String[150]; XMLSize_t blabla = 0; XMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor("UTF-8", resValue, 150); t->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw); delete t; string textString((char *)utf8String); string theName("HaikuTwitter"); string theUrl("error"); string theDate(""); tweetPtr = new HTTweet*[1]; tweetPtr[0] = new HTTweet(theName, textString, theUrl, theDate); numberOfEntries++; return; } } } // Parse XML file for tags of interest: "text" statusNodes = elementRoot->getElementsByTagName(TAG_text); XMLSize_t nodeCount = statusNodes->getLength(); tweetPtr = new HTTweet*[nodeCount]; for(XMLSize_t i = 1; i < nodeCount; i++) { //We skip first item (item 0), not interested in atom main title DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_text)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); /*Transcode to UTF-8*/ XMLTransService::Codes resValue; XMLByte utf8String[150]; XMLSize_t blabla = 0; XMLTranscoder *t = XMLPlatformUtils::fgTransService->makeNewTranscoderFor("UTF-8", resValue, 150); t->transcodeTo(textNode->getWholeText(), (XMLSize_t)150, utf8String, (XMLSize_t)150, blabla, XMLTranscoder::UnRep_Throw); delete t; string textString((char *)utf8String); textString.erase(textString.length()-5, 5); //Last three chars is garbage! tweetPtr[numberOfEntries] = new HTTweet(); tweetPtr[numberOfEntries]->setText(textString); numberOfEntries++; } } } nodeCount--; //Because we skipped item(0) // Parse XML file for tags of interest: "id" statusNodes = elementRoot->getElementsByTagName(TAG_id); for(XMLSize_t i = 0; i < nodeCount; i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_id)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); char *rawString = XMLString::transcode(textNode->getWholeText()); //Remove last character, holds ugly symbol. //rawString[strlen(rawString)-5] = '\0'; tweetPtr[i]->setId(atoi(rawString)); delete rawString; } } } // Parse XML file for tags of interest: "screen_name" statusNodes = elementRoot->getElementsByTagName(TAG_username); for(XMLSize_t i = 0; i < nodeCount; i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_username)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); char *rawString = XMLString::transcode(textNode->getWholeText()); /*Remove last 11 or 9 characters, junk.*/ if(i < nodeCount-1) rawString[strlen(rawString)-11] = '\0'; else rawString[strlen(rawString)-9] = '\0'; string textString(rawString+19); //Skip "http://twitter.com/"... and we've got the username:) tweetPtr[i]->setScreenName(textString); delete rawString; } } } // Parse XML file for tags of interest: "link" statusNodes = elementRoot->getElementsByTagName(TAG_image); //Result will give us 5 links in header that we don't care about. int skipCount = 5; for(XMLSize_t i = skipCount; i < (nodeCount*2)+skipCount; i+=2) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_image)) { const XMLCh* href = currentElement->getAttribute(ATTR_href); char *rawString = XMLString::transcode(href); string textString(rawString); if(textString.find("statuses", 0) != std::string::npos) { //There was an extra link the header i--; //Step back skipCount++; //Skip the extra header link. } else tweetPtr[(i-skipCount)/2]->setProfileImageUrl(textString); delete rawString; } } } // Parse XML file for tags of interest: "published" statusNodes = elementRoot->getElementsByTagName(TAG_date); for(XMLSize_t i = 0; i < nodeCount; i++) { DOMNode* currentNode = statusNodes->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), TAG_date)) { DOMText* textNode = dynamic_cast< xercesc::DOMText* >( currentElement->getChildNodes()->item(0) ); char *rawString = XMLString::transcode(textNode->getWholeText()); //Remove last character, holds ugly symbol. rawString[strlen(rawString)-3] = '\0'; string textString(rawString); tweetPtr[i]->setPublishedDate(textString); delete rawString; } } } } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); ostringstream errBuf; errBuf << "Error parsing file: " << message << flush; XMLString::release( &message ); } std::cout << "Done parsing XML" << std::endl; } <|endoftext|>
<commit_before>// Copyright 2016-2019 Chris Conway (Koderz). All Rights Reserved. #include "RuntimeMeshProviderPlane.h" FRuntimeMeshProviderPlaneProxy::FRuntimeMeshProviderPlaneProxy(TWeakObjectPtr<URuntimeMeshProvider> InParent) : FRuntimeMeshProviderProxy(InParent) { } FRuntimeMeshProviderPlaneProxy::~FRuntimeMeshProviderPlaneProxy() { } void FRuntimeMeshProviderPlaneProxy::UpdateProxyParameters(URuntimeMeshProvider* ParentProvider, bool bIsInitialSetup) { URuntimeMeshProviderPlane* PlaneProvider = Cast<URuntimeMeshProviderPlane>(ParentProvider); MarkCollisionDirty(); if (LocationA != PlaneProvider->LocationA || LocationB != PlaneProvider->LocationB || LocationC != PlaneProvider->LocationC) { LocationA = PlaneProvider->LocationA; LocationB = PlaneProvider->LocationB; LocationC = PlaneProvider->LocationC; MarkSectionDirty(INDEX_NONE, 0); //Mark all LODs dirty } bool bHasParameterChanged = false; TArray<int32> VertsABBefore = VertsAB, VertsACBefore = VertsAC; if (VertsAB != PlaneProvider->VertsAB) { bHasParameterChanged = true; VertsAB = PlaneProvider->VertsAB; } if (VertsAC != PlaneProvider->VertsAC) { bHasParameterChanged = true; VertsAC = PlaneProvider->VertsAC; } if (ScreenSize != PlaneProvider->ScreenSize) { bHasParameterChanged = true; ScreenSize = PlaneProvider->ScreenSize; } Material = PlaneProvider->Material; int32 MaxLODBefore = MaxLOD; MaxLOD = GetMaximumPossibleLOD(); if (!bIsInitialSetup && bHasParameterChanged) { for (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++) { FRuntimeMeshLODProperties LODProperties; LODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex]; ConfigureLOD(LODIndex, LODProperties); if (LODIndex >= MaxLODBefore) //Section is new { FRuntimeMeshSectionProperties Properties; Properties.bCastsShadow = true; Properties.bIsVisible = true; Properties.MaterialSlot = 0; Properties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent; CreateSection(LODIndex, 0, Properties); } else if(VertsAB[LODIndex] != VertsABBefore[LODIndex] || VertsAC[LODIndex] != VertsACBefore[LODIndex]) { MarkSectionDirty(LODIndex, 0); } } for (int32 LODIndex = MaxLOD; LODIndex < MaxLODBefore; LODIndex++) { RemoveSection(LODIndex, 0); } } } void FRuntimeMeshProviderPlaneProxy::Initialize() { for (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++) { FRuntimeMeshLODProperties LODProperties; LODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex]; ConfigureLOD(LODIndex, LODProperties); FRuntimeMeshSectionProperties Properties; Properties.bCastsShadow = true; Properties.bIsVisible = true; Properties.MaterialSlot = 0; Properties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent; CreateSection(LODIndex, 0, Properties); } SetupMaterialSlot(0, FName("Plane Base"), Material.Get()); } bool FRuntimeMeshProviderPlaneProxy::GetSectionMeshForLOD(int32 LODIndex, int32 SectionId, FRuntimeMeshRenderableMeshData& MeshData) { // We should only ever be queried for section 0 check(SectionId == 0 && LODIndex <= MaxLOD); //UE_LOG(LogTemp, Log, TEXT("Asking for LOD index %i, VertsAB len = %i, VertsAC len = %i"), LODIndex, VertsAB.Num(), VertsAC.Num()); //return true; int32 NumVertsAB = VertsAB[LODIndex], NumVertsAC = VertsAC[LODIndex]; FVector ABDirection = (LocationB - LocationA) / (NumVertsAB - 1); FVector ACDirection = (LocationC - LocationA) / (NumVertsAB - 1); FVector Normal = (ACDirection ^ ABDirection).GetUnsafeNormal(); FVector Tangent = ABDirection.GetUnsafeNormal(); FColor Color = FColor::White; for (int32 ACIndex = 0; ACIndex < NumVertsAC; ACIndex++) { for (int32 ABIndex = 0; ABIndex < NumVertsAB; ABIndex++) { FVector Location = LocationA + ABDirection * ABIndex + ACDirection * ACIndex; FVector2D TexCoord = FVector2D(ABIndex / NumVertsAB, ACIndex / NumVertsAC); MeshData.Positions.Add(Location); MeshData.Tangents.Add(Normal, Tangent); MeshData.Colors.Add(Color); MeshData.TexCoords.Add(TexCoord); if (ABIndex != NumVertsAB - 1 && ACIndex != NumVertsAC - 1) { int32 AIndex = ABIndex + ACIndex * NumVertsAB; int32 BIndex = AIndex + 1; int32 CIndex = AIndex + NumVertsAB; int32 DIndex = CIndex + 1; MeshData.Triangles.AddTriangle(AIndex, CIndex, BIndex); MeshData.Triangles.AddTriangle(BIndex, CIndex, DIndex); } } } return true; } FRuntimeMeshCollisionSettings FRuntimeMeshProviderPlaneProxy::GetCollisionSettings() { FRuntimeMeshCollisionSettings Settings; Settings.bUseAsyncCooking = false; Settings.bUseComplexAsSimple = true; return Settings; } bool FRuntimeMeshProviderPlaneProxy::HasCollisionMesh() { return false; } bool FRuntimeMeshProviderPlaneProxy::GetCollisionMesh(FRuntimeMeshCollisionData& CollisionData) { return false; } URuntimeMeshProviderPlane::URuntimeMeshProviderPlane() { LocationA = FVector(100, -100, 0); LocationB = FVector(100, 100, 0); LocationC = FVector(-100, -100, 0); VertsAB = TArray<int32>({100,10,1}); VertsAC = TArray<int32>({100,10,1}); ScreenSize = TArray<float>({ 0.1,0.01 }); }<commit_msg>Plane provider now automatically switches to 32bit indices<commit_after>// Copyright 2016-2019 Chris Conway (Koderz). All Rights Reserved. #include "RuntimeMeshProviderPlane.h" FRuntimeMeshProviderPlaneProxy::FRuntimeMeshProviderPlaneProxy(TWeakObjectPtr<URuntimeMeshProvider> InParent) : FRuntimeMeshProviderProxy(InParent) { } FRuntimeMeshProviderPlaneProxy::~FRuntimeMeshProviderPlaneProxy() { } void FRuntimeMeshProviderPlaneProxy::UpdateProxyParameters(URuntimeMeshProvider* ParentProvider, bool bIsInitialSetup) { URuntimeMeshProviderPlane* PlaneProvider = Cast<URuntimeMeshProviderPlane>(ParentProvider); MarkCollisionDirty(); if (LocationA != PlaneProvider->LocationA || LocationB != PlaneProvider->LocationB || LocationC != PlaneProvider->LocationC) { LocationA = PlaneProvider->LocationA; LocationB = PlaneProvider->LocationB; LocationC = PlaneProvider->LocationC; MarkSectionDirty(INDEX_NONE, 0); //Mark all LODs dirty } bool bHasParameterChanged = false; TArray<int32> VertsABBefore = VertsAB, VertsACBefore = VertsAC; if (VertsAB != PlaneProvider->VertsAB) { bHasParameterChanged = true; VertsAB = PlaneProvider->VertsAB; } if (VertsAC != PlaneProvider->VertsAC) { bHasParameterChanged = true; VertsAC = PlaneProvider->VertsAC; } if (ScreenSize != PlaneProvider->ScreenSize) { bHasParameterChanged = true; ScreenSize = PlaneProvider->ScreenSize; } Material = PlaneProvider->Material; int32 MaxLODBefore = MaxLOD; MaxLOD = GetMaximumPossibleLOD(); if (!bIsInitialSetup && bHasParameterChanged) { for (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++) { FRuntimeMeshLODProperties LODProperties; LODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex]; ConfigureLOD(LODIndex, LODProperties); if (LODIndex >= MaxLODBefore) //Section is new { FRuntimeMeshSectionProperties Properties; Properties.bCastsShadow = true; Properties.bIsVisible = true; Properties.MaterialSlot = 0; Properties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent; Properties.bWants32BitIndices = VertsAB[LODIndex] * VertsAC[LODIndex] >= 1 << 16; //Use 32 bit indices if more than 2^16 verts are needed CreateSection(LODIndex, 0, Properties); } else if(VertsAB[LODIndex] != VertsABBefore[LODIndex] || VertsAC[LODIndex] != VertsACBefore[LODIndex]) { MarkSectionDirty(LODIndex, 0); } } for (int32 LODIndex = MaxLOD; LODIndex < MaxLODBefore; LODIndex++) { RemoveSection(LODIndex, 0); } } } void FRuntimeMeshProviderPlaneProxy::Initialize() { for (int32 LODIndex = 0; LODIndex <= MaxLOD; LODIndex++) { FRuntimeMeshLODProperties LODProperties; LODProperties.ScreenSize = LODIndex >= ScreenSize.Num() ? 0.0 : ScreenSize[LODIndex]; ConfigureLOD(LODIndex, LODProperties); FRuntimeMeshSectionProperties Properties; Properties.bCastsShadow = true; Properties.bIsVisible = true; Properties.MaterialSlot = 0; Properties.UpdateFrequency = ERuntimeMeshUpdateFrequency::Infrequent; CreateSection(LODIndex, 0, Properties); } SetupMaterialSlot(0, FName("Plane Base"), Material.Get()); } bool FRuntimeMeshProviderPlaneProxy::GetSectionMeshForLOD(int32 LODIndex, int32 SectionId, FRuntimeMeshRenderableMeshData& MeshData) { // We should only ever be queried for section 0 check(SectionId == 0 && LODIndex <= MaxLOD); //UE_LOG(LogTemp, Log, TEXT("Asking for LOD index %i, VertsAB len = %i, VertsAC len = %i"), LODIndex, VertsAB.Num(), VertsAC.Num()); //return true; int32 NumVertsAB = VertsAB[LODIndex], NumVertsAC = VertsAC[LODIndex]; FVector ABDirection = (LocationB - LocationA) / (NumVertsAB - 1); FVector ACDirection = (LocationC - LocationA) / (NumVertsAB - 1); FVector Normal = (ACDirection ^ ABDirection).GetUnsafeNormal(); FVector Tangent = ABDirection.GetUnsafeNormal(); FColor Color = FColor::White; for (int32 ACIndex = 0; ACIndex < NumVertsAC; ACIndex++) { for (int32 ABIndex = 0; ABIndex < NumVertsAB; ABIndex++) { FVector Location = LocationA + ABDirection * ABIndex + ACDirection * ACIndex; FVector2D TexCoord = FVector2D(ABIndex / NumVertsAB, ACIndex / NumVertsAC); MeshData.Positions.Add(Location); MeshData.Tangents.Add(Normal, Tangent); MeshData.Colors.Add(Color); MeshData.TexCoords.Add(TexCoord); if (ABIndex != NumVertsAB - 1 && ACIndex != NumVertsAC - 1) { int32 AIndex = ABIndex + ACIndex * NumVertsAB; int32 BIndex = AIndex + 1; int32 CIndex = AIndex + NumVertsAB; int32 DIndex = CIndex + 1; MeshData.Triangles.AddTriangle(AIndex, CIndex, BIndex); MeshData.Triangles.AddTriangle(BIndex, CIndex, DIndex); } } } return true; } FRuntimeMeshCollisionSettings FRuntimeMeshProviderPlaneProxy::GetCollisionSettings() { FRuntimeMeshCollisionSettings Settings; Settings.bUseAsyncCooking = false; Settings.bUseComplexAsSimple = true; return Settings; } bool FRuntimeMeshProviderPlaneProxy::HasCollisionMesh() { return false; } bool FRuntimeMeshProviderPlaneProxy::GetCollisionMesh(FRuntimeMeshCollisionData& CollisionData) { return false; } URuntimeMeshProviderPlane::URuntimeMeshProviderPlane() { LocationA = FVector(100, -100, 0); LocationB = FVector(100, 100, 0); LocationC = FVector(-100, -100, 0); VertsAB = TArray<int32>({100,10,1}); VertsAC = TArray<int32>({100,10,1}); ScreenSize = TArray<float>({ 0.1,0.01 }); }<|endoftext|>
<commit_before>// (C) 2014 Arek Olek #pragma once #include <iostream> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graphviz.hpp> struct graph_writer { bool labels; graph_writer(bool l) : labels(l) {} virtual void operator()(std::ostream& out) const { if(labels) { out << "node [shape=circle color=burlywood style=filled]" << std::endl; out << "edge [style=dashed color=burlywood penwidth=4 weight=0.3]" << std::endl; } else { out << "node [shape=point color=burlywood style=filled label=\"\" width=0.05]" << std::endl; out << "edge [style=dashed color=burlywood]" << std::endl; } } }; template <class Graph> class node_writer { public: node_writer(Graph const& t) : T(t) {} template <class V> void operator()(std::ostream& out, const V& v) const { if(out_degree(v, T) == 1) out << "[shape=square color=forestgreen]"; if(out_degree(v, T) > 2) out << "[color=brown1]"; } private: Graph const& T; }; template <class Graph> node_writer<Graph> make_node_writer(Graph t) { return node_writer<Graph>(t); } template<class Graph, class Tree> class edge_writer { public: edge_writer(Graph const& g, Tree const& t) : G(g), T(t) {} template <class E> void operator()(std::ostream& out, const E& e) const { if(edge(source(e, G), target(e, G), T).second) out << "[style=solid]"; } private: Graph const& G; Tree const& T; }; template<class Graph, class Tree> edge_writer<Graph, Tree> make_edge_writer(Graph g, Tree t) { return edge_writer<Graph, Tree>(g, t); } template<class Graph, class Tree> void show(std::string file, Graph const & g, Tree const & t) { std::ofstream f(file); write_graphviz(f, g, make_node_writer(t), make_edge_writer(g, t), graph_writer(num_vertices(g) < 30)); f.close(); } <commit_msg>draw graph without spanning tree<commit_after>// (C) 2014 Arek Olek #pragma once #include <iostream> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graphviz.hpp> struct graph_writer { bool labels; graph_writer(bool l) : labels(l) {} virtual void operator()(std::ostream& out) const { if(labels) { out << "node [shape=circle color=burlywood style=filled]" << std::endl; out << "edge [style=dashed color=burlywood penwidth=4 weight=0.3]" << std::endl; } else { out << "node [shape=point color=burlywood style=filled label=\"\" width=0.05]" << std::endl; out << "edge [style=dashed color=burlywood]" << std::endl; } } }; template <class Graph> class node_writer { public: node_writer(Graph const& t) : T(t) {} template <class V> void operator()(std::ostream& out, const V& v) const { if(out_degree(v, T) == 1) out << "[shape=square color=forestgreen]"; if(out_degree(v, T) > 2) out << "[color=brown1]"; } private: Graph const& T; }; template <class Graph> node_writer<Graph> make_node_writer(Graph t) { return node_writer<Graph>(t); } template<class Graph, class Tree> class edge_writer { public: edge_writer(Graph const& g, Tree const& t) : G(g), T(t) {} template <class E> void operator()(std::ostream& out, const E& e) const { if(edge(source(e, G), target(e, G), T).second) out << "[style=solid]"; } private: Graph const& G; Tree const& T; }; template<class Graph, class Tree> edge_writer<Graph, Tree> make_edge_writer(Graph g, Tree t) { return edge_writer<Graph, Tree>(g, t); } template<class Graph, class Tree> void show(std::string file, Graph const & g, Tree const & t) { std::ofstream f(file); write_graphviz(f, g, make_node_writer(t), make_edge_writer(g, t), graph_writer(num_vertices(g) < 30)); f.close(); } template<class Graph> void show(std::string file, Graph const & g) { std::ofstream f(file); write_graphviz(f, g, boost::default_writer(), boost::default_writer(), graph_writer(false)); f.close(); } <|endoftext|>
<commit_before>#include "DerivativeBaseMaterial.h" template<> InputParameters validParams<DerivativeBaseMaterial>() { InputParameters params = validParams<Material>(); params.addClassDescription("KKS model helper material to provide the free energy and its first and second derivatives"); params.addParam<std::string>("f_name", "F", "Base name of the free energy function (used to name the material properties)"); params.addRequiredCoupledVar("args", "Arguments of F() - use vector coupling"); params.addParam<bool>("third_derivatives", true, "Calculate third derivatoves of the free energy"); return params; } DerivativeBaseMaterial::DerivativeBaseMaterial(const std::string & name, InputParameters parameters) : DerivativeMaterialInterface<Material>(name, parameters), _F_name(getParam<std::string>("f_name")), _nargs(coupledComponents("args")), _third_derivatives(getParam<bool>("third_derivatives")), _prop_F(&declareProperty<Real>(_F_name)) { // loop counters unsigned int i, j, k; // coupled variables _args.resize(_nargs); // reserve space for material properties _prop_dF.resize(_nargs); _prop_d2F.resize(_nargs); _prop_d3F.resize(_nargs); for (i = 0; i < _nargs; ++i) { _prop_d2F[i].resize(_nargs); // TODO: maybe we should reserve and initialize to NULL... if (_third_derivatives) { _prop_d3F[i].resize(_nargs); for (unsigned int j = 0; j < _nargs; ++j) _prop_d3F[i][j].resize(_nargs); } } // fetch names of variables in args _arg_names.resize(_nargs); for (i = 0; i < _nargs; ++i) _arg_names[i] = getVar("args", i)->name(); // initialize derivatives for (i = 0; i < _nargs; ++i) { // get the coupled variable to use as function arguments _args[i] = &coupledValue("args", i); // first derivatives _prop_dF[i] = &declareProperty<Real>(propertyNameFirst(_F_name, _arg_names[i])); // second derivatives for (j = i; j < _nargs; ++j) { _prop_d2F[i][j] = _prop_d2F[j][i] = &declareProperty<Real>( propertyNameSecond(_F_name, _arg_names[i], _arg_names[j]) ); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { // filling all permutations does not cost us much and simplifies access // (no need to check i<=j<=k) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = &declareProperty<Real>( propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]) ); } } } } } void DerivativeBaseMaterial::initialSetup() { if (_nargs != expectedNumArgs()) { mooseError("Wrong number of arguments supplied for DerivativeBaseMaterial " + _F_name); } // set the _prop_* pointers of all material poroperties that are not beeing used back to NULL unsigned int i, j, k; bool needs_third_derivatives = false; if (!_fe_problem.isMatPropRequested(_F_name)) _prop_F = NULL; for (i = 0; i < _nargs; ++i) { if (!_fe_problem.isMatPropRequested(propertyNameFirst(_F_name, _arg_names[i]))) _prop_dF[i] = NULL; // second derivatives for (j = i; j < _nargs; ++j) { if (!_fe_problem.isMatPropRequested(propertyNameSecond(_F_name, _arg_names[i], _arg_names[j]))) _prop_d2F[i][j] = _prop_d2F[j][i] = NULL; // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { if (!_fe_problem.isMatPropRequested(propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]))) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = NULL; else needs_third_derivatives = true; } if (!needs_third_derivatives) mooseWarning("This simulation does not actually need the third derivatives of DerivativeBaseMaterial " + _name); } } } } // implementing this in the derived class is optional (not really, but we'l have to check what is needed for the residuals!) Real DerivativeBaseMaterial::computeD3F(unsigned int /*arg1*/, unsigned int /*arg2*/, unsigned int /*arg3*/) { return 0.0; } void DerivativeBaseMaterial::computeProperties() { unsigned int i, j, k; for (_qp = 0; _qp < _qrule->n_points(); _qp++) { // set function value if (_prop_F) (*_prop_F)[_qp] = computeF(); for (i = 0; i < _nargs; ++i) { // set first derivatives if (_prop_dF[i]) (*_prop_dF[i])[_qp] = computeDF(i); // second derivatives for (j = i; j < _nargs; ++j) { if (_prop_d2F[i][j]) (*_prop_d2F[i][j])[_qp] = computeD2F(i, j); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) if (_prop_d3F[i][j][k]) (*_prop_d3F[i][j][k])[_qp] = computeD3F(i, j, k); } } } } } <commit_msg>Use declarePropertyDerivative in DerivativeBaseMaterial (#4300)<commit_after>#include "DerivativeBaseMaterial.h" template<> InputParameters validParams<DerivativeBaseMaterial>() { InputParameters params = validParams<Material>(); params.addClassDescription("KKS model helper material to provide the free energy and its first and second derivatives"); params.addParam<std::string>("f_name", "F", "Base name of the free energy function (used to name the material properties)"); params.addRequiredCoupledVar("args", "Arguments of F() - use vector coupling"); params.addParam<bool>("third_derivatives", true, "Calculate third derivatoves of the free energy"); return params; } DerivativeBaseMaterial::DerivativeBaseMaterial(const std::string & name, InputParameters parameters) : DerivativeMaterialInterface<Material>(name, parameters), _F_name(getParam<std::string>("f_name")), _nargs(coupledComponents("args")), _third_derivatives(getParam<bool>("third_derivatives")), _prop_F(&declareProperty<Real>(_F_name)) { // loop counters unsigned int i, j, k; // coupled variables _args.resize(_nargs); // reserve space for material properties _prop_dF.resize(_nargs); _prop_d2F.resize(_nargs); _prop_d3F.resize(_nargs); for (i = 0; i < _nargs; ++i) { _prop_d2F[i].resize(_nargs); // TODO: maybe we should reserve and initialize to NULL... if (_third_derivatives) { _prop_d3F[i].resize(_nargs); for (unsigned int j = 0; j < _nargs; ++j) _prop_d3F[i][j].resize(_nargs); } } // fetch names of variables in args _arg_names.resize(_nargs); for (i = 0; i < _nargs; ++i) _arg_names[i] = getVar("args", i)->name(); // initialize derivatives for (i = 0; i < _nargs; ++i) { // get the coupled variable to use as function arguments _args[i] = &coupledValue("args", i); // first derivatives _prop_dF[i] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i]); // second derivatives for (j = i; j < _nargs; ++j) { _prop_d2F[i][j] = _prop_d2F[j][i] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i], _arg_names[j]); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { // filling all permutations does not cost us much and simplifies access // (no need to check i<=j<=k) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = &declarePropertyDerivative<Real>(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]); } } } } } void DerivativeBaseMaterial::initialSetup() { if (_nargs != expectedNumArgs()) { mooseError("Wrong number of arguments supplied for DerivativeBaseMaterial " + _F_name); } // set the _prop_* pointers of all material poroperties that are not beeing used back to NULL unsigned int i, j, k; bool needs_third_derivatives = false; if (!_fe_problem.isMatPropRequested(_F_name)) _prop_F = NULL; for (i = 0; i < _nargs; ++i) { if (!_fe_problem.isMatPropRequested(propertyNameFirst(_F_name, _arg_names[i]))) _prop_dF[i] = NULL; // second derivatives for (j = i; j < _nargs; ++j) { if (!_fe_problem.isMatPropRequested(propertyNameSecond(_F_name, _arg_names[i], _arg_names[j]))) _prop_d2F[i][j] = _prop_d2F[j][i] = NULL; // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) { if (!_fe_problem.isMatPropRequested(propertyNameThird(_F_name, _arg_names[i], _arg_names[j], _arg_names[k]))) _prop_d3F[i][j][k] = _prop_d3F[k][i][j] = _prop_d3F[j][k][i] = _prop_d3F[k][j][i] = _prop_d3F[j][i][k] = _prop_d3F[i][k][j] = NULL; else needs_third_derivatives = true; } if (!needs_third_derivatives) mooseWarning("This simulation does not actually need the third derivatives of DerivativeBaseMaterial " + _name); } } } } // implementing this in the derived class is optional (not really, but we'l have to check what is needed for the residuals!) Real DerivativeBaseMaterial::computeD3F(unsigned int /*arg1*/, unsigned int /*arg2*/, unsigned int /*arg3*/) { return 0.0; } void DerivativeBaseMaterial::computeProperties() { unsigned int i, j, k; for (_qp = 0; _qp < _qrule->n_points(); _qp++) { // set function value if (_prop_F) (*_prop_F)[_qp] = computeF(); for (i = 0; i < _nargs; ++i) { // set first derivatives if (_prop_dF[i]) (*_prop_dF[i])[_qp] = computeDF(i); // second derivatives for (j = i; j < _nargs; ++j) { if (_prop_d2F[i][j]) (*_prop_d2F[i][j])[_qp] = computeD2F(i, j); // third derivatives if (_third_derivatives) { for (k = j; k < _nargs; ++k) if (_prop_d3F[i][j][k]) (*_prop_d3F[i][j][k])[_qp] = computeD3F(i, j, k); } } } } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_scenario.h" #include <fstream> #include <limits> #include <utility> #include "cyber/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/ego_info.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/toolkits/optimizers/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/toolkits/optimizers/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/path_decider/path_decider.h" #include "modules/planning/toolkits/optimizers/poly_st_speed/poly_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/speed_decider/speed_decider.h" namespace apollo { namespace planning { using common::ErrorCode; using common::SLPoint; using common::SpeedPoint; using common::TrajectoryPoint; using common::math::Vec2d; using common::time::Clock; namespace { constexpr double kPathOptimizationFallbackCost = 2e4; constexpr double kSpeedOptimizationFallbackCost = 2e4; constexpr double kStraightForwardLineCost = 10.0; } // namespace void SidePassScenario::Init() { if (init_) { return; } Scenario::Init(); init_ = true; } apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> SidePassScenario::s_stage_factory_; void SidePassScenario::RegisterStages() { s_stage_factory_.Clear(); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassApproachObstacle(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_DETECT_SAFETY, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassDetectSafety(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_GENERATE_PATH, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassGeneratePath(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassStopOnWaitPoint(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_PASS_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassPassObstacle(config); }); } std::unique_ptr<Stage> SidePassScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); ptr->SetContext(&side_pass_context_); return ptr; } bool SidePassScenario::IsTransferable(const Scenario& current_scenario, const common::TrajectoryPoint& ego_point, const Frame& frame) const { if (frame.reference_line_info().size() > 1) { return false; } if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) { return (current_scenario.GetStatus() != Scenario::ScenarioStatus::STATUS_DONE); } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) { return false; } else { return IsSidePassScenario(ego_point, frame); } } Stage::StageStatus SidePassApproachObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } if (frame->vehicle_state().linear_velocity() < 1.0e-5) { next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH; return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassGeneratePath::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT; return Stage::FINISHED; } else { return Stage::ERROR; } } Stage::StageStatus SidePassStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool all_far_away = false; const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual()) { continue; } // TODO(All): check all ST boundaries are far away. } if (!all_far_away) { // wait here, do nothing this cycle. return Stage::RUNNING; } double move_forward_distance = 5.0; for (const auto& path_point : GetContext()->path_data_.discretized_path().path_points()) { // TODO(All): // (1) check if the ego car on path_point will partially go into the // neighbor // lane. // (2) update move_forward_distance CHECK_GE(path_point.s(), 0.0); CHECK_GE(move_forward_distance, 0.0); } // TODO(All): // (1) call proceed with cautious // (2) combine path and speed. next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; } Stage::StageStatus SidePassDetectSafety::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { return Stage::ERROR; } bool is_safe = true; const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual()) { is_safe = false; break; } } if (is_safe) { next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE; return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassPassObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); const auto& frenet_frame_path = frame->reference_line_info().front().path_data().frenet_frame_path(); const auto& frenet_frame_point = frenet_frame_path.PointAt(frenet_frame_path.NumOfPoints() - 1); int adc_start_s = adc_sl_boundary.start_s(); int path_end_s = frenet_frame_point.s(); if ((path_end_s - adc_start_s) > 20.0) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } return Stage::RUNNING; } bool SidePassScenario::IsSidePassScenario( const common::TrajectoryPoint& planning_start_point, const Frame& frame) const { const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame.reference_line_info().front().path_decision(); // TODO(lianglia-apollo) return HasBlockingObstacle(adc_sl_boundary, path_decision); } bool SidePassScenario::IsFarFromIntersection(const Frame& frame) { if (frame.reference_line_info().size() > 1) { return false; } const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const auto& first_encounters = frame.reference_line_info().front().FirstEncounteredOverlaps(); const double kClearDistance = 15.0; // in meters for (const auto& encounter : first_encounters) { if (encounter.first != ReferenceLineInfo::SIGNAL || encounter.first != ReferenceLineInfo::STOP_SIGN) { continue; } if (encounter.second.start_s - adc_sl_boundary.end_s() < kClearDistance) { return false; } } return true; } bool SidePassScenario::HasBlockingObstacle( const SLBoundary& adc_sl_boundary, const PathDecision& path_decision) const { // a blocking obstacle is an obstacle blocks the road when it is not blocked // (by other obstacles or traffic rules) for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual() || !path_obstacle->obstacle()->IsStatic()) { continue; } CHECK(path_obstacle->obstacle()->IsStatic()); if (path_obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the adc. continue; } constexpr double kAdcDistanceThreshold = 15.0; // unit: m if (path_obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + kAdcDistanceThreshold) { // vehicles are far away continue; } if (path_obstacle->PerceptionSLBoundary().start_l() > 1.0 || path_obstacle->PerceptionSLBoundary().end_l() < -1.0) { continue; } bool is_blocked_by_others = false; for (const auto* other_obstacle : path_decision.path_obstacles().Items()) { if (other_obstacle->Id() == path_obstacle->Id()) { continue; } if (other_obstacle->PerceptionSLBoundary().start_l() > path_obstacle->PerceptionSLBoundary().end_l() || other_obstacle->PerceptionSLBoundary().end_l() < path_obstacle->PerceptionSLBoundary().start_l()) { // not blocking the backside vehicle continue; } double delta_s = other_obstacle->PerceptionSLBoundary().start_s() - path_obstacle->PerceptionSLBoundary().end_s(); if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) { continue; } else { // TODO(All): fixed the segmentation bug for large vehicles, otherwise // the follow line will be problematic. // is_blocked_by_others = true; break; } } if (!is_blocked_by_others) { return true; } } return false; } } // namespace planning } // namespace apollo <commit_msg>planning: updated side pass scenario exit condition.<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_scenario.h" #include <fstream> #include <limits> #include <utility> #include "cyber/common/log.h" #include "modules/common/math/math_utils.h" #include "modules/common/time/time.h" #include "modules/common/util/file.h" #include "modules/common/util/string_tokenizer.h" #include "modules/common/util/string_util.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/map/hdmap/hdmap.h" #include "modules/map/hdmap/hdmap_common.h" #include "modules/planning/common/ego_info.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/constraint_checker/constraint_checker.h" #include "modules/planning/toolkits/optimizers/dp_poly_path/dp_poly_path_optimizer.h" #include "modules/planning/toolkits/optimizers/dp_st_speed/dp_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/path_decider/path_decider.h" #include "modules/planning/toolkits/optimizers/poly_st_speed/poly_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_path/qp_spline_path_optimizer.h" #include "modules/planning/toolkits/optimizers/qp_spline_st_speed/qp_spline_st_speed_optimizer.h" #include "modules/planning/toolkits/optimizers/speed_decider/speed_decider.h" namespace apollo { namespace planning { using common::ErrorCode; using common::SLPoint; using common::SpeedPoint; using common::TrajectoryPoint; using common::math::Vec2d; using common::time::Clock; namespace { constexpr double kPathOptimizationFallbackCost = 2e4; constexpr double kSpeedOptimizationFallbackCost = 2e4; constexpr double kStraightForwardLineCost = 10.0; } // namespace void SidePassScenario::Init() { if (init_) { return; } Scenario::Init(); init_ = true; } apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> SidePassScenario::s_stage_factory_; void SidePassScenario::RegisterStages() { s_stage_factory_.Clear(); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_APPROACH_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassApproachObstacle(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_DETECT_SAFETY, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassDetectSafety(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_GENERATE_PATH, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassGeneratePath(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassStopOnWaitPoint(config); }); s_stage_factory_.Register( ScenarioConfig::SIDE_PASS_PASS_OBSTACLE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new SidePassPassObstacle(config); }); } std::unique_ptr<Stage> SidePassScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); ptr->SetContext(&side_pass_context_); return ptr; } bool SidePassScenario::IsTransferable(const Scenario& current_scenario, const common::TrajectoryPoint& ego_point, const Frame& frame) const { if (frame.reference_line_info().size() > 1) { return false; } if (current_scenario.scenario_type() == ScenarioConfig::SIDE_PASS) { return (current_scenario.GetStatus() != Scenario::ScenarioStatus::STATUS_DONE); } else if (current_scenario.scenario_type() != ScenarioConfig::LANE_FOLLOW) { return false; } else { return IsSidePassScenario(ego_point, frame); } } Stage::StageStatus SidePassApproachObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } if (frame->vehicle_state().linear_velocity() < 1.0e-5) { next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH; return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassGeneratePath::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT; return Stage::FINISHED; } else { return Stage::ERROR; } } Stage::StageStatus SidePassStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool all_far_away = false; const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual()) { continue; } // TODO(All): check all ST boundaries are far away. } if (!all_far_away) { // wait here, do nothing this cycle. return Stage::RUNNING; } double move_forward_distance = 5.0; for (const auto& path_point : GetContext()->path_data_.discretized_path().path_points()) { // TODO(All): // (1) check if the ego car on path_point will partially go into the // neighbor // lane. // (2) update move_forward_distance CHECK_GE(path_point.s(), 0.0); CHECK_GE(move_forward_distance, 0.0); } // TODO(All): // (1) call proceed with cautious // (2) combine path and speed. next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; } Stage::StageStatus SidePassDetectSafety::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (PlanningOnReferenceLine(planning_start_point, frame)) { return Stage::ERROR; } bool is_safe = true; const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual()) { is_safe = false; break; } } if (is_safe) { next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE; return Stage::FINISHED; } return Stage::RUNNING; } Stage::StageStatus SidePassPassObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { bool plan_ok = PlanningOnReferenceLine(planning_start_point, frame); if (!plan_ok) { return Stage::ERROR; } const auto& reference_line_info = frame->reference_line_info().front(); const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary(); const auto& end_point = reference_line_info.path_data().discretized_path().EndPoint(); Vec2d last_xy_point(end_point.x(), end_point.y()); // get s of last point on path SLPoint sl_point; if (!reference_line_info.reference_line().XYToSL(last_xy_point, &sl_point)) { AERROR << "Fail to transfer cartesian point to frenet point."; return Stage::ERROR; } if (adc_sl_boundary.end_s() > sl_point.s() - 1.0) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } return Stage::RUNNING; } bool SidePassScenario::IsSidePassScenario( const common::TrajectoryPoint& planning_start_point, const Frame& frame) const { const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame.reference_line_info().front().path_decision(); // TODO(lianglia-apollo) return HasBlockingObstacle(adc_sl_boundary, path_decision); } bool SidePassScenario::IsFarFromIntersection(const Frame& frame) { if (frame.reference_line_info().size() > 1) { return false; } const SLBoundary& adc_sl_boundary = frame.reference_line_info().front().AdcSlBoundary(); const auto& first_encounters = frame.reference_line_info().front().FirstEncounteredOverlaps(); const double kClearDistance = 15.0; // in meters for (const auto& encounter : first_encounters) { if (encounter.first != ReferenceLineInfo::SIGNAL || encounter.first != ReferenceLineInfo::STOP_SIGN) { continue; } if (encounter.second.start_s - adc_sl_boundary.end_s() < kClearDistance) { return false; } } return true; } bool SidePassScenario::HasBlockingObstacle( const SLBoundary& adc_sl_boundary, const PathDecision& path_decision) const { // a blocking obstacle is an obstacle blocks the road when it is not blocked // (by other obstacles or traffic rules) for (const auto* path_obstacle : path_decision.path_obstacles().Items()) { if (path_obstacle->obstacle()->IsVirtual() || !path_obstacle->obstacle()->IsStatic()) { continue; } CHECK(path_obstacle->obstacle()->IsStatic()); if (path_obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the adc. continue; } constexpr double kAdcDistanceThreshold = 15.0; // unit: m if (path_obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + kAdcDistanceThreshold) { // vehicles are far away continue; } if (path_obstacle->PerceptionSLBoundary().start_l() > 1.0 || path_obstacle->PerceptionSLBoundary().end_l() < -1.0) { continue; } bool is_blocked_by_others = false; for (const auto* other_obstacle : path_decision.path_obstacles().Items()) { if (other_obstacle->Id() == path_obstacle->Id()) { continue; } if (other_obstacle->PerceptionSLBoundary().start_l() > path_obstacle->PerceptionSLBoundary().end_l() || other_obstacle->PerceptionSLBoundary().end_l() < path_obstacle->PerceptionSLBoundary().start_l()) { // not blocking the backside vehicle continue; } double delta_s = other_obstacle->PerceptionSLBoundary().start_s() - path_obstacle->PerceptionSLBoundary().end_s(); if (delta_s < 0.0 || delta_s > kAdcDistanceThreshold) { continue; } else { // TODO(All): fixed the segmentation bug for large vehicles, otherwise // the follow line will be problematic. // is_blocked_by_others = true; break; } } if (!is_blocked_by_others) { return true; } } return false; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include "MaterialTensorAux.h" #include "SymmTensor.h" template<> InputParameters validParams<MaterialTensorAux>() { MooseEnum quantities("VonMises=1, PlasticStrainMag, Hydrostatic, Hoop, FirstInvariant, SecondInvariant, ThirdInvariant, TriAxiality"); InputParameters params = validParams<AuxKernel>(); params.addRequiredParam<std::string>("tensor", "The material tensor name."); params.addParam<int>("index", -1, "The index into the tensor, from 0 to 5 (xx, yy, zz, xy, yz, zx)."); params.addParam<MooseEnum>("quantity", quantities, "A scalar quantity to compute: " + quantities.getRawNames()); params.addParam<RealVectorValue>("point1", RealVectorValue(3, 0, 0), "Point one for defining an axis"); params.addParam<RealVectorValue>("point2", RealVectorValue(3, 1, 0), "Point two for defining an axis"); return params; } MaterialTensorAux::MaterialTensorAux( const std::string & name, InputParameters parameters ) : AuxKernel( name, parameters ), _tensor( getMaterialProperty<SymmTensor>( getParam<std::string>("tensor") ) ), _index( getParam<int>("index") ), _quantity_moose_enum( getParam<MooseEnum>("quantity") ), _p1( getParam<RealVectorValue>("point1") ), _p2( getParam<RealVectorValue>("point2") ) { if (_quantity_moose_enum.isValid()) { if ( _index > 0 ) mooseError("Cannot define an index and a quantity in " + _name); else _quantity = MTA_ENUM(int(_quantity_moose_enum)); } else { if ( _index < 0 ) mooseError("Neither an index nor a quantity listed for " + _name); else _quantity = MTA_COMPONENT; // default } if (_index > -1 && _index > 5) { mooseError("MaterialTensorAux requires the index to be >= 0 and <= 5 OR < 0 (off)."); } } Real MaterialTensorAux::computeValue() { Real value(0); const SymmTensor & tensor( _tensor[_qp] ); if (_quantity == MTA_COMPONENT) { value = tensor.component(_index); } else if ( _quantity == MTA_VONMISES ) { value = std::sqrt(0.5*( std::pow(tensor.xx() - tensor.yy(), 2) + std::pow(tensor.yy() - tensor.zz(), 2) + std::pow(tensor.zz() - tensor.xx(), 2) + 6 * ( std::pow(tensor.xy(), 2) + std::pow(tensor.yz(), 2) + std::pow(tensor.zx(), 2)))); } else if ( _quantity == MTA_PLASTICSTRAINMAG ) { value = std::sqrt(2.0/3.0 * tensor.doubleContraction(tensor)); } else if ( _quantity == MTA_HYDROSTATIC ) { value = tensor.trace()/3.0; } else if ( _quantity == MTA_HOOP ) { if (LIBMESH_DIM == 2) { value = tensor.zz(); } else { // This is the location of the stress. A vector from the cylindrical axis to this point will define the x' axis. Point p0( _q_point[_qp] ); // The vector _p1 + t*(_p2-_p1) defines the cylindrical axis. The point along this // axis closest to p0 is found by the following for t: const Point p2p1( _p2 - _p1 ); const Point p2p0( _p2 - p0 ); const Point p1p0( _p1 - p0 ); const Real t( -(p1p0*p2p1)/p2p1.size_sq() ); // The nearest point on the cylindrical axis to p0 is p. const Point p( _p1 + t * p2p1 ); Point xp( p0 - p ); xp /= xp.size(); Point yp( p2p1/p2p1.size() ); Point zp( xp.cross( yp )); // // The following works but does more than we need // // // Rotation matrix R // ColumnMajorMatrix R(3,3); // // Fill with direction cosines // R(0,0) = xp(0); // R(1,0) = xp(1); // R(2,0) = xp(2); // R(0,1) = yp(0); // R(1,1) = yp(1); // R(2,1) = yp(2); // R(0,2) = zp(0); // R(1,2) = zp(1); // R(2,2) = zp(2); // // Rotate // ColumnMajorMatrix tensor( _tensor[_qp].columnMajorMatrix() ); // ColumnMajorMatrix tensorp( R.transpose() * ( tensor * R )); // // Hoop stress is the zz stress // value = tensorp(2,2); // // Instead, tensorp(2,2) = R^T(2,:)*tensor*R(:,2) // const Real zp0( zp(0) ); const Real zp1( zp(1) ); const Real zp2( zp(2) ); value = (zp0*tensor(0,0)+zp1*tensor(1,0)+zp2*tensor(2,0))*zp0 + (zp0*tensor(0,1)+zp1*tensor(1,1)+zp2*tensor(2,1))*zp1 + (zp0*tensor(0,2)+zp1*tensor(1,2)+zp2*tensor(2,2))*zp2; } } else if ( _quantity == MTA_FIRSTINVARIANT ) { value = tensor.trace(); } else if ( _quantity == MTA_SECONDINVARIANT ) { value = tensor.xx()*tensor.yy() + tensor.yy()*tensor.zz() + tensor.zz()*tensor.xx() - tensor.xy()*tensor.xy() - tensor.yz()*tensor.yz() - tensor.zx()*tensor.zx(); } else if ( _quantity == MTA_THIRDINVARIANT ) { value = tensor.xx()*tensor.yy()*tensor.zz() - tensor.xx()*tensor.yz()*tensor.yz() + tensor.xy()*tensor.zx()*tensor.yz() - tensor.xy()*tensor.xy()*tensor.zz() + tensor.zx()*tensor.xy()*tensor.yz() - tensor.zx()*tensor.zx()*tensor.yy(); } else if ( _quantity == MTA_TRIAXIALITY ) { Real hydrostatic = tensor.trace()/3.0; Real von_mises = std::sqrt(0.5*( std::pow(tensor.xx() - tensor.yy(), 2) + std::pow(tensor.yy() - tensor.zz(), 2) + std::pow(tensor.zz() - tensor.xx(), 2) + 6 * ( std::pow(tensor.xy(), 2) + std::pow(tensor.yz(), 2) + std::pow(tensor.zx(), 2)))); value = std::abs(hydrostatic / von_mises); } else { mooseError("Internal logic error from " + name()); } return value; } <commit_msg>pf cp<commit_after>#include "MaterialTensorAux.h" #include "SymmTensor.h" template<> InputParameters validParams<MaterialTensorAux>() { MooseEnum quantities("VonMises=1, PlasticStrainMag, Hydrostatic, Hoop, FirstInvariant, SecondInvariant, ThirdInvariant, TriAxiality"); InputParameters params = validParams<AuxKernel>(); params.addRequiredParam<std::string>("tensor", "The material tensor name."); params.addParam<int>("index", -1, "The index into the tensor, from 0 to 5 (xx, yy, zz, xy, yz, zx)."); params.addParam<MooseEnum>("quantity", quantities, "A scalar quantity to compute: " + quantities.getRawNames()); params.addParam<RealVectorValue>("point1", RealVectorValue(3, 0, 0), "Point one for defining an axis"); params.addParam<RealVectorValue>("point2", RealVectorValue(3, 1, 0), "Point two for defining an axis"); return params; } MaterialTensorAux::MaterialTensorAux( const std::string & name, InputParameters parameters ) : AuxKernel( name, parameters ), _tensor( getMaterialProperty<SymmTensor>( getParam<std::string>("tensor") ) ), _index( getParam<int>("index") ), _quantity_moose_enum( getParam<MooseEnum>("quantity") ), _p1( getParam<RealVectorValue>("point1") ), _p2( getParam<RealVectorValue>("point2") ) { if (_quantity_moose_enum.isValid()) { if ( _index > 0 ) mooseError("Cannot define an index and a quantity in " + _name); else _quantity = MTA_ENUM(int(_quantity_moose_enum)); } else { if ( _index < 0 ) mooseError("Neither an index nor a quantity listed for " + _name); else _quantity = MTA_COMPONENT; // default } if (_index > -1 && _index > 5) { mooseError("MaterialTensorAux requires the index to be >= 0 and <= 5 OR < 0 (off)."); } } Real MaterialTensorAux::computeValue() { Real value(0); const SymmTensor & tensor( _tensor[_qp] ); if (_quantity == MTA_COMPONENT) { value = tensor.component(_index); } else if ( _quantity == MTA_VONMISES ) { value = std::sqrt(0.5*( std::pow(tensor.xx() - tensor.yy(), 2) + std::pow(tensor.yy() - tensor.zz(), 2) + std::pow(tensor.zz() - tensor.xx(), 2) + 6 * ( std::pow(tensor.xy(), 2) + std::pow(tensor.yz(), 2) + std::pow(tensor.zx(), 2)))); } else if ( _quantity == MTA_PLASTICSTRAINMAG ) { value = std::sqrt(2.0/3.0 * tensor.doubleContraction(tensor)); } else if ( _quantity == MTA_HYDROSTATIC ) { value = tensor.trace()/3.0; } else if ( _quantity == MTA_HOOP ) { if (LIBMESH_DIM == 2) { value = tensor.zz(); } else { // This is the location of the stress. A vector from the cylindrical axis to this point will define the x' axis. Point p0( _q_point[_qp] ); // The vector _p1 + t*(_p2-_p1) defines the cylindrical axis. The point along this // axis closest to p0 is found by the following for t: const Point p2p1( _p2 - _p1 ); const Point p2p0( _p2 - p0 ); const Point p1p0( _p1 - p0 ); const Real t( -(p1p0*p2p1)/p2p1.size_sq() ); // The nearest point on the cylindrical axis to p0 is p. const Point p( _p1 + t * p2p1 ); Point xp( p0 - p ); xp /= xp.size(); Point yp( p2p1/p2p1.size() ); Point zp( xp.cross( yp )); // // The following works but does more than we need // // // Rotation matrix R // ColumnMajorMatrix R(3,3); // // Fill with direction cosines // R(0,0) = xp(0); // R(1,0) = xp(1); // R(2,0) = xp(2); // R(0,1) = yp(0); // R(1,1) = yp(1); // R(2,1) = yp(2); // R(0,2) = zp(0); // R(1,2) = zp(1); // R(2,2) = zp(2); // // Rotate // ColumnMajorMatrix tensor( _tensor[_qp].columnMajorMatrix() ); // ColumnMajorMatrix tensorp( R.transpose() * ( tensor * R )); // // Hoop stress is the zz stress // value = tensorp(2,2); // // Instead, tensorp(2,2) = R^T(2,:)*tensor*R(:,2) // const Real zp0( zp(0) ); const Real zp1( zp(1) ); const Real zp2( zp(2) ); value = (zp0*tensor(0,0)+zp1*tensor(1,0)+zp2*tensor(2,0))*zp0 + (zp0*tensor(0,1)+zp1*tensor(1,1)+zp2*tensor(2,1))*zp1 + (zp0*tensor(0,2)+zp1*tensor(1,2)+zp2*tensor(2,2))*zp2; } } else if ( _quantity == MTA_FIRSTINVARIANT ) { value = tensor.trace(); } else if ( _quantity == MTA_SECONDINVARIANT ) { value = tensor.xx()*tensor.yy() + tensor.yy()*tensor.zz() + tensor.zz()*tensor.xx() - tensor.xy()*tensor.xy() - tensor.yz()*tensor.yz() - tensor.zx()*tensor.zx(); } else if ( _quantity == MTA_THIRDINVARIANT ) { value = tensor.xx()*tensor.yy()*tensor.zz() - tensor.xx()*tensor.yz()*tensor.yz() + tensor.xy()*tensor.zx()*tensor.yz() - tensor.xy()*tensor.xy()*tensor.zz() + tensor.zx()*tensor.xy()*tensor.yz() - tensor.zx()*tensor.zx()*tensor.yy(); } else if ( _quantity == MTA_TRIAXIALITY ) { Real hydrostatic = tensor.trace()/3.0; Real von_mises = std::sqrt(0.5*( std::pow(tensor.xx() - tensor.yy(), 2) + std::pow(tensor.yy() - tensor.zz(), 2) + std::pow(tensor.zz() - tensor.xx(), 2) + 6 * ( std::pow(tensor.xy(), 2) + std::pow(tensor.yz(), 2) + std::pow(tensor.zx(), 2)))); value = std::abs(hydrostatic / von_mises); } else { mooseError("Internal logic error from " + name()); } return value; } <|endoftext|>
<commit_before>/*! @file * * @brief Do I need a Parker * * This module contains the routines that drive the dinapd daemon. * * @author APope * @date 20-02-2016 */ /*! ** @addtogroup DINAP_module DINAP module documentation ** @{ */ /* MODULE DINAP */ #include <syslog.h> #include <stdlib.h> #include <unistd.h> #include <glib.h> #include <libnotify/notify.h> #include "DINAP.h" DINAP::DINAP(TSTATE location=STATE_NSW, int parker_temp=18, int shorts_temp=25) { DINAP::location = location; DINAP::parker_temp = parker_temp; DINAP::shorts_temp = shorts_temp; } void DINAP::CheckWeatherInfo(void) { bool scrapeSucceeded; //TODO: expand functionality syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_NOTICE), "Checking the Weather... "); //TODO: Scrape weather information using location scrapeSucceeded = DINAP::scrapeWeatherData(); } bool DINAP::scrapeWeatherData(void) { DINAP::notifyUser("Weather is 17 degs", "Brrr it's chilly! Time for a coat."); //TEST MESSAGE return true; } void DINAP::notifyUser(const char * summary, const char * message) { //Initialise the lib-notify handle notify_init("Do I need A Parker?"); //Create the notification NotifyNotification * weatherUpdate; weatherUpdate = notify_notification_new(summary, message, NULL); //Set timeout - 3 seconds notify_notification_set_timeout(weatherUpdate, 3000); //Set the urgency level notify_notification_set_urgency(weatherUpdate, NOTIFY_URGENCY_CRITICAL); //Show the notification if (!notify_notification_show(weatherUpdate, NULL)) { syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), "Failed to send notification."); } //Unitialise lib-notify notify_uninit(); } void DINAP::compareUserTemp(int scrapedTemp) { } /* END DINAP */ /*! ** @} */ <commit_msg>Dinap.cpp: - Expanded basic functionality in calling to the bomparser module to get 'real-time' temperature information<commit_after>/*! @file * * @brief Do I need a Parker * * This module contains the routines that drive the dinapd daemon. * * @author APope * @date 20-02-2016 */ /*! ** @addtogroup DINAP_module DINAP module documentation ** @{ */ /* MODULE DINAP */ #include <syslog.h> #include <stdlib.h> #include <unistd.h> #include <glib.h> #include <libnotify/notify.h> #include "DINAP.h" #include "bomparser.h" DINAP::DINAP(TSTATE location=STATE_NSW, int parker_temp=18, int shorts_temp=25) { DINAP::location = location; DINAP::parker_temp = parker_temp; DINAP::shorts_temp = shorts_temp; } void DINAP::CheckWeatherInfo(void) { bool scrapeSucceeded; //TODO: expand functionality syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_NOTICE), "Checking the Weather... "); scrapeSucceeded = DINAP::scrapeWeatherData(); } bool DINAP::scrapeWeatherData(void) { bool scrapeOK = false; BomParser bomSpider = BomParser(); std::string scrapedTemp = bomSpider.GetWeatherInfo(STATE_NSW, INFO_Temp); //TEST CODE if (!scrapedTemp.empty()) { syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_INFO), scrapedTemp.c_str()); compareUserTemp(32); scrapeOK = true; } else { syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), "Unable to obtain weather information."); } return scrapeOK; } void DINAP::notifyUser(const char * summary, const char * message) { //Initialise the lib-notify handle notify_init("Do I need A Parker?"); //Create the notification NotifyNotification * weatherUpdate; weatherUpdate = notify_notification_new(summary, message, NULL); //Set timeout - 3 seconds notify_notification_set_timeout(weatherUpdate, 3000); //Set the urgency level notify_notification_set_urgency(weatherUpdate, NOTIFY_URGENCY_CRITICAL); //Show the notification if (!notify_notification_show(weatherUpdate, NULL)) { syslog(LOG_MAKEPRI(LOG_DAEMON, LOG_ERR), "Failed to send notification."); } //Unitialise lib-notify notify_uninit(); } void DINAP::compareUserTemp(int scrapedTemp) { DINAP::notifyUser("Weather is 17 degs", "Brrr it's chilly! Time for a coat."); //TEST MESSAGE } /* END DINAP */ /*! ** @} */ <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "net/test/test_server.h" #include <poll.h> #include <vector> #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" namespace { // Helper class used to detect and kill orphaned python test server processes. // Checks if the command line of a process contains |path_string| (the path // from which the test server was launched) and |port_string| (the port used by // the test server), and if the parent pid of the process is 1 (indicating that // it is an orphaned process). class OrphanedTestServerFilter : public base::ProcessFilter { public: OrphanedTestServerFilter( const std::string& path_string, const std::string& port_string) : path_string_(path_string), port_string_(port_string) {} virtual bool Includes(const base::ProcessEntry& entry) const { if (entry.parent_pid() != 1) return false; bool found_path_string = false; bool found_port_string = false; for (std::vector<std::string>::const_iterator it = entry.cmd_line_args().begin(); it != entry.cmd_line_args().end(); ++it) { if (it->find(path_string_) != std::string::npos) found_path_string = true; if (it->find(port_string_) != std::string::npos) found_port_string = true; } return found_path_string && found_port_string; } private: std::string path_string_; std::string port_string_; DISALLOW_COPY_AND_ASSIGN(OrphanedTestServerFilter); }; // Given a file descriptor, reads into |buffer| until |bytes_max| // bytes has been read or an error has been encountered. Returns true // if the read was successful. |remaining_time| is used as a timeout. bool ReadData(int fd, ssize_t bytes_max, uint8* buffer, base::TimeDelta* remaining_time) { ssize_t bytes_read = 0; base::Time previous_time = base::Time::Now(); while (bytes_read < bytes_max) { struct pollfd poll_fds[1]; poll_fds[0].fd = fd; poll_fds[0].events = POLLIN | POLLPRI; poll_fds[0].revents = 0; int rv = HANDLE_EINTR(poll(poll_fds, 1, remaining_time->InMilliseconds())); if (rv != 1) { LOG(ERROR) << "Failed to poll for the child file descriptor."; return false; } base::Time current_time = base::Time::Now(); base::TimeDelta elapsed_time_cycle = current_time - previous_time; DCHECK(elapsed_time_cycle.InMilliseconds() >= 0); *remaining_time -= elapsed_time_cycle; previous_time = current_time; ssize_t num_bytes = HANDLE_EINTR(read(fd, buffer + bytes_read, bytes_max - bytes_read)); if (num_bytes <= 0) return false; bytes_read += num_bytes; } return true; } } // namespace namespace net { bool TestServer::LaunchPython(const FilePath& testserver_path) { CommandLine python_command(FilePath(FILE_PATH_LITERAL("python"))); python_command.AppendArgPath(testserver_path); if (!AddCommandLineArguments(&python_command)) return false; int pipefd[2]; if (pipe(pipefd) != 0) { PLOG(ERROR) << "Could not create pipe."; return false; } // Save the read half. The write half is sent to the child. child_fd_ = pipefd[0]; child_fd_closer_.reset(&child_fd_); file_util::ScopedFD write_closer(&pipefd[1]); base::file_handle_mapping_vector map_write_fd; map_write_fd.push_back(std::make_pair(pipefd[1], pipefd[1])); python_command.AppendArg("--startup-pipe=" + base::IntToString(pipefd[1])); // Try to kill any orphaned testserver processes that may be running. OrphanedTestServerFilter filter(testserver_path.value(), base::IntToString(host_port_pair_.port())); if (!base::KillProcesses("python", -1, &filter)) { LOG(WARNING) << "Failed to clean up older orphaned testserver instances."; } // Launch a new testserver process. base::LaunchOptions options; options.fds_to_remap = &map_write_fd; if (!base::LaunchProcess(python_command, options, &process_handle_)) { LOG(ERROR) << "Failed to launch " << python_command.GetCommandLineString(); return false; } return true; } bool TestServer::WaitToStart() { file_util::ScopedFD child_fd_closer(child_fd_closer_.release()); base::TimeDelta remaining_time = base::TimeDelta::FromMilliseconds( TestTimeouts::action_timeout_ms()); uint32 server_data_len = 0; if (!ReadData(child_fd_, sizeof(server_data_len), reinterpret_cast<uint8*>(&server_data_len), &remaining_time)) { LOG(ERROR) << "Could not read server_data_len"; return false; } std::string server_data(server_data_len, '\0'); if (!ReadData(child_fd_, server_data_len, reinterpret_cast<uint8*>(&server_data[0]), &remaining_time)) { LOG(ERROR) << "Could not read server_data (" << server_data_len << " bytes)"; return false; } if (!ParseServerData(server_data)) { LOG(ERROR) << "Could not parse server_data: " << server_data; return false; } return true; } } // namespace net <commit_msg>test_server: include errno in failed poll()<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 "net/test/test_server.h" #include <poll.h> #include <vector> #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/test/test_timeouts.h" namespace { // Helper class used to detect and kill orphaned python test server processes. // Checks if the command line of a process contains |path_string| (the path // from which the test server was launched) and |port_string| (the port used by // the test server), and if the parent pid of the process is 1 (indicating that // it is an orphaned process). class OrphanedTestServerFilter : public base::ProcessFilter { public: OrphanedTestServerFilter( const std::string& path_string, const std::string& port_string) : path_string_(path_string), port_string_(port_string) {} virtual bool Includes(const base::ProcessEntry& entry) const { if (entry.parent_pid() != 1) return false; bool found_path_string = false; bool found_port_string = false; for (std::vector<std::string>::const_iterator it = entry.cmd_line_args().begin(); it != entry.cmd_line_args().end(); ++it) { if (it->find(path_string_) != std::string::npos) found_path_string = true; if (it->find(port_string_) != std::string::npos) found_port_string = true; } return found_path_string && found_port_string; } private: std::string path_string_; std::string port_string_; DISALLOW_COPY_AND_ASSIGN(OrphanedTestServerFilter); }; // Given a file descriptor, reads into |buffer| until |bytes_max| // bytes has been read or an error has been encountered. Returns true // if the read was successful. |remaining_time| is used as a timeout. bool ReadData(int fd, ssize_t bytes_max, uint8* buffer, base::TimeDelta* remaining_time) { ssize_t bytes_read = 0; base::Time previous_time = base::Time::Now(); while (bytes_read < bytes_max) { struct pollfd poll_fds[1]; poll_fds[0].fd = fd; poll_fds[0].events = POLLIN | POLLPRI; poll_fds[0].revents = 0; int rv = HANDLE_EINTR(poll(poll_fds, 1, remaining_time->InMilliseconds())); if (rv != 1) { PLOG(ERROR) << "poll() failed for child file descriptor"; return false; } base::Time current_time = base::Time::Now(); base::TimeDelta elapsed_time_cycle = current_time - previous_time; DCHECK(elapsed_time_cycle.InMilliseconds() >= 0); *remaining_time -= elapsed_time_cycle; previous_time = current_time; ssize_t num_bytes = HANDLE_EINTR(read(fd, buffer + bytes_read, bytes_max - bytes_read)); if (num_bytes <= 0) return false; bytes_read += num_bytes; } return true; } } // namespace namespace net { bool TestServer::LaunchPython(const FilePath& testserver_path) { CommandLine python_command(FilePath(FILE_PATH_LITERAL("python"))); python_command.AppendArgPath(testserver_path); if (!AddCommandLineArguments(&python_command)) return false; int pipefd[2]; if (pipe(pipefd) != 0) { PLOG(ERROR) << "Could not create pipe."; return false; } // Save the read half. The write half is sent to the child. child_fd_ = pipefd[0]; child_fd_closer_.reset(&child_fd_); file_util::ScopedFD write_closer(&pipefd[1]); base::file_handle_mapping_vector map_write_fd; map_write_fd.push_back(std::make_pair(pipefd[1], pipefd[1])); python_command.AppendArg("--startup-pipe=" + base::IntToString(pipefd[1])); // Try to kill any orphaned testserver processes that may be running. OrphanedTestServerFilter filter(testserver_path.value(), base::IntToString(host_port_pair_.port())); if (!base::KillProcesses("python", -1, &filter)) { LOG(WARNING) << "Failed to clean up older orphaned testserver instances."; } // Launch a new testserver process. base::LaunchOptions options; options.fds_to_remap = &map_write_fd; if (!base::LaunchProcess(python_command, options, &process_handle_)) { LOG(ERROR) << "Failed to launch " << python_command.GetCommandLineString(); return false; } return true; } bool TestServer::WaitToStart() { file_util::ScopedFD child_fd_closer(child_fd_closer_.release()); base::TimeDelta remaining_time = base::TimeDelta::FromMilliseconds( TestTimeouts::action_timeout_ms()); uint32 server_data_len = 0; if (!ReadData(child_fd_, sizeof(server_data_len), reinterpret_cast<uint8*>(&server_data_len), &remaining_time)) { LOG(ERROR) << "Could not read server_data_len"; return false; } std::string server_data(server_data_len, '\0'); if (!ReadData(child_fd_, server_data_len, reinterpret_cast<uint8*>(&server_data[0]), &remaining_time)) { LOG(ERROR) << "Could not read server_data (" << server_data_len << " bytes)"; return false; } if (!ParseServerData(server_data)) { LOG(ERROR) << "Could not parse server_data: " << server_data; return false; } return true; } } // namespace net <|endoftext|>
<commit_before>#include "VSLapp.h" #include <QLockFile> #include <QDir> #include <QApplication> #include <QSettings> #include <QDateTime> #include <QMessageBox> #include <QMainWindow> #include <QTextStream> #ifdef __unix #include <unistd.h> #include <sys/types.h> #endif void VSLapp::applicationSetup(const char *organizationName) { // set up application name QFileInfo applicationFile(QApplication::applicationFilePath()); // These allow us to simply construct a "QSettings" object without arguments qApp->setOrganizationDomain("mil.army.arl"); qApp->setApplicationName(applicationFile.baseName()); qApp->setOrganizationName(organizationName); qApp->setApplicationVersion(__DATE__ __TIME__); // Look up the last directory where the user opened files. // set it if it hasn't been set. QSettings settings; if (!settings.allKeys().contains("app/currentDirectory")) settings.setValue("app/currentDirectory", applicationFile.absoluteDir().absolutePath()); // log this launch of the program to track usage. logApplicationLaunch(applicationFile); // comes after settingsRead so we can set a preference } void VSLapp::logApplicationLaunch(QFileInfo appFile) { QSettings settings; settings.value("logUsage", QVariant(true)); qApp->applicationDirPath(); // obtain the string we will log to the file QString message = QDateTime::currentDateTime().toString("yyyyMMddhhmmss"); #ifdef __unix message.append(getuid()); #endif message.append("\\n"); QString nameOfLogFile = QString("%1%2").arg(appFile.absoluteFilePath()).arg(".log"); QString nameOfLockFile = QString("%1%2").arg(nameOfLogFile).arg(".lck"); QLockFile lockFile(nameOfLockFile); if (lockFile.tryLock(1000)) { // got the lock write the data QFile usageLogFile(nameOfLogFile); if (usageLogFile.open(QIODevice::Append)) { usageLogFile.write(message.toStdString().c_str()); usageLogFile.close(); } lockFile.unlock(); } } QString VSLapp::getApplicationDir() { QDir applicationDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (applicationDir.dirName().toLower() == "debug" || applicationDir.dirName().toLower() == "release" # ifdef CMAKE_INTDIR || applicationDir.dirName() == CMAKE_INTDIR # endif ) applicationDir.cdUp(); #elif defined(Q_OS_MAC) if (applicationDir.dirName() == "MacOS") { applicationDir.cdUp(); applicationDir.cdUp(); applicationDir.cdUp(); } #endif return applicationDir.absolutePath(); } #include <QTextEdit> class QMessageBoxResize: public QMessageBox { public: QMessageBoxResize(QWidget *parent = 0) : QMessageBox(parent) { setMouseTracking(true); setSizeGripEnabled(true); } private: virtual bool event(QEvent *e) { bool res = QMessageBox::event(e); switch (e->type()) { case QEvent::MouseMove: case QEvent::MouseButtonPress: setSizeGripEnabled(true); setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); if (QWidget *textEdit = findChild<QTextEdit *>()) { textEdit->setMaximumHeight(QWIDGETSIZE_MAX); } } return res; } }; void VSLapp::showAboutDialog(QWidget *parent) { QMessageBoxResize msgBox(parent); QString message; QTextStream stream(&message); stream << "Built " __DATE__ " " __TIME__ << endl << "By " BUILT_BY_USER " on " BUILT_ON_MACHINE << endl; msgBox.setInformativeText(message); msgBox.setDetailedText(QString("Binary:%1").arg(VSLapp::getApplicationDir())); msgBox.setWindowTitle(QString("About %1").arg(qApp->applicationName())); msgBox.setText(QString("This is <b>%1</b> from <br><b>%2</b>") .arg(qApp->applicationName()) .arg(qApp->organizationName())); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); } #define MainWindowGeometry "MainWindow/geometry" #define MainWindowDoRestore "MainWindow/restore" #define UI_VERSION 1 void VSLapp::mainWindowSetup(QMainWindow *mw) { mw->setWindowTitle(qApp->applicationName()); // set the geometry QSettings settings; if (settings.allKeys().contains(MainWindowGeometry)) { mw->setGeometry(settings.value(MainWindowGeometry).toRect()); } } void VSLapp::mainWindowSave(QMainWindow *mw) { // stash things that we will want on startup. QSettings settings; settings.setValue(MainWindowGeometry, mw->geometry()); } <commit_msg>add default clause to event handler switch<commit_after>#include "VSLapp.h" #include <QLockFile> #include <QDir> #include <QApplication> #include <QSettings> #include <QDateTime> #include <QMessageBox> #include <QMainWindow> #include <QTextStream> #ifdef __unix #include <unistd.h> #include <sys/types.h> #endif void VSLapp::applicationSetup(const char *organizationName) { // set up application name QFileInfo applicationFile(QApplication::applicationFilePath()); // These allow us to simply construct a "QSettings" object without arguments qApp->setOrganizationDomain("mil.army.arl"); qApp->setApplicationName(applicationFile.baseName()); qApp->setOrganizationName(organizationName); qApp->setApplicationVersion(__DATE__ __TIME__); // Look up the last directory where the user opened files. // set it if it hasn't been set. QSettings settings; if (!settings.allKeys().contains("app/currentDirectory")) settings.setValue("app/currentDirectory", applicationFile.absoluteDir().absolutePath()); // log this launch of the program to track usage. logApplicationLaunch(applicationFile); // comes after settingsRead so we can set a preference } void VSLapp::logApplicationLaunch(QFileInfo appFile) { QSettings settings; settings.value("logUsage", QVariant(true)); qApp->applicationDirPath(); // obtain the string we will log to the file QString message = QDateTime::currentDateTime().toString("yyyyMMddhhmmss"); #ifdef __unix message.append(getuid()); #endif message.append("\\n"); QString nameOfLogFile = QString("%1%2").arg(appFile.absoluteFilePath()).arg(".log"); QString nameOfLockFile = QString("%1%2").arg(nameOfLogFile).arg(".lck"); QLockFile lockFile(nameOfLockFile); if (lockFile.tryLock(1000)) { // got the lock write the data QFile usageLogFile(nameOfLogFile); if (usageLogFile.open(QIODevice::Append)) { usageLogFile.write(message.toStdString().c_str()); usageLogFile.close(); } lockFile.unlock(); } } QString VSLapp::getApplicationDir() { QDir applicationDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (applicationDir.dirName().toLower() == "debug" || applicationDir.dirName().toLower() == "release" # ifdef CMAKE_INTDIR || applicationDir.dirName() == CMAKE_INTDIR # endif ) applicationDir.cdUp(); #elif defined(Q_OS_MAC) if (applicationDir.dirName() == "MacOS") { applicationDir.cdUp(); applicationDir.cdUp(); applicationDir.cdUp(); } #endif return applicationDir.absolutePath(); } #include <QTextEdit> class QMessageBoxResize: public QMessageBox { public: QMessageBoxResize(QWidget *parent = 0) : QMessageBox(parent) { setMouseTracking(true); setSizeGripEnabled(true); } private: virtual bool event(QEvent *e) { bool res = QMessageBox::event(e); switch (e->type()) { case QEvent::MouseMove: case QEvent::MouseButtonPress: setSizeGripEnabled(true); setMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); if (QWidget *textEdit = findChild<QTextEdit *>()) { textEdit->setMaximumHeight(QWIDGETSIZE_MAX); } default: break; } return res; } }; void VSLapp::showAboutDialog(QWidget *parent) { QMessageBoxResize msgBox(parent); QString message; QTextStream stream(&message); stream << "Built " __DATE__ " " __TIME__ << endl << "By " BUILT_BY_USER " on " BUILT_ON_MACHINE << endl; msgBox.setInformativeText(message); msgBox.setDetailedText(QString("Binary:%1").arg(VSLapp::getApplicationDir())); msgBox.setWindowTitle(QString("About %1").arg(qApp->applicationName())); msgBox.setText(QString("This is <b>%1</b> from <br><b>%2</b>") .arg(qApp->applicationName()) .arg(qApp->organizationName())); msgBox.setDefaultButton(QMessageBox::Ok); msgBox.exec(); } #define MainWindowGeometry "MainWindow/geometry" #define MainWindowDoRestore "MainWindow/restore" #define UI_VERSION 1 void VSLapp::mainWindowSetup(QMainWindow *mw) { mw->setWindowTitle(qApp->applicationName()); // set the geometry QSettings settings; if (settings.allKeys().contains(MainWindowGeometry)) { mw->setGeometry(settings.value(MainWindowGeometry).toRect()); } } void VSLapp::mainWindowSave(QMainWindow *mw) { // stash things that we will want on startup. QSettings settings; settings.setValue(MainWindowGeometry, mw->geometry()); } <|endoftext|>
<commit_before>// Copyright 2013 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 "nacl_io/socket/udp_node.h" #include <errno.h> #include <string.h> #include <algorithm> #include "nacl_io/log.h" #include "nacl_io/pepper_interface.h" #include "nacl_io/socket/packet.h" #include "nacl_io/socket/udp_event_emitter.h" #include "nacl_io/stream/stream_fs.h" namespace { const size_t kMaxPacketSize = 65536; const size_t kDefaultFifoSize = kMaxPacketSize * 8; } namespace nacl_io { class UdpWork : public StreamFs::Work { public: explicit UdpWork(const ScopedUdpEventEmitter& emitter) : StreamFs::Work(emitter->stream()->stream()), emitter_(emitter), packet_(NULL) {} ~UdpWork() { delete packet_; } UDPSocketInterface* UDPInterface() { return filesystem()->ppapi()->GetUDPSocketInterface(); } protected: ScopedUdpEventEmitter emitter_; Packet* packet_; }; class UdpSendWork : public UdpWork { public: explicit UdpSendWork(const ScopedUdpEventEmitter& emitter, const ScopedSocketNode& node) : UdpWork(emitter), node_(node) {} virtual bool Start(int32_t val) { AUTO_LOCK(emitter_->GetLock()); // Does the stream exist, and can it send? if (!node_->TestStreamFlags(SSF_CAN_SEND)) return false; packet_ = emitter_->ReadTXPacket_Locked(); if (NULL == packet_) return false; int err = UDPInterface()->SendTo(node_->socket_resource(), packet_->buffer(), packet_->len(), packet_->addr(), filesystem()->GetRunCompletion(this)); if (err != PP_OK_COMPLETIONPENDING) { // Anything else, we should assume the socket has gone bad. node_->SetError_Locked(err); return false; } node_->SetStreamFlags(SSF_SENDING); return true; } virtual void Run(int32_t length_error) { AUTO_LOCK(emitter_->GetLock()); if (length_error < 0) { node_->SetError_Locked(length_error); return; } // If we did send, then Q more work. node_->ClearStreamFlags(SSF_SENDING); node_->QueueOutput(); } private: // We assume that transmits will always complete. If the upstream // actually back pressures, enough to prevent the Send callback // from triggering, this resource may never go away. ScopedSocketNode node_; }; class UdpRecvWork : public UdpWork { public: explicit UdpRecvWork(const ScopedUdpEventEmitter& emitter) : UdpWork(emitter) { } virtual bool Start(int32_t val) { AUTO_LOCK(emitter_->GetLock()); UdpNode* stream = static_cast<UdpNode*>(emitter_->stream()); // Does the stream exist, and can it recv? if (NULL == stream || !stream->TestStreamFlags(SSF_CAN_RECV)) return false; // Check if we are already receiving. if (stream->TestStreamFlags(SSF_RECVING)) return false; stream->SetStreamFlags(SSF_RECVING); int err = UDPInterface()->RecvFrom(stream->socket_resource(), data_, kMaxPacketSize, &addr_, filesystem()->GetRunCompletion(this)); if (err != PP_OK_COMPLETIONPENDING) { stream->SetError_Locked(err); return false; } return true; } virtual void Run(int32_t length_error) { AUTO_LOCK(emitter_->GetLock()); UdpNode* stream = static_cast<UdpNode*>(emitter_->stream()); if (NULL == stream) return; // On successful receive we queue more input if (length_error > 0) { Packet* packet = new Packet(filesystem()->ppapi()); packet->Copy(data_, length_error, addr_); emitter_->WriteRXPacket_Locked(packet); stream->ClearStreamFlags(SSF_RECVING); stream->QueueInput(); } else { stream->SetError_Locked(length_error); } } private: char data_[kMaxPacketSize]; PP_Resource addr_; }; UdpNode::UdpNode(Filesystem* filesystem) : SocketNode(filesystem), emitter_(new UdpEventEmitter(kDefaultFifoSize, kDefaultFifoSize)) { emitter_->AttachStream(this); } void UdpNode::Destroy() { emitter_->DetachStream(); SocketNode::Destroy(); } UdpEventEmitter* UdpNode::GetEventEmitter() { return emitter_.get(); } Error UdpNode::Init(int open_flags) { Error err = SocketNode::Init(open_flags); if (err != 0) return err; if (UDPInterface() == NULL) { LOG_ERROR("Got NULL interface: UDP"); return EACCES; } socket_resource_ = UDPInterface()->Create(filesystem_->ppapi()->GetInstance()); if (0 == socket_resource_) { LOG_ERROR("Unable to create UDP resource."); return EACCES; } return 0; } void UdpNode::QueueInput() { UdpRecvWork* work = new UdpRecvWork(emitter_); stream()->EnqueueWork(work); } void UdpNode::QueueOutput() { if (!TestStreamFlags(SSF_CAN_SEND)) return; if (TestStreamFlags(SSF_SENDING)) return; UdpSendWork* work = new UdpSendWork(emitter_, ScopedSocketNode(this)); stream()->EnqueueWork(work); } Error UdpNode::Bind(const struct sockaddr* addr, socklen_t len) { if (0 == socket_resource_) return EBADF; /* Only bind once. */ if (IsBound()) return EINVAL; PP_Resource out_addr = SockAddrToResource(addr, len); if (0 == out_addr) return EINVAL; int err = UDPInterface()->Bind(socket_resource_, out_addr, PP_BlockUntilComplete()); filesystem_->ppapi()->ReleaseResource(out_addr); if (err != 0) return PPErrorToErrno(err); // Get the address that was actually bound (in case addr was 0.0.0.0:0). out_addr = UDPInterface()->GetBoundAddress(socket_resource_); if (out_addr == 0) return EINVAL; // Now that we are bound, we can start sending and receiving. SetStreamFlags(SSF_CAN_SEND | SSF_CAN_RECV); QueueInput(); local_addr_ = out_addr; return 0; } Error UdpNode::Connect(const HandleAttr& attr, const struct sockaddr* addr, socklen_t len) { if (0 == socket_resource_) return EBADF; /* Connect for UDP is the default dest, it's legal to change it. */ if (remote_addr_ != 0) { filesystem_->ppapi()->ReleaseResource(remote_addr_); remote_addr_ = 0; } remote_addr_ = SockAddrToResource(addr, len); if (0 == remote_addr_) return EINVAL; return 0; } Error UdpNode::Recv_Locked(void* buf, size_t len, PP_Resource* out_addr, int* out_len) { Packet* packet = emitter_->ReadRXPacket_Locked(); *out_len = 0; *out_addr = 0; if (packet) { int capped_len = static_cast<int32_t>(std::min<int>(len, packet->len())); memcpy(buf, packet->buffer(), capped_len); if (packet->addr() != 0) { filesystem_->ppapi()->AddRefResource(packet->addr()); *out_addr = packet->addr(); } *out_len = capped_len; delete packet; return 0; } // Should never happen, Recv_Locked should not be called // unless already in a POLLIN state. return EBADF; } Error UdpNode::Send_Locked(const void* buf, size_t len, PP_Resource addr, int* out_len) { if (!IsBound()) { // Pepper requires a socket to be bound before it can send. sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = 0; memset(&addr.sin_addr, 0, sizeof(addr.sin_addr)); Error err = Bind(reinterpret_cast<const struct sockaddr*>(&addr), sizeof(addr)); if (err != 0) return err; } *out_len = 0; int capped_len = static_cast<int32_t>(std::min<int>(len, kMaxPacketSize)); Packet* packet = new Packet(filesystem_->ppapi()); packet->Copy(buf, capped_len, addr); emitter_->WriteTXPacket_Locked(packet); *out_len = capped_len; return 0; } } // namespace nacl_io <commit_msg>[NaCl SDK] nacl_io: Fix leak when recv'ing from udp socket.<commit_after>// Copyright 2013 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 "nacl_io/socket/udp_node.h" #include <errno.h> #include <string.h> #include <algorithm> #include "nacl_io/log.h" #include "nacl_io/pepper_interface.h" #include "nacl_io/socket/packet.h" #include "nacl_io/socket/udp_event_emitter.h" #include "nacl_io/stream/stream_fs.h" namespace { const size_t kMaxPacketSize = 65536; const size_t kDefaultFifoSize = kMaxPacketSize * 8; } namespace nacl_io { class UdpWork : public StreamFs::Work { public: explicit UdpWork(const ScopedUdpEventEmitter& emitter) : StreamFs::Work(emitter->stream()->stream()), emitter_(emitter), packet_(NULL) {} ~UdpWork() { delete packet_; } UDPSocketInterface* UDPInterface() { return filesystem()->ppapi()->GetUDPSocketInterface(); } protected: ScopedUdpEventEmitter emitter_; Packet* packet_; }; class UdpSendWork : public UdpWork { public: explicit UdpSendWork(const ScopedUdpEventEmitter& emitter, const ScopedSocketNode& node) : UdpWork(emitter), node_(node) {} virtual bool Start(int32_t val) { AUTO_LOCK(emitter_->GetLock()); // Does the stream exist, and can it send? if (!node_->TestStreamFlags(SSF_CAN_SEND)) return false; packet_ = emitter_->ReadTXPacket_Locked(); if (NULL == packet_) return false; int err = UDPInterface()->SendTo(node_->socket_resource(), packet_->buffer(), packet_->len(), packet_->addr(), filesystem()->GetRunCompletion(this)); if (err != PP_OK_COMPLETIONPENDING) { // Anything else, we should assume the socket has gone bad. node_->SetError_Locked(err); return false; } node_->SetStreamFlags(SSF_SENDING); return true; } virtual void Run(int32_t length_error) { AUTO_LOCK(emitter_->GetLock()); if (length_error < 0) { node_->SetError_Locked(length_error); return; } // If we did send, then Q more work. node_->ClearStreamFlags(SSF_SENDING); node_->QueueOutput(); } private: // We assume that transmits will always complete. If the upstream // actually back pressures, enough to prevent the Send callback // from triggering, this resource may never go away. ScopedSocketNode node_; }; class UdpRecvWork : public UdpWork { public: explicit UdpRecvWork(const ScopedUdpEventEmitter& emitter) : UdpWork(emitter) { } virtual bool Start(int32_t val) { AUTO_LOCK(emitter_->GetLock()); UdpNode* stream = static_cast<UdpNode*>(emitter_->stream()); // Does the stream exist, and can it recv? if (NULL == stream || !stream->TestStreamFlags(SSF_CAN_RECV)) return false; // Check if we are already receiving. if (stream->TestStreamFlags(SSF_RECVING)) return false; stream->SetStreamFlags(SSF_RECVING); int err = UDPInterface()->RecvFrom(stream->socket_resource(), data_, kMaxPacketSize, &addr_, filesystem()->GetRunCompletion(this)); if (err != PP_OK_COMPLETIONPENDING) { stream->SetError_Locked(err); return false; } return true; } virtual void Run(int32_t length_error) { AUTO_LOCK(emitter_->GetLock()); UdpNode* stream = static_cast<UdpNode*>(emitter_->stream()); if (NULL == stream) return; // On successful receive we queue more input if (length_error > 0) { Packet* packet = new Packet(filesystem()->ppapi()); packet->Copy(data_, length_error, addr_); filesystem()->ppapi()->ReleaseResource(addr_); emitter_->WriteRXPacket_Locked(packet); stream->ClearStreamFlags(SSF_RECVING); stream->QueueInput(); } else { stream->SetError_Locked(length_error); } } private: char data_[kMaxPacketSize]; PP_Resource addr_; }; UdpNode::UdpNode(Filesystem* filesystem) : SocketNode(filesystem), emitter_(new UdpEventEmitter(kDefaultFifoSize, kDefaultFifoSize)) { emitter_->AttachStream(this); } void UdpNode::Destroy() { emitter_->DetachStream(); SocketNode::Destroy(); } UdpEventEmitter* UdpNode::GetEventEmitter() { return emitter_.get(); } Error UdpNode::Init(int open_flags) { Error err = SocketNode::Init(open_flags); if (err != 0) return err; if (UDPInterface() == NULL) { LOG_ERROR("Got NULL interface: UDP"); return EACCES; } socket_resource_ = UDPInterface()->Create(filesystem_->ppapi()->GetInstance()); if (0 == socket_resource_) { LOG_ERROR("Unable to create UDP resource."); return EACCES; } return 0; } void UdpNode::QueueInput() { UdpRecvWork* work = new UdpRecvWork(emitter_); stream()->EnqueueWork(work); } void UdpNode::QueueOutput() { if (!TestStreamFlags(SSF_CAN_SEND)) return; if (TestStreamFlags(SSF_SENDING)) return; UdpSendWork* work = new UdpSendWork(emitter_, ScopedSocketNode(this)); stream()->EnqueueWork(work); } Error UdpNode::Bind(const struct sockaddr* addr, socklen_t len) { if (0 == socket_resource_) return EBADF; /* Only bind once. */ if (IsBound()) return EINVAL; PP_Resource out_addr = SockAddrToResource(addr, len); if (0 == out_addr) return EINVAL; int err = UDPInterface()->Bind(socket_resource_, out_addr, PP_BlockUntilComplete()); filesystem_->ppapi()->ReleaseResource(out_addr); if (err != 0) return PPErrorToErrno(err); // Get the address that was actually bound (in case addr was 0.0.0.0:0). out_addr = UDPInterface()->GetBoundAddress(socket_resource_); if (out_addr == 0) return EINVAL; // Now that we are bound, we can start sending and receiving. SetStreamFlags(SSF_CAN_SEND | SSF_CAN_RECV); QueueInput(); local_addr_ = out_addr; return 0; } Error UdpNode::Connect(const HandleAttr& attr, const struct sockaddr* addr, socklen_t len) { if (0 == socket_resource_) return EBADF; /* Connect for UDP is the default dest, it's legal to change it. */ if (remote_addr_ != 0) { filesystem_->ppapi()->ReleaseResource(remote_addr_); remote_addr_ = 0; } remote_addr_ = SockAddrToResource(addr, len); if (0 == remote_addr_) return EINVAL; return 0; } Error UdpNode::Recv_Locked(void* buf, size_t len, PP_Resource* out_addr, int* out_len) { Packet* packet = emitter_->ReadRXPacket_Locked(); *out_len = 0; *out_addr = 0; if (packet) { int capped_len = static_cast<int32_t>(std::min<int>(len, packet->len())); memcpy(buf, packet->buffer(), capped_len); if (packet->addr() != 0) { filesystem_->ppapi()->AddRefResource(packet->addr()); *out_addr = packet->addr(); } *out_len = capped_len; delete packet; return 0; } // Should never happen, Recv_Locked should not be called // unless already in a POLLIN state. return EBADF; } Error UdpNode::Send_Locked(const void* buf, size_t len, PP_Resource addr, int* out_len) { if (!IsBound()) { // Pepper requires a socket to be bound before it can send. sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = 0; memset(&addr.sin_addr, 0, sizeof(addr.sin_addr)); Error err = Bind(reinterpret_cast<const struct sockaddr*>(&addr), sizeof(addr)); if (err != 0) return err; } *out_len = 0; int capped_len = static_cast<int32_t>(std::min<int>(len, kMaxPacketSize)); Packet* packet = new Packet(filesystem_->ppapi()); packet->Copy(buf, capped_len, addr); emitter_->WriteTXPacket_Locked(packet); *out_len = capped_len; return 0; } } // namespace nacl_io <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ListenerHelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2006-11-06 15:04:41 $ * * 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 * ************************************************************************/ #include "ListenerHelper.h" using com::sun::star::frame::XFrame; using com::sun::star::frame::XDispatch; using com::sun::star::frame::XStatusListener; using com::sun::star::lang::XEventListener; using com::sun::star::lang::EventObject; using com::sun::star::uno::Reference; using com::sun::star::uno::RuntimeException; using com::sun::star::frame::FeatureStateEvent; static AllListeners aListeners; void ListenerHelper::AddListener( const Reference < XFrame >& xFrame, const Reference < XStatusListener > xControl, const ::rtl::OUString& aCommand ) { sal_uInt32 i=0; sal_uInt32 nSize = aListeners.size(); for ( i=0; i<nSize; i++ ) if ( aListeners[i].xFrame == xFrame ) break; OSL_ENSURE( i<nSize, "No dispatch found for this listener!" ); aListeners[i].aContainer[aCommand].push_back( xControl ); } void ListenerHelper::RemoveListener( const Reference < XFrame >& xFrame, const Reference < XStatusListener > xControl, const ::rtl::OUString& aCommand ) { sal_uInt32 nSize = aListeners.size(); for ( sal_uInt32 i=0; i<nSize; i++ ) { if ( aListeners[i].xFrame == xFrame ) { StatusListeners& aL = aListeners[i].aContainer[aCommand]; StatusListeners::iterator aIter = aL.begin(); while ( aIter != aL.end() ) { if ( (*aIter) == xControl ) { aL.erase( aIter ); break; } aIter++; } } } } void ListenerHelper::Notify( const Reference < XFrame >& xFrame, const ::rtl::OUString& aCommand, FeatureStateEvent& rEvent ) { sal_uInt32 nSize = aListeners.size(); for ( sal_uInt32 i=0; i<nSize; i++ ) { if ( aListeners[i].xFrame == xFrame ) { rEvent.Source = aListeners[i].xDispatch; StatusListeners& aL = aListeners[i].aContainer[aCommand]; StatusListeners::iterator aIter = aL.begin(); while ( aIter != aL.end() ) { (*aIter)->statusChanged( rEvent ); aIter++; } } } } com::sun::star::uno::Reference < XDispatch > ListenerHelper::GetDispatch( const Reference < XFrame >& xFrame, const ::rtl::OUString& aCommand ) { sal_uInt32 nSize = aListeners.size(); for ( sal_uInt32 i=0; i<nSize; i++ ) { if ( aListeners[i].xFrame == xFrame ) return aListeners[i].xDispatch; } return Reference < XDispatch >(); } void ListenerHelper::AddDispatch( const Reference < XDispatch > xDispatch, const Reference < XFrame >& xFrame, const ::rtl::OUString& aCommand ) { ListenerItem aItem; aItem.xFrame = xFrame; aItem.xDispatch = xDispatch; aListeners.push_back( aItem ); xFrame->addEventListener( new ListenerItemEventListener( xFrame ) ); } void SAL_CALL ListenerItemEventListener::disposing( const EventObject& aEvent) throw (RuntimeException) { AllListeners::iterator aIter = aListeners.begin(); while ( aIter != aListeners.end() ) { if ( (*aIter).xFrame == mxFrame ) { aListeners.erase( aIter ); break; } aIter++; } } <commit_msg>INTEGRATION: CWS changefileheader (1.4.98); FILE MERGED 2008/03/31 15:52:51 rt 1.4.98.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: ListenerHelper.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. * ************************************************************************/ #include "ListenerHelper.h" using com::sun::star::frame::XFrame; using com::sun::star::frame::XDispatch; using com::sun::star::frame::XStatusListener; using com::sun::star::lang::XEventListener; using com::sun::star::lang::EventObject; using com::sun::star::uno::Reference; using com::sun::star::uno::RuntimeException; using com::sun::star::frame::FeatureStateEvent; static AllListeners aListeners; void ListenerHelper::AddListener( const Reference < XFrame >& xFrame, const Reference < XStatusListener > xControl, const ::rtl::OUString& aCommand ) { sal_uInt32 i=0; sal_uInt32 nSize = aListeners.size(); for ( i=0; i<nSize; i++ ) if ( aListeners[i].xFrame == xFrame ) break; OSL_ENSURE( i<nSize, "No dispatch found for this listener!" ); aListeners[i].aContainer[aCommand].push_back( xControl ); } void ListenerHelper::RemoveListener( const Reference < XFrame >& xFrame, const Reference < XStatusListener > xControl, const ::rtl::OUString& aCommand ) { sal_uInt32 nSize = aListeners.size(); for ( sal_uInt32 i=0; i<nSize; i++ ) { if ( aListeners[i].xFrame == xFrame ) { StatusListeners& aL = aListeners[i].aContainer[aCommand]; StatusListeners::iterator aIter = aL.begin(); while ( aIter != aL.end() ) { if ( (*aIter) == xControl ) { aL.erase( aIter ); break; } aIter++; } } } } void ListenerHelper::Notify( const Reference < XFrame >& xFrame, const ::rtl::OUString& aCommand, FeatureStateEvent& rEvent ) { sal_uInt32 nSize = aListeners.size(); for ( sal_uInt32 i=0; i<nSize; i++ ) { if ( aListeners[i].xFrame == xFrame ) { rEvent.Source = aListeners[i].xDispatch; StatusListeners& aL = aListeners[i].aContainer[aCommand]; StatusListeners::iterator aIter = aL.begin(); while ( aIter != aL.end() ) { (*aIter)->statusChanged( rEvent ); aIter++; } } } } com::sun::star::uno::Reference < XDispatch > ListenerHelper::GetDispatch( const Reference < XFrame >& xFrame, const ::rtl::OUString& aCommand ) { sal_uInt32 nSize = aListeners.size(); for ( sal_uInt32 i=0; i<nSize; i++ ) { if ( aListeners[i].xFrame == xFrame ) return aListeners[i].xDispatch; } return Reference < XDispatch >(); } void ListenerHelper::AddDispatch( const Reference < XDispatch > xDispatch, const Reference < XFrame >& xFrame, const ::rtl::OUString& aCommand ) { ListenerItem aItem; aItem.xFrame = xFrame; aItem.xDispatch = xDispatch; aListeners.push_back( aItem ); xFrame->addEventListener( new ListenerItemEventListener( xFrame ) ); } void SAL_CALL ListenerItemEventListener::disposing( const EventObject& aEvent) throw (RuntimeException) { AllListeners::iterator aIter = aListeners.begin(); while ( aIter != aListeners.end() ) { if ( (*aIter).xFrame == mxFrame ) { aListeners.erase( aIter ); break; } aIter++; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkXRenderWindow.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 <math.h> #include <stdlib.h> #include <iostream.h> #include "vtkXRenderWindow.h" #include "vtkXRenderWindowInteractor.h" vtkXRenderWindow::vtkXRenderWindow() { vtkDebugMacro(<< "vtkXRenderWindow::vtkXRenderWindow"); this->DisplayId = (Display *)NULL; this->WindowId = (Window)NULL; this->ParentId = (Window)NULL; this->NextWindowId = (Window)NULL; this->ColorMap = (Colormap)NULL; this->ScreenSize[0] = 0; this->ScreenSize[1] = 0; this->OwnDisplay = 0; } vtkXRenderWindow::~vtkXRenderWindow() { vtkDebugMacro(<< "vtkXRenderWindow::~vtkXRenderWindow"); if (this->DisplayId) { XSync(this->DisplayId,0); } // if we create the display, we'll delete it if (this->OwnDisplay && this->DisplayId) { XCloseDisplay(this->DisplayId); this->DisplayId = NULL; } } int vtkXRenderWindowFoundMatch; Bool vtkXRenderWindowPredProc(Display *vtkNotUsed(disp), XEvent *event, char *arg) { Window win = (Window)arg; if ((((XAnyEvent *)event)->window == win) && ((event->type == ButtonPress))) vtkXRenderWindowFoundMatch = 1; return 0; } void *vtkXRenderWindow::GetGenericContext() { static GC gc = (GC) NULL; if (!gc) gc = XCreateGC(this->DisplayId, this->WindowId, 0, 0); return (void *) gc; } int vtkXRenderWindow::GetEventPending() { XEvent report; vtkXRenderWindowFoundMatch = 0; XCheckIfEvent(this->DisplayId, &report, vtkXRenderWindowPredProc, (char *)this->WindowId); return vtkXRenderWindowFoundMatch; } // Get the size of the screen in pixels int *vtkXRenderWindow::GetScreenSize() { // get the default display connection if (!this->DisplayId) { this->DisplayId = XOpenDisplay((char *)NULL); if (this->DisplayId == NULL) { vtkErrorMacro(<< "bad X server connection.\n"); } else { this->OwnDisplay = 1; } } this->ScreenSize[0] = DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId)); this->ScreenSize[1] = DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId)); return this->ScreenSize; } // Get the current size of the window in pixels. int *vtkXRenderWindow::GetSize(void) { XWindowAttributes attribs; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Size); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); this->Size[0] = attribs.width; this->Size[1] = attribs.height; return this->Size; } // Get the position in screen coordinates (pixels) of the window. int *vtkXRenderWindow::GetPosition(void) { XWindowAttributes attribs; int x,y; Window child; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Position); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); x = attribs.x; y = attribs.y; XTranslateCoordinates(this->DisplayId,this->WindowId, RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)), x,y,&this->Position[0],&this->Position[1],&child); return this->Position; } // Get this RenderWindow's X display id. Display *vtkXRenderWindow::GetDisplayId() { vtkDebugMacro(<< "Returning DisplayId of " << (void *)this->DisplayId << "\n"); return this->DisplayId; } // Get this RenderWindow's parent X window id. Window vtkXRenderWindow::GetParentId() { vtkDebugMacro(<< "Returning ParentId of " << (void *)this->ParentId << "\n"); return this->ParentId; } // Get this RenderWindow's X window id. Window vtkXRenderWindow::GetWindowId() { vtkDebugMacro(<< "Returning WindowId of " << (void *)this->WindowId << "\n"); return this->WindowId; } // Move the window to a new position on the display. void vtkXRenderWindow::SetPosition(int x, int y) { // if we aren't mapped then just set the ivars if (!this->Mapped) { if ((this->Position[0] != x)||(this->Position[1] != y)) { this->Modified(); } this->Position[0] = x; this->Position[1] = y; return; } XMoveResizeWindow(this->DisplayId,this->WindowId,x,y, this->Size[0], this->Size[1]); XSync(this->DisplayId,False); } // Sets the parent of the window that WILL BE created. void vtkXRenderWindow::SetParentId(Window arg) { if (this->ParentId) { vtkErrorMacro("ParentId is already set."); return; } vtkDebugMacro(<< "Setting ParentId to " << (void *)arg << "\n"); this->ParentId = arg; } // Set this RenderWindow's X window id to a pre-existing window. void vtkXRenderWindow::SetWindowId(Window arg) { vtkDebugMacro(<< "Setting WindowId to " << (void *)arg << "\n"); this->WindowId = arg; } // Set this RenderWindow's X window id to a pre-existing window. void vtkXRenderWindow::SetWindowInfo(char *info) { int tmp; // get the default display connection if (!this->DisplayId) { this->DisplayId = XOpenDisplay((char *)NULL); if (this->DisplayId == NULL) { vtkErrorMacro(<< "bad X server connection.\n"); } else { this->OwnDisplay = 1; } } sscanf(info,"%i",&tmp); this->WindowId = tmp; vtkDebugMacro(<< "Setting WindowId to " << (void *)this->WindowId<< "\n"); } void vtkXRenderWindow::SetWindowId(void *arg) { this->SetWindowId((Window)arg); } void vtkXRenderWindow::SetParentId(void *arg) { this->SetParentId((Window)arg); } void vtkXRenderWindow::SetWindowName(char * name) { XTextProperty win_name_text_prop; vtkRenderWindow::SetWindowName( name ); if (this->Mapped) { if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 ) { vtkWarningMacro(<< "Can't rename window"); return; } XSetWMName( this->DisplayId, this->WindowId, &win_name_text_prop ); XSetWMIconName( this->DisplayId, this->WindowId, &win_name_text_prop ); } } // Specify the X window id to use if a WindowRemap is done. void vtkXRenderWindow::SetNextWindowId(Window arg) { vtkDebugMacro(<< "Setting NextWindowId to " << (void *)arg << "\n"); this->NextWindowId = arg; } // Set the X display id for this RenderWindow to use to a pre-existing // X display id. void vtkXRenderWindow::SetDisplayId(Display *arg) { vtkDebugMacro(<< "Setting DisplayId to " << (void *)arg << "\n"); this->DisplayId = arg; this->OwnDisplay = 0; } void vtkXRenderWindow::SetDisplayId(void *arg) { this->SetDisplayId((Display *)arg); this->OwnDisplay = 0; } void vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent) { this->vtkRenderWindow::PrintSelf(os,indent); os << indent << "Color Map: " << this->ColorMap << "\n"; os << indent << "Display Id: " << this->GetDisplayId() << "\n"; os << indent << "Next Window Id: " << this->NextWindowId << "\n"; os << indent << "Window Id: " << this->GetWindowId() << "\n"; } <commit_msg>ERR: memory leak in SetWindowName repaired.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkXRenderWindow.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 <math.h> #include <stdlib.h> #include <iostream.h> #include "vtkXRenderWindow.h" #include "vtkXRenderWindowInteractor.h" vtkXRenderWindow::vtkXRenderWindow() { vtkDebugMacro(<< "vtkXRenderWindow::vtkXRenderWindow"); this->DisplayId = (Display *)NULL; this->WindowId = (Window)NULL; this->ParentId = (Window)NULL; this->NextWindowId = (Window)NULL; this->ColorMap = (Colormap)NULL; this->ScreenSize[0] = 0; this->ScreenSize[1] = 0; this->OwnDisplay = 0; } vtkXRenderWindow::~vtkXRenderWindow() { vtkDebugMacro(<< "vtkXRenderWindow::~vtkXRenderWindow"); if (this->DisplayId) { XSync(this->DisplayId,0); } // if we create the display, we'll delete it if (this->OwnDisplay && this->DisplayId) { XCloseDisplay(this->DisplayId); this->DisplayId = NULL; } } int vtkXRenderWindowFoundMatch; Bool vtkXRenderWindowPredProc(Display *vtkNotUsed(disp), XEvent *event, char *arg) { Window win = (Window)arg; if ((((XAnyEvent *)event)->window == win) && ((event->type == ButtonPress))) vtkXRenderWindowFoundMatch = 1; return 0; } void *vtkXRenderWindow::GetGenericContext() { static GC gc = (GC) NULL; if (!gc) gc = XCreateGC(this->DisplayId, this->WindowId, 0, 0); return (void *) gc; } int vtkXRenderWindow::GetEventPending() { XEvent report; vtkXRenderWindowFoundMatch = 0; XCheckIfEvent(this->DisplayId, &report, vtkXRenderWindowPredProc, (char *)this->WindowId); return vtkXRenderWindowFoundMatch; } // Get the size of the screen in pixels int *vtkXRenderWindow::GetScreenSize() { // get the default display connection if (!this->DisplayId) { this->DisplayId = XOpenDisplay((char *)NULL); if (this->DisplayId == NULL) { vtkErrorMacro(<< "bad X server connection.\n"); } else { this->OwnDisplay = 1; } } this->ScreenSize[0] = DisplayWidth(this->DisplayId, DefaultScreen(this->DisplayId)); this->ScreenSize[1] = DisplayHeight(this->DisplayId, DefaultScreen(this->DisplayId)); return this->ScreenSize; } // Get the current size of the window in pixels. int *vtkXRenderWindow::GetSize(void) { XWindowAttributes attribs; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Size); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); this->Size[0] = attribs.width; this->Size[1] = attribs.height; return this->Size; } // Get the position in screen coordinates (pixels) of the window. int *vtkXRenderWindow::GetPosition(void) { XWindowAttributes attribs; int x,y; Window child; // if we aren't mapped then just return the ivar if (!this->Mapped) { return(this->Position); } // Find the current window size XGetWindowAttributes(this->DisplayId, this->WindowId, &attribs); x = attribs.x; y = attribs.y; XTranslateCoordinates(this->DisplayId,this->WindowId, RootWindowOfScreen(ScreenOfDisplay(this->DisplayId,0)), x,y,&this->Position[0],&this->Position[1],&child); return this->Position; } // Get this RenderWindow's X display id. Display *vtkXRenderWindow::GetDisplayId() { vtkDebugMacro(<< "Returning DisplayId of " << (void *)this->DisplayId << "\n"); return this->DisplayId; } // Get this RenderWindow's parent X window id. Window vtkXRenderWindow::GetParentId() { vtkDebugMacro(<< "Returning ParentId of " << (void *)this->ParentId << "\n"); return this->ParentId; } // Get this RenderWindow's X window id. Window vtkXRenderWindow::GetWindowId() { vtkDebugMacro(<< "Returning WindowId of " << (void *)this->WindowId << "\n"); return this->WindowId; } // Move the window to a new position on the display. void vtkXRenderWindow::SetPosition(int x, int y) { // if we aren't mapped then just set the ivars if (!this->Mapped) { if ((this->Position[0] != x)||(this->Position[1] != y)) { this->Modified(); } this->Position[0] = x; this->Position[1] = y; return; } XMoveResizeWindow(this->DisplayId,this->WindowId,x,y, this->Size[0], this->Size[1]); XSync(this->DisplayId,False); } // Sets the parent of the window that WILL BE created. void vtkXRenderWindow::SetParentId(Window arg) { if (this->ParentId) { vtkErrorMacro("ParentId is already set."); return; } vtkDebugMacro(<< "Setting ParentId to " << (void *)arg << "\n"); this->ParentId = arg; } // Set this RenderWindow's X window id to a pre-existing window. void vtkXRenderWindow::SetWindowId(Window arg) { vtkDebugMacro(<< "Setting WindowId to " << (void *)arg << "\n"); this->WindowId = arg; } // Set this RenderWindow's X window id to a pre-existing window. void vtkXRenderWindow::SetWindowInfo(char *info) { int tmp; // get the default display connection if (!this->DisplayId) { this->DisplayId = XOpenDisplay((char *)NULL); if (this->DisplayId == NULL) { vtkErrorMacro(<< "bad X server connection.\n"); } else { this->OwnDisplay = 1; } } sscanf(info,"%i",&tmp); this->WindowId = tmp; vtkDebugMacro(<< "Setting WindowId to " << (void *)this->WindowId<< "\n"); } void vtkXRenderWindow::SetWindowId(void *arg) { this->SetWindowId((Window)arg); } void vtkXRenderWindow::SetParentId(void *arg) { this->SetParentId((Window)arg); } void vtkXRenderWindow::SetWindowName(char * name) { XTextProperty win_name_text_prop; vtkRenderWindow::SetWindowName( name ); if (this->Mapped) { if( XStringListToTextProperty( &name, 1, &win_name_text_prop ) == 0 ) { XFree (win_name_text_prop.value); vtkWarningMacro(<< "Can't rename window"); return; } XSetWMName( this->DisplayId, this->WindowId, &win_name_text_prop ); XSetWMIconName( this->DisplayId, this->WindowId, &win_name_text_prop ); XFree (win_name_text_prop.value); } } // Specify the X window id to use if a WindowRemap is done. void vtkXRenderWindow::SetNextWindowId(Window arg) { vtkDebugMacro(<< "Setting NextWindowId to " << (void *)arg << "\n"); this->NextWindowId = arg; } // Set the X display id for this RenderWindow to use to a pre-existing // X display id. void vtkXRenderWindow::SetDisplayId(Display *arg) { vtkDebugMacro(<< "Setting DisplayId to " << (void *)arg << "\n"); this->DisplayId = arg; this->OwnDisplay = 0; } void vtkXRenderWindow::SetDisplayId(void *arg) { this->SetDisplayId((Display *)arg); this->OwnDisplay = 0; } void vtkXRenderWindow::PrintSelf(ostream& os, vtkIndent indent) { this->vtkRenderWindow::PrintSelf(os,indent); os << indent << "Color Map: " << this->ColorMap << "\n"; os << indent << "Display Id: " << this->GetDisplayId() << "\n"; os << indent << "Next Window Id: " << this->NextWindowId << "\n"; os << indent << "Window Id: " << this->GetWindowId() << "\n"; } <|endoftext|>
<commit_before>#include "workerCL.hpp" #define __CL_DEFINE_EXCEPTIONS #include <CL/cl.hpp> #include <vector> #include <string> #include <iostream> #include "log.hpp" #include "reads.hpp" using namespace std; WorkerCL::WorkerCL(size_t platform_id, size_t device_id){ /* GPU environment preparation */ //Get platforms (drivers) list and keep the one to be use vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); if(!all_platforms.size()){ //No platform ? Send error string error = "OPENCL: no platforms found."; throw(error); } m_platform = all_platforms[platform_id]; //Get devices list and keep the one to use vector<cl::Device> devices; m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); if(device_id >= devices.size()){ string error = "OPENCL: no device of id "+to_string(device_id)+ " on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)"; throw(error); } m_device = devices[device_id]; //Create context m_context = cl::Context({m_device}); //initialize commands queue m_commandqueue = cl::CommandQueue(m_context, m_device); //Build kernel sources m_program = cl::Program(m_context, kernel_cmp_2_contigs); if(m_program.build({m_device}) != CL_SUCCESS){ string error = "Error building: "; error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device); throw(error); } //Make the kernel m_kernel = cl::Kernel(m_program, "cmp_2_contigs"); } WorkerCL::~WorkerCL(){ } void WorkerCL::run(const Contigs& contigs, size_t work_group_size){ /* Create the string containing all contigs sequences and store the list of contigs size (in same orders) to be able to retrieve contigs. Size is store in an uint64_t (ulong) to be sure it is 64bits as cl_ulong */ //Get list of contigs size, the total length of the //contigs concatenation and the longuest contig size uint64_t nbContigs = contigs.get_nbContigs(); uint64_t ultraSequenceSize = 0; uint64_t longuest_contig_size = 0; vector<uint64_t> contigs_size (nbContigs, 0); for(uint64_t i=0; i < nbContigs; i++){ contigs_size[i] = contigs.get_sizeContig(i); ultraSequenceSize += contigs_size[i]; if(contigs_size[i] > longuest_contig_size){longuest_contig_size = contigs_size[i];} } //Prepare GPU for the run cl::Event ev; //infos buffer (64bits): number of contigs, size of the ultrasequence, size of longuest contig //buffer only accepts non-dynamics arrays (even of size 1) uint64_t infos[3] = {nbContigs, ultraSequenceSize, longuest_contig_size}; cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)); m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos); m_kernel.setArg(0, buf_infos); //update kernel //Prepare the buffer for the results matrix (it will be 1D so an id of {x,y} is id=x+y*x_size) //The size of the buffer = char * x_size * y_size. Note: x_size == y_size == nb_contigs unsigned int scores_size = sizeof(char)*nbContigs*nbContigs; cl::Buffer buf_scores (m_context, CL_MEM_WRITE_ONLY, scores_size); m_kernel.setArg(1, buf_scores); //sequences sizes (array of 64bits) buffer cl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs); m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]); m_kernel.setArg(2, buf_sizes); //ultrasequence, get each contigs sequence and add it in ultrasequence char* ultraSequence = new char[ultraSequenceSize]; uint64_t i = 0; for(uint64_t c=0; c < nbContigs; c++){ string seq = contigs.get_seqContig(c); for(size_t j=0; j < seq.size(); j++){ ultraSequence[i] = seq[j]; i++; } } cout << "UltraSequence:" << endl; cout << ultraSequence << endl; cl::Buffer buf_ultraseq (m_context, CL_MEM_READ_ONLY, sizeof(char)*ultraSequenceSize); m_commandqueue.enqueueWriteBuffer(buf_ultraseq, CL_TRUE, 0, sizeof(char)*ultraSequenceSize, ultraSequence); m_kernel.setArg(3, buf_ultraseq); delete ultraSequence; //Clean the memory ultraSequence = nullptr; //buffer for work items : they need 2 arrays for need2a and 2 array for each sequences. These arrays are of size of longuest contig. /* Each work item need its own array (for each arrays) allocated on local. So a local array (of a work group) contains all concatenated array of the work items of the same group. This local array have a size of longuest_contig_size*work_group_size number of elements. */ //Run the kernel and wait the end m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev); ev.wait(); //Get the score matrix: get the buffer into a 1D array then convert de 2D vectors array char* scores_1D = new char[nbContigs*nbContigs]; m_commandqueue.enqueueReadBuffer(buf_scores, CL_TRUE, 0, scores_size, scores_1D); vector< vector<char> > scores = vector< vector<char> >(nbContigs, vector<char>(nbContigs, 0)); for(size_t j=0; j<nbContigs; j++){ for(size_t i=0; i<nbContigs; i++){ scores[i][j] = scores_1D[i+nbContigs*j]; } } //TEST: display scores cerr << "Seqs" << flush; for(size_t i=0; i < nbContigs; i++){cerr << "\t" << i << flush;} cerr << endl; for(size_t j=0; j < nbContigs; j++){ string t = to_string(j); for(size_t i=0; i < nbContigs; i++){ t += "\t"+to_string(scores[i][j]); } cerr << t << endl; } //Clean the memory delete scores_1D; scores_1D = nullptr; } void WorkerCL::list_infos(Log& output){ string txt; //Get platforms txt = "\n\t[Platforms list]"; output.write(txt); vector<cl::Platform> platforms; cl::Platform::get(&platforms); if(!platforms.size()){ txt = "No platform detected"; output.write(txt); return; } txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version"; output.write(txt); for(size_t i=0; i < platforms.size(); i++){ cl::Platform& p = platforms[i]; txt = to_string(i); txt += "\t" + p.getInfo<CL_PLATFORM_NAME>(); txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>(); txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>(); txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>(); //txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>(); output.write(txt); } //Get devices txt = "\n\t[Devices list]"; output.write(txt); txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdevice_globalmem\tdevice_localmem\tdevice_maxgroupsize\tdriver_version\topencl_c_version"; output.write(txt); for(size_t p = 0; p < platforms.size(); p++){ vector<cl::Device> devices; platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices); for(size_t d = 0; d < devices.size(); d++){ cl::Device& device = devices[d]; txt = to_string(p)+"\t"+to_string(d); txt += "\t" + device.getInfo<CL_DEVICE_NAME>(); txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>(); txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>(); txt += "\t" + device.getInfo<CL_DEVICE_VERSION>(); txt += "\t" + to_string(device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>())+"B"; txt += "\t" + to_string(device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>())+"B"; txt += "\t" + to_string(device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>()); txt += "\t" + device.getInfo<CL_DRIVER_VERSION>(); txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>(); output.write(txt); } } } /* Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code, et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne. */ string WorkerCL::kernel_cmp_2_contigs = R"CLCODE( kernel void cmp_2_contigs(global unsigned long *infos, global char *scores, global unsigned long *seqs_sizes, global char *ultraseq){ int seq1_id = get_global_id(0); int seq2_id = get_global_id(1); //Get the position of the seqs in the ultraseq unsigned long seq1_begin = 0; unsigned long seq2_begin = 0; unsigned long i=0; while(i < seq1_id || i < seq2_id){ if(i < seq1_id){seq1_begin += seqs_sizes[i];} if(i < seq2_id){seq2_begin += seqs_sizes[i];} i++; } //Get the sizes and the end pos of the seqs unsigned long seq1_size = seqs_sizes[seq1_id]; unsigned long seq2_size = seqs_sizes[seq2_id]; unsigned long seq1_end= seq1_begin + seq1_size - 1; unsigned long seq2_end= seq2_begin + seq1_size - 1; //Test if same seq : =1 else =0 scores[seq1_id + infos[0]*seq2_id] = 0; if(seq1_size == seq2_size){ bool same = true; for(unsigned int i=0; i < seq1_size; i++){ if(ultraseq[seq1_begin+i] != ultraseq[seq2_begin+i]){ same = false; i = seq1_size; } } if(same){scores[seq1_id+infos[0]*seq2_id]=1;} } } )CLCODE"; <commit_msg>Use ptr to access the sequences (instead of copying them in private/local). It's a test to the further implementation of local buffers manipulations<commit_after>#include "workerCL.hpp" #define __CL_DEFINE_EXCEPTIONS #include <CL/cl.hpp> #include <vector> #include <string> #include <iostream> #include "log.hpp" #include "reads.hpp" using namespace std; WorkerCL::WorkerCL(size_t platform_id, size_t device_id){ /* GPU environment preparation */ //Get platforms (drivers) list and keep the one to be use vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); if(!all_platforms.size()){ //No platform ? Send error string error = "OPENCL: no platforms found."; throw(error); } m_platform = all_platforms[platform_id]; //Get devices list and keep the one to use vector<cl::Device> devices; m_platform.getDevices(CL_DEVICE_TYPE_ALL, &devices); if(device_id >= devices.size()){ string error = "OPENCL: no device of id "+to_string(device_id)+ " on platform "+to_string(platform_id)+" ("+to_string(devices.size())+" devices)"; throw(error); } m_device = devices[device_id]; //Create context m_context = cl::Context({m_device}); //initialize commands queue m_commandqueue = cl::CommandQueue(m_context, m_device); //Build kernel sources m_program = cl::Program(m_context, kernel_cmp_2_contigs); if(m_program.build({m_device}) != CL_SUCCESS){ string error = "Error building: "; error += m_program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device); throw(error); } //Make the kernel m_kernel = cl::Kernel(m_program, "cmp_2_contigs"); } WorkerCL::~WorkerCL(){ } void WorkerCL::run(const Contigs& contigs, size_t work_group_size){ /* Create the string containing all contigs sequences and store the list of contigs size (in same orders) to be able to retrieve contigs. Size is store in an uint64_t (ulong) to be sure it is 64bits as cl_ulong */ //Get list of contigs size, the total length of the //contigs concatenation and the longuest contig size uint64_t nbContigs = contigs.get_nbContigs(); uint64_t ultraSequenceSize = 0; uint64_t longuest_contig_size = 0; vector<uint64_t> contigs_size (nbContigs, 0); for(uint64_t i=0; i < nbContigs; i++){ contigs_size[i] = contigs.get_sizeContig(i); ultraSequenceSize += contigs_size[i]; if(contigs_size[i] > longuest_contig_size){longuest_contig_size = contigs_size[i];} } //Prepare GPU for the run cl::Event ev; //infos buffer (64bits): number of contigs, size of the ultrasequence, size of longuest contig //buffer only accepts non-dynamics arrays (even of size 1) uint64_t infos[3] = {nbContigs, ultraSequenceSize, longuest_contig_size}; cl::Buffer buf_infos (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)); m_commandqueue.enqueueWriteBuffer(buf_infos, CL_TRUE, 0, sizeof(uint64_t), &infos); m_kernel.setArg(0, buf_infos); //update kernel //Prepare the buffer for the results matrix (it will be 1D so an id of {x,y} is id=x+y*x_size) //The size of the buffer = char * x_size * y_size. Note: x_size == y_size == nb_contigs unsigned int scores_size = sizeof(char)*nbContigs*nbContigs; cl::Buffer buf_scores (m_context, CL_MEM_WRITE_ONLY, scores_size); m_kernel.setArg(1, buf_scores); //sequences sizes (array of 64bits) buffer cl::Buffer buf_sizes (m_context, CL_MEM_READ_ONLY, sizeof(uint64_t)*nbContigs); m_commandqueue.enqueueWriteBuffer(buf_sizes, CL_TRUE, 0, sizeof(uint64_t)*nbContigs, &contigs_size[0]); m_kernel.setArg(2, buf_sizes); //ultrasequence, get each contigs sequence and add it in ultrasequence char* ultraSequence = new char[ultraSequenceSize]; uint64_t i = 0; for(uint64_t c=0; c < nbContigs; c++){ string seq = contigs.get_seqContig(c); for(size_t j=0; j < seq.size(); j++){ ultraSequence[i] = seq[j]; i++; } } cout << "UltraSequence:" << endl; cout << ultraSequence << endl; cl::Buffer buf_ultraseq (m_context, CL_MEM_READ_ONLY, sizeof(char)*ultraSequenceSize); m_commandqueue.enqueueWriteBuffer(buf_ultraseq, CL_TRUE, 0, sizeof(char)*ultraSequenceSize, ultraSequence); m_kernel.setArg(3, buf_ultraseq); delete ultraSequence; //Clean the memory ultraSequence = nullptr; //buffer for work items : they need 2 arrays for need2a and 2 array for each sequences. These arrays are of size of longuest contig. /* Each work item need its own array (for each arrays) allocated on local. So a local array (of a work group) contains all concatenated array of the work items of the same group. This local array have a size of longuest_contig_size*work_group_size number of elements. */ //Run the kernel and wait the end m_commandqueue.enqueueNDRangeKernel(m_kernel,cl::NullRange, cl::NDRange(nbContigs, nbContigs), cl::NullRange, NULL, &ev); ev.wait(); //Get the score matrix: get the buffer into a 1D array then convert de 2D vectors array char* scores_1D = new char[nbContigs*nbContigs]; m_commandqueue.enqueueReadBuffer(buf_scores, CL_TRUE, 0, scores_size, scores_1D); vector< vector<char> > scores = vector< vector<char> >(nbContigs, vector<char>(nbContigs, 0)); for(size_t j=0; j<nbContigs; j++){ for(size_t i=0; i<nbContigs; i++){ scores[i][j] = scores_1D[i+nbContigs*j]; } } //TEST: display scores cerr << "Seqs" << flush; for(size_t i=0; i < nbContigs; i++){cerr << "\t" << i << flush;} cerr << endl; for(size_t j=0; j < nbContigs; j++){ string t = to_string(j); for(size_t i=0; i < nbContigs; i++){ t += "\t"+to_string(scores[i][j]); } cerr << t << endl; } //Clean the memory delete scores_1D; scores_1D = nullptr; } void WorkerCL::list_infos(Log& output){ string txt; //Get platforms txt = "\n\t[Platforms list]"; output.write(txt); vector<cl::Platform> platforms; cl::Platform::get(&platforms); if(!platforms.size()){ txt = "No platform detected"; output.write(txt); return; } txt = "platform_id\tplatform_name\tplatform_profile\tplatform_vendor\tplatform_version"; output.write(txt); for(size_t i=0; i < platforms.size(); i++){ cl::Platform& p = platforms[i]; txt = to_string(i); txt += "\t" + p.getInfo<CL_PLATFORM_NAME>(); txt += "\t" + p.getInfo<CL_PLATFORM_PROFILE>(); txt += "\t" + p.getInfo<CL_PLATFORM_VENDOR>(); txt += "\t" + p.getInfo<CL_PLATFORM_VERSION>(); //txt += "\t" + p.getInfo<CL_PLATFORM_EXTENSIONS>(); output.write(txt); } //Get devices txt = "\n\t[Devices list]"; output.write(txt); txt = "platform_id\tdevice_id\tdevice_name\tdevice_vendor\tdevice_profile\tdevice_version\tdevice_globalmem\tdevice_localmem\tdevice_maxgroupsize\tdriver_version\topencl_c_version"; output.write(txt); for(size_t p = 0; p < platforms.size(); p++){ vector<cl::Device> devices; platforms[p].getDevices(CL_DEVICE_TYPE_ALL, &devices); for(size_t d = 0; d < devices.size(); d++){ cl::Device& device = devices[d]; txt = to_string(p)+"\t"+to_string(d); txt += "\t" + device.getInfo<CL_DEVICE_NAME>(); txt += "\t" + device.getInfo<CL_DEVICE_VENDOR>(); txt += "\t" + device.getInfo<CL_DEVICE_PROFILE>(); txt += "\t" + device.getInfo<CL_DEVICE_VERSION>(); txt += "\t" + to_string(device.getInfo<CL_DEVICE_GLOBAL_MEM_SIZE>())+"B"; txt += "\t" + to_string(device.getInfo<CL_DEVICE_LOCAL_MEM_SIZE>())+"B"; txt += "\t" + to_string(device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>()); txt += "\t" + device.getInfo<CL_DRIVER_VERSION>(); txt += "\t" + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>(); output.write(txt); } } } /* Les balises 'R"CLCODE(' et ')CLCODE' (du type R"NAME( ... )NAME") servent à définir un string litéral brut. C'est utile pour avoir un string sur plusieurs ligne, comme un code, et cela évite d'avoir à ouvrir puis fermer les guillemets à chaque ligne. */ string WorkerCL::kernel_cmp_2_contigs = R"CLCODE( kernel void cmp_2_contigs(global unsigned long *infos, global char *scores, global unsigned long *seqs_sizes, global char *ultraseq){ int seq1_id = get_global_id(0); int seq2_id = get_global_id(1); /* Old way: basic memory. Work //Get the position of the seqs in the ultraseq unsigned long seq1_begin = 0; unsigned long seq2_begin = 0; unsigned long i=0; while(i < seq1_id || i < seq2_id){ if(i < seq1_id){seq1_begin += seqs_sizes[i];} if(i < seq2_id){seq2_begin += seqs_sizes[i];} i++; } //Get the sizes and the end pos of the seqs unsigned long seq1_size = seqs_sizes[seq1_id]; unsigned long seq2_size = seqs_sizes[seq2_id]; unsigned long seq1_end= seq1_begin + seq1_size - 1; unsigned long seq2_end= seq2_begin + seq1_size - 1; //Test if same seq : =1 else =0 scores[seq1_id + infos[0]*seq2_id] = 0; if(seq1_size == seq2_size){ bool same = true; for(unsigned int i=0; i < seq1_size; i++){ if(ultraseq[seq1_begin+i] != ultraseq[seq2_begin+i]){ same = false; i = seq1_size; } } if(same){scores[seq1_id+infos[0]*seq2_id]=1;} } */ //Get the position of seqs and sizes global char* seq1_ptr = NULL; global char* seq2_ptr = NULL; //Calculate the begin for each item (the for boucle is on all contigs (infos[0]) but it's stop before) unsigned long start = 0; for(unsigned long i = 0; i < seq1_id; i++){start += seqs_sizes[i];} seq1_ptr = &ultraseq[start]; start = 0; for(unsigned long i = 0; i < seq2_id; i++){start += seqs_sizes[i];} seq2_ptr = &ultraseq[start]; //get sizes unsigned long seq1_size = seqs_sizes[seq1_id]; unsigned long seq2_size = seqs_sizes[seq2_id]; //Test: if same seq then =1 else =0 scores[seq1_id + infos[0]*seq2_id] = 0; if(seq1_size == seq2_size){ bool same=true; for(unsigned int i=0; i < seq1_size; i++){ if(seq1_ptr[i] != seq2_ptr[i]){ same = false; i = seq1_size; } } if(same){scores[seq1_id+infos[0]*seq2_id]=1;} } } )CLCODE"; <|endoftext|>
<commit_before>#pragma once #include <cstdint> namespace haste { using std::uint32_t; enum class entity_type : uint32_t { camera = 0, mesh = 1, light = 2, empty = 3 }; inline uint32_t encode_material(uint32_t material_id, entity_type type) { return material_id << 2 | uint32_t(type); } inline uint32_t decode_material(uint32_t material_id) { return material_id >> 2; } inline uint32_t pack_normal(vec3 n) { float x = clamp((n.x + 1.0f) * 0.5f, 0.f, 1.0f) * 65534.f; float y = clamp((n.y + 1.0f) * 0.5f, 0.f, 1.0f) * 32766.f; float z = n.z < 0.0f ? 0.0f : 1.0f; return uint32_t(x) << 16 | uint32_t(y) << 1 | uint32_t(z); } inline vec3 unpack_normal(uint32_t n) { float x = float(n >> 16) * 3.05185094e-05f - 1.0f; float y = float(n << 16 >> 17) * 6.10388817e-05f - 1.0f; float z = sqrt(1.0f - x * x - y * y) * (float(n & 1u) - 0.5f) * 2.0f; return vec3(x, y, z); } struct SurfacePoint { vec3 _position; vec3 gnormal; mat3 _tangent; uint32_t material_id = UINT32_MAX; SurfacePoint() = default; SurfacePoint(const vec3& position, const vec3& normal, const vec3& tangent, uint32_t material_id) { _position = position; _tangent[0] = normalize(cross(normal, tangent)); _tangent[1] = normal; _tangent[2] = tangent; material_id = material_id; } const vec3& position() const { return _position; } const vec3& normal() const { return _tangent[1]; } const vec3& tangent() const { return _tangent[2]; } const vec3& bitangent() const { return _tangent[0]; } const vec3 toWorld(const vec3& surface) const { return _tangent * surface; } const vec3 toSurface(const vec3& world) const { return world * _tangent; } uint32_t material_index() const { return material_id >> 2; } bool is_camera() const { return (material_id & 3u) == uint32_t(entity_type::camera); } bool is_mesh() const { return (material_id & 3u) == uint32_t(entity_type::mesh); } bool is_light() const { return (material_id & 3u) == uint32_t(entity_type::light); } bool is_present() const { return material_id != UINT32_MAX; } }; struct Edge { public: Edge(const SurfacePoint& fst, const SurfacePoint& snd, const vec3& omega) { distSqInv = 1.0f / distance2(fst.position(), snd.position()); fCosTheta = abs(dot(omega, snd.normal())); bCosTheta = abs(dot(omega, fst.normal())); fGeometry = distSqInv * fCosTheta; bGeometry = distSqInv * bCosTheta; } float distSqInv; float fCosTheta; float bCosTheta; float fGeometry; float bGeometry; }; } <commit_msg>Remove dead code from SurfacePoint.<commit_after>#pragma once #include <cstdint> namespace haste { using std::uint32_t; enum class entity_type : uint32_t { camera = 0, mesh = 1, light = 2, empty = 3 }; inline uint32_t encode_material(uint32_t material_id, entity_type type) { return material_id << 2 | uint32_t(type); } inline uint32_t decode_material(uint32_t material_id) { return material_id >> 2; } inline uint32_t pack_normal(vec3 n) { float x = clamp((n.x + 1.0f) * 0.5f, 0.f, 1.0f) * 65534.f; float y = clamp((n.y + 1.0f) * 0.5f, 0.f, 1.0f) * 32766.f; float z = n.z < 0.0f ? 0.0f : 1.0f; return uint32_t(x) << 16 | uint32_t(y) << 1 | uint32_t(z); } inline vec3 unpack_normal(uint32_t n) { float x = float(n >> 16) * 3.05185094e-05f - 1.0f; float y = float(n << 16 >> 17) * 6.10388817e-05f - 1.0f; float z = sqrt(1.0f - x * x - y * y) * (float(n & 1u) - 0.5f) * 2.0f; return vec3(x, y, z); } struct SurfacePoint { vec3 _position; vec3 gnormal; mat3 _tangent; uint32_t material_id = UINT32_MAX; SurfacePoint() = default; const vec3& position() const { return _position; } const vec3& normal() const { return _tangent[1]; } const vec3& tangent() const { return _tangent[2]; } const vec3& bitangent() const { return _tangent[0]; } const vec3 toWorld(const vec3& surface) const { return _tangent * surface; } const vec3 toSurface(const vec3& world) const { return world * _tangent; } uint32_t material_index() const { return material_id >> 2; } bool is_camera() const { return (material_id & 3u) == uint32_t(entity_type::camera); } bool is_mesh() const { return (material_id & 3u) == uint32_t(entity_type::mesh); } bool is_light() const { return (material_id & 3u) == uint32_t(entity_type::light); } bool is_present() const { return material_id != UINT32_MAX; } }; struct Edge { public: Edge(const SurfacePoint& fst, const SurfacePoint& snd, const vec3& omega) { distSqInv = 1.0f / distance2(fst.position(), snd.position()); fCosTheta = abs(dot(omega, snd.normal())); bCosTheta = abs(dot(omega, fst.normal())); fGeometry = distSqInv * fCosTheta; bGeometry = distSqInv * bCosTheta; } float distSqInv; float fCosTheta; float bCosTheta; float fGeometry; float bGeometry; }; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * 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.txt * * 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 "selxDisplacementFieldNiftiToItkImageSinkComponent.h" #include "selxCheckTemplateProperties.h" namespace selx { template< int Dimensionality, class TPixel > DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::DisplacementFieldNiftiToItkImageSinkComponent( const std::string & name, LoggerImpl & logger ) : Superclass( name, logger ), m_NetworkBuilderOutputImage( nullptr ), m_DisplacementFieldInterface( nullptr ), m_ImageDomainInterface( nullptr ) { m_MiniPipelineOutputImage = ItkDisplacementFieldType::New(); // this is just an empty image for we have a SmartPointer we can pass around downstream. The actual image data will be grafted into this image. m_ImportFilter = ImportFilterType::New(); } template< int Dimensionality, class TPixel > DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::~DisplacementFieldNiftiToItkImageSinkComponent() { } template< int Dimensionality, class TPixel > int DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename NiftiDisplacementFieldInterfaceType::Pointer other ) { // Store pointer to the m_WarpedImageInterface for getting the result image after in has been generated (registration). // TODO: sanity check that m_WarpedImageInterface was Null to detect if Set was called more than once erroneously. this->m_DisplacementFieldInterface = other; return 0; } template< int Dimensionality, class TPixel > int DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename ItkImageDomainInterfaceType::Pointer other ) { // Store pointer to the m_ImageDomainInterface for getting the result image after in has been generated (registration). // TODO: sanity check that m_ImageDomainInterface was Null to detect if Set was called more than once erroneously. m_MiniPipelineOutputImage->SetRegions( other->GetItkImageDomainFixed()->GetLargestPossibleRegion() ); //this->m_ImageDomainInterface = other; return 0; } template< int Dimensionality, class TPixel > void DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::SetMiniPipelineOutput( itk::DataObject::Pointer NetworkBuilderOutput ) { /** Tries to cast the NetworkBuilderOutput to an image (data object) and stores the result. * The resulting output image will be grafted into when the sink component is connected to an other component. * */ // /* this->m_NetworkBuilderOutputImage = dynamic_cast< ItkImageType * >(NetworkBuilderOutput.GetPointer()); if (this->m_NetworkBuilderOutputImage == nullptr) { throw std::runtime_error("DisplacementFieldNiftiToItkImageSinkComponent cannot cast the NetworkBuilder's Output to the required type"); } this->m_MiniPipelineOutputImage = this->m_NetworkBuilderOutputImage; */ } template< int Dimensionality, class TPixel > typename itk::DataObject::Pointer DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetMiniPipelineOutput() { return this->m_MiniPipelineOutputImage.GetPointer(); } template< int Dimensionality, class TPixel > typename AnyFileWriter::Pointer DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetOutputFileWriter() { // Instanstiate an image file writer, decorated such that it can be implicitly cast to an AnyFileWriterType return DecoratedWriterType::New().GetPointer(); } template< int Dimensionality, class TPixel > typename itk::DataObject::Pointer DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetInitializedOutput() { return ItkDisplacementFieldType::New().GetPointer(); } template< int Dimensionality, class TPixel > void DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Update() { auto displacementFieldNiftiImage = this->m_DisplacementFieldInterface->GetDisplacementFieldNiftiImage(); displacementFieldNiftiImage->scl_slope = -1; //auto region = m_MiniPipelineOutputImage->GetOutput()->GetRegion(); // auto other->GetItkImageDomainFixed()->GetLargestPossibleRegion() /*float *dispPtrX = static_cast<float *>(displacementFieldNiftiImage->data); float *dispPtrY = static_cast<float *>(&dispPtrX[displacementFieldNiftiImage->nvox]); float *dispPtrZ = static_cast<float *>(&dispPtrY[displacementFieldNiftiImage->nvox]); for (int v = 0; v < displacementFieldNiftiImage->nvox; v++) { dispPtrX[v] *= -1.f; dispPtrY[v] *= -1.f; } */ auto displacementFieldItkImage = NiftiToItkImage< ItkDisplacementFieldType, TPixel >::Convert( displacementFieldNiftiImage ); //auto displacementFieldItkImage = NiftiToItkImage< itk::Image< TPixel, Dimensionality >, TPixel >::Convert(displacementFieldNiftiImage); this->m_MiniPipelineOutputImage->Graft( displacementFieldItkImage ); } template< int Dimensionality, class TPixel > bool DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::MeetsCriterion( const ComponentBase::CriterionType & criterion ) { bool hasUndefinedCriteria( false ); bool meetsCriteria( false ); auto status = CheckTemplateProperties( this->TemplateProperties(), criterion ); if( status == CriterionStatus::Satisfied ) { return true; } else if( status == CriterionStatus::Failed ) { return false; } // else: CriterionStatus::Unknown return meetsCriteria; } } //end namespace selx <commit_msg>DOC: small comment on niftyreg displacement fields<commit_after>/*========================================================================= * * Copyright Leiden University Medical Center, Erasmus University Medical * Center and contributors * * 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.txt * * 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 "selxDisplacementFieldNiftiToItkImageSinkComponent.h" #include "selxCheckTemplateProperties.h" namespace selx { template< int Dimensionality, class TPixel > DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::DisplacementFieldNiftiToItkImageSinkComponent( const std::string & name, LoggerImpl & logger ) : Superclass( name, logger ), m_NetworkBuilderOutputImage( nullptr ), m_DisplacementFieldInterface( nullptr ), m_ImageDomainInterface( nullptr ) { m_MiniPipelineOutputImage = ItkDisplacementFieldType::New(); // this is just an empty image for we have a SmartPointer we can pass around downstream. The actual image data will be grafted into this image. m_ImportFilter = ImportFilterType::New(); } template< int Dimensionality, class TPixel > DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::~DisplacementFieldNiftiToItkImageSinkComponent() { } template< int Dimensionality, class TPixel > int DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename NiftiDisplacementFieldInterfaceType::Pointer other ) { // Store pointer to the m_WarpedImageInterface for getting the result image after in has been generated (registration). // TODO: sanity check that m_WarpedImageInterface was Null to detect if Set was called more than once erroneously. this->m_DisplacementFieldInterface = other; return 0; } template< int Dimensionality, class TPixel > int DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Accept( typename ItkImageDomainInterfaceType::Pointer other ) { // Store pointer to the m_ImageDomainInterface for getting the result image after in has been generated (registration). // TODO: sanity check that m_ImageDomainInterface was Null to detect if Set was called more than once erroneously. m_MiniPipelineOutputImage->SetRegions( other->GetItkImageDomainFixed()->GetLargestPossibleRegion() ); //this->m_ImageDomainInterface = other; return 0; } template< int Dimensionality, class TPixel > void DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::SetMiniPipelineOutput( itk::DataObject::Pointer NetworkBuilderOutput ) { /** Tries to cast the NetworkBuilderOutput to an image (data object) and stores the result. * The resulting output image will be grafted into when the sink component is connected to an other component. * */ // /* this->m_NetworkBuilderOutputImage = dynamic_cast< ItkImageType * >(NetworkBuilderOutput.GetPointer()); if (this->m_NetworkBuilderOutputImage == nullptr) { throw std::runtime_error("DisplacementFieldNiftiToItkImageSinkComponent cannot cast the NetworkBuilder's Output to the required type"); } this->m_MiniPipelineOutputImage = this->m_NetworkBuilderOutputImage; */ } template< int Dimensionality, class TPixel > typename itk::DataObject::Pointer DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetMiniPipelineOutput() { return this->m_MiniPipelineOutputImage.GetPointer(); } template< int Dimensionality, class TPixel > typename AnyFileWriter::Pointer DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetOutputFileWriter() { // Instanstiate an image file writer, decorated such that it can be implicitly cast to an AnyFileWriterType return DecoratedWriterType::New().GetPointer(); } template< int Dimensionality, class TPixel > typename itk::DataObject::Pointer DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::GetInitializedOutput() { return ItkDisplacementFieldType::New().GetPointer(); } template< int Dimensionality, class TPixel > void DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::Update() { auto displacementFieldNiftiImage = this->m_DisplacementFieldInterface->GetDisplacementFieldNiftiImage(); // For some reason the displacement vectors in niftyreg have opposite sign than in itk. A quick fix is to set the slope from 1 to -1. // TODO: 1) NiftiToItkImage should handle this generically for displacement fields. 2) nifti images can have an intent_code = DISPVECT, which seem applicable here. However, the intent_code = VECTOR, currently. displacementFieldNiftiImage->scl_slope = -1; auto displacementFieldItkImage = NiftiToItkImage< ItkDisplacementFieldType, TPixel >::Convert( displacementFieldNiftiImage ); this->m_MiniPipelineOutputImage->Graft( displacementFieldItkImage ); } template< int Dimensionality, class TPixel > bool DisplacementFieldNiftiToItkImageSinkComponent< Dimensionality, TPixel >::MeetsCriterion( const ComponentBase::CriterionType & criterion ) { bool hasUndefinedCriteria( false ); bool meetsCriteria( false ); auto status = CheckTemplateProperties( this->TemplateProperties(), criterion ); if( status == CriterionStatus::Satisfied ) { return true; } else if( status == CriterionStatus::Failed ) { return false; } // else: CriterionStatus::Unknown return meetsCriteria; } } //end namespace selx <|endoftext|>
<commit_before>/* Copyright 2016 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/distributed_runtime/rpc/grpc_tensor_coding.h" #include "grpcpp/support/byte_buffer.h" #include "grpcpp/support/slice.h" #include "absl/flags/flag.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/tensor_reference.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/io/proto_encode_helper.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/protobuf/worker.pb.h" // (Omitted internal-only flag) namespace tensorflow { namespace grpc { void EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto, ::grpc::ByteBuffer* result) { ::grpc::Slice slice(proto.ByteSizeLong()); proto.SerializeWithCachedSizesToArray( const_cast<uint8*>(reinterpret_cast<const uint8*>(slice.begin()))); ::grpc::ByteBuffer tmp(&slice, 1); result->Swap(&tmp); } // We generate a RecvTensorResponse protocol buffer encoding into "*result", // but where possible, we share the underlying Tensor buffer for "val", to // avoid an extra copy. // // We hand-encode the protocol buffer data in the following order, as follows: // // Let R be a RecvTensorResponse object we want to encode, logically // constructed by filling in data from "is_dead" and "val" and filling // in a few other fields as well. // // (Letters here are used in the code to refer back to which part of the // encoding the code is generating). // // A: <protocol buffer encoding of fields except R.tensor()> // B1: <tag encoding for RecvTensorResponse::tensor> // B2: <varint32 length of R.tensor() sub message> // C: <protocol buffer encoding of R.tensor() except for // R.tensor().tensor_content()> // D1: <tag encoding for TensorProto::tensor_content> // D2: <varint32 length of R.tensor().tensor_content() data> // E: <actual data for val's representation> // // If the tensor data is up to "kLargeTensorBytes", then A // through E will all be encoded into "*result" in a single grpc::Slice. // // If the tensor data is larger than "kLargeTensorBytes", then A through // D2 will be encoded in one grpc::Slice, and E will be encoded in a second // grpc::Slice that points to the backing store for the tensor data, to avoid // copying the tensor data (and the grpc::Slice setup will be arrange so as // to dereference the underlying tensor data buffer when it is no longer // needed in the "*result" ByteBuffer). static int VarLengthEncodingSize(uint32 tag, size_t bytes) { return core::VarintLength(tag << 3) + core::VarintLength(bytes) + bytes; } // Returns an upper bound in bytes of the protocol buffer encoding of // the "skeleton" of "val" (all the data needed for dtype and the shape, // but not the actual contents of "val"). static int SkeletonEncodingSizeUpperBound(const Tensor& val) { static const int kVarintMax64 = 10; // Max length of varint64 encoding const int ndims = val.shape().dims(); return (2 * kVarintMax64) + // dtype (ndims * (4 * kVarintMax64)); // Shape: 4 varints per dim } // Encode the skeleton for "val" (the encoded TensorProto contents // (dtype and shape, but not the actual data) into "*e". The backing // store for "*e" must be of appropriate size to hold this encoding. static void EncodeSkeleton(const Tensor& val, io::ProtoEncodeHelper* e) { // Encode val.dtype() e->WriteUint64(TensorProto::kDtypeFieldNumber, val.dtype()); // Compute length of val.shape() proto encoding const int ndims = val.shape().dims(); int tensor_shape_bytes = 0; for (int d = 0; d < ndims; d++) { int64 dim_size = val.shape().dim_size(d); tensor_shape_bytes += 2 + // TensorShapeProto dim tag + varintlength of submessage 1 + // TensorShapeProto_Dim::kSizeFieldNumber core::VarintLength(dim_size); } if (tensor_shape_bytes > 0) { e->WriteVarlengthBeginning(TensorProto::kTensorShapeFieldNumber, tensor_shape_bytes); // Encode val.shape() for (int d = 0; d < ndims; d++) { int64 dim_size = val.shape().dim_size(d); int64 dim_varlen = 1 + // TensorShapeProto_Dim::kSizeFieldNumber core::VarintLength(dim_size); e->WriteVarlengthBeginning(TensorShapeProto::kDimFieldNumber, dim_varlen); e->WriteUint64(TensorShapeProto_Dim::kSizeFieldNumber, dim_size); } } #ifndef NDEBUG { // Debug-mode only check to make sure the encoding above is // identical to the auto-generated protocol buffer encoding. TensorProto skeleton; skeleton.set_dtype(val.dtype()); val.shape().AsProto(skeleton.mutable_tensor_shape()); string tensor_except_contents; // tensor() field except contents skeleton.AppendToString(&tensor_except_contents); TensorProto skeleton2; skeleton2.ParseFromString(string(e->data(), e->size())); string out; skeleton.AppendToString(&out); DCHECK_EQ(tensor_except_contents, out) << skeleton.DebugString() << " vs\n" << skeleton2.DebugString(); } #endif } void EncodeTensorToByteBuffer(bool is_dead, const Tensor& val, bool require_ack, ::grpc::ByteBuffer* result) { const int kLargeTensorBytes = 1024; const int64 kProtoBufLimitBytes = 1LL << 31; if (val.TotalBytes() > kProtoBufLimitBytes) { size_t exceeded_bytes = val.TotalBytes() - kProtoBufLimitBytes; LOG(FATAL) << "Cannot encode a Tensor that exceeds the 2GB protobuf limit. " "Exceeded bytes: " << exceeded_bytes; } RecvTensorResponse response; if (is_dead) { response.set_is_dead(is_dead); } response.set_require_ack(require_ack); response.set_send_start_micros(Env::Default()->NowMicros()); if (!DataTypeCanUseMemcpy(val.dtype())) { // Straightforward but slow path for complicated kinds of tensor data // TODO(jeff,sanjay): If this becomes an issue, we could // go directly from val -> ByteBuffer, with some effort. val.AsProtoTensorContent(response.mutable_tensor()); // Encode full protocol buffer to a ByteBuffer EncodeRecvTensorResponseToByteBuffer(response, result); } else { // skeleton is the encoded TensorProto contents (dtype and shape), but // not the actual data gtl::InlinedVector<char, 128> skeleton(SkeletonEncodingSizeUpperBound(val)); io::ProtoEncodeHelper e_skeleton(skeleton.data(), skeleton.size()); EncodeSkeleton(val, &e_skeleton); StringPiece tdata = val.tensor_data(); uint32 overall_tensor_proto_bytesize = (e_skeleton.size() + VarLengthEncodingSize(TensorProto::kTensorContentFieldNumber, tdata.size())); string header; // All of RecvTensorResponse except the tensor() field response.AppendToString(&header); size_t expected_size = (header.size() + VarLengthEncodingSize(RecvTensorResponse::kTensorFieldNumber, overall_tensor_proto_bytesize)); // If "share_tensor_slice_memory == false", we copy the tensor data to // the end of the buffer we are preparing that holds the rest of the // RecvTensorResponse protocol buffer. // // If "share_tensor_slice_memory == true", we arrange to share the // backing store of the data by creating a slice that also points to the // backing store, with appropriate reference counts to keep the // backing store alive as needed. // // We enable this behavior if the tensor is large. bool share_tensor_slice_memory = (tdata.size() > kLargeTensorBytes); // (Omitted internal-only conditional) size_t encoder_size = expected_size - tdata.size(); // Encode all but the actual "tdata", but including the tag and // varlength header for the "tdata" gtl::InlinedVector<char, 1024> space(encoder_size); io::ProtoEncodeHelper e(space.data(), space.size()); // (A) e.WriteRawBytes(header); // (B1) & (B2) e.WriteVarlengthBeginning(RecvTensorResponse::kTensorFieldNumber, overall_tensor_proto_bytesize); // (C) e.WriteRawBytes(StringPiece(e_skeleton.data(), e_skeleton.size())); // (D1) & (D2) e.WriteVarlengthBeginning(TensorProto::kTensorContentFieldNumber, tdata.size()); // All but the tensor backing store are serialized now // Now allocate memory and put into the ByteBuffer ::grpc::Slice slices[2]; int num_slices = 0; { size_t slice_len = e.size() + (share_tensor_slice_memory ? 0 : tdata.size()); slices[0] = ::grpc::Slice(slice_len); memcpy(const_cast<uint8_t*>(slices[0].begin()), e.data(), e.size()); if (!share_tensor_slice_memory) { // (E) memcpy(const_cast<uint8_t*>(slices[0].begin()) + e.size(), tdata.data(), tdata.size()); } num_slices += 1; } if (share_tensor_slice_memory) { // (E) Encode tensor data, but by sharing backing store const TensorBuffer* buf = DMAHelper::buffer(&val); buf->Ref(); slices[1] = ::grpc::Slice( const_cast<void*>(static_cast<const void*>(tdata.data())), tdata.size(), [](void* backing) { static_cast<TensorBuffer*>(backing)->Unref(); }, const_cast<TensorBuffer*>(buf)); num_slices += 1; } size_t total_bytes = 0; for (int i = 0; i < num_slices; i++) { total_bytes += slices[i].size(); } CHECK_EQ(total_bytes, expected_size); ::grpc::ByteBuffer tmp(&slices[0], num_slices); result->Swap(&tmp); } } } // namespace grpc } // namespace tensorflow <commit_msg>Remove unused flag<commit_after>/* Copyright 2016 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/distributed_runtime/rpc/grpc_tensor_coding.h" #include "grpcpp/support/byte_buffer.h" #include "grpcpp/support/slice.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/tensor_reference.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/lib/io/proto_encode_helper.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/protobuf/worker.pb.h" namespace tensorflow { namespace grpc { void EncodeRecvTensorResponseToByteBuffer(const RecvTensorResponse& proto, ::grpc::ByteBuffer* result) { ::grpc::Slice slice(proto.ByteSizeLong()); proto.SerializeWithCachedSizesToArray( const_cast<uint8*>(reinterpret_cast<const uint8*>(slice.begin()))); ::grpc::ByteBuffer tmp(&slice, 1); result->Swap(&tmp); } // We generate a RecvTensorResponse protocol buffer encoding into "*result", // but where possible, we share the underlying Tensor buffer for "val", to // avoid an extra copy. // // We hand-encode the protocol buffer data in the following order, as follows: // // Let R be a RecvTensorResponse object we want to encode, logically // constructed by filling in data from "is_dead" and "val" and filling // in a few other fields as well. // // (Letters here are used in the code to refer back to which part of the // encoding the code is generating). // // A: <protocol buffer encoding of fields except R.tensor()> // B1: <tag encoding for RecvTensorResponse::tensor> // B2: <varint32 length of R.tensor() sub message> // C: <protocol buffer encoding of R.tensor() except for // R.tensor().tensor_content()> // D1: <tag encoding for TensorProto::tensor_content> // D2: <varint32 length of R.tensor().tensor_content() data> // E: <actual data for val's representation> // // If the tensor data is up to "kLargeTensorBytes", then A // through E will all be encoded into "*result" in a single grpc::Slice. // // If the tensor data is larger than "kLargeTensorBytes", then A through // D2 will be encoded in one grpc::Slice, and E will be encoded in a second // grpc::Slice that points to the backing store for the tensor data, to avoid // copying the tensor data (and the grpc::Slice setup will be arrange so as // to dereference the underlying tensor data buffer when it is no longer // needed in the "*result" ByteBuffer). static int VarLengthEncodingSize(uint32 tag, size_t bytes) { return core::VarintLength(tag << 3) + core::VarintLength(bytes) + bytes; } // Returns an upper bound in bytes of the protocol buffer encoding of // the "skeleton" of "val" (all the data needed for dtype and the shape, // but not the actual contents of "val"). static int SkeletonEncodingSizeUpperBound(const Tensor& val) { static const int kVarintMax64 = 10; // Max length of varint64 encoding const int ndims = val.shape().dims(); return (2 * kVarintMax64) + // dtype (ndims * (4 * kVarintMax64)); // Shape: 4 varints per dim } // Encode the skeleton for "val" (the encoded TensorProto contents // (dtype and shape, but not the actual data) into "*e". The backing // store for "*e" must be of appropriate size to hold this encoding. static void EncodeSkeleton(const Tensor& val, io::ProtoEncodeHelper* e) { // Encode val.dtype() e->WriteUint64(TensorProto::kDtypeFieldNumber, val.dtype()); // Compute length of val.shape() proto encoding const int ndims = val.shape().dims(); int tensor_shape_bytes = 0; for (int d = 0; d < ndims; d++) { int64 dim_size = val.shape().dim_size(d); tensor_shape_bytes += 2 + // TensorShapeProto dim tag + varintlength of submessage 1 + // TensorShapeProto_Dim::kSizeFieldNumber core::VarintLength(dim_size); } if (tensor_shape_bytes > 0) { e->WriteVarlengthBeginning(TensorProto::kTensorShapeFieldNumber, tensor_shape_bytes); // Encode val.shape() for (int d = 0; d < ndims; d++) { int64 dim_size = val.shape().dim_size(d); int64 dim_varlen = 1 + // TensorShapeProto_Dim::kSizeFieldNumber core::VarintLength(dim_size); e->WriteVarlengthBeginning(TensorShapeProto::kDimFieldNumber, dim_varlen); e->WriteUint64(TensorShapeProto_Dim::kSizeFieldNumber, dim_size); } } #ifndef NDEBUG { // Debug-mode only check to make sure the encoding above is // identical to the auto-generated protocol buffer encoding. TensorProto skeleton; skeleton.set_dtype(val.dtype()); val.shape().AsProto(skeleton.mutable_tensor_shape()); string tensor_except_contents; // tensor() field except contents skeleton.AppendToString(&tensor_except_contents); TensorProto skeleton2; skeleton2.ParseFromString(string(e->data(), e->size())); string out; skeleton.AppendToString(&out); DCHECK_EQ(tensor_except_contents, out) << skeleton.DebugString() << " vs\n" << skeleton2.DebugString(); } #endif } void EncodeTensorToByteBuffer(bool is_dead, const Tensor& val, bool require_ack, ::grpc::ByteBuffer* result) { const int kLargeTensorBytes = 1024; const int64 kProtoBufLimitBytes = 1LL << 31; if (val.TotalBytes() > kProtoBufLimitBytes) { size_t exceeded_bytes = val.TotalBytes() - kProtoBufLimitBytes; LOG(FATAL) << "Cannot encode a Tensor that exceeds the 2GB protobuf limit. " "Exceeded bytes: " << exceeded_bytes; } RecvTensorResponse response; if (is_dead) { response.set_is_dead(is_dead); } response.set_require_ack(require_ack); response.set_send_start_micros(Env::Default()->NowMicros()); if (!DataTypeCanUseMemcpy(val.dtype())) { // Straightforward but slow path for complicated kinds of tensor data // TODO(jeff,sanjay): If this becomes an issue, we could // go directly from val -> ByteBuffer, with some effort. val.AsProtoTensorContent(response.mutable_tensor()); // Encode full protocol buffer to a ByteBuffer EncodeRecvTensorResponseToByteBuffer(response, result); } else { // skeleton is the encoded TensorProto contents (dtype and shape), but // not the actual data gtl::InlinedVector<char, 128> skeleton(SkeletonEncodingSizeUpperBound(val)); io::ProtoEncodeHelper e_skeleton(skeleton.data(), skeleton.size()); EncodeSkeleton(val, &e_skeleton); StringPiece tdata = val.tensor_data(); uint32 overall_tensor_proto_bytesize = (e_skeleton.size() + VarLengthEncodingSize(TensorProto::kTensorContentFieldNumber, tdata.size())); string header; // All of RecvTensorResponse except the tensor() field response.AppendToString(&header); size_t expected_size = (header.size() + VarLengthEncodingSize(RecvTensorResponse::kTensorFieldNumber, overall_tensor_proto_bytesize)); // If "share_tensor_slice_memory == false", we copy the tensor data to // the end of the buffer we are preparing that holds the rest of the // RecvTensorResponse protocol buffer. // // If "share_tensor_slice_memory == true", we arrange to share the // backing store of the data by creating a slice that also points to the // backing store, with appropriate reference counts to keep the // backing store alive as needed. // // We enable this behavior if the tensor is large. bool share_tensor_slice_memory = (tdata.size() > kLargeTensorBytes); size_t encoder_size = expected_size - tdata.size(); // Encode all but the actual "tdata", but including the tag and // varlength header for the "tdata" gtl::InlinedVector<char, 1024> space(encoder_size); io::ProtoEncodeHelper e(space.data(), space.size()); // (A) e.WriteRawBytes(header); // (B1) & (B2) e.WriteVarlengthBeginning(RecvTensorResponse::kTensorFieldNumber, overall_tensor_proto_bytesize); // (C) e.WriteRawBytes(StringPiece(e_skeleton.data(), e_skeleton.size())); // (D1) & (D2) e.WriteVarlengthBeginning(TensorProto::kTensorContentFieldNumber, tdata.size()); // All but the tensor backing store are serialized now // Now allocate memory and put into the ByteBuffer ::grpc::Slice slices[2]; int num_slices = 0; { size_t slice_len = e.size() + (share_tensor_slice_memory ? 0 : tdata.size()); slices[0] = ::grpc::Slice(slice_len); memcpy(const_cast<uint8_t*>(slices[0].begin()), e.data(), e.size()); if (!share_tensor_slice_memory) { // (E) memcpy(const_cast<uint8_t*>(slices[0].begin()) + e.size(), tdata.data(), tdata.size()); } num_slices += 1; } if (share_tensor_slice_memory) { // (E) Encode tensor data, but by sharing backing store const TensorBuffer* buf = DMAHelper::buffer(&val); buf->Ref(); slices[1] = ::grpc::Slice( const_cast<void*>(static_cast<const void*>(tdata.data())), tdata.size(), [](void* backing) { static_cast<TensorBuffer*>(backing)->Unref(); }, const_cast<TensorBuffer*>(buf)); num_slices += 1; } size_t total_bytes = 0; for (int i = 0; i < num_slices; i++) { total_bytes += slices[i].size(); } CHECK_EQ(total_bytes, expected_size); ::grpc::ByteBuffer tmp(&slices[0], num_slices); result->Swap(&tmp); } } } // namespace grpc } // namespace tensorflow <|endoftext|>
<commit_before>// -------------------------------------------------------------------------------------- // File: bspline_field.cxx // Date: Mar 5, 2014 // Author: [email protected] (Oscar Esteban) // Version: 1.0 beta // License: GPLv3 - 29 June 2007 // Short Summary: // -------------------------------------------------------------------------------------- // #include "bspline_field.h" #include <vnl/vnl_matrix.h> #include <vnl/vnl_diag_matrix.h> #include <sstream> int main(int argc, char *argv[]) { std::string outPrefix = ""; std::string maskfile; std::vector< std::string > fixedImageNames, movingSurfaceNames,coefficientImageNames; std::vector<size_t> grid_size; bpo::options_description all_desc("Usage"); all_desc.add_options() ("help,h", "show help message") ("coeff-images,C", bpo::value < std::vector<std::string> > (&coefficientImageNames )->multitoken(), "coefficient image(s)" ) ("images,I", bpo::value < std::vector<std::string> > (&fixedImageNames)->multitoken()->required(), "fixed image file") ("surfaces,S", bpo::value < std::vector<std::string> > (&movingSurfaceNames)->multitoken(), "moving image file") ("mask,M", bpo::value< std::string >(&maskfile), "mask file" ) ("output-prefix,o", bpo::value < std::string > (&outPrefix), "prefix for output files") ("num-threads", bpo::value < unsigned int >()->default_value(NUM_THREADS), "use num-threads") ("grid-size,g", bpo::value< std::vector<size_t> >(&grid_size)->multitoken(), "size of grid of bspline control points (default is 10x10x10)") ("mask-inputs", bpo::bool_switch(), "use deformed mask to filter input files"); bpo::variables_map vm; bpo::store( bpo::parse_command_line( argc, argv, all_desc ), vm); bpo::notify(vm); if (vm.count("help") || vm.size() == 0 ) { std::cout << all_desc << std::endl; return 1; } ReaderPointer readref = ReaderType::New(); readref->SetFileName( fixedImageNames[0] ); readref->Update(); ChannelPointer ref = readref->GetOutput(); typename ChannelType::DirectionType ref_dir(ref->GetDirection()); typename ChannelType::PointType ref_orig = ref->GetOrigin(); typename ChannelType::DirectionType itk; itk.SetIdentity(); itk(0,0)=-1.0; itk(1,1)=-1.0; typename ChannelType::DirectionType int_dir(itk * ref_dir); typename ChannelType::PointType int_orig( itk * ref_orig ); ref->SetDirection( int_dir ); ref->SetOrigin( int_orig ); typename CoefficientsType::SizeType size; typename CoefficientsType::SpacingType spacing; size.Fill(10); CoefficientsImageArray coeffs; TPointer transform = Transform::New(); #ifndef NDEBUG transform->SetNumberOfThreads( 2 ); #endif if (vm.count("coeff-images")) { std::cout << "coefficient images mode not implemented" << std::endl; // set size return 0; } else { if( vm.count("grid-size") ){ if( grid_size.size() == 1 ) { size.Fill( grid_size[0] ); } else if ( grid_size.size() == DIMENSION ) { for( size_t i = 0; i < DIMENSION; i++) size[i] = grid_size[i]; } else { std::cout << "error with grid size" << std::endl; return 1; } } transform->SetControlPointsSize( size ); transform->SetPhysicalDomainInformation( ref ); transform->SetOutputReference( ref ); transform->UpdateField(); coeffs = transform->GetCoefficientsImages(); spacing = coeffs[0]->GetSpacing(); size_t numPix = coeffs[0]->GetLargestPossibleRegion().GetNumberOfPixels(); typename CoefficientsType::RegionType region; typename CoefficientsType::IndexType start; typename CoefficientsType::SizeType regionSize; for( size_t i = 0; i<DIMENSION; i++ ) { start[i] = static_cast<size_t>( floor( size[i] * 0.35 + 0.5f ) ) -1; regionSize[i] = size[i] - 2.0 * start[i]; } region.SetIndex( start ); region.SetSize( regionSize ); for( size_t i = 0; i< DIMENSION; i++) { RandomIterator rndit( coeffs[i], region ); #ifdef NDEBUG rndit.ReinitializeSeed(); #endif rndit.SetNumberOfSamples( static_cast<size_t>( floor( numPix * 0.08 + 0.5f ) ) ); for(rndit.GoToBegin(); !rndit.IsAtEnd(); ++rndit){ float r = -1.0 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/2.0)); rndit.Set( r ); } SigmaArrayType sigma; sigma.Fill(12.0); SmoothingFilterPointer s = SmoothingFilterType::New(); s->SetInput( coeffs[i] ); s->SetSigmaArray( sigma ); s->Update(); coeffs[i] = s->GetOutput(); ScalarType *buff = coeffs[i]->GetBufferPointer(); std::vector< ScalarType > sample; for( size_t j = 0; j < numPix; j++ ) { sample.push_back( *(buff + j) ); } std::sort( sample.begin(), sample.end() ); SubtractPointer sub = SubtractFilter::New(); sub->SetInput1( coeffs[i] ); sub->SetConstant( sample[ static_cast<size_t>( floor( 0.5 * numPix + 0.5f ) ) ] ); sub->Update(); coeffs[i] = sub->GetOutput(); MaxCalcPointer max = MaxCalc::New(); max->SetImage( coeffs[i] ); max->Compute(); float immax = max->GetMaximum(); if ( fabs( max->GetMinimum() ) > fabs(immax) ) { immax = fabs( max->GetMinimum() ); } float scale = (spacing[i] * 0.35) / immax; MultiplyPointer m = MultiplyFilter::New(); m->SetInput1( coeffs[i] ); m->SetConstant( scale ); m->Update(); coeffs[i] = m->GetOutput(); CoefficientsWriterPointer w = CoefficientsWriterType::New(); std::stringstream ss; ss << outPrefix << "_coeffs_" << i << ".nii.gz"; w->SetFileName( ss.str().c_str() ); w->SetInput( coeffs[i] ); w->Update(); } } // Set coefficients transform->SetCoefficientsImages( coeffs ); transform->UpdateField(); typename ComponentsWriter::Pointer f = ComponentsWriter::New(); std::stringstream ss; ss << outPrefix << "_field"; f->SetFileName( ss.str().c_str() ); f->SetInput( transform->GetField() ); f->Update(); transform->Interpolate(); typename FieldType::Pointer field = transform->GetDisplacementField(); typename FieldWriter::Pointer ff = FieldWriter::New(); ff->SetInput( field ); ff->SetFileName( (outPrefix + "_dispfield.nii.gz").c_str() ); ff->Update(); // Read and transform mask, if present MaskPointer mask; if (vm.count( "mask" ) ) { typename ReaderType::Pointer rmask = ReaderType::New(); rmask->SetFileName( maskfile ); rmask->Update(); typename ChannelType::Pointer im = rmask->GetOutput(); im->SetDirection( int_dir ); im->SetOrigin( int_orig ); typename Binarize::Pointer bin = Binarize::New(); bin->SetInput( im ); bin->SetLowerThreshold( 0.01 ); bin->SetOutsideValue( 0 ); bin->SetInsideValue( 1 ); bin->Update(); WarpMaskFilterPointer wrp = WarpMaskFilter::New(); wrp->SetInterpolator( WarpMaskInterpolator::New() ); wrp->SetOutputParametersFromImage( bin->GetOutput() ); wrp->SetInput( bin->GetOutput() ); wrp->SetDisplacementField( field ); wrp->Update(); mask = wrp->GetOutput(); mask->SetDirection( ref_dir ); mask->SetOrigin( ref_orig ); typename MaskWriter::Pointer wm = MaskWriter::New(); wm->SetInput( mask ); wm->SetFileName( (outPrefix + "_mask_warped.nii.gz").c_str() ); wm->Update(); } // Read and transform images if present for( size_t i = 0; i<fixedImageNames.size(); i++) { std::stringstream ss; typename WriterType::Pointer w = WriterType::New(); typename ReaderType::Pointer r = ReaderType::New(); r->SetFileName( fixedImageNames[i] ); r->Update(); typename ChannelType::Pointer im = r->GetOutput(); im->SetDirection( int_dir ); im->SetOrigin( int_orig ); WarpFilterPointer wrp = WarpFilter::New(); wrp->SetInterpolator( WarpInterpolator::New() ); wrp->SetOutputParametersFromImage( im ); wrp->SetInput( im ); wrp->SetDisplacementField( field ); wrp->Update(); ThresholdPointer th = ThresholdFilter::New(); th->SetInput( wrp->GetOutput() ); th->ThresholdBelow( 0.0 ); th->SetOutsideValue( 0.0 ); th->Update(); typename ChannelType::Pointer im_wrp = th->GetOutput(); im_wrp->SetDirection( ref_dir ); im_wrp->SetOrigin( ref_orig ); if (mask.IsNotNull() && vm.count("mask-inputs")) { typename MaskFilter::Pointer mm = MaskFilter::New(); mm->SetMaskImage( mask ); mm->SetInput( im_wrp ); mm->Update(); im_wrp = mm->GetOutput(); } ss.str(""); ss << outPrefix << "_warped_" << i << ".nii.gz"; w->SetInput( im_wrp ); w->SetFileName( ss.str().c_str() ); w->Update(); } // Warp surfaces -------------------------------------------------- DisplacementFieldTransformPointer tf_inv = DisplacementFieldTransformType::New(); tf_inv->SetDisplacementField( transform->GetInverseDisplacementField() ); for( size_t i = 0; i<movingSurfaceNames.size(); i++){ MeshReaderPointer r = MeshReaderType::New(); r->SetFileName( movingSurfaceNames[i] ); r->Update(); MeshPointer mesh = r->GetOutput(); PointsIterator p_it = mesh->GetPoints()->Begin(); PointsIterator p_end = mesh->GetPoints()->End(); MeshPointType p; while ( p_it!=p_end ) { p = p_it.Value(); p_it.Value() = tf_inv->TransformPoint( p ); ++p_it; } MeshWriterPointer wmesh = MeshWriterType::New(); ss.str(""); ss << outPrefix << "_warped_" << i << ".vtk"; wmesh->SetFileName( ss.str().c_str() ); wmesh->SetInput( mesh ); wmesh->Update(); } } <commit_msg>A working workflow with transforms<commit_after>// -------------------------------------------------------------------------------------- // File: bspline_field.cxx // Date: Mar 5, 2014 // Author: [email protected] (Oscar Esteban) // Version: 1.0 beta // License: GPLv3 - 29 June 2007 // Short Summary: // -------------------------------------------------------------------------------------- // #include "bspline_field.h" #include <vnl/vnl_matrix.h> #include <vnl/vnl_diag_matrix.h> #include <sstream> int main(int argc, char *argv[]) { std::string outPrefix = ""; std::string maskfile; std::vector< std::string > fixedImageNames, movingSurfaceNames,coefficientImageNames; std::vector<size_t> grid_size; bpo::options_description all_desc("Usage"); all_desc.add_options() ("help,h", "show help message") ("coeff-images,C", bpo::value < std::vector<std::string> > (&coefficientImageNames )->multitoken(), "coefficient image(s)" ) ("images,I", bpo::value < std::vector<std::string> > (&fixedImageNames)->multitoken()->required(), "fixed image file") ("surfaces,S", bpo::value < std::vector<std::string> > (&movingSurfaceNames)->multitoken(), "moving image file") ("mask,M", bpo::value< std::string >(&maskfile), "mask file" ) ("output-prefix,o", bpo::value < std::string > (&outPrefix), "prefix for output files") ("num-threads", bpo::value < unsigned int >()->default_value(NUM_THREADS), "use num-threads") ("grid-size,g", bpo::value< std::vector<size_t> >(&grid_size)->multitoken(), "size of grid of bspline control points (default is 10x10x10)") ("mask-inputs", bpo::bool_switch(), "use deformed mask to filter input files"); bpo::variables_map vm; try { bpo::store( bpo::parse_command_line( argc, argv, all_desc ), vm); if (vm.count("help")) { std::cout << all_desc << std::endl; return 1; } bpo::notify(vm); } catch ( bpo::error& e ) { std::cerr << "Error: " << e.what() << std::endl << std::endl; std::cerr << all_desc << std::endl; return 1; } ReaderPointer readref = ReaderType::New(); readref->SetFileName( fixedImageNames[0] ); readref->Update(); ChannelPointer ref = readref->GetOutput(); typename ChannelType::DirectionType ref_dir(ref->GetDirection()); typename ChannelType::PointType ref_orig = ref->GetOrigin(); typename ChannelType::DirectionType itk; itk.SetIdentity(); itk(0,0)=-1.0; itk(1,1)=-1.0; typename ChannelType::DirectionType int_dir(itk * ref_dir); typename ChannelType::PointType int_orig( itk * ref_orig ); ref->SetDirection( int_dir ); ref->SetOrigin( int_orig ); typename CoefficientsType::SizeType size; typename CoefficientsType::SpacingType spacing; size.Fill(10); CoefficientsImageArray coeffs; TPointer transform = Transform::New(); #ifndef NDEBUG transform->SetNumberOfThreads( 2 ); #endif if (vm.count("coeff-images")) { std::cout << "coefficient images mode not implemented" << std::endl; // set size return 0; } else { if( vm.count("grid-size") ){ if( grid_size.size() == 1 ) { size.Fill( grid_size[0] ); } else if ( grid_size.size() == DIMENSION ) { for( size_t i = 0; i < DIMENSION; i++) size[i] = grid_size[i]; } else { std::cout << "error with grid size" << std::endl; return 1; } } transform->SetControlPointsSize( size ); transform->SetPhysicalDomainInformation( ref ); transform->SetOutputReference( ref ); transform->UpdateField(); coeffs = transform->GetCoefficientsImages(); spacing = coeffs[0]->GetSpacing(); size_t numPix = coeffs[0]->GetLargestPossibleRegion().GetNumberOfPixels(); typename CoefficientsType::RegionType region; typename CoefficientsType::IndexType start; typename CoefficientsType::SizeType regionSize; for( size_t i = 0; i<DIMENSION; i++ ) { start[i] = static_cast<size_t>( floor( size[i] * 0.35 + 0.5f ) ) -1; regionSize[i] = size[i] - 2.0 * start[i]; } region.SetIndex( start ); region.SetSize( regionSize ); for( size_t i = 0; i< DIMENSION; i++) { RandomIterator rndit( coeffs[i], region ); #ifdef NDEBUG rndit.ReinitializeSeed(); #endif rndit.SetNumberOfSamples( static_cast<size_t>( floor( numPix * 0.08 + 0.5f ) ) ); for(rndit.GoToBegin(); !rndit.IsAtEnd(); ++rndit){ float r = -1.0 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/2.0)); rndit.Set( r ); } SigmaArrayType sigma; sigma.Fill(12.0); SmoothingFilterPointer s = SmoothingFilterType::New(); s->SetInput( coeffs[i] ); s->SetSigmaArray( sigma ); s->Update(); coeffs[i] = s->GetOutput(); ScalarType *buff = coeffs[i]->GetBufferPointer(); std::vector< ScalarType > sample; for( size_t j = 0; j < numPix; j++ ) { sample.push_back( *(buff + j) ); } std::sort( sample.begin(), sample.end() ); SubtractPointer sub = SubtractFilter::New(); sub->SetInput1( coeffs[i] ); sub->SetConstant( sample[ static_cast<size_t>( floor( 0.5 * numPix + 0.5f ) ) ] ); sub->Update(); coeffs[i] = sub->GetOutput(); MaxCalcPointer max = MaxCalc::New(); max->SetImage( coeffs[i] ); max->Compute(); float immax = max->GetMaximum(); if ( fabs( max->GetMinimum() ) > fabs(immax) ) { immax = fabs( max->GetMinimum() ); } float scale = (spacing[i] * 0.35) / immax; MultiplyPointer m = MultiplyFilter::New(); m->SetInput1( coeffs[i] ); m->SetConstant( scale ); m->Update(); coeffs[i] = m->GetOutput(); CoefficientsWriterPointer w = CoefficientsWriterType::New(); std::stringstream ss; ss << outPrefix << "_coeffs_" << i << ".nii.gz"; w->SetFileName( ss.str().c_str() ); w->SetInput( coeffs[i] ); w->Update(); } } // Set coefficients transform->SetCoefficientsImages( coeffs ); transform->UpdateField(); typename ComponentsWriter::Pointer f = ComponentsWriter::New(); std::stringstream ss; ss << outPrefix << "_field"; f->SetFileName( ss.str().c_str() ); f->SetInput( transform->GetField() ); f->Update(); transform->Interpolate(); typename FieldType::Pointer field = transform->GetDisplacementField(); typename FieldWriter::Pointer ff = FieldWriter::New(); ff->SetInput( field ); ff->SetFileName( (outPrefix + "_dispfield.nii.gz").c_str() ); ff->Update(); // Read and transform mask, if present MaskPointer mask; if (vm.count( "mask" ) ) { typename ReaderType::Pointer rmask = ReaderType::New(); rmask->SetFileName( maskfile ); rmask->Update(); typename ChannelType::Pointer im = rmask->GetOutput(); im->SetDirection( int_dir ); im->SetOrigin( int_orig ); typename Binarize::Pointer bin = Binarize::New(); bin->SetInput( im ); bin->SetLowerThreshold( 0.01 ); bin->SetOutsideValue( 0 ); bin->SetInsideValue( 1 ); bin->Update(); WarpMaskFilterPointer wrp = WarpMaskFilter::New(); wrp->SetInterpolator( WarpMaskInterpolator::New() ); wrp->SetOutputParametersFromImage( bin->GetOutput() ); wrp->SetInput( bin->GetOutput() ); wrp->SetDisplacementField( field ); wrp->Update(); mask = wrp->GetOutput(); mask->SetDirection( ref_dir ); mask->SetOrigin( ref_orig ); typename MaskWriter::Pointer wm = MaskWriter::New(); wm->SetInput( mask ); wm->SetFileName( (outPrefix + "_mask_warped.nii.gz").c_str() ); wm->Update(); } // Read and transform images if present for( size_t i = 0; i<fixedImageNames.size(); i++) { std::stringstream ss; typename WriterType::Pointer w = WriterType::New(); typename ReaderType::Pointer r = ReaderType::New(); r->SetFileName( fixedImageNames[i] ); r->Update(); typename ChannelType::Pointer im = r->GetOutput(); im->SetDirection( int_dir ); im->SetOrigin( int_orig ); WarpFilterPointer wrp = WarpFilter::New(); wrp->SetInterpolator( WarpInterpolator::New() ); wrp->SetOutputParametersFromImage( im ); wrp->SetInput( im ); wrp->SetDisplacementField( field ); wrp->Update(); ThresholdPointer th = ThresholdFilter::New(); th->SetInput( wrp->GetOutput() ); th->ThresholdBelow( 0.0 ); th->SetOutsideValue( 0.0 ); th->Update(); typename ChannelType::Pointer im_wrp = th->GetOutput(); im_wrp->SetDirection( ref_dir ); im_wrp->SetOrigin( ref_orig ); if (mask.IsNotNull() && (vm.count("mask-inputs") && vm["mask-inputs"].as<bool>() ) ) { typename MaskFilter::Pointer mm = MaskFilter::New(); mm->SetMaskImage( mask ); mm->SetInput( im_wrp ); mm->Update(); im_wrp = mm->GetOutput(); } ss.str(""); ss << outPrefix << "_warped_" << i << ".nii.gz"; w->SetInput( im_wrp ); w->SetFileName( ss.str().c_str() ); w->Update(); } // Warp surfaces -------------------------------------------------- DisplacementFieldTransformPointer tf_inv = DisplacementFieldTransformType::New(); tf_inv->SetDisplacementField( transform->GetInverseDisplacementField() ); for( size_t i = 0; i<movingSurfaceNames.size(); i++){ MeshReaderPointer r = MeshReaderType::New(); r->SetFileName( movingSurfaceNames[i] ); r->Update(); MeshPointer mesh = r->GetOutput(); PointsIterator p_it = mesh->GetPoints()->Begin(); PointsIterator p_end = mesh->GetPoints()->End(); MeshPointType p; while ( p_it!=p_end ) { p = p_it.Value(); p_it.Value() = tf_inv->TransformPoint( p ); ++p_it; } MeshWriterPointer wmesh = MeshWriterType::New(); ss.str(""); ss << outPrefix << "_warped_" << i << ".vtk"; wmesh->SetFileName( ss.str().c_str() ); wmesh->SetInput( mesh ); wmesh->Update(); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: webdavprovider.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 16:17:04 $ * * 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 _WEBDAV_UCP_PROVIDER_HXX #define _WEBDAV_UCP_PROVIDER_HXX #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #ifndef _DAVSESSIONFACTORY_HXX_ #include "DAVSessionFactory.hxx" #endif #ifndef _UCBHELPER_PROVIDERHELPER_HXX #include <ucbhelper/providerhelper.hxx> #endif #ifndef _WEBDAV_UCP_PROPERTYMAP_HXX #include "PropertyMap.hxx" #endif namespace webdav_ucp { //========================================================================= // UNO service name for the provider. This name will be used by the UCB to // create instances of the provider. #define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \ "com.sun.star.ucb.WebDAVContentProvider" #define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38 // URL scheme. This is the scheme the provider will be able to create // contents for. The UCB will select the provider ( i.e. in order to create // contents ) according to this scheme. #define WEBDAV_URL_SCHEME \ "vnd.sun.star.webdav" #define WEBDAV_URL_SCHEME_LENGTH 19 #define HTTP_URL_SCHEME "http" #define HTTP_URL_SCHEME_LENGTH 4 #define HTTPS_URL_SCHEME "https" #define HTTPS_URL_SCHEME_LENGTH 5 #define FTP_URL_SCHEME "ftp" #define HTTP_CONTENT_TYPE \ "application/" HTTP_URL_SCHEME "-content" #define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE #define WEBDAV_COLLECTION_TYPE \ "application/" WEBDAV_URL_SCHEME "-collection" //========================================================================= class ContentProvider : public ::ucb::ContentProviderImplHelper { rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory; PropertyMap * m_pProps; public: ContentProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr ); virtual ~ContentProvider(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo XSERVICEINFO_DECL() // XContentProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent > SAL_CALL queryContent( const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( ::com::sun::star::ucb::IllegalIdentifierException, ::com::sun::star::uno::RuntimeException ); ////////////////////////////////////////////////////////////////////// // Additional interfaces ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Non-interface methods. ////////////////////////////////////////////////////////////////////// rtl::Reference< DAVSessionFactory > getDAVSessionFactory() { return m_xDAVSessionFactory; } bool getProperty( const ::rtl::OUString & rPropName, ::com::sun::star::beans::Property & rProp, bool bStrict = false ); }; } #endif <commit_msg>INTEGRATION: CWS bgdlremove (1.8.108); FILE MERGED 2007/05/18 11:37:19 kso 1.8.108.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: webdavprovider.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: ihi $ $Date: 2007-06-05 18:22:16 $ * * 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 _WEBDAV_UCP_PROVIDER_HXX #define _WEBDAV_UCP_PROVIDER_HXX #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_ #include <com/sun/star/beans/Property.hpp> #endif #ifndef _DAVSESSIONFACTORY_HXX_ #include "DAVSessionFactory.hxx" #endif #ifndef _UCBHELPER_PROVIDERHELPER_HXX #include <ucbhelper/providerhelper.hxx> #endif #ifndef _WEBDAV_UCP_PROPERTYMAP_HXX #include "PropertyMap.hxx" #endif namespace webdav_ucp { //========================================================================= // UNO service name for the provider. This name will be used by the UCB to // create instances of the provider. #define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME \ "com.sun.star.ucb.WebDAVContentProvider" #define WEBDAV_CONTENT_PROVIDER_SERVICE_NAME_LENGTH 38 // URL scheme. This is the scheme the provider will be able to create // contents for. The UCB will select the provider ( i.e. in order to create // contents ) according to this scheme. #define WEBDAV_URL_SCHEME \ "vnd.sun.star.webdav" #define WEBDAV_URL_SCHEME_LENGTH 19 #define HTTP_URL_SCHEME "http" #define HTTP_URL_SCHEME_LENGTH 4 #define HTTPS_URL_SCHEME "https" #define HTTPS_URL_SCHEME_LENGTH 5 #define FTP_URL_SCHEME "ftp" #define HTTP_CONTENT_TYPE \ "application/" HTTP_URL_SCHEME "-content" #define WEBDAV_CONTENT_TYPE HTTP_CONTENT_TYPE #define WEBDAV_COLLECTION_TYPE \ "application/" WEBDAV_URL_SCHEME "-collection" //========================================================================= class ContentProvider : public ::ucbhelper::ContentProviderImplHelper { rtl::Reference< DAVSessionFactory > m_xDAVSessionFactory; PropertyMap * m_pProps; public: ContentProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr ); virtual ~ContentProvider(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo XSERVICEINFO_DECL() // XContentProvider virtual ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent > SAL_CALL queryContent( const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( ::com::sun::star::ucb::IllegalIdentifierException, ::com::sun::star::uno::RuntimeException ); ////////////////////////////////////////////////////////////////////// // Additional interfaces ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Non-interface methods. ////////////////////////////////////////////////////////////////////// rtl::Reference< DAVSessionFactory > getDAVSessionFactory() { return m_xDAVSessionFactory; } bool getProperty( const ::rtl::OUString & rPropName, ::com::sun::star::beans::Property & rProp, bool bStrict = false ); }; } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbMapProjectionWrapper.h" #include <cassert> #include "otbMacro.h" #include "otbUtils.h" #include "projection/ossimMapProjection.h" #include "projection/ossimMapProjectionFactory.h" #include "projection/ossimMapProjection.h" #include "base/ossimGpt.h" #include "base/ossimDpt.h" #include "projection/ossimProjection.h" #include "base/ossimEllipsoid.h" #include "base/ossimEllipsoidFactory.h" #include "base/ossimString.h" #include "gdal/ossimOgcWktTranslator.h" #include "projection/ossimUtmProjection.h" #include "projection/ossimLambertConformalConicProjection.h" #include "projection/ossimTransMercatorProjection.h" namespace otb { MapProjectionWrapper::MapProjectionWrapper(): m_MapProjection(NULL), m_ProjectionRefWkt(""), m_ReinstanciateProjection(true) { } MapProjectionWrapper::~MapProjectionWrapper() { if (m_MapProjection != NULL) { delete m_MapProjection; } } MapProjectionWrapper::InternalMapProjectionPointer MapProjectionWrapper::GetMapProjection() { itkDebugMacro("returning MapProjection address " << this->m_MapProjection); if ((m_ReinstanciateProjection) || (m_MapProjection == NULL)) { this->InstanciateProjection(); } return this->m_MapProjection; } MapProjectionWrapper::InternalMapProjectionConstPointer MapProjectionWrapper::GetMapProjection() const { itkDebugMacro("returning MapProjection address " << this->m_MapProjection); if ((m_ReinstanciateProjection) || (m_MapProjection == NULL)) { itkExceptionMacro(<< "m_MapProjection not up-to-date, call InstanciateProjection() first"); } return this->m_MapProjection; } std::string MapProjectionWrapper::GetWkt() const { ossimKeywordlist kwl; this->GetMapProjection(); if (m_MapProjection == NULL) { return ""; } m_MapProjection->saveState(kwl); ossimOgcWktTranslator wktTranslator; std::string wkt; wkt = wktTranslator.fromOssimKwl(kwl); return wkt; } void MapProjectionWrapper::SetWkt(std::string projectionRefWkt) { this->m_ProjectionRefWkt = projectionRefWkt; m_ReinstanciateProjection = true; this->InstanciateProjection(); //Should not be needed, but it is... this->Modified(); } void MapProjectionWrapper::SetParameter(std::string key, std::string value) { m_ParameterStore[key] = value; m_ReinstanciateProjection = true; this->InstanciateProjection(); //Should not be needed, but it is... this->Modified(); } std::string MapProjectionWrapper::GetParameter(std::string key) const { // Please refer to the note in the header filer // we do NOT want to read from m_ParameterStore here! std::string projectionName = this->GetMapProjection()->getClassName(); // Start by matching generic parameters const ossimMapProjection* projection = dynamic_cast<const ossimMapProjection*>(this->GetMapProjection()); if (key.compare("Origin") == 0) { return Utils::ConvertToString(projection->origin()); } if (key.compare("FalseNorthing") == 0) { return Utils::ConvertToString(projection->getFalseNorthing()); } if (key.compare("FalseEasting") == 0) { return Utils::ConvertToString(projection->getFalseEasting()); } if (key.compare("StandardParallel1") == 0) { return Utils::ConvertToString(projection->getStandardParallel1()); } if (key.compare("StandardParallel2") == 0) { return Utils::ConvertToString(projection->getStandardParallel2()); } if (key.compare("A") == 0) { return Utils::ConvertToString(projection->getA()); } if (key.compare("B") == 0) { return Utils::ConvertToString(projection->getB()); } if (key.compare("F") == 0) { return Utils::ConvertToString(projection->getF()); } if (key.compare("MetersPerPixel") == 0) { return Utils::ConvertToString(projection->getMetersPerPixel()); } if (key.compare("DecimalDegreesPerPixel") == 0) { return Utils::ConvertToString(projection->getDecimalDegreesPerPixel()); } // Apply parameters to transmercator if (projectionName.compare("ossimTransMercatorProjection") == 0) { const ossimTransMercatorProjection* projection = dynamic_cast<const ossimTransMercatorProjection*>(this->GetMapProjection()); if (key.compare("ScaleFactor") == 0) { return Utils::ConvertToString(projection->getScaleFactor()); } } // Apply parameters to Utm if (projectionName.compare("ossimUtmProjection") == 0) { const ossimUtmProjection* projection = dynamic_cast<const ossimUtmProjection*>(this->GetMapProjection()); if (key.compare("Zone") == 0) { return Utils::ConvertToString(projection->getZone()); } if (key.compare("Hemisphere") == 0) { return Utils::ConvertToString(projection->getHemisphere()); } } return ""; } bool MapProjectionWrapper::InstanciateProjection() { if ((this->m_ReinstanciateProjection) || (m_MapProjection == NULL)) { ossimKeywordlist kwl; ossimOgcWktTranslator wktTranslator; bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl); if (projectionInformationAvailable) { //we don't want to have a ossimEquDistCylProjection here: //see discussion in May 2009 on ossim list; //a better solution might be available... std::string projectionString(kwl.find("type")); if (projectionString.find("ossimEquDistCylProjection") != string::npos) { otbMsgDevMacro(<< "WARNING: Not instanciating a ossimEquDistCylProjection: " << projectionString); otbMsgDevMacro(<< "Wkt was: " << kwl); otbMsgDevMacro(<< "From RefWkt: " << m_ProjectionRefWkt); return false; } m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl); } else { otbMsgDevMacro(<< "WARNING: Impossible to create the projection from Wkt: " << m_ProjectionRefWkt); otbMsgDevMacro(<< "Trying with string as a string (ossimUtmProjection or Utm would qualify"); // Trying directly with the m_ProjectionRefWkt (is // ossimUtmProjection for example) ossimString name(m_ProjectionRefWkt); m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(name); if (m_MapProjection == NULL) { // Trying directly extending the m_ProjectionRefWkt (convert the // Utm to ossimUtmProjection for example) ossimString extendedName("ossim"); extendedName += m_ProjectionRefWkt; extendedName += "Projection"; m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(extendedName); } if (m_MapProjection == NULL) return false; } this->m_ReinstanciateProjection = false; this->ApplyParametersToProjection(); return true; } return false; } void MapProjectionWrapper::InverseTransform(double x, double y, double z, double& lon, double& lat, double& h) { if (m_MapProjection == NULL) { otbMsgDevMacro(<< "WARNING: Using identity"); lon = x; lat = y; h = z; return; } ossimDpt ossimDPoint(x, y); //map projection ossimGpt ossimGPoint; ossimGPoint = this->GetMapProjection()->inverse(ossimDPoint); ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84()); lon = ossimGPoint.lon; lat = ossimGPoint.lat; h = z; } void MapProjectionWrapper::ForwardTransform(double lon, double lat, double h, double& x, double& y, double& z) { if (m_MapProjection == NULL) { otbMsgDevMacro(<< "WARNING: Using identity"); x = lon; y = lat; z = h; return; } ossimGpt ossimGPoint(lat, lon, h); //map projection ossimDpt ossimDPoint; ossimDPoint = this->GetMapProjection()->forward(ossimGPoint); x = ossimDPoint.x; y = ossimDPoint.y; z = h; } void MapProjectionWrapper::ApplyParametersToProjection() { // Start by identifying the projection, that will be necessary for // the casting. std::string projectionName = this->GetMapProjection()->getClassName(); StoreType::const_iterator it; // Apply standard map projection parameters ossimMapProjection* projection = dynamic_cast<ossimMapProjection*>(this->GetMapProjection()); // Set up origin const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); //default value it = m_ParameterStore.find("Datum"); if (it != m_ParameterStore.end()) { datum = ossimDatumFactory::instance()->create((*it).second); projection->setDatum(datum); } StoreType::const_iterator itX = m_ParameterStore.find("OriginX"); StoreType::const_iterator itY = m_ParameterStore.find("OriginY"); StoreType::const_iterator itZ = m_ParameterStore.find("OriginZ"); if (itX != m_ParameterStore.end() && itY != m_ParameterStore.end()) { double originX = atof((*itX).second.c_str()); double originY = atof((*itY).second.c_str()); double originZ = 0; if (itZ != m_ParameterStore.end()) { originZ = atof((*itZ).second.c_str()); } ossimGpt origin(originY, originX, originZ, datum); projection->setOrigin(origin); } // Apply parameters to LambertConformalConic if (projectionName.compare("ossimLambertConformalConicProjection") == 0) { ossimLambertConformalConicProjection* projection = dynamic_cast<ossimLambertConformalConicProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("FalseNorthing"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseNorthing(value); } it = m_ParameterStore.find("FalseEasting"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseEasting(value); } it = m_ParameterStore.find("StandardParallel1"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setStandardParallel1(value); } it = m_ParameterStore.find("StandardParallel2"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setStandardParallel2(value); } } // Apply parameters to trasnmercator if (projectionName.compare("ossimTransMercatorProjection") == 0) { ossimTransMercatorProjection* projection = dynamic_cast<ossimTransMercatorProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("ScaleFactor"); if (it != m_ParameterStore.end()) { double scale = atof((*it).second.c_str()); projection->setScaleFactor(scale); } } // Apply parameters to Utm if (projectionName.compare("ossimUtmProjection") == 0) { ossimUtmProjection* projection = dynamic_cast<ossimUtmProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("Zone"); if (it != m_ParameterStore.end()) { int zone = atoi((*it).second.c_str()); projection->setZone(zone); } it = m_ParameterStore.find("Hemisphere"); if (it != m_ParameterStore.end()) { projection->setHemisphere((*it).second[0]); } } } void MapProjectionWrapper::PrintMap() const { std::cout << m_MapProjection->print(std::cout); std::cout << "Parameter store:\n"; for (StoreType::const_iterator it = m_ParameterStore.begin(); it != m_ParameterStore.end(); ++it) { std::cout << " " << (*it).first << ": " << (*it).second << "\n"; } } namespace Utils { int GetZoneFromGeoPoint(double lon, double lat) { //use ossim to handle the special case of UTM ossimGpt point(lat, lon); ossimUtmProjection projection; int zone = projection.computeZone(point); return zone; } } } // namespace otb <commit_msg>BUG: fix parameter setting<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt 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 notices for more information. =========================================================================*/ #include "otbMapProjectionWrapper.h" #include <cassert> #include "otbMacro.h" #include "otbUtils.h" #include "projection/ossimMapProjection.h" #include "projection/ossimMapProjectionFactory.h" #include "projection/ossimMapProjection.h" #include "base/ossimGpt.h" #include "base/ossimDpt.h" #include "projection/ossimProjection.h" #include "base/ossimEllipsoid.h" #include "base/ossimEllipsoidFactory.h" #include "base/ossimString.h" #include "gdal/ossimOgcWktTranslator.h" #include "projection/ossimUtmProjection.h" #include "projection/ossimLambertConformalConicProjection.h" #include "projection/ossimTransMercatorProjection.h" #include "projection/ossimEckert4Projection.h" #include "projection/ossimMollweidProjection.h" #include "projection/ossimSinusoidalProjection.h" namespace otb { MapProjectionWrapper::MapProjectionWrapper(): m_MapProjection(NULL), m_ProjectionRefWkt(""), m_ReinstanciateProjection(true) { } MapProjectionWrapper::~MapProjectionWrapper() { if (m_MapProjection != NULL) { delete m_MapProjection; } } MapProjectionWrapper::InternalMapProjectionPointer MapProjectionWrapper::GetMapProjection() { itkDebugMacro("returning MapProjection address " << this->m_MapProjection); if ((m_ReinstanciateProjection) || (m_MapProjection == NULL)) { this->InstanciateProjection(); } return this->m_MapProjection; } MapProjectionWrapper::InternalMapProjectionConstPointer MapProjectionWrapper::GetMapProjection() const { itkDebugMacro("returning MapProjection address " << this->m_MapProjection); if ((m_ReinstanciateProjection) || (m_MapProjection == NULL)) { itkExceptionMacro(<< "m_MapProjection not up-to-date, call InstanciateProjection() first"); } return this->m_MapProjection; } std::string MapProjectionWrapper::GetWkt() const { ossimKeywordlist kwl; this->GetMapProjection(); if (m_MapProjection == NULL) { return ""; } m_MapProjection->saveState(kwl); ossimOgcWktTranslator wktTranslator; std::string wkt; wkt = wktTranslator.fromOssimKwl(kwl); return wkt; } void MapProjectionWrapper::SetWkt(std::string projectionRefWkt) { this->m_ProjectionRefWkt = projectionRefWkt; m_ReinstanciateProjection = true; this->InstanciateProjection(); //Should not be needed, but it is... this->Modified(); } void MapProjectionWrapper::SetParameter(std::string key, std::string value) { m_ParameterStore[key] = value; m_ReinstanciateProjection = true; this->InstanciateProjection(); //Should not be needed, but it is... this->Modified(); } std::string MapProjectionWrapper::GetParameter(std::string key) const { // Please refer to the note in the header filer // we do NOT want to read from m_ParameterStore here! std::string projectionName = this->GetMapProjection()->getClassName(); // Start by matching generic parameters const ossimMapProjection* projection = dynamic_cast<const ossimMapProjection*>(this->GetMapProjection()); if (key.compare("Origin") == 0) { return Utils::ConvertToString(projection->origin()); } if (key.compare("FalseNorthing") == 0) { return Utils::ConvertToString(projection->getFalseNorthing()); } if (key.compare("FalseEasting") == 0) { return Utils::ConvertToString(projection->getFalseEasting()); } if (key.compare("StandardParallel1") == 0) { return Utils::ConvertToString(projection->getStandardParallel1()); } if (key.compare("StandardParallel2") == 0) { return Utils::ConvertToString(projection->getStandardParallel2()); } if (key.compare("A") == 0) { return Utils::ConvertToString(projection->getA()); } if (key.compare("B") == 0) { return Utils::ConvertToString(projection->getB()); } if (key.compare("F") == 0) { return Utils::ConvertToString(projection->getF()); } if (key.compare("MetersPerPixel") == 0) { return Utils::ConvertToString(projection->getMetersPerPixel()); } if (key.compare("DecimalDegreesPerPixel") == 0) { return Utils::ConvertToString(projection->getDecimalDegreesPerPixel()); } // Apply parameters to transmercator if (projectionName.compare("ossimTransMercatorProjection") == 0) { const ossimTransMercatorProjection* projection = dynamic_cast<const ossimTransMercatorProjection*>(this->GetMapProjection()); if (key.compare("ScaleFactor") == 0) { return Utils::ConvertToString(projection->getScaleFactor()); } } // Apply parameters to Utm if (projectionName.compare("ossimUtmProjection") == 0) { const ossimUtmProjection* projection = dynamic_cast<const ossimUtmProjection*>(this->GetMapProjection()); if (key.compare("Zone") == 0) { return Utils::ConvertToString(projection->getZone()); } if (key.compare("Hemisphere") == 0) { return Utils::ConvertToString(projection->getHemisphere()); } } return ""; } bool MapProjectionWrapper::InstanciateProjection() { if ((this->m_ReinstanciateProjection) || (m_MapProjection == NULL)) { ossimKeywordlist kwl; ossimOgcWktTranslator wktTranslator; bool projectionInformationAvailable = wktTranslator.toOssimKwl(m_ProjectionRefWkt, kwl); if (projectionInformationAvailable) { //we don't want to have a ossimEquDistCylProjection here: //see discussion in May 2009 on ossim list; //a better solution might be available... std::string projectionString(kwl.find("type")); if (projectionString.find("ossimEquDistCylProjection") != string::npos) { otbMsgDevMacro(<< "WARNING: Not instanciating a ossimEquDistCylProjection: " << projectionString); otbMsgDevMacro(<< "Wkt was: " << kwl); otbMsgDevMacro(<< "From RefWkt: " << m_ProjectionRefWkt); return false; } m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(kwl); } else { otbMsgDevMacro(<< "WARNING: Impossible to create the projection from Wkt: " << m_ProjectionRefWkt); otbMsgDevMacro(<< "Trying with string as a string (ossimUtmProjection or Utm would qualify"); // Trying directly with the m_ProjectionRefWkt (is // ossimUtmProjection for example) ossimString name(m_ProjectionRefWkt); m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(name); if (m_MapProjection == NULL) { // Trying directly extending the m_ProjectionRefWkt (convert the // Utm to ossimUtmProjection for example) ossimString extendedName("ossim"); extendedName += m_ProjectionRefWkt; extendedName += "Projection"; m_MapProjection = ossimMapProjectionFactory::instance()->createProjection(extendedName); } if (m_MapProjection == NULL) return false; } this->m_ReinstanciateProjection = false; this->ApplyParametersToProjection(); return true; } return false; } void MapProjectionWrapper::InverseTransform(double x, double y, double z, double& lon, double& lat, double& h) { if (m_MapProjection == NULL) { otbMsgDevMacro(<< "WARNING: Using identity"); lon = x; lat = y; h = z; return; } ossimDpt ossimDPoint(x, y); //map projection ossimGpt ossimGPoint; ossimGPoint = this->GetMapProjection()->inverse(ossimDPoint); ossimGPoint.changeDatum(ossimDatumFactory::instance()->wgs84()); lon = ossimGPoint.lon; lat = ossimGPoint.lat; h = z; } void MapProjectionWrapper::ForwardTransform(double lon, double lat, double h, double& x, double& y, double& z) { if (m_MapProjection == NULL) { otbMsgDevMacro(<< "WARNING: Using identity"); x = lon; y = lat; z = h; return; } ossimGpt ossimGPoint(lat, lon, h); //map projection ossimDpt ossimDPoint; ossimDPoint = this->GetMapProjection()->forward(ossimGPoint); x = ossimDPoint.x; y = ossimDPoint.y; z = h; } void MapProjectionWrapper::ApplyParametersToProjection() { // Start by identifying the projection, that will be necessary for // the casting. std::string projectionName = this->GetMapProjection()->getClassName(); StoreType::const_iterator it; // Apply standard map projection parameters ossimMapProjection* projection = dynamic_cast<ossimMapProjection*>(this->GetMapProjection()); // Set up origin const ossimDatum* datum = ossimDatumFactory::instance()->wgs84(); //default value it = m_ParameterStore.find("Datum"); if (it != m_ParameterStore.end()) { datum = ossimDatumFactory::instance()->create((*it).second); projection->setDatum(datum); } StoreType::const_iterator itX = m_ParameterStore.find("OriginX"); StoreType::const_iterator itY = m_ParameterStore.find("OriginY"); StoreType::const_iterator itZ = m_ParameterStore.find("OriginZ"); if (itX != m_ParameterStore.end() && itY != m_ParameterStore.end()) { double originX = atof((*itX).second.c_str()); double originY = atof((*itY).second.c_str()); double originZ = 0; if (itZ != m_ParameterStore.end()) { originZ = atof((*itZ).second.c_str()); } ossimGpt origin(originY, originX, originZ, datum); projection->setOrigin(origin); } // Apply parameters to LambertConformalConic if (projectionName.compare("ossimLambertConformalConicProjection") == 0) { ossimLambertConformalConicProjection* projection = dynamic_cast<ossimLambertConformalConicProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("FalseNorthing"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseNorthing(value); } it = m_ParameterStore.find("FalseEasting"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseEasting(value); } it = m_ParameterStore.find("StandardParallel1"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setStandardParallel1(value); } it = m_ParameterStore.find("StandardParallel2"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setStandardParallel2(value); } } // Apply parameters to Eckert4 if (projectionName.compare("ossimEckert4Projection") == 0) { ossimEckert4Projection* projection = dynamic_cast<ossimEckert4Projection*>(this->GetMapProjection()); it = m_ParameterStore.find("FalseNorthing"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseNorthing(value); } it = m_ParameterStore.find("FalseEasting"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseEasting(value); } } // Apply parameters to Mollweid if (projectionName.compare("ossimMollweidProjection") == 0) { ossimMollweidProjection* projection = dynamic_cast<ossimMollweidProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("FalseNorthing"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseNorthing(value); } it = m_ParameterStore.find("FalseEasting"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseEasting(value); } } // Apply parameters to Sinusoidal if (projectionName.compare("ossimSinusoidalProjection") == 0) { ossimSinusoidalProjection* projection = dynamic_cast<ossimSinusoidalProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("FalseNorthing"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseNorthing(value); } it = m_ParameterStore.find("FalseEasting"); if (it != m_ParameterStore.end()) { double value = atof((*it).second.c_str()); projection->setFalseEasting(value); } } // Apply parameters to trasnmercator if (projectionName.compare("ossimTransMercatorProjection") == 0) { ossimTransMercatorProjection* projection = dynamic_cast<ossimTransMercatorProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("ScaleFactor"); if (it != m_ParameterStore.end()) { double scale = atof((*it).second.c_str()); projection->setScaleFactor(scale); } } // Apply parameters to Utm if (projectionName.compare("ossimUtmProjection") == 0) { ossimUtmProjection* projection = dynamic_cast<ossimUtmProjection*>(this->GetMapProjection()); it = m_ParameterStore.find("Zone"); if (it != m_ParameterStore.end()) { int zone = atoi((*it).second.c_str()); projection->setZone(zone); } it = m_ParameterStore.find("Hemisphere"); if (it != m_ParameterStore.end()) { projection->setHemisphere((*it).second[0]); } } } void MapProjectionWrapper::PrintMap() const { std::cout << m_MapProjection->print(std::cout); std::cout << "Parameter store:\n"; for (StoreType::const_iterator it = m_ParameterStore.begin(); it != m_ParameterStore.end(); ++it) { std::cout << " " << (*it).first << ": " << (*it).second << "\n"; } } namespace Utils { int GetZoneFromGeoPoint(double lon, double lat) { //use ossim to handle the special case of UTM ossimGpt point(lat, lon); ossimUtmProjection projection; int zone = projection.computeZone(point); return zone; } } } // namespace otb <|endoftext|>
<commit_before>#include "MessageHandler.h" #include "IqrfCdcChannel.h" #include "IqrfSpiChannel.h" #include "UdpChannel.h" #include "UdpMessage.h" #include "helpers.h" #include "MessageQueue.h" #include "IqrfLogging.h" #include "PlatformDep.h" #include <climits> enum IqrfWriteResults { wr_OK = 0x50, wr_Error_Len = 0x60, //(number of data = 0 or more than TR buffer COM length) wr_Error_SPI = 0x61, //(SPI bus busy) wr_Error_IQRF = 0x62 //(IQRF - CRCM Error) }; int MessageHandler::handleMessageFromUdp(const ustring& udpMessage) { TRC_DBG("Received from UDP: " << std::endl << FORM_HEX(udpMessage.data(), udpMessage.size())); size_t msgSize = udpMessage.size(); std::basic_string<unsigned char> message; try { decodeMessageUdp(udpMessage, message); } catch (UdpChannelException& e) { TRC_DBG("Wrong message: " << e.what()); return -1; } switch (udpMessage[cmd]) { case IQRF_UDP_GET_GW_INFO: // --- Returns GW identification --- { std::basic_string<unsigned char> udpResponse(udpMessage); udpResponse[cmd] = (unsigned char)IQRF_UDP_GET_GW_INFO | 0x80; encodeMessageUdp(getGwIdent(), udpResponse); m_toUdpMessageQueue->pushToQueue(udpResponse); } return 0; case IQRF_UDP_WRITE_IQRF: // --- Writes data to the TR module --- { m_toIqrfMessageQueue->pushToQueue(message); //send response std::basic_string<unsigned char> udpResponse(udpMessage.substr(0, IQRF_UDP_HEADER_SIZE)); std::basic_string<unsigned char> message; udpResponse[cmd] = (unsigned char)IQRF_UDP_WRITE_IQRF | 0x80; encodeMessageUdp(message, udpResponse); //TODO it is required to send back via subcmd write result - implement sync write with appropriate ret code udpResponse[subcmd] = (unsigned char)IQRF_UDP_ACK; m_toUdpMessageQueue->pushToQueue(udpResponse); } return 0; default: break; } return -1; } int MessageHandler::handleMessageFromIqrf(const ustring& iqrfMessage) { TRC_DBG("Received from to IQRF: " << std::endl << FORM_HEX(iqrfMessage.data(), iqrfMessage.size())); std::basic_string<unsigned char> udpMessage; std::basic_string<unsigned char> message(iqrfMessage); encodeMessageUdp(message, udpMessage); udpMessage[cmd] = (unsigned char)IQRF_UDP_IQRF_SPI_DATA; m_toUdpMessageQueue->pushToQueue(udpMessage); //std::basic_string<unsigned char> udpMessage; //encodeMessageUdp(iqrfMessage, udpMessage); //m_toUdpMessageQueue->pushToQueue(udpMessage); return 0; } void MessageHandler::encodeMessageUdp(const ustring& message, ustring& udpMessage) { unsigned short dlen = (unsigned short)message.size(); udpMessage.resize(IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE, '\0'); udpMessage[gwAddr] = IQRF_UDP_GW_ADR; udpMessage[dlen_H] = (unsigned char)((dlen >> 8) & 0xFF); udpMessage[dlen_L] = (unsigned char)(dlen & 0xFF); udpMessage.insert(IQRF_UDP_HEADER_SIZE, message); uint16_t crc = GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE); udpMessage[dlen + IQRF_UDP_HEADER_SIZE] = (unsigned char)((crc >> 8) & 0xFF); udpMessage[dlen + IQRF_UDP_HEADER_SIZE + 1] = (unsigned char)(crc & 0xFF); } void MessageHandler::decodeMessageUdp(const ustring& udpMessage, ustring& message) { unsigned short dlen = 0; // Min. packet length check if (udpMessage.size() < IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) THROW_EX(UdpChannelException, "Message is too short: " << FORM_HEX(udpMessage.data(), udpMessage.size())); // GW_ADR check if (udpMessage[gwAddr] != IQRF_UDP_GW_ADR) THROW_EX(UdpChannelException, "Message is has wrong GW_ADDR: " << PAR_HEX(udpMessage[gwAddr])); //iqrf data length dlen = (udpMessage[dlen_H] << 8) + udpMessage[dlen_L]; // Max. packet length check if ((dlen + IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) > IQRF_UDP_BUFFER_SIZE) THROW_EX(UdpChannelException, "Message is too long: " << PAR(dlen)); // CRC check unsigned short crc = (udpMessage[IQRF_UDP_HEADER_SIZE + dlen] << 8) + udpMessage[IQRF_UDP_HEADER_SIZE + dlen + 1]; if (crc != GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE)) THROW_EX(UdpChannelException, "Message has wrong CRC"); message = udpMessage.substr(IQRF_UDP_HEADER_SIZE, dlen); } MessageHandler::MessageHandler(const std::string& iqrf_port_name, const std::string& remote_ip_port, const std::string& local_ip_port) :m_iqrfChannel(nullptr) , m_udpChannel(nullptr) , m_toUdpMessageQueue(nullptr) , m_toIqrfMessageQueue(nullptr) , m_iqrfPortName(iqrf_port_name) { m_remotePort = strtoul(remote_ip_port.c_str(), nullptr, 0); if (0 == m_remotePort || ULONG_MAX == m_remotePort) m_remotePort = 55000; m_localPort = strtoul(local_ip_port.c_str(), nullptr, 0); if (0 == m_localPort || ULONG_MAX == m_localPort) m_localPort = 55300; } MessageHandler::~MessageHandler() { } std::basic_string<unsigned char> MessageHandler::getGwIdent() { //1. - GW type e.g.: �GW - ETH - 02A� //2. - FW version e.g. : �2.50� //3. - MAC address e.g. : �00 11 22 33 44 55� //4. - TCP / IP Stack version e.g. : �5.42� //5. - IP address of GW e.g. : �192.168.2.100� //6. - Net BIOS Name e.g. : �iqrf_xxxx � 15 characters //7. - IQRF module OS version e.g. : �3.06D� //8. - Public IP address e.g. : �213.214.215.120� //std::basic_ostringstream<unsigned char> os; std::basic_ostringstream<char> ostring; ostring << "\x0D\x0A" << "udp-daemon-01" << "\x0D\x0A" << "2.50" << "\x0D\x0A" << "00 11 22 33 44 55" << "\x0D\x0A" << "5.42" << "\x0D\x0A" << "192.168.1.11" << "\x0D\x0A" << "iqrf_xxxx" << "\x0D\x0A" << "3.06D" << "\x0D\x0A" << "192.168.1.11" << "\x0D\x0A"; ustring res((unsigned char*)ostring.str().data(), ostring.str().size()); //TRC_DBG("retval:" << PAR(res.size()) << std::endl << FORM_HEX(res.data(),res.size())); return res; } void MessageHandler::watchDog() { TRC_ENTER(""); m_running = true; try { start(); while (m_running) { //TODO //watch worker threads std::this_thread::sleep_for(std::chrono::milliseconds(3000)); } } catch (std::exception& e) { CATCH_EX("error", std::exception, e); } stop(); TRC_LEAVE(""); } void MessageHandler::start() { TRC_ENTER(""); size_t found = m_iqrfPortName.find("spi"); if (found != std::string::npos) m_iqrfChannel = ant_new IqrfSpiChannel(m_iqrfPortName); else m_iqrfChannel = ant_new IqrfCdcChannel(m_iqrfPortName); m_udpChannel = ant_new UdpChannel((unsigned short)m_remotePort, (unsigned short)m_localPort, IQRF_UDP_BUFFER_SIZE); //Messages from IQRF are sent via MessageQueue to UDP channel m_toUdpMessageQueue = ant_new MessageQueue(m_udpChannel); //Messages from UDP are sent via MessageQueue to IQRF channel m_toIqrfMessageQueue = ant_new MessageQueue(m_iqrfChannel); //Received messages from IQRF channel are pushed to UDP MessageQueue m_iqrfChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int { return handleMessageFromIqrf(msg); }); //Received messages from UDP channel are pushed to IQRF MessageQueue m_udpChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int { return handleMessageFromUdp(msg); }); std::cout << "udp-daemon started" << std::endl; TRC_LEAVE(""); } void MessageHandler::stop() { TRC_ENTER(""); std::cout << "udp-daemon stops" << std::endl; delete m_iqrfChannel; delete m_udpChannel; delete m_toUdpMessageQueue; delete m_toIqrfMessageQueue; TRC_LEAVE(""); } void MessageHandler::exit() { TRC_WAR("exiting ..."); std::cout << "udp-daemon exits" << std::endl; m_running = false; } <commit_msg>Fixed CRC bug in responses<commit_after>#include "MessageHandler.h" #include "IqrfCdcChannel.h" #include "IqrfSpiChannel.h" #include "UdpChannel.h" #include "UdpMessage.h" #include "helpers.h" #include "MessageQueue.h" #include "IqrfLogging.h" #include "PlatformDep.h" #include <climits> enum IqrfWriteResults { wr_OK = 0x50, wr_Error_Len = 0x60, //(number of data = 0 or more than TR buffer COM length) wr_Error_SPI = 0x61, //(SPI bus busy) wr_Error_IQRF = 0x62 //(IQRF - CRCM Error) }; int MessageHandler::handleMessageFromUdp(const ustring& udpMessage) { TRC_DBG("Received from UDP: " << std::endl << FORM_HEX(udpMessage.data(), udpMessage.size())); size_t msgSize = udpMessage.size(); std::basic_string<unsigned char> message; try { decodeMessageUdp(udpMessage, message); } catch (UdpChannelException& e) { TRC_DBG("Wrong message: " << e.what()); return -1; } switch (udpMessage[cmd]) { case IQRF_UDP_GET_GW_INFO: // --- Returns GW identification --- { std::basic_string<unsigned char> udpResponse(udpMessage); udpResponse[cmd] = (unsigned char)IQRF_UDP_GET_GW_INFO | 0x80; encodeMessageUdp(getGwIdent(), udpResponse); m_toUdpMessageQueue->pushToQueue(udpResponse); } return 0; case IQRF_UDP_WRITE_IQRF: // --- Writes data to the TR module --- { m_toIqrfMessageQueue->pushToQueue(message); //send response std::basic_string<unsigned char> udpResponse(udpMessage.substr(0, IQRF_UDP_HEADER_SIZE)); std::basic_string<unsigned char> message; udpResponse[cmd] = (unsigned char)IQRF_UDP_WRITE_IQRF | 0x80; udpResponse[subcmd] = (unsigned char)IQRF_UDP_ACK; encodeMessageUdp(message, udpResponse); //TODO it is required to send back via subcmd write result - implement sync write with appropriate ret code m_toUdpMessageQueue->pushToQueue(udpResponse); } return 0; default: break; } return -1; } int MessageHandler::handleMessageFromIqrf(const ustring& iqrfMessage) { TRC_DBG("Received from to IQRF: " << std::endl << FORM_HEX(iqrfMessage.data(), iqrfMessage.size())); std::basic_string<unsigned char> udpMessage; std::basic_string<unsigned char> message(iqrfMessage); encodeMessageUdp(message, udpMessage); udpMessage[cmd] = (unsigned char)IQRF_UDP_IQRF_SPI_DATA; m_toUdpMessageQueue->pushToQueue(udpMessage); //std::basic_string<unsigned char> udpMessage; //encodeMessageUdp(iqrfMessage, udpMessage); //m_toUdpMessageQueue->pushToQueue(udpMessage); return 0; } void MessageHandler::encodeMessageUdp(const ustring& message, ustring& udpMessage) { unsigned short dlen = (unsigned short)message.size(); udpMessage.resize(IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE, '\0'); udpMessage[gwAddr] = IQRF_UDP_GW_ADR; udpMessage[dlen_H] = (unsigned char)((dlen >> 8) & 0xFF); udpMessage[dlen_L] = (unsigned char)(dlen & 0xFF); udpMessage.insert(IQRF_UDP_HEADER_SIZE, message); uint16_t crc = GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE); udpMessage[dlen + IQRF_UDP_HEADER_SIZE] = (unsigned char)((crc >> 8) & 0xFF); udpMessage[dlen + IQRF_UDP_HEADER_SIZE + 1] = (unsigned char)(crc & 0xFF); } void MessageHandler::decodeMessageUdp(const ustring& udpMessage, ustring& message) { unsigned short dlen = 0; // Min. packet length check if (udpMessage.size() < IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) THROW_EX(UdpChannelException, "Message is too short: " << FORM_HEX(udpMessage.data(), udpMessage.size())); // GW_ADR check if (udpMessage[gwAddr] != IQRF_UDP_GW_ADR) THROW_EX(UdpChannelException, "Message is has wrong GW_ADDR: " << PAR_HEX(udpMessage[gwAddr])); //iqrf data length dlen = (udpMessage[dlen_H] << 8) + udpMessage[dlen_L]; // Max. packet length check if ((dlen + IQRF_UDP_HEADER_SIZE + IQRF_UDP_CRC_SIZE) > IQRF_UDP_BUFFER_SIZE) THROW_EX(UdpChannelException, "Message is too long: " << PAR(dlen)); // CRC check unsigned short crc = (udpMessage[IQRF_UDP_HEADER_SIZE + dlen] << 8) + udpMessage[IQRF_UDP_HEADER_SIZE + dlen + 1]; if (crc != GetCRC_CCITT((unsigned char*)udpMessage.data(), dlen + IQRF_UDP_HEADER_SIZE)) THROW_EX(UdpChannelException, "Message has wrong CRC"); message = udpMessage.substr(IQRF_UDP_HEADER_SIZE, dlen); } MessageHandler::MessageHandler(const std::string& iqrf_port_name, const std::string& remote_ip_port, const std::string& local_ip_port) :m_iqrfChannel(nullptr) , m_udpChannel(nullptr) , m_toUdpMessageQueue(nullptr) , m_toIqrfMessageQueue(nullptr) , m_iqrfPortName(iqrf_port_name) { m_remotePort = strtoul(remote_ip_port.c_str(), nullptr, 0); if (0 == m_remotePort || ULONG_MAX == m_remotePort) m_remotePort = 55000; m_localPort = strtoul(local_ip_port.c_str(), nullptr, 0); if (0 == m_localPort || ULONG_MAX == m_localPort) m_localPort = 55300; } MessageHandler::~MessageHandler() { } std::basic_string<unsigned char> MessageHandler::getGwIdent() { //1. - GW type e.g.: �GW - ETH - 02A� //2. - FW version e.g. : �2.50� //3. - MAC address e.g. : �00 11 22 33 44 55� //4. - TCP / IP Stack version e.g. : �5.42� //5. - IP address of GW e.g. : �192.168.2.100� //6. - Net BIOS Name e.g. : �iqrf_xxxx � 15 characters //7. - IQRF module OS version e.g. : �3.06D� //8. - Public IP address e.g. : �213.214.215.120� //std::basic_ostringstream<unsigned char> os; std::basic_ostringstream<char> ostring; ostring << "\x0D\x0A" << "udp-daemon-01" << "\x0D\x0A" << "2.50" << "\x0D\x0A" << "00 11 22 33 44 55" << "\x0D\x0A" << "5.42" << "\x0D\x0A" << "192.168.1.11" << "\x0D\x0A" << "iqrf_xxxx" << "\x0D\x0A" << "3.06D" << "\x0D\x0A" << "192.168.1.11" << "\x0D\x0A"; ustring res((unsigned char*)ostring.str().data(), ostring.str().size()); //TRC_DBG("retval:" << PAR(res.size()) << std::endl << FORM_HEX(res.data(),res.size())); return res; } void MessageHandler::watchDog() { TRC_ENTER(""); m_running = true; try { start(); while (m_running) { //TODO //watch worker threads std::this_thread::sleep_for(std::chrono::milliseconds(3000)); } } catch (std::exception& e) { CATCH_EX("error", std::exception, e); } stop(); TRC_LEAVE(""); } void MessageHandler::start() { TRC_ENTER(""); size_t found = m_iqrfPortName.find("spi"); if (found != std::string::npos) m_iqrfChannel = ant_new IqrfSpiChannel(m_iqrfPortName); else m_iqrfChannel = ant_new IqrfCdcChannel(m_iqrfPortName); m_udpChannel = ant_new UdpChannel((unsigned short)m_remotePort, (unsigned short)m_localPort, IQRF_UDP_BUFFER_SIZE); //Messages from IQRF are sent via MessageQueue to UDP channel m_toUdpMessageQueue = ant_new MessageQueue(m_udpChannel); //Messages from UDP are sent via MessageQueue to IQRF channel m_toIqrfMessageQueue = ant_new MessageQueue(m_iqrfChannel); //Received messages from IQRF channel are pushed to UDP MessageQueue m_iqrfChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int { return handleMessageFromIqrf(msg); }); //Received messages from UDP channel are pushed to IQRF MessageQueue m_udpChannel->registerReceiveFromHandler([&](const std::basic_string<unsigned char>& msg) -> int { return handleMessageFromUdp(msg); }); std::cout << "udp-daemon started" << std::endl; TRC_LEAVE(""); } void MessageHandler::stop() { TRC_ENTER(""); std::cout << "udp-daemon stops" << std::endl; delete m_iqrfChannel; delete m_udpChannel; delete m_toUdpMessageQueue; delete m_toIqrfMessageQueue; TRC_LEAVE(""); } void MessageHandler::exit() { TRC_WAR("exiting ..."); std::cout << "udp-daemon exits" << std::endl; m_running = false; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX600 グループ DMACAa 定義 @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/io_utils.hpp" #include "RX600/peripheral.hpp" #include "RX600/icu.hpp" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief DMA コントローラ(DMACAa) @param[in] base ベース・アドレス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base> struct dmaca_core_t { }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief DMA コントローラ(DMACAa) @param[in] base ベース・アドレス @param[in] t ペリフェラル型 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral t> struct dmaca_t : public dmaca_core_t<base> { }; typedef dmaca_t<0x00820000, peripheral::DMACA0> DMACA0; typedef dmaca_t<0x00820040, peripheral::DMACA1> DMACA1; typedef dmaca_t<0x00820080, peripheral::DMACA2> DMACA2; typedef dmaca_t<0x008200C0, peripheral::DMACA3> DMACA3; typedef dmaca_t<0x00820100, peripheral::DMACA4> DMACA4; typedef dmaca_t<0x00820140, peripheral::DMACA5> DMACA5; typedef dmaca_t<0x00820180, peripheral::DMACA6> DMACA6; typedef dmaca_t<0x008201C0, peripheral::DMACA7> DMACA7; } <commit_msg>remove: rename<commit_after><|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "sitkImageReaderBase.h" #include "sitkMacro.h" #include "sitkExceptionObject.h" #include <itksys/SystemTools.hxx> // Include the Transform IO here, so that the IO factory registration // will occur. #include <itkTransformFileReader.h> #include <itkTransformFileWriter.h> #include <string> #include <itkImage.h> #include <itkImageIOBase.h> #include <itkImageIOFactory.h> #include <itkGDCMImageIO.h> namespace itk { namespace simple { ImageReaderBase ::~ImageReaderBase() { } ImageReaderBase ::ImageReaderBase() : m_OutputPixelType(sitkUnknown), m_LoadPrivateTags(false) { } std::string ImageReaderBase ::ToString() const { std::ostringstream out; out << " OutputPixelType: "; this->ToStringHelper(out, this->m_OutputPixelType) << std::endl; out << " LoadPrivateTags: "; this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl; out << ProcessObject::ToString(); return out.str(); } itk::SmartPointer<ImageIOBase> ImageReaderBase ::GetImageIOBase(const std::string &fileName) { itk::ImageIOBase::Pointer iobase = itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode); if ( iobase.IsNull() ) { if ( !itksys::SystemTools::FileExists( fileName.c_str() ) ) { sitkExceptionMacro( "The file \"" << fileName << "\" does not exist." ); } if ( !bool(std::ifstream( fileName.c_str() )) ) { sitkExceptionMacro( "Unable to open \"" << fileName << "\" for reading." ); } sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" ); } // Try additional parameters GDCMImageIO *ioGDCMImage = dynamic_cast<GDCMImageIO*>(iobase.GetPointer()); if (ioGDCMImage) { ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags); } // Read the image information iobase->SetFileName( fileName ); iobase->ReadImageInformation(); return iobase; } ImageReaderBase::Self& ImageReaderBase ::SetOutputPixelType( PixelIDValueEnum pixelID ) { this->m_OutputPixelType = pixelID; return *this; } PixelIDValueEnum ImageReaderBase ::GetOutputPixelType( void ) const { return this->m_OutputPixelType; } ImageReaderBase::Self& ImageReaderBase ::SetLoadPrivateTags(bool loadPrivateTags) { this->m_LoadPrivateTags = loadPrivateTags; return *this; } bool ImageReaderBase ::GetLoadPrivateTags() const { return this->m_LoadPrivateTags; } void ImageReaderBase ::LoadPrivateTagsOn() { this->SetLoadPrivateTags(true); } void ImageReaderBase ::LoadPrivateTagsOff() { this->SetLoadPrivateTags(false); } void ImageReaderBase ::GetPixelIDFromImageIO( const std::string &fileName, PixelIDValueType &outPixelType, unsigned int & outDimensions ) { itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName); this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions); } void ImageReaderBase ::GetPixelIDFromImageIO( const ImageIOBase *iobase, PixelIDValueType &outPixelType, unsigned int & outDimensions ) { // get output information about input image unsigned int dimension = iobase->GetNumberOfDimensions(); itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType(); itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType(); unsigned int numberOfComponents = iobase->GetNumberOfComponents(); outDimensions = dimension; if (numberOfComponents == 1 && ( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) ) { outPixelType = this->ExecuteInternalReadScalar( componentType ); return; } // we try to load anything else into a VectorImage else if (pixelType == itk::ImageIOBase::RGB || pixelType == itk::ImageIOBase::RGBA || pixelType == itk::ImageIOBase::VECTOR || pixelType == itk::ImageIOBase::COVARIANTVECTOR || pixelType == itk::ImageIOBase::FIXEDARRAY || pixelType == itk::ImageIOBase::POINT || pixelType == itk::ImageIOBase::OFFSET ) { outPixelType = this->ExecuteInternalReadVector( componentType ); return; } else if ( pixelType == itk::ImageIOBase::COMPLEX ) { outPixelType = this->ExecuteInternalReadComplex( componentType ); return; } else { sitkExceptionMacro( "Unknown PixelType: " << (int) componentType ); } sitkExceptionMacro( "Unable to load image." ); } unsigned int ImageReaderBase ::GetDimensionFromImageIO( const itk::ImageIOBase* iobase, unsigned int i) { return iobase->GetDimensions(i); } unsigned int ImageReaderBase ::GetDimensionFromImageIO(const std::string &filename, unsigned int i) { itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename); return this->GetDimensionFromImageIO(iobase.GetPointer(), i); } PixelIDValueType ImageReaderBase ::ExecuteInternalReadScalar( int componentType ) { const unsigned int UnusedDimension = 2; switch(componentType) { case itk::ImageIOBase::CHAR: return ImageTypeToPixelIDValue< itk::Image<int8_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UCHAR: return ImageTypeToPixelIDValue< itk::Image<uint8_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::SHORT: return ImageTypeToPixelIDValue< itk::Image<int16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::USHORT: return ImageTypeToPixelIDValue< itk::Image<uint16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::INT: return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UINT: return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONG: if (sizeof(long) == 4 ) return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONG: if (sizeof(unsigned long) == 4 ) return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::Image<uint64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONGLONG: return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONGLONG: return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::FLOAT: return ImageTypeToPixelIDValue< itk::Image<float, UnusedDimension> >::Result; break; case itk::ImageIOBase::DOUBLE: return ImageTypeToPixelIDValue< itk::Image<double, UnusedDimension> >::Result; break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: assert( false ); // should never get here unless we forgot a type sitkExceptionMacro( "Logic error!" ); } } PixelIDValueType ImageReaderBase ::ExecuteInternalReadComplex( int componentType ) { const unsigned int UnusedDimension = 2; switch(componentType) { case itk::ImageIOBase::FLOAT: return ImageTypeToPixelIDValue< itk::Image<std::complex<float>, UnusedDimension> >::Result; break; case itk::ImageIOBase::DOUBLE: return ImageTypeToPixelIDValue< itk::Image<std::complex<double>, UnusedDimension> >::Result; break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: sitkExceptionMacro( "Only Complex image with float and double are supported!" ); } } PixelIDValueType ImageReaderBase ::ExecuteInternalReadVector( int componentType ) { const unsigned int UnusedDimension = 2; switch(componentType) { case itk::ImageIOBase::CHAR: return ImageTypeToPixelIDValue< itk::VectorImage<int8_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UCHAR: return ImageTypeToPixelIDValue< itk::VectorImage<uint8_t , UnusedDimension> >::Result; break; case itk::ImageIOBase::SHORT: return ImageTypeToPixelIDValue< itk::VectorImage<int16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::USHORT: return ImageTypeToPixelIDValue< itk::VectorImage<uint16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::INT: return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UINT: return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONG: if (sizeof(long) == 4 ) return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONG: if (sizeof(unsigned long) == 4 ) return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONGLONG: return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONGLONG: return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::FLOAT: return ImageTypeToPixelIDValue< itk::VectorImage<float, UnusedDimension> >::Result; break; case itk::ImageIOBase::DOUBLE: return ImageTypeToPixelIDValue< itk::VectorImage<double, UnusedDimension> >::Result; break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: assert( false ); // should never get here unless we forgot a type sitkExceptionMacro( "Logic error!" ); } } } } <commit_msg>Improve error message with unexpected component type<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "sitkImageReaderBase.h" #include "sitkMacro.h" #include "sitkExceptionObject.h" #include <itksys/SystemTools.hxx> // Include the Transform IO here, so that the IO factory registration // will occur. #include <itkTransformFileReader.h> #include <itkTransformFileWriter.h> #include <string> #include <itkImage.h> #include <itkImageIOBase.h> #include <itkImageIOFactory.h> #include <itkGDCMImageIO.h> namespace itk { namespace simple { ImageReaderBase ::~ImageReaderBase() { } ImageReaderBase ::ImageReaderBase() : m_OutputPixelType(sitkUnknown), m_LoadPrivateTags(false) { } std::string ImageReaderBase ::ToString() const { std::ostringstream out; out << " OutputPixelType: "; this->ToStringHelper(out, this->m_OutputPixelType) << std::endl; out << " LoadPrivateTags: "; this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl; out << ProcessObject::ToString(); return out.str(); } itk::SmartPointer<ImageIOBase> ImageReaderBase ::GetImageIOBase(const std::string &fileName) { itk::ImageIOBase::Pointer iobase = itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode); if ( iobase.IsNull() ) { if ( !itksys::SystemTools::FileExists( fileName.c_str() ) ) { sitkExceptionMacro( "The file \"" << fileName << "\" does not exist." ); } if ( !bool(std::ifstream( fileName.c_str() )) ) { sitkExceptionMacro( "Unable to open \"" << fileName << "\" for reading." ); } sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" ); } // Try additional parameters GDCMImageIO *ioGDCMImage = dynamic_cast<GDCMImageIO*>(iobase.GetPointer()); if (ioGDCMImage) { ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags); } // Read the image information iobase->SetFileName( fileName ); iobase->ReadImageInformation(); return iobase; } ImageReaderBase::Self& ImageReaderBase ::SetOutputPixelType( PixelIDValueEnum pixelID ) { this->m_OutputPixelType = pixelID; return *this; } PixelIDValueEnum ImageReaderBase ::GetOutputPixelType( void ) const { return this->m_OutputPixelType; } ImageReaderBase::Self& ImageReaderBase ::SetLoadPrivateTags(bool loadPrivateTags) { this->m_LoadPrivateTags = loadPrivateTags; return *this; } bool ImageReaderBase ::GetLoadPrivateTags() const { return this->m_LoadPrivateTags; } void ImageReaderBase ::LoadPrivateTagsOn() { this->SetLoadPrivateTags(true); } void ImageReaderBase ::LoadPrivateTagsOff() { this->SetLoadPrivateTags(false); } void ImageReaderBase ::GetPixelIDFromImageIO( const std::string &fileName, PixelIDValueType &outPixelType, unsigned int & outDimensions ) { itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName); this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions); } void ImageReaderBase ::GetPixelIDFromImageIO( const ImageIOBase *iobase, PixelIDValueType &outPixelType, unsigned int & outDimensions ) { // get output information about input image unsigned int dimension = iobase->GetNumberOfDimensions(); itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType(); itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType(); unsigned int numberOfComponents = iobase->GetNumberOfComponents(); outDimensions = dimension; if (numberOfComponents == 1 && ( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) ) { outPixelType = this->ExecuteInternalReadScalar( componentType ); return; } // we try to load anything else into a VectorImage else if (pixelType == itk::ImageIOBase::RGB || pixelType == itk::ImageIOBase::RGBA || pixelType == itk::ImageIOBase::VECTOR || pixelType == itk::ImageIOBase::COVARIANTVECTOR || pixelType == itk::ImageIOBase::FIXEDARRAY || pixelType == itk::ImageIOBase::POINT || pixelType == itk::ImageIOBase::OFFSET ) { outPixelType = this->ExecuteInternalReadVector( componentType ); return; } else if ( pixelType == itk::ImageIOBase::COMPLEX ) { outPixelType = this->ExecuteInternalReadComplex( componentType ); return; } else { sitkExceptionMacro( "Unknown PixelType: " << itk::ImageIOBase::GetComponentTypeAsString(componentType) << "(" <<(int) componentType << ")" ); } sitkExceptionMacro( "Unable to load image." ); } unsigned int ImageReaderBase ::GetDimensionFromImageIO( const itk::ImageIOBase* iobase, unsigned int i) { return iobase->GetDimensions(i); } unsigned int ImageReaderBase ::GetDimensionFromImageIO(const std::string &filename, unsigned int i) { itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename); return this->GetDimensionFromImageIO(iobase.GetPointer(), i); } PixelIDValueType ImageReaderBase ::ExecuteInternalReadScalar( int componentType ) { const unsigned int UnusedDimension = 2; switch(componentType) { case itk::ImageIOBase::CHAR: return ImageTypeToPixelIDValue< itk::Image<int8_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UCHAR: return ImageTypeToPixelIDValue< itk::Image<uint8_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::SHORT: return ImageTypeToPixelIDValue< itk::Image<int16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::USHORT: return ImageTypeToPixelIDValue< itk::Image<uint16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::INT: return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UINT: return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONG: if (sizeof(long) == 4 ) return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONG: if (sizeof(unsigned long) == 4 ) return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::Image<uint64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONGLONG: return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONGLONG: return ImageTypeToPixelIDValue< itk::Image<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::FLOAT: return ImageTypeToPixelIDValue< itk::Image<float, UnusedDimension> >::Result; break; case itk::ImageIOBase::DOUBLE: return ImageTypeToPixelIDValue< itk::Image<double, UnusedDimension> >::Result; break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: assert( false ); // should never get here unless we forgot a type sitkExceptionMacro( "Logic error!" ); } } PixelIDValueType ImageReaderBase ::ExecuteInternalReadComplex( int componentType ) { const unsigned int UnusedDimension = 2; switch(componentType) { case itk::ImageIOBase::FLOAT: return ImageTypeToPixelIDValue< itk::Image<std::complex<float>, UnusedDimension> >::Result; break; case itk::ImageIOBase::DOUBLE: return ImageTypeToPixelIDValue< itk::Image<std::complex<double>, UnusedDimension> >::Result; break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: sitkExceptionMacro( "Only Complex image with float and double are supported!" ); } } PixelIDValueType ImageReaderBase ::ExecuteInternalReadVector( int componentType ) { const unsigned int UnusedDimension = 2; switch(componentType) { case itk::ImageIOBase::CHAR: return ImageTypeToPixelIDValue< itk::VectorImage<int8_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UCHAR: return ImageTypeToPixelIDValue< itk::VectorImage<uint8_t , UnusedDimension> >::Result; break; case itk::ImageIOBase::SHORT: return ImageTypeToPixelIDValue< itk::VectorImage<int16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::USHORT: return ImageTypeToPixelIDValue< itk::VectorImage<uint16_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::INT: return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::UINT: return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONG: if (sizeof(long) == 4 ) return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONG: if (sizeof(unsigned long) == 4 ) return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result; else return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::LONGLONG: return ImageTypeToPixelIDValue< itk::VectorImage<int64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::ULONGLONG: return ImageTypeToPixelIDValue< itk::VectorImage<uint64_t, UnusedDimension> >::Result; break; case itk::ImageIOBase::FLOAT: return ImageTypeToPixelIDValue< itk::VectorImage<float, UnusedDimension> >::Result; break; case itk::ImageIOBase::DOUBLE: return ImageTypeToPixelIDValue< itk::VectorImage<double, UnusedDimension> >::Result; break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: assert( false ); // should never get here unless we forgot a type sitkExceptionMacro( "Logic error!" ); } } } } <|endoftext|>
<commit_before>#include "blackmagicsdk_video_source.h" #include "deck_link_display_mode_detector.h" #include <chrono> namespace gg { VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK() : IVideoSource() , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(UYVY)) , _running(false) { // nop } VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index, ColourSpace colour) : IVideoSource(colour) , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data? , _deck_link(nullptr) , _deck_link_input(nullptr) , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D) , _12_bit_rgb_to_bgra_converter(nullptr) , _bgra_frame_buffers({nullptr, nullptr}) , _running(false) { // Pixel format, i.e. colour space BMDPixelFormat pixel_format; switch(_colour) { case UYVY: pixel_format = bmdFormat8BitYUV; break; case BGRA: pixel_format = bmdFormat8BitBGRA; break; case I420: default: bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces"); } // Get an iterator through the available DeckLink ports IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance(); if (deck_link_iterator == nullptr) bail("DeckLink drivers do not appear to be installed"); HRESULT res; // Get the desired DeckLink index (port) int idx = deck_link_index; while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK) { if (idx == 0) break; --idx; _deck_link->Release(); } if (deck_link_iterator != nullptr) deck_link_iterator->Release(); // No glory: release everything and throw exception if (res != S_OK or _deck_link == nullptr) bail( std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index)) ); // Get the input interface of connected DeckLink port res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input)); // No glory: release everything and throw exception if (res != S_OK) bail("Could not get the Blackmagic DeckLink input interface"); // Set the input format (i.e. display mode) BMDDisplayMode display_mode; std::string error_msg = ""; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg)) { _video_input_flags ^= bmdVideoInputDualStream3D; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg)) bail(error_msg); } // Set this object (IDeckLinkInputCallback instance) as callback res = _deck_link_input->SetCallback(this); // No glory: release everything and throw exception if (res != S_OK) bail("Could not set the callback of Blackmagic DeckLink device"); // Enable video input res = _deck_link_input->EnableVideoInput(display_mode, pixel_format, _video_input_flags); // No glory if (res != S_OK) bail("Could not enable video input of Blackmagic DeckLink device"); // Start streaming _running = true; res = _deck_link_input->StartStreams(); // No glory: release everything and throw exception if (res != S_OK) { _running = false; bail("Could not start streaming from the Blackmagic DeckLink device"); } if (_colour == BGRA) { _12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance(); if (_12_bit_rgb_to_bgra_converter == nullptr) bail("Could not create colour converter for Blackmagic source"); } } VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK() { { // Artificial scope for data lock // Make sure streamer thread not trying to access buffer std::lock_guard<std::mutex> data_lock_guard(_data_lock); _running = false; } // Stop streaming and disable enabled inputs _deck_link_input->SetCallback(nullptr); _deck_link_input->StopStreams(); _deck_link_input->DisableVideoInput(); // Release DeckLink members release_deck_link(); } bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height) { // Make sure only this thread is accessing the cols and rows members now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_cols <= 0 or _rows <= 0) return false; width = _cols; height = _rows; return true; } bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame) { if (frame.colour() != _colour) return false; // Make sure only this thread is accessing the video frame data now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer_length > 0 and _cols > 0 and _rows > 0) { frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows); return true; } else return false; } double VideoSourceBlackmagicSDK::get_frame_rate() { return _frame_rate; } void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height) { // issue #147 throw VideoSourceError("Blackmagic does not support cropping yet"); } void VideoSourceBlackmagicSDK::get_full_frame() { // nop: set_sub_frame currently not implemented } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv) { return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void) { __sync_add_and_fetch(&_n_ref, 1); return _n_ref; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void) { __sync_sub_and_fetch(&_n_ref, 1); return _n_ref; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged( BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode * display_mode, BMDDetectedVideoInputFormatFlags format_flags ) { // not supported yet: see issue #149 return S_OK; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived( IDeckLinkVideoInputFrame * video_frame, IDeckLinkAudioInputPacket * audio_packet ) { if (not _running) // nop if not running! return S_OK; // Not processing the audio packet, but only the video // frame for the time being if (video_frame == nullptr) // nop if no data return S_OK; // Nr. of bytes of received data size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight(); if (is_stereo()) n_bytes *= 2; { // Artificial scope for data lock // Make sure only this thread is accessing the buffer now std::lock_guard<std::mutex> data_lock_guard(_data_lock); // Extend buffer if more memory needed than already allocated if (n_bytes > _video_buffer_length) _video_buffer = reinterpret_cast<uint8_t *>( realloc(_video_buffer, n_bytes * sizeof(uint8_t)) ); if (_video_buffer == nullptr) // something's terribly wrong! // nop if something's terribly wrong! return S_OK; // Get the new data into the buffer HRESULT res = video_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer) ); // If data could not be read into the buffer, return if (FAILED(res)) return res; if (is_stereo()) { IDeckLinkVideoFrame *right_eye_frame = nullptr; IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr; if ((video_frame->QueryInterface( IID_IDeckLinkVideoFrame3DExtensions, (void **) &three_d_extensions) != S_OK) || (three_d_extensions->GetFrameForRightEye( &right_eye_frame) != S_OK)) { right_eye_frame = nullptr; } if (three_d_extensions != nullptr) three_d_extensions->Release(); if (right_eye_frame != nullptr) { res = right_eye_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer[n_bytes / 2]) ); right_eye_frame->Release(); // If data could not be read into the buffer, return if (FAILED(res)) return res; } } // Set video frame specs according to new data _video_buffer_length = n_bytes; _cols = video_frame->GetWidth(); _rows = video_frame->GetHeight(); // Propagate new video frame to observers _buffer_video_frame.init_from_specs( _video_buffer, _video_buffer_length, _cols, _rows, is_stereo() ? 2 : 1 ); } this->notify(_buffer_video_frame); // Everything went fine, return success return S_OK; } void VideoSourceBlackmagicSDK::release_deck_link() noexcept { if (_deck_link_input != nullptr) { _deck_link_input->Release(); _deck_link_input = nullptr; } if (_deck_link != nullptr) _deck_link->Release(); } bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format, BMDVideoInputFlags & video_input_flags, BMDDisplayMode & display_mode, double & frame_rate, std::string & error_msg) noexcept { std::vector<BMDDisplayMode> display_modes = { bmdModeHD1080p6000, bmdModeHD1080p5994, bmdModeHD1080p50, bmdModeHD1080p30, bmdModeHD1080p2997, bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398, bmdModeHD1080i6000, bmdModeHD1080i5994, bmdModeHD1080i50, bmdModeHD720p60, bmdModeHD720p5994, bmdModeHD720p50, bmdMode4K2160p60, bmdMode4K2160p5994, bmdMode4K2160p50, bmdMode4K2160p30, bmdMode4K2160p2997, bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398, bmdMode2k25, bmdMode2k24, bmdMode2k2398, }; DeckLinkDisplayModeDetector detector( _deck_link_input, display_modes, pixel_format, video_input_flags ); BMDDisplayMode display_mode_ = detector.get_display_mode(); if (display_mode_ != bmdModeUnknown) { frame_rate = detector.get_frame_rate(); display_mode = display_mode_; video_input_flags = detector.get_video_input_flags(); return true; } else { error_msg = detector.get_error_msg(); return false; } } } <commit_msg>Issue #30: releasing DeckLink converter upon destruction<commit_after>#include "blackmagicsdk_video_source.h" #include "deck_link_display_mode_detector.h" #include <chrono> namespace gg { VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK() : IVideoSource() , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(UYVY)) , _running(false) { // nop } VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index, ColourSpace colour) : IVideoSource(colour) , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data? , _deck_link(nullptr) , _deck_link_input(nullptr) , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D) , _12_bit_rgb_to_bgra_converter(nullptr) , _bgra_frame_buffers({nullptr, nullptr}) , _running(false) { // Pixel format, i.e. colour space BMDPixelFormat pixel_format; switch(_colour) { case UYVY: pixel_format = bmdFormat8BitYUV; break; case BGRA: pixel_format = bmdFormat8BitBGRA; break; case I420: default: bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces"); } // Get an iterator through the available DeckLink ports IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance(); if (deck_link_iterator == nullptr) bail("DeckLink drivers do not appear to be installed"); HRESULT res; // Get the desired DeckLink index (port) int idx = deck_link_index; while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK) { if (idx == 0) break; --idx; _deck_link->Release(); } if (deck_link_iterator != nullptr) deck_link_iterator->Release(); // No glory: release everything and throw exception if (res != S_OK or _deck_link == nullptr) bail( std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index)) ); // Get the input interface of connected DeckLink port res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input)); // No glory: release everything and throw exception if (res != S_OK) bail("Could not get the Blackmagic DeckLink input interface"); // Set the input format (i.e. display mode) BMDDisplayMode display_mode; std::string error_msg = ""; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg)) { _video_input_flags ^= bmdVideoInputDualStream3D; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, error_msg)) bail(error_msg); } // Set this object (IDeckLinkInputCallback instance) as callback res = _deck_link_input->SetCallback(this); // No glory: release everything and throw exception if (res != S_OK) bail("Could not set the callback of Blackmagic DeckLink device"); // Enable video input res = _deck_link_input->EnableVideoInput(display_mode, pixel_format, _video_input_flags); // No glory if (res != S_OK) bail("Could not enable video input of Blackmagic DeckLink device"); // Start streaming _running = true; res = _deck_link_input->StartStreams(); // No glory: release everything and throw exception if (res != S_OK) { _running = false; bail("Could not start streaming from the Blackmagic DeckLink device"); } if (_colour == BGRA) { _12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance(); if (_12_bit_rgb_to_bgra_converter == nullptr) bail("Could not create colour converter for Blackmagic source"); } } VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK() { { // Artificial scope for data lock // Make sure streamer thread not trying to access buffer std::lock_guard<std::mutex> data_lock_guard(_data_lock); _running = false; } // Stop streaming and disable enabled inputs _deck_link_input->SetCallback(nullptr); _deck_link_input->StopStreams(); _deck_link_input->DisableVideoInput(); // Release DeckLink members release_deck_link(); } bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height) { // Make sure only this thread is accessing the cols and rows members now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_cols <= 0 or _rows <= 0) return false; width = _cols; height = _rows; return true; } bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame) { if (frame.colour() != _colour) return false; // Make sure only this thread is accessing the video frame data now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer_length > 0 and _cols > 0 and _rows > 0) { frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows); return true; } else return false; } double VideoSourceBlackmagicSDK::get_frame_rate() { return _frame_rate; } void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height) { // issue #147 throw VideoSourceError("Blackmagic does not support cropping yet"); } void VideoSourceBlackmagicSDK::get_full_frame() { // nop: set_sub_frame currently not implemented } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv) { return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void) { __sync_add_and_fetch(&_n_ref, 1); return _n_ref; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void) { __sync_sub_and_fetch(&_n_ref, 1); return _n_ref; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged( BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode * display_mode, BMDDetectedVideoInputFormatFlags format_flags ) { // not supported yet: see issue #149 return S_OK; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived( IDeckLinkVideoInputFrame * video_frame, IDeckLinkAudioInputPacket * audio_packet ) { if (not _running) // nop if not running! return S_OK; // Not processing the audio packet, but only the video // frame for the time being if (video_frame == nullptr) // nop if no data return S_OK; // Nr. of bytes of received data size_t n_bytes = video_frame->GetRowBytes() * video_frame->GetHeight(); if (is_stereo()) n_bytes *= 2; { // Artificial scope for data lock // Make sure only this thread is accessing the buffer now std::lock_guard<std::mutex> data_lock_guard(_data_lock); // Extend buffer if more memory needed than already allocated if (n_bytes > _video_buffer_length) _video_buffer = reinterpret_cast<uint8_t *>( realloc(_video_buffer, n_bytes * sizeof(uint8_t)) ); if (_video_buffer == nullptr) // something's terribly wrong! // nop if something's terribly wrong! return S_OK; // Get the new data into the buffer HRESULT res = video_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer) ); // If data could not be read into the buffer, return if (FAILED(res)) return res; if (is_stereo()) { IDeckLinkVideoFrame *right_eye_frame = nullptr; IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr; if ((video_frame->QueryInterface( IID_IDeckLinkVideoFrame3DExtensions, (void **) &three_d_extensions) != S_OK) || (three_d_extensions->GetFrameForRightEye( &right_eye_frame) != S_OK)) { right_eye_frame = nullptr; } if (three_d_extensions != nullptr) three_d_extensions->Release(); if (right_eye_frame != nullptr) { res = right_eye_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer[n_bytes / 2]) ); right_eye_frame->Release(); // If data could not be read into the buffer, return if (FAILED(res)) return res; } } // Set video frame specs according to new data _video_buffer_length = n_bytes; _cols = video_frame->GetWidth(); _rows = video_frame->GetHeight(); // Propagate new video frame to observers _buffer_video_frame.init_from_specs( _video_buffer, _video_buffer_length, _cols, _rows, is_stereo() ? 2 : 1 ); } this->notify(_buffer_video_frame); // Everything went fine, return success return S_OK; } void VideoSourceBlackmagicSDK::release_deck_link() noexcept { if (_deck_link_input != nullptr) { _deck_link_input->Release(); _deck_link_input = nullptr; } if (_deck_link != nullptr) _deck_link->Release(); if (_12_bit_rgb_to_bgra_converter != nullptr) { _12_bit_rgb_to_bgra_converter->Release(); _12_bit_rgb_to_bgra_converter = nullptr; } } bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format, BMDVideoInputFlags & video_input_flags, BMDDisplayMode & display_mode, double & frame_rate, std::string & error_msg) noexcept { std::vector<BMDDisplayMode> display_modes = { bmdModeHD1080p6000, bmdModeHD1080p5994, bmdModeHD1080p50, bmdModeHD1080p30, bmdModeHD1080p2997, bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398, bmdModeHD1080i6000, bmdModeHD1080i5994, bmdModeHD1080i50, bmdModeHD720p60, bmdModeHD720p5994, bmdModeHD720p50, bmdMode4K2160p60, bmdMode4K2160p5994, bmdMode4K2160p50, bmdMode4K2160p30, bmdMode4K2160p2997, bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398, bmdMode2k25, bmdMode2k24, bmdMode2k2398, }; DeckLinkDisplayModeDetector detector( _deck_link_input, display_modes, pixel_format, video_input_flags ); BMDDisplayMode display_mode_ = detector.get_display_mode(); if (display_mode_ != bmdModeUnknown) { frame_rate = detector.get_frame_rate(); display_mode = display_mode_; video_input_flags = detector.get_video_input_flags(); return true; } else { error_msg = detector.get_error_msg(); return false; } } } <|endoftext|>
<commit_before>//===-- TestCompletion.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Utility/StringList.h" #include "lldb/Utility/TildeExpressionResolver.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "TestingSupport/MockTildeExpressionResolver.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" namespace fs = llvm::sys::fs; namespace path = llvm::sys::path; using namespace llvm; using namespace lldb_private; #define ASSERT_NO_ERROR(x) \ if (std::error_code ASSERT_NO_ERROR_ec = x) { \ SmallString<128> MessageStorage; \ raw_svector_ostream Message(MessageStorage); \ Message << #x ": did not return errc::success.\n" \ << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \ << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \ GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \ } else { \ } namespace { class CompletionTest : public testing::Test { protected: /// Unique temporary directory in which all created filesystem entities must /// be placed. It is removed at the end of the test suite. SmallString<128> BaseDir; /// The working directory that we got when starting the test. Every test /// should chdir into this directory first because some tests maybe chdir /// into another one during their run. static SmallString<128> OriginalWorkingDir; SmallString<128> DirFoo; SmallString<128> DirFooA; SmallString<128> DirFooB; SmallString<128> DirFooC; SmallString<128> DirBar; SmallString<128> DirBaz; SmallString<128> DirTestFolder; SmallString<128> DirNested; SmallString<128> FileAA; SmallString<128> FileAB; SmallString<128> FileAC; SmallString<128> FileFoo; SmallString<128> FileBar; SmallString<128> FileBaz; void SetUp() override { // chdir back into the original working dir this test binary started with. // A previous test may have have changed the working dir. ASSERT_NO_ERROR(fs::set_current_path(OriginalWorkingDir)); // Get the name of the current test. To prevent that by chance two tests // get the same temporary directory if createUniqueDirectory fails. auto test_info = ::testing::UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(test_info != nullptr); std::string name = test_info->name(); ASSERT_NO_ERROR(fs::createUniqueDirectory("FsCompletion-" + name, BaseDir)); const char *DirNames[] = {"foo", "fooa", "foob", "fooc", "bar", "baz", "test_folder", "foo/nested"}; const char *FileNames[] = {"aa1234.tmp", "ab1234.tmp", "ac1234.tmp", "foo1234.tmp", "bar1234.tmp", "baz1234.tmp"}; SmallString<128> *Dirs[] = {&DirFoo, &DirFooA, &DirFooB, &DirFooC, &DirBar, &DirBaz, &DirTestFolder, &DirNested}; for (auto Dir : llvm::zip(DirNames, Dirs)) { auto &Path = *std::get<1>(Dir); Path = BaseDir; path::append(Path, std::get<0>(Dir)); ASSERT_NO_ERROR(fs::create_directories(Path)); } SmallString<128> *Files[] = {&FileAA, &FileAB, &FileAC, &FileFoo, &FileBar, &FileBaz}; for (auto File : llvm::zip(FileNames, Files)) { auto &Path = *std::get<1>(File); Path = BaseDir; path::append(Path, std::get<0>(File)); int FD; ASSERT_NO_ERROR(fs::createUniqueFile(Path, FD, Path)); ::close(FD); } } static void SetUpTestCase() { ASSERT_NO_ERROR(fs::current_path(OriginalWorkingDir)); } void TearDown() override { ASSERT_NO_ERROR(fs::remove_directories(BaseDir)); } static bool HasEquivalentFile(const Twine &Path, const StringList &Paths) { for (size_t I = 0; I < Paths.GetSize(); ++I) { if (fs::equivalent(Path, Paths[I])) return true; } return false; } void DoDirCompletions(const Twine &Prefix, StandardTildeExpressionResolver &Resolver, StringList &Results) { // When a partial name matches, it returns all matches. If it matches both // a full name AND some partial names, it returns all of them. uint32_t Count = CommandCompletions::DiskDirectories(Prefix + "foo", Results, Resolver); ASSERT_EQ(4u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); // If it matches only partial names, it still works as expected. Count = CommandCompletions::DiskDirectories(Twine(Prefix) + "b", Results, Resolver); ASSERT_EQ(2u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirBar, Results)); EXPECT_TRUE(HasEquivalentFile(DirBaz, Results)); } }; SmallString<128> CompletionTest::OriginalWorkingDir; } static std::vector<std::string> toVector(const StringList &SL) { std::vector<std::string> Result; for (size_t Idx = 0; Idx < SL.GetSize(); ++Idx) Result.push_back(SL[Idx]); return Result; } using testing::UnorderedElementsAre; TEST_F(CompletionTest, DirCompletionAbsolute) { // All calls to DiskDirectories() return only directories, even when // there are files which also match. The tests below all check this // by asserting an exact result count, and verifying against known // folders. std::string Prefixes[] = {(Twine(BaseDir) + "/").str(), ""}; StandardTildeExpressionResolver Resolver; StringList Results; // When a directory is specified that doesn't end in a slash, it searches // for that directory, not items under it. size_t Count = CommandCompletions::DiskDirectories(BaseDir, Results, Resolver); ASSERT_EQ(1u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(BaseDir, Results)); // When the same directory ends with a slash, it finds all children. Count = CommandCompletions::DiskDirectories(Prefixes[0], Results, Resolver); ASSERT_EQ(7u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); EXPECT_TRUE(HasEquivalentFile(DirBar, Results)); EXPECT_TRUE(HasEquivalentFile(DirBaz, Results)); EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results)); DoDirCompletions(Twine(BaseDir) + "/", Resolver, Results); llvm::sys::fs::set_current_path(BaseDir); DoDirCompletions("", Resolver, Results); } TEST_F(CompletionTest, FileCompletionAbsolute) { // All calls to DiskFiles() return both files and directories The tests below // all check this by asserting an exact result count, and verifying against // known folders. StandardTildeExpressionResolver Resolver; StringList Results; // When an item is specified that doesn't end in a slash but exactly matches // one item, it returns that item. size_t Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/fooa", Results, Resolver); ASSERT_EQ(1u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); // The previous check verified a directory match. But it should work for // files too. Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/aa", Results, Resolver); ASSERT_EQ(1u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(FileAA, Results)); // When it ends with a slash, it should find all files and directories. Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/", Results, Resolver); ASSERT_EQ(13u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); EXPECT_TRUE(HasEquivalentFile(DirBar, Results)); EXPECT_TRUE(HasEquivalentFile(DirBaz, Results)); EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results)); EXPECT_TRUE(HasEquivalentFile(FileAA, Results)); EXPECT_TRUE(HasEquivalentFile(FileAB, Results)); EXPECT_TRUE(HasEquivalentFile(FileAC, Results)); EXPECT_TRUE(HasEquivalentFile(FileFoo, Results)); EXPECT_TRUE(HasEquivalentFile(FileBar, Results)); EXPECT_TRUE(HasEquivalentFile(FileBaz, Results)); // When a partial name matches, it returns all file & directory matches. Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/foo", Results, Resolver); ASSERT_EQ(5u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); EXPECT_TRUE(HasEquivalentFile(FileFoo, Results)); } TEST_F(CompletionTest, DirCompletionUsername) { MockTildeExpressionResolver Resolver("James", BaseDir); Resolver.AddKnownUser("Kirk", DirFooB); Resolver.AddKnownUser("Lars", DirFooC); Resolver.AddKnownUser("Jason", DirFoo); Resolver.AddKnownUser("Larry", DirFooA); std::string sep = path::get_separator(); // Just resolving current user's home directory by itself should return the // directory. StringList Results; size_t Count = CommandCompletions::DiskDirectories("~", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~" + sep)); // With a slash appended, it should return all items in the directory. Count = CommandCompletions::DiskDirectories("~/", Results, Resolver); EXPECT_THAT(toVector(Results), UnorderedElementsAre( "~/foo" + sep, "~/fooa" + sep, "~/foob" + sep, "~/fooc" + sep, "~/bar" + sep, "~/baz" + sep, "~/test_folder" + sep)); EXPECT_EQ(Count, Results.GetSize()); // Check that we can complete directories in nested paths Count = CommandCompletions::DiskDirectories("~/foo/", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~/foo/nested" + sep)); Count = CommandCompletions::DiskDirectories("~/foo/nes", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~/foo/nested" + sep)); // With ~username syntax it should return one match if there is an exact // match. It shouldn't translate to the actual directory, it should keep the // form the user typed. Count = CommandCompletions::DiskDirectories("~Lars", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~Lars" + sep)); // But with a username that is not found, no results are returned. Count = CommandCompletions::DiskDirectories("~Dave", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre()); // And if there are multiple matches, it should return all of them. Count = CommandCompletions::DiskDirectories("~La", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~Lars" + sep, "~Larry" + sep)); } <commit_msg>Add more pre-run asserts for the DirCompletionAbsolute test<commit_after>//===-- TestCompletion.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Utility/StringList.h" #include "lldb/Utility/TildeExpressionResolver.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "TestingSupport/MockTildeExpressionResolver.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" namespace fs = llvm::sys::fs; namespace path = llvm::sys::path; using namespace llvm; using namespace lldb_private; #define ASSERT_NO_ERROR(x) \ if (std::error_code ASSERT_NO_ERROR_ec = x) { \ SmallString<128> MessageStorage; \ raw_svector_ostream Message(MessageStorage); \ Message << #x ": did not return errc::success.\n" \ << "error number: " << ASSERT_NO_ERROR_ec.value() << "\n" \ << "error message: " << ASSERT_NO_ERROR_ec.message() << "\n"; \ GTEST_FATAL_FAILURE_(MessageStorage.c_str()); \ } else { \ } namespace { class CompletionTest : public testing::Test { protected: /// Unique temporary directory in which all created filesystem entities must /// be placed. It is removed at the end of the test suite. SmallString<128> BaseDir; /// The working directory that we got when starting the test. Every test /// should chdir into this directory first because some tests maybe chdir /// into another one during their run. static SmallString<128> OriginalWorkingDir; SmallString<128> DirFoo; SmallString<128> DirFooA; SmallString<128> DirFooB; SmallString<128> DirFooC; SmallString<128> DirBar; SmallString<128> DirBaz; SmallString<128> DirTestFolder; SmallString<128> DirNested; SmallString<128> FileAA; SmallString<128> FileAB; SmallString<128> FileAC; SmallString<128> FileFoo; SmallString<128> FileBar; SmallString<128> FileBaz; void SetUp() override { // chdir back into the original working dir this test binary started with. // A previous test may have have changed the working dir. ASSERT_NO_ERROR(fs::set_current_path(OriginalWorkingDir)); // Get the name of the current test. To prevent that by chance two tests // get the same temporary directory if createUniqueDirectory fails. auto test_info = ::testing::UnitTest::GetInstance()->current_test_info(); ASSERT_TRUE(test_info != nullptr); std::string name = test_info->name(); ASSERT_NO_ERROR(fs::createUniqueDirectory("FsCompletion-" + name, BaseDir)); const char *DirNames[] = {"foo", "fooa", "foob", "fooc", "bar", "baz", "test_folder", "foo/nested"}; const char *FileNames[] = {"aa1234.tmp", "ab1234.tmp", "ac1234.tmp", "foo1234.tmp", "bar1234.tmp", "baz1234.tmp"}; SmallString<128> *Dirs[] = {&DirFoo, &DirFooA, &DirFooB, &DirFooC, &DirBar, &DirBaz, &DirTestFolder, &DirNested}; for (auto Dir : llvm::zip(DirNames, Dirs)) { auto &Path = *std::get<1>(Dir); Path = BaseDir; path::append(Path, std::get<0>(Dir)); ASSERT_NO_ERROR(fs::create_directories(Path)); } SmallString<128> *Files[] = {&FileAA, &FileAB, &FileAC, &FileFoo, &FileBar, &FileBaz}; for (auto File : llvm::zip(FileNames, Files)) { auto &Path = *std::get<1>(File); Path = BaseDir; path::append(Path, std::get<0>(File)); int FD; ASSERT_NO_ERROR(fs::createUniqueFile(Path, FD, Path)); ::close(FD); } } static void SetUpTestCase() { ASSERT_NO_ERROR(fs::current_path(OriginalWorkingDir)); } void TearDown() override { ASSERT_NO_ERROR(fs::remove_directories(BaseDir)); } static bool HasEquivalentFile(const Twine &Path, const StringList &Paths) { for (size_t I = 0; I < Paths.GetSize(); ++I) { if (fs::equivalent(Path, Paths[I])) return true; } return false; } void DoDirCompletions(const Twine &Prefix, StandardTildeExpressionResolver &Resolver, StringList &Results) { // When a partial name matches, it returns all matches. If it matches both // a full name AND some partial names, it returns all of them. uint32_t Count = CommandCompletions::DiskDirectories(Prefix + "foo", Results, Resolver); ASSERT_EQ(4u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); // If it matches only partial names, it still works as expected. Count = CommandCompletions::DiskDirectories(Twine(Prefix) + "b", Results, Resolver); ASSERT_EQ(2u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirBar, Results)); EXPECT_TRUE(HasEquivalentFile(DirBaz, Results)); } }; SmallString<128> CompletionTest::OriginalWorkingDir; } static std::vector<std::string> toVector(const StringList &SL) { std::vector<std::string> Result; for (size_t Idx = 0; Idx < SL.GetSize(); ++Idx) Result.push_back(SL[Idx]); return Result; } using testing::UnorderedElementsAre; TEST_F(CompletionTest, DirCompletionAbsolute) { // All calls to DiskDirectories() return only directories, even when // there are files which also match. The tests below all check this // by asserting an exact result count, and verifying against known // folders. std::string Prefixes[] = {(Twine(BaseDir) + "/").str(), ""}; StandardTildeExpressionResolver Resolver; StringList Results; // When a directory is specified that doesn't end in a slash, it searches // for that directory, not items under it. // Sanity check that the path we complete on exists and isn't too long. ASSERT_TRUE(llvm::sys::fs::exists(BaseDir)); ASSERT_LE(BaseDir.size(), static_cast<size_t>(PATH_MAX)); size_t Count = CommandCompletions::DiskDirectories(BaseDir, Results, Resolver); ASSERT_EQ(1u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(BaseDir, Results)); // When the same directory ends with a slash, it finds all children. Count = CommandCompletions::DiskDirectories(Prefixes[0], Results, Resolver); ASSERT_EQ(7u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); EXPECT_TRUE(HasEquivalentFile(DirBar, Results)); EXPECT_TRUE(HasEquivalentFile(DirBaz, Results)); EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results)); DoDirCompletions(Twine(BaseDir) + "/", Resolver, Results); llvm::sys::fs::set_current_path(BaseDir); DoDirCompletions("", Resolver, Results); } TEST_F(CompletionTest, FileCompletionAbsolute) { // All calls to DiskFiles() return both files and directories The tests below // all check this by asserting an exact result count, and verifying against // known folders. StandardTildeExpressionResolver Resolver; StringList Results; // When an item is specified that doesn't end in a slash but exactly matches // one item, it returns that item. size_t Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/fooa", Results, Resolver); ASSERT_EQ(1u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); // The previous check verified a directory match. But it should work for // files too. Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/aa", Results, Resolver); ASSERT_EQ(1u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(FileAA, Results)); // When it ends with a slash, it should find all files and directories. Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/", Results, Resolver); ASSERT_EQ(13u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); EXPECT_TRUE(HasEquivalentFile(DirBar, Results)); EXPECT_TRUE(HasEquivalentFile(DirBaz, Results)); EXPECT_TRUE(HasEquivalentFile(DirTestFolder, Results)); EXPECT_TRUE(HasEquivalentFile(FileAA, Results)); EXPECT_TRUE(HasEquivalentFile(FileAB, Results)); EXPECT_TRUE(HasEquivalentFile(FileAC, Results)); EXPECT_TRUE(HasEquivalentFile(FileFoo, Results)); EXPECT_TRUE(HasEquivalentFile(FileBar, Results)); EXPECT_TRUE(HasEquivalentFile(FileBaz, Results)); // When a partial name matches, it returns all file & directory matches. Count = CommandCompletions::DiskFiles(Twine(BaseDir) + "/foo", Results, Resolver); ASSERT_EQ(5u, Count); ASSERT_EQ(Count, Results.GetSize()); EXPECT_TRUE(HasEquivalentFile(DirFoo, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooA, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooB, Results)); EXPECT_TRUE(HasEquivalentFile(DirFooC, Results)); EXPECT_TRUE(HasEquivalentFile(FileFoo, Results)); } TEST_F(CompletionTest, DirCompletionUsername) { MockTildeExpressionResolver Resolver("James", BaseDir); Resolver.AddKnownUser("Kirk", DirFooB); Resolver.AddKnownUser("Lars", DirFooC); Resolver.AddKnownUser("Jason", DirFoo); Resolver.AddKnownUser("Larry", DirFooA); std::string sep = path::get_separator(); // Just resolving current user's home directory by itself should return the // directory. StringList Results; size_t Count = CommandCompletions::DiskDirectories("~", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~" + sep)); // With a slash appended, it should return all items in the directory. Count = CommandCompletions::DiskDirectories("~/", Results, Resolver); EXPECT_THAT(toVector(Results), UnorderedElementsAre( "~/foo" + sep, "~/fooa" + sep, "~/foob" + sep, "~/fooc" + sep, "~/bar" + sep, "~/baz" + sep, "~/test_folder" + sep)); EXPECT_EQ(Count, Results.GetSize()); // Check that we can complete directories in nested paths Count = CommandCompletions::DiskDirectories("~/foo/", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~/foo/nested" + sep)); Count = CommandCompletions::DiskDirectories("~/foo/nes", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~/foo/nested" + sep)); // With ~username syntax it should return one match if there is an exact // match. It shouldn't translate to the actual directory, it should keep the // form the user typed. Count = CommandCompletions::DiskDirectories("~Lars", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~Lars" + sep)); // But with a username that is not found, no results are returned. Count = CommandCompletions::DiskDirectories("~Dave", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre()); // And if there are multiple matches, it should return all of them. Count = CommandCompletions::DiskDirectories("~La", Results, Resolver); EXPECT_EQ(Count, Results.GetSize()); EXPECT_THAT(toVector(Results), UnorderedElementsAre("~Lars" + sep, "~Larry" + sep)); } <|endoftext|>
<commit_before>#include "CommonFoundation.h" #include "CommonMeshUtilities.h" #include "CommonLog.h" #include "CommonProfiler.h" bool isAlembicMeshValid( Alembic::AbcGeom::IObject *pIObj ) { //ESS_PROFILE_FUNC(); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } if(!objMesh.valid() && !objSubD.valid()) { return false; } return true; } bool isAlembicMeshNormals( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) { //ESS_PROFILE_FUNC(); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); if( objMesh.getSchema().getNormalsParam().valid() ) { isConstant = objMesh.getSchema().getNormalsParam().isConstant(); return true; } } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } isConstant = true; return false; } bool isAlembicMeshPositions( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) { ESS_PROFILE_SCOPE("isAlembicMeshPositions"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); isConstant = objMesh.getSchema().getPositionsProperty().isConstant(); return true; } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); isConstant = objSubD.getSchema().getPositionsProperty().isConstant(); return true; } isConstant = true; return false; } bool isAlembicMeshUVWs( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) { ESS_PROFILE_SCOPE("isAlembicMeshUVWs"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); if( objMesh.getSchema().getUVsParam().valid() ) { isConstant = objMesh.getSchema().getUVsParam().isConstant(); return true; } } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); if( objSubD.getSchema().getUVsParam().valid() ) { isConstant = objSubD.getSchema().getUVsParam().isConstant(); return true; } } isConstant = true; return false; } bool isAlembicMeshTopoDynamic( Alembic::AbcGeom::IObject *pIObj ) { ESS_PROFILE_SCOPE("isAlembicMeshTopoDynamic"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } Alembic::AbcGeom::IPolyMeshSchema::Sample polyMeshSample; Alembic::AbcGeom::ISubDSchema::Sample subDSample; bool hasDynamicTopo = false; if(objMesh.valid()) { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),".faceCounts"); if(faceCountProp.valid()) { hasDynamicTopo = !faceCountProp.isConstant(); } } else { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),".faceCounts"); if(faceCountProp.valid()) { hasDynamicTopo = !faceCountProp.isConstant(); } } return hasDynamicTopo; } bool isAlembicMeshPointCache( Alembic::AbcGeom::IObject *pIObj ) { ESS_PROFILE_SCOPE("isAlembicMeshPointCache"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } Alembic::AbcGeom::IPolyMeshSchema::Sample polyMeshSample; Alembic::AbcGeom::ISubDSchema::Sample subDSample; bool isPointCache = false; if(objMesh.valid()) { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),".faceCounts"); if( ! faceCountProp.valid() ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),".P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } else if( faceCountProp.isConstant() ) { Alembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue(); // the first is our preferred method, the second check here is Helge's method that is now considered obsolete if( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),".P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } } } else { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),".faceCounts"); if( ! faceCountProp.valid() ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),".P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } else if( faceCountProp.isConstant() ) { Alembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue(); // the first is our preferred method, the second check here is Helge's method that is now considered obsolete if( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objSubD.getSchema(),".P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } } } return isPointCache; } struct edge { int a; int b; bool operator<( const edge& rEdge ) const { if(a < rEdge.a) return true; if(a > rEdge.a) return false; if(b < rEdge.b) return true; return false; } }; struct edgeData { bool bReversed; int count; int face; edgeData():bReversed(false), count(1), face(-1) {} }; int validateAlembicMeshTopo(std::vector<Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t> faceCounts, std::vector<Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t> faceIndices, const std::string& meshName) { std::map<edge, edgeData> edgeToCountMap; typedef std::map<edge, edgeData>::iterator iterator; int meshErrors = 0; int faceOffset = 0; for(int i=0; i<faceCounts.size(); i++){ int count = faceCounts[i]; std::vector<int> occurences; occurences.reserve(count); Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t* v = &faceIndices[faceOffset]; for(int j=0; j<count; j++){ occurences.push_back(v[j]); } std::sort(occurences.begin(), occurences.end()); for(int j=0; j<occurences.size()-1; j++){ if(occurences[j] == occurences[j+1]){ ESS_LOG_WARNING("Error in mesh \""<<meshName<<"\". Vertex "<<occurences[j]<<" of face "<<i<<" is duplicated."); meshErrors ++; } } for(int j=0; j<count-1; j++){ edge e; e.a = v[j]; e.b = v[j+1]; if( e.a == e.b ){ //the duplicate vertices check already covers this case. //ESS_LOG_WARNING("edge ("<<e.a<<", "<<e.b<<") is degenerate."); continue; } edgeData eData; eData.face = i; if(e.b < e.a){ std::swap(e.a, e.b); eData.bReversed = true; } if( edgeToCountMap.find(e) == edgeToCountMap.end() ){ edgeToCountMap[e] = eData; } else{ edgeData eData2 = edgeToCountMap[e]; eData2.count++; if( (eData.bReversed && eData2.bReversed) || (!eData.bReversed && !eData2.bReversed) ){ ESS_LOG_WARNING("Error in mesh \""<<meshName<<"\". Edge ("<<e.a<<", "<<e.b<<") is shared between polygons "<<eData.face<<" and "<<eData2.face<<", and these polygons have reversed orderings."); meshErrors ++; } } } faceOffset += count; } return meshErrors; }<commit_msg>fixed #23<commit_after>#include "CommonFoundation.h" #include "CommonMeshUtilities.h" #include "CommonLog.h" #include "CommonProfiler.h" bool isAlembicMeshValid( Alembic::AbcGeom::IObject *pIObj ) { //ESS_PROFILE_FUNC(); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } if(!objMesh.valid() && !objSubD.valid()) { return false; } return true; } bool isAlembicMeshNormals( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) { //ESS_PROFILE_FUNC(); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); if( objMesh.valid() ) { if( objMesh.getSchema().getNormalsParam().valid() ) { isConstant = objMesh.getSchema().getNormalsParam().isConstant(); return true; } } } isConstant = true; return false; } bool isAlembicMeshPositions( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) { ESS_PROFILE_SCOPE("isAlembicMeshPositions"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); if( objMesh.valid() ) { isConstant = objMesh.getSchema().getPositionsProperty().isConstant(); return true; } } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); if( objSubD.valid() ) { isConstant = objSubD.getSchema().getPositionsProperty().isConstant(); return true; } } isConstant = true; return false; } bool isAlembicMeshUVWs( Alembic::AbcGeom::IObject *pIObj, bool& isConstant ) { ESS_PROFILE_SCOPE("isAlembicMeshUVWs"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); if( objMesh.valid() ) { if( objMesh.getSchema().getUVsParam().valid() ) { isConstant = objMesh.getSchema().getUVsParam().isConstant(); return true; } } } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); if( objSubD.valid() ) { if( objSubD.getSchema().getUVsParam().valid() ) { isConstant = objSubD.getSchema().getUVsParam().isConstant(); return true; } } } isConstant = true; return false; } bool isAlembicMeshTopoDynamic( Alembic::AbcGeom::IObject *pIObj ) { ESS_PROFILE_SCOPE("isAlembicMeshTopoDynamic"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } Alembic::AbcGeom::IPolyMeshSchema::Sample polyMeshSample; Alembic::AbcGeom::ISubDSchema::Sample subDSample; bool hasDynamicTopo = false; if(objMesh.valid()) { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),".faceCounts"); if(faceCountProp.valid()) { hasDynamicTopo = !faceCountProp.isConstant(); } } else if( subDSample.valid() ) { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),".faceCounts"); if(faceCountProp.valid()) { hasDynamicTopo = !faceCountProp.isConstant(); } } return hasDynamicTopo; } bool isAlembicMeshPointCache( Alembic::AbcGeom::IObject *pIObj ) { ESS_PROFILE_SCOPE("isAlembicMeshPointCache"); Alembic::AbcGeom::IPolyMesh objMesh; Alembic::AbcGeom::ISubD objSubD; if(Alembic::AbcGeom::IPolyMesh::matches((*pIObj).getMetaData())) { objMesh = Alembic::AbcGeom::IPolyMesh(*pIObj,Alembic::Abc::kWrapExisting); } else { objSubD = Alembic::AbcGeom::ISubD(*pIObj,Alembic::Abc::kWrapExisting); } bool isPointCache = false; if(objMesh.valid()) { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objMesh.getSchema(),".faceCounts"); if( ! faceCountProp.valid() ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),"P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } else if( faceCountProp.isConstant() ) { Alembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue(); // the first is our preferred method, the second check here is Helge's method that is now considered obsolete if( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objMesh.getSchema(),"P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } } } else if( objSubD.valid() ) { Alembic::Abc::IInt32ArrayProperty faceCountProp = Alembic::Abc::IInt32ArrayProperty(objSubD.getSchema(),".faceCounts"); if( ! faceCountProp.valid() ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objSubD.getSchema(),"P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } else if( faceCountProp.isConstant() ) { Alembic::Abc::Int32ArraySamplePtr faceCounts = faceCountProp.getValue(); // the first is our preferred method, the second check here is Helge's method that is now considered obsolete if( faceCounts->size() == 0 || ( faceCounts->size() == 1 && ( faceCounts->get()[0] == 0 ) ) ) { Alembic::Abc::IP3fArrayProperty positionsProp = Alembic::Abc::IP3fArrayProperty(objSubD.getSchema(),"P"); if( positionsProp.valid() && positionsProp.getValue()->size() > 0 ) { isPointCache = true; } } } } return isPointCache; } struct edge { int a; int b; bool operator<( const edge& rEdge ) const { if(a < rEdge.a) return true; if(a > rEdge.a) return false; if(b < rEdge.b) return true; return false; } }; struct edgeData { bool bReversed; int count; int face; edgeData():bReversed(false), count(1), face(-1) {} }; int validateAlembicMeshTopo(std::vector<Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t> faceCounts, std::vector<Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t> faceIndices, const std::string& meshName) { std::map<edge, edgeData> edgeToCountMap; typedef std::map<edge, edgeData>::iterator iterator; int meshErrors = 0; int faceOffset = 0; for(int i=0; i<faceCounts.size(); i++){ int count = faceCounts[i]; std::vector<int> occurences; occurences.reserve(count); Alembic::AbcCoreAbstract::ALEMBIC_VERSION_NS::int32_t* v = &faceIndices[faceOffset]; for(int j=0; j<count; j++){ occurences.push_back(v[j]); } std::sort(occurences.begin(), occurences.end()); for(int j=0; j<occurences.size()-1; j++){ if(occurences[j] == occurences[j+1]){ ESS_LOG_WARNING("Error in mesh \""<<meshName<<"\". Vertex "<<occurences[j]<<" of face "<<i<<" is duplicated."); meshErrors ++; } } for(int j=0; j<count-1; j++){ edge e; e.a = v[j]; e.b = v[j+1]; if( e.a == e.b ){ //the duplicate vertices check already covers this case. //ESS_LOG_WARNING("edge ("<<e.a<<", "<<e.b<<") is degenerate."); continue; } edgeData eData; eData.face = i; if(e.b < e.a){ std::swap(e.a, e.b); eData.bReversed = true; } if( edgeToCountMap.find(e) == edgeToCountMap.end() ){ edgeToCountMap[e] = eData; } else{ edgeData eData2 = edgeToCountMap[e]; eData2.count++; if( (eData.bReversed && eData2.bReversed) || (!eData.bReversed && !eData2.bReversed) ){ ESS_LOG_WARNING("Error in mesh \""<<meshName<<"\". Edge ("<<e.a<<", "<<e.b<<") is shared between polygons "<<eData.face<<" and "<<eData2.face<<", and these polygons have reversed orderings."); meshErrors ++; } } } faceOffset += count; } return meshErrors; }<|endoftext|>
<commit_before>// Copyright 2016 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <vector> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <Dedispersion.hpp> #include <ArgumentList.hpp> #include <Observation.hpp> #include <utils.hpp> #include <Shifts.hpp> #include <ReadData.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { unsigned int padding = 0; uint8_t inputBits = 0; bool printResults = false; uint64_t wrongSamples = 0; std::string channelsFile; AstroData::Observation observation_c; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); printResults = args.getSwitch("-print_results"); inputBits = args.getSwitchArgument< unsigned int >("-input_bits"); padding = args.getSwitchArgument< unsigned int >("-padding"); channelsFile = args.getSwitchArgument< std::string >("-zapped_channels"); observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams")); observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >("-synthetic_beams")); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-subbands"), args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >("-subbanding_dms"), args.getSwitchArgument< float >("-subbanding_dm_first"), args.getSwitchArgument< float >("-subbanding_dm_step")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, args.getSwitchArgument< float >("-dm_step")); observation_c = observation; observation_c.setDMRange(observation.getNrDMsSubbanding() * observation.getNrDMs(), args.getSwitchArgument< float >("-dm_first"), observation.getDMStep()); } catch ( isa::utils::SwitchNotFound & err ) { std::cerr << err.what() << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << "Usage: " << argv[0] << " [-print_results] -input_bits ... -padding ... -zapped_channels ... -beams ... -synthetic_beams ... -min_freq ... -channel_bandwidth ... -samples ... -subbands ... -channels ... -subbanding_dms ... -dms ... -subbanding_dm_first ... -dm_first ... -subbanding_dm_step ... -dm_step ..." << std::endl; return 1; } // Allocate memory std::vector< inputDataType > dispersedData; std::vector< outputDataType > subbandedData; std::vector< outputDataType > dedispersedData; std::vector< outputDataType > dedispersedData_c; std::vector< uint8_t > zappedChannels(observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))); std::vector< uint8_t > beamDriver(observation_c.getNrSyntheticBeams() * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))); std::vector< float > * shifts = PulsarSearch::getShifts(observation_c, padding); AstroData::readZappedChannels(observation_c, channelsFile, zappedChannels); observation_c.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation_c.getFirstDM() + ((observation_c.getNrDMs() - 1) * observation_c.getDMStep())))); observation.setNrSamplesPerBatchSubbanding(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))); observation.setNrSamplesPerSubbandingDispersedChannel(observation.getNrSamplesPerBatchSubbanding() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDMSubbanding() + ((observation.getNrDMsSubbanding() - 1) * observation.getDMSubbandingStep())))); if ( inputBits >= 8 ) { dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedSubbandingDispersedChannel(padding / sizeof(inputDataType))); subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * observation.getNrDMsSubbanding() * observation.getNrSamplesPerPaddedSubbandingDispersedChannel(padding / sizeof(inputDataType))); dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType))); dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * observation_c.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType))); } else { dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))); subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * isa::utils::pad(observation.getNrSamplesPerSubbandingDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))); dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * isa::utils::pad(observation.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType))); dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * isa::utils::pad(observation_c.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType))); } // Generate data srand(time(0)); for ( unsigned int beam = 0; beam < observation_c.getNrBeams(); beam++ ) { for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation_c.getNrSamplesPerDispersedChannel(); sample++ ) { if ( inputBits >= 8 ) { dispersedData[(beam * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + (channel * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + sample] = rand() % observation_c.getNrChannels(); } else { unsigned int byte = 0; uint8_t firstBit = 0; uint8_t value = rand() % inputBits; uint8_t buffer = 0; byte = sample / (8 / inputBits); firstBit = (sample % (8 / inputBits)) * inputBits; buffer = dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte]; for ( unsigned int bit = 0; bit < inputBits; bit++ ) { isa::utils::setBit(buffer, isa::utils::getBit(value, bit), firstBit + bit); } dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte] = buffer; } } } } for ( unsigned int beam = 0; beam < observation_c.getNrSyntheticBeams(); beam++ ) { for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) { beamDriver[(beam * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))) + channel] = rand() % observation_c.getNrBeams(); } } std::fill(subbandedData.begin(), subbandedData.end(), 0); std::fill(dedispersedData.begin(), dedispersedData.end(), 0); std::fill(dedispersedData_c.begin(), dedispersedData_c.end(), 0); // Execute dedispersion PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation_c, zappedChannels, beamDriver, dispersedData, dedispersedData_c, *shifts, padding, inputBits); PulsarSearch::subbandDedispersionStepOne< inputDataType, intermediateDataType, outputDataType >(observation, zappedChannels, dispersedData, subbandedData, *shifts, padding, inputBits); PulsarSearch::subbandDedispersionStepTwo< outputDataType, intermediateDataType, outputDataType >(observation, beamDriver, subbandedData, dedispersedData, *shifts, padding); for ( unsigned int sBeam = 0; sBeam < observation.getNrSyntheticBeams(); sBeam++ ) { for ( unsigned int firstStepDM = 0; firstStepDM < observation.getNrDMsSubbanding(); firstStepDM++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { if ( printResults ) { std::cout << "sBeam: " << sBeam << " DM: " << (firstStepDM * observation.getNrDMs()) + dm << std::endl; } for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) { if ( !isa::utils::same(dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample], dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample]) ) { wrongSamples++; } if ( printResults ) { std::cout << dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << "," << dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << " "; } } if ( printResults ) { std::cout << std::endl; } } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< uint64_t >(observation_c.getNrSyntheticBeams()) * observation_c.getNrDMs() * observation_c.getNrSamplesPerBatch()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <commit_msg>Fixed the < 8 bit case.<commit_after>// Copyright 2016 Alessio Sclocco <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <vector> #include <ctime> #include <algorithm> #include <configuration.hpp> #include <Dedispersion.hpp> #include <ArgumentList.hpp> #include <Observation.hpp> #include <utils.hpp> #include <Shifts.hpp> #include <ReadData.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { unsigned int padding = 0; uint8_t inputBits = 0; bool printResults = false; uint64_t wrongSamples = 0; std::string channelsFile; AstroData::Observation observation_c; AstroData::Observation observation; try { isa::utils::ArgumentList args(argc, argv); printResults = args.getSwitch("-print_results"); inputBits = args.getSwitchArgument< unsigned int >("-input_bits"); padding = args.getSwitchArgument< unsigned int >("-padding"); channelsFile = args.getSwitchArgument< std::string >("-zapped_channels"); observation.setNrBeams(args.getSwitchArgument< unsigned int >("-beams")); observation.setNrSyntheticBeams(args.getSwitchArgument< unsigned int >("-synthetic_beams")); observation.setFrequencyRange(args.getSwitchArgument< unsigned int >("-subbands"), args.getSwitchArgument< unsigned int >("-channels"), args.getSwitchArgument< float >("-min_freq"), args.getSwitchArgument< float >("-channel_bandwidth")); observation.setNrSamplesPerBatch(args.getSwitchArgument< unsigned int >("-samples")); observation.setDMSubbandingRange(args.getSwitchArgument< unsigned int >("-subbanding_dms"), args.getSwitchArgument< float >("-subbanding_dm_first"), args.getSwitchArgument< float >("-subbanding_dm_step")); observation.setDMRange(args.getSwitchArgument< unsigned int >("-dms"), 0.0, args.getSwitchArgument< float >("-dm_step")); observation_c = observation; observation_c.setDMRange(observation.getNrDMsSubbanding() * observation.getNrDMs(), args.getSwitchArgument< float >("-dm_first"), observation.getDMStep()); } catch ( isa::utils::SwitchNotFound & err ) { std::cerr << err.what() << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << "Usage: " << argv[0] << " [-print_results] -input_bits ... -padding ... -zapped_channels ... -beams ... -synthetic_beams ... -min_freq ... -channel_bandwidth ... -samples ... -subbands ... -channels ... -subbanding_dms ... -dms ... -subbanding_dm_first ... -dm_first ... -subbanding_dm_step ... -dm_step ..." << std::endl; return 1; } // Allocate memory std::vector< inputDataType > dispersedData; std::vector< outputDataType > subbandedData; std::vector< outputDataType > dedispersedData; std::vector< outputDataType > dedispersedData_c; std::vector< uint8_t > zappedChannels(observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))); std::vector< uint8_t > beamDriver(observation_c.getNrSyntheticBeams() * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))); std::vector< float > * shifts = PulsarSearch::getShifts(observation_c, padding); AstroData::readZappedChannels(observation_c, channelsFile, zappedChannels); observation_c.setNrSamplesPerDispersedChannel(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation_c.getFirstDM() + ((observation_c.getNrDMs() - 1) * observation_c.getDMStep())))); observation.setNrSamplesPerBatchSubbanding(observation.getNrSamplesPerBatch() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDM() + ((observation.getNrDMs() - 1) * observation.getDMStep())))); observation.setNrSamplesPerSubbandingDispersedChannel(observation.getNrSamplesPerBatchSubbanding() + static_cast< unsigned int >(shifts->at(0) * (observation.getFirstDMSubbanding() + ((observation.getNrDMsSubbanding() - 1) * observation.getDMSubbandingStep())))); if ( inputBits >= 8 ) { dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedSubbandingDispersedChannel(padding / sizeof(inputDataType))); subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * observation.getNrDMsSubbanding() * observation.getNrSamplesPerPaddedSubbandingDispersedChannel(padding / sizeof(inputDataType))); dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType))); dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * observation_c.getNrSamplesPerPaddedBatch(padding / sizeof(inputDataType))); } else { dispersedData.resize(observation_c.getNrBeams() * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerPaddedDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))); subbandedData.resize(observation.getNrBeams() * observation.getNrSubbands() * isa::utils::pad(observation.getNrSamplesPerSubbandingDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))); dedispersedData.resize(observation.getNrSyntheticBeams() * (observation.getNrDMsSubbanding() * observation.getNrDMs()) * isa::utils::pad(observation.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType))); dedispersedData_c.resize(observation_c.getNrSyntheticBeams() * observation_c.getNrDMs() * isa::utils::pad(observation_c.getNrSamplesPerBatch() / (8 / inputBits), padding / sizeof(inputDataType))); } // Generate data srand(time(0)); for ( unsigned int beam = 0; beam < observation_c.getNrBeams(); beam++ ) { for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) { for ( unsigned int sample = 0; sample < observation_c.getNrSamplesPerDispersedChannel(); sample++ ) { if ( inputBits >= 8 ) { dispersedData[(beam * observation_c.getNrChannels() * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + (channel * observation_c.getNrSamplesPerPaddedDispersedChannel(padding / sizeof(inputDataType))) + sample] = rand() % observation_c.getNrChannels(); } else { unsigned int byte = 0; uint8_t firstBit = 0; uint8_t value = rand() % inputBits; uint8_t buffer = 0; byte = sample / (8 / inputBits); firstBit = (sample % (8 / inputBits)) * inputBits; buffer = dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte]; for ( unsigned int bit = 0; bit < inputBits; bit++ ) { isa::utils::setBit(buffer, isa::utils::getBit(value, bit), firstBit + bit); } dispersedData[(beam * observation_c.getNrChannels() * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + (channel * isa::utils::pad(observation_c.getNrSamplesPerDispersedChannel() / (8 / inputBits), padding / sizeof(inputDataType))) + byte] = buffer; } } } } for ( unsigned int beam = 0; beam < observation_c.getNrSyntheticBeams(); beam++ ) { for ( unsigned int channel = 0; channel < observation_c.getNrChannels(); channel++ ) { beamDriver[(beam * observation_c.getNrPaddedChannels(padding / sizeof(uint8_t))) + channel] = rand() % observation_c.getNrBeams(); } } std::fill(subbandedData.begin(), subbandedData.end(), 0); std::fill(dedispersedData.begin(), dedispersedData.end(), 0); std::fill(dedispersedData_c.begin(), dedispersedData_c.end(), 0); // Execute dedispersion PulsarSearch::dedispersion< inputDataType, intermediateDataType, outputDataType >(observation_c, zappedChannels, beamDriver, dispersedData, dedispersedData_c, *shifts, padding, inputBits); PulsarSearch::subbandDedispersionStepOne< inputDataType, intermediateDataType, outputDataType >(observation, zappedChannels, dispersedData, subbandedData, *shifts, padding, inputBits); PulsarSearch::subbandDedispersionStepTwo< outputDataType, intermediateDataType, outputDataType >(observation, beamDriver, subbandedData, dedispersedData, *shifts, padding); for ( unsigned int sBeam = 0; sBeam < observation.getNrSyntheticBeams(); sBeam++ ) { for ( unsigned int firstStepDM = 0; firstStepDM < observation.getNrDMsSubbanding(); firstStepDM++ ) { for ( unsigned int dm = 0; dm < observation.getNrDMs(); dm++ ) { if ( printResults ) { std::cout << "sBeam: " << sBeam << " DM: " << (firstStepDM * observation.getNrDMs()) + dm << std::endl; } for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) { if ( !isa::utils::same(dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample], dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample]) ) { wrongSamples++; } if ( printResults ) { std::cout << dedispersedData[(sBeam * observation.getNrDMsSubbanding() * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (firstStepDM * observation.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (dm * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << "," << dedispersedData_c[(sBeam * observation_c.getNrDMs() * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + (((firstStepDM * observation.getNrDMs()) + dm) * observation.getNrSamplesPerPaddedBatch(padding / sizeof(outputDataType))) + sample] << " "; } } if ( printResults ) { std::cout << std::endl; } } } } if ( wrongSamples > 0 ) { std::cout << "Wrong samples: " << wrongSamples << " (" << (wrongSamples * 100.0) / (static_cast< uint64_t >(observation_c.getNrSyntheticBeams()) * observation_c.getNrDMs() * observation_c.getNrSamplesPerBatch()) << "%)." << std::endl; } else { std::cout << "TEST PASSED." << std::endl; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Disable exception handler warnings. #pragma warning( disable : 4530 ) #include <errno.h> #include "client/windows/sender/crash_report_sender.h" #include "common/windows/http_upload.h" #if _MSC_VER < 1400 // MSVC 2005/8 // Older MSVC doesn't have fscanf_s, but they are compatible as long as // we don't use the string conversions (%s/%c/%S/%C). #define fscanf_s fscanf #endif namespace google_breakpad { static const char kCheckpointSignature[] = "GBP1\n"; CrashReportSender::CrashReportSender(const wstring &checkpoint_file) : checkpoint_file_(checkpoint_file), max_reports_per_day_(-1), last_sent_date_(-1), reports_sent_(0) { FILE *fd; if (OpenCheckpointFile(L"r", &fd) == 0) { ReadCheckpoint(fd); fclose(fd); } } ReportResult CrashReportSender::SendCrashReport( const wstring &url, const map<wstring, wstring> &parameters, const wstring &dump_file_name, wstring *report_code) { int today = GetCurrentDate(); if (today == last_sent_date_ && max_reports_per_day_ != -1 && reports_sent_ >= max_reports_per_day_) { return RESULT_THROTTLED; } int http_response = 0; bool result = HTTPUpload::SendRequest( url, parameters, dump_file_name, L"upload_file_minidump", NULL, report_code, &http_response); if (result) { ReportSent(today); return RESULT_SUCCEEDED; } else if (http_response == 400) { // TODO: update if/when the server // switches to a different code return RESULT_REJECTED; } else { return RESULT_FAILED; } } void CrashReportSender::ReadCheckpoint(FILE *fd) { char buf[128]; if (!fgets(buf, sizeof(buf), fd) || strcmp(buf, kCheckpointSignature) != 0) { return; } if (fscanf_s(fd, "%d\n", &last_sent_date_) != 1) { last_sent_date_ = -1; return; } if (fscanf_s(fd, "%d\n", &reports_sent_) != 1) { reports_sent_ = 0; return; } } void CrashReportSender::ReportSent(int today) { // Update the report stats if (today != last_sent_date_) { last_sent_date_ = today; reports_sent_ = 0; } ++reports_sent_; // Update the checkpoint file FILE *fd; if (OpenCheckpointFile(L"w", &fd) == 0) { fputs(kCheckpointSignature, fd); fprintf(fd, "%d\n", last_sent_date_); fprintf(fd, "%d\n", reports_sent_); fclose(fd); } } int CrashReportSender::GetCurrentDate() const { SYSTEMTIME system_time; GetSystemTime(&system_time); return (system_time.wYear * 10000) + (system_time.wMonth * 100) + system_time.wDay; } int CrashReportSender::OpenCheckpointFile(const wchar_t *mode, FILE **fd) { if (checkpoint_file_.empty()) { return ENOENT; } #if _MSC_VER >= 1400 // MSVC 2005/8 return _wfopen_s(fd, checkpoint_file_.c_str(), mode); #else *fd = _wfopen(checkpoint_file_.c_str(), mode); if (*fd == NULL) { return errno; } return 0; #endif } } // namespace google_breakpad <commit_msg>Actually treat fatal error codes as fatal<commit_after>// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Disable exception handler warnings. #pragma warning( disable : 4530 ) #include <errno.h> #include "client/windows/sender/crash_report_sender.h" #include "common/windows/http_upload.h" #if _MSC_VER < 1400 // MSVC 2005/8 // Older MSVC doesn't have fscanf_s, but they are compatible as long as // we don't use the string conversions (%s/%c/%S/%C). #define fscanf_s fscanf #endif namespace google_breakpad { static const char kCheckpointSignature[] = "GBP1\n"; CrashReportSender::CrashReportSender(const wstring &checkpoint_file) : checkpoint_file_(checkpoint_file), max_reports_per_day_(-1), last_sent_date_(-1), reports_sent_(0) { FILE *fd; if (OpenCheckpointFile(L"r", &fd) == 0) { ReadCheckpoint(fd); fclose(fd); } } ReportResult CrashReportSender::SendCrashReport( const wstring &url, const map<wstring, wstring> &parameters, const wstring &dump_file_name, wstring *report_code) { int today = GetCurrentDate(); if (today == last_sent_date_ && max_reports_per_day_ != -1 && reports_sent_ >= max_reports_per_day_) { return RESULT_THROTTLED; } int http_response = 0; bool result = HTTPUpload::SendRequest( url, parameters, dump_file_name, L"upload_file_minidump", NULL, report_code, &http_response); if (result) { ReportSent(today); return RESULT_SUCCEEDED; } else if (http_response >= 400 && http_response < 500) { return RESULT_REJECTED; } else { return RESULT_FAILED; } } void CrashReportSender::ReadCheckpoint(FILE *fd) { char buf[128]; if (!fgets(buf, sizeof(buf), fd) || strcmp(buf, kCheckpointSignature) != 0) { return; } if (fscanf_s(fd, "%d\n", &last_sent_date_) != 1) { last_sent_date_ = -1; return; } if (fscanf_s(fd, "%d\n", &reports_sent_) != 1) { reports_sent_ = 0; return; } } void CrashReportSender::ReportSent(int today) { // Update the report stats if (today != last_sent_date_) { last_sent_date_ = today; reports_sent_ = 0; } ++reports_sent_; // Update the checkpoint file FILE *fd; if (OpenCheckpointFile(L"w", &fd) == 0) { fputs(kCheckpointSignature, fd); fprintf(fd, "%d\n", last_sent_date_); fprintf(fd, "%d\n", reports_sent_); fclose(fd); } } int CrashReportSender::GetCurrentDate() const { SYSTEMTIME system_time; GetSystemTime(&system_time); return (system_time.wYear * 10000) + (system_time.wMonth * 100) + system_time.wDay; } int CrashReportSender::OpenCheckpointFile(const wchar_t *mode, FILE **fd) { if (checkpoint_file_.empty()) { return ENOENT; } #if _MSC_VER >= 1400 // MSVC 2005/8 return _wfopen_s(fd, checkpoint_file_.c_str(), mode); #else *fd = _wfopen(checkpoint_file_.c_str(), mode); if (*fd == NULL) { return errno; } return 0; #endif } } // namespace google_breakpad <|endoftext|>
<commit_before>//===--- BindingInferenceTests.cpp ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 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 // //===----------------------------------------------------------------------===// #include "SemaFixture.h" #include "swift/AST/Expr.h" #include "swift/Sema/ConstraintSystem.h" #include "llvm/ADT/SmallPtrSet.h" using namespace swift; using namespace swift::unittest; using namespace swift::constraints; TEST_F(SemaTest, TestIntLiteralBindingInference) { ConstraintSystemOptions options; options |= ConstraintSystemFlags::AllowUnresolvedTypeVariables; ConstraintSystem cs(DC, options); auto *intLiteral = IntegerLiteralExpr::createFromUnsigned(Context, 42); auto *literalTy = cs.createTypeVariable(cs.getConstraintLocator(intLiteral), /*options=*/0); cs.addConstraint( ConstraintKind::LiteralConformsTo, literalTy, Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral) ->getDeclaredInterfaceType(), cs.getConstraintLocator(intLiteral)); auto bindings = cs.inferBindingsFor(literalTy); ASSERT_EQ(bindings.Bindings.size(), (unsigned)1); const auto &binding = bindings.Bindings.front(); ASSERT_TRUE(binding.BindingType->isEqual(getStdlibType("Int"))); ASSERT_TRUE(binding.hasDefaultedLiteralProtocol()); } TEST_F(SemaTest, TestTransitiveProtocolInference) { ConstraintSystemOptions options; ConstraintSystem cs(DC, options); auto *PD1 = new (Context) ProtocolDecl(DC, SourceLoc(), SourceLoc(), Context.getIdentifier("P1"), /*Inherited=*/{}, /*trailingWhere=*/nullptr); PD1->setImplicit(); auto *protocolTy1 = ProtocolType::get(PD1, Type(), Context); auto *GPT = cs.createTypeVariable(cs.getConstraintLocator({}), /*options=*/TVO_CanBindToNoEscape); cs.addConstraint( ConstraintKind::ConformsTo, GPT, protocolTy1, cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement( 0, RequirementKind::Conformance))); // First, let's try inferring through a single conversion // relationship. { auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}), /*options=*/0); cs.addConstraint( ConstraintKind::Conversion, typeVar, GPT, cs.getConstraintLocator({}, LocatorPathElt::ContextualType())); auto bindings = inferBindings(cs, typeVar); ASSERT_TRUE(bindings.Protocols.empty()); const auto &inferredProtocols = bindings.TransitiveProtocols; ASSERT_TRUE(bool(inferredProtocols)); ASSERT_EQ(inferredProtocols->size(), (unsigned)1); ASSERT_TRUE( (*inferredProtocols->begin())->getSecondType()->isEqual(protocolTy1)); } } <commit_msg>[unittest/Sema] Cover transitive protocol inference with unit tests<commit_after>//===--- BindingInferenceTests.cpp ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 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 // //===----------------------------------------------------------------------===// #include "SemaFixture.h" #include "swift/AST/Expr.h" #include "swift/Sema/ConstraintSystem.h" #include "llvm/ADT/SmallPtrSet.h" using namespace swift; using namespace swift::unittest; using namespace swift::constraints; TEST_F(SemaTest, TestIntLiteralBindingInference) { ConstraintSystemOptions options; options |= ConstraintSystemFlags::AllowUnresolvedTypeVariables; ConstraintSystem cs(DC, options); auto *intLiteral = IntegerLiteralExpr::createFromUnsigned(Context, 42); auto *literalTy = cs.createTypeVariable(cs.getConstraintLocator(intLiteral), /*options=*/0); cs.addConstraint( ConstraintKind::LiteralConformsTo, literalTy, Context.getProtocol(KnownProtocolKind::ExpressibleByIntegerLiteral) ->getDeclaredInterfaceType(), cs.getConstraintLocator(intLiteral)); auto bindings = cs.inferBindingsFor(literalTy); ASSERT_EQ(bindings.Bindings.size(), (unsigned)1); const auto &binding = bindings.Bindings.front(); ASSERT_TRUE(binding.BindingType->isEqual(getStdlibType("Int"))); ASSERT_TRUE(binding.hasDefaultedLiteralProtocol()); } // Given a set of inferred protocol requirements, make sure that // all of the expected types are present. static void verifyProtocolInferenceResults( const llvm::SmallPtrSetImpl<Constraint *> &protocols, ArrayRef<Type> expectedTypes) { ASSERT_TRUE(protocols.size() >= expectedTypes.size()); llvm::SmallPtrSet<Type, 2> inferredProtocolTypes; for (auto *protocol : protocols) inferredProtocolTypes.insert(protocol->getSecondType()); for (auto expectedTy : expectedTypes) { ASSERT_TRUE(inferredProtocolTypes.count(expectedTy)); } } TEST_F(SemaTest, TestTransitiveProtocolInference) { ConstraintSystemOptions options; ConstraintSystem cs(DC, options); auto *protocolTy1 = createProtocol("P1"); auto *protocolTy2 = createProtocol("P2"); auto *GPT1 = cs.createTypeVariable(cs.getConstraintLocator({}), /*options=*/TVO_CanBindToNoEscape); auto *GPT2 = cs.createTypeVariable(cs.getConstraintLocator({}), /*options=*/TVO_CanBindToNoEscape); cs.addConstraint( ConstraintKind::ConformsTo, GPT1, protocolTy1, cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement( 0, RequirementKind::Conformance))); cs.addConstraint( ConstraintKind::ConformsTo, GPT2, protocolTy2, cs.getConstraintLocator({}, LocatorPathElt::TypeParameterRequirement( 0, RequirementKind::Conformance))); // First, let's try inferring through a single conversion // relationship. { auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}), /*options=*/0); cs.addConstraint( ConstraintKind::Conversion, typeVar, GPT1, cs.getConstraintLocator({}, LocatorPathElt::ContextualType())); auto bindings = inferBindings(cs, typeVar); ASSERT_TRUE(bindings.Protocols.empty()); ASSERT_TRUE(bool(bindings.TransitiveProtocols)); verifyProtocolInferenceResults(*bindings.TransitiveProtocols, {protocolTy1}); } // Now, let's make sure that protocol requirements could be propagated // down conversion/equality chains through multiple hops. { // GPT1 is a subtype of GPT2 and GPT2 is convertible to a target type // variable, target should get both protocols inferred - P1 & P2. auto *typeVar = cs.createTypeVariable(cs.getConstraintLocator({}), /*options=*/0); cs.addConstraint(ConstraintKind::Subtype, GPT1, GPT2, cs.getConstraintLocator({})); cs.addConstraint(ConstraintKind::Conversion, typeVar, GPT1, cs.getConstraintLocator({})); auto bindings = inferBindings(cs, typeVar); ASSERT_TRUE(bindings.Protocols.empty()); ASSERT_TRUE(bool(bindings.TransitiveProtocols)); verifyProtocolInferenceResults(*bindings.TransitiveProtocols, {protocolTy1, protocolTy2}); } } /// Let's try a more complicated situation where there protocols /// are inferred from multiple sources on different levels of /// convertion chain. /// /// (P1) T0 T4 (T3) T6 (P4) /// \ / / /// T3 = T1 (P2) = T5 /// \ / /// T2 TEST_F(SemaTest, TestComplexTransitiveProtocolInference) { ConstraintSystemOptions options; ConstraintSystem cs(DC, options); auto *protocolTy1 = createProtocol("P1"); auto *protocolTy2 = createProtocol("P2"); auto *protocolTy3 = createProtocol("P3"); auto *protocolTy4 = createProtocol("P4"); auto *nilLocator = cs.getConstraintLocator({}); auto typeVar0 = cs.createTypeVariable(nilLocator, /*options=*/0); auto typeVar1 = cs.createTypeVariable(nilLocator, /*options=*/0); auto typeVar2 = cs.createTypeVariable(nilLocator, /*options=*/0); // Allow this type variable to be bound to l-value type to prevent // it from being merged with the rest of the type variables. auto typeVar3 = cs.createTypeVariable(nilLocator, /*options=*/TVO_CanBindToLValue); auto typeVar4 = cs.createTypeVariable(nilLocator, /*options=*/0); auto typeVar5 = cs.createTypeVariable(nilLocator, /*options=*/TVO_CanBindToLValue); auto typeVar6 = cs.createTypeVariable(nilLocator, /*options=*/0); cs.addConstraint(ConstraintKind::ConformsTo, typeVar0, protocolTy1, nilLocator); cs.addConstraint(ConstraintKind::ConformsTo, typeVar1, protocolTy2, nilLocator); cs.addConstraint(ConstraintKind::ConformsTo, typeVar4, protocolTy3, nilLocator); cs.addConstraint(ConstraintKind::ConformsTo, typeVar6, protocolTy4, nilLocator); // T3 <: T0, T3 <: T4 cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar0, nilLocator); cs.addConstraint(ConstraintKind::Conversion, typeVar3, typeVar4, nilLocator); // T2 <: T3, T2 <: T1, T3 == T1 cs.addConstraint(ConstraintKind::Subtype, typeVar2, typeVar3, nilLocator); cs.addConstraint(ConstraintKind::Conversion, typeVar2, typeVar1, nilLocator); cs.addConstraint(ConstraintKind::Equal, typeVar3, typeVar1, nilLocator); // T1 == T5, T <: T6 cs.addConstraint(ConstraintKind::Equal, typeVar1, typeVar5, nilLocator); cs.addConstraint(ConstraintKind::Conversion, typeVar5, typeVar6, nilLocator); auto bindingsForT1 = inferBindings(cs, typeVar1); auto bindingsForT2 = inferBindings(cs, typeVar2); auto bindingsForT3 = inferBindings(cs, typeVar3); auto bindingsForT5 = inferBindings(cs, typeVar5); ASSERT_TRUE(bool(bindingsForT1.TransitiveProtocols)); verifyProtocolInferenceResults(*bindingsForT1.TransitiveProtocols, {protocolTy1, protocolTy3, protocolTy4}); ASSERT_TRUE(bool(bindingsForT2.TransitiveProtocols)); verifyProtocolInferenceResults( *bindingsForT2.TransitiveProtocols, {protocolTy1, protocolTy2, protocolTy3, protocolTy4}); ASSERT_TRUE(bool(bindingsForT3.TransitiveProtocols)); verifyProtocolInferenceResults( *bindingsForT3.TransitiveProtocols, {protocolTy1, protocolTy2, protocolTy3, protocolTy4}); ASSERT_TRUE(bool(bindingsForT5.TransitiveProtocols)); verifyProtocolInferenceResults( *bindingsForT5.TransitiveProtocols, {protocolTy1, protocolTy2, protocolTy3, protocolTy4}); } <|endoftext|>
<commit_before>// // Copyright (c) 2014 Toshiaki Takada // // 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 <iostream> #include <iomanip> #include <algorithm> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <curlpp/Infos.hpp> #include <curlpp/Exception.hpp> #include "json/json.h" #include "cli.hpp" #include "cli_action.hpp" using namespace curlpp; CliActionHttp::CliActionHttp(Json::Value& http) : CliAction() { method_ = http["method"].asString(); path_ = http["path"].asString(); format_ = http["format"].asString(); Json::Value params = http["params"]; if (!params.isNull()) for (Json::Value::iterator it = params.begin(); it != params.end(); ++it) param_token_[it.key().asString()] = *it; } bool CliActionHttp::get_token(string& str, string& token) { const char *p = str.c_str(); size_t pos; // skip "/". pos = strspn(p, "/"); if (pos > 0) str = str.substr(pos, string::npos); // stirng is empty. if (str.empty()) return false; p = str.c_str(); pos = strcspn(p, "/"); token = str.substr(0, pos); str = str.substr(pos, string::npos); return true; } bool CliActionHttp::handle(Cli *cli, ParamsMap& input) { Json::Value json_params; Json::FastWriter writer; Json::Value null_value; string str(path_); string path; string token; const char *delim = ""; if (cli->is_debug()) { cout << "method: " << method_ << endl; cout << "path: " << path_ << endl; } for (ParamTokenMap::iterator it = param_token_.begin(); it != param_token_.end(); ++it) { string key = it->first; replace(key.begin(), key.end(), '-', '_'); if (cli->is_debug()) cout << "param_token_[" << key << "] = " << it->second << endl; if (it->second.isNull()) json_params[key] = null_value; else if (it->second.isBool()) json_params[key] = it->second.asBool(); else if (it->second.isUInt64()) json_params[key] = it->second.asUInt64(); else if (it->second.isInt64()) json_params[key] = it->second.asInt64(); else if (it->second.isString()) { if (!input[it->second.asString()].empty()) json_params[key] = input[it->second.asString()]; else json_params[key] = it->second; } } // Generate path with parameter. while (get_token(str, token)) { path += delim; if (token.c_str()[0] == ':') path += input[&token.c_str()[1]]; else path += token; delim = "/"; } string json_str = writer.write(json_params); if (cli->is_debug()) cout << "json: " << json_str << endl; request(cli, method_, path, json_str); return true; } void CliActionHttp::request(Cli *cli, string& method, string& path, string& json) { if (method != "GET" && method != "POST" && method != "PUT" && method != "DELETE") return; string url("http://localhost"); string api_prefix("/zebra/api"); url += api_prefix; if (!path.empty()) url += "/" + path; if (format_.empty()) url += ".json"; else url += "." + format_; try { Cleanup myCleanup; Easy req; stringstream result; req.setOpt(new options::Url(url)); if (cli->is_debug()) req.setOpt(new options::Verbose(true)); list<string> header; header.push_back("Content-type: application/json"); req.setOpt(new options::HttpHeader(header)); req.setOpt(new options::CustomRequest(method)); req.setOpt(new options::WriteStream(&result)); if (method != "GET") { req.setOpt(new options::PostFields(json)); req.setOpt(new options::PostFieldSize(json.size())); } req.perform(); int status = infos::ResponseCode::get(req); switch (status / 100) { case 1: case 2: if (format_ == "cli") cout << result.str() << endl; break; case 3: case 4: case 5: cout << "HTTP Error: " << status << endl; break; } cli->set_result(result); } catch (curlpp::RuntimeError& e) { if (cli->is_debug()) cout << e.what() << std::endl; } catch (curlpp::LogicError& e) { if (cli->is_debug()) cout << e.what() << std::endl; } // cout << endl; } CliActionMode::CliActionMode(Json::Value& mode) : CliAction() { Json::Value name = mode["name"]; Json::Value up = mode["up"]; Json::Value params = mode["params"]; if (!name.isNull()) name_ = name.asString(); if (!up.isNull()) up_ = up.asUInt(); if (!params.isNull()) for (Json::Value::iterator it = params.begin(); it != params.end(); ++it) params_.push_back((*it).asString()); } bool CliActionMode::handle(Cli *cli, ParamsMap& input) { if (!name_.empty()) { cli->mode_set(name_); // Derive parameters. cli->params_.clear(); for (StringVector::iterator it = params_.begin(); it != params_.end(); ++it) { ParamsMap::iterator is = input.find(*it); if (is != input.end()) cli->params_[*it] = is->second; } } else if (up_) cli->mode_up(up_); return true; } bool CliActionBuiltIn::handle(Cli *cli, ParamsMap& input) { (void)input; //TODO StringVector vec; if (cli->built_in_[func_]) cli->built_in_[func_](cli, vec); return true; } <commit_msg>Add dynamic key from input. This is a little bit tricky.<commit_after>// // Copyright (c) 2014 Toshiaki Takada // // 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 <iostream> #include <iomanip> #include <algorithm> #include <curlpp/cURLpp.hpp> #include <curlpp/Easy.hpp> #include <curlpp/Options.hpp> #include <curlpp/Infos.hpp> #include <curlpp/Exception.hpp> #include "json/json.h" #include "cli.hpp" #include "cli_action.hpp" using namespace curlpp; CliActionHttp::CliActionHttp(Json::Value& http) : CliAction() { method_ = http["method"].asString(); path_ = http["path"].asString(); format_ = http["format"].asString(); Json::Value params = http["params"]; if (!params.isNull()) for (Json::Value::iterator it = params.begin(); it != params.end(); ++it) param_token_[it.key().asString()] = *it; } bool CliActionHttp::get_token(string& str, string& token) { const char *p = str.c_str(); size_t pos; // skip "/". pos = strspn(p, "/"); if (pos > 0) str = str.substr(pos, string::npos); // stirng is empty. if (str.empty()) return false; p = str.c_str(); pos = strcspn(p, "/"); token = str.substr(0, pos); str = str.substr(pos, string::npos); return true; } bool CliActionHttp::handle(Cli *cli, ParamsMap& input) { Json::Value json_params; Json::FastWriter writer; Json::Value null_value; string str(path_); string path; string token; const char *delim = ""; if (cli->is_debug()) { cout << "method: " << method_ << endl; cout << "path: " << path_ << endl; } for (ParamTokenMap::iterator it = param_token_.begin(); it != param_token_.end(); ++it) { string key = it->first; ParamsMap::iterator is; is = input.find(key); if (is != input.end()) key = is->second; replace(key.begin(), key.end(), '-', '_'); if (cli->is_debug()) cout << "param_token_[" << key << "] = " << it->second << endl; if (it->second.isNull()) json_params[key] = null_value; else if (it->second.isBool()) json_params[key] = it->second.asBool(); else if (it->second.isUInt64()) json_params[key] = it->second.asUInt64(); else if (it->second.isInt64()) json_params[key] = it->second.asInt64(); else if (it->second.isString()) { if (!input[it->second.asString()].empty()) json_params[key] = input[it->second.asString()]; else json_params[key] = it->second; } } // Generate path with parameter. while (get_token(str, token)) { path += delim; if (token.c_str()[0] == ':') path += input[&token.c_str()[1]]; else path += token; delim = "/"; } string json_str = writer.write(json_params); if (cli->is_debug()) cout << "json: " << json_str << endl; request(cli, method_, path, json_str); return true; } void CliActionHttp::request(Cli *cli, string& method, string& path, string& json) { if (method != "GET" && method != "POST" && method != "PUT" && method != "DELETE") return; string url("http://localhost"); string api_prefix("/zebra/api"); url += api_prefix; if (!path.empty()) url += "/" + path; if (format_.empty()) url += ".json"; else url += "." + format_; try { Cleanup myCleanup; Easy req; stringstream result; req.setOpt(new options::Url(url)); if (cli->is_debug()) req.setOpt(new options::Verbose(true)); list<string> header; header.push_back("Content-type: application/json"); req.setOpt(new options::HttpHeader(header)); req.setOpt(new options::CustomRequest(method)); req.setOpt(new options::WriteStream(&result)); if (method != "GET") { req.setOpt(new options::PostFields(json)); req.setOpt(new options::PostFieldSize(json.size())); } req.perform(); int status = infos::ResponseCode::get(req); switch (status / 100) { case 1: case 2: if (format_ == "cli") cout << result.str() << endl; break; case 3: case 4: case 5: cout << "HTTP Error: " << status << endl; break; } cli->set_result(result); } catch (curlpp::RuntimeError& e) { if (cli->is_debug()) cout << e.what() << std::endl; } catch (curlpp::LogicError& e) { if (cli->is_debug()) cout << e.what() << std::endl; } // cout << endl; } CliActionMode::CliActionMode(Json::Value& mode) : CliAction() { Json::Value name = mode["name"]; Json::Value up = mode["up"]; Json::Value params = mode["params"]; if (!name.isNull()) name_ = name.asString(); if (!up.isNull()) up_ = up.asUInt(); if (!params.isNull()) for (Json::Value::iterator it = params.begin(); it != params.end(); ++it) params_.push_back((*it).asString()); } bool CliActionMode::handle(Cli *cli, ParamsMap& input) { if (!name_.empty()) { cli->mode_set(name_); // Derive parameters. cli->params_.clear(); for (StringVector::iterator it = params_.begin(); it != params_.end(); ++it) { ParamsMap::iterator is = input.find(*it); if (is != input.end()) cli->params_[*it] = is->second; } } else if (up_) cli->mode_up(up_); return true; } bool CliActionBuiltIn::handle(Cli *cli, ParamsMap& input) { (void)input; //TODO StringVector vec; if (cli->built_in_[func_]) cli->built_in_[func_](cli, vec); return true; } <|endoftext|>