text
stringlengths
54
60.6k
<commit_before>#ifndef ITER_STARMAP_H_ #define ITER_STARMAP_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <type_traits> #include <array> #include <cassert> #include <memory> namespace iter { // starmap with a container<T> where T is one of tuple, pair, array template <typename Func, typename Container> class StarMapper { private: Func func; Container container; using StarIterDeref = std::remove_reference_t<decltype(call_with_tuple(func, std::declval<iterator_deref<Container>>()))>; public: StarMapper(Func f, Container&& c) : func(std::forward<Func>(f)), container(std::forward<Container>(c)) { } class Iterator : public std::iterator<std::input_iterator_tag, StarIterDeref> { private: Func func; iterator_type<Container> sub_iter; public: Iterator(Func& f, iterator_type<Container> iter) : func(f), sub_iter(iter) { } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } Iterator operator++() { ++this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } decltype(auto) operator*() { return call_with_tuple(this->func, *this->sub_iter); } }; Iterator begin() { return {this->func, std::begin(this->container)}; } Iterator end() { return {this->func, std::end(this->container)}; } }; template <typename Func, typename Container> StarMapper<Func, Container> starmap_helper( Func func, Container&& container, std::false_type) { return {std::forward<Func>(func), std::forward<Container>(container)}; } // starmap for a tuple or pair of tuples or pairs template <typename Func, typename TupType, std::size_t... Is> class TupleStarMapper { private: Func func; TupType tup; private: static_assert(sizeof...(Is) == std::tuple_size<std::decay_t<TupType>>::value, "tuple size doesn't match size of Is"); template <std::size_t Idx> static decltype(auto) get_and_call_with_tuple(Func& f, TupType &t){ return call_with_tuple(f, std::get<Idx>(t)); } using ResultType = decltype(get_and_call_with_tuple<0>(func, tup)); using CallerFunc = ResultType (*)(Func&, TupType&); constexpr static std::array<CallerFunc, sizeof...(Is)> callers{{ get_and_call_with_tuple<Is>...}}; public: TupleStarMapper(Func f, TupType t) : func(std::forward<Func>(f)), tup(std::forward<TupType>(t)) { } // TODO inherit from std::iterator class Iterator { private: Func& func; TupType& tup; std::size_t index; public: Iterator(Func& f, TupType& t, std::size_t i) : func{f}, tup{t}, index{i} { } decltype(auto) operator*() { return callers[this->index](this->func, this->tup); } Iterator operator++() { ++this->index; return *this; } bool operator!=(const Iterator& other) const { return this->index != other.index; } }; Iterator begin() { return {this->func, this->tup, 0}; } Iterator end() { return {this->func, this->tup, sizeof...(Is)}; } }; template <typename Func, typename TupType, std::size_t... Is> constexpr std::array< typename TupleStarMapper<Func, TupType, Is...>::CallerFunc, sizeof...(Is)> TupleStarMapper<Func, TupType, Is...>::callers; template <typename Func, typename TupType, std::size_t... Is> TupleStarMapper<Func, TupType, Is...> starmap_helper_impl( Func func, TupType&& tup, std::index_sequence<Is...>) { return {std::forward<Func>(func), std::forward<TupType>(tup)}; } template <typename Func, typename TupType> auto starmap_helper( Func func, TupType&& tup, std::true_type) { return starmap_helper_impl( std::forward<Func>(func), std::forward<TupType>(tup), std::make_index_sequence< std::tuple_size<std::decay_t<TupType>>::value>{}); } // "tag dispatch" to differentiate between normal containers and // tuple-like containers, things that work with std::get template <typename T, typename =void> struct is_tuple_like : public std::false_type { }; template <typename T> struct is_tuple_like<T, decltype(std::get<0>(std::declval<T>()), void())> : public std::true_type { }; template <typename Func, typename Seq> auto starmap(Func func, Seq&& sequence) { return starmap_helper( std::forward<Func>(func), std::forward<Seq>(sequence), is_tuple_like<Seq>{}); } } #endif <commit_msg>TupleStarMapper iter derives std::iterator<commit_after>#ifndef ITER_STARMAP_H_ #define ITER_STARMAP_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <type_traits> #include <array> #include <cassert> #include <memory> namespace iter { // starmap with a container<T> where T is one of tuple, pair, array template <typename Func, typename Container> class StarMapper { private: Func func; Container container; using StarIterDeref = std::remove_reference_t<decltype(call_with_tuple(func, std::declval<iterator_deref<Container>>()))>; public: StarMapper(Func f, Container&& c) : func(std::forward<Func>(f)), container(std::forward<Container>(c)) { } class Iterator : public std::iterator<std::input_iterator_tag, StarIterDeref> { private: Func func; iterator_type<Container> sub_iter; public: Iterator(Func& f, iterator_type<Container> iter) : func(f), sub_iter(iter) { } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } Iterator operator++() { ++this->sub_iter; return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } decltype(auto) operator*() { return call_with_tuple(this->func, *this->sub_iter); } }; Iterator begin() { return {this->func, std::begin(this->container)}; } Iterator end() { return {this->func, std::end(this->container)}; } }; template <typename Func, typename Container> StarMapper<Func, Container> starmap_helper( Func func, Container&& container, std::false_type) { return {std::forward<Func>(func), std::forward<Container>(container)}; } // starmap for a tuple or pair of tuples or pairs template <typename Func, typename TupType, std::size_t... Is> class TupleStarMapper { private: Func func; TupType tup; private: static_assert(sizeof...(Is) == std::tuple_size<std::decay_t<TupType>>::value, "tuple size doesn't match size of Is"); template <std::size_t Idx> static decltype(auto) get_and_call_with_tuple(Func& f, TupType &t){ return call_with_tuple(f, std::get<Idx>(t)); } using ResultType = decltype(get_and_call_with_tuple<0>(func, tup)); using CallerFunc = ResultType (*)(Func&, TupType&); constexpr static std::array<CallerFunc, sizeof...(Is)> callers{{ get_and_call_with_tuple<Is>...}}; using TraitsValue = std::remove_reference_t<ResultType>; public: TupleStarMapper(Func f, TupType t) : func(std::forward<Func>(f)), tup(std::forward<TupType>(t)) { } class Iterator : public std::iterator<std::input_iterator_tag, TraitsValue> { private: Func& func; TupType& tup; std::size_t index; public: Iterator(Func& f, TupType& t, std::size_t i) : func{f}, tup{t}, index{i} { } decltype(auto) operator*() { return callers[this->index](this->func, this->tup); } Iterator operator++() { ++this->index; return *this; } bool operator!=(const Iterator& other) const { return this->index != other.index; } }; Iterator begin() { return {this->func, this->tup, 0}; } Iterator end() { return {this->func, this->tup, sizeof...(Is)}; } }; template <typename Func, typename TupType, std::size_t... Is> constexpr std::array< typename TupleStarMapper<Func, TupType, Is...>::CallerFunc, sizeof...(Is)> TupleStarMapper<Func, TupType, Is...>::callers; template <typename Func, typename TupType, std::size_t... Is> TupleStarMapper<Func, TupType, Is...> starmap_helper_impl( Func func, TupType&& tup, std::index_sequence<Is...>) { return {std::forward<Func>(func), std::forward<TupType>(tup)}; } template <typename Func, typename TupType> auto starmap_helper( Func func, TupType&& tup, std::true_type) { return starmap_helper_impl( std::forward<Func>(func), std::forward<TupType>(tup), std::make_index_sequence< std::tuple_size<std::decay_t<TupType>>::value>{}); } // "tag dispatch" to differentiate between normal containers and // tuple-like containers, things that work with std::get template <typename T, typename =void> struct is_tuple_like : public std::false_type { }; template <typename T> struct is_tuple_like<T, decltype(std::get<0>(std::declval<T>()), void())> : public std::true_type { }; template <typename Func, typename Seq> auto starmap(Func func, Seq&& sequence) { return starmap_helper( std::forward<Func>(func), std::forward<Seq>(sequence), is_tuple_like<Seq>{}); } } #endif <|endoftext|>
<commit_before>// Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "src/pdf/SkPDFType1Font.h" #include "include/private/SkTemplates.h" #include "include/private/SkTo.h" #include "src/core/SkStrikeSpec.h" #include <ctype.h> /* "A standard Type 1 font program, as described in the Adobe Type 1 Font Format specification, consists of three parts: a clear-text portion (written using PostScript syntax), an encrypted portion, and a fixed-content portion. The fixed-content portion contains 512 ASCII zeros followed by a cleartomark operator, and perhaps followed by additional data. Although the encrypted portion of a standard Type 1 font may be in binary or ASCII hexadecimal format, PDF supports only the binary format." */ static bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType, size_t* size) { // PFB sections have a two or six bytes header. 0x80 and a one byte // section type followed by a four byte section length. Type one is // an ASCII section (includes a length), type two is a binary section // (includes a length) and type three is an EOF marker with no length. const uint8_t* buf = *src; if (*len < 2 || buf[0] != 0x80 || buf[1] != sectionType) { return false; } else if (buf[1] == 3) { return true; } else if (*len < 6) { return false; } *size = (size_t)buf[2] | ((size_t)buf[3] << 8) | ((size_t)buf[4] << 16) | ((size_t)buf[5] << 24); size_t consumed = *size + 6; if (consumed > *len) { return false; } *src = *src + consumed; *len = *len - consumed; return true; } static bool parsePFB(const uint8_t* src, size_t size, size_t* headerLen, size_t* dataLen, size_t* trailerLen) { const uint8_t* srcPtr = src; size_t remaining = size; return parsePFBSection(&srcPtr, &remaining, 1, headerLen) && parsePFBSection(&srcPtr, &remaining, 2, dataLen) && parsePFBSection(&srcPtr, &remaining, 1, trailerLen) && parsePFBSection(&srcPtr, &remaining, 3, nullptr); } /* The sections of a PFA file are implicitly defined. The body starts * after the line containing "eexec," and the trailer starts with 512 * literal 0's followed by "cleartomark" (plus arbitrary white space). * * This function assumes that src is NUL terminated, but the NUL * termination is not included in size. * */ static bool parsePFA(const char* src, size_t size, size_t* headerLen, size_t* hexDataLen, size_t* dataLen, size_t* trailerLen) { const char* end = src + size; const char* dataPos = strstr(src, "eexec"); if (!dataPos) { return false; } dataPos += strlen("eexec"); while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') && dataPos < end) { dataPos++; } *headerLen = dataPos - src; const char* trailerPos = strstr(dataPos, "cleartomark"); if (!trailerPos) { return false; } int zeroCount = 0; for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) { if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') { continue; } else if (*trailerPos == '0') { zeroCount++; } else { return false; } } if (zeroCount != 512) { return false; } *hexDataLen = trailerPos - src - *headerLen; *trailerLen = size - *headerLen - *hexDataLen; // Verify that the data section is hex encoded and count the bytes. int nibbles = 0; for (; dataPos < trailerPos; dataPos++) { if (isspace(*dataPos)) { continue; } // isxdigit() is locale-sensitive https://bugs.skia.org/8285 if (nullptr == strchr("0123456789abcdefABCDEF", *dataPos)) { return false; } nibbles++; } *dataLen = (nibbles + 1) / 2; return true; } static int8_t hexToBin(uint8_t c) { if (!isxdigit(c)) { return -1; } else if (c <= '9') { return c - '0'; } else if (c <= 'F') { return c - 'A' + 10; } else if (c <= 'f') { return c - 'a' + 10; } return -1; } static sk_sp<SkData> convert_type1_font_stream(std::unique_ptr<SkStreamAsset> srcStream, size_t* headerLen, size_t* dataLen, size_t* trailerLen) { size_t srcLen = srcStream ? srcStream->getLength() : 0; SkASSERT(srcLen); if (!srcLen) { return nullptr; } // Flatten and Nul-terminate the source stream so that we can use // strstr() to search it. SkAutoTMalloc<uint8_t> sourceBuffer(SkToInt(srcLen + 1)); (void)srcStream->read(sourceBuffer.get(), srcLen); sourceBuffer[SkToInt(srcLen)] = 0; const uint8_t* src = sourceBuffer.get(); if (parsePFB(src, srcLen, headerLen, dataLen, trailerLen)) { static const int kPFBSectionHeaderLength = 6; const size_t length = *headerLen + *dataLen + *trailerLen; SkASSERT(length > 0); SkASSERT(length + (2 * kPFBSectionHeaderLength) <= srcLen); sk_sp<SkData> data(SkData::MakeUninitialized(length)); const uint8_t* const srcHeader = src + kPFBSectionHeaderLength; // There is a six-byte section header before header and data // (but not trailer) that we're not going to copy. const uint8_t* const srcData = srcHeader + *headerLen + kPFBSectionHeaderLength; const uint8_t* const srcTrailer = srcData + *headerLen; uint8_t* const resultHeader = (uint8_t*)data->writable_data(); uint8_t* const resultData = resultHeader + *headerLen; uint8_t* const resultTrailer = resultData + *dataLen; SkASSERT(resultTrailer + *trailerLen == resultHeader + length); memcpy(resultHeader, srcHeader, *headerLen); memcpy(resultData, srcData, *dataLen); memcpy(resultTrailer, srcTrailer, *trailerLen); return data; } // A PFA has to be converted for PDF. size_t hexDataLen; if (!parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen, trailerLen)) { return nullptr; } const size_t length = *headerLen + *dataLen + *trailerLen; SkASSERT(length > 0); auto data = SkData::MakeUninitialized(length); uint8_t* buffer = (uint8_t*)data->writable_data(); memcpy(buffer, src, *headerLen); uint8_t* const resultData = &(buffer[*headerLen]); const uint8_t* hexData = src + *headerLen; const uint8_t* trailer = hexData + hexDataLen; size_t outputOffset = 0; uint8_t dataByte = 0; // To hush compiler. bool highNibble = true; for (; hexData < trailer; hexData++) { int8_t curNibble = hexToBin(*hexData); if (curNibble < 0) { continue; } if (highNibble) { dataByte = curNibble << 4; highNibble = false; } else { dataByte |= curNibble; highNibble = true; resultData[outputOffset++] = dataByte; } } if (!highNibble) { resultData[outputOffset++] = dataByte; } SkASSERT(outputOffset == *dataLen); uint8_t* const resultTrailer = &(buffer[SkToInt(*headerLen + outputOffset)]); memcpy(resultTrailer, src + *headerLen + hexDataLen, *trailerLen); return data; } inline static bool can_embed(const SkAdvancedTypefaceMetrics& metrics) { return !SkToBool(metrics.fFlags & SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag); } inline static SkScalar from_font_units(SkScalar scaled, uint16_t emSize) { return emSize == 1000 ? scaled : scaled * 1000 / emSize; } static SkPDFIndirectReference make_type1_font_descriptor(SkPDFDocument* doc, const SkTypeface* typeface, const SkAdvancedTypefaceMetrics* info) { SkPDFDict descriptor("FontDescriptor"); uint16_t emSize = SkToU16(typeface->getUnitsPerEm()); if (info) { SkPDFFont::PopulateCommonFontDescriptor(&descriptor, *info, emSize, 0); if (can_embed(*info)) { int ttcIndex; size_t header SK_INIT_TO_AVOID_WARNING; size_t data SK_INIT_TO_AVOID_WARNING; size_t trailer SK_INIT_TO_AVOID_WARNING; std::unique_ptr<SkStreamAsset> rawFontData = typeface->openStream(&ttcIndex); sk_sp<SkData> fontData = convert_type1_font_stream(std::move(rawFontData), &header, &data, &trailer); if (fontData) { std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict(); dict->insertInt("Length1", header); dict->insertInt("Length2", data); dict->insertInt("Length3", trailer); auto fontStream = SkMemoryStream::Make(std::move(fontData)); descriptor.insertRef("FontFile", SkPDFStreamOut(std::move(dict), std::move(fontStream), doc, true)); } } } return doc->emit(descriptor); } static const std::vector<SkString>& type_1_glyphnames(SkPDFDocument* canon, const SkTypeface* typeface) { SkFontID fontID = typeface->uniqueID(); const std::vector<SkString>* glyphNames = canon->fType1GlyphNames.find(fontID); if (!glyphNames) { std::vector<SkString> names(typeface->countGlyphs()); SkPDFFont::GetType1GlyphNames(*typeface, names.data()); glyphNames = canon->fType1GlyphNames.set(fontID, std::move(names)); } SkASSERT(glyphNames); return *glyphNames; } static SkPDFIndirectReference type1_font_descriptor(SkPDFDocument* doc, const SkTypeface* typeface) { SkFontID fontID = typeface->uniqueID(); if (SkPDFIndirectReference* ptr = doc->fFontDescriptors.find(fontID)) { return *ptr; } const SkAdvancedTypefaceMetrics* info = SkPDFFont::GetMetrics(typeface, doc); auto fontDescriptor = make_type1_font_descriptor(doc, typeface, info); doc->fFontDescriptors.set(fontID, fontDescriptor); return fontDescriptor; } void SkPDFEmitType1Font(const SkPDFFont& pdfFont, SkPDFDocument* doc) { SkTypeface* typeface = pdfFont.typeface(); const std::vector<SkString> glyphNames = type_1_glyphnames(doc, typeface); SkGlyphID firstGlyphID = pdfFont.firstGlyphID(); SkGlyphID lastGlyphID = pdfFont.lastGlyphID(); SkPDFDict font("Font"); font.insertRef("FontDescriptor", type1_font_descriptor(doc, typeface)); font.insertName("Subtype", "Type1"); if (const SkAdvancedTypefaceMetrics* info = SkPDFFont::GetMetrics(typeface, doc)) { font.insertName("BaseFont", info->fPostScriptName); } // glyphCount not including glyph 0 unsigned glyphCount = 1 + lastGlyphID - firstGlyphID; SkASSERT(glyphCount > 0 && glyphCount <= 255); font.insertInt("FirstChar", (size_t)0); font.insertInt("LastChar", (size_t)glyphCount); { int emSize; SkStrikeSpecStorage strikeSpec = SkStrikeSpecStorage::MakePDFVector(*typeface, &emSize); auto glyphCache = strikeSpec.findOrCreateExclusiveStrike(); auto widths = SkPDFMakeArray(); SkScalar advance = glyphCache->getGlyphIDAdvance(0).fAdvanceX; widths->appendScalar(from_font_units(advance, SkToU16(emSize))); for (unsigned gID = firstGlyphID; gID <= lastGlyphID; gID++) { advance = glyphCache->getGlyphIDAdvance(gID).fAdvanceX; widths->appendScalar(from_font_units(advance, SkToU16(emSize))); } font.insertObject("Widths", std::move(widths)); } auto encDiffs = SkPDFMakeArray(); encDiffs->reserve(lastGlyphID - firstGlyphID + 3); encDiffs->appendInt(0); SkASSERT(glyphNames.size() > lastGlyphID); const SkString unknown("UNKNOWN"); encDiffs->appendName(glyphNames[0].isEmpty() ? unknown : glyphNames[0]); for (int gID = firstGlyphID; gID <= lastGlyphID; gID++) { encDiffs->appendName(glyphNames[gID].isEmpty() ? unknown : glyphNames[gID]); } auto encoding = SkPDFMakeDict("Encoding"); encoding->insertObject("Differences", std::move(encDiffs)); font.insertObject("Encoding", std::move(encoding)); doc->emit(font, pdfFont.indirectReference()); } <commit_msg>Use bulk advances in SkPDFEmitType1Font<commit_after>// Copyright 2019 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "src/pdf/SkPDFType1Font.h" #include "include/private/SkTemplates.h" #include "include/private/SkTo.h" #include "src/core/SkStrikeSpec.h" #include <ctype.h> /* "A standard Type 1 font program, as described in the Adobe Type 1 Font Format specification, consists of three parts: a clear-text portion (written using PostScript syntax), an encrypted portion, and a fixed-content portion. The fixed-content portion contains 512 ASCII zeros followed by a cleartomark operator, and perhaps followed by additional data. Although the encrypted portion of a standard Type 1 font may be in binary or ASCII hexadecimal format, PDF supports only the binary format." */ static bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType, size_t* size) { // PFB sections have a two or six bytes header. 0x80 and a one byte // section type followed by a four byte section length. Type one is // an ASCII section (includes a length), type two is a binary section // (includes a length) and type three is an EOF marker with no length. const uint8_t* buf = *src; if (*len < 2 || buf[0] != 0x80 || buf[1] != sectionType) { return false; } else if (buf[1] == 3) { return true; } else if (*len < 6) { return false; } *size = (size_t)buf[2] | ((size_t)buf[3] << 8) | ((size_t)buf[4] << 16) | ((size_t)buf[5] << 24); size_t consumed = *size + 6; if (consumed > *len) { return false; } *src = *src + consumed; *len = *len - consumed; return true; } static bool parsePFB(const uint8_t* src, size_t size, size_t* headerLen, size_t* dataLen, size_t* trailerLen) { const uint8_t* srcPtr = src; size_t remaining = size; return parsePFBSection(&srcPtr, &remaining, 1, headerLen) && parsePFBSection(&srcPtr, &remaining, 2, dataLen) && parsePFBSection(&srcPtr, &remaining, 1, trailerLen) && parsePFBSection(&srcPtr, &remaining, 3, nullptr); } /* The sections of a PFA file are implicitly defined. The body starts * after the line containing "eexec," and the trailer starts with 512 * literal 0's followed by "cleartomark" (plus arbitrary white space). * * This function assumes that src is NUL terminated, but the NUL * termination is not included in size. * */ static bool parsePFA(const char* src, size_t size, size_t* headerLen, size_t* hexDataLen, size_t* dataLen, size_t* trailerLen) { const char* end = src + size; const char* dataPos = strstr(src, "eexec"); if (!dataPos) { return false; } dataPos += strlen("eexec"); while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') && dataPos < end) { dataPos++; } *headerLen = dataPos - src; const char* trailerPos = strstr(dataPos, "cleartomark"); if (!trailerPos) { return false; } int zeroCount = 0; for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) { if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') { continue; } else if (*trailerPos == '0') { zeroCount++; } else { return false; } } if (zeroCount != 512) { return false; } *hexDataLen = trailerPos - src - *headerLen; *trailerLen = size - *headerLen - *hexDataLen; // Verify that the data section is hex encoded and count the bytes. int nibbles = 0; for (; dataPos < trailerPos; dataPos++) { if (isspace(*dataPos)) { continue; } // isxdigit() is locale-sensitive https://bugs.skia.org/8285 if (nullptr == strchr("0123456789abcdefABCDEF", *dataPos)) { return false; } nibbles++; } *dataLen = (nibbles + 1) / 2; return true; } static int8_t hexToBin(uint8_t c) { if (!isxdigit(c)) { return -1; } else if (c <= '9') { return c - '0'; } else if (c <= 'F') { return c - 'A' + 10; } else if (c <= 'f') { return c - 'a' + 10; } return -1; } static sk_sp<SkData> convert_type1_font_stream(std::unique_ptr<SkStreamAsset> srcStream, size_t* headerLen, size_t* dataLen, size_t* trailerLen) { size_t srcLen = srcStream ? srcStream->getLength() : 0; SkASSERT(srcLen); if (!srcLen) { return nullptr; } // Flatten and Nul-terminate the source stream so that we can use // strstr() to search it. SkAutoTMalloc<uint8_t> sourceBuffer(SkToInt(srcLen + 1)); (void)srcStream->read(sourceBuffer.get(), srcLen); sourceBuffer[SkToInt(srcLen)] = 0; const uint8_t* src = sourceBuffer.get(); if (parsePFB(src, srcLen, headerLen, dataLen, trailerLen)) { static const int kPFBSectionHeaderLength = 6; const size_t length = *headerLen + *dataLen + *trailerLen; SkASSERT(length > 0); SkASSERT(length + (2 * kPFBSectionHeaderLength) <= srcLen); sk_sp<SkData> data(SkData::MakeUninitialized(length)); const uint8_t* const srcHeader = src + kPFBSectionHeaderLength; // There is a six-byte section header before header and data // (but not trailer) that we're not going to copy. const uint8_t* const srcData = srcHeader + *headerLen + kPFBSectionHeaderLength; const uint8_t* const srcTrailer = srcData + *headerLen; uint8_t* const resultHeader = (uint8_t*)data->writable_data(); uint8_t* const resultData = resultHeader + *headerLen; uint8_t* const resultTrailer = resultData + *dataLen; SkASSERT(resultTrailer + *trailerLen == resultHeader + length); memcpy(resultHeader, srcHeader, *headerLen); memcpy(resultData, srcData, *dataLen); memcpy(resultTrailer, srcTrailer, *trailerLen); return data; } // A PFA has to be converted for PDF. size_t hexDataLen; if (!parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen, trailerLen)) { return nullptr; } const size_t length = *headerLen + *dataLen + *trailerLen; SkASSERT(length > 0); auto data = SkData::MakeUninitialized(length); uint8_t* buffer = (uint8_t*)data->writable_data(); memcpy(buffer, src, *headerLen); uint8_t* const resultData = &(buffer[*headerLen]); const uint8_t* hexData = src + *headerLen; const uint8_t* trailer = hexData + hexDataLen; size_t outputOffset = 0; uint8_t dataByte = 0; // To hush compiler. bool highNibble = true; for (; hexData < trailer; hexData++) { int8_t curNibble = hexToBin(*hexData); if (curNibble < 0) { continue; } if (highNibble) { dataByte = curNibble << 4; highNibble = false; } else { dataByte |= curNibble; highNibble = true; resultData[outputOffset++] = dataByte; } } if (!highNibble) { resultData[outputOffset++] = dataByte; } SkASSERT(outputOffset == *dataLen); uint8_t* const resultTrailer = &(buffer[SkToInt(*headerLen + outputOffset)]); memcpy(resultTrailer, src + *headerLen + hexDataLen, *trailerLen); return data; } inline static bool can_embed(const SkAdvancedTypefaceMetrics& metrics) { return !SkToBool(metrics.fFlags & SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag); } inline static SkScalar from_font_units(SkScalar scaled, uint16_t emSize) { return emSize == 1000 ? scaled : scaled * 1000 / emSize; } static SkPDFIndirectReference make_type1_font_descriptor(SkPDFDocument* doc, const SkTypeface* typeface, const SkAdvancedTypefaceMetrics* info) { SkPDFDict descriptor("FontDescriptor"); uint16_t emSize = SkToU16(typeface->getUnitsPerEm()); if (info) { SkPDFFont::PopulateCommonFontDescriptor(&descriptor, *info, emSize, 0); if (can_embed(*info)) { int ttcIndex; size_t header SK_INIT_TO_AVOID_WARNING; size_t data SK_INIT_TO_AVOID_WARNING; size_t trailer SK_INIT_TO_AVOID_WARNING; std::unique_ptr<SkStreamAsset> rawFontData = typeface->openStream(&ttcIndex); sk_sp<SkData> fontData = convert_type1_font_stream(std::move(rawFontData), &header, &data, &trailer); if (fontData) { std::unique_ptr<SkPDFDict> dict = SkPDFMakeDict(); dict->insertInt("Length1", header); dict->insertInt("Length2", data); dict->insertInt("Length3", trailer); auto fontStream = SkMemoryStream::Make(std::move(fontData)); descriptor.insertRef("FontFile", SkPDFStreamOut(std::move(dict), std::move(fontStream), doc, true)); } } } return doc->emit(descriptor); } static const std::vector<SkString>& type_1_glyphnames(SkPDFDocument* canon, const SkTypeface* typeface) { SkFontID fontID = typeface->uniqueID(); const std::vector<SkString>* glyphNames = canon->fType1GlyphNames.find(fontID); if (!glyphNames) { std::vector<SkString> names(typeface->countGlyphs()); SkPDFFont::GetType1GlyphNames(*typeface, names.data()); glyphNames = canon->fType1GlyphNames.set(fontID, std::move(names)); } SkASSERT(glyphNames); return *glyphNames; } static SkPDFIndirectReference type1_font_descriptor(SkPDFDocument* doc, const SkTypeface* typeface) { SkFontID fontID = typeface->uniqueID(); if (SkPDFIndirectReference* ptr = doc->fFontDescriptors.find(fontID)) { return *ptr; } const SkAdvancedTypefaceMetrics* info = SkPDFFont::GetMetrics(typeface, doc); auto fontDescriptor = make_type1_font_descriptor(doc, typeface, info); doc->fFontDescriptors.set(fontID, fontDescriptor); return fontDescriptor; } void SkPDFEmitType1Font(const SkPDFFont& pdfFont, SkPDFDocument* doc) { SkTypeface* typeface = pdfFont.typeface(); const std::vector<SkString> glyphNames = type_1_glyphnames(doc, typeface); SkGlyphID firstGlyphID = pdfFont.firstGlyphID(); SkGlyphID lastGlyphID = pdfFont.lastGlyphID(); SkPDFDict font("Font"); font.insertRef("FontDescriptor", type1_font_descriptor(doc, typeface)); font.insertName("Subtype", "Type1"); if (const SkAdvancedTypefaceMetrics* info = SkPDFFont::GetMetrics(typeface, doc)) { font.insertName("BaseFont", info->fPostScriptName); } // glyphCount not including glyph 0 unsigned glyphCount = 1 + lastGlyphID - firstGlyphID; SkASSERT(glyphCount > 0 && glyphCount <= 255); font.insertInt("FirstChar", (size_t)0); font.insertInt("LastChar", (size_t)glyphCount); { int emSize; SkStrikeSpecStorage strikeSpec = SkStrikeSpecStorage::MakePDFVector(*typeface, &emSize); auto glyphCache = strikeSpec.findOrCreateExclusiveStrike(); auto widths = SkPDFMakeArray(); int glyphRangeSize = lastGlyphID - firstGlyphID + 2; SkAutoTArray<SkGlyphID> glyphIDs{glyphRangeSize}; glyphIDs[0] = 0; for (unsigned gId = firstGlyphID; gId <= lastGlyphID; gId++) { glyphIDs[gId - firstGlyphID + 1] = gId; } SkAutoTArray<SkPoint> advances{glyphRangeSize}; glyphCache->getAdvances( SkSpan<const SkGlyphID>{glyphIDs.get(), SkTo<size_t>(glyphRangeSize)}, advances.get()); for (int i = 0; i < glyphRangeSize; ++i) { widths->appendScalar(from_font_units(advances[i].x(), SkToU16(emSize))); } font.insertObject("Widths", std::move(widths)); } auto encDiffs = SkPDFMakeArray(); encDiffs->reserve(lastGlyphID - firstGlyphID + 3); encDiffs->appendInt(0); SkASSERT(glyphNames.size() > lastGlyphID); const SkString unknown("UNKNOWN"); encDiffs->appendName(glyphNames[0].isEmpty() ? unknown : glyphNames[0]); for (int gID = firstGlyphID; gID <= lastGlyphID; gID++) { encDiffs->appendName(glyphNames[gID].isEmpty() ? unknown : glyphNames[gID]); } auto encoding = SkPDFMakeDict("Encoding"); encoding->insertObject("Differences", std::move(encDiffs)); font.insertObject("Encoding", std::move(encoding)); doc->emit(font, pdfFont.indirectReference()); } <|endoftext|>
<commit_before><commit_msg>FInally passing all tests again.<commit_after><|endoftext|>
<commit_before><commit_msg>dont export config segmentwise<commit_after><|endoftext|>
<commit_before>// // Created by dar on 11/27/15. // #include <stdio.h> #include <stdlib.h> #include "Game.h" #include "../core/Core.h" #include "../core/map/TiledTxtMapLoader.h" #include "render/RenderManager.h" #include "InputManager.h" #include "../logging.h" Game::Game() { GuiButton *b = new GuiButton(GUI_TOP_RIGHT, 15, 15, 75, 75, 0); this->guiElements.push_back(b); } void Game::reload(unsigned int windowWidth, unsigned int windowHeight) { if (this->core == nullptr) { MapLoader *mapLoader = new TiledTxtMapLoader("test_map.txt"); Map *bmap = mapLoader->loadMap(); this->core = new Core(bmap); delete mapLoader; } for (GuiElement *e : this->guiElements) { e->reinit(windowWidth, windowHeight); } this->windowWidth = windowWidth; this->windowHeight = windowHeight; SDL_StartTextInput(); } void Game::tick(double deltaTime) { for (int i = 0; i < 256; i++) { //if (this->pressDelays[i] > 0) this->pressDelays[i]--; } this->core->getMap()->update(); this->core->getMap()->getWorld()->Step(deltaTime, 8, 3); for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) { Entity *entity = this->core->getMap()->getEntities().at(i); if (entity->isToBeDeleted()) { this->core->getMap()->removeEntity(entity); i--; } } double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX(); double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY(); if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05); if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05); } void Game::handleKeyboard(const Keypress *const keypress) { if (keypress[SDLK_c].isPressed()) { double angle = atan2(0, 0) + M_PI; //TODO EntityBullet *p = new EntityBullet(this->core, angle, 1); p->setX(this->core->getPlayer()->getX() - (p->getWidth()) + 0.5 * cos(angle)); p->setY(this->core->getPlayer()->getY() - (p->getHeight()) + 0.5 * sin(angle)); this->core->getMap()->addEntity(p); } if (keypress[SDLK_n].isPressed()) { EntityToy *p = new EntityToy(this->core); p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2); p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2); this->core->getMap()->addEntity(p); } if (keypress[SDLK_m].isPressed()) { SimpleShape *p = new SimpleShape(this->core, (unsigned int) (rand() % 3)); p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2); p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2); this->core->getMap()->addEntity(p); } if (keypress[SDLK_k].isPressed()) { if (this->core->getPlayer()->getToy() == nullptr) { this->core->getPlayer()->setToy(); } else { this->core->getPlayer()->eject(); } } double playerSpeed = this->core->getPlayer()->getSpeed(); if (keypress[SDLK_w].isDown()) { this->core->getPlayer()->applyImpulse(0, -playerSpeed); } if (keypress[SDLK_s].isDown()) { this->core->getPlayer()->applyImpulse(0, playerSpeed); } if (keypress[SDLK_a].isDown()) { this->core->getPlayer()->applyImpulse(-playerSpeed, 0); } if (keypress[SDLK_d].isDown()) { this->core->getPlayer()->applyImpulse(playerSpeed, 0); } if (keypress[SDLK_q].isPressed()) { this->core->stop(); } if (keypress[SDLK_MINUS].isDown()) { this->core->setBlockSize(this->core->getBlockSize() - 0.15); } if (keypress[SDLK_EQUALS].isDown()) { this->core->setBlockSize(this->core->getBlockSize() + 0.15); } } void Game::handleClick(const TouchPoint *const p) { float x = (float) ((-this->core->getCamX() - (double) this->windowWidth / 2 + p->x) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5); float y = (float) ((-this->core->getCamY() - (double) this->windowHeight / 2 + p->y) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5); if (p->id == SDL_BUTTON_LEFT) { if (p->state == 0) { this->heldEntity = this->getEntityAt(x, y); int i = 0; } else if (p->state == 2) { if (this->heldEntity != nullptr) { Entity *e = this->heldEntity; e->setX(x + e->getWidth() / 2); e->setY(y + e->getHeight() / 2); } } else if (p->state == 1) { if (this->heldEntity == nullptr) { SimpleShape *s = new SimpleShape(this->core, (unsigned int) (rand() % 3)); s->setX(x + s->getWidth() / 2); s->setY(y + s->getWidth() / 2); this->core->getMap()->addEntity(s); } else { this->heldEntity = nullptr; } } } } Entity *Game::getEntityAt(float x, float y) { for (Entity *e : this->core->getMap()->getEntities()) { if (x >= e->getX() - e->getWidth() && x <= e->getX() && y >= e->getY() - e->getHeight() && y <= e->getY()) { return e; } } return nullptr; } Game::~Game() { SDL_StopTextInput(); delete this->core; } <commit_msg>Added possibility to remove objects with right mouse button<commit_after>// // Created by dar on 11/27/15. // #include <stdio.h> #include <stdlib.h> #include "Game.h" #include "../core/Core.h" #include "../core/map/TiledTxtMapLoader.h" #include "render/RenderManager.h" #include "InputManager.h" #include "../logging.h" Game::Game() { GuiButton *b = new GuiButton(GUI_TOP_RIGHT, 15, 15, 75, 75, 0); this->guiElements.push_back(b); } void Game::reload(unsigned int windowWidth, unsigned int windowHeight) { if (this->core == nullptr) { MapLoader *mapLoader = new TiledTxtMapLoader("test_map.txt"); Map *bmap = mapLoader->loadMap(); this->core = new Core(bmap); delete mapLoader; } for (GuiElement *e : this->guiElements) { e->reinit(windowWidth, windowHeight); } this->windowWidth = windowWidth; this->windowHeight = windowHeight; SDL_StartTextInput(); } void Game::tick(double deltaTime) { for (int i = 0; i < 256; i++) { //if (this->pressDelays[i] > 0) this->pressDelays[i]--; } this->core->getMap()->update(); this->core->getMap()->getWorld()->Step(deltaTime, 8, 3); for (int i = 0; i < this->core->getMap()->getEntities().size(); i++) { Entity *entity = this->core->getMap()->getEntities().at(i); if (entity->isToBeDeleted()) { this->core->getMap()->removeEntity(entity); i--; } } double dx = (this->core->getPlayer()->getX() + this->core->getPlayer()->getWidth() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamX(); double dy = (this->core->getPlayer()->getY() + this->core->getPlayer()->getHeight() / 2 - 1) * this->core->getBlockSize() * this->core->getGeneralScale() + this->core->getCamY(); if (abs(dx) > 2) this->core->setCamX(-this->core->getCamX() + (dx) * 0.05); if (abs(dy) > 2) this->core->setCamY(-this->core->getCamY() + (dy) * 0.05); } void Game::handleKeyboard(const Keypress *const keypress) { if (keypress[SDLK_c].isPressed()) { double angle = atan2(0, 0) + M_PI; //TODO EntityBullet *p = new EntityBullet(this->core, angle, 1); p->setX(this->core->getPlayer()->getX() - (p->getWidth()) + 0.5 * cos(angle)); p->setY(this->core->getPlayer()->getY() - (p->getHeight()) + 0.5 * sin(angle)); this->core->getMap()->addEntity(p); } if (keypress[SDLK_n].isPressed()) { EntityToy *p = new EntityToy(this->core); p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2); p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2); this->core->getMap()->addEntity(p); } if (keypress[SDLK_m].isPressed()) { SimpleShape *p = new SimpleShape(this->core, (unsigned int) (rand() % 3)); p->setX(this->core->getPlayer()->getX() - this->core->getPlayer()->getWidth() / 2); p->setY(this->core->getPlayer()->getY() - this->core->getPlayer()->getHeight() / 2); this->core->getMap()->addEntity(p); } if (keypress[SDLK_k].isPressed()) { if (this->core->getPlayer()->getToy() == nullptr) { this->core->getPlayer()->setToy(); } else { this->core->getPlayer()->eject(); } } double playerSpeed = this->core->getPlayer()->getSpeed(); if (keypress[SDLK_w].isDown()) { this->core->getPlayer()->applyImpulse(0, -playerSpeed); } if (keypress[SDLK_s].isDown()) { this->core->getPlayer()->applyImpulse(0, playerSpeed); } if (keypress[SDLK_a].isDown()) { this->core->getPlayer()->applyImpulse(-playerSpeed, 0); } if (keypress[SDLK_d].isDown()) { this->core->getPlayer()->applyImpulse(playerSpeed, 0); } if (keypress[SDLK_q].isPressed()) { this->core->stop(); } if (keypress[SDLK_MINUS].isDown()) { this->core->setBlockSize(this->core->getBlockSize() - 0.15); } if (keypress[SDLK_EQUALS].isDown()) { this->core->setBlockSize(this->core->getBlockSize() + 0.15); } } void Game::handleClick(const TouchPoint *const p) { float x = (float) ((-this->core->getCamX() - (double) this->windowWidth / 2 + p->x) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5); float y = (float) ((-this->core->getCamY() - (double) this->windowHeight / 2 + p->y) / this->core->getGeneralScale() / this->core->getBlockSize() + 0.5); if (p->id == SDL_BUTTON_LEFT) { if (p->state == 0) { this->heldEntity = this->getEntityAt(x, y); int i = 0; } else if (p->state == 2) { if (this->heldEntity != nullptr) { Entity *e = this->heldEntity; e->setX(x + e->getWidth() / 2); e->setY(y + e->getHeight() / 2); } } else if (p->state == 1) { if (this->heldEntity == nullptr) { SimpleShape *s = new SimpleShape(this->core, (unsigned int) (rand() % 3)); s->setX(x + s->getWidth() / 2); s->setY(y + s->getWidth() / 2); this->core->getMap()->addEntity(s); } else { this->heldEntity = nullptr; } } } else if (p->id == SDL_BUTTON_RIGHT) { if (p->state == 0) { this->heldEntity = this->getEntityAt(x, y); } else if (p->state == 1) { if (this->heldEntity != nullptr && this->getEntityAt(x, y) == this->heldEntity) { this->heldEntity->remove(); } } } } Entity *Game::getEntityAt(float x, float y) { for (Entity *e : this->core->getMap()->getEntities()) { if (x >= e->getX() - e->getWidth() && x <= e->getX() && y >= e->getY() - e->getHeight() && y <= e->getY()) { return e; } } return nullptr; } Game::~Game() { SDL_StopTextInput(); delete this->core; } <|endoftext|>
<commit_before>// image feature extraction source code // implentations of image coding class and methods // Author: Bingqing Qu // License: GPLv3 #include "sireen/image_feature_extract.hpp" /** * Default constuctor */ ImageCoder::ImageCoder(void) { this->dsift_filter_ = NULL; /* default setting */ this->SetParams(128,128,8,16); } /** * Constructer overloading */ ImageCoder::ImageCoder(int std_width, int std_height, int step, int bin_size) { this->dsift_filter_ = NULL; this->SetParams(std_width,std_height,step,bin_size); } /** * Constructer overloading */ ImageCoder::ImageCoder(VlDsiftFilter* filter) { this->dsift_filter_ = filter; // switch off gaussian windowing vl_dsift_set_flat_window(dsift_filter_,true); // assume that x part equals to y part this->std_width_ = filter->imWidth; this->std_height_ = filter->imHeight; this->step_ = filter->stepX; this->bin_size_ = filter->geom.binSizeX; this->image_data_ = new vl_sift_pix[this->std_width_*this->std_height_]; } /** * Destructor */ ImageCoder::~ImageCoder(void){ vl_dsift_delete(this->dsift_filter_); delete this->image_data_; } /** * set dsiftfilter parameters of vlfeat library */ void ImageCoder::SetParams(int std_width, int std_height, int step, int bin_size) { this->std_width_ = std_width; this->std_height_ = std_height; this->step_ = step; this->bin_size_ = bin_size; this->image_data_ = new vl_sift_pix[this->std_width_*this->std_height_]; // if dsift filter was initialized if(this->dsift_filter_) { cout<< "set filter from EXIST"<<endl; this->dsift_filter_->imWidth = std_width_; this->dsift_filter_->imHeight = std_height_; VlDsiftDescriptorGeometry geom = *vl_dsift_get_geometry(this->dsift_filter_); geom.binSizeX = bin_size ; geom.binSizeY = bin_size ; vl_dsift_set_geometry(this->dsift_filter_, &geom); vl_dsift_set_steps(this->dsift_filter_, step, step); } else { cout<< "set filter from NULL"<<endl; this->dsift_filter_ = vl_dsift_new_basic(std_width, std_height, step, bin_size); // switch off gaussian windowing vl_dsift_set_flat_window(this->dsift_filter_,true); } } /** * encode dense-sift descriptors * * @param src_image opencv Mat image * @return the dense sift float-point descriptors */ float* ImageCoder::DsiftDescriptor(Mat src_image) { // check if source image is graylevel if (src_image.channels() != 1) cvtColor(src_image,src_image,CV_BGR2GRAY); // resize image if(src_image.rows != 0 || !(src_image.cols==this->std_width_ && src_image.rows==this->std_height_)) resize(src_image, src_image, Size(this->std_width_,this->std_height_), 0, 0, INTER_LINEAR); // validate if(!src_image.data) return NULL; // get valid input for dsift process // memset here to prevent memory leak memset(this->image_data_, 0, sizeof(vl_sift_pix) * this->std_width_*this->std_height_); uchar * row_ptr; for (int i=0; i<src_image.rows; i++) { row_ptr = src_image.ptr<uchar>(i); for (int j=0; j<src_image.cols; j++) { this->image_data_[i*src_image.cols+j] = row_ptr[j]; } } // process an image data vl_dsift_process(this->dsift_filter_,this->image_data_); // return the (unnormalized) sift descriptors // by default, the vlfeat library has normalized the descriptors // our following normalization eliminates those peaks (big value gradients) // and re-normalize them return this->dsift_filter_->descrs; } /** * compute linear local constraint coding descriptor * * @param src_image source image in opencv mat format * @param codebook codebook from sift-kmeans * @param ncb dimension of codebook * @param k get top k nearest codes */ string ImageCoder::LLCDescriptor(Mat src_image, float *codebook, const int ncb, const int k) { float* dsift_descr = this->DsiftDescriptor(src_image); if(!dsift_descr) throw runtime_error("image not loaded or resized properly"); // get sift descriptor size and number of keypoints int descr_size = vl_dsift_get_descriptor_size(dsift_filter_); int n_keypoints = vl_dsift_get_keypoint_num(dsift_filter_); // eliminate peak gradients and normalize // initialize dsift descriptors and codebook Eigen matrix MatrixXf mat_dsift= this->NormSift(dsift_descr,descr_size,n_keypoints,true); Map<MatrixXf> mat_cb(codebook,descr_size,ncb); // Step 1 - compute eucliean distance and sort // only in the case if all the sift features are not sure to // be nomalized to sum square 1, we arrange the distance as following MatrixXi knn_idx(n_keypoints, k); MatrixXf cdist(n_keypoints,ncb); // get euclidean distance of pairwise column features // use the trick of (u-v)^2 = u^2 + v^2 - 2uv // with assumption of Eigen column-wise manipulcation // is quite fast cdist = ( (mat_dsift.transpose() * mat_cb * -2).colwise() + mat_dsift.colwise().squaredNorm().transpose()).rowwise() + mat_cb.colwise().squaredNorm(); // The idea behand this is according to Jinjun Wang et al.(2010) // section 3, an approximate fast encoding llc can be achieved by // keeping only the significant top k values and set others to 0. typedef std::pair<double,int> ValueAndIndex; for (int i = 0; i< n_keypoints; i++) { std::priority_queue<ValueAndIndex, std::vector<ValueAndIndex>, std::greater<ValueAndIndex> > q; // use a priority queue to implement the pop top k for (int j = 0; j < ncb; j++) q.push(std::pair<double, int>(cdist(i,j),j)); for (int n = 0; n < k; n++ ) { knn_idx(i,n) = q.top().second; q.pop(); } } // Step 2 - compute the covariance and solve the analytic solution // put the results into llc cache // declare temp variables // identity matrix MatrixXf I = MatrixXf::Identity(k,k) * (1e-4); // llc caches MatrixXf caches = MatrixXf::Zero(n_keypoints,ncb); // subtraction between vectors MatrixXf U(descr_size,k); // covariance matrix MatrixXf covariance(k,k); // c^hat in the formular: // c^hat_i = (C_i + lambda * diag(d)) \ 1 // c_i = c^hat_i /1^T *c^hat_i // where C_i is the covariance matrix VectorXf c_hat(k); for(int i=0;i<n_keypoints;i++) { for(int j=0;j<k;j++) U.col(j) = (mat_cb.col(knn_idx(i,j)) - mat_dsift.col(i)) .cwiseAbs(); // compute covariance covariance = U.transpose()*U; c_hat = (covariance + I*covariance.trace()) .fullPivLu().solve(VectorXf::Ones(k)); c_hat = c_hat / c_hat.sum(); for(int j = 0 ; j < k ; j++) caches(i,knn_idx(i,j)) = c_hat(j); } // Step 3 - get the llc descriptor and normalize // get max coofficient for each column VectorXf llc = caches.colwise().maxCoeff(); // normalization llc.normalize(); // output the result in squeezed form // (i.e. bis after floating points are omitted) ostringstream s; s << llc(0); for(int i=1; i<ncb; i++) { s << ","; s << llc(i); } return s.str(); } /** * Optimized sift feature improvement and normalization * @param descriptors sift descriptors * @param row number of rows * @param col number of column * @param normalized flag for normalized input */ Eigen::MatrixXf ImageCoder::NormSift(float *descriptors, int row, int col, const bool normalized=false) { // use Eigen Map to pass float* to MatrixXf Map<MatrixXf> mat_dsift(descriptors,row,col); // clock_t s = clock(); // check flag if the input is already normalized if(normalized) { for(int i=0;i<col;i++) { // safely check all values not equals to 0 // to prevent float division exception if((mat_dsift.col(i).array()>0).any()) { // suppress the sharp (>0.2) features mat_dsift.col(i) = (mat_dsift.col(i).array() > 0.2) .select(0.2,mat_dsift.col(i)); // final normalization mat_dsift.col(i).normalize(); } } } else { for(int i=0;i<col;i++) { // compute root l2 norm float norm = mat_dsift.col(i).norm(); if(norm > 0) { // normalization and suppression mat_dsift.col(i) = ((mat_dsift.col(i).array() / norm) > 0.2).select(0.2,mat_dsift.col(i)); // normalization mat_dsift.col(i).normalize(); } } } return mat_dsift; } <commit_msg>edit i++ to ++i for good practice<commit_after>// image feature extraction source code // implentations of image coding class and methods // Author: Bingqing Qu // License: GPLv3 #include "sireen/image_feature_extract.hpp" /** * Default constuctor */ ImageCoder::ImageCoder(void) { this->dsift_filter_ = NULL; /* default setting */ this->SetParams(128,128,8,16); } /** * Constructer overloading */ ImageCoder::ImageCoder(int std_width, int std_height, int step, int bin_size) { this->dsift_filter_ = NULL; this->SetParams(std_width,std_height,step,bin_size); } /** * Constructer overloading */ ImageCoder::ImageCoder(VlDsiftFilter* filter) { this->dsift_filter_ = filter; // switch off gaussian windowing vl_dsift_set_flat_window(dsift_filter_,true); // assume that x part equals to y part this->std_width_ = filter->imWidth; this->std_height_ = filter->imHeight; this->step_ = filter->stepX; this->bin_size_ = filter->geom.binSizeX; this->image_data_ = new vl_sift_pix[this->std_width_*this->std_height_]; } /** * Destructor */ ImageCoder::~ImageCoder(void){ vl_dsift_delete(this->dsift_filter_); delete this->image_data_; } /** * set dsiftfilter parameters of vlfeat library */ void ImageCoder::SetParams(int std_width, int std_height, int step, int bin_size) { this->std_width_ = std_width; this->std_height_ = std_height; this->step_ = step; this->bin_size_ = bin_size; this->image_data_ = new vl_sift_pix[this->std_width_*this->std_height_]; // if dsift filter was initialized if(this->dsift_filter_) { cout<< "set filter from EXIST"<<endl; this->dsift_filter_->imWidth = std_width_; this->dsift_filter_->imHeight = std_height_; VlDsiftDescriptorGeometry geom = *vl_dsift_get_geometry(this->dsift_filter_); geom.binSizeX = bin_size ; geom.binSizeY = bin_size ; vl_dsift_set_geometry(this->dsift_filter_, &geom); vl_dsift_set_steps(this->dsift_filter_, step, step); } else { cout<< "set filter from NULL"<<endl; this->dsift_filter_ = vl_dsift_new_basic(std_width, std_height, step, bin_size); // switch off gaussian windowing vl_dsift_set_flat_window(this->dsift_filter_,true); } } /** * encode dense-sift descriptors * * @param src_image opencv Mat image * @return the dense sift float-point descriptors */ float* ImageCoder::DsiftDescriptor(Mat src_image) { // check if source image is graylevel if (src_image.channels() != 1) cvtColor(src_image,src_image,CV_BGR2GRAY); // resize image if(src_image.rows != 0 || !(src_image.cols==this->std_width_ && src_image.rows==this->std_height_)) resize(src_image, src_image, Size(this->std_width_,this->std_height_), 0, 0, INTER_LINEAR); // validate if(!src_image.data) return NULL; // get valid input for dsift process // memset here to prevent memory leak memset(this->image_data_, 0, sizeof(vl_sift_pix) * this->std_width_*this->std_height_); uchar * row_ptr; for (int i=0; i<src_image.rows; ++i) { row_ptr = src_image.ptr<uchar>(i); for (int j=0; j<src_image.cols; ++j) { this->image_data_[i*src_image.cols+j] = row_ptr[j]; } } // process an image data vl_dsift_process(this->dsift_filter_,this->image_data_); // return the (unnormalized) sift descriptors // by default, the vlfeat library has normalized the descriptors // our following normalization eliminates those peaks (big value gradients) // and re-normalize them return this->dsift_filter_->descrs; } /** * compute linear local constraint coding descriptor * * @param src_image source image in opencv mat format * @param codebook codebook from sift-kmeans * @param ncb dimension of codebook * @param k get top k nearest codes */ string ImageCoder::LLCDescriptor(Mat src_image, float *codebook, const int ncb, const int k) { float* dsift_descr = this->DsiftDescriptor(src_image); if(!dsift_descr) throw runtime_error("image not loaded or resized properly"); // get sift descriptor size and number of keypoints int descr_size = vl_dsift_get_descriptor_size(dsift_filter_); int n_keypoints = vl_dsift_get_keypoint_num(dsift_filter_); // eliminate peak gradients and normalize // initialize dsift descriptors and codebook Eigen matrix MatrixXf mat_dsift= this->NormSift(dsift_descr,descr_size,n_keypoints,true); Map<MatrixXf> mat_cb(codebook,descr_size,ncb); // Step 1 - compute eucliean distance and sort // only in the case if all the sift features are not sure to // be nomalized to sum square 1, we arrange the distance as following MatrixXi knn_idx(n_keypoints, k); MatrixXf cdist(n_keypoints,ncb); // get euclidean distance of pairwise column features // use the trick of (u-v)^2 = u^2 + v^2 - 2uv // with assumption of Eigen column-wise manipulcation // is quite fast cdist = ( (mat_dsift.transpose() * mat_cb * -2).colwise() + mat_dsift.colwise().squaredNorm().transpose()).rowwise() + mat_cb.colwise().squaredNorm(); // The idea behand this is according to Jinjun Wang et al.(2010) // section 3, an approximate fast encoding llc can be achieved by // keeping only the significant top k values and set others to 0. typedef std::pair<double,int> ValueAndIndex; for (int i = 0; i< n_keypoints; ++i) { std::priority_queue<ValueAndIndex, std::vector<ValueAndIndex>, std::greater<ValueAndIndex> > q; // use a priority queue to implement the pop top k for (int j = 0; j < ncb; ++j) q.push(std::pair<double, int>(cdist(i,j),j)); for (int n = 0; n < k; ++n ) { knn_idx(i,n) = q.top().second; q.pop(); } } // Step 2 - compute the covariance and solve the analytic solution // put the results into llc cache // declare temp variables // identity matrix MatrixXf I = MatrixXf::Identity(k,k) * (1e-4); // llc caches MatrixXf caches = MatrixXf::Zero(n_keypoints,ncb); // subtraction between vectors MatrixXf U(descr_size,k); // covariance matrix MatrixXf covariance(k,k); // c^hat in the formular: // c^hat_i = (C_i + lambda * diag(d)) \ 1 // c_i = c^hat_i /1^T *c^hat_i // where C_i is the covariance matrix VectorXf c_hat(k); for(int i=0;i<n_keypoints;++i) { for(int j=0;j<k;j++) U.col(j) = (mat_cb.col(knn_idx(i,j)) - mat_dsift.col(i)) .cwiseAbs(); // compute covariance covariance = U.transpose()*U; c_hat = (covariance + I*covariance.trace()) .fullPivLu().solve(VectorXf::Ones(k)); c_hat = c_hat / c_hat.sum(); for(int j = 0 ; j < k ; ++j) caches(i,knn_idx(i,j)) = c_hat(j); } // Step 3 - get the llc descriptor and normalize // get max coofficient for each column VectorXf llc = caches.colwise().maxCoeff(); // normalization llc.normalize(); // output the result in squeezed form // (i.e. bis after floating points are omitted) ostringstream s; s << llc(0); for(int i=1; i<ncb; ++i) { s << ","; s << llc(i); } return s.str(); } /** * Optimized sift feature improvement and normalization * @param descriptors sift descriptors * @param row number of rows * @param col number of column * @param normalized flag for normalized input */ Eigen::MatrixXf ImageCoder::NormSift(float *descriptors, int row, int col, const bool normalized=false) { // use Eigen Map to pass float* to MatrixXf Map<MatrixXf> mat_dsift(descriptors,row,col); // clock_t s = clock(); // check flag if the input is already normalized if(normalized) { for(int i=0;i<col;++i) { // safely check all values not equals to 0 // to prevent float division exception if((mat_dsift.col(i).array()>0).any()) { // suppress the sharp (>0.2) features mat_dsift.col(i) = (mat_dsift.col(i).array() > 0.2) .select(0.2,mat_dsift.col(i)); // final normalization mat_dsift.col(i).normalize(); } } } else { for(int i=0;i<col;++i) { // compute root l2 norm float norm = mat_dsift.col(i).norm(); if(norm > 0) { // normalization and suppression mat_dsift.col(i) = ((mat_dsift.col(i).array() / norm) > 0.2).select(0.2,mat_dsift.col(i)); // normalization mat_dsift.col(i).normalize(); } } } return mat_dsift; } <|endoftext|>
<commit_before><commit_msg>Remove macro usage from ChaCha<commit_after><|endoftext|>
<commit_before>// Xerus - A General Purpose Tensor Library // Copyright (C) 2014-2016 Benjamin Huber and Sebastian Wolf. // // Xerus is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // Xerus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with Xerus. If not, see <http://www.gnu.org/licenses/>. // // For further information on Xerus visit https://libXerus.org // or contact us at [email protected]. #include<xerus.h> #include "../../include/xerus/test/test.h" #include "../../include/xerus/misc/internal.h" using namespace xerus; static misc::UnitTest tt_crea("TT", "TTTensor_Creation", [](){ Index i,j,k; Tensor A1 = Tensor::random({2}); TTTensor TTA1(A1, 1e-14); Tensor B1; B1(i) = TTA1(i); TEST(approx_equal(B1,A1, 1e-14)); Tensor A2 = Tensor::random({2,2}); TTTensor TTA2(A2, 1e-14); Tensor B2; B2(j,i) = TTA2(j,i); TEST(approx_equal(B2,A2, 1e-14)); Tensor A3 = Tensor::random({2,7}); TTTensor TTA3(A3, 1e-14); Tensor B3; B3(j,i) = TTA3(j,i); TEST(approx_equal(B3,A3, 1e-14)); Tensor A4 = Tensor::random({2,2,2,2,2,2,2,2}); TTTensor TTA4(A4, 1e-14); Tensor B4; B4(j,i^7) = TTA4(j,i^7); TEST(approx_equal(B4,A4, 1e-14)); Tensor A5 = Tensor::random({7,5,3,1,4,2,8,1}); TTTensor TTA5(A5, 1e-14); Tensor B5; B5(j,i^7) = TTA5(j,i&1); TEST(approx_equal(B5,A5, 1e-14)); }); static misc::UnitTest tt_opcrea("TT", "TTOperator_Creation", [](){ Index i,j,k; Tensor A1 = Tensor::random({2,2}); TTOperator TTA1(A1, 1e-14); Tensor B1; B1(i^2) = TTA1(i^2); TEST(approx_equal(B1,A1, 1e-14)); Tensor A2 = Tensor::random({2,7}); TTOperator TTA2(A2, 1e-14); Tensor B2; B2(j,i) = TTA2(j,i); TEST(approx_equal(B2,A2, 1e-14)); Tensor A3 = Tensor::random({2,7,3,1}); TTOperator TTA3(A3, 1e-14); Tensor B3; B3(j,i^3) = TTA3(j,i^3); TEST(approx_equal(B3,A3, 1e-14)); Tensor A4 = Tensor::random({2,2,2,2,2,2,2,2}); TTOperator TTA4(A4, 1e-14); Tensor B4; B4(j,i^7) = TTA4(j,i&1); TEST(approx_equal(B4, A4, 1e-14)); Tensor A5 = Tensor::random({7,5,6,3,1,4,2,1}); TTOperator TTA5(A5, 1e-14); Tensor B5; B5(j,i^7) = TTA5(j,i^7); TEST(approx_equal(B5,A5, 1e-14)); }); static misc::UnitTest tt_crea_eps("TT", "creation_with_epsilon", [](){ const value_t EPS = 0.03; Tensor A = Tensor::random({5,5,5,5}); TTTensor ttA(A, EPS); TTTensor ttB(A, 0); ttB.round(EPS); size_t numDecrease = 5-ttA.rank(0) + 25 - ttA.rank(1) + 5 - ttA.rank(2); Index i; TEST(frob_norm(A(i&0)-Tensor(ttA)(i&0))/frob_norm(A) < numDecrease*EPS); TEST(ttA.ranks()[1] < 25); TEST(frob_norm(A(i&0)-Tensor(ttB)(i&0))/frob_norm(A) < numDecrease*EPS); TEST(ttB.ranks()[1] < 25); }); static misc::UnitTest tt_crea_full5("TT", "creation_from_fullTensor_5x5x5x5", [](){ Tensor A = Tensor::random({5,5,5,5}); TTTensor ttA(A); Tensor B(ttA); Index i; TEST(approx_equal(A,B, 1e-14)); TEST(frob_norm(A(i&0)-B(i&0)) < 1e-13*5*5*5*5); }); static misc::UnitTest tt_namedconstr("TT", "named_constructors", [](){ std::vector<size_t> dimensions(10, 2); std::vector<size_t> operatorDimensions(20,2); std::vector<size_t> ranks(9, 4); ranks[4] = 1; TTTensor X = TTTensor::random(dimensions, ranks); std::vector<size_t> found_ranks = X.ranks(); X.round(1e-16); MTEST(X.ranks() == found_ranks, X.ranks() << " vs " << found_ranks); // { // value_t mean = 0; // Tensor tmp(X); // for (size_t i=0; i<tmp.size; ++i) { // mean += tmp[i]; // } // mean /= (double)tmp.size; // MTEST(std::abs(mean) < 0.5, "X mean " << mean); // } TTOperator Xop = TTOperator::random(operatorDimensions, ranks); found_ranks = Xop.ranks(); Xop.round(1e-15); MTEST(Xop.ranks() == found_ranks, Xop.ranks() << " vs " << found_ranks); // { // value_t mean = 0; // Tensor tmp(Xop); // for (size_t i=0; i<tmp.size; ++i) { // mean += tmp[i]; // } // mean /= (double)tmp.size; // MTEST(std::abs(mean) < 0.5, "Xop mean " << mean); // } TTOperator id = TTOperator::identity(operatorDimensions); MTEST(id.ranks() == std::vector<size_t>(9,1), id.ranks()); Index i,j; TTTensor X2; X2(j/1) = id(j/2, i/2) * X(i/1); MTEST(frob_norm(X2-X) < 1e-14*1024, frob_norm(X2-X)); TTTensor ttones = TTTensor::ones(dimensions); MTEST(ttones.ranks() == std::vector<size_t>(9,1), ttones.ranks()); Tensor fones(ttones); MTEST(frob_norm(fones - Tensor::ones(dimensions)) < 1e-14*1024, "tt " << frob_norm(fones - Tensor::ones(dimensions)) ); TTOperator ttopones = TTOperator::ones(dimensions); MTEST(ttopones.ranks() == std::vector<size_t>(4,1), ttopones.ranks()); fones = Tensor(ttopones); MTEST(frob_norm(fones - Tensor::ones(dimensions)) < 1e-14*1024, "op " << frob_norm(fones - Tensor::ones(dimensions)) ); }); static misc::UnitTest tt_dyadic("TT", "dyadic_product", [](){ TTOperator o1 = TTOperator::random({10,10}, {}); TTOperator o2 = TTOperator::random({10,10}, {}); TTOperator o3 = TTOperator::random({10,10}, {}); TTTensor s1 = TTTensor::random({10},{}); TTTensor s2 = TTTensor::random({10},{}); TTTensor s3 = TTTensor::random({10},{}); TTOperator O = dyadic_product<true>({o1,o2,o3}); TTTensor S = dyadic_product<false>({s1,s2,s3}); TEST(O.cannonicalized); MTEST(O.corePosition == 0, O.corePosition); TEST(S.cannonicalized); MTEST(S.corePosition == 0, S.corePosition); Index i,j; value_t r1 = frob_norm(o1(i/2,j/2) * s1(j/1)); value_t r2 = frob_norm(o2(i/2,j/2) * s2(j/1)); value_t r3 = frob_norm(o3(i/2,j/2) * s3(j/1)); value_t R = frob_norm(O(i/2,j/2) * S(j/1)); TEST(std::abs(R - r1*r2*r3) < 1e-12); S = dyadic_product(S,TTTensor::ones({10})) + dyadic_product(TTTensor::ones({10}), S); TEST(S.cannonicalized); MTEST(S.corePosition == 0, S.corePosition); Tensor e0({10}, [&](const std::vector<size_t> &_idx){ return (_idx[0]==0?1.0:0.0); }); Tensor e1({10}, [&](const std::vector<size_t> &_idx){ return (_idx[0]==1?1.0:0.0); }); S *= 1/std::sqrt(2); S = dyadic_product(S,TTTensor(e0)) + dyadic_product(TTTensor(e1), S); TEST(S.cannonicalized); MTEST(S.corePosition == 0, S.corePosition); }); <commit_msg>Fixed missing cast in test case<commit_after>// Xerus - A General Purpose Tensor Library // Copyright (C) 2014-2016 Benjamin Huber and Sebastian Wolf. // // Xerus is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // Xerus is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with Xerus. If not, see <http://www.gnu.org/licenses/>. // // For further information on Xerus visit https://libXerus.org // or contact us at [email protected]. #include<xerus.h> #include "../../include/xerus/test/test.h" #include "../../include/xerus/misc/internal.h" using namespace xerus; static misc::UnitTest tt_crea("TT", "TTTensor_Creation", [](){ Index i,j,k; Tensor A1 = Tensor::random({2}); TTTensor TTA1(A1, 1e-14); Tensor B1; B1(i) = TTA1(i); TEST(approx_equal(B1,A1, 1e-14)); Tensor A2 = Tensor::random({2,2}); TTTensor TTA2(A2, 1e-14); Tensor B2; B2(j,i) = TTA2(j,i); TEST(approx_equal(B2,A2, 1e-14)); Tensor A3 = Tensor::random({2,7}); TTTensor TTA3(A3, 1e-14); Tensor B3; B3(j,i) = TTA3(j,i); TEST(approx_equal(B3,A3, 1e-14)); Tensor A4 = Tensor::random({2,2,2,2,2,2,2,2}); TTTensor TTA4(A4, 1e-14); Tensor B4; B4(j,i^7) = TTA4(j,i^7); TEST(approx_equal(B4,A4, 1e-14)); Tensor A5 = Tensor::random({7,5,3,1,4,2,8,1}); TTTensor TTA5(A5, 1e-14); Tensor B5; B5(j,i^7) = TTA5(j,i&1); TEST(approx_equal(B5,A5, 1e-14)); }); static misc::UnitTest tt_opcrea("TT", "TTOperator_Creation", [](){ Index i,j,k; Tensor A1 = Tensor::random({2,2}); TTOperator TTA1(A1, 1e-14); Tensor B1; B1(i^2) = TTA1(i^2); TEST(approx_equal(B1,A1, 1e-14)); Tensor A2 = Tensor::random({2,7}); TTOperator TTA2(A2, 1e-14); Tensor B2; B2(j,i) = TTA2(j,i); TEST(approx_equal(B2,A2, 1e-14)); Tensor A3 = Tensor::random({2,7,3,1}); TTOperator TTA3(A3, 1e-14); Tensor B3; B3(j,i^3) = TTA3(j,i^3); TEST(approx_equal(B3,A3, 1e-14)); Tensor A4 = Tensor::random({2,2,2,2,2,2,2,2}); TTOperator TTA4(A4, 1e-14); Tensor B4; B4(j,i^7) = TTA4(j,i&1); TEST(approx_equal(B4, A4, 1e-14)); Tensor A5 = Tensor::random({7,5,6,3,1,4,2,1}); TTOperator TTA5(A5, 1e-14); Tensor B5; B5(j,i^7) = TTA5(j,i^7); TEST(approx_equal(B5,A5, 1e-14)); }); static misc::UnitTest tt_crea_eps("TT", "creation_with_epsilon", [](){ const value_t EPS = 0.03; Tensor A = Tensor::random({5,5,5,5}); TTTensor ttA(A, EPS); TTTensor ttB(A, 0); ttB.round(EPS); size_t numDecrease = 5-ttA.rank(0) + 25 - ttA.rank(1) + 5 - ttA.rank(2); Index i; TEST(frob_norm(A(i&0)-Tensor(ttA)(i&0))/frob_norm(A) < static_cast<double>(numDecrease)*EPS); TEST(ttA.ranks()[1] < 25); TEST(frob_norm(A(i&0)-Tensor(ttB)(i&0))/frob_norm(A) < static_cast<double>(numDecrease)*EPS); TEST(ttB.ranks()[1] < 25); }); static misc::UnitTest tt_crea_full5("TT", "creation_from_fullTensor_5x5x5x5", [](){ Tensor A = Tensor::random({5,5,5,5}); TTTensor ttA(A); Tensor B(ttA); Index i; TEST(approx_equal(A,B, 1e-14)); TEST(frob_norm(A(i&0)-B(i&0)) < 1e-13*5*5*5*5); }); static misc::UnitTest tt_namedconstr("TT", "named_constructors", [](){ std::vector<size_t> dimensions(10, 2); std::vector<size_t> operatorDimensions(20,2); std::vector<size_t> ranks(9, 4); ranks[4] = 1; TTTensor X = TTTensor::random(dimensions, ranks); std::vector<size_t> found_ranks = X.ranks(); X.round(1e-16); MTEST(X.ranks() == found_ranks, X.ranks() << " vs " << found_ranks); // { // value_t mean = 0; // Tensor tmp(X); // for (size_t i=0; i<tmp.size; ++i) { // mean += tmp[i]; // } // mean /= (double)tmp.size; // MTEST(std::abs(mean) < 0.5, "X mean " << mean); // } TTOperator Xop = TTOperator::random(operatorDimensions, ranks); found_ranks = Xop.ranks(); Xop.round(1e-15); MTEST(Xop.ranks() == found_ranks, Xop.ranks() << " vs " << found_ranks); // { // value_t mean = 0; // Tensor tmp(Xop); // for (size_t i=0; i<tmp.size; ++i) { // mean += tmp[i]; // } // mean /= (double)tmp.size; // MTEST(std::abs(mean) < 0.5, "Xop mean " << mean); // } TTOperator id = TTOperator::identity(operatorDimensions); MTEST(id.ranks() == std::vector<size_t>(9,1), id.ranks()); Index i,j; TTTensor X2; X2(j/1) = id(j/2, i/2) * X(i/1); MTEST(frob_norm(X2-X) < 1e-14*1024, frob_norm(X2-X)); TTTensor ttones = TTTensor::ones(dimensions); MTEST(ttones.ranks() == std::vector<size_t>(9,1), ttones.ranks()); Tensor fones(ttones); MTEST(frob_norm(fones - Tensor::ones(dimensions)) < 1e-14*1024, "tt " << frob_norm(fones - Tensor::ones(dimensions)) ); TTOperator ttopones = TTOperator::ones(dimensions); MTEST(ttopones.ranks() == std::vector<size_t>(4,1), ttopones.ranks()); fones = Tensor(ttopones); MTEST(frob_norm(fones - Tensor::ones(dimensions)) < 1e-14*1024, "op " << frob_norm(fones - Tensor::ones(dimensions)) ); }); static misc::UnitTest tt_dyadic("TT", "dyadic_product", [](){ TTOperator o1 = TTOperator::random({10,10}, {}); TTOperator o2 = TTOperator::random({10,10}, {}); TTOperator o3 = TTOperator::random({10,10}, {}); TTTensor s1 = TTTensor::random({10},{}); TTTensor s2 = TTTensor::random({10},{}); TTTensor s3 = TTTensor::random({10},{}); TTOperator O = dyadic_product<true>({o1,o2,o3}); TTTensor S = dyadic_product<false>({s1,s2,s3}); TEST(O.cannonicalized); MTEST(O.corePosition == 0, O.corePosition); TEST(S.cannonicalized); MTEST(S.corePosition == 0, S.corePosition); Index i,j; value_t r1 = frob_norm(o1(i/2,j/2) * s1(j/1)); value_t r2 = frob_norm(o2(i/2,j/2) * s2(j/1)); value_t r3 = frob_norm(o3(i/2,j/2) * s3(j/1)); value_t R = frob_norm(O(i/2,j/2) * S(j/1)); TEST(std::abs(R - r1*r2*r3) < 1e-12); S = dyadic_product(S,TTTensor::ones({10})) + dyadic_product(TTTensor::ones({10}), S); TEST(S.cannonicalized); MTEST(S.corePosition == 0, S.corePosition); Tensor e0({10}, [&](const std::vector<size_t> &_idx){ return (_idx[0]==0?1.0:0.0); }); Tensor e1({10}, [&](const std::vector<size_t> &_idx){ return (_idx[0]==1?1.0:0.0); }); S *= 1/std::sqrt(2); S = dyadic_product(S,TTTensor(e0)) + dyadic_product(TTTensor(e1), S); TEST(S.cannonicalized); MTEST(S.corePosition == 0, S.corePosition); }); <|endoftext|>
<commit_before>#include "utest_helper.hpp" #include <string.h> static void runtime_use_host_ptr_large_image(void) { const size_t w = 4096; const size_t h = 4096; cl_image_format format; cl_image_desc desc; memset(&desc, 0x0, sizeof(cl_image_desc)); memset(&format, 0x0, sizeof(cl_image_format)); format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT32; desc.image_type = CL_MEM_OBJECT_IMAGE2D; desc.image_width = w; desc.image_height = h; size_t alignment = 4096; //page size if (cl_check_beignet()) alignment = 64; //cacheline size, beignet has loose limitaiont to enable userptr //src image int ret = posix_memalign(&buf_data[0], alignment, sizeof(uint32_t) * w * h * 4); OCL_ASSERT(ret == 0); for (size_t i = 0; i < w*h*4; ++i) ((uint32_t*)buf_data[0])[i] = i; OCL_CREATE_IMAGE(buf[0], CL_MEM_USE_HOST_PTR, &format, &desc, buf_data[0]); //dst image ret = posix_memalign(&buf_data[1], alignment, sizeof(uint32_t) * w * h * 4); OCL_ASSERT(ret == 0); for (size_t i = 0; i < w*h*4; ++i) ((uint32_t*)buf_data[1])[i] = 0; OCL_CREATE_IMAGE(buf[1], CL_MEM_USE_HOST_PTR, &format, &desc, buf_data[1]); OCL_CREATE_KERNEL("runtime_use_host_ptr_image"); // Run the kernel OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]); OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]); globals[0] = w; globals[1] = h; locals[0] = 16; locals[1] = 16; OCL_NDRANGE(2); // Check result size_t origin[3]; origin[0] = 0; origin[1] = 0; origin[2] = 0; size_t region[3]; region[0] = w; region[1] = h; region[2] = 1; size_t pitch = 0; void* mapptr = (int*)clEnqueueMapImage(queue, buf[1], CL_TRUE, CL_MAP_READ, origin, region, &pitch, NULL, 0, NULL, NULL, NULL); OCL_ASSERT(mapptr == buf_data[1]); for (uint32_t i = 0; i < w*h*4; ++i) { OCL_ASSERT(((uint32_t*)buf_data[0])[i] == ((uint32_t*)buf_data[1])[i]); } clEnqueueUnmapMemObject(queue, buf[1], mapptr, 0, NULL, NULL); free(buf_data[0]); buf_data[0] = NULL; free(buf_data[1]); buf_data[1] = NULL; } MAKE_UTEST_FROM_FUNCTION(runtime_use_host_ptr_large_image); <commit_msg>Add utest to test writing data into large image (TILE_Y) by map/unmap and USE_HOST_PTR mode.<commit_after>#include "utest_helper.hpp" #include <string.h> static void runtime_use_host_ptr_large_image(void) { const size_t w = 4096; const size_t h = 4096; cl_image_format format; cl_image_desc desc; memset(&desc, 0x0, sizeof(cl_image_desc)); memset(&format, 0x0, sizeof(cl_image_format)); format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT32; desc.image_type = CL_MEM_OBJECT_IMAGE2D; desc.image_width = w; desc.image_height = h; size_t alignment = 4096; //page size if (cl_check_beignet()) alignment = 64; //cacheline size, beignet has loose limitaiont to enable userptr //src image int ret = posix_memalign(&buf_data[0], alignment, sizeof(uint32_t) * w * h * 4); OCL_ASSERT(ret == 0); for (size_t i = 0; i < w*h*4; ++i) ((uint32_t*)buf_data[0])[i] = i; OCL_CREATE_IMAGE(buf[0], CL_MEM_USE_HOST_PTR, &format, &desc, buf_data[0]); //dst image ret = posix_memalign(&buf_data[1], alignment, sizeof(uint32_t) * w * h * 4); OCL_ASSERT(ret == 0); for (size_t i = 0; i < w*h*4; ++i) ((uint32_t*)buf_data[1])[i] = 0; OCL_CREATE_IMAGE(buf[1], CL_MEM_USE_HOST_PTR, &format, &desc, buf_data[1]); OCL_CREATE_KERNEL("runtime_use_host_ptr_image"); // Run the kernel OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]); OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]); globals[0] = w; globals[1] = h; locals[0] = 16; locals[1] = 16; OCL_NDRANGE(2); // Check result size_t origin[3]; origin[0] = 0; origin[1] = 0; origin[2] = 0; size_t region[3]; region[0] = w; region[1] = h; region[2] = 1; size_t pitch = 0; void* mapptr = (int*)clEnqueueMapImage(queue, buf[1], CL_TRUE, CL_MAP_READ, origin, region, &pitch, NULL, 0, NULL, NULL, NULL); OCL_ASSERT(mapptr == buf_data[1]); for (uint32_t i = 0; i < w*h*4; ++i) { OCL_ASSERT(((uint32_t*)buf_data[0])[i] == ((uint32_t*)buf_data[1])[i]); } clEnqueueUnmapMemObject(queue, buf[1], mapptr, 0, NULL, NULL); free(buf_data[0]); buf_data[0] = NULL; free(buf_data[1]); buf_data[1] = NULL; } MAKE_UTEST_FROM_FUNCTION(runtime_use_host_ptr_large_image); static void runtime_use_host_ptr_large_image_1(void) { cl_int status; const size_t w = 4096; const size_t h = 4096; size_t image_row_pitch, image_slice_pitch; size_t origin[3] = {5, 5, 0}; size_t region[3] = {8, 8, 1}; uint8_t *p = NULL; uint8_t *q = NULL; cl_image_format format; cl_image_desc desc; memset(&desc, 0x0, sizeof(cl_image_desc)); memset(&format, 0x0, sizeof(cl_image_format)); format.image_channel_order = CL_RGBA; format.image_channel_data_type = CL_UNSIGNED_INT32; desc.image_type = CL_MEM_OBJECT_IMAGE2D; desc.image_width = w; desc.image_height = h; size_t alignment = 4096; //page size if (cl_check_beignet()) alignment = 64; //cacheline size, beignet has loose limitaiont to enable userptr //src image int ret = posix_memalign(&buf_data[0], alignment, sizeof(uint32_t) * w * h * 4); OCL_ASSERT(ret == 0); for (size_t i = 0; i < w*h*4; ++i) ((uint32_t*)buf_data[0])[i] = i; OCL_CREATE_IMAGE(buf[0], CL_MEM_USE_HOST_PTR, &format, &desc, buf_data[0]); // Use mapping mode to fill data into src image buf_data[1] = clEnqueueMapImage(queue, buf[0], CL_TRUE, CL_MAP_WRITE, origin, region, &image_row_pitch, &image_slice_pitch, 0, NULL, NULL, &status); OCL_ASSERT(image_slice_pitch == 0); for (uint32_t j = 0; j < region[1]; ++j) for (uint32_t i = 0; i < region[0]; i++) for (uint32_t k = 0; k < 4; k++) ((uint32_t*)buf_data[1])[(j * w + i) * 4 + k] = rand(); clEnqueueUnmapMemObject(queue, buf[0], buf_data[1], 0, NULL, NULL); // Check src image origin[0] = 0; origin[1] = 0; origin[2] = 0; region[0] = w; region[1] = h; region[2] = 1; buf_data[1] = clEnqueueMapImage(queue, buf[0], CL_TRUE, CL_MAP_READ, origin, region, &image_row_pitch, &image_slice_pitch, 0, NULL, NULL, &status); OCL_ASSERT(image_slice_pitch == 0); for (uint32_t j = 0; j < h; ++j) { p = ((uint8_t*)buf_data[0]) + j * image_row_pitch; q = ((uint8_t*)buf_data[1]) + j * image_row_pitch; for (uint32_t i = 0; i < w; i++) for (uint32_t k = 0; k < 4; k++) OCL_ASSERT(((uint32_t*)p)[i * 4 + k] == ((uint32_t*)q)[i * 4 + k]); } clEnqueueUnmapMemObject(queue, buf[0], buf_data[1], 0, NULL, NULL); //dst image ret = posix_memalign(&buf_data[1], alignment, sizeof(uint32_t) * w * h * 4); OCL_ASSERT(ret == 0); for (size_t i = 0; i < w*h*4; ++i) ((uint32_t*)buf_data[1])[i] = 0; OCL_CREATE_IMAGE(buf[1], CL_MEM_USE_HOST_PTR, &format, &desc, buf_data[1]); OCL_CREATE_KERNEL("runtime_use_host_ptr_image"); // Run the kernel OCL_SET_ARG(0, sizeof(cl_mem), &buf[0]); OCL_SET_ARG(1, sizeof(cl_mem), &buf[1]); globals[0] = w; globals[1] = h; locals[0] = 16; locals[1] = 16; OCL_NDRANGE(2); // Check result origin[0] = 0; origin[1] = 0; origin[2] = 0; region[0] = w; region[1] = h; region[2] = 1; void* mapptr = (int*)clEnqueueMapImage(queue, buf[1], CL_TRUE, CL_MAP_READ, origin, region, &image_row_pitch, &image_slice_pitch, 0, NULL, NULL, NULL); OCL_ASSERT(mapptr == buf_data[1]); for (uint32_t j = 0; j < h; ++j) { p = ((uint8_t*)buf_data[0]) + j * image_row_pitch; q = ((uint8_t*)buf_data[1]) + j * image_row_pitch; for (uint32_t i = 0; i < w; i++) for (uint32_t k = 0; k < 4; k++) OCL_ASSERT(((uint32_t*)p)[i * 4 + k] == ((uint32_t*)q)[i * 4 + k]); } clEnqueueUnmapMemObject(queue, buf[1], mapptr, 0, NULL, NULL); free(buf_data[0]); buf_data[0] = NULL; free(buf_data[1]); buf_data[1] = NULL; } MAKE_UTEST_FROM_FUNCTION(runtime_use_host_ptr_large_image_1); <|endoftext|>
<commit_before>#include "credentialpassword.h" #include <QDebug> using namespace Cutelyst::Plugin; CredentialPassword::CredentialPassword() : m_passwordField(QLatin1String("password")), m_passwordType(None), m_hashType(QCryptographicHash::Md5) { } Authentication::User CredentialPassword::authenticate(Context *ctx, Authentication::Realm *realm, const CStringHash &authinfo) { Authentication::User user = realm->findUser(ctx, authinfo); if (!user.isNull()) { if (checkPassword(user, authinfo)) { return user; } qDebug() << "Password didn't match"; } else { qDebug() << "Unable to locate a user matching user info provided in realm"; } return Authentication::User(); } QString CredentialPassword::passwordField() const { return m_passwordField; } void CredentialPassword::setPasswordField(const QString &fieldName) { m_passwordField = fieldName; } CredentialPassword::Type CredentialPassword::passwordType() const { return m_passwordType; } void CredentialPassword::setPasswordType(CredentialPassword::Type type) { m_passwordType = type; } QCryptographicHash::Algorithm CredentialPassword::hashType() const { return m_hashType; } void CredentialPassword::setHashType(QCryptographicHash::Algorithm type) { m_hashType = type; } bool CredentialPassword::checkPassword(const Authentication::User &user, const CStringHash &authinfo) { QString password = authinfo.value(m_passwordField); QString storedPassword = user.value(m_passwordField); if (m_passwordType == None) { return true; } else if (m_passwordType == Clear) { return storedPassword == password; } else if (m_passwordType == Hashed) { QCryptographicHash hash(m_hashType); hash.addData(m_passwordPreSalt.toUtf8()); hash.addData(password.toUtf8()); hash.addData(m_passwordPostSalt.toUtf8()); QByteArray result = hash.result(); return storedPassword == result || storedPassword == result.toHex() || storedPassword == result.toBase64(); } else if (m_passwordType == SelfCheck) { return user.checkPassword(password); } return false; } <commit_msg>Implement some methods on credential password<commit_after>#include "credentialpassword.h" #include <QDebug> using namespace Cutelyst::Plugin; CredentialPassword::CredentialPassword() : m_passwordField(QLatin1String("password")), m_passwordType(None), m_hashType(QCryptographicHash::Md5) { } Authentication::User CredentialPassword::authenticate(Context *ctx, Authentication::Realm *realm, const CStringHash &authinfo) { Authentication::User user = realm->findUser(ctx, authinfo); if (!user.isNull()) { if (checkPassword(user, authinfo)) { return user; } qDebug() << "Password didn't match"; } else { qDebug() << "Unable to locate a user matching user info provided in realm"; } return Authentication::User(); } QString CredentialPassword::passwordField() const { return m_passwordField; } void CredentialPassword::setPasswordField(const QString &fieldName) { m_passwordField = fieldName; } CredentialPassword::Type CredentialPassword::passwordType() const { return m_passwordType; } void CredentialPassword::setPasswordType(CredentialPassword::Type type) { m_passwordType = type; } QCryptographicHash::Algorithm CredentialPassword::hashType() const { return m_hashType; } void CredentialPassword::setHashType(QCryptographicHash::Algorithm type) { m_hashType = type; } QString CredentialPassword::passwordPreSalt() const { return m_passwordPreSalt; } void CredentialPassword::setPasswordPreSalt(const QString &passwordPreSalt) { m_passwordPreSalt = passwordPreSalt; } QString CredentialPassword::passwordPostSalt() const { return m_passwordPostSalt; } void CredentialPassword::setPasswordPostSalt(const QString &passwordPostSalt) { m_passwordPostSalt = passwordPostSalt; } bool CredentialPassword::checkPassword(const Authentication::User &user, const CStringHash &authinfo) { QString password = authinfo.value(m_passwordField); QString storedPassword = user.value(m_passwordField); if (m_passwordType == None) { return true; } else if (m_passwordType == Clear) { return storedPassword == password; } else if (m_passwordType == Hashed) { QCryptographicHash hash(m_hashType); hash.addData(m_passwordPreSalt.toUtf8()); hash.addData(password.toUtf8()); hash.addData(m_passwordPostSalt.toUtf8()); QByteArray result = hash.result(); return storedPassword == result || storedPassword == result.toHex() || storedPassword == result.toBase64(); } else if (m_passwordType == SelfCheck) { return user.checkPassword(password); } return false; } <|endoftext|>
<commit_before>/* Copyright 2015 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "initVideoStreamingBlock.h" using namespace trik::blocks::details; InitVideoStreamingBlock::InitVideoStreamingBlock(kitBase::robotModel::RobotModelInterface &robotModel) : kitBase::blocksBase::common::DeviceBlock<trik::robotModel::parts::TrikShell>(robotModel) { } void InitVideoStreamingBlock::doJob(trik::robotModel::parts::TrikShell &shell) { const int qual = intProperty("Quality"); const bool blackwhite = boolProperty("blackwhite"); shell.initVideoStreaming(qual, blackwhite); emit done(mNextBlockId); } <commit_msg>Update initVideoStreamingBlock.cpp<commit_after>/* Copyright 2015 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "initVideoStreamingBlock.h" using namespace trik::blocks::details; InitVideoStreamingBlock::InitVideoStreamingBlock(kitBase::robotModel::RobotModelInterface &robotModel) : kitBase::blocksBase::common::DeviceBlock<trik::robotModel::parts::TrikShell>(robotModel) { } void InitVideoStreamingBlock::doJob(trik::robotModel::parts::TrikShell &shell) { const int qual = intProperty("Quality"); const bool grayscaled = boolProperty("Grayscaled"); shell.initVideoStreaming(qual, grayscaled); emit done(mNextBlockId); } <|endoftext|>
<commit_before>#include <iostream> #include "gtest/gtest.h" #include "onnx/onnxifi_loader.h" #include "onnx/onnxifi.h" #if defined(__APPLE__) #define ONNXIFI_DUMMY_LIBRARY "libonnxifi_dummy.dylib" #elif defined(_WIN32) #define ONNXIFI_DUMMY_LIBRARY L"onnxifi_dummy.dll" #else #define ONNXIFI_DUMMY_LIBRARY "libonnxifi_dummy.so" #endif namespace ONNX_NAMESPACE { namespace Test { TEST(OnnxifiLoadTest, OnnxifiDummyBackend) { #define EXPECT_EQ_OSS(X) EXPECT_EQ(X, ONNXIFI_STATUS_SUCCESS) onnxifi_library dummy_backend; EXPECT_TRUE(onnxifi_load(1, ONNXIFI_DUMMY_LIBRARY, &dummy_backend)); onnxBackendID backendID; onnxBackend backend; onnxEvent event; onnxGraph graph; // Testing onnxGetBackendIDs size_t numBackends = -1; EXPECT_EQ_OSS(dummy_backend.onnxGetBackendIDs(&backendID, &numBackends)); EXPECT_EQ(numBackends, 1); // Testing onnxReleaseBackendID EXPECT_EQ_OSS(dummy_backend.onnxReleaseBackendID(backendID)); // Testing onnxGetBackendInfo onnxBackendInfo infoType = 0; char infoValue[11] = "abc"; size_t infoValueSize = 3; EXPECT_EQ_OSS(dummy_backend.onnxGetBackendInfo( backendID, infoType, infoValue, &infoValueSize)); EXPECT_EQ(infoValue[0], 0); // Testing onnxGetBackendCompatibility char onnxModel[] = ""; size_t onnxModelSize = 0; EXPECT_EQ_OSS(dummy_backend.onnxGetBackendCompatibility( backendID, onnxModelSize, onnxModel)); // Testing onnxInitBackend const uint64_t backendProperties[] = { ONNXIFI_BACKEND_PROPERTY_NONE }; EXPECT_EQ_OSS( dummy_backend.onnxInitBackend(backendID, &auxpropertiesList, &backend)); // Testing onnxReleaseBackend EXPECT_EQ_OSS(dummy_backend.onnxReleaseBackend(backend)); // Testing onnxInitEvent EXPECT_EQ_OSS(dummy_backend.onnxInitEvent(backend, &event)); // Testing onnxSignalEvent EXPECT_EQ_OSS(dummy_backend.onnxSignalEvent(event)); // Testing onnxWaitEvent EXPECT_EQ_OSS(dummy_backend.onnxWaitEvent(event)); // Testing onnxReleaseEvent EXPECT_EQ_OSS(dummy_backend.onnxReleaseEvent(event)); // Testing onnxInitGraph uint32_t weightCount = 1; onnxTensorDescriptorV1 weightDescriptors; const uint64_t graphProperties[] = { ONNXIFI_GRAPH_PROPERTY_NONE }; EXPECT_EQ_OSS(dummy_backend.onnxInitGraph( backend, graphProperties, onnxModelSize, &onnxModel, weightCount, &weightDescriptors, &graph)); // Testing onnxInitGraph uint32_t inputsCount = 1; onnxTensorDescriptorV1 inputDescriptors; uint32_t outputsCount = 1; onnxTensorDescriptorV1 outputDescriptors; EXPECT_EQ_OSS(dummy_backend.onnxSetGraphIO( graph, inputsCount, &inputDescriptors, outputsCount, &outputDescriptors)); // Testing onnxRunGraph onnxMemoryFenceV1 inputFence, outputFence; EXPECT_EQ_OSS(dummy_backend.onnxRunGraph(graph, &inputFence, &outputFence)); EXPECT_EQ(outputFence.type, ONNXIFI_SYNCHRONIZATION_EVENT); // Testing onnxReleaseGraph EXPECT_EQ_OSS(dummy_backend.onnxReleaseGraph(graph)); #undef EXPECT_EQ_OSS } } // namespace Test } // namespace ONNX_NAMESPACE <commit_msg>Fix compilation bug in ONNXIFI dummy backend test introduced in #1256 (#1261)<commit_after>#include <iostream> #include "gtest/gtest.h" #include "onnx/onnxifi_loader.h" #include "onnx/onnxifi.h" #if defined(__APPLE__) #define ONNXIFI_DUMMY_LIBRARY "libonnxifi_dummy.dylib" #elif defined(_WIN32) #define ONNXIFI_DUMMY_LIBRARY L"onnxifi_dummy.dll" #else #define ONNXIFI_DUMMY_LIBRARY "libonnxifi_dummy.so" #endif namespace ONNX_NAMESPACE { namespace Test { TEST(OnnxifiLoadTest, OnnxifiDummyBackend) { #define EXPECT_EQ_OSS(X) EXPECT_EQ(X, ONNXIFI_STATUS_SUCCESS) onnxifi_library dummy_backend; EXPECT_TRUE(onnxifi_load(1, ONNXIFI_DUMMY_LIBRARY, &dummy_backend)); onnxBackendID backendID; onnxBackend backend; onnxEvent event; onnxGraph graph; // Testing onnxGetBackendIDs size_t numBackends = -1; EXPECT_EQ_OSS(dummy_backend.onnxGetBackendIDs(&backendID, &numBackends)); EXPECT_EQ(numBackends, 1); // Testing onnxReleaseBackendID EXPECT_EQ_OSS(dummy_backend.onnxReleaseBackendID(backendID)); // Testing onnxGetBackendInfo onnxBackendInfo infoType = 0; char infoValue[11] = "abc"; size_t infoValueSize = 3; EXPECT_EQ_OSS(dummy_backend.onnxGetBackendInfo( backendID, infoType, infoValue, &infoValueSize)); EXPECT_EQ(infoValue[0], 0); // Testing onnxGetBackendCompatibility char onnxModel[] = ""; size_t onnxModelSize = 0; EXPECT_EQ_OSS(dummy_backend.onnxGetBackendCompatibility( backendID, onnxModelSize, onnxModel)); // Testing onnxInitBackend const uint64_t backendProperties[] = { ONNXIFI_BACKEND_PROPERTY_NONE }; EXPECT_EQ_OSS( dummy_backend.onnxInitBackend(backendID, backendProperties, &backend)); // Testing onnxReleaseBackend EXPECT_EQ_OSS(dummy_backend.onnxReleaseBackend(backend)); // Testing onnxInitEvent EXPECT_EQ_OSS(dummy_backend.onnxInitEvent(backend, &event)); // Testing onnxSignalEvent EXPECT_EQ_OSS(dummy_backend.onnxSignalEvent(event)); // Testing onnxWaitEvent EXPECT_EQ_OSS(dummy_backend.onnxWaitEvent(event)); // Testing onnxReleaseEvent EXPECT_EQ_OSS(dummy_backend.onnxReleaseEvent(event)); // Testing onnxInitGraph uint32_t weightCount = 1; onnxTensorDescriptorV1 weightDescriptors; const uint64_t graphProperties[] = { ONNXIFI_GRAPH_PROPERTY_NONE }; EXPECT_EQ_OSS(dummy_backend.onnxInitGraph( backend, graphProperties, onnxModelSize, &onnxModel, weightCount, &weightDescriptors, &graph)); // Testing onnxInitGraph uint32_t inputsCount = 1; onnxTensorDescriptorV1 inputDescriptors; uint32_t outputsCount = 1; onnxTensorDescriptorV1 outputDescriptors; EXPECT_EQ_OSS(dummy_backend.onnxSetGraphIO( graph, inputsCount, &inputDescriptors, outputsCount, &outputDescriptors)); // Testing onnxRunGraph onnxMemoryFenceV1 inputFence, outputFence; EXPECT_EQ_OSS(dummy_backend.onnxRunGraph(graph, &inputFence, &outputFence)); EXPECT_EQ(outputFence.type, ONNXIFI_SYNCHRONIZATION_EVENT); // Testing onnxReleaseGraph EXPECT_EQ_OSS(dummy_backend.onnxReleaseGraph(graph)); #undef EXPECT_EQ_OSS } } // namespace Test } // namespace ONNX_NAMESPACE <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <boost/range/iterator_range.hpp> #include "bytes.hh" #include <seastar/core/unaligned.hh> #include "hashing.hh" #include <seastar/core/simple-stream.hh> /** * Utility for writing data into a buffer when its final size is not known up front. * * Internally the data is written into a chain of chunks allocated on-demand. * No resizing of previously written data happens. * */ class bytes_ostream { public: using size_type = bytes::size_type; using value_type = bytes::value_type; static constexpr size_type max_chunk_size() { return 128 * 1024; } private: static_assert(sizeof(value_type) == 1, "value_type is assumed to be one byte long"); struct chunk { // FIXME: group fragment pointers to reduce pointer chasing when packetizing std::unique_ptr<chunk> next; ~chunk() { auto p = std::move(next); while (p) { // Avoid recursion when freeing chunks auto p_next = std::move(p->next); p = std::move(p_next); } } size_type offset; // Also means "size" after chunk is closed size_type size; value_type data[0]; void operator delete(void* ptr) { free(ptr); } }; static constexpr size_type default_chunk_size{512}; private: std::unique_ptr<chunk> _begin; chunk* _current; size_type _size; size_type _initial_chunk_size = default_chunk_size; public: class fragment_iterator : public std::iterator<std::input_iterator_tag, bytes_view> { chunk* _current = nullptr; public: fragment_iterator() = default; fragment_iterator(chunk* current) : _current(current) {} fragment_iterator(const fragment_iterator&) = default; fragment_iterator& operator=(const fragment_iterator&) = default; bytes_view operator*() const { return { _current->data, _current->offset }; } bytes_view operator->() const { return *(*this); } fragment_iterator& operator++() { _current = _current->next.get(); return *this; } fragment_iterator operator++(int) { fragment_iterator tmp(*this); ++(*this); return tmp; } bool operator==(const fragment_iterator& other) const { return _current == other._current; } bool operator!=(const fragment_iterator& other) const { return _current != other._current; } }; private: inline size_type current_space_left() const { if (!_current) { return 0; } return _current->size - _current->offset; } // Figure out next chunk size. // - must be enough for data_size // - must be at least _initial_chunk_size // - try to double each time to prevent too many allocations // - do not exceed max_chunk_size size_type next_alloc_size(size_t data_size) const { auto next_size = _current ? _current->size * 2 : _initial_chunk_size; next_size = std::min(next_size, max_chunk_size()); // FIXME: check for overflow? return std::max<size_type>(next_size, data_size + sizeof(chunk)); } // Makes room for a contiguous region of given size. // The region is accounted for as already written. // size must not be zero. value_type* alloc(size_type size) { if (size <= current_space_left()) { auto ret = _current->data + _current->offset; _current->offset += size; _size += size; return ret; } else { auto alloc_size = next_alloc_size(size); auto space = malloc(alloc_size); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = size; new_chunk->size = alloc_size - sizeof(chunk); if (_current) { _current->next = std::move(new_chunk); _current = _current->next.get(); } else { _begin = std::move(new_chunk); _current = _begin.get(); } _size += size; return _current->data; }; } public: explicit bytes_ostream(size_t initial_chunk_size) noexcept : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(initial_chunk_size) { } bytes_ostream() noexcept : bytes_ostream(default_chunk_size) {} bytes_ostream(bytes_ostream&& o) noexcept : _begin(std::move(o._begin)) , _current(o._current) , _size(o._size) , _initial_chunk_size(o._initial_chunk_size) { o._current = nullptr; o._size = 0; } bytes_ostream(const bytes_ostream& o) : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(o._initial_chunk_size) { append(o); } bytes_ostream& operator=(const bytes_ostream& o) { if (this != &o) { auto x = bytes_ostream(o); *this = std::move(x); } return *this; } bytes_ostream& operator=(bytes_ostream&& o) noexcept { if (this != &o) { this->~bytes_ostream(); new (this) bytes_ostream(std::move(o)); } return *this; } template <typename T> struct place_holder { value_type* ptr; // makes the place_holder looks like a stream seastar::simple_output_stream get_stream() { return seastar::simple_output_stream(reinterpret_cast<char*>(ptr), sizeof(T)); } }; // Returns a place holder for a value to be written later. template <typename T> inline std::enable_if_t<std::is_fundamental<T>::value, place_holder<T>> write_place_holder() { return place_holder<T>{alloc(sizeof(T))}; } value_type* write_place_holder(size_type size) { return alloc(size); } // Writes given sequence of bytes inline void write(bytes_view v) { if (v.empty()) { return; } auto this_size = std::min(v.size(), size_t(current_space_left())); if (this_size) { memcpy(_current->data + _current->offset, v.begin(), this_size); _current->offset += this_size; _size += this_size; v.remove_prefix(this_size); } while (!v.empty()) { auto this_size = std::min(v.size(), size_t(max_chunk_size())); std::copy_n(v.begin(), this_size, alloc(this_size)); v.remove_prefix(this_size); } } void write(const char* ptr, size_t size) { write(bytes_view(reinterpret_cast<const signed char*>(ptr), size)); } bool is_linearized() const { return !_begin || !_begin->next; } // Call only when is_linearized() bytes_view view() const { assert(is_linearized()); if (!_current) { return bytes_view(); } return bytes_view(_current->data, _size); } // Makes the underlying storage contiguous and returns a view to it. // Invalidates all previously created placeholders. bytes_view linearize() { if (is_linearized()) { return view(); } auto space = malloc(_size + sizeof(chunk)); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = _size; new_chunk->size = _size; auto dst = new_chunk->data; auto r = _begin.get(); while (r) { auto next = r->next.get(); dst = std::copy_n(r->data, r->offset, dst); r = next; } _current = new_chunk.get(); _begin = std::move(new_chunk); return bytes_view(_current->data, _size); } // Returns the amount of bytes written so far size_type size() const { return _size; } bool empty() const { return _size == 0; } void reserve(size_t size) { // FIXME: implement } void append(const bytes_ostream& o) { for (auto&& bv : o.fragments()) { write(bv); } } // Removes n bytes from the end of the bytes_ostream. // Beware of O(n) algorithm. void remove_suffix(size_t n) { _size -= n; auto left = _size; auto current = _begin.get(); while (current) { if (current->offset >= left) { current->offset = left; _current = current; current->next.reset(); return; } left -= current->offset; current = current->next.get(); } } // begin() and end() form an input range to bytes_view representing fragments. // Any modification of this instance invalidates iterators. fragment_iterator begin() const { return { _begin.get() }; } fragment_iterator end() const { return { nullptr }; } boost::iterator_range<fragment_iterator> fragments() const { return { begin(), end() }; } struct position { chunk* _chunk; size_type _offset; }; position pos() const { return { _current, _current ? _current->offset : 0 }; } // Returns the amount of bytes written since given position. // "pos" must be valid. size_type written_since(position pos) { chunk* c = pos._chunk; if (!c) { return _size; } size_type total = c->offset - pos._offset; c = c->next.get(); while (c) { total += c->offset; c = c->next.get(); } return total; } // Rollbacks all data written after "pos". // Invalidates all placeholders and positions created after "pos". void retract(position pos) { if (!pos._chunk) { *this = {}; return; } _size -= written_since(pos); _current = pos._chunk; _current->next = nullptr; _current->offset = pos._offset; } void reduce_chunk_count() { // FIXME: This is a simplified version. It linearizes the whole buffer // if its size is below max_chunk_size. We probably could also gain // some read performance by doing "real" reduction, i.e. merging // all chunks until all but the last one is max_chunk_size. if (size() < max_chunk_size()) { linearize(); } } bool operator==(const bytes_ostream& other) const { auto as = fragments().begin(); auto as_end = fragments().end(); auto bs = other.fragments().begin(); auto bs_end = other.fragments().end(); auto a = *as++; auto b = *bs++; while (!a.empty() || !b.empty()) { auto now = std::min(a.size(), b.size()); if (!std::equal(a.begin(), a.begin() + now, b.begin(), b.begin() + now)) { return false; } a.remove_prefix(now); if (a.empty() && as != as_end) { a = *as++; } b.remove_prefix(now); if (b.empty() && bs != bs_end) { b = *bs++; } } return true; } bool operator!=(const bytes_ostream& other) const { return !(*this == other); } // Makes this instance empty. // // The first buffer is not deallocated, so callers may rely on the // fact that if they write less than the initial chunk size between // the clear() calls then writes will not involve any memory allocations, // except for the first write made on this instance. void clear() { if (_begin) { _begin->offset = 0; _size = 0; _current = _begin.get(); _begin->next.reset(); } } }; <commit_msg>bytes_ostream: Optimize writing of fixed-size types<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <boost/range/iterator_range.hpp> #include "bytes.hh" #include <seastar/core/unaligned.hh> #include "hashing.hh" #include <seastar/core/simple-stream.hh> /** * Utility for writing data into a buffer when its final size is not known up front. * * Internally the data is written into a chain of chunks allocated on-demand. * No resizing of previously written data happens. * */ class bytes_ostream { public: using size_type = bytes::size_type; using value_type = bytes::value_type; static constexpr size_type max_chunk_size() { return 128 * 1024; } private: static_assert(sizeof(value_type) == 1, "value_type is assumed to be one byte long"); struct chunk { // FIXME: group fragment pointers to reduce pointer chasing when packetizing std::unique_ptr<chunk> next; ~chunk() { auto p = std::move(next); while (p) { // Avoid recursion when freeing chunks auto p_next = std::move(p->next); p = std::move(p_next); } } size_type offset; // Also means "size" after chunk is closed size_type size; value_type data[0]; void operator delete(void* ptr) { free(ptr); } }; static constexpr size_type default_chunk_size{512}; private: std::unique_ptr<chunk> _begin; chunk* _current; size_type _size; size_type _initial_chunk_size = default_chunk_size; public: class fragment_iterator : public std::iterator<std::input_iterator_tag, bytes_view> { chunk* _current = nullptr; public: fragment_iterator() = default; fragment_iterator(chunk* current) : _current(current) {} fragment_iterator(const fragment_iterator&) = default; fragment_iterator& operator=(const fragment_iterator&) = default; bytes_view operator*() const { return { _current->data, _current->offset }; } bytes_view operator->() const { return *(*this); } fragment_iterator& operator++() { _current = _current->next.get(); return *this; } fragment_iterator operator++(int) { fragment_iterator tmp(*this); ++(*this); return tmp; } bool operator==(const fragment_iterator& other) const { return _current == other._current; } bool operator!=(const fragment_iterator& other) const { return _current != other._current; } }; private: inline size_type current_space_left() const { if (!_current) { return 0; } return _current->size - _current->offset; } // Figure out next chunk size. // - must be enough for data_size // - must be at least _initial_chunk_size // - try to double each time to prevent too many allocations // - do not exceed max_chunk_size size_type next_alloc_size(size_t data_size) const { auto next_size = _current ? _current->size * 2 : _initial_chunk_size; next_size = std::min(next_size, max_chunk_size()); // FIXME: check for overflow? return std::max<size_type>(next_size, data_size + sizeof(chunk)); } // Makes room for a contiguous region of given size. // The region is accounted for as already written. // size must not be zero. [[gnu::always_inline]] value_type* alloc(size_type size) { if (__builtin_expect(size <= current_space_left(), true)) { auto ret = _current->data + _current->offset; _current->offset += size; _size += size; return ret; } else { return alloc_new(size); } } [[gnu::noinline]] value_type* alloc_new(size_type size) { auto alloc_size = next_alloc_size(size); auto space = malloc(alloc_size); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = size; new_chunk->size = alloc_size - sizeof(chunk); if (_current) { _current->next = std::move(new_chunk); _current = _current->next.get(); } else { _begin = std::move(new_chunk); _current = _begin.get(); } _size += size; return _current->data; } public: explicit bytes_ostream(size_t initial_chunk_size) noexcept : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(initial_chunk_size) { } bytes_ostream() noexcept : bytes_ostream(default_chunk_size) {} bytes_ostream(bytes_ostream&& o) noexcept : _begin(std::move(o._begin)) , _current(o._current) , _size(o._size) , _initial_chunk_size(o._initial_chunk_size) { o._current = nullptr; o._size = 0; } bytes_ostream(const bytes_ostream& o) : _begin() , _current(nullptr) , _size(0) , _initial_chunk_size(o._initial_chunk_size) { append(o); } bytes_ostream& operator=(const bytes_ostream& o) { if (this != &o) { auto x = bytes_ostream(o); *this = std::move(x); } return *this; } bytes_ostream& operator=(bytes_ostream&& o) noexcept { if (this != &o) { this->~bytes_ostream(); new (this) bytes_ostream(std::move(o)); } return *this; } template <typename T> struct place_holder { value_type* ptr; // makes the place_holder looks like a stream seastar::simple_output_stream get_stream() { return seastar::simple_output_stream(reinterpret_cast<char*>(ptr), sizeof(T)); } }; // Returns a place holder for a value to be written later. template <typename T> inline std::enable_if_t<std::is_fundamental<T>::value, place_holder<T>> write_place_holder() { return place_holder<T>{alloc(sizeof(T))}; } [[gnu::always_inline]] value_type* write_place_holder(size_type size) { return alloc(size); } // Writes given sequence of bytes [[gnu::always_inline]] inline void write(bytes_view v) { if (v.empty()) { return; } auto this_size = std::min(v.size(), size_t(current_space_left())); if (__builtin_expect(this_size, true)) { memcpy(_current->data + _current->offset, v.begin(), this_size); _current->offset += this_size; _size += this_size; v.remove_prefix(this_size); } while (!v.empty()) { auto this_size = std::min(v.size(), size_t(max_chunk_size())); std::copy_n(v.begin(), this_size, alloc_new(this_size)); v.remove_prefix(this_size); } } [[gnu::always_inline]] void write(const char* ptr, size_t size) { write(bytes_view(reinterpret_cast<const signed char*>(ptr), size)); } bool is_linearized() const { return !_begin || !_begin->next; } // Call only when is_linearized() bytes_view view() const { assert(is_linearized()); if (!_current) { return bytes_view(); } return bytes_view(_current->data, _size); } // Makes the underlying storage contiguous and returns a view to it. // Invalidates all previously created placeholders. bytes_view linearize() { if (is_linearized()) { return view(); } auto space = malloc(_size + sizeof(chunk)); if (!space) { throw std::bad_alloc(); } auto new_chunk = std::unique_ptr<chunk>(new (space) chunk()); new_chunk->offset = _size; new_chunk->size = _size; auto dst = new_chunk->data; auto r = _begin.get(); while (r) { auto next = r->next.get(); dst = std::copy_n(r->data, r->offset, dst); r = next; } _current = new_chunk.get(); _begin = std::move(new_chunk); return bytes_view(_current->data, _size); } // Returns the amount of bytes written so far size_type size() const { return _size; } bool empty() const { return _size == 0; } void reserve(size_t size) { // FIXME: implement } void append(const bytes_ostream& o) { for (auto&& bv : o.fragments()) { write(bv); } } // Removes n bytes from the end of the bytes_ostream. // Beware of O(n) algorithm. void remove_suffix(size_t n) { _size -= n; auto left = _size; auto current = _begin.get(); while (current) { if (current->offset >= left) { current->offset = left; _current = current; current->next.reset(); return; } left -= current->offset; current = current->next.get(); } } // begin() and end() form an input range to bytes_view representing fragments. // Any modification of this instance invalidates iterators. fragment_iterator begin() const { return { _begin.get() }; } fragment_iterator end() const { return { nullptr }; } boost::iterator_range<fragment_iterator> fragments() const { return { begin(), end() }; } struct position { chunk* _chunk; size_type _offset; }; position pos() const { return { _current, _current ? _current->offset : 0 }; } // Returns the amount of bytes written since given position. // "pos" must be valid. size_type written_since(position pos) { chunk* c = pos._chunk; if (!c) { return _size; } size_type total = c->offset - pos._offset; c = c->next.get(); while (c) { total += c->offset; c = c->next.get(); } return total; } // Rollbacks all data written after "pos". // Invalidates all placeholders and positions created after "pos". void retract(position pos) { if (!pos._chunk) { *this = {}; return; } _size -= written_since(pos); _current = pos._chunk; _current->next = nullptr; _current->offset = pos._offset; } void reduce_chunk_count() { // FIXME: This is a simplified version. It linearizes the whole buffer // if its size is below max_chunk_size. We probably could also gain // some read performance by doing "real" reduction, i.e. merging // all chunks until all but the last one is max_chunk_size. if (size() < max_chunk_size()) { linearize(); } } bool operator==(const bytes_ostream& other) const { auto as = fragments().begin(); auto as_end = fragments().end(); auto bs = other.fragments().begin(); auto bs_end = other.fragments().end(); auto a = *as++; auto b = *bs++; while (!a.empty() || !b.empty()) { auto now = std::min(a.size(), b.size()); if (!std::equal(a.begin(), a.begin() + now, b.begin(), b.begin() + now)) { return false; } a.remove_prefix(now); if (a.empty() && as != as_end) { a = *as++; } b.remove_prefix(now); if (b.empty() && bs != bs_end) { b = *bs++; } } return true; } bool operator!=(const bytes_ostream& other) const { return !(*this == other); } // Makes this instance empty. // // The first buffer is not deallocated, so callers may rely on the // fact that if they write less than the initial chunk size between // the clear() calls then writes will not involve any memory allocations, // except for the first write made on this instance. void clear() { if (_begin) { _begin->offset = 0; _size = 0; _current = _begin.get(); _begin->next.reset(); } } }; <|endoftext|>
<commit_before>#include <DO/Sara/Core/MultiArray.hpp> #include <boost/interprocess/containers/vector.hpp> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/sync/interprocess_condition.hpp> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <iostream> #include <thread> namespace bip = boost::interprocess; template <typename T> using ipc_allocator = bip::allocator<T, bip::managed_shared_memory::segment_manager>; template <typename T> using ipc_vector = bip::vector<T, ipc_allocator<T>>; struct Message { bip::interprocess_mutex mutex; bip::interprocess_condition cond_image_batch_refilled; bip::interprocess_condition cond_image_batch_processed; bip::interprocess_condition cond_terminate_processing; int image_batch_filling_iter = -1; int image_batch_processing_iter = -1; int num_iter = -1; //ipc_vector<int> *image_shape; //ipc_vector<float> *image_data; //auto image_view() const -> DO::Sara::MultiArrayView<float, 2> //{ // return DO::Sara::MultiArrayView<float, 2>{ // image_data->data(), {(*image_shape)[0], (*image_shape)[1]}}; //} }; int main(int argc, char** argv) { if (argc == 1) { struct SharedMemoryRemover { SharedMemoryRemover() { bip::shared_memory_object::remove("MySharedMemory"); } ~SharedMemoryRemover() { bip::shared_memory_object::remove("MySharedMemory"); } } remover; bip::managed_shared_memory segment{bip::create_only, "MySharedMemory", 64 * 1024 * 1024 * 3 * sizeof(float)}; bip::allocator<Message, bip::managed_shared_memory::segment_manager> message_allocator{segment.get_segment_manager()}; bip::allocator<int, bip::managed_shared_memory::segment_manager> int_allocator{segment.get_segment_manager()}; bip::allocator<float, bip::managed_shared_memory::segment_manager> float_allocator{segment.get_segment_manager()}; const auto num_iter = 10; // Synchronisation between processes. auto message = segment.construct<Message>("message")(); message->num_iter = num_iter; // Allocate image data in the memory segment. segment.construct<ipc_vector<int>>("image_shape")( std::initializer_list<int>{3, 4}, int_allocator); auto image_data = segment.construct<ipc_vector<float>>("image_data")( 3 * 4, 0.f, float_allocator); // Allocate image descriptors data in the memory segment. auto image_descriptors = segment.construct<ipc_vector<float>>( "image_descriptors")(128, 0.f, float_allocator); // Start Process 2 by running a command in an asynchronous way. auto command = std::string{argv[0]} + " 1"; std::thread t([&command]() { std::cout << "running " << command << std::endl; std::system(command.c_str()); }); t.detach(); // Loop where the two processes communicate. for (int i = 0; i < num_iter; ++i) { std::cout << "[Process 1] Iteration " << i << std::endl; bip::scoped_lock<bip::interprocess_mutex> lock(message->mutex); // Fill with new image data. std::cout << "[Process 1] Refilling image data" << std::endl; std::fill(image_data->begin(), image_data->end(), i); std::cout << "[Process 1] Refilled image data" << std::endl; message->image_batch_filling_iter = i; message->cond_image_batch_refilled.notify_one(); // Wait until the image is processed. if (message->image_batch_processing_iter != i) { std::cout << "[Process 1] Waiting for Process 2 to complete" << std::endl; message->cond_image_batch_processed.wait(lock); } // Print the calculated descriptors. std::cout << "[Process 1] Process 2 calculated descriptors" << std::endl; for (auto i = 0; i < 10; ++i) std::cout << (*image_descriptors)[i] << " "; std::cout << std::endl << std::endl; }; bip::scoped_lock<bip::interprocess_mutex> lock(message->mutex); message->cond_terminate_processing.wait(lock); segment.destroy<ipc_vector<int>>("image_shape"); segment.destroy<ipc_vector<float>>("image_data"); segment.destroy<ipc_vector<float>>("image_descriptors"); segment.destroy<Message>("message"); } else { std::cout << "Running child process" << std::endl; bip::managed_shared_memory segment{bip::open_only, "MySharedMemory"}; auto image_shape = segment.find<ipc_vector<int>>("image_shape").first; auto image_data = segment.find<ipc_vector<float>>("image_data").first; auto image_descriptors = segment.find<ipc_vector<float>>("image_descriptors").first; auto message = segment.find<Message>("message").first; auto image_view = DO::Sara::MultiArrayView<float, 2>{ image_data->data(), {(*image_shape)[0], (*image_shape)[1]}}; while (true) { bip::scoped_lock<bip::interprocess_mutex> lock(message->mutex); if (message->image_batch_filling_iter <= message->image_batch_processing_iter) { std::cout << "[Process 2] Waiting for Process 1 to refill image data" << std::endl; message->cond_image_batch_refilled.wait(lock); } const auto value = (*image_data)[0]; std::cout << "[Process 2] Calculating descriptors" << std::endl; std::fill(image_descriptors->begin(), image_descriptors->end(), value); std::cout << "[Process 2] Notifying Process 1 that processing is finished" << std::endl; message->image_batch_processing_iter = message->image_batch_filling_iter; message->cond_image_batch_processed.notify_one(); if (message->image_batch_processing_iter == message->num_iter - 1) { message->cond_terminate_processing.notify_one(); break; } } std::cout << "Terminating child process" << std::endl; } return 0; } <commit_msg>WIP: fix assertion in posix condition.<commit_after>#include <DO/Sara/Core/MultiArray.hpp> #include <boost/interprocess/containers/vector.hpp> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/sync/interprocess_condition.hpp> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <iostream> #include <thread> namespace bip = boost::interprocess; template <typename T> using ipc_allocator = bip::allocator<T, bip::managed_shared_memory::segment_manager>; template <typename T> using ipc_vector = bip::vector<T, ipc_allocator<T>>; struct Message { bip::interprocess_mutex mutex; bip::interprocess_condition cond_image_batch_refilled; bip::interprocess_condition cond_image_batch_processed; bip::interprocess_condition cond_terminate_processing; int image_batch_filling_iter = -1; int image_batch_processing_iter = -1; int num_iter = -1; //ipc_vector<int> *image_shape; //ipc_vector<float> *image_data; //auto image_view() const -> DO::Sara::MultiArrayView<float, 2> //{ // return DO::Sara::MultiArrayView<float, 2>{ // image_data->data(), {(*image_shape)[0], (*image_shape)[1]}}; //} }; int main(int argc, char** argv) { if (argc == 1) { struct SharedMemoryRemover { SharedMemoryRemover() { bip::shared_memory_object::remove("MySharedMemory"); } ~SharedMemoryRemover() { bip::shared_memory_object::remove("MySharedMemory"); } } remover; bip::managed_shared_memory segment{bip::create_only, "MySharedMemory", 64 * 1024 * 1024 * 3 * sizeof(float)}; bip::allocator<Message, bip::managed_shared_memory::segment_manager> message_allocator{segment.get_segment_manager()}; bip::allocator<int, bip::managed_shared_memory::segment_manager> int_allocator{segment.get_segment_manager()}; bip::allocator<float, bip::managed_shared_memory::segment_manager> float_allocator{segment.get_segment_manager()}; const auto num_iter = 100000; // Synchronisation between processes. auto message = segment.construct<Message>("message")(); message->num_iter = num_iter; // Allocate image data in the memory segment. segment.construct<ipc_vector<int>>("image_shape")( std::initializer_list<int>{3, 4}, int_allocator); auto image_data = segment.construct<ipc_vector<float>>("image_data")( 3 * 4, 0.f, float_allocator); // Allocate image descriptors data in the memory segment. auto image_descriptors = segment.construct<ipc_vector<float>>( "image_descriptors")(128, 0.f, float_allocator); // Start Process 2 by running a command in an asynchronous way. auto command = std::string{argv[0]} + " 1"; std::thread t([&command]() { std::cout << "running " << command << std::endl; std::system(command.c_str()); }); t.detach(); // Loop where the two processes communicate. for (int i = 0; i < num_iter; ++i) { std::cout << "[Process 1] Iteration " << i << std::endl; bip::scoped_lock<bip::interprocess_mutex> lock(message->mutex); // Fill with new image data. std::cout << "[Process 1] Refilling image data" << std::endl; std::fill(image_data->begin(), image_data->end(), i); std::cout << "[Process 1] Refilled image data" << std::endl; message->image_batch_filling_iter = i; message->cond_image_batch_refilled.notify_one(); // Wait until the image is processed. if (message->image_batch_processing_iter != i) { std::cout << "[Process 1] Waiting for Process 2 to complete" << std::endl; message->cond_image_batch_processed.wait(lock); } // Print the calculated descriptors. std::cout << "[Process 1] Process 2 calculated descriptors" << std::endl; for (auto i = 0; i < 10; ++i) std::cout << (*image_descriptors)[i] << " "; std::cout << std::endl << std::endl; if (message->image_batch_processing_iter == num_iter - 1) { std::cout << "[Process 1] Notifying Process 2 to terminate" << std::endl; message->cond_terminate_processing.notify_one(); } }; segment.destroy<ipc_vector<int>>("image_shape"); segment.destroy<ipc_vector<float>>("image_data"); segment.destroy<ipc_vector<float>>("image_descriptors"); segment.destroy<Message>("message"); } else { std::cout << "Running child process" << std::endl; bip::managed_shared_memory segment{bip::open_only, "MySharedMemory"}; auto image_shape = segment.find<ipc_vector<int>>("image_shape").first; auto image_data = segment.find<ipc_vector<float>>("image_data").first; auto image_descriptors = segment.find<ipc_vector<float>>("image_descriptors").first; auto message = segment.find<Message>("message").first; auto image_view = DO::Sara::MultiArrayView<float, 2>{ image_data->data(), {(*image_shape)[0], (*image_shape)[1]}}; while (true) { { bip::scoped_lock<bip::interprocess_mutex> lock(message->mutex); if (message->image_batch_filling_iter <= message->image_batch_processing_iter) { std::cout << "[Process 2] Waiting for Process 1 to refill image data" << std::endl; message->cond_image_batch_refilled.wait(lock); } const auto value = (*image_data)[0]; std::cout << "[Process 2] Calculating descriptors" << std::endl; std::fill(image_descriptors->begin(), image_descriptors->end(), value); std::cout << "[Process 2] Notifying Process 1 that image processing is " "finished" << std::endl; message->image_batch_processing_iter = message->image_batch_filling_iter; message->cond_image_batch_processed.notify_one(); } { bip::scoped_lock<bip::interprocess_mutex> lock(message->mutex); if (message->image_batch_processing_iter == message->num_iter - 1) { std::cout << "[Process 2] Waiting for Process 1 to signal termination" << std::endl; message->cond_terminate_processing.wait(lock); std::cout << "[Process 2] Received signal from Process 1 to " "terminate process" << std::endl; break; } } } } return 0; } <|endoftext|>
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "..\BatchEncoder.h" #include "..\utilities\Utilities.h" #include "WorkThread.h" enum Mode { None = -1, Encode = 0, Transcode = 1 }; bool ConvertItem(CItemContext* pContext) { // input path CString szInputFile = pContext->item->szPath; // validate input path WIN32_FIND_DATA lpFindFileData; HANDLE hFind = ::FindFirstFile(szInputFile, &lpFindFileData); if (hFind == INVALID_HANDLE_VALUE) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find input file.")); ::FindClose(hFind); return false; } ::FindClose(hFind); // output path CString szOutPath; if (pContext->pWorkerContext->pConfig->m_Options.bOutputPathChecked == true) { szOutPath = pContext->pWorkerContext->pConfig->m_Options.szOutputPath; } else { CString szInputFileName = ::GetFileName(szInputFile); szOutPath = szInputFile; szOutPath.Truncate(szOutPath.GetLength() - szInputFileName.GetLength()); } // find encoder int nEncoder = pContext->pWorkerContext->pConfig->m_Formats.GetFormatById(pContext->item->szFormatId); if (nEncoder == -1) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid encoder by id.")); return false; } CFormat& encoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nEncoder); // validate encoder preset if (pContext->item->nPreset >= encoderFormat.m_Presets.GetSize()) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoder format preset.")); return false; } // validate input extension CString szInputFileExt = ::GetFileExtension(szInputFile).MakeUpper(); bool bIsValidEncoderInput = encoderFormat.IsValidInputExtension(szInputFileExt); // processing mode Mode nProcessingMode = Mode::None; if (bIsValidEncoderInput) nProcessingMode = Mode::Encode; else nProcessingMode = Mode::Transcode; // output path CString szEncoderExtension = encoderFormat.szOutputExtension; CString szName = pContext->item->szName + _T(".") + szEncoderExtension.MakeLower(); CString szOutputFile; if (szOutPath.GetLength() >= 1) { if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/') szOutputFile = szOutPath + szName; else szOutputFile = szOutPath + _T("\\") + szName; } else { szOutputFile = szName; } CString szOrgInputFile = szInputFile; CString szOrgOutputFile = szOutputFile; if (nProcessingMode == Mode::Transcode) { // find decoder int nDecoder = pContext->pWorkerContext->pConfig->m_Formats.GetDecoderByExtension(pContext->item->szExtension); if (nDecoder == -1) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid decoder by extension.")); return false; } CFormat& decoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nDecoder); // validate decoder preset if (decoderFormat.nDefaultPreset >= decoderFormat.m_Presets.GetSize()) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoder format preset.")); return false; } // validate decoder output extension bIsValidEncoderInput = encoderFormat.IsValidInputExtension(decoderFormat.szOutputExtension); if (bIsValidEncoderInput == false) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: decoder output not supported by encoder.")); return false; } CString szDecoderExtension = decoderFormat.szOutputExtension; szOutputFile = szOutputFile + +_T(".") + szDecoderExtension.MakeLower(); pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Decoding...")); try { CFileContext context(pContext->pWorkerContext, decoderFormat, decoderFormat.nDefaultPreset, pContext->item->nId, szInputFile, szOutputFile); if (::ConvertFile(&context) == false) { if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); return false; } } catch (...) { if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file.")); pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true); } } if (pContext->pWorkerContext->bRunning == false) return false; if (nProcessingMode == Mode::Transcode) { szInputFile = szOutputFile; szOutputFile = szOrgOutputFile; } if ((nProcessingMode == Mode::Encode) || (nProcessingMode == Mode::Transcode)) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Encoding...")); try { CFileContext context(pContext->pWorkerContext, encoderFormat, pContext->item->nPreset, pContext->item->nId, szInputFile, szOutputFile); if (::ConvertFile(&context) == true) { if (nProcessingMode == Mode::Transcode) ::DeleteFile(szInputFile); if (pContext->pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true) ::DeleteFile(szOrgInputFile); return true; } else { if (nProcessingMode == Mode::Transcode) ::DeleteFile(szInputFile); if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); return false; } } catch (...) { if (nProcessingMode == Mode::Transcode) ::DeleteFile(szInputFile); if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file.")); pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true); } } return false; } <commit_msg>Update ConvertItem.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "..\BatchEncoder.h" #include "..\utilities\Utilities.h" #include "WorkThread.h" enum Mode { None = -1, Encode = 0, Transcode = 1 }; bool FileExists(CString szPath) { WIN32_FIND_DATA lpFindFileData; HANDLE hFind = ::FindFirstFile(szPath, &lpFindFileData); bool bInvalidHandle = hFind == INVALID_HANDLE_VALUE; ::FindClose(hFind); return bInvalidHandle == false; } bool ConvertItem(CItemContext* pContext) { // input file CString szInputFile = pContext->item->szPath; // validate input file if (FileExists(szInputFile) == false) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find input file.")); return false; } // output path CString szOutPath; if (pContext->pWorkerContext->pConfig->m_Options.bOutputPathChecked == true) { szOutPath = pContext->pWorkerContext->pConfig->m_Options.szOutputPath; } else { CString szInputFileName = ::GetFileName(szInputFile); szOutPath = szInputFile; szOutPath.Truncate(szOutPath.GetLength() - szInputFileName.GetLength()); } // find encoder int nEncoder = pContext->pWorkerContext->pConfig->m_Formats.GetFormatById(pContext->item->szFormatId); if (nEncoder == -1) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid encoder by id.")); return false; } CFormat& encoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nEncoder); // validate encoder executable if (FileExists(encoderFormat.szPath) == false) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoder executable.")); return false; } // validate encoder preset if (pContext->item->nPreset >= encoderFormat.m_Presets.GetSize()) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find encoder format preset.")); return false; } // validate input extension CString szInputFileExt = ::GetFileExtension(szInputFile).MakeUpper(); bool bIsValidEncoderInput = encoderFormat.IsValidInputExtension(szInputFileExt); // processing mode Mode nProcessingMode = Mode::None; if (bIsValidEncoderInput) nProcessingMode = Mode::Encode; else nProcessingMode = Mode::Transcode; // output path CString szEncoderExtension = encoderFormat.szOutputExtension; CString szName = pContext->item->szName + _T(".") + szEncoderExtension.MakeLower(); CString szOutputFile; if (szOutPath.GetLength() >= 1) { if (szOutPath[szOutPath.GetLength() - 1] == '\\' || szOutPath[szOutPath.GetLength() - 1] == '/') szOutputFile = szOutPath + szName; else szOutputFile = szOutPath + _T("\\") + szName; } else { szOutputFile = szName; } CString szOrgInputFile = szInputFile; CString szOrgOutputFile = szOutputFile; if (nProcessingMode == Mode::Transcode) { // find decoder int nDecoder = pContext->pWorkerContext->pConfig->m_Formats.GetDecoderByExtension(pContext->item->szExtension); if (nDecoder == -1) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find valid decoder by extension.")); return false; } CFormat& decoderFormat = pContext->pWorkerContext->pConfig->m_Formats.GetData(nDecoder); // validate decoder executable if (FileExists(decoderFormat.szPath) == false) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoder executable.")); return false; } // validate decoder preset if (decoderFormat.nDefaultPreset >= decoderFormat.m_Presets.GetSize()) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoder format preset.")); return false; } // validate decoder output extension bIsValidEncoderInput = encoderFormat.IsValidInputExtension(decoderFormat.szOutputExtension); if (bIsValidEncoderInput == false) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: decoder output not supported by encoder.")); return false; } CString szDecoderExtension = decoderFormat.szOutputExtension; szOutputFile = szOutputFile + +_T(".") + szDecoderExtension.MakeLower(); pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Decoding...")); try { CFileContext context(pContext->pWorkerContext, decoderFormat, decoderFormat.nDefaultPreset, pContext->item->nId, szInputFile, szOutputFile); if (::ConvertFile(&context) == false) { if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); return false; } } catch (...) { if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file.")); pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true); } } if (pContext->pWorkerContext->bRunning == false) return false; if (nProcessingMode == Mode::Transcode) { // validate decoded file if (FileExists(szOutputFile) == false) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: can not find decoded file.")); return false; } // decoder output file as encoder input file szInputFile = szOutputFile; // original encoder output file szOutputFile = szOrgOutputFile; } if ((nProcessingMode == Mode::Encode) || (nProcessingMode == Mode::Transcode)) { pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Encoding...")); try { CFileContext context(pContext->pWorkerContext, encoderFormat, pContext->item->nPreset, pContext->item->nId, szInputFile, szOutputFile); if (::ConvertFile(&context) == true) { if (nProcessingMode == Mode::Transcode) ::DeleteFile(szInputFile); if (pContext->pWorkerContext->pConfig->m_Options.bDeleteSourceFiles == true) ::DeleteFile(szOrgInputFile); return true; } else { if (nProcessingMode == Mode::Transcode) ::DeleteFile(szInputFile); if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); return false; } } catch (...) { if (nProcessingMode == Mode::Transcode) ::DeleteFile(szInputFile); if (pContext->pWorkerContext->pConfig->m_Options.bDeleteOnErrors == true) ::DeleteFile(szOutputFile); pContext->pWorkerContext->Status(pContext->item->nId, _T("--:--"), _T("Error: exception thrown while converting file.")); pContext->pWorkerContext->Callback(pContext->item->nId, -1, true, true); } } return false; } <|endoftext|>
<commit_before>#include "AssetInputMesh.h" #include <maya/MFnMesh.h> #include <maya/MFloatPointArray.h> #include <maya/MIntArray.h> #include <maya/MMatrix.h> #include "util.h" AssetInputMesh::AssetInputMesh(int assetId, int inputIdx) : AssetInput(assetId, inputIdx), myInputAssetId(0) { HAPI_CreateGeoInput(myAssetId, myInputIdx, &myInputInfo); } AssetInputMesh::~AssetInputMesh() { } AssetInput::AssetInputType AssetInputMesh::assetInputType() const { return AssetInput::AssetInputType_Mesh; } void AssetInputMesh::setInputTransform(MDataHandle &dataHandle) { // Set the transform MMatrix transformMat = dataHandle.asMatrix(); float inputMat[ 16 ]; for( int ii = 0; ii < 4; ii++ ) { for( int jj = 0; jj < 4; jj++ ) { inputMat[ii*4 + jj] = (float) transformMat.matrix[ii][jj]; } } HAPI_TransformEuler transformEuler; HAPI_ConvertMatrixToEuler( inputMat, HAPI_TRS, HAPI_XYZ, &transformEuler ); HAPI_SetObjectTransform( myInputAssetId, myInputInfo.objectId, transformEuler ); } void AssetInputMesh::setInputGeo(MDataHandle &dataHandle) { // extract mesh data from Maya MObject meshObj = dataHandle.asMesh(); MFnMesh meshFn(meshObj); // get face data MIntArray faceCounts; MIntArray vertexList; meshFn.getVertices(faceCounts, vertexList); Util::reverseWindingOrder(vertexList, faceCounts); // set up part info HAPI_PartInfo partInfo; HAPI_PartInfo_Init(&partInfo); partInfo.id = 0; partInfo.faceCount = faceCounts.length(); partInfo.vertexCount = vertexList.length(); partInfo.pointCount = meshFn.numVertices(); // copy data to arrays int * vl = new int[partInfo.vertexCount]; int * fc = new int[partInfo.faceCount]; vertexList.get(vl); faceCounts.get(fc); // Set the data HAPI_SetPartInfo(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, &partInfo); HAPI_SetFaceCounts(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, fc, 0, partInfo.faceCount); HAPI_SetVertexList(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, vl, 0, partInfo.vertexCount); // Set position attributes. HAPI_AttributeInfo pos_attr_info; pos_attr_info.exists = true; pos_attr_info.owner = HAPI_ATTROWNER_POINT; pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT; pos_attr_info.count = meshFn.numVertices(); pos_attr_info.tupleSize = 3; HAPI_AddAttribute(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info ); HAPI_SetAttributeFloatData(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info, meshFn.getRawPoints(NULL), 0, meshFn.numVertices()); // Commit it HAPI_CommitGeo(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId); delete[] vl; delete[] fc; } <commit_msg>Add support for converting normals from Maya mesh into HAPI<commit_after>#include "AssetInputMesh.h" #include <maya/MFnMesh.h> #include <maya/MFloatPointArray.h> #include <maya/MFloatVectorArray.h> #include <maya/MIntArray.h> #include <maya/MMatrix.h> #include "util.h" AssetInputMesh::AssetInputMesh(int assetId, int inputIdx) : AssetInput(assetId, inputIdx), myInputAssetId(0) { HAPI_CreateGeoInput(myAssetId, myInputIdx, &myInputInfo); } AssetInputMesh::~AssetInputMesh() { } AssetInput::AssetInputType AssetInputMesh::assetInputType() const { return AssetInput::AssetInputType_Mesh; } void AssetInputMesh::setInputTransform(MDataHandle &dataHandle) { // Set the transform MMatrix transformMat = dataHandle.asMatrix(); float inputMat[ 16 ]; for( int ii = 0; ii < 4; ii++ ) { for( int jj = 0; jj < 4; jj++ ) { inputMat[ii*4 + jj] = (float) transformMat.matrix[ii][jj]; } } HAPI_TransformEuler transformEuler; HAPI_ConvertMatrixToEuler( inputMat, HAPI_TRS, HAPI_XYZ, &transformEuler ); HAPI_SetObjectTransform( myInputAssetId, myInputInfo.objectId, transformEuler ); } void AssetInputMesh::setInputGeo(MDataHandle &dataHandle) { // extract mesh data from Maya MObject meshObj = dataHandle.asMesh(); MFnMesh meshFn(meshObj); // get face data MIntArray faceCounts; MIntArray vertexList; meshFn.getVertices(faceCounts, vertexList); Util::reverseWindingOrder(vertexList, faceCounts); // set up part info HAPI_PartInfo partInfo; HAPI_PartInfo_Init(&partInfo); partInfo.id = 0; partInfo.faceCount = faceCounts.length(); partInfo.vertexCount = vertexList.length(); partInfo.pointCount = meshFn.numVertices(); // copy data to arrays int * vl = new int[partInfo.vertexCount]; int * fc = new int[partInfo.faceCount]; vertexList.get(vl); faceCounts.get(fc); // Set the data HAPI_SetPartInfo(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, &partInfo); HAPI_SetFaceCounts(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, fc, 0, partInfo.faceCount); HAPI_SetVertexList(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, vl, 0, partInfo.vertexCount); // Set position attributes. HAPI_AttributeInfo pos_attr_info; pos_attr_info.exists = true; pos_attr_info.owner = HAPI_ATTROWNER_POINT; pos_attr_info.storage = HAPI_STORAGETYPE_FLOAT; pos_attr_info.count = meshFn.numVertices(); pos_attr_info.tupleSize = 3; HAPI_AddAttribute(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info ); HAPI_SetAttributeFloatData(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "P", &pos_attr_info, meshFn.getRawPoints(NULL), 0, meshFn.numVertices()); // normals { // get normal IDs MIntArray normalCounts; MIntArray normalIds; meshFn.getNormalIds(normalCounts, normalIds); if(normalIds.length()) { // reverse winding order Util::reverseWindingOrder(normalIds, faceCounts); // get normal values const float* rawNormals = meshFn.getRawNormals(NULL); // build the per-vertex normals std::vector<float> vertexNormals; vertexNormals.reserve(normalIds.length() * 3); for(unsigned int i = 0; i < normalIds.length(); ++i) { vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 0]); vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 1]); vertexNormals.push_back(rawNormals[normalIds[i] * 3 + 2]); } // add and set it to HAPI HAPI_AttributeInfo attributeInfo; attributeInfo.exists = true; attributeInfo.owner = HAPI_ATTROWNER_VERTEX; attributeInfo.storage = HAPI_STORAGETYPE_FLOAT; attributeInfo.count = normalIds.length(); attributeInfo.tupleSize = 3; HAPI_AddAttribute(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "N", &attributeInfo); HAPI_SetAttributeFloatData(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId, "N", &attributeInfo, &vertexNormals.front(), 0, normalIds.length()); } } // Commit it HAPI_CommitGeo(myInputAssetId, myInputInfo.objectId, myInputInfo.geoId); delete[] vl; delete[] fc; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ /* * Sampling from WishHart and Normal distributions */ #include <numeric> #include <functional> #include <iostream> #include <random> #include "bpmf.h" #ifdef BPMF_RANDOM123 #include <Random123/philox.h> #include <Random123/MicroURNG.hpp> typedef r123::MicroURNG<r123::Philox4x32> RNG; #else typedef std::mt19937 RNG; #endif using namespace Eigen; static thread_local RNG rng({{0}}, {{42}}); void rng_set_pos(uint32_t c) { #ifdef BPMF_RANDOM123 rng.reset({{c}}, {{42}}); #endif } double randn() { return std::normal_distribution<>()(rng); } /* -------------------------------------------------------------------------------- */ /* Draw nn samples from a size-dimensional normal distribution with a specified mean vector and precision matrix */ VectorNd MvNormalChol_prec(double kappa, const MatrixNNd & Lambda_U, const VectorNd & mean) { VectorNd r = nrandn(num_latent); Lambda_U.triangularView<Upper>().solveInPlace(r); return (r / sqrt(kappa)) + mean; } void WishartUnitChol(int df, MatrixNNd & c) { c.setZero(); for ( int i = 0; i < num_latent; i++ ) { std::gamma_distribution<> gam(0.5*(df - i)); c(i,i) = sqrt(2.0 * gam(rng)); VectorXd r = nrandn(num_latent-i-1); for(int j=i+1;j<num_latent;j++) c.coeffRef(i,j) = randn(); } } void WishartChol(const MatrixNNd &sigma, const int df, MatrixNNd & U) { // Get R, the upper triangular Cholesky factor of SIGMA. auto chol = sigma.llt(); // Get AU, a sample from the unit Wishart distribution. MatrixNNd au; WishartUnitChol(df, au); U.noalias() = au * chol.matrixU(); #ifdef TEST_MVNORMAL cout << "WISHART {\n" << endl; cout << " sigma::\n" << sigma << endl; cout << " au:\n" << au << endl; cout << " df:\n" << df << endl; cout << "}\n" << endl; #endif } // from julia package Distributions: conjugates/normalwishart.jl std::pair<VectorNd, MatrixNNd> NormalWishart(const VectorNd & mu, double kappa, const MatrixNNd & T, double nu) { MatrixNNd LamU; WishartChol(T, nu, LamU); VectorNd mu_o = MvNormalChol_prec(kappa, LamU, mu); #ifdef TEST_MVNORMAL cout << "NORMAL WISHART {\n" << endl; cout << " mu:\n" << mu << endl; cout << " kappa:\n" << kappa << endl; cout << " T:\n" << T << endl; cout << " nu:\n" << nu << endl; cout << " mu_o\n" << mu_o << endl; cout << " Lam\n" << LamU.transpose() * LamU << endl; cout << "}\n" << endl; #endif return std::make_pair(mu_o , LamU); } std::pair<VectorNd, MatrixNNd> CondNormalWishart(const int N, const MatrixNNd &S, const VectorNd &Um, const VectorNd &mu, const double kappa, const MatrixNNd &T, const int nu) { auto mu_m = (mu - Um); VectorNd mu_c = (kappa*mu + N*Um) / (kappa + N); double kappa_c = kappa + N; double kappa_m = (kappa * N)/(kappa + N); auto X = ( T + N * S + kappa_m * (mu_m * mu_m.transpose())); MatrixNNd T_c = X.inverse(); int nu_c = nu + N; #ifdef TEST_MVNORMAL cout << "mu_c:\n" << mu_c << endl; cout << "kappa_c:\n" << kappa_c << endl; cout << "T_c:\n" << T_c << endl; cout << "nu_c:\n" << nu_c << endl; #endif return NormalWishart(mu_c, kappa_c, T_c, nu_c); } <commit_msg>FIX: fix std:: random<commit_after>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ /* * Sampling from WishHart and Normal distributions */ #include <numeric> #include <functional> #include <iostream> #include <random> #include "bpmf.h" #ifdef BPMF_RANDOM123 #include <Random123/philox.h> #include <Random123/MicroURNG.hpp> typedef r123::MicroURNG<r123::Philox4x32> RNG; static thread_local RNG rng({{0}}, {{42}}); #else typedef std::mt19937 RNG; static thread_local RNG rng; #endif using namespace Eigen; void rng_set_pos(uint32_t c) { #ifdef BPMF_RANDOM123 rng.reset({{c}}, {{42}}); #endif } double randn() { return std::normal_distribution<>()(rng); } /* -------------------------------------------------------------------------------- */ /* Draw nn samples from a size-dimensional normal distribution with a specified mean vector and precision matrix */ VectorNd MvNormalChol_prec(double kappa, const MatrixNNd & Lambda_U, const VectorNd & mean) { VectorNd r = nrandn(num_latent); Lambda_U.triangularView<Upper>().solveInPlace(r); return (r / sqrt(kappa)) + mean; } void WishartUnitChol(int df, MatrixNNd & c) { c.setZero(); for ( int i = 0; i < num_latent; i++ ) { std::gamma_distribution<> gam(0.5*(df - i)); c(i,i) = sqrt(2.0 * gam(rng)); VectorXd r = nrandn(num_latent-i-1); for(int j=i+1;j<num_latent;j++) c.coeffRef(i,j) = randn(); } } void WishartChol(const MatrixNNd &sigma, const int df, MatrixNNd & U) { // Get R, the upper triangular Cholesky factor of SIGMA. auto chol = sigma.llt(); // Get AU, a sample from the unit Wishart distribution. MatrixNNd au; WishartUnitChol(df, au); U.noalias() = au * chol.matrixU(); #ifdef TEST_MVNORMAL cout << "WISHART {\n" << endl; cout << " sigma::\n" << sigma << endl; cout << " au:\n" << au << endl; cout << " df:\n" << df << endl; cout << "}\n" << endl; #endif } // from julia package Distributions: conjugates/normalwishart.jl std::pair<VectorNd, MatrixNNd> NormalWishart(const VectorNd & mu, double kappa, const MatrixNNd & T, double nu) { MatrixNNd LamU; WishartChol(T, nu, LamU); VectorNd mu_o = MvNormalChol_prec(kappa, LamU, mu); #ifdef TEST_MVNORMAL cout << "NORMAL WISHART {\n" << endl; cout << " mu:\n" << mu << endl; cout << " kappa:\n" << kappa << endl; cout << " T:\n" << T << endl; cout << " nu:\n" << nu << endl; cout << " mu_o\n" << mu_o << endl; cout << " Lam\n" << LamU.transpose() * LamU << endl; cout << "}\n" << endl; #endif return std::make_pair(mu_o , LamU); } std::pair<VectorNd, MatrixNNd> CondNormalWishart(const int N, const MatrixNNd &S, const VectorNd &Um, const VectorNd &mu, const double kappa, const MatrixNNd &T, const int nu) { auto mu_m = (mu - Um); VectorNd mu_c = (kappa*mu + N*Um) / (kappa + N); double kappa_c = kappa + N; double kappa_m = (kappa * N)/(kappa + N); auto X = ( T + N * S + kappa_m * (mu_m * mu_m.transpose())); MatrixNNd T_c = X.inverse(); int nu_c = nu + N; #ifdef TEST_MVNORMAL cout << "mu_c:\n" << mu_c << endl; cout << "kappa_c:\n" << kappa_c << endl; cout << "T_c:\n" << T_c << endl; cout << "nu_c:\n" << nu_c << endl; #endif return NormalWishart(mu_c, kappa_c, T_c, nu_c); } <|endoftext|>
<commit_before>#include <core/stdafx.h> #include <core/utility/cli.h> #include <core/utility/strings.h> #include <queue> namespace cli { OptParser GetParser(int clSwitch, const std::vector<OptParser>& parsers) { for (const auto& parser : parsers) { if (clSwitch == parser.clSwitch) return parser; } return {}; } // Checks if szArg is an option, and if it is, returns which option it is // We return the first match, so switches should be ordered appropriately // The first switch should be our "no match" switch int ParseArgument(const std::wstring& szArg, const std::vector<COMMANDLINE_SWITCH>& switches) { if (szArg.empty()) return 0; auto szSwitch = std::wstring{}; // Check if this is a switch at all switch (szArg[0]) { case L'-': case L'/': case L'\\': if (szArg[1] != 0) szSwitch = strings::wstringToLower(&szArg[1]); break; default: return 0; } for (const auto& s : switches) { // If we have a match if (strings::beginsWith(s.szSwitch, szSwitch)) { return s.iSwitch; } } return 0; } // If the mode isn't set (is 0), then we can set it to any mode // If the mode IS set (non 0), then we can only set it to the same mode // IE trying to change the mode from anything but unset will fail bool bSetMode(_In_ int& pMode, _In_ int targetMode) { if (0 == pMode || targetMode == pMode) { pMode = targetMode; return true; } return false; } // Converts an argc/argv style command line to a vector std::deque<std::wstring> GetCommandLine(_In_ int argc, _In_count_(argc) const char* const argv[]) { auto args = std::deque<std::wstring>{}; for (auto i = 1; i < argc; i++) { args.emplace_back(strings::LPCSTRToWstring(argv[i])); } return args; } // Assumes that our no switch case is 0 _Check_return_ bool CheckMinArgs( cli::OptParser opt, const std::deque<std::wstring> args, const std::vector<COMMANDLINE_SWITCH>& switches) { if (opt.minArgs > 0) { // TODO: Rebuild this without array access for (auto iArg = UINT{1}; iArg <= opt.minArgs; iArg++) { if (args.size() <= iArg || 0 != ParseArgument(args[iArg], switches)) { return false; } } } return true; } } // namespace cli<commit_msg>move size checks out of loop<commit_after>#include <core/stdafx.h> #include <core/utility/cli.h> #include <core/utility/strings.h> #include <queue> namespace cli { OptParser GetParser(int clSwitch, const std::vector<OptParser>& parsers) { for (const auto& parser : parsers) { if (clSwitch == parser.clSwitch) return parser; } return {}; } // Checks if szArg is an option, and if it is, returns which option it is // We return the first match, so switches should be ordered appropriately // The first switch should be our "no match" switch int ParseArgument(const std::wstring& szArg, const std::vector<COMMANDLINE_SWITCH>& switches) { if (szArg.empty()) return 0; auto szSwitch = std::wstring{}; // Check if this is a switch at all switch (szArg[0]) { case L'-': case L'/': case L'\\': if (szArg[1] != 0) szSwitch = strings::wstringToLower(&szArg[1]); break; default: return 0; } for (const auto& s : switches) { // If we have a match if (strings::beginsWith(s.szSwitch, szSwitch)) { return s.iSwitch; } } return 0; } // If the mode isn't set (is 0), then we can set it to any mode // If the mode IS set (non 0), then we can only set it to the same mode // IE trying to change the mode from anything but unset will fail bool bSetMode(_In_ int& pMode, _In_ int targetMode) { if (0 == pMode || targetMode == pMode) { pMode = targetMode; return true; } return false; } // Converts an argc/argv style command line to a vector std::deque<std::wstring> GetCommandLine(_In_ int argc, _In_count_(argc) const char* const argv[]) { auto args = std::deque<std::wstring>{}; for (auto i = 1; i < argc; i++) { args.emplace_back(strings::LPCSTRToWstring(argv[i])); } return args; } // Assumes that our no switch case is 0 _Check_return_ bool CheckMinArgs( cli::OptParser opt, const std::deque<std::wstring> args, const std::vector<COMMANDLINE_SWITCH>& switches) { if (opt.minArgs == 0) return true; if (args.size() <= opt.minArgs) return false; // TODO: Rebuild this without array access for (auto iArg = UINT{1}; iArg <= opt.minArgs; iArg++) { if (0 != ParseArgument(args[iArg], switches)) { return false; } } return true; } } // namespace cli<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 * *****************************************************************************/ #include "process_geojson_file.hpp" #include <mapnik/geometry.hpp> #include <mapnik/geometry_envelope.hpp> #include <mapnik/geometry_adapters.hpp> #include <mapnik/util/file_io.hpp> #include <mapnik/util/utf_conv_win.hpp> #if defined(MAPNIK_MEMORY_MAPPED_FILE) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedef" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wsign-conversion" #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/streams/bufferstream.hpp> #include <boost/spirit/include/qi.hpp> #pragma GCC diagnostic pop #include <mapnik/mapped_memory_cache.hpp> #endif #include <mapnik/json/positions_grammar.hpp> #include <mapnik/json/extract_bounding_box_grammar_impl.hpp> namespace { using base_iterator_type = char const*; const mapnik::json::extract_bounding_box_grammar<base_iterator_type> geojson_datasource_static_bbox_grammar; } namespace mapnik { namespace detail { template <typename T> std::pair<bool,box2d<double>> process_geojson_file(T & boxes, std::string const& filename) { mapnik::box2d<double> extent; #if defined(MAPNIK_MEMORY_MAPPED_FILE) mapnik::mapped_region_ptr mapped_region; boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(filename, true); if (!memory) { std::clog << "Error : cannot memory map " << filename << std::endl; return std::make_pair(false, extent); } else { mapped_region = *memory; } char const* start = reinterpret_cast<char const*>(mapped_region->get_address()); char const* end = start + mapped_region->get_size(); #else mapnik::util::file file(filename); if (!file.open()) { std::clog << "Error : cannot open " << filename << std::endl; return std::make_pair(false, extent); } std::string file_buffer; file_buffer.resize(file.size()); std::fread(&file_buffer[0], file.size(), 1, file.get()); char const* start = file_buffer.c_str(); char const* end = start + file_buffer.length(); #endif boost::spirit::standard::space_type space; try { if (!boost::spirit::qi::phrase_parse(start, end, (geojson_datasource_static_bbox_grammar)(boost::phoenix::ref(boxes)) , space)) { std::clog << "mapnik-index (GeoJSON) : could extract bounding boxes from : '" << filename << "'"; return std::make_pair(false, extent); } } catch (std::exception const& ex) { std::clog << "mapnik-index (GeoJSON): " << ex.what() << std::endl; } for (auto const& item : boxes) { if (item.first.valid()) { if (!extent.valid()) extent = item.first; else extent.expand_to_include(item.first); } } return std::make_pair(true, extent); } using box_type = mapnik::box2d<double>; using item_type = std::pair<box_type, std::pair<std::size_t, std::size_t>>; using boxes_type = std::vector<item_type>; template std::pair<bool,box2d<double>> process_geojson_file(boxes_type&, std::string const&); }} <commit_msg>mapnik-index - fix std::clog message typo<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 * *****************************************************************************/ #include "process_geojson_file.hpp" #include <mapnik/geometry.hpp> #include <mapnik/geometry_envelope.hpp> #include <mapnik/geometry_adapters.hpp> #include <mapnik/util/file_io.hpp> #include <mapnik/util/utf_conv_win.hpp> #if defined(MAPNIK_MEMORY_MAPPED_FILE) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedef" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wsign-conversion" #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/streams/bufferstream.hpp> #include <boost/spirit/include/qi.hpp> #pragma GCC diagnostic pop #include <mapnik/mapped_memory_cache.hpp> #endif #include <mapnik/json/positions_grammar.hpp> #include <mapnik/json/extract_bounding_box_grammar_impl.hpp> namespace { using base_iterator_type = char const*; const mapnik::json::extract_bounding_box_grammar<base_iterator_type> geojson_datasource_static_bbox_grammar; } namespace mapnik { namespace detail { template <typename T> std::pair<bool,box2d<double>> process_geojson_file(T & boxes, std::string const& filename) { mapnik::box2d<double> extent; #if defined(MAPNIK_MEMORY_MAPPED_FILE) mapnik::mapped_region_ptr mapped_region; boost::optional<mapnik::mapped_region_ptr> memory = mapnik::mapped_memory_cache::instance().find(filename, true); if (!memory) { std::clog << "Error : cannot memory map " << filename << std::endl; return std::make_pair(false, extent); } else { mapped_region = *memory; } char const* start = reinterpret_cast<char const*>(mapped_region->get_address()); char const* end = start + mapped_region->get_size(); #else mapnik::util::file file(filename); if (!file.open()) { std::clog << "Error : cannot open " << filename << std::endl; return std::make_pair(false, extent); } std::string file_buffer; file_buffer.resize(file.size()); std::fread(&file_buffer[0], file.size(), 1, file.get()); char const* start = file_buffer.c_str(); char const* end = start + file_buffer.length(); #endif boost::spirit::standard::space_type space; try { if (!boost::spirit::qi::phrase_parse(start, end, (geojson_datasource_static_bbox_grammar)(boost::phoenix::ref(boxes)) , space)) { std::clog << "mapnik-index (GeoJSON) : could not extract bounding boxes from : '" << filename << "'" << std::endl; return std::make_pair(false, extent); } } catch (std::exception const& ex) { std::clog << "mapnik-index (GeoJSON): " << ex.what() << std::endl; } for (auto const& item : boxes) { if (item.first.valid()) { if (!extent.valid()) extent = item.first; else extent.expand_to_include(item.first); } } return std::make_pair(true, extent); } using box_type = mapnik::box2d<double>; using item_type = std::pair<box_type, std::pair<std::size_t, std::size_t>>; using boxes_type = std::vector<item_type>; template std::pair<bool,box2d<double>> process_geojson_file(boxes_type&, std::string const&); }} <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h" #include <string> #include "base/bind.h" #include "base/logging.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h" #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync_file_system/drive_file_sync_service.h" #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "chrome/common/extensions/api/sync_file_system.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_client.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_types.h" #include "webkit/fileapi/file_system_url.h" #include "webkit/fileapi/file_system_util.h" #include "webkit/fileapi/syncable/sync_file_status.h" #include "webkit/quota/quota_manager.h" using content::BrowserContext; using content::BrowserThread; using sync_file_system::SyncFileSystemServiceFactory; namespace extensions { namespace { // This is the only supported cloud backend service for now. const char* const kDriveCloudService = sync_file_system::DriveFileSyncService::kServiceName; // Error messages. const char kNotSupportedService[] = "Cloud service %s not supported."; const char kFileError[] = "File error %d."; const char kQuotaError[] = "Quota error %d."; api::sync_file_system::FileSyncStatus FileSyncStatusEnumToExtensionEnum( const fileapi::SyncFileStatus state) { switch (state) { case fileapi::SYNC_FILE_STATUS_UNKNOWN: return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_NONE; case fileapi::SYNC_FILE_STATUS_SYNCED: return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_SYNCED; case fileapi::SYNC_FILE_STATUS_HAS_PENDING_CHANGES: return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_PENDING; case fileapi::SYNC_FILE_STATUS_CONFLICTING: return api::sync_file_system:: SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_CONFLICTING; } NOTREACHED(); return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_NONE; } sync_file_system::SyncFileSystemService* GetSyncFileSystemService( Profile* profile) { sync_file_system::SyncFileSystemService* service = SyncFileSystemServiceFactory::GetForProfile(profile); DCHECK(service); ExtensionSyncEventObserver* observer = ExtensionSyncEventObserverFactory::GetForProfile(profile); DCHECK(observer); observer->InitializeForService(service, kDriveCloudService); return service; } } // namespace bool SyncFileSystemDeleteFileSystemFunction::RunImpl() { // TODO(calvinlo): Move error code to util function. (http://crbug.com/160496) std::string url; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url)); fileapi::FileSystemURL file_system_url((GURL(url))); scoped_refptr<fileapi::FileSystemContext> file_system_context = BrowserContext::GetStoragePartition( profile(), render_view_host()->GetSiteInstance())->GetFileSystemContext(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, Bind(&fileapi::FileSystemContext::DeleteFileSystem, file_system_context, source_url().GetOrigin(), file_system_url.type(), Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this))); return true; } void SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem( base::PlatformFileError error) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this, error)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != base::PLATFORM_FILE_OK) { error_ = base::StringPrintf(kFileError, static_cast<int>(error)); SetResult(base::Value::CreateBooleanValue(false)); SendResponse(false); return; } SetResult(base::Value::CreateBooleanValue(true)); SendResponse(true); } bool SyncFileSystemRequestFileSystemFunction::RunImpl() { std::string service_name; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &service_name)); // TODO(calvinlo): Move error code to util function. (http://crbug.com/160496) if (service_name != std::string(kDriveCloudService)) { error_ = base::StringPrintf(kNotSupportedService, service_name.c_str()); return false; } // Initializes sync context for this extension and continue to open // a new file system. GetSyncFileSystemService(profile())-> InitializeForApp( GetFileSystemContext(), service_name, source_url().GetOrigin(), base::Bind(&self::DidInitializeFileSystemContext, this, service_name)); return true; } fileapi::FileSystemContext* SyncFileSystemRequestFileSystemFunction::GetFileSystemContext() { return BrowserContext::GetStoragePartition( profile(), render_view_host()->GetSiteInstance())->GetFileSystemContext(); } void SyncFileSystemRequestFileSystemFunction::DidInitializeFileSystemContext( const std::string& service_name, fileapi::SyncStatusCode status) { if (status != fileapi::SYNC_STATUS_OK) { error_ = fileapi::SyncStatusCodeToString(status); SendResponse(false); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, Bind(&fileapi::FileSystemContext::OpenSyncableFileSystem, GetFileSystemContext(), service_name, source_url().GetOrigin(), fileapi::kFileSystemTypeSyncable, true, /* create */ base::Bind(&self::DidOpenFileSystem, this))); } void SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem( base::PlatformFileError error, const std::string& file_system_name, const GURL& root_url) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem, this, error, file_system_name, root_url)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != base::PLATFORM_FILE_OK) { error_ = base::StringPrintf(kFileError, static_cast<int>(error)); SendResponse(false); return; } DictionaryValue* dict = new DictionaryValue(); SetResult(dict); dict->SetString("name", file_system_name); dict->SetString("root", root_url.spec()); SendResponse(true); } bool SyncFileSystemGetUsageAndQuotaFunction::RunImpl() { std::string url; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url)); fileapi::FileSystemURL file_system_url((GURL(url))); // TODO(calvinlo): For now only gDrive cloud service is supported. // TODO(calvinlo): Move error code to util function. (http://crbug.com/160496) const std::string service_name = file_system_url.filesystem_id(); if (service_name != std::string(kDriveCloudService)) { error_ = base::StringPrintf(kNotSupportedService, service_name.c_str()); return false; } scoped_refptr<quota::QuotaManager> quota_manager = BrowserContext::GetStoragePartition( profile(), render_view_host()->GetSiteInstance())->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, Bind(&quota::QuotaManager::GetUsageAndQuota, quota_manager, source_url().GetOrigin(), fileapi::FileSystemTypeToQuotaStorageType(file_system_url.type()), Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this))); return true; } bool SyncFileSystemGetFileSyncStatusFunction::RunImpl() { std::string url; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url)); fileapi::FileSystemURL file_system_url((GURL(url))); SyncFileSystemServiceFactory::GetForProfile(profile())->GetFileSyncStatus( file_system_url, Bind(&SyncFileSystemGetFileSyncStatusFunction::DidGetFileSyncStatus, this)); return true; } void SyncFileSystemGetFileSyncStatusFunction::DidGetFileSyncStatus( const fileapi::SyncStatusCode sync_service_status, const fileapi::SyncFileStatus sync_file_status) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemGetFileSyncStatusFunction::DidGetFileSyncStatus, this, sync_service_status, sync_file_status)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (sync_service_status != fileapi::SYNC_STATUS_OK) { error_ = fileapi::SyncStatusCodeToString(sync_service_status); SendResponse(false); return; } // Convert from C++ to JavaScript enum. results_ = api::sync_file_system::GetFileSyncStatus::Results::Create( FileSyncStatusEnumToExtensionEnum(sync_file_status)); SendResponse(true); } void SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota( quota::QuotaStatusCode status, int64 usage, int64 quota) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this, status, usage, quota)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (status != quota::kQuotaStatusOk) { error_ = QuotaStatusCodeToString(status); SendResponse(false); return; } api::sync_file_system::StorageInfo info; info.usage_bytes = usage; info.quota_bytes = quota; results_ = api::sync_file_system::GetUsageAndQuota::Results::Create(info); SendResponse(true); } } // namespace extensions <commit_msg>Added common function to check for supported syncable file system service names.<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 "chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h" #include <string> #include "base/bind.h" #include "base/logging.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h" #include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sync_file_system/drive_file_sync_service.h" #include "chrome/browser/sync_file_system/sync_file_system_service.h" #include "chrome/common/extensions/api/sync_file_system.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/content_client.h" #include "webkit/fileapi/file_system_context.h" #include "webkit/fileapi/file_system_types.h" #include "webkit/fileapi/file_system_url.h" #include "webkit/fileapi/file_system_util.h" #include "webkit/fileapi/syncable/sync_file_status.h" #include "webkit/quota/quota_manager.h" using content::BrowserContext; using content::BrowserThread; using sync_file_system::SyncFileSystemServiceFactory; namespace extensions { namespace { // This is the only supported cloud backend service for now. const char* const kDriveCloudService = sync_file_system::DriveFileSyncService::kServiceName; // Error messages. const char kNotSupportedService[] = "Cloud service %s not supported."; const char kFileError[] = "File error %d."; const char kQuotaError[] = "Quota error %d."; api::sync_file_system::FileSyncStatus FileSyncStatusEnumToExtensionEnum( const fileapi::SyncFileStatus state) { switch (state) { case fileapi::SYNC_FILE_STATUS_UNKNOWN: return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_NONE; case fileapi::SYNC_FILE_STATUS_SYNCED: return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_SYNCED; case fileapi::SYNC_FILE_STATUS_HAS_PENDING_CHANGES: return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_PENDING; case fileapi::SYNC_FILE_STATUS_CONFLICTING: return api::sync_file_system:: SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_CONFLICTING; } NOTREACHED(); return api::sync_file_system::SYNC_FILE_SYSTEM_FILE_SYNC_STATUS_NONE; } sync_file_system::SyncFileSystemService* GetSyncFileSystemService( Profile* profile) { sync_file_system::SyncFileSystemService* service = SyncFileSystemServiceFactory::GetForProfile(profile); DCHECK(service); ExtensionSyncEventObserver* observer = ExtensionSyncEventObserverFactory::GetForProfile(profile); DCHECK(observer); observer->InitializeForService(service, kDriveCloudService); return service; } bool IsValidServiceName(const std::string& service_name, std::string* error) { DCHECK(error); if (service_name != std::string(kDriveCloudService)) { *error = base::StringPrintf(kNotSupportedService, service_name.c_str()); return false; } return true; } } // namespace bool SyncFileSystemDeleteFileSystemFunction::RunImpl() { std::string url; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url)); fileapi::FileSystemURL file_system_url((GURL(url))); if (!IsValidServiceName(file_system_url.filesystem_id(), &error_)) { return false; } scoped_refptr<fileapi::FileSystemContext> file_system_context = BrowserContext::GetStoragePartition( profile(), render_view_host()->GetSiteInstance())->GetFileSystemContext(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, Bind(&fileapi::FileSystemContext::DeleteFileSystem, file_system_context, source_url().GetOrigin(), file_system_url.type(), Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this))); return true; } void SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem( base::PlatformFileError error) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this, error)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != base::PLATFORM_FILE_OK) { error_ = base::StringPrintf(kFileError, static_cast<int>(error)); SetResult(base::Value::CreateBooleanValue(false)); SendResponse(false); return; } SetResult(base::Value::CreateBooleanValue(true)); SendResponse(true); } bool SyncFileSystemRequestFileSystemFunction::RunImpl() { std::string service_name; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &service_name)); if (!IsValidServiceName(service_name, &error_)) { return false; } // Initializes sync context for this extension and continue to open // a new file system. GetSyncFileSystemService(profile())-> InitializeForApp( GetFileSystemContext(), service_name, source_url().GetOrigin(), base::Bind(&self::DidInitializeFileSystemContext, this, service_name)); return true; } fileapi::FileSystemContext* SyncFileSystemRequestFileSystemFunction::GetFileSystemContext() { return BrowserContext::GetStoragePartition( profile(), render_view_host()->GetSiteInstance())->GetFileSystemContext(); } void SyncFileSystemRequestFileSystemFunction::DidInitializeFileSystemContext( const std::string& service_name, fileapi::SyncStatusCode status) { if (status != fileapi::SYNC_STATUS_OK) { error_ = fileapi::SyncStatusCodeToString(status); SendResponse(false); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, Bind(&fileapi::FileSystemContext::OpenSyncableFileSystem, GetFileSystemContext(), service_name, source_url().GetOrigin(), fileapi::kFileSystemTypeSyncable, true, /* create */ base::Bind(&self::DidOpenFileSystem, this))); } void SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem( base::PlatformFileError error, const std::string& file_system_name, const GURL& root_url) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem, this, error, file_system_name, root_url)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (error != base::PLATFORM_FILE_OK) { error_ = base::StringPrintf(kFileError, static_cast<int>(error)); SendResponse(false); return; } DictionaryValue* dict = new DictionaryValue(); SetResult(dict); dict->SetString("name", file_system_name); dict->SetString("root", root_url.spec()); SendResponse(true); } bool SyncFileSystemGetUsageAndQuotaFunction::RunImpl() { std::string url; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url)); fileapi::FileSystemURL file_system_url((GURL(url))); if (!IsValidServiceName(file_system_url.filesystem_id(), &error_)) { return false; } scoped_refptr<quota::QuotaManager> quota_manager = BrowserContext::GetStoragePartition( profile(), render_view_host()->GetSiteInstance())->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, Bind(&quota::QuotaManager::GetUsageAndQuota, quota_manager, source_url().GetOrigin(), fileapi::FileSystemTypeToQuotaStorageType(file_system_url.type()), Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this))); return true; } bool SyncFileSystemGetFileSyncStatusFunction::RunImpl() { std::string url; EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url)); fileapi::FileSystemURL file_system_url((GURL(url))); SyncFileSystemServiceFactory::GetForProfile(profile())->GetFileSyncStatus( file_system_url, Bind(&SyncFileSystemGetFileSyncStatusFunction::DidGetFileSyncStatus, this)); return true; } void SyncFileSystemGetFileSyncStatusFunction::DidGetFileSyncStatus( const fileapi::SyncStatusCode sync_service_status, const fileapi::SyncFileStatus sync_file_status) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemGetFileSyncStatusFunction::DidGetFileSyncStatus, this, sync_service_status, sync_file_status)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (sync_service_status != fileapi::SYNC_STATUS_OK) { error_ = fileapi::SyncStatusCodeToString(sync_service_status); SendResponse(false); return; } // Convert from C++ to JavaScript enum. results_ = api::sync_file_system::GetFileSyncStatus::Results::Create( FileSyncStatusEnumToExtensionEnum(sync_file_status)); SendResponse(true); } void SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota( quota::QuotaStatusCode status, int64 usage, int64 quota) { // Repost to switch from IO thread to UI thread for SendResponse(). if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this, status, usage, quota)); return; } DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (status != quota::kQuotaStatusOk) { error_ = QuotaStatusCodeToString(status); SendResponse(false); return; } api::sync_file_system::StorageInfo info; info.usage_bytes = usage; info.quota_bytes = quota; results_ = api::sync_file_system::GetUsageAndQuota::Results::Create(info); SendResponse(true); } } // namespace extensions <|endoftext|>
<commit_before>/* * opencog/attentionbank/AttentionBank.cc * * Copyright (C) 2013,2017 Linas Vepstas <[email protected]> * All Rights Reserved * * Written by Joel Pitt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <functional> #include <opencog/util/Config.h> #include <opencog/atoms/base/Handle.h> #include <opencog/atomspace/AtomSpace.h> #include "AttentionBank.h" #include "AVUtils.h" using namespace opencog; AttentionBank::AttentionBank(AtomSpace* asp) { startingFundsSTI = fundsSTI = config().get_double("STARTING_STI_FUNDS", 100000); startingFundsLTI = fundsLTI = config().get_double("STARTING_LTI_FUNDS", 100000); stiFundsBuffer = config().get_double("STI_FUNDS_BUFFER", 10000); ltiFundsBuffer = config().get_double("LTI_FUNDS_BUFFER", 10000); targetLTI = config().get_double("TARGET_LTI_FUNDS", 10000); targetSTI = config().get_double("TARGET_STI_FUNDS", 10000); STIAtomWage = config().get_double("ECAN_STARTING_ATOM_STI_WAGE", 10); LTIAtomWage = config().get_double("ECAN_STARTING_ATOM_LTI_WAGE", 10); maxAFSize = config().get_int("ECAN_MAX_AF_SIZE", 100); _remove_signal = &asp->atomRemovedSignal(); _remove_connection = _remove_signal->connect( std::bind(&AttentionBank::remove_atom_from_bank, this, std::placeholders::_1)); } AttentionBank::~AttentionBank() { //_remove_signal->disconnect(_remove_connection); } void AttentionBank::remove_atom_from_bank(const AtomPtr& atom) { AFMutex.lock(); auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [atom](std::pair<Handle, AttentionValuePtr> p) { return p.first == Handle(atom);}); if (it != attentionalFocus.end()) attentionalFocus.erase(it); AFMutex.unlock(); _importanceIndex.removeAtom(Handle(atom)); } void AttentionBank::set_sti(const Handle& h, AttentionValue::sti_t stiValue) { AttentionValuePtr oldav = get_av(h); AttentionValuePtr newav = AttentionValue::createAV( stiValue, oldav->getLTI(), oldav->getVLTI()); _importanceIndex.updateImportance(h, oldav, newav); AVChanged(h, oldav, newav); } void AttentionBank::set_lti(const Handle& h, AttentionValue::lti_t ltiValue) { AttentionValuePtr old_av = get_av(h); AttentionValuePtr new_av = AttentionValue::createAV( old_av->getSTI(), ltiValue, old_av->getVLTI()); AVChanged(h, old_av, new_av); } void AttentionBank::change_vlti(const Handle& h, int unit) { AttentionValuePtr old_av = get_av(h); AttentionValuePtr new_av = AttentionValue::createAV( old_av->getSTI(), old_av->getLTI(), old_av->getVLTI() + unit); AVChanged(h, old_av, new_av); } void AttentionBank::change_av(const Handle& h, const AttentionValuePtr& new_av) { AttentionValuePtr old_av = get_av(h); _importanceIndex.updateImportance(h, old_av, new_av); AVChanged(h, old_av, new_av); } void AttentionBank::AVChanged(const Handle& h, const AttentionValuePtr& old_av, const AttentionValuePtr& new_av) { _mtx.lock(); // First, update the atom's actual AV. set_av(h, new_av); AttentionValue::sti_t oldSti = old_av->getSTI(); AttentionValue::sti_t newSti = new_av->getSTI(); // Add the old attention values to the AttentionBank funds and // subtract the new attention values from the AttentionBank funds fundsSTI += (oldSti - newSti); fundsLTI += (old_av->getLTI() - new_av->getLTI()); _importanceIndex.update(); _mtx.unlock(); logger().fine("AVChanged: fundsSTI = %d, old_av: %d, new_av: %d", fundsSTI, oldSti, newSti); // Notify any interested parties that the AV changed. _AVChangedSignal.emit(h, old_av, new_av); // update AF updateAttentionalFocus(h, old_av, new_av); } void AttentionBank::stimulate(const Handle& h, double stimulus) { // XXX This is not protected or made atomic in any way ... // If two different threads stimulate the same atom at the same // time, then the calculations will be bad. Does it matter? AttentionValuePtr oldav(get_av(h)); AttentionValue::sti_t sti = oldav->getSTI(); AttentionValue::lti_t lti = oldav->getLTI(); AttentionValue::vlti_t vlti = oldav->getVLTI(); AttentionValue::sti_t stiWage = calculateSTIWage() * stimulus; AttentionValue::lti_t ltiWage = calculateLTIWage() * stimulus; AttentionValuePtr newav = AttentionValue::createAV( sti + stiWage, lti + ltiWage, vlti); _importanceIndex.updateImportance(h, oldav, newav); AVChanged(h, oldav, newav); #ifdef ECAN_EXPERIMENT if(stimulusRec.find(h) != stimulusRec.end()){ stimulusRec[h] += stimulus; } else{ stimulusRec[h] = stimulus; } #endif } AttentionValue::sti_t AttentionBank::calculateSTIWage() { AttentionValue::sti_t funds = getSTIFunds(); AttentionValue::sti_t diff = funds - targetSTI; AttentionValue::sti_t ndiff = diff / stiFundsBuffer; ndiff = std::min(ndiff, 1.0); ndiff = std::max(ndiff, -1.0); return STIAtomWage + (STIAtomWage * ndiff); } AttentionValue::lti_t AttentionBank::calculateLTIWage() { AttentionValue::lti_t funds = getLTIFunds(); AttentionValue::lti_t diff = funds - targetLTI; AttentionValue::lti_t ndiff = diff / ltiFundsBuffer; ndiff = std::min(ndiff, 1.0); ndiff = std::max(ndiff, -1.0); return LTIAtomWage + (LTIAtomWage * ndiff); } double AttentionBank::getNormalisedSTI(AttentionValuePtr av, bool average, bool clip) const { double val; // get normalizer (maxSTI - attention boundary) AttentionValue::sti_t s = av->getSTI(); if (s > get_af_max_sti()) { int normaliser = (int) getMaxSTI(average) - get_af_max_sti(); if (normaliser == 0) return 0.0; val = (s - get_af_max_sti()) / (double) normaliser; } else { int normaliser = -((int) getMinSTI(average) + get_af_max_sti()); if (normaliser == 0) return 0.0; val = (s + get_af_max_sti()) / (double) normaliser; } if (clip) return std::max(-1.0, std::min(val, 1.0)); return val; } double AttentionBank::getNormalisedSTI(AttentionValuePtr av) const { AttentionValue::sti_t s = av->getSTI(); auto normaliser = s > get_af_max_sti() ? getMaxSTI() : getMinSTI(); return (s / normaliser); } double AttentionBank::getNormalisedZeroToOneSTI(AttentionValuePtr av, bool average, bool clip) const { AttentionValue::sti_t s = av->getSTI(); int normaliser = getMaxSTI(average) - getMinSTI(average); if (normaliser == 0) return 0.0; double val = (s - getMinSTI(average)) / (double) normaliser; if (clip) return std::max(0.0, std::min(val, 1.0)); return val; } /** Unique singleton instance (for now) */ // This implementation is pretty hokey, and is a stop-gap until some // sort of more elegant way of managing the attentionbank is found. // One of the issues is that access via this function can be CPU-wasteful. AttentionBank& opencog::attentionbank(AtomSpace* asp) { static AttentionBank* _instance = nullptr; static AtomSpace* _as = nullptr; // Protect setting and getting against thread races. // This is probably not needed. static std::map<AtomSpace*, AttentionBank*> banksy; static std::mutex art; std::unique_lock<std::mutex> graffiti(art); if (_as != asp and _instance) { delete _instance; _instance = nullptr; _as = nullptr; } if (asp and nullptr == _instance) { _instance = new AttentionBank(asp); _as = asp; } return *_instance; } bool AttentionBank::atom_is_in_AF(const Handle& h) { auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [h](std::pair<Handle, AttentionValuePtr> p) { if (p.first == h) return true; return false; }); return (it != attentionalFocus.end()); } /** * Updates list of top K important atoms based on STI value. */ void AttentionBank::updateAttentionalFocus(const Handle& h, const AttentionValuePtr& old_av, const AttentionValuePtr& new_av) { std::lock_guard<std::mutex> lock(AFMutex); AttentionValue::sti_t sti = new_av->getSTI(); auto least = attentionalFocus.begin(); // Atom to be removed from the AF bool insertable = false; auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [h](std::pair<Handle, AttentionValuePtr> p) { return p.first == h;}); // Update the STI value if atoms was already in AF if (it != attentionalFocus.end()) { attentionalFocus.erase(it); attentionalFocus.insert(std::make_pair(h, new_av)); return; } // Simply insert the new Atom if AF is not full yet. else if (attentionalFocus.size() < maxAFSize) { insertable = true; } // Remove the least sti valued atom in the AF and replace // it with the new atom holding a higher STI value. else if (sti > (least->second)->getSTI()) { Handle hrm = least->first; AttentionValuePtr hrm_new_av = get_av(hrm); // Value recorded when this atom entered into AF AttentionValuePtr hrm_old_av = least->second; attentionalFocus.erase(least); AFCHSigl& afch = RemoveAFSignal(); afch.emit(hrm, hrm_old_av, hrm_new_av); insertable = true; } // Insert the new atom in to AF and emit the AddAFSignal. if (insertable) { attentionalFocus.insert(std::make_pair(h, new_av)); AFCHSigl& afch = AddAFSignal(); afch.emit(h, old_av, new_av); } } Handle AttentionBank::getRandomAtomNotInAF(void) { std::lock_guard<std::mutex> lock(AFMutex); auto find_in_af = [this](const Handle& h){ auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [h](std::pair<Handle, AttentionValuePtr> hsp) { return hsp.first == h; }); return it; }; int count = 50; // We might get stuck in the while loop if there are no atoms outside the AF Handle h = Handle::UNDEFINED; while(find_in_af(h) != attentionalFocus.end() and --count > 0){ h = _importanceIndex.getRandomAtom(); } // Make sure the last selection did not select from the AF. if(find_in_af(h) != attentionalFocus.end()) return Handle::UNDEFINED; return h; } <commit_msg>Fix bad signal delivery when attentionbank is gone<commit_after>/* * opencog/attentionbank/AttentionBank.cc * * Copyright (C) 2013,2017 Linas Vepstas <[email protected]> * All Rights Reserved * * Written by Joel Pitt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <functional> #include <opencog/util/Config.h> #include <opencog/atoms/base/Handle.h> #include <opencog/atomspace/AtomSpace.h> #include "AttentionBank.h" #include "AVUtils.h" using namespace opencog; AttentionBank::AttentionBank(AtomSpace* asp) { startingFundsSTI = fundsSTI = config().get_double("STARTING_STI_FUNDS", 100000); startingFundsLTI = fundsLTI = config().get_double("STARTING_LTI_FUNDS", 100000); stiFundsBuffer = config().get_double("STI_FUNDS_BUFFER", 10000); ltiFundsBuffer = config().get_double("LTI_FUNDS_BUFFER", 10000); targetLTI = config().get_double("TARGET_LTI_FUNDS", 10000); targetSTI = config().get_double("TARGET_STI_FUNDS", 10000); STIAtomWage = config().get_double("ECAN_STARTING_ATOM_STI_WAGE", 10); LTIAtomWage = config().get_double("ECAN_STARTING_ATOM_LTI_WAGE", 10); maxAFSize = config().get_int("ECAN_MAX_AF_SIZE", 100); _remove_signal = &asp->atomRemovedSignal(); _remove_connection = _remove_signal->connect( std::bind(&AttentionBank::remove_atom_from_bank, this, std::placeholders::_1)); } AttentionBank::~AttentionBank() { _remove_signal->disconnect(_remove_connection); } void AttentionBank::remove_atom_from_bank(const AtomPtr& atom) { AFMutex.lock(); auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [atom](std::pair<Handle, AttentionValuePtr> p) { return p.first == Handle(atom);}); if (it != attentionalFocus.end()) attentionalFocus.erase(it); AFMutex.unlock(); _importanceIndex.removeAtom(Handle(atom)); } void AttentionBank::set_sti(const Handle& h, AttentionValue::sti_t stiValue) { AttentionValuePtr oldav = get_av(h); AttentionValuePtr newav = AttentionValue::createAV( stiValue, oldav->getLTI(), oldav->getVLTI()); _importanceIndex.updateImportance(h, oldav, newav); AVChanged(h, oldav, newav); } void AttentionBank::set_lti(const Handle& h, AttentionValue::lti_t ltiValue) { AttentionValuePtr old_av = get_av(h); AttentionValuePtr new_av = AttentionValue::createAV( old_av->getSTI(), ltiValue, old_av->getVLTI()); AVChanged(h, old_av, new_av); } void AttentionBank::change_vlti(const Handle& h, int unit) { AttentionValuePtr old_av = get_av(h); AttentionValuePtr new_av = AttentionValue::createAV( old_av->getSTI(), old_av->getLTI(), old_av->getVLTI() + unit); AVChanged(h, old_av, new_av); } void AttentionBank::change_av(const Handle& h, const AttentionValuePtr& new_av) { AttentionValuePtr old_av = get_av(h); _importanceIndex.updateImportance(h, old_av, new_av); AVChanged(h, old_av, new_av); } void AttentionBank::AVChanged(const Handle& h, const AttentionValuePtr& old_av, const AttentionValuePtr& new_av) { _mtx.lock(); // First, update the atom's actual AV. set_av(h, new_av); AttentionValue::sti_t oldSti = old_av->getSTI(); AttentionValue::sti_t newSti = new_av->getSTI(); // Add the old attention values to the AttentionBank funds and // subtract the new attention values from the AttentionBank funds fundsSTI += (oldSti - newSti); fundsLTI += (old_av->getLTI() - new_av->getLTI()); _importanceIndex.update(); _mtx.unlock(); logger().fine("AVChanged: fundsSTI = %d, old_av: %d, new_av: %d", fundsSTI, oldSti, newSti); // Notify any interested parties that the AV changed. _AVChangedSignal.emit(h, old_av, new_av); // update AF updateAttentionalFocus(h, old_av, new_av); } void AttentionBank::stimulate(const Handle& h, double stimulus) { // XXX This is not protected or made atomic in any way ... // If two different threads stimulate the same atom at the same // time, then the calculations will be bad. Does it matter? AttentionValuePtr oldav(get_av(h)); AttentionValue::sti_t sti = oldav->getSTI(); AttentionValue::lti_t lti = oldav->getLTI(); AttentionValue::vlti_t vlti = oldav->getVLTI(); AttentionValue::sti_t stiWage = calculateSTIWage() * stimulus; AttentionValue::lti_t ltiWage = calculateLTIWage() * stimulus; AttentionValuePtr newav = AttentionValue::createAV( sti + stiWage, lti + ltiWage, vlti); _importanceIndex.updateImportance(h, oldav, newav); AVChanged(h, oldav, newav); #ifdef ECAN_EXPERIMENT if(stimulusRec.find(h) != stimulusRec.end()){ stimulusRec[h] += stimulus; } else{ stimulusRec[h] = stimulus; } #endif } AttentionValue::sti_t AttentionBank::calculateSTIWage() { AttentionValue::sti_t funds = getSTIFunds(); AttentionValue::sti_t diff = funds - targetSTI; AttentionValue::sti_t ndiff = diff / stiFundsBuffer; ndiff = std::min(ndiff, 1.0); ndiff = std::max(ndiff, -1.0); return STIAtomWage + (STIAtomWage * ndiff); } AttentionValue::lti_t AttentionBank::calculateLTIWage() { AttentionValue::lti_t funds = getLTIFunds(); AttentionValue::lti_t diff = funds - targetLTI; AttentionValue::lti_t ndiff = diff / ltiFundsBuffer; ndiff = std::min(ndiff, 1.0); ndiff = std::max(ndiff, -1.0); return LTIAtomWage + (LTIAtomWage * ndiff); } double AttentionBank::getNormalisedSTI(AttentionValuePtr av, bool average, bool clip) const { double val; // get normalizer (maxSTI - attention boundary) AttentionValue::sti_t s = av->getSTI(); if (s > get_af_max_sti()) { int normaliser = (int) getMaxSTI(average) - get_af_max_sti(); if (normaliser == 0) return 0.0; val = (s - get_af_max_sti()) / (double) normaliser; } else { int normaliser = -((int) getMinSTI(average) + get_af_max_sti()); if (normaliser == 0) return 0.0; val = (s + get_af_max_sti()) / (double) normaliser; } if (clip) return std::max(-1.0, std::min(val, 1.0)); return val; } double AttentionBank::getNormalisedSTI(AttentionValuePtr av) const { AttentionValue::sti_t s = av->getSTI(); auto normaliser = s > get_af_max_sti() ? getMaxSTI() : getMinSTI(); return (s / normaliser); } double AttentionBank::getNormalisedZeroToOneSTI(AttentionValuePtr av, bool average, bool clip) const { AttentionValue::sti_t s = av->getSTI(); int normaliser = getMaxSTI(average) - getMinSTI(average); if (normaliser == 0) return 0.0; double val = (s - getMinSTI(average)) / (double) normaliser; if (clip) return std::max(0.0, std::min(val, 1.0)); return val; } /** Unique singleton instance (for now) */ // This implementation is pretty hokey, and is a stop-gap until some // sort of more elegant way of managing the attentionbank is found. // One of the issues is that access via this function can be CPU-wasteful. AttentionBank& opencog::attentionbank(AtomSpace* asp) { static AttentionBank* _instance = nullptr; static AtomSpace* _as = nullptr; // Protect setting and getting against thread races. // This is probably not needed. static std::map<AtomSpace*, AttentionBank*> banksy; static std::mutex art; std::unique_lock<std::mutex> graffiti(art); if (_as != asp and _instance) { delete _instance; _instance = nullptr; _as = nullptr; } if (asp and nullptr == _instance) { _instance = new AttentionBank(asp); _as = asp; } return *_instance; } bool AttentionBank::atom_is_in_AF(const Handle& h) { auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [h](std::pair<Handle, AttentionValuePtr> p) { if (p.first == h) return true; return false; }); return (it != attentionalFocus.end()); } /** * Updates list of top K important atoms based on STI value. */ void AttentionBank::updateAttentionalFocus(const Handle& h, const AttentionValuePtr& old_av, const AttentionValuePtr& new_av) { std::lock_guard<std::mutex> lock(AFMutex); AttentionValue::sti_t sti = new_av->getSTI(); auto least = attentionalFocus.begin(); // Atom to be removed from the AF bool insertable = false; auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [h](std::pair<Handle, AttentionValuePtr> p) { return p.first == h;}); // Update the STI value if atoms was already in AF if (it != attentionalFocus.end()) { attentionalFocus.erase(it); attentionalFocus.insert(std::make_pair(h, new_av)); return; } // Simply insert the new Atom if AF is not full yet. else if (attentionalFocus.size() < maxAFSize) { insertable = true; } // Remove the least sti valued atom in the AF and replace // it with the new atom holding a higher STI value. else if (sti > (least->second)->getSTI()) { Handle hrm = least->first; AttentionValuePtr hrm_new_av = get_av(hrm); // Value recorded when this atom entered into AF AttentionValuePtr hrm_old_av = least->second; attentionalFocus.erase(least); AFCHSigl& afch = RemoveAFSignal(); afch.emit(hrm, hrm_old_av, hrm_new_av); insertable = true; } // Insert the new atom in to AF and emit the AddAFSignal. if (insertable) { attentionalFocus.insert(std::make_pair(h, new_av)); AFCHSigl& afch = AddAFSignal(); afch.emit(h, old_av, new_av); } } Handle AttentionBank::getRandomAtomNotInAF(void) { std::lock_guard<std::mutex> lock(AFMutex); auto find_in_af = [this](const Handle& h){ auto it = std::find_if(attentionalFocus.begin(), attentionalFocus.end(), [h](std::pair<Handle, AttentionValuePtr> hsp) { return hsp.first == h; }); return it; }; int count = 50; // We might get stuck in the while loop if there are no atoms outside the AF Handle h = Handle::UNDEFINED; while(find_in_af(h) != attentionalFocus.end() and --count > 0){ h = _importanceIndex.getRandomAtom(); } // Make sure the last selection did not select from the AF. if(find_in_af(h) != attentionalFocus.end()) return Handle::UNDEFINED; return h; } <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/sort.hpp * * Part of Project c7a. * * Copyright (C) 2015 Alexander Noe <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_SORT_HEADER #define C7A_API_SORT_HEADER #include <c7a/api/function_stack.hpp> #include <c7a/api/dia.hpp> #include <c7a/api/context.hpp> #include <c7a/net/group.hpp> #include <c7a/net/collective_communication.hpp> #include <c7a/net/flow_control_channel.hpp> #include <c7a/net/flow_control_manager.hpp> #include <c7a/common/logger.hpp> #include <cmath> namespace c7a { namespace api { template <typename ValueType, typename ParentStack, typename CompareFunction> class SortNode : public DOpNode<ValueType> { static const bool debug = true; using Super = DOpNode<ValueType>; using Super::context_; using Super::data_id_; using ParentInput = typename ParentStack::Input; public: SortNode(Context& ctx, std::shared_ptr<DIANode<ParentInput> > parent, const ParentStack& parent_stack, CompareFunction compare_function) : DOpNode<ValueType>(ctx, { parent }), compare_function_(compare_function), channel_id_samples_(ctx.data_manager().AllocateNetworkChannel()), emitters_samples_(ctx.data_manager(). template GetNetworkEmitters<ValueType>(channel_id_samples_)), channel_id_data_(ctx.data_manager().AllocateNetworkChannel()), emitters_data_(ctx.data_manager(). template GetNetworkEmitters<ValueType>(channel_id_data_)) { // Hook PreOp(s) auto pre_op_fn = [=](const ValueType& input) { PreOp(input); }; auto lop_chain = parent_stack.push(pre_op_fn).emit(); parent->RegisterChild(lop_chain); } virtual ~SortNode() { } //! Executes the sum operation. void Execute() override { MainOp(); } /*! * Produces an 'empty' function stack, which only contains the identity * emitter function. * * \return Empty function stack */ auto ProduceStack() { // Hook Identity auto id_fn = [=](ValueType t, auto emit_func) { return emit_func(t); }; return MakeFunctionStack<ValueType>(id_fn); } /*! * Returns "[SortNode]" as a string. * \return "[SortNode]" */ std::string ToString() override { return "[PrefixSumNode] Id:" + data_id_.ToString(); } private: //! The sum function which is applied to two elements. CompareFunction compare_function_; //! Local data std::vector<ValueType> data_; //!Emitter to send samples to process 0 data::ChannelId channel_id_samples_; std::vector<data::Emitter<ValueType> > emitters_samples_; //!Emitters to send data to other workers specified by splitters. data::ChannelId channel_id_data_; std::vector<data::Emitter<ValueType> > emitters_data_; //epsilon double desired_imbalance = 0.25; void PreOp(ValueType input) { //LOG << "Input: " << input; data_.push_back(input); } void MainOp() { //LOG << "MainOp processing"; size_t samplesize = std::ceil(log2((double) data_.size()) * (1 / (desired_imbalance * desired_imbalance))); std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(0, data_.size() - 1); //Send samples to worker 0 for (size_t i = 0; i < samplesize; i++) { size_t sample = distribution(generator); emitters_samples_[0](data_[sample]); } emitters_samples_[0].Close(); std::vector<ValueType> splitters; splitters.reserve(context_.number_worker() - 1); if (context_.rank() == 0) { //Get samples std::vector<ValueType> samples; samples.reserve(samplesize * context_.number_worker()); auto it = context_.data_manager(). template GetIterator<ValueType>(channel_id_samples_); do { it.WaitForMore(); while (it.HasNext()) { samples.push_back(it.Next()); } } while (!it.IsFinished()); //Find splitters std::sort(samples.begin(), samples.end(), compare_function_); size_t splitting_size = samples.size() / context_.number_worker(); //Send splitters to other workers for (size_t i = 1; i < context_.number_worker(); i++) { splitters.push_back(samples[i * splitting_size]); for (size_t j = 1; j < context_.number_worker(); j++) { emitters_samples_[j](samples[i * splitting_size]); } } for (size_t j = 1; j < context_.number_worker(); j++) { emitters_samples_[j].Close(); } } else { //Close unused emitters for (size_t j = 1; j < context_.number_worker(); j++) { emitters_samples_[j].Close(); } auto it = context_.data_manager(). template GetIterator<ValueType>(channel_id_samples_); do { it.WaitForMore(); while (it.HasNext()) { splitters.push_back(it.Next()); } } while (!it.IsFinished()); } for (size_t i = 0; i < data_.size(); i++) { for (auto func : DIANode<ValueType>::callbacks_) { func(data_[i]); } } } void PostOp() { } }; template <typename ValueType, typename Stack> template <typename CompareFunction> auto DIARef<ValueType, Stack>::Sort(const CompareFunction & compare_function) const { using SortResultNode = SortNode<ValueType, Stack, CompareFunction>; static_assert( std::is_same< typename common::FunctionTraits<CompareFunction>::template arg<0>, ValueType>::value || std::is_same<CompareFunction, common::LessThan<ValueType> >::value, "CompareFunction has the wrong input type"); static_assert( std::is_same< typename common::FunctionTraits<CompareFunction>::template arg<1>, ValueType>::value || std::is_same<CompareFunction, common::LessThan<ValueType> >::value, "CompareFunction has the wrong input type"); static_assert( std::is_same< typename common::FunctionTraits<CompareFunction>::result_type, ValueType>::value || std::is_same<CompareFunction, common::LessThan<ValueType> >::value, "CompareFunction has the wrong input type"); auto shared_node = std::make_shared<SortResultNode>(node_->context(), node_, stack_, compare_function); auto sort_stack = shared_node->ProduceStack(); return DIARef<ValueType, decltype(sort_stack)>( std::move(shared_node), sort_stack); } } // namespace api } // namespace c7a #endif // !C7A_API_SORT_NODE_HEADER /******************************************************************************/ <commit_msg>Sort with trivial distribution.<commit_after>/******************************************************************************* * c7a/api/sort.hpp * * Part of Project c7a. * * Copyright (C) 2015 Alexander Noe <[email protected]> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_SORT_HEADER #define C7A_API_SORT_HEADER #include <c7a/api/function_stack.hpp> #include <c7a/api/dia.hpp> #include <c7a/api/context.hpp> #include <c7a/net/group.hpp> #include <c7a/net/collective_communication.hpp> #include <c7a/net/flow_control_channel.hpp> #include <c7a/net/flow_control_manager.hpp> #include <c7a/common/logger.hpp> #include <cmath> namespace c7a { namespace api { template <typename ValueType, typename ParentStack, typename CompareFunction> class SortNode : public DOpNode<ValueType> { static const bool debug = true; using Super = DOpNode<ValueType>; using Super::context_; using Super::data_id_; using ParentInput = typename ParentStack::Input; public: SortNode(Context& ctx, std::shared_ptr<DIANode<ParentInput> > parent, const ParentStack& parent_stack, CompareFunction compare_function) : DOpNode<ValueType>(ctx, { parent }), compare_function_(compare_function), channel_id_samples_(ctx.data_manager().AllocateNetworkChannel()), emitters_samples_(ctx.data_manager(). template GetNetworkEmitters<ValueType>(channel_id_samples_)), channel_id_data_(ctx.data_manager().AllocateNetworkChannel()), emitters_data_(ctx.data_manager(). template GetNetworkEmitters<ValueType>(channel_id_data_)) { // Hook PreOp(s) auto pre_op_fn = [=](const ValueType& input) { PreOp(input); }; auto lop_chain = parent_stack.push(pre_op_fn).emit(); parent->RegisterChild(lop_chain); } virtual ~SortNode() { } //! Executes the sum operation. void Execute() override { MainOp(); } /*! * Produces an 'empty' function stack, which only contains the identity * emitter function. * * \return Empty function stack */ auto ProduceStack() { // Hook Identity auto id_fn = [=](ValueType t, auto emit_func) { return emit_func(t); }; return MakeFunctionStack<ValueType>(id_fn); } /*! * Returns "[SortNode]" as a string. * \return "[SortNode]" */ std::string ToString() override { return "[PrefixSumNode] Id:" + data_id_.ToString(); } private: //! The sum function which is applied to two elements. CompareFunction compare_function_; //! Local data std::vector<ValueType> data_; //!Emitter to send samples to process 0 data::ChannelId channel_id_samples_; std::vector<data::Emitter<ValueType> > emitters_samples_; //!Emitters to send data to other workers specified by splitters. data::ChannelId channel_id_data_; std::vector<data::Emitter<ValueType> > emitters_data_; //epsilon double desired_imbalance = 0.25; void PreOp(ValueType input) { //LOG << "Input: " << input; data_.push_back(input); } void MainOp() { //LOG << "MainOp processing"; size_t samplesize = std::ceil(log2((double) data_.size()) * (1 / (desired_imbalance * desired_imbalance))); std::random_device random_device; std::default_random_engine generator(random_device()); std::uniform_int_distribution<int> distribution(0, data_.size() - 1); //Send samples to worker 0 for (size_t i = 0; i < samplesize; i++) { size_t sample = distribution(generator); emitters_samples_[0](data_[sample]); } emitters_samples_[0].Close(); std::vector<ValueType> splitters; splitters.reserve(context_.number_worker() - 1); if (context_.rank() == 0) { //Get samples std::vector<ValueType> samples; samples.reserve(samplesize * context_.number_worker()); auto it = context_.data_manager(). template GetIterator<ValueType>(channel_id_samples_); do { it.WaitForMore(); while (it.HasNext()) { samples.push_back(it.Next()); } } while (!it.IsFinished()); //Find splitters std::sort(samples.begin(), samples.end(), compare_function_); size_t splitting_size = samples.size() / context_.number_worker(); //Send splitters to other workers for (size_t i = 1; i < context_.number_worker(); i++) { splitters.push_back(samples[i * splitting_size]); for (size_t j = 1; j < context_.number_worker(); j++) { emitters_samples_[j](samples[i * splitting_size]); } } for (size_t j = 1; j < context_.number_worker(); j++) { emitters_samples_[j].Close(); } } else { //Close unused emitters for (size_t j = 1; j < context_.number_worker(); j++) { emitters_samples_[j].Close(); } auto it = context_.data_manager(). template GetIterator<ValueType>(channel_id_samples_); do { it.WaitForMore(); while (it.HasNext()) { splitters.push_back(it.Next()); } } while (!it.IsFinished()); } for (ValueType ele : data_) { bool sent = false; for (size_t i = 0; i < splitters.size() && !sent; i++) { if (compare_function_(ele, splitters[i])) { emitters_data_[i](ele); sent = true; break; } } if (!sent) { emitters_data_[splitters.size()](ele); } } for (size_t i = 0; i < emitters_data_.size(); i++) { emitters_data_[i].Close(); } data_.clear(); auto it = context_.data_manager(). template GetIterator<ValueType>(channel_id_data_); do { it.WaitForMore(); while (it.HasNext()) { data_.push_back(it.Next()); } } while (!it.IsFinished()); std::sort(data_.begin(), data_.end(), compare_function_); for (size_t i = 0; i < data_.size(); i++) { for (auto func : DIANode<ValueType>::callbacks_) { func(data_[i]); } } std::vector<ValueType>().swap(data_); } void PostOp() { } }; template <typename ValueType, typename Stack> template <typename CompareFunction> auto DIARef<ValueType, Stack>::Sort(const CompareFunction & compare_function) const { using SortResultNode = SortNode<ValueType, Stack, CompareFunction>; static_assert( std::is_same< typename common::FunctionTraits<CompareFunction>::template arg<0>, ValueType>::value || std::is_same<CompareFunction, common::LessThan<ValueType> >::value, "CompareFunction has the wrong input type"); static_assert( std::is_same< typename common::FunctionTraits<CompareFunction>::template arg<1>, ValueType>::value || std::is_same<CompareFunction, common::LessThan<ValueType> >::value, "CompareFunction has the wrong input type"); static_assert( std::is_same< typename common::FunctionTraits<CompareFunction>::result_type, ValueType>::value || std::is_same<CompareFunction, common::LessThan<ValueType> >::value, "CompareFunction has the wrong input type"); auto shared_node = std::make_shared<SortResultNode>(node_->context(), node_, stack_, compare_function); auto sort_stack = shared_node->ProduceStack(); return DIARef<ValueType, decltype(sort_stack)>( std::move(shared_node), sort_stack); } } // namespace api } // namespace c7a #endif // !C7A_API_SORT_NODE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]> 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 <memory> #include <unordered_map> #include <PluginManager/Manager.h> #include <DefaultFramebuffer.h> #include <Mesh.h> #include <Renderer.h> #include <MeshTools/Tipsify.h> #include <MeshTools/Interleave.h> #include <MeshTools/CompressIndices.h> #include <SceneGraph/Scene.h> #include <SceneGraph/Camera3D.h> #include <Shaders/Phong.h> #include <Trade/AbstractImporter.h> #include <Trade/MeshData3D.h> #include <Trade/MeshObjectData3D.h> #include <Trade/SceneData.h> #include "FpsCounterExample.h" #include "ViewedObject.h" #include "configure.h" using namespace Magnum::Trade; namespace Magnum { namespace Examples { class ViewerExample: public FpsCounterExample { public: explicit ViewerExample(const Arguments& arguments); ~ViewerExample(); protected: void viewportEvent(const Vector2i& size) override; void drawEvent() override; void keyPressEvent(KeyEvent& event) override; void mousePressEvent(MouseEvent& event) override; void mouseReleaseEvent(MouseEvent& event) override; void mouseMoveEvent(MouseMoveEvent& event) override; private: Vector3 positionOnSphere(const Vector2i& _position) const; void addObject(AbstractImporter* colladaImporter, Object3D* parent, std::unordered_map<std::size_t, PhongMaterialData*>& materials, std::size_t objectId); Scene3D scene; SceneGraph::DrawableGroup3D drawables; Object3D* cameraObject; SceneGraph::Camera3D* camera; Shaders::Phong shader; Object3D* o; std::unordered_map<std::size_t, std::tuple<Buffer*, Buffer*, Mesh*>> meshes; std::size_t vertexCount, triangleCount, objectCount, meshCount, materialCount; bool wireframe; Vector3 previousPosition; }; ViewerExample::ViewerExample(const Arguments& arguments): FpsCounterExample(arguments, (new Configuration)->setTitle("Magnum Viewer")), vertexCount(0), triangleCount(0), objectCount(0), meshCount(0), materialCount(0), wireframe(false) { if(arguments.argc != 2) { Debug() << "Usage:" << arguments.argv[0] << "file.dae"; std::exit(0); } /* Instance ColladaImporter plugin */ PluginManager::Manager<AbstractImporter> manager(MAGNUM_PLUGINS_IMPORTER_DIR); if(manager.load("ColladaImporter") != PluginManager::LoadState::Loaded) { Error() << "Could not load ColladaImporter plugin"; std::exit(1); } std::unique_ptr<AbstractImporter> colladaImporter(manager.instance("ColladaImporter")); if(!colladaImporter) { Error() << "Could not instance ColladaImporter plugin"; std::exit(2); } /* Every scene needs a camera */ (cameraObject = new Object3D(&scene)) ->translate(Vector3::zAxis(5)); (camera = new SceneGraph::Camera3D(cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) ->setPerspective(35.0_degf, 1.0f, 0.001f, 100); Renderer::setFeature(Renderer::Feature::DepthTest, true); Renderer::setFeature(Renderer::Feature::FaceCulling, true); Debug() << "Opening file" << arguments.argv[1]; /* Load file */ if(!colladaImporter->openFile(arguments.argv[1])) std::exit(4); if(colladaImporter->sceneCount() == 0) std::exit(5); /* Map with materials */ std::unordered_map<std::size_t, PhongMaterialData*> materials; /* Default object, parent of all (for manipulation) */ o = new Object3D(&scene); Debug() << "Adding default scene..."; /* Load the scene */ SceneData* scene = colladaImporter->scene(colladaImporter->defaultScene()); /* Add all children */ for(std::size_t objectId: scene->children3D()) addObject(colladaImporter.get(), o, materials, objectId); Debug() << "Imported" << objectCount << "objects with" << meshCount << "meshes and" << materialCount << "materials,"; Debug() << " " << vertexCount << "vertices and" << triangleCount << "triangles total."; /* Delete materials, as they are now unused */ for(auto i: materials) delete i.second; colladaImporter->close(); delete colladaImporter.release(); } ViewerExample::~ViewerExample() { for(auto i: meshes) { delete std::get<0>(i.second); delete std::get<1>(i.second); delete std::get<2>(i.second); } } void ViewerExample::viewportEvent(const Vector2i& size) { defaultFramebuffer.setViewport({{}, size}); camera->setViewport(size); FpsCounterExample::viewportEvent(size); } void ViewerExample::drawEvent() { defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth); camera->draw(drawables); swapBuffers(); if(fpsCounterEnabled()) redraw(); } void ViewerExample::keyPressEvent(KeyEvent& event) { switch(event.key()) { case KeyEvent::Key::Up: o->rotateX(-10.0_degf); break; case KeyEvent::Key::Down: o->rotateX(10.0_degf); break; case KeyEvent::Key::Left: o->rotateY(-10.0_degf, SceneGraph::TransformationType::Local); break; case KeyEvent::Key::Right: o->rotateY(10.0_degf, SceneGraph::TransformationType::Local); break; case KeyEvent::Key::PageUp: cameraObject->translate(Vector3::zAxis(-0.5), SceneGraph::TransformationType::Local); break; case KeyEvent::Key::PageDown: cameraObject->translate(Vector3::zAxis(0.5), SceneGraph::TransformationType::Local); break; #ifndef MAGNUM_TARGET_GLES case KeyEvent::Key::Home: Renderer::setPolygonMode(wireframe ? Renderer::PolygonMode::Fill : Renderer::PolygonMode::Line); wireframe = !wireframe; break; #endif case KeyEvent::Key::End: if(fpsCounterEnabled()) printCounterStatistics(); else resetCounter(); setFpsCounterEnabled(!fpsCounterEnabled()); break; default: break; } redraw(); } void ViewerExample::mousePressEvent(MouseEvent& event) { switch(event.button()) { case MouseEvent::Button::Left: previousPosition = positionOnSphere(event.position()); break; case MouseEvent::Button::WheelUp: case MouseEvent::Button::WheelDown: { /* Distance between origin and near camera clipping plane */ Float distance = cameraObject->transformation().translation().z()-0-camera->near(); /* Move 15% of the distance back or forward */ if(event.button() == MouseEvent::Button::WheelUp) distance *= 1 - 1/0.85f; else distance *= 1 - 0.85f; cameraObject->translate(Vector3::zAxis(distance), SceneGraph::TransformationType::Global); redraw(); break; } default: ; } } void ViewerExample::mouseReleaseEvent(MouseEvent& event) { if(event.button() == MouseEvent::Button::Left) previousPosition = Vector3(); } void ViewerExample::mouseMoveEvent(MouseMoveEvent& event) { Vector3 currentPosition = positionOnSphere(event.position()); Vector3 axis = Vector3::cross(previousPosition, currentPosition); if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return; o->rotate(Vector3::angle(previousPosition, currentPosition), axis.normalized()); previousPosition = currentPosition; redraw(); } Vector3 ViewerExample::positionOnSphere(const Vector2i& _position) const { Vector2i viewport = camera->viewport(); Vector2 position(_position.x()*2.0f/viewport.x() - 1.0f, _position.y()*2.0f/viewport.y() - 1.0f); Float length = position.length(); Vector3 result(length > 1.0f ? Vector3(position, 0.0f) : Vector3(position, 1.0f - length)); result.y() *= -1.0f; return result.normalized(); } void ViewerExample::addObject(AbstractImporter* colladaImporter, Object3D* parent, std::unordered_map<std::size_t, PhongMaterialData*>& materials, std::size_t objectId) { ObjectData3D* object = colladaImporter->object3D(objectId); /* Only meshes for now */ if(object->instanceType() == ObjectData3D::InstanceType::Mesh) { ++objectCount; /* Use already processed mesh, if exists */ Mesh* mesh; auto found = meshes.find(object->instanceId()); if(found != meshes.end()) mesh = std::get<2>(found->second); /* Or create a new one */ else { ++meshCount; mesh = new Mesh; Buffer* buffer = new Buffer; Buffer* indexBuffer = new Buffer; meshes.insert(std::make_pair(object->instanceId(), std::make_tuple(buffer, indexBuffer, mesh))); MeshData3D* data = colladaImporter->mesh3D(object->instanceId()); if(!data || !data->isIndexed() || !data->positionArrayCount() || !data->normalArrayCount()) std::exit(6); vertexCount += data->positions(0).size(); triangleCount += data->indices().size()/3; /* Optimize vertices */ Debug() << "Optimizing vertices of mesh" << object->instanceId() << "using Tipsify algorithm (cache size 24)..."; MeshTools::tipsify(data->indices(), data->positions(0).size(), 24); /* Interleave mesh data */ MeshTools::interleave(mesh, buffer, Buffer::Usage::StaticDraw, data->positions(0), data->normals(0)); mesh->addInterleavedVertexBuffer(buffer, 0, Shaders::Phong::Position(), Shaders::Phong::Normal()); /* Compress indices */ MeshTools::compressIndices(mesh, indexBuffer, Buffer::Usage::StaticDraw, data->indices()); delete data; } /* Use already processed material, if exists */ PhongMaterialData* material; auto materialFound = materials.find(static_cast<MeshObjectData3D*>(object)->material()); if(materialFound != materials.end()) material = materialFound->second; /* Else get material or create default one */ else { ++materialCount; material = static_cast<PhongMaterialData*>(colladaImporter->material(static_cast<MeshObjectData3D*>(object)->material())); if(!material) material = new PhongMaterialData({0.0f, 0.0f, 0.0f}, {0.9f, 0.9f, 0.9f}, {1.0f, 1.0f, 1.0f}, 50.0f); } /* Add object */ Object3D* o = new ViewedObject(mesh, material, &shader, parent, &drawables); delete material; o->setTransformation(object->transformation()); } /* Recursively add children */ for(std::size_t id: object->children()) addObject(colladaImporter, o, materials, id); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::ViewerExample) <commit_msg>viewer: adapted to Magnum changes.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <[email protected]> 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 <memory> #include <unordered_map> #include <PluginManager/Manager.h> #include <DefaultFramebuffer.h> #include <Mesh.h> #include <Renderer.h> #include <MeshTools/Tipsify.h> #include <MeshTools/Interleave.h> #include <MeshTools/CompressIndices.h> #include <SceneGraph/Scene.h> #include <SceneGraph/Camera3D.h> #include <Shaders/Phong.h> #include <Trade/AbstractImporter.h> #include <Trade/MeshData3D.h> #include <Trade/MeshObjectData3D.h> #include <Trade/SceneData.h> #include "FpsCounterExample.h" #include "ViewedObject.h" #include "configure.h" using namespace Magnum::Trade; namespace Magnum { namespace Examples { class ViewerExample: public FpsCounterExample { public: explicit ViewerExample(const Arguments& arguments); ~ViewerExample(); protected: void viewportEvent(const Vector2i& size) override; void drawEvent() override; void keyPressEvent(KeyEvent& event) override; void mousePressEvent(MouseEvent& event) override; void mouseReleaseEvent(MouseEvent& event) override; void mouseMoveEvent(MouseMoveEvent& event) override; private: Vector3 positionOnSphere(const Vector2i& _position) const; void addObject(AbstractImporter* colladaImporter, Object3D* parent, std::unordered_map<std::size_t, PhongMaterialData*>& materials, std::size_t objectId); Scene3D scene; SceneGraph::DrawableGroup3D drawables; Object3D* cameraObject; SceneGraph::Camera3D* camera; Shaders::Phong shader; Object3D* o; std::unordered_map<std::size_t, std::tuple<Buffer*, Buffer*, Mesh*>> meshes; std::size_t vertexCount, triangleCount, objectCount, meshCount, materialCount; bool wireframe; Vector3 previousPosition; }; ViewerExample::ViewerExample(const Arguments& arguments): FpsCounterExample(arguments, (new Configuration)->setTitle("Magnum Viewer")), vertexCount(0), triangleCount(0), objectCount(0), meshCount(0), materialCount(0), wireframe(false) { if(arguments.argc != 2) { Debug() << "Usage:" << arguments.argv[0] << "file.dae"; std::exit(0); } /* Instance ColladaImporter plugin */ PluginManager::Manager<AbstractImporter> manager(MAGNUM_PLUGINS_IMPORTER_DIR); if(manager.load("ColladaImporter") != PluginManager::LoadState::Loaded) { Error() << "Could not load ColladaImporter plugin"; std::exit(1); } std::unique_ptr<AbstractImporter> colladaImporter(manager.instance("ColladaImporter")); if(!colladaImporter) { Error() << "Could not instance ColladaImporter plugin"; std::exit(2); } /* Every scene needs a camera */ (cameraObject = new Object3D(&scene)) ->translate(Vector3::zAxis(5)); (camera = new SceneGraph::Camera3D(cameraObject)) ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend) ->setPerspective(35.0_degf, 1.0f, 0.001f, 100); Renderer::setFeature(Renderer::Feature::DepthTest, true); Renderer::setFeature(Renderer::Feature::FaceCulling, true); Debug() << "Opening file" << arguments.argv[1]; /* Load file */ if(!colladaImporter->openFile(arguments.argv[1])) std::exit(4); if(colladaImporter->sceneCount() == 0) std::exit(5); /* Map with materials */ std::unordered_map<std::size_t, PhongMaterialData*> materials; /* Default object, parent of all (for manipulation) */ o = new Object3D(&scene); Debug() << "Adding default scene..."; /* Load the scene */ SceneData* scene = colladaImporter->scene(colladaImporter->defaultScene()); /* Add all children */ for(std::size_t objectId: scene->children3D()) addObject(colladaImporter.get(), o, materials, objectId); Debug() << "Imported" << objectCount << "objects with" << meshCount << "meshes and" << materialCount << "materials,"; Debug() << " " << vertexCount << "vertices and" << triangleCount << "triangles total."; /* Delete materials, as they are now unused */ for(auto i: materials) delete i.second; colladaImporter->close(); delete colladaImporter.release(); } ViewerExample::~ViewerExample() { for(auto i: meshes) { delete std::get<0>(i.second); delete std::get<1>(i.second); delete std::get<2>(i.second); } } void ViewerExample::viewportEvent(const Vector2i& size) { defaultFramebuffer.setViewport({{}, size}); camera->setViewport(size); FpsCounterExample::viewportEvent(size); } void ViewerExample::drawEvent() { defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth); camera->draw(drawables); swapBuffers(); if(fpsCounterEnabled()) redraw(); } void ViewerExample::keyPressEvent(KeyEvent& event) { switch(event.key()) { case KeyEvent::Key::Up: o->rotateX(-10.0_degf); break; case KeyEvent::Key::Down: o->rotateX(10.0_degf); break; case KeyEvent::Key::Left: o->rotateY(-10.0_degf, SceneGraph::TransformationType::Local); break; case KeyEvent::Key::Right: o->rotateY(10.0_degf, SceneGraph::TransformationType::Local); break; case KeyEvent::Key::PageUp: cameraObject->translate(Vector3::zAxis(-0.5), SceneGraph::TransformationType::Local); break; case KeyEvent::Key::PageDown: cameraObject->translate(Vector3::zAxis(0.5), SceneGraph::TransformationType::Local); break; #ifndef MAGNUM_TARGET_GLES case KeyEvent::Key::Home: Renderer::setPolygonMode(wireframe ? Renderer::PolygonMode::Fill : Renderer::PolygonMode::Line); wireframe = !wireframe; break; #endif case KeyEvent::Key::End: if(fpsCounterEnabled()) printCounterStatistics(); else resetCounter(); setFpsCounterEnabled(!fpsCounterEnabled()); break; default: break; } redraw(); } void ViewerExample::mousePressEvent(MouseEvent& event) { switch(event.button()) { case MouseEvent::Button::Left: previousPosition = positionOnSphere(event.position()); break; case MouseEvent::Button::WheelUp: case MouseEvent::Button::WheelDown: { /* Distance between origin and near camera clipping plane */ Float distance = cameraObject->transformation().translation().z()-0-camera->near(); /* Move 15% of the distance back or forward */ if(event.button() == MouseEvent::Button::WheelUp) distance *= 1 - 1/0.85f; else distance *= 1 - 0.85f; cameraObject->translate(Vector3::zAxis(distance), SceneGraph::TransformationType::Global); redraw(); break; } default: ; } } void ViewerExample::mouseReleaseEvent(MouseEvent& event) { if(event.button() == MouseEvent::Button::Left) previousPosition = Vector3(); } void ViewerExample::mouseMoveEvent(MouseMoveEvent& event) { Vector3 currentPosition = positionOnSphere(event.position()); Vector3 axis = Vector3::cross(previousPosition, currentPosition); if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return; o->rotate(Vector3::angle(previousPosition, currentPosition), axis.normalized()); previousPosition = currentPosition; redraw(); } Vector3 ViewerExample::positionOnSphere(const Vector2i& _position) const { Vector2i viewport = camera->viewport(); Vector2 position(_position.x()*2.0f/viewport.x() - 1.0f, _position.y()*2.0f/viewport.y() - 1.0f); Float length = position.length(); Vector3 result(length > 1.0f ? Vector3(position, 0.0f) : Vector3(position, 1.0f - length)); result.y() *= -1.0f; return result.normalized(); } void ViewerExample::addObject(AbstractImporter* colladaImporter, Object3D* parent, std::unordered_map<std::size_t, PhongMaterialData*>& materials, std::size_t objectId) { ObjectData3D* object = colladaImporter->object3D(objectId); /* Only meshes for now */ if(object->instanceType() == ObjectData3D::InstanceType::Mesh) { ++objectCount; /* Use already processed mesh, if exists */ Mesh* mesh; auto found = meshes.find(object->instanceId()); if(found != meshes.end()) mesh = std::get<2>(found->second); /* Or create a new one */ else { ++meshCount; mesh = new Mesh; Buffer* buffer = new Buffer; Buffer* indexBuffer = new Buffer; meshes.insert(std::make_pair(object->instanceId(), std::make_tuple(buffer, indexBuffer, mesh))); MeshData3D* data = colladaImporter->mesh3D(object->instanceId()); if(!data || !data->isIndexed() || !data->positionArrayCount() || !data->normalArrayCount()) std::exit(6); vertexCount += data->positions(0).size(); triangleCount += data->indices().size()/3; /* Optimize vertices */ Debug() << "Optimizing vertices of mesh" << object->instanceId() << "using Tipsify algorithm (cache size 24)..."; MeshTools::tipsify(data->indices(), data->positions(0).size(), 24); /* Interleave mesh data */ MeshTools::interleave(mesh, buffer, Buffer::Usage::StaticDraw, data->positions(0), data->normals(0)); mesh->addInterleavedVertexBuffer(buffer, 0, Shaders::Phong::Position(), Shaders::Phong::Normal()); /* Compress indices */ MeshTools::compressIndices(mesh, indexBuffer, Buffer::Usage::StaticDraw, data->indices()); delete data; } /* Use already processed material, if exists */ PhongMaterialData* material; auto materialFound = materials.find(static_cast<MeshObjectData3D*>(object)->material()); if(materialFound != materials.end()) material = materialFound->second; /* Else get material or create default one */ else { ++materialCount; material = static_cast<PhongMaterialData*>(colladaImporter->material(static_cast<MeshObjectData3D*>(object)->material())); if(!material) { material = new PhongMaterialData({}, 50.0f); material->ambientColor() = {0.0f, 0.0f, 0.0f}; material->diffuseColor() = {0.9f, 0.9f, 0.9f}; material->specularColor() = {1.0f, 1.0f, 1.0f}; } } /* Add object */ Object3D* o = new ViewedObject(mesh, material, &shader, parent, &drawables); delete material; o->setTransformation(object->transformation()); } /* Recursively add children */ for(std::size_t id: object->children()) addObject(colladaImporter, o, materials, id); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::ViewerExample) <|endoftext|>
<commit_before>#include "cinder/app/AppNative.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/gl/VboMesh.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Context.h" #include "cinder/GeomIo.h" #include "cinder/Rand.h" #include "cinder/Log.h" #include "cinder/params/Params.h" #include "BlurrableThings.h" using namespace ci; using namespace ci::app; using namespace std; class MotionBlurVelocityBufferApp : public AppNative { public: void prepareSettings( Settings *settings ) override; void setup() override; void keyDown( KeyEvent event ) override; void update() override; void draw() override; void createGeometry(); void createBuffers(); void loadShaders(); void drawVelocityBuffers(); private: gl::TextureRef mBackground; std::vector<BlurrableMeshRef> mMeshes; gl::GlslProgRef mVelocityProg; // Renders screen-space velocity to RG channels. gl::GlslProgRef mTileProg; // Downsamples velocity, preserving local maxima gl::GlslProgRef mNeighborProg; // Finds dominant velocities in downsampled map gl::GlslProgRef mMotionBlurProg; // Generates final image from color and velocity buffers gl::GlslProgRef mVelocityRenderProg;// Debug rendering of velocity to screen. gl::FboRef mColorBuffer; // full-resolution RGBA color gl::FboRef mVelocityBuffer; // full-resolution velocity gl::FboRef mTileMaxBuffer; // downsampled velocity gl::FboRef mNeighborMaxBuffer; // dominant velocities in regions params::InterfaceGlRef mParams; int mTileSize = 20; int mSampleCount = 31; float mAnimationSpeed = 1.0f; float mBlurNoise = 0.0f; bool mBlurEnabled = true; bool mPaused = false; bool mDisplayVelocityBuffers = true; }; void MotionBlurVelocityBufferApp::prepareSettings( Settings *settings ) { settings->setWindowSize( 1280, 720 ); #if defined( CINDER_COCOA_TOUCH ) || defined( CINDER_COCOA_TOUCH_SIMULATOR ) getSignalSupportedOrientations().connect( [] { return InterfaceOrientation::LandscapeAll; } ); #endif // COCOA_TOUCH } void MotionBlurVelocityBufferApp::setup() { mBackground = gl::Texture::create( loadImage( loadAsset( "background.jpg" ) ) ); createGeometry(); createBuffers(); loadShaders(); mParams = params::InterfaceGl::create( "Motion Blur Options", ivec2( 250, 300 ) ); mParams->addParam( "Enable Blur", &mBlurEnabled ); mParams->addParam( "Show Velocity Buffers", &mDisplayVelocityBuffers ); mParams->addParam( "Pause Animation", &mPaused ); mParams->addParam( "Animation Speed", &mAnimationSpeed ).min( 0.05f ).step( 0.2f ); mParams->addParam( "Max Samples", &mSampleCount ).min( 1 ).step( 2 ); mParams->addParam( "Blur Noise", &mBlurNoise ).min( 0.0f ).step( 0.01f ); } void MotionBlurVelocityBufferApp::createGeometry() { for( int i = 0; i < 20; ++i ) { // create some randomized geometry vec3 pos = vec3( randFloat( 200.0f, getWindowWidth() - 200.0f ), randFloat( 150.0f, getWindowHeight() - 150.0f ), randFloat( -50.0f, 10.0f ) ); float base = randFloat( 50.0f, 100.0f ); float height = randFloat( 100.0f, 300.0f ); auto mesh = make_shared<BlurrableMesh>( gl::VboMesh::create( geom::Cone().height( height ).base( base ) ), pos ); mesh->setAxis( randVec3f() ); mesh->setColor( ColorA( CM_HSV, randFloat( 0.05f, 0.33f ), 1.0f, 1.0f ) ); mesh->setOscillation( vec3( randFloat( -150.0f, 150.0f ), randFloat( -300.0f, 300.0f ), randFloat( -500.0f, 200.0f ) ) ); mesh->setTheta( randFloat( M_PI * 2 ) ); mMeshes.push_back( mesh ); } } void MotionBlurVelocityBufferApp::createBuffers() { const int bufferWidth = getWindowWidth(); const int bufferHeight = getWindowHeight(); { // color gl::Fbo::Format format; format.colorTexture( gl::Texture::Format().internalFormat( GL_RGBA ) ); mColorBuffer = gl::Fbo::create( bufferWidth, bufferHeight, format ); } { // velocity gl::Fbo::Format format; format.colorTexture( gl::Texture::Format().internalFormat( GL_RG16F ) ); mVelocityBuffer = gl::Fbo::create( bufferWidth, bufferHeight, format ); } { // neighbor tile gl::Fbo::Format format; format.colorTexture( gl::Texture::Format().internalFormat( GL_RG16F ) ).disableDepth(); mTileMaxBuffer = gl::Fbo::create( bufferWidth / mTileSize, bufferHeight / mTileSize, format ); mNeighborMaxBuffer = gl::Fbo::create( bufferWidth / mTileSize, bufferHeight / mTileSize, format ); } } void MotionBlurVelocityBufferApp::loadShaders() { try { mVelocityProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "velocity.vs" ) ) .fragment( loadAsset( "velocity.fs" ) ) ); mMotionBlurProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "motion-blur.fs" ) ) ); mVelocityRenderProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "velocity-render.fs" ) ) ); mTileProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "tilemax.fs" ) ) ); mNeighborProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "neighbormax.fs" ) ) ); } catch( ci::gl::GlslProgCompileExc &exc ) { CI_LOG_E( "Shader load error: " << exc.what() ); } catch( ci::Exception &exc ) { CI_LOG_E( "Shader load error: " << exc.what() ); } } void MotionBlurVelocityBufferApp::keyDown( KeyEvent event ) { switch ( event.getCode() ) { case KeyEvent::KEY_SPACE: mPaused = ! mPaused; break; case KeyEvent::KEY_b: mBlurEnabled = ! mBlurEnabled; break; case KeyEvent::KEY_r: loadShaders(); break; default: break; } } void MotionBlurVelocityBufferApp::update() { if( ! mPaused ) { for( auto &mesh : mMeshes ) { mesh->update( mAnimationSpeed / 60.0f ); } } } void MotionBlurVelocityBufferApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::setMatricesWindowPersp( getWindowSize(), 60.0f, 1.0f, 5000.0f ); gl::draw( mBackground, getWindowBounds() ); gl::enableDepthRead(); gl::enableDepthWrite(); { // draw into color buffer gl::ScopedFramebuffer fbo( mColorBuffer ); gl::ScopedAlphaBlend blend( false ); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); for( auto &mesh : mMeshes ) { gl::ScopedModelMatrix model; gl::ScopedColor meshColor( mesh->getColor() ); gl::multModelMatrix( mesh->getTransform() ); gl::draw( mesh->getMesh() ); } } { // draw into velocity buffer gl::ScopedFramebuffer fbo( mVelocityBuffer ); gl::ScopedGlslProg prog( mVelocityProg ); gl::clear( Color::black() ); mVelocityProg->uniform( "uViewProjection", gl::getProjectionMatrix() * gl::getViewMatrix() ); for( auto &mesh : mMeshes ) { mVelocityProg->uniform( "uModelMatrix", mesh->getTransform() ); mVelocityProg->uniform( "uPrevModelMatrix", mesh->getPreviousTransform() ); gl::draw( mesh->getMesh() ); } } { // render velocity reconstruction buffers (dilation) gl::ScopedViewport viewport( ivec2( 0, 0 ), mTileMaxBuffer->getSize() ); gl::ScopedMatrices matrices; gl::setMatricesWindowPersp( mTileMaxBuffer->getSize() ); { // downsample velocity into tilemax gl::ScopedTextureBind tex( mVelocityBuffer->getColorTexture(), (GLuint)0 ); gl::ScopedGlslProg prog( mTileProg ); gl::ScopedFramebuffer fbo( mTileMaxBuffer ); mTileProg->uniform( "uVelocityMap", 0 ); mTileProg->uniform( "uTileSize", mTileSize ); gl::clear( Color::black() ); gl::drawSolidRect( mTileMaxBuffer->getBounds() ); } { // find max neighbors within tilemax gl::ScopedTextureBind tex( mTileMaxBuffer->getColorTexture(), (GLuint)0 ); gl::ScopedGlslProg prog( mNeighborProg ); gl::ScopedFramebuffer fbo( mNeighborMaxBuffer ); mNeighborProg->uniform( "uTileMap", 0 ); gl::clear( Color::white() ); gl::drawSolidRect( mNeighborMaxBuffer->getBounds() ); } } gl::disableDepthRead(); gl::disableDepthWrite(); if( ! mBlurEnabled ) { // draw to screen gl::ScopedAlphaBlend blend( false ); gl::draw( mColorBuffer->getColorTexture() ); } else { // draw to screen with motion blur gl::ScopedAlphaBlend blend( true ); gl::ScopedTextureBind colorTex( mColorBuffer->getColorTexture(), (GLuint)0 ); gl::ScopedTextureBind velTex( mVelocityBuffer->getColorTexture(), (GLuint)1 ); gl::ScopedTextureBind neigborTex( mNeighborMaxBuffer->getColorTexture(), (GLuint)2 ); gl::ScopedGlslProg prog( mMotionBlurProg ); mMotionBlurProg->uniform( "uColorMap", 0 ); mMotionBlurProg->uniform( "uVelocityMap", 1 ); mMotionBlurProg->uniform( "uNeighborMaxMap", 2 ); mMotionBlurProg->uniform( "uNoiseFactor", mBlurNoise ); mMotionBlurProg->uniform( "uSamples", mSampleCount ); gl::drawSolidRect( getWindowBounds() ); } if( mDisplayVelocityBuffers ) { drawVelocityBuffers(); } mParams->draw(); } void MotionBlurVelocityBufferApp::drawVelocityBuffers() { gl::ScopedGlslProg prog( mVelocityRenderProg ); gl::ScopedModelMatrix matrix; gl::setDefaultShaderVars(); float width = 200.0f; float height = width / Rectf( mNeighborMaxBuffer->getBounds() ).getAspectRatio(); Rectf rect( 0.0f, 0.0f, width, height ); gl::ScopedTextureBind velTex( mVelocityBuffer->getColorTexture(), (GLuint)0 ); gl::translate( getWindowWidth() - width - 10.0f, 10.0f ); gl::drawSolidRect( rect ); gl::ScopedTextureBind tileTex( mTileMaxBuffer->getColorTexture(), (GLuint)0 ); gl::translate( 0.0f, height + 10.0f ); gl::drawSolidRect( rect ); gl::ScopedTextureBind neigborTex( mNeighborMaxBuffer->getColorTexture(), (GLuint)0 ); gl::translate( 0.0f, height + 10.0f ); gl::drawSolidRect( rect ); } CINDER_APP_NATIVE( MotionBlurVelocityBufferApp, RendererGl( RendererGl::Options().antiAliasing( RendererGl::AA_NONE ) ) ) <commit_msg>Motion Blur tested with VS 2013<commit_after>#include "cinder/app/AppNative.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/gl/Texture.h" #include "cinder/gl/VboMesh.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Context.h" #include "cinder/GeomIo.h" #include "cinder/Rand.h" #include "cinder/Log.h" #include "cinder/params/Params.h" #include "BlurrableThings.h" using namespace ci; using namespace ci::app; using namespace std; class MotionBlurVelocityBufferApp : public AppNative { public: void prepareSettings( Settings *settings ) override; void setup() override; void keyDown( KeyEvent event ) override; void update() override; void draw() override; void createGeometry(); void createBuffers(); void loadShaders(); void drawVelocityBuffers(); private: gl::TextureRef mBackground; std::vector<BlurrableMeshRef> mMeshes; gl::GlslProgRef mVelocityProg; // Renders screen-space velocity to RG channels. gl::GlslProgRef mTileProg; // Downsamples velocity, preserving local maxima gl::GlslProgRef mNeighborProg; // Finds dominant velocities in downsampled map gl::GlslProgRef mMotionBlurProg; // Generates final image from color and velocity buffers gl::GlslProgRef mVelocityRenderProg;// Debug rendering of velocity to screen. gl::FboRef mColorBuffer; // full-resolution RGBA color gl::FboRef mVelocityBuffer; // full-resolution velocity gl::FboRef mTileMaxBuffer; // downsampled velocity gl::FboRef mNeighborMaxBuffer; // dominant velocities in regions params::InterfaceGlRef mParams; int mTileSize = 20; int mSampleCount = 31; float mAnimationSpeed = 1.0f; float mBlurNoise = 0.0f; bool mBlurEnabled = true; bool mPaused = false; bool mDisplayVelocityBuffers = true; }; void MotionBlurVelocityBufferApp::prepareSettings( Settings *settings ) { settings->setWindowSize( 1280, 720 ); #if defined( CINDER_COCOA_TOUCH ) || defined( CINDER_COCOA_TOUCH_SIMULATOR ) getSignalSupportedOrientations().connect( [] { return InterfaceOrientation::LandscapeAll; } ); #endif // COCOA_TOUCH } void MotionBlurVelocityBufferApp::setup() { mBackground = gl::Texture::create( loadImage( loadAsset( "background.jpg" ) ) ); createGeometry(); createBuffers(); loadShaders(); mParams = params::InterfaceGl::create( "Motion Blur Options", ivec2( 250, 300 ) ); mParams->addParam( "Enable Blur", &mBlurEnabled ); mParams->addParam( "Show Velocity Buffers", &mDisplayVelocityBuffers ); mParams->addParam( "Pause Animation", &mPaused ); mParams->addParam( "Animation Speed", &mAnimationSpeed ).min( 0.05f ).step( 0.2f ); mParams->addParam( "Max Samples", &mSampleCount ).min( 1 ).step( 2 ); mParams->addParam( "Blur Noise", &mBlurNoise ).min( 0.0f ).step( 0.01f ); } void MotionBlurVelocityBufferApp::createGeometry() { for( int i = 0; i < 20; ++i ) { // create some randomized geometry vec3 pos = vec3( randFloat( 200.0f, getWindowWidth() - 200.0f ), randFloat( 150.0f, getWindowHeight() - 150.0f ), randFloat( -50.0f, 10.0f ) ); float base = randFloat( 50.0f, 100.0f ); float height = randFloat( 100.0f, 300.0f ); auto mesh = make_shared<BlurrableMesh>( gl::VboMesh::create( geom::Cone().height( height ).base( base ) ), pos ); mesh->setAxis( randVec3f() ); mesh->setColor( ColorA( CM_HSV, randFloat( 0.05f, 0.33f ), 1.0f, 1.0f ) ); mesh->setOscillation( vec3( randFloat( -150.0f, 150.0f ), randFloat( -300.0f, 300.0f ), randFloat( -500.0f, 200.0f ) ) ); mesh->setTheta( randFloat( M_PI * 2 ) ); mMeshes.push_back( mesh ); } } void MotionBlurVelocityBufferApp::createBuffers() { const int bufferWidth = getWindowWidth(); const int bufferHeight = getWindowHeight(); { // color gl::Fbo::Format format; format.colorTexture( gl::Texture::Format().internalFormat( GL_RGBA ) ); mColorBuffer = gl::Fbo::create( bufferWidth, bufferHeight, format ); } { // velocity gl::Fbo::Format format; format.colorTexture( gl::Texture::Format().internalFormat( GL_RG16F ) ); mVelocityBuffer = gl::Fbo::create( bufferWidth, bufferHeight, format ); } { // neighbor tile gl::Fbo::Format format; format.colorTexture( gl::Texture::Format().internalFormat( GL_RG16F ) ).disableDepth(); mTileMaxBuffer = gl::Fbo::create( bufferWidth / mTileSize, bufferHeight / mTileSize, format ); mNeighborMaxBuffer = gl::Fbo::create( bufferWidth / mTileSize, bufferHeight / mTileSize, format ); } } void MotionBlurVelocityBufferApp::loadShaders() { try { mVelocityProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "velocity.vs" ) ) .fragment( loadAsset( "velocity.fs" ) ) ); mMotionBlurProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "motion-blur.fs" ) ) ); mVelocityRenderProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "velocity-render.fs" ) ) ); mTileProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "tilemax.fs" ) ) ); mNeighborProg = gl::GlslProg::create( gl::GlslProg::Format().vertex( loadAsset( "passthrough.vs" ) ) .fragment( loadAsset( "neighbormax.fs" ) ) ); } catch( ci::gl::GlslProgCompileExc &exc ) { CI_LOG_E( "Shader load error: " << exc.what() ); } catch( ci::Exception &exc ) { CI_LOG_E( "Shader load error: " << exc.what() ); } } void MotionBlurVelocityBufferApp::keyDown( KeyEvent event ) { switch ( event.getCode() ) { case KeyEvent::KEY_SPACE: mPaused = ! mPaused; break; case KeyEvent::KEY_b: mBlurEnabled = ! mBlurEnabled; break; case KeyEvent::KEY_r: loadShaders(); break; default: break; } } void MotionBlurVelocityBufferApp::update() { if( ! mPaused ) { for( auto &mesh : mMeshes ) { mesh->update( mAnimationSpeed / 60.0f ); } } } void MotionBlurVelocityBufferApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::setMatricesWindowPersp( getWindowSize(), 60.0f, 1.0f, 5000.0f ); gl::draw( mBackground, getWindowBounds() ); gl::enableDepthRead(); gl::enableDepthWrite(); { // draw into color buffer gl::ScopedFramebuffer fbo( mColorBuffer ); gl::ScopedAlphaBlend blend( false ); gl::clear( ColorA( 0.0f, 0.0f, 0.0f, 0.0f ) ); for( auto &mesh : mMeshes ) { gl::ScopedModelMatrix model; gl::ScopedColor meshColor( mesh->getColor() ); gl::multModelMatrix( mesh->getTransform() ); gl::draw( mesh->getMesh() ); } } { // draw into velocity buffer gl::ScopedFramebuffer fbo( mVelocityBuffer ); gl::ScopedGlslProg prog( mVelocityProg ); gl::clear( Color::black() ); mVelocityProg->uniform( "uViewProjection", gl::getProjectionMatrix() * gl::getViewMatrix() ); for( auto &mesh : mMeshes ) { mVelocityProg->uniform( "uModelMatrix", mesh->getTransform() ); mVelocityProg->uniform( "uPrevModelMatrix", mesh->getPreviousTransform() ); gl::draw( mesh->getMesh() ); } } { // render velocity reconstruction buffers (dilation) gl::ScopedViewport viewport( ivec2( 0, 0 ), mTileMaxBuffer->getSize() ); gl::ScopedMatrices matrices; gl::setMatricesWindowPersp( mTileMaxBuffer->getSize() ); { // downsample velocity into tilemax gl::ScopedTextureBind tex( mVelocityBuffer->getColorTexture(), (std::uint8_t)0 ); gl::ScopedGlslProg prog( mTileProg ); gl::ScopedFramebuffer fbo( mTileMaxBuffer ); mTileProg->uniform( "uVelocityMap", 0 ); mTileProg->uniform( "uTileSize", mTileSize ); gl::clear( Color::black() ); gl::drawSolidRect( mTileMaxBuffer->getBounds() ); } { // find max neighbors within tilemax gl::ScopedTextureBind tex( mTileMaxBuffer->getColorTexture(), (std::uint8_t)0 ); gl::ScopedGlslProg prog( mNeighborProg ); gl::ScopedFramebuffer fbo( mNeighborMaxBuffer ); mNeighborProg->uniform( "uTileMap", 0 ); gl::clear( Color::white() ); gl::drawSolidRect( mNeighborMaxBuffer->getBounds() ); } } gl::disableDepthRead(); gl::disableDepthWrite(); if( ! mBlurEnabled ) { // draw to screen gl::ScopedAlphaBlend blend( false ); gl::draw( mColorBuffer->getColorTexture() ); } else { // draw to screen with motion blur gl::ScopedAlphaBlend blend( true ); gl::ScopedTextureBind colorTex( mColorBuffer->getColorTexture(), (std::uint8_t)0 ); gl::ScopedTextureBind velTex( mVelocityBuffer->getColorTexture(), (std::uint8_t)1 ); gl::ScopedTextureBind neigborTex( mNeighborMaxBuffer->getColorTexture(), (std::uint8_t)2 ); gl::ScopedGlslProg prog( mMotionBlurProg ); mMotionBlurProg->uniform( "uColorMap", 0 ); mMotionBlurProg->uniform( "uVelocityMap", 1 ); mMotionBlurProg->uniform( "uNeighborMaxMap", 2 ); mMotionBlurProg->uniform( "uNoiseFactor", mBlurNoise ); mMotionBlurProg->uniform( "uSamples", mSampleCount ); gl::drawSolidRect( getWindowBounds() ); } if( mDisplayVelocityBuffers ) { drawVelocityBuffers(); } mParams->draw(); } void MotionBlurVelocityBufferApp::drawVelocityBuffers() { gl::ScopedGlslProg prog( mVelocityRenderProg ); gl::ScopedModelMatrix matrix; gl::setDefaultShaderVars(); float width = 200.0f; float height = width / Rectf( mNeighborMaxBuffer->getBounds() ).getAspectRatio(); Rectf rect( 0.0f, 0.0f, width, height ); gl::ScopedTextureBind velTex( mVelocityBuffer->getColorTexture(), (std::uint8_t)0 ); gl::translate( getWindowWidth() - width - 10.0f, 10.0f ); gl::drawSolidRect( rect ); gl::ScopedTextureBind tileTex( mTileMaxBuffer->getColorTexture(), (std::uint8_t)0 ); gl::translate( 0.0f, height + 10.0f ); gl::drawSolidRect( rect ); gl::ScopedTextureBind neigborTex( mNeighborMaxBuffer->getColorTexture(), (std::uint8_t)0 ); gl::translate( 0.0f, height + 10.0f ); gl::drawSolidRect( rect ); } CINDER_APP_NATIVE( MotionBlurVelocityBufferApp, RendererGl( RendererGl::Options().antiAliasing( RendererGl::AA_NONE ) ) ) <|endoftext|>
<commit_before>#include "vlc_video_source.h" #include <cstdio> #include <cstdlib> #include <chrono> #include <thread> namespace gg { VideoSourceVLC::VideoSourceVLC(const std::string path) : _vlc_inst(nullptr) , _vlc_mp(nullptr) , _video_buffer(nullptr) , _data_length(0) , _cols(0) , _rows(0) , _sub(nullptr) , _path(path) { this->init_vlc(); this->run_vlc(); } VideoSourceVLC::~VideoSourceVLC() { stop_vlc(); release_vlc(); } bool VideoSourceVLC::get_frame_dimensions(int & width, int & height) { ///\todo mutex if(this->_cols == 0 || this->_rows == 0) return false; width = this->_cols; height = this->_rows; return true; } bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame) { throw VideoSourceError("VLC video source supports only I420 colour space"); // TODO ///\todo mutex if (_cols == 0 || _rows == 0 || _video_buffer == nullptr) return false; // allocate and fill the image if (_cols * _rows * 4 == this->_data_length) frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows); else throw VideoSourceError("VLC video source does not support padded images"); return true; } bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame) { if (_data_length > 0) { // TODO manage data? frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false); return true; } else return false; // TODO #86 } double VideoSourceVLC::get_frame_rate() { //return libvlc_media_player_get_rate( m_mp ); return libvlc_media_player_get_fps(_vlc_mp); //throw std::runtime_error("get_frame_rate to be implemented"); //return 0.0; } void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height) { // TODO mutex? if (x >= _full.x and x + width <= _full.x + _full.width and y >= _full.y and y + height <= _full.y + _full.height) { stop_vlc(); release_vlc(); if (_sub == nullptr) _sub = new FrameBox; _sub->x = x; _sub->y = y; _sub->width = width; _sub->height = height; init_vlc(); run_vlc(); } } void VideoSourceVLC::get_full_frame() { // TODO mutex? stop_vlc(); release_vlc(); if (_sub) { delete _sub; _sub = nullptr; } init_vlc(); run_vlc(); } void VideoSourceVLC::init_vlc() { // VLC pointers libvlc_media_t * vlc_media = nullptr; // VLC options char smem_options[512]; sprintf(smem_options, "#"); if (_sub != nullptr) { unsigned int croptop = _sub->y, cropbottom = _full.height - (_sub->y + _sub->height), cropleft = _sub->x, cropright = _full.width - (_sub->x + _sub->width); sprintf(smem_options, "%stranscode{vcodec=I420,vfilter=croppadd{", smem_options); sprintf(smem_options, "%scroptop=%d,cropbottom=%d,cropleft=%d,cropright=%d}}:", smem_options, croptop, cropbottom, cropleft, cropright); // TODO %d OK? } sprintf(smem_options, "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}", smem_options, (long long int)(intptr_t)(void*) this, (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender, (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream ); const char * const vlc_args[] = { "-I", "dummy", // Don't use any interface "--ignore-config", // Don't use VLC's config "--extraintf=logger", // Log anything // TODO - what about the options below? //"--verbose=2", // Be much more verbose then normal for debugging purpose //"--clock-jitter=0", //"--file-caching=150", "--no-audio", "--sout", smem_options // Stream to memory }; // We launch VLC _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (_vlc_inst == nullptr) throw VideoSourceError("Could not create VLC engine"); // If path contains a colon (:), it will be treated as a // URL. Else, it will be considered as a local path. if (std::string(path).find(":") == std::string::npos) vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str()); else vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str()); if (vlc_media == nullptr) throw VideoSourceError(std::string("Could not open ").append(path)); libvlc_media_add_option(vlc_media, ":noaudio"); libvlc_media_add_option(vlc_media, ":no-video-title-show"); // Create a media player playing environement _vlc_mp = libvlc_media_player_new_from_media(vlc_media); if (_vlc_mp == nullptr) throw VideoSourceError("Could create VLC media player"); // No need to keep the media now libvlc_media_release( vlc_media ); } void VideoSourceVLC::run_vlc() { // play the media_player if (libvlc_media_player_play(_vlc_mp) != 0) throw VideoSourceError("Could not start VLC media player"); // empirically determined value that allows for initialisation // to succeed before any API functions are called on this object std::this_thread::sleep_for(std::chrono::milliseconds(350)); unsigned int width, height; if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0) throw VideoSourceError("Could not get video dimensions"); _full.x = 0; _full.y = 0; _full.width = width; _full.height = height; } void VideoSourceVLC::stop_vlc() { if (libvlc_media_player_is_playing(_vlc_mp) == 1) // stop playing libvlc_media_player_stop(_vlc_mp); } void VideoSourceVLC::release_vlc() { // free media player if (_vlc_mp) libvlc_media_player_release(_vlc_mp); // free engine if (_vlc_inst) libvlc_release(_vlc_inst); // free buffer if (_video_buffer != nullptr) delete[] _video_buffer; } void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data, uint8_t ** pp_pixel_buffer, size_t size) { ///\todo create mutex guard if (size != p_video_data->_data_length) { unsigned int width,height; if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0) return; // TODO deallocate previous data? p_video_data->_video_buffer = new uint8_t[size]; p_video_data->_data_length = size; p_video_data->_cols = width; p_video_data->_rows = height; } *pp_pixel_buffer = p_video_data->_video_buffer; } void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data, uint8_t * p_pixel_buffer, size_t cols, size_t rows, size_t colour_depth, size_t size) { // TODO: explain how data should be handled (see #86) p_video_data->_cols = cols; p_video_data->_rows = rows; p_video_data->_video_buffer = p_pixel_buffer; p_video_data->_data_length = size; // TODO: Unlock the mutex } std::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height) { std::string psz_geometry; psz_geometry.append(std::to_string(width)).append("x") .append(std::to_string(height)) .append("+").append(std::to_string(x)) .append("+").append(std::to_string(y)); return psz_geometry; } } <commit_msg>Issue #83: fixed errors due to change of variable name from path to (member variable) _path<commit_after>#include "vlc_video_source.h" #include <cstdio> #include <cstdlib> #include <chrono> #include <thread> namespace gg { VideoSourceVLC::VideoSourceVLC(const std::string path) : _vlc_inst(nullptr) , _vlc_mp(nullptr) , _video_buffer(nullptr) , _data_length(0) , _cols(0) , _rows(0) , _sub(nullptr) , _path(path) { this->init_vlc(); this->run_vlc(); } VideoSourceVLC::~VideoSourceVLC() { stop_vlc(); release_vlc(); } bool VideoSourceVLC::get_frame_dimensions(int & width, int & height) { ///\todo mutex if(this->_cols == 0 || this->_rows == 0) return false; width = this->_cols; height = this->_rows; return true; } bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame) { throw VideoSourceError("VLC video source supports only I420 colour space"); // TODO ///\todo mutex if (_cols == 0 || _rows == 0 || _video_buffer == nullptr) return false; // allocate and fill the image if (_cols * _rows * 4 == this->_data_length) frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows); else throw VideoSourceError("VLC video source does not support padded images"); return true; } bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame) { if (_data_length > 0) { // TODO manage data? frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false); return true; } else return false; // TODO #86 } double VideoSourceVLC::get_frame_rate() { //return libvlc_media_player_get_rate( m_mp ); return libvlc_media_player_get_fps(_vlc_mp); //throw std::runtime_error("get_frame_rate to be implemented"); //return 0.0; } void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height) { // TODO mutex? if (x >= _full.x and x + width <= _full.x + _full.width and y >= _full.y and y + height <= _full.y + _full.height) { stop_vlc(); release_vlc(); if (_sub == nullptr) _sub = new FrameBox; _sub->x = x; _sub->y = y; _sub->width = width; _sub->height = height; init_vlc(); run_vlc(); } } void VideoSourceVLC::get_full_frame() { // TODO mutex? stop_vlc(); release_vlc(); if (_sub) { delete _sub; _sub = nullptr; } init_vlc(); run_vlc(); } void VideoSourceVLC::init_vlc() { // VLC pointers libvlc_media_t * vlc_media = nullptr; // VLC options char smem_options[512]; sprintf(smem_options, "#"); if (_sub != nullptr) { unsigned int croptop = _sub->y, cropbottom = _full.height - (_sub->y + _sub->height), cropleft = _sub->x, cropright = _full.width - (_sub->x + _sub->width); sprintf(smem_options, "%stranscode{vcodec=I420,vfilter=croppadd{", smem_options); sprintf(smem_options, "%scroptop=%d,cropbottom=%d,cropleft=%d,cropright=%d}}:", smem_options, croptop, cropbottom, cropleft, cropright); // TODO %d OK? } sprintf(smem_options, "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}", smem_options, (long long int)(intptr_t)(void*) this, (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender, (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream ); const char * const vlc_args[] = { "-I", "dummy", // Don't use any interface "--ignore-config", // Don't use VLC's config "--extraintf=logger", // Log anything // TODO - what about the options below? //"--verbose=2", // Be much more verbose then normal for debugging purpose //"--clock-jitter=0", //"--file-caching=150", "--no-audio", "--sout", smem_options // Stream to memory }; // We launch VLC _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (_vlc_inst == nullptr) throw VideoSourceError("Could not create VLC engine"); // If path contains a colon (:), it will be treated as a // URL. Else, it will be considered as a local path. if (_path.find(":") == std::string::npos) vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str()); else vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str()); if (vlc_media == nullptr) throw VideoSourceError(std::string("Could not open ").append(_path)); libvlc_media_add_option(vlc_media, ":noaudio"); libvlc_media_add_option(vlc_media, ":no-video-title-show"); // Create a media player playing environement _vlc_mp = libvlc_media_player_new_from_media(vlc_media); if (_vlc_mp == nullptr) throw VideoSourceError("Could create VLC media player"); // No need to keep the media now libvlc_media_release( vlc_media ); } void VideoSourceVLC::run_vlc() { // play the media_player if (libvlc_media_player_play(_vlc_mp) != 0) throw VideoSourceError("Could not start VLC media player"); // empirically determined value that allows for initialisation // to succeed before any API functions are called on this object std::this_thread::sleep_for(std::chrono::milliseconds(350)); unsigned int width, height; if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0) throw VideoSourceError("Could not get video dimensions"); _full.x = 0; _full.y = 0; _full.width = width; _full.height = height; } void VideoSourceVLC::stop_vlc() { if (libvlc_media_player_is_playing(_vlc_mp) == 1) // stop playing libvlc_media_player_stop(_vlc_mp); } void VideoSourceVLC::release_vlc() { // free media player if (_vlc_mp) libvlc_media_player_release(_vlc_mp); // free engine if (_vlc_inst) libvlc_release(_vlc_inst); // free buffer if (_video_buffer != nullptr) delete[] _video_buffer; } void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data, uint8_t ** pp_pixel_buffer, size_t size) { ///\todo create mutex guard if (size != p_video_data->_data_length) { unsigned int width,height; if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0) return; // TODO deallocate previous data? p_video_data->_video_buffer = new uint8_t[size]; p_video_data->_data_length = size; p_video_data->_cols = width; p_video_data->_rows = height; } *pp_pixel_buffer = p_video_data->_video_buffer; } void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data, uint8_t * p_pixel_buffer, size_t cols, size_t rows, size_t colour_depth, size_t size) { // TODO: explain how data should be handled (see #86) p_video_data->_cols = cols; p_video_data->_rows = rows; p_video_data->_video_buffer = p_pixel_buffer; p_video_data->_data_length = size; // TODO: Unlock the mutex } std::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height) { std::string psz_geometry; psz_geometry.append(std::to_string(width)).append("x") .append(std::to_string(height)) .append("+").append(std::to_string(x)) .append("+").append(std::to_string(y)); return psz_geometry; } } <|endoftext|>
<commit_before>#include "proxyparser.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <Winhttp.h> #include <Ws2tcpip.h> #include <Winsock2.h> #include <iostream> #include <sstream> bool ProxyParser::getProxySettingForUrl(string url, ProxySetting & proxy) { WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig; WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions; WINHTTP_PROXY_INFO autoProxyInfo; BOOL autoProxy = FALSE; bool result = false; memset(&ieProxyConfig,0,sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG)); memset(&autoProxyOptions,0,sizeof(WINHTTP_AUTOPROXY_OPTIONS)); memset(&autoProxyInfo,0,sizeof(WINHTTP_PROXY_INFO)); if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) ){ if( ieProxyConfig.fAutoDetect ){ // WPAD autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoProxyOptions.fAutoLogonIfChallenged = TRUE; autoProxy = TRUE; cout << "proxy configured with WPAD" << endl; } else if( ieProxyConfig.lpszAutoConfigUrl != NULL ){ // Normal PAC file autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl; autoProxy = TRUE; wcout << L"download PAC file from: " << ieProxyConfig.lpszAutoConfigUrl << endl; } else if ( ieProxyConfig.lpszProxy != NULL ){ autoProxy = FALSE; wcout << L"hardcoded proxy address: " << ieProxyConfig.lpszProxy << endl; if(ieProxyConfig.lpszProxyBypass != NULL) wcout << L"proxy bypass list: " << ieProxyConfig.lpszProxyBypass << endl; else wcout << L"proxy bypass list: NONE" << endl; } } if(autoProxy) { cout << "testing proxy autoconfiguration for this URL: " << url << endl; std::wstring wUrl(url.begin() , url.end()); HINTERNET session = WinHttpOpen(0, // no agent string WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); autoProxy = WinHttpGetProxyForUrl( session, wUrl.c_str(), &autoProxyOptions, &autoProxyInfo ); if (!autoProxy) cout << "WinHttpGetProxyForUrl failed with error: " << GetLastError() << endl; else { if (NULL != autoProxyInfo.lpszProxy) { wcout << L"got proxy list: " << autoProxyInfo.lpszProxy << endl; wstring wproxyList(autoProxyInfo.lpszProxy); string proxyList(wproxyList.begin(), wproxyList.end()); if(proxyList.empty()) result = false; else { getProxySettingForProtocolFromProxyList("http", proxyList, proxy); result = true; } GlobalFree(autoProxyInfo.lpszProxy); if(NULL != autoProxyInfo.lpszProxyBypass) { wcout << L"and proxy bypass list: " << autoProxyInfo.lpszProxyBypass << endl; GlobalFree(autoProxyInfo.lpszProxyBypass); } return result; } } } else { result = getStaticProxySettingForUrl(url, ieProxyConfig.lpszProxy, ieProxyConfig.lpszProxyBypass, proxy); } if(ieProxyConfig.lpszAutoConfigUrl != NULL) GlobalFree( ieProxyConfig.lpszAutoConfigUrl ); if(ieProxyConfig.lpszProxy != NULL) GlobalFree( ieProxyConfig.lpszProxy ); if(ieProxyConfig.lpszProxyBypass != NULL) GlobalFree( ieProxyConfig.lpszProxyBypass ); return result; } void ProxyParser::getProxySettingForProtocolFromProxyList(string protocol, string proxyList, ProxySetting & proxy) { size_t token, precedent_token = 0; token = proxyList.find(";"); do { string proxyItem = proxyList.substr(precedent_token, token-precedent_token); getProxySettingForProxyListItem(proxyItem, proxy); cout << "found proxy setting wioth protocol: " << proxy.protocol << endl; if(proxy.protocol== protocol || proxy.protocol == "all") break; precedent_token = token+1; token = proxyList.find(";", precedent_token);//can be separated by whitespace too? }while(token != string::npos); } void ProxyParser::getProxySettingForProxyListItem(string proxyItem, ProxySetting & proxy) { //proxy item strings: ([<scheme>=][<scheme>"://"]<server>[":"<port>]) size_t proxyToken = proxyItem.find("="); if(proxyToken != string::npos) proxy.protocol = proxyItem.substr(0, proxyToken); else proxy.protocol = "all"; proxyItem = proxyItem.erase(0, proxyToken+1); cout << "remaining proxy item: " <<proxyItem << endl; proxyToken = proxyItem.find("/"); if(proxyToken != string::npos) proxyItem = proxyItem.erase(0, proxyToken+2); proxyToken = proxyItem.find(":"); proxy.domain = proxyItem.substr(0, proxyToken); stringstream s(proxyItem.substr(proxyToken+1, string::npos)); s >> proxy.port; } bool ProxyParser::getStaticProxySettingForUrl(string url, wstring wproxylist, wstring proxybypass, ProxySetting & proxy) { URL_COMPONENTS components = {0}; components.dwStructSize = sizeof(URL_COMPONENTS); wchar_t scheme[20] = {0}; wchar_t domain[MAX_PATH] = {0}; components.lpszScheme = scheme; components.dwSchemeLength = 20; components.lpszHostName = domain; components.dwHostNameLength = MAX_PATH; wstring wurl(url.begin(), url.end()); WinHttpCrackUrl( wurl.c_str(), (DWORD)wurl.length(), 0, &components); wstring whost(domain); string host(whost.begin(), whost.end()); //FIXME if(!testHostForBypassList(host, proxybypass)) { string proxylist(wproxylist.begin(), wproxylist.end()); wstring wscheme(scheme); string protocol(wscheme.begin(), wscheme.end()); getProxySettingForProtocolFromProxyList(protocol, proxylist, proxy); return true; } else return false; } bool ProxyParser::testHostForBypassList(string host, wstring wproxybypass) { string proxybypass(wproxybypass.begin(), wproxybypass.end()); size_t token, precedent_token = 0; token = proxybypass.find(";"); while(token != string::npos) { string bypass = proxybypass.substr(precedent_token, token-precedent_token); if(testHostForBypass(host, bypass)) return true; precedent_token = token+1; token = proxybypass.find(";", precedent_token); } string bypass = proxybypass.substr(precedent_token, token); return testHostForBypass(host, bypass); } bool ProxyParser::testHostForBypass(string host, string bypass) { cout << "testing domain \"" << host << "\" for bypass: " << bypass << " "; if(isDomain(host)) { bool result = testDomainForBypass(host, bypass); if(result) { cout << " => MATCH" << endl; return true; } else { cout << " => NO MATCH" << endl; return false; } } return false; } bool ProxyParser::testDomainForBypass(string domain, string bypass) { if(isDomain(bypass)) { if(domain == bypass) return true; if(bypass.at(0) == '*') { string suffix = bypass.substr(1, string::npos); size_t found = domain.rfind(suffix); return(found+suffix.length() == domain.length());//the suffix is the end of the domain } if(bypass == "<local>" && domain.find('.') == string::npos) return true; } else { vector<string> ips = getIPForHost(domain); vector<string>::iterator ipIt; for(ipIt = ips.begin(); ipIt != ips.end(); ipIt++) { string ip = *ipIt; if(testIpForBypass(ip, bypass)) return true; } } return false; } bool ProxyParser::testIpForBypass(string ip, string bypass) { if(!isDomain(bypass)) { if(ip == bypass) return true; //special case for IP like 172.16* if(bypass.at(bypass.size()-1) == '*') { if(ip.substr(0, bypass.size()-1) == bypass.substr(0, bypass.size()-1)) return true; } size_t token, iptoken, precedent_token = 0, precedent_iptoken = 0; token = bypass.find("."); iptoken = ip.find("."); while(token != string::npos) { string bypassnum = bypass.substr(precedent_token, token-precedent_token); string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken); if(!(bypassnum == ipnum || bypassnum == "*")) return false; precedent_token = token+1; precedent_iptoken = iptoken+1; token = bypass.find(".", precedent_token); iptoken = ip.find(".", precedent_iptoken); } string bypassnum = bypass.substr(precedent_token, token-precedent_token); string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken); if(bypassnum == ipnum || bypassnum == "*") return true; } return false; } vector<string> ProxyParser::getIPForHost(string host) { vector<string> ips; WSADATA wsaData; int res = WSAStartup(MAKEWORD(2, 2), &wsaData); if(res != 0) return ips; struct addrinfo * result; res = getaddrinfo(host.c_str(), NULL, NULL, &result); if(res == 0) { struct addrinfo * current = result; do{ struct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) current->ai_addr; string ip = inet_ntoa(sockaddr_ipv4->sin_addr); ips.push_back(ip); current = current->ai_next; }while(current != NULL); freeaddrinfo(result); } WSACleanup(); return ips; } bool ProxyParser::isDomain(string host) { return (isalpha(host.at(0)) || (host.at(0) == '*' && host.at(1) == '.' && isalpha(host.at(2))) || host == "<local>"); } <commit_msg>don't forget test matches beteen an IP and the bypass list<commit_after>#include "proxyparser.h" #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <Winhttp.h> #include <Ws2tcpip.h> #include <Winsock2.h> #include <iostream> #include <sstream> bool ProxyParser::getProxySettingForUrl(string url, ProxySetting & proxy) { WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig; WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions; WINHTTP_PROXY_INFO autoProxyInfo; BOOL autoProxy = FALSE; bool result = false; memset(&ieProxyConfig,0,sizeof(WINHTTP_CURRENT_USER_IE_PROXY_CONFIG)); memset(&autoProxyOptions,0,sizeof(WINHTTP_AUTOPROXY_OPTIONS)); memset(&autoProxyInfo,0,sizeof(WINHTTP_PROXY_INFO)); if( WinHttpGetIEProxyConfigForCurrentUser( &ieProxyConfig ) ){ if( ieProxyConfig.fAutoDetect ){ // WPAD autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT; autoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A; autoProxyOptions.fAutoLogonIfChallenged = TRUE; autoProxy = TRUE; cout << "proxy configured with WPAD" << endl; } else if( ieProxyConfig.lpszAutoConfigUrl != NULL ){ // Normal PAC file autoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL; autoProxyOptions.lpszAutoConfigUrl = ieProxyConfig.lpszAutoConfigUrl; autoProxy = TRUE; wcout << L"download PAC file from: " << ieProxyConfig.lpszAutoConfigUrl << endl; } else if ( ieProxyConfig.lpszProxy != NULL ){ autoProxy = FALSE; wcout << L"hardcoded proxy address: " << ieProxyConfig.lpszProxy << endl; if(ieProxyConfig.lpszProxyBypass != NULL) wcout << L"proxy bypass list: " << ieProxyConfig.lpszProxyBypass << endl; else wcout << L"proxy bypass list: NONE" << endl; } } if(autoProxy) { cout << "testing proxy autoconfiguration for this URL: " << url << endl; std::wstring wUrl(url.begin() , url.end()); HINTERNET session = WinHttpOpen(0, // no agent string WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); autoProxy = WinHttpGetProxyForUrl( session, wUrl.c_str(), &autoProxyOptions, &autoProxyInfo ); if (!autoProxy) cout << "WinHttpGetProxyForUrl failed with error: " << GetLastError() << endl; else { if (NULL != autoProxyInfo.lpszProxy) { wcout << L"got proxy list: " << autoProxyInfo.lpszProxy << endl; wstring wproxyList(autoProxyInfo.lpszProxy); string proxyList(wproxyList.begin(), wproxyList.end()); if(proxyList.empty()) result = false; else { getProxySettingForProtocolFromProxyList("http", proxyList, proxy); result = true; } GlobalFree(autoProxyInfo.lpszProxy); if(NULL != autoProxyInfo.lpszProxyBypass) { wcout << L"and proxy bypass list: " << autoProxyInfo.lpszProxyBypass << endl; GlobalFree(autoProxyInfo.lpszProxyBypass); } return result; } } } else { result = getStaticProxySettingForUrl(url, ieProxyConfig.lpszProxy, ieProxyConfig.lpszProxyBypass, proxy); } if(ieProxyConfig.lpszAutoConfigUrl != NULL) GlobalFree( ieProxyConfig.lpszAutoConfigUrl ); if(ieProxyConfig.lpszProxy != NULL) GlobalFree( ieProxyConfig.lpszProxy ); if(ieProxyConfig.lpszProxyBypass != NULL) GlobalFree( ieProxyConfig.lpszProxyBypass ); return result; } void ProxyParser::getProxySettingForProtocolFromProxyList(string protocol, string proxyList, ProxySetting & proxy) { size_t token, precedent_token = 0; token = proxyList.find(";"); do { string proxyItem = proxyList.substr(precedent_token, token-precedent_token); getProxySettingForProxyListItem(proxyItem, proxy); cout << "found proxy setting wioth protocol: " << proxy.protocol << endl; if(proxy.protocol== protocol || proxy.protocol == "all") break; precedent_token = token+1; token = proxyList.find(";", precedent_token);//can be separated by whitespace too? }while(token != string::npos); } void ProxyParser::getProxySettingForProxyListItem(string proxyItem, ProxySetting & proxy) { //proxy item strings: ([<scheme>=][<scheme>"://"]<server>[":"<port>]) size_t proxyToken = proxyItem.find("="); if(proxyToken != string::npos) proxy.protocol = proxyItem.substr(0, proxyToken); else proxy.protocol = "all"; proxyItem = proxyItem.erase(0, proxyToken+1); cout << "remaining proxy item: " <<proxyItem << endl; proxyToken = proxyItem.find("/"); if(proxyToken != string::npos) proxyItem = proxyItem.erase(0, proxyToken+2); proxyToken = proxyItem.find(":"); proxy.domain = proxyItem.substr(0, proxyToken); stringstream s(proxyItem.substr(proxyToken+1, string::npos)); s >> proxy.port; } bool ProxyParser::getStaticProxySettingForUrl(string url, wstring wproxylist, wstring proxybypass, ProxySetting & proxy) { URL_COMPONENTS components = {0}; components.dwStructSize = sizeof(URL_COMPONENTS); wchar_t scheme[20] = {0}; wchar_t domain[MAX_PATH] = {0}; components.lpszScheme = scheme; components.dwSchemeLength = 20; components.lpszHostName = domain; components.dwHostNameLength = MAX_PATH; wstring wurl(url.begin(), url.end()); WinHttpCrackUrl( wurl.c_str(), (DWORD)wurl.length(), 0, &components); wstring whost(domain); string host(whost.begin(), whost.end()); //FIXME if(!testHostForBypassList(host, proxybypass)) { string proxylist(wproxylist.begin(), wproxylist.end()); wstring wscheme(scheme); string protocol(wscheme.begin(), wscheme.end()); getProxySettingForProtocolFromProxyList(protocol, proxylist, proxy); return true; } else return false; } bool ProxyParser::testHostForBypassList(string host, wstring wproxybypass) { string proxybypass(wproxybypass.begin(), wproxybypass.end()); size_t token, precedent_token = 0; token = proxybypass.find(";"); while(token != string::npos) { string bypass = proxybypass.substr(precedent_token, token-precedent_token); if(testHostForBypass(host, bypass)) return true; precedent_token = token+1; token = proxybypass.find(";", precedent_token); } string bypass = proxybypass.substr(precedent_token, token); return testHostForBypass(host, bypass); } bool ProxyParser::testHostForBypass(string host, string bypass) { cout << "testing domain \"" << host << "\" for bypass: " << bypass << " "; if(isDomain(host)) { bool result = testDomainForBypass(host, bypass); if(result) { cout << " => MATCH" << endl; return true; } else { cout << " => NO MATCH" << endl; return false; } } else { bool result = testIpForBypass(host, bypass); if(result) { cout << " => MATCH" << endl; return true; } else { cout << " => NO MATCH" << endl; return false; } } } bool ProxyParser::testDomainForBypass(string domain, string bypass) { if(isDomain(bypass)) { if(domain == bypass) return true; if(bypass.at(0) == '*') { string suffix = bypass.substr(1, string::npos); size_t found = domain.rfind(suffix); return(found+suffix.length() == domain.length());//the suffix is the end of the domain } if(bypass == "<local>" && domain.find('.') == string::npos) return true; } else { vector<string> ips = getIPForHost(domain); vector<string>::iterator ipIt; for(ipIt = ips.begin(); ipIt != ips.end(); ipIt++) { string ip = *ipIt; if(testIpForBypass(ip, bypass)) return true; } } return false; } bool ProxyParser::testIpForBypass(string ip, string bypass) { if(!isDomain(bypass)) { if(ip == bypass) return true; //special case for IP like 172.16* if(bypass.at(bypass.size()-1) == '*') { if(ip.substr(0, bypass.size()-1) == bypass.substr(0, bypass.size()-1)) return true; } size_t token, iptoken, precedent_token = 0, precedent_iptoken = 0; token = bypass.find("."); iptoken = ip.find("."); while(token != string::npos) { string bypassnum = bypass.substr(precedent_token, token-precedent_token); string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken); if(!(bypassnum == ipnum || bypassnum == "*")) return false; precedent_token = token+1; precedent_iptoken = iptoken+1; token = bypass.find(".", precedent_token); iptoken = ip.find(".", precedent_iptoken); } string bypassnum = bypass.substr(precedent_token, token-precedent_token); string ipnum = ip.substr(precedent_iptoken, iptoken-precedent_iptoken); if(bypassnum == ipnum || bypassnum == "*") return true; } return false; } vector<string> ProxyParser::getIPForHost(string host) { vector<string> ips; WSADATA wsaData; int res = WSAStartup(MAKEWORD(2, 2), &wsaData); if(res != 0) return ips; struct addrinfo * result; res = getaddrinfo(host.c_str(), NULL, NULL, &result); if(res == 0) { struct addrinfo * current = result; do{ struct sockaddr_in *sockaddr_ipv4 = (struct sockaddr_in *) current->ai_addr; string ip = inet_ntoa(sockaddr_ipv4->sin_addr); ips.push_back(ip); current = current->ai_next; }while(current != NULL); freeaddrinfo(result); } WSACleanup(); return ips; } bool ProxyParser::isDomain(string host) { return (isalpha(host.at(0)) || (host.at(0) == '*' && host.at(1) == '.' && isalpha(host.at(2))) || host == "<local>"); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ADatabaseMetaDataResultSetMetaData.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:12:38 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _CONNECTIVITY_ADO_ADATABASEMETADATARESULTSETMETADATA_HXX_ #include "ado/ADatabaseMetaDataResultSetMetaData.hxx" #endif #ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_ #include "ado/Awrapado.hxx" #endif #ifndef _DBHELPER_DBEXCEPTION_HXX_ #include "connectivity/dbexception.hxx" #endif using namespace connectivity; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // ------------------------------------------------------------------------- ODatabaseMetaDataResultSetMetaData::~ODatabaseMetaDataResultSetMetaData() { if(m_pRecordSet) m_pRecordSet->Release(); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nSize = 0; if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) nSize = (*m_mColumnsIter).second.getColumnDisplaySize(); else if(m_pRecordSet) { WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) nSize = aField.GetActualSize(); } return nSize; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nType = 0; if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) nType = (*m_mColumnsIter).second.getColumnType(); else if(m_pRecordSet) { WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); nType = ADOS::MapADOType2Jdbc(aField.GetADOType()); } return nType; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException) { if(!m_pRecordSet) return 0; if(m_nColCount != -1) return m_nColCount; if(m_vMapping.size()) return m_mColumns.size(); ADOFields* pFields = NULL; m_pRecordSet->get_Fields(&pFields); WpOLEAppendCollection<ADOFields, ADOField, WpADOField> aFields(pFields); m_nColCount = aFields.GetItemCount(); return m_nColCount; } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getColumnName(); if(!m_pRecordSet) return ::rtl::OUString(); WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) return aField.GetName(); return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getColumnLabel(); return getColumnName(column); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isCurrency(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldFixed) == adFldFixed; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isSigned(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldNegativeScale) == adFldNegativeScale; } return sal_False; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getPrecision(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) return aField.GetPrecision(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getScale(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) return aField.GetNumericScale(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isNullable(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldIsNullable) == adFldIsNullable; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isReadOnly(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { // return (aField.GetStatus() & adFieldReadOnly) == adFieldReadOnly; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isDefinitelyWritable(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldUpdatable) == adFldUpdatable; } return sal_False; ; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isWritable(); return isDefinitelyWritable(column); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.10.216); FILE MERGED 2008/04/01 10:52:49 thb 1.10.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:25 rt 1.10.216.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: ADatabaseMetaDataResultSetMetaData.cxx,v $ * $Revision: 1.11 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "ado/ADatabaseMetaDataResultSetMetaData.hxx" #include "ado/Awrapado.hxx" #include "connectivity/dbexception.hxx" using namespace connectivity; using namespace connectivity::ado; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; // ------------------------------------------------------------------------- ODatabaseMetaDataResultSetMetaData::~ODatabaseMetaDataResultSetMetaData() { if(m_pRecordSet) m_pRecordSet->Release(); } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnDisplaySize( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nSize = 0; if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) nSize = (*m_mColumnsIter).second.getColumnDisplaySize(); else if(m_pRecordSet) { WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) nSize = aField.GetActualSize(); } return nSize; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnType( sal_Int32 column ) throw(SQLException, RuntimeException) { sal_Int32 nType = 0; if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) nType = (*m_mColumnsIter).second.getColumnType(); else if(m_pRecordSet) { WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); nType = ADOS::MapADOType2Jdbc(aField.GetADOType()); } return nType; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnCount( ) throw(SQLException, RuntimeException) { if(!m_pRecordSet) return 0; if(m_nColCount != -1) return m_nColCount; if(m_vMapping.size()) return m_mColumns.size(); ADOFields* pFields = NULL; m_pRecordSet->get_Fields(&pFields); WpOLEAppendCollection<ADOFields, ADOField, WpADOField> aFields(pFields); m_nColCount = aFields.GetItemCount(); return m_nColCount; } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnName( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getColumnName(); if(!m_pRecordSet) return ::rtl::OUString(); WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) return aField.GetName(); return ::rtl::OUString(); } // ------------------------------------------------------------------------- ::rtl::OUString SAL_CALL ODatabaseMetaDataResultSetMetaData::getColumnLabel( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getColumnLabel(); return getColumnName(column); } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isCurrency( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isCurrency(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldFixed) == adFldFixed; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isSigned( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isSigned(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldNegativeScale) == adFldNegativeScale; } return sal_False; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getPrecision( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getPrecision(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) return aField.GetPrecision(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.getScale(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) return aField.GetNumericScale(); return 0; } // ------------------------------------------------------------------------- sal_Int32 SAL_CALL ODatabaseMetaDataResultSetMetaData::isNullable( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isNullable(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldIsNullable) == adFldIsNullable; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isReadOnly( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isReadOnly(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { // return (aField.GetStatus() & adFieldReadOnly) == adFieldReadOnly; } return sal_False; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isDefinitelyWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isDefinitelyWritable(); if(!m_pRecordSet) return 0; WpADOField aField = ADOS::getField(m_pRecordSet,m_vMapping[column]); if(aField.IsValid()) { return (aField.GetAttributes() & adFldUpdatable) == adFldUpdatable; } return sal_False; ; } // ------------------------------------------------------------------------- sal_Bool SAL_CALL ODatabaseMetaDataResultSetMetaData::isWritable( sal_Int32 column ) throw(SQLException, RuntimeException) { if(m_mColumns.size() && (m_mColumnsIter = m_mColumns.find(column)) != m_mColumns.end()) return (*m_mColumnsIter).second.isWritable(); return isDefinitelyWritable(column); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before><commit_msg>Prevent a possible infinite loop in EulerNormalize.<commit_after><|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. *****************************************************************************/ /** * @file reference_line_smooother.cpp **/ #include "modules/planning/reference_line/reference_line_smoother.h" #include <algorithm> #include <limits> #include <string> #include <utility> #include "modules/common/log.h" #include "modules/common/math/vec2d.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/common/util/file.h" #include "modules/planning/math/curve_math.h" #include "modules/planning/math/double.h" namespace apollo { namespace planning { bool ReferenceLineSmoother::Init(const std::string& config_file) { if (!common::util::GetProtoFromFile(config_file, &smoother_config_)) { AERROR << "failed to load config file " << config_file; return false; } return true; } void ReferenceLineSmoother::Init(const ReferenceLineSmootherConfig& config) { smoother_config_ = config; } void ReferenceLineSmoother::Reset() { t_knots_.clear(); ref_points_.clear(); spline_solver_.reset(nullptr); } bool ReferenceLineSmoother::smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { Reset(); std::vector<ReferencePoint> ref_points; if (!sampling(raw_reference_line)) { AERROR << "Fail to sample reference line smoother points!"; return false; } spline_solver_.reset( new Spline2dSolver(t_knots_, smoother_config_.spline_order())); if (!apply_constraint(raw_reference_line)) { AERROR << "Add constraint for spline smoother failed"; return false; } if (!ApplyKernel()) { AERROR << "Add kernel for spline smoother failed."; return false; } if (!Solve()) { AERROR << "Solve spline smoother problem failed"; } // mapping spline to reference line point const double start_t = t_knots_.front(); const double end_t = t_knots_.back(); const double resolution = (end_t - start_t) / (smoother_config_.num_of_total_points() - 1); double t = start_t; const auto& spline = spline_solver_->spline(); for (std::uint32_t i = 0; i < smoother_config_.num_of_total_points() && t < end_t; ++i, t += resolution) { std::pair<double, double> xy = spline(t); const double heading = std::atan2(spline_solver_->spline().derivative_y(t), spline_solver_->spline().DerivativeX(t)); const double kappa = CurveMath::ComputeCurvature( spline_solver_->spline().DerivativeX(t), spline_solver_->spline().SecondDerivativeX(t), spline_solver_->spline().derivative_y(t), spline_solver_->spline().second_derivative_y(t)); const double dkappa = CurveMath::ComputeCurvatureDerivative( spline_solver_->spline().DerivativeX(t), spline_solver_->spline().SecondDerivativeX(t), spline_solver_->spline().ThirdDerivativeX(t), spline_solver_->spline().derivative_y(t), spline_solver_->spline().second_derivative_y(t), spline_solver_->spline().third_derivative_y(t)); common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({xy.first, xy.second}, &ref_sl_point)) { return false; } if (ref_sl_point.s() < 0 || ref_sl_point.s() > raw_reference_line.Length()) { continue; } ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s()); ref_points.emplace_back(ReferencePoint( hdmap::MapPathPoint(common::math::Vec2d(xy.first, xy.second), heading, rlp.lane_waypoints()), kappa, dkappa, 0.0, 0.0)); } ReferencePoint::RemoveDuplicates(&ref_points); *smoothed_reference_line = ReferenceLine(ref_points); return true; } bool ReferenceLineSmoother::sampling(const ReferenceLine& raw_reference_line) { const double length = raw_reference_line.Length(); const double resolution = length / smoother_config_.num_spline(); double accumulated_s = 0.0; for (std::uint32_t i = 0; i <= smoother_config_.num_spline() && accumulated_s <= length; ++i, accumulated_s += resolution) { ReferencePoint rlp = raw_reference_line.GetReferencePoint(accumulated_s); common::PathPoint path_point; path_point.set_x(rlp.x()); path_point.set_y(rlp.y()); path_point.set_theta(rlp.heading()); path_point.set_s(accumulated_s); ref_points_.push_back(std::move(path_point)); t_knots_.push_back(i); } return true; } bool ReferenceLineSmoother::apply_constraint( const ReferenceLine& raw_reference_line) { const double t_length = t_knots_.back() - t_knots_.front(); const double dt = t_length / (smoother_config_.num_evaluated_points() - 1); std::vector<double> evaluated_t; double accumulated_eval_t = 0.0; for (std::uint32_t i = 0; i < smoother_config_.num_evaluated_points(); ++i, accumulated_eval_t += dt) { evaluated_t.push_back(accumulated_eval_t); } std::vector<common::PathPoint> path_points; if (!extract_evaluated_points(raw_reference_line, evaluated_t, &path_points)) { AERROR << "Extract evaluated points failed"; return false; } // Add x, y boundary constraint std::vector<double> angles; std::vector<double> longitidinal_bound; std::vector<double> lateral_bound; std::vector<common::math::Vec2d> xy_points; for (std::uint32_t i = 0; i < path_points.size(); ++i) { angles.push_back(path_points[i].theta()); longitidinal_bound.push_back(smoother_config_.boundary_bound()); lateral_bound.push_back(smoother_config_.boundary_bound()); xy_points.emplace_back(path_points[i].x(), path_points[i].y()); } if (!spline_solver_->mutable_constraint()->Add2dBoundary( evaluated_t, angles, xy_points, longitidinal_bound, lateral_bound)) { AERROR << "Add 2d boundary constraint failed"; return false; } if (!spline_solver_->mutable_constraint() ->AddThirdDerivativeSmoothConstraint()) { AERROR << "Add jointness constraint failed"; return false; } return true; } bool ReferenceLineSmoother::ApplyKernel() { Spline2dKernel* kernel = spline_solver_->mutable_kernel(); // add spline kernel if (smoother_config_.derivative_weight() > 0) { kernel->add_derivative_kernel_matrix(smoother_config_.derivative_weight()); } if (smoother_config_.second_derivative_weight() > 0) { kernel->add_second_order_derivative_matrix( smoother_config_.second_derivative_weight()); } if (smoother_config_.third_derivative_weight() > 0) { kernel->add_third_order_derivative_matrix( smoother_config_.third_derivative_weight()); } // TODO(fanhaoyang): change to a configurable param kernel->AddRegularization(0.01); return true; } bool ReferenceLineSmoother::Solve() { return spline_solver_->Solve(); } bool ReferenceLineSmoother::extract_evaluated_points( const ReferenceLine& raw_reference_line, const std::vector<double>& vec_t, std::vector<common::PathPoint>* const path_points) const { for (const auto t : vec_t) { double s = 0.0; if (!get_s_from_param_t(t, &s)) { AERROR << "get s from " << t << " failed"; return false; } ReferencePoint rlp = raw_reference_line.GetReferencePoint(s); common::PathPoint path_point; path_point.set_x(rlp.x()); path_point.set_y(rlp.y()); path_point.set_theta(rlp.heading()); path_point.set_s(s); path_points->push_back(std::move(path_point)); } return true; } bool ReferenceLineSmoother::get_s_from_param_t(const double t, double* const s) const { if (t_knots_.size() < 2 || Double::Compare(t, t_knots_.back(), 1e-8) > 0) { return false; } std::uint32_t lower = find_index(t); std::uint32_t upper = lower + 1; double weight = 0.0; if (Double::Compare(t_knots_[upper], t_knots_[lower], 1e-8) > 0) { weight = (t - t_knots_[lower]) / (t_knots_[upper] - t_knots_[lower]); } *s = ref_points_[lower].s() * (1.0 - weight) + ref_points_[upper].s() * weight; return true; } std::uint32_t ReferenceLineSmoother::find_index(const double t) const { auto upper_bound = std::upper_bound(t_knots_.begin() + 1, t_knots_.end(), t); return std::min(t_knots_.size() - 1, static_cast<std::size_t>(upper_bound - t_knots_.begin())) - 1; } } // namespace planning } // namespace apollo <commit_msg>Planning: fix smoother sampling error<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. *****************************************************************************/ /** * @file reference_line_smooother.cpp **/ #include "modules/planning/reference_line/reference_line_smoother.h" #include <algorithm> #include <limits> #include <string> #include <utility> #include "modules/common/log.h" #include "modules/common/math/vec2d.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/common/util/file.h" #include "modules/planning/math/curve_math.h" #include "modules/planning/math/double.h" namespace apollo { namespace planning { bool ReferenceLineSmoother::Init(const std::string& config_file) { if (!common::util::GetProtoFromFile(config_file, &smoother_config_)) { AERROR << "failed to load config file " << config_file; return false; } return true; } void ReferenceLineSmoother::Init(const ReferenceLineSmootherConfig& config) { smoother_config_ = config; } void ReferenceLineSmoother::Reset() { t_knots_.clear(); ref_points_.clear(); spline_solver_.reset(nullptr); } bool ReferenceLineSmoother::smooth( const ReferenceLine& raw_reference_line, ReferenceLine* const smoothed_reference_line) { Reset(); std::vector<ReferencePoint> ref_points; if (!sampling(raw_reference_line)) { AERROR << "Fail to sample reference line smoother points!"; return false; } spline_solver_.reset( new Spline2dSolver(t_knots_, smoother_config_.spline_order())); if (!apply_constraint(raw_reference_line)) { AERROR << "Add constraint for spline smoother failed"; return false; } if (!ApplyKernel()) { AERROR << "Add kernel for spline smoother failed."; return false; } if (!Solve()) { AERROR << "Solve spline smoother problem failed"; } // mapping spline to reference line point const double start_t = t_knots_.front(); const double end_t = t_knots_.back(); const double resolution = (end_t - start_t) / (smoother_config_.num_of_total_points() - 1); double t = start_t; const auto& spline = spline_solver_->spline(); for (std::uint32_t i = 0; i < smoother_config_.num_of_total_points() && t < end_t; ++i, t += resolution) { std::pair<double, double> xy = spline(t); const double heading = std::atan2(spline_solver_->spline().derivative_y(t), spline_solver_->spline().DerivativeX(t)); const double kappa = CurveMath::ComputeCurvature( spline_solver_->spline().DerivativeX(t), spline_solver_->spline().SecondDerivativeX(t), spline_solver_->spline().derivative_y(t), spline_solver_->spline().second_derivative_y(t)); const double dkappa = CurveMath::ComputeCurvatureDerivative( spline_solver_->spline().DerivativeX(t), spline_solver_->spline().SecondDerivativeX(t), spline_solver_->spline().ThirdDerivativeX(t), spline_solver_->spline().derivative_y(t), spline_solver_->spline().second_derivative_y(t), spline_solver_->spline().third_derivative_y(t)); common::SLPoint ref_sl_point; if (!raw_reference_line.XYToSL({xy.first, xy.second}, &ref_sl_point)) { return false; } if (ref_sl_point.s() < 0 || ref_sl_point.s() > raw_reference_line.Length()) { continue; } ReferencePoint rlp = raw_reference_line.GetReferencePoint(ref_sl_point.s()); ref_points.emplace_back(ReferencePoint( hdmap::MapPathPoint(common::math::Vec2d(xy.first, xy.second), heading, rlp.lane_waypoints()), kappa, dkappa, 0.0, 0.0)); } ReferencePoint::RemoveDuplicates(&ref_points); *smoothed_reference_line = ReferenceLine(ref_points); return true; } bool ReferenceLineSmoother::sampling(const ReferenceLine& raw_reference_line) { const double length = raw_reference_line.Length(); const double resolution = length / smoother_config_.num_spline(); double accumulated_s = 0.0; for (std::uint32_t i = 0; i <= smoother_config_.num_spline(); ++i, accumulated_s = std::min(accumulated_s + resolution, length)) { ReferencePoint rlp = raw_reference_line.GetReferencePoint(accumulated_s); common::PathPoint path_point; path_point.set_x(rlp.x()); path_point.set_y(rlp.y()); path_point.set_theta(rlp.heading()); path_point.set_s(accumulated_s); ref_points_.push_back(std::move(path_point)); t_knots_.push_back(i); } return true; } bool ReferenceLineSmoother::apply_constraint( const ReferenceLine& raw_reference_line) { const double t_length = t_knots_.back() - t_knots_.front(); const double dt = t_length / (smoother_config_.num_evaluated_points() - 1); std::vector<double> evaluated_t; double accumulated_eval_t = 0.0; for (std::uint32_t i = 0; i < smoother_config_.num_evaluated_points(); ++i, accumulated_eval_t += dt) { evaluated_t.push_back(accumulated_eval_t); } std::vector<common::PathPoint> path_points; if (!extract_evaluated_points(raw_reference_line, evaluated_t, &path_points)) { AERROR << "Extract evaluated points failed"; return false; } // Add x, y boundary constraint std::vector<double> angles; std::vector<double> longitidinal_bound; std::vector<double> lateral_bound; std::vector<common::math::Vec2d> xy_points; for (std::uint32_t i = 0; i < path_points.size(); ++i) { angles.push_back(path_points[i].theta()); longitidinal_bound.push_back(smoother_config_.boundary_bound()); lateral_bound.push_back(smoother_config_.boundary_bound()); xy_points.emplace_back(path_points[i].x(), path_points[i].y()); } if (!spline_solver_->mutable_constraint()->Add2dBoundary( evaluated_t, angles, xy_points, longitidinal_bound, lateral_bound)) { AERROR << "Add 2d boundary constraint failed"; return false; } if (!spline_solver_->mutable_constraint() ->AddThirdDerivativeSmoothConstraint()) { AERROR << "Add jointness constraint failed"; return false; } return true; } bool ReferenceLineSmoother::ApplyKernel() { Spline2dKernel* kernel = spline_solver_->mutable_kernel(); // add spline kernel if (smoother_config_.derivative_weight() > 0) { kernel->add_derivative_kernel_matrix(smoother_config_.derivative_weight()); } if (smoother_config_.second_derivative_weight() > 0) { kernel->add_second_order_derivative_matrix( smoother_config_.second_derivative_weight()); } if (smoother_config_.third_derivative_weight() > 0) { kernel->add_third_order_derivative_matrix( smoother_config_.third_derivative_weight()); } // TODO(fanhaoyang): change to a configurable param kernel->AddRegularization(0.01); return true; } bool ReferenceLineSmoother::Solve() { return spline_solver_->Solve(); } bool ReferenceLineSmoother::extract_evaluated_points( const ReferenceLine& raw_reference_line, const std::vector<double>& vec_t, std::vector<common::PathPoint>* const path_points) const { for (const auto t : vec_t) { double s = 0.0; if (!get_s_from_param_t(t, &s)) { AERROR << "get s from " << t << " failed"; return false; } ReferencePoint rlp = raw_reference_line.GetReferencePoint(s); common::PathPoint path_point; path_point.set_x(rlp.x()); path_point.set_y(rlp.y()); path_point.set_theta(rlp.heading()); path_point.set_s(s); path_points->push_back(std::move(path_point)); } return true; } bool ReferenceLineSmoother::get_s_from_param_t(const double t, double* const s) const { if (t_knots_.size() < 2 || Double::Compare(t, t_knots_.back(), 1e-8) > 0) { return false; } std::uint32_t lower = find_index(t); std::uint32_t upper = lower + 1; double weight = 0.0; if (Double::Compare(t_knots_[upper], t_knots_[lower], 1e-8) > 0) { weight = (t - t_knots_[lower]) / (t_knots_[upper] - t_knots_[lower]); } *s = ref_points_[lower].s() * (1.0 - weight) + ref_points_[upper].s() * weight; return true; } std::uint32_t ReferenceLineSmoother::find_index(const double t) const { auto upper_bound = std::upper_bound(t_knots_.begin() + 1, t_knots_.end(), t); return std::min(t_knots_.size() - 1, static_cast<std::size_t>(upper_bound - t_knots_.begin())) - 1; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* * Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, * Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. * This file is part of Sipi. * Sipi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Sipi 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. * Additional permission under GNU AGPL version 3 section 7: * If you modify this Program, or any covered work, by linking or combining * it with Kakadu (or a modified version of that library) or Adobe ICC Color * Profiles (or a modified version of that library) or both, containing parts * covered by the terms of the Kakadu Software Licence or Adobe Software Licence, * or both, the licensors of this Program grant you additional permission * to convey the resulting work. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public * License along with Sipi. If not, see <http://www.gnu.org/licenses/>. */ #include <sstream> // std::ostringstream #include "Error.h" namespace shttps { Error::Error (const char *file_p, const int line_p, const char *msg, int errno_p) : runtime_error(std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line (line_p), file (file_p), message (msg), sysErrno (errno_p) { } //============================================================================ Error::Error (const char *file_p, const int line_p, const std::string &msg, int errno_p) : runtime_error(std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line (line_p), file (file_p), message (msg), sysErrno (errno_p) { } //============================================================================ std::string Error::to_string(void) const { std::ostringstream errStream; errStream << "Error at [" << file << ": " << line << "]"; if (sysErrno != 0) errStream << " (system error: " << std::strerror(sysErrno) << ")"; errStream << ": " << message; return errStream.str(); } //============================================================================ std::ostream &operator<< (std::ostream &outStream, const Error &rhs) { std::string errStr = rhs.to_string(); outStream << errStr << std::endl; // TODO: remove the endl, the logging code should do it return outStream; } //============================================================================ } <commit_msg>fix: add missing include.<commit_after>/* * Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, * Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. * This file is part of Sipi. * Sipi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Sipi 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. * Additional permission under GNU AGPL version 3 section 7: * If you modify this Program, or any covered work, by linking or combining * it with Kakadu (or a modified version of that library) or Adobe ICC Color * Profiles (or a modified version of that library) or both, containing parts * covered by the terms of the Kakadu Software Licence or Adobe Software Licence, * or both, the licensors of this Program grant you additional permission * to convey the resulting work. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public * License along with Sipi. If not, see <http://www.gnu.org/licenses/>. */ #include <cstring> // std::strerror #include <sstream> // std::ostringstream #include "Error.h" namespace shttps { Error::Error (const char *file_p, const int line_p, const char *msg, int errno_p) : runtime_error(std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line (line_p), file (file_p), message (msg), sysErrno (errno_p) { } //============================================================================ Error::Error (const char *file_p, const int line_p, const std::string &msg, int errno_p) : runtime_error(std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line (line_p), file (file_p), message (msg), sysErrno (errno_p) { } //============================================================================ std::string Error::to_string(void) const { std::ostringstream errStream; errStream << "Error at [" << file << ": " << line << "]"; if (sysErrno != 0) errStream << " (system error: " << std::strerror(sysErrno) << ")"; errStream << ": " << message; return errStream.str(); } //============================================================================ std::ostream &operator<< (std::ostream &outStream, const Error &rhs) { std::string errStr = rhs.to_string(); outStream << errStr << std::endl; // TODO: remove the endl, the logging code should do it return outStream; } //============================================================================ } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Sync tests. *//*--------------------------------------------------------------------*/ #include "es3fSyncTests.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" #include "gluShaderProgram.hpp" #include "gluCallLogWrapper.hpp" #include "gluRenderContext.hpp" #include "glwEnums.hpp" #include "deRandom.hpp" #include "deStringUtil.hpp" #include "deString.h" #include <vector> using tcu::TestLog; namespace deqp { namespace gles3 { namespace Functional { using namespace glw; // GL types static const int NUM_CASE_ITERATIONS = 5; enum WaitCommand { COMMAND_WAIT_SYNC = 1 << 0, COMMAND_CLIENT_WAIT_SYNC = 1 << 1 }; enum CaseOptions { CASE_FLUSH_BEFORE_WAIT = 1 << 0, CASE_FINISH_BEFORE_WAIT = 1 << 1 }; class FenceSyncCase : public TestCase, private glu::CallLogWrapper { public: FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options); ~FenceSyncCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: FenceSyncCase (const FenceSyncCase& other); FenceSyncCase& operator= (const FenceSyncCase& other); int m_numPrimitives; deUint32 m_waitCommand; deUint32 m_waitFlags; deUint64 m_timeout; deUint32 m_caseOptions; glu::ShaderProgram* m_program; GLsync m_syncObject; int m_iterNdx; de::Random m_rnd; }; FenceSyncCase::FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options) : TestCase (context, name, description) , CallLogWrapper (context.getRenderContext().getFunctions(), context.getTestContext().getLog()) , m_numPrimitives (numPrimitives) , m_waitCommand (waitCommand) , m_waitFlags (waitFlags) , m_timeout (timeout) , m_caseOptions (options) , m_program (DE_NULL) , m_syncObject (DE_NULL) , m_iterNdx (0) , m_rnd (deStringHash(name)) { } FenceSyncCase::~FenceSyncCase (void) { FenceSyncCase::deinit(); } static void generateVertices (std::vector<float>& dst, int numPrimitives, de::Random& rnd) { int numVertices = 3*numPrimitives; dst.resize(numVertices * 4); for (int i = 0; i < numVertices; i++) { dst[i*4 ] = rnd.getFloat(-1.0f, 1.0f); // x dst[i*4 + 1] = rnd.getFloat(-1.0f, 1.0f); // y dst[i*4 + 2] = rnd.getFloat( 0.0f, 1.0f); // z dst[i*4 + 3] = 1.0f; // w } } void FenceSyncCase::init (void) { const char* vertShaderSource = "#version 300 es\n" "layout(location = 0) in mediump vec4 a_position;\n" "\n" "void main (void)\n" "{\n" " gl_Position = a_position;\n" "}\n"; const char* fragShaderSource = "#version 300 es\n" "layout(location = 0) out mediump vec4 o_color;\n" "\n" "void main (void)\n" "{\n" " o_color = vec4(0.25, 0.5, 0.75, 1.0);\n" "}\n"; DE_ASSERT(!m_program); m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(vertShaderSource, fragShaderSource)); if (!m_program->isOk()) { m_testCtx.getLog() << *m_program; TCU_FAIL("Failed to compile shader program"); } m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); // Initialize test result to pass. GLU_CHECK_MSG("Case initialization finished"); } void FenceSyncCase::deinit (void) { if (m_program) { delete m_program; m_program = DE_NULL; } if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; } } FenceSyncCase::IterateResult FenceSyncCase::iterate (void) { TestLog& log = m_testCtx.getLog(); std::vector<float> vertices; bool testOk = true; std::string header = "Case iteration " + de::toString(m_iterNdx+1) + " / " + de::toString(NUM_CASE_ITERATIONS); const tcu::ScopedLogSection section (log, header, header); enableLogging(true); DE_ASSERT (m_program); glUseProgram (m_program->getProgram()); glEnable (GL_DEPTH_TEST); glClearColor (0.3f, 0.3f, 0.3f, 1.0f); glClearDepthf (1.0f); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Generate vertices glEnableVertexAttribArray (0); generateVertices (vertices, m_numPrimitives, m_rnd); glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, &vertices[0]); // Draw glDrawArrays(GL_TRIANGLES, 0, (int)vertices.size() / 4); log << TestLog::Message << "// Primitives drawn." << TestLog::EndMessage; // Create sync object m_syncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); GLU_CHECK_MSG ("Sync object created"); log << TestLog::Message << "// Sync object created." << TestLog::EndMessage; if (m_caseOptions & CASE_FLUSH_BEFORE_WAIT) glFlush(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT) glFinish(); // Wait for sync object GLenum waitValue = 0; if (m_waitCommand & COMMAND_WAIT_SYNC) { DE_ASSERT(m_timeout == GL_TIMEOUT_IGNORED); DE_ASSERT(m_waitFlags == 0); glWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glWaitSync called"); log << TestLog::Message << "// Wait command glWaitSync called with GL_TIMEOUT_IGNORED." << TestLog::EndMessage; } if (m_waitCommand & COMMAND_CLIENT_WAIT_SYNC) { waitValue = glClientWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glClientWaitSync called"); log << TestLog::Message << "// glClientWaitSync return value:" << TestLog::EndMessage; switch (waitValue) { case GL_ALREADY_SIGNALED: log << TestLog::Message << "// GL_ALREADY_SIGNALED" << TestLog::EndMessage; break; case GL_TIMEOUT_EXPIRED: log << TestLog::Message << "// GL_TIMEOUT_EXPIRED" << TestLog::EndMessage; break; case GL_CONDITION_SATISFIED: log << TestLog::Message << "// GL_CONDITION_SATISFIED" << TestLog::EndMessage; break; case GL_WAIT_FAILED: log << TestLog::Message << "// GL_WAIT_FAILED" << TestLog::EndMessage; testOk = false; break; default: TCU_FAIL("// Illegal return value!"); } } glFinish(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT && waitValue != GL_ALREADY_SIGNALED) { testOk = false; log << TestLog::Message << "// Expected glClientWaitSync to return GL_ALREADY_SIGNALED." << TestLog::EndMessage; } // Delete sync object if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; GLU_CHECK_MSG ("Sync object deleted"); log << TestLog::Message << "// Sync object deleted." << TestLog::EndMessage; } // Evaluate test result log << TestLog::Message << "// Test result: " << (testOk ? "Passed!" : "Failed!") << TestLog::EndMessage; if (!testOk) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } log << TestLog::Message << "// Sync objects created and deleted successfully." << TestLog::EndMessage; return (++m_iterNdx < NUM_CASE_ITERATIONS) ? CONTINUE : STOP; } SyncTests::SyncTests (Context& context) : TestCaseGroup(context, "fence_sync", "Fence Sync Tests") { } SyncTests::~SyncTests (void) { } void SyncTests::init (void) { // Fence sync tests. addChild(new FenceSyncCase(m_context, "wait_sync_smalldraw", "", 10, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "wait_sync_largedraw", "", 100000, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_largedraw", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_largedraw", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_auto", "", 100000, COMMAND_CLIENT_WAIT_SYNC, GL_SYNC_FLUSH_COMMANDS_BIT, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_manual", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FLUSH_BEFORE_WAIT)); addChild(new FenceSyncCase(m_context, "client_wait_sync_noflush", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_finish", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FINISH_BEFORE_WAIT)); } } // Functional } // gles3 } // deqp <commit_msg>am 29a994fb: am 6fe4621d: Reduce rendering load in large sync tests by 90%.<commit_after>/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Sync tests. *//*--------------------------------------------------------------------*/ #include "es3fSyncTests.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" #include "gluShaderProgram.hpp" #include "gluCallLogWrapper.hpp" #include "gluRenderContext.hpp" #include "glwEnums.hpp" #include "deRandom.hpp" #include "deStringUtil.hpp" #include "deString.h" #include <vector> using tcu::TestLog; namespace deqp { namespace gles3 { namespace Functional { using namespace glw; // GL types static const int NUM_CASE_ITERATIONS = 5; enum WaitCommand { COMMAND_WAIT_SYNC = 1 << 0, COMMAND_CLIENT_WAIT_SYNC = 1 << 1 }; enum CaseOptions { CASE_FLUSH_BEFORE_WAIT = 1 << 0, CASE_FINISH_BEFORE_WAIT = 1 << 1 }; class FenceSyncCase : public TestCase, private glu::CallLogWrapper { public: FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options); ~FenceSyncCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: FenceSyncCase (const FenceSyncCase& other); FenceSyncCase& operator= (const FenceSyncCase& other); int m_numPrimitives; deUint32 m_waitCommand; deUint32 m_waitFlags; deUint64 m_timeout; deUint32 m_caseOptions; glu::ShaderProgram* m_program; GLsync m_syncObject; int m_iterNdx; de::Random m_rnd; }; FenceSyncCase::FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options) : TestCase (context, name, description) , CallLogWrapper (context.getRenderContext().getFunctions(), context.getTestContext().getLog()) , m_numPrimitives (numPrimitives) , m_waitCommand (waitCommand) , m_waitFlags (waitFlags) , m_timeout (timeout) , m_caseOptions (options) , m_program (DE_NULL) , m_syncObject (DE_NULL) , m_iterNdx (0) , m_rnd (deStringHash(name)) { } FenceSyncCase::~FenceSyncCase (void) { FenceSyncCase::deinit(); } static void generateVertices (std::vector<float>& dst, int numPrimitives, de::Random& rnd) { int numVertices = 3*numPrimitives; dst.resize(numVertices * 4); for (int i = 0; i < numVertices; i++) { dst[i*4 ] = rnd.getFloat(-1.0f, 1.0f); // x dst[i*4 + 1] = rnd.getFloat(-1.0f, 1.0f); // y dst[i*4 + 2] = rnd.getFloat( 0.0f, 1.0f); // z dst[i*4 + 3] = 1.0f; // w } } void FenceSyncCase::init (void) { const char* vertShaderSource = "#version 300 es\n" "layout(location = 0) in mediump vec4 a_position;\n" "\n" "void main (void)\n" "{\n" " gl_Position = a_position;\n" "}\n"; const char* fragShaderSource = "#version 300 es\n" "layout(location = 0) out mediump vec4 o_color;\n" "\n" "void main (void)\n" "{\n" " o_color = vec4(0.25, 0.5, 0.75, 1.0);\n" "}\n"; DE_ASSERT(!m_program); m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(vertShaderSource, fragShaderSource)); if (!m_program->isOk()) { m_testCtx.getLog() << *m_program; TCU_FAIL("Failed to compile shader program"); } m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); // Initialize test result to pass. GLU_CHECK_MSG("Case initialization finished"); } void FenceSyncCase::deinit (void) { if (m_program) { delete m_program; m_program = DE_NULL; } if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; } } FenceSyncCase::IterateResult FenceSyncCase::iterate (void) { TestLog& log = m_testCtx.getLog(); std::vector<float> vertices; bool testOk = true; std::string header = "Case iteration " + de::toString(m_iterNdx+1) + " / " + de::toString(NUM_CASE_ITERATIONS); const tcu::ScopedLogSection section (log, header, header); enableLogging(true); DE_ASSERT (m_program); glUseProgram (m_program->getProgram()); glEnable (GL_DEPTH_TEST); glClearColor (0.3f, 0.3f, 0.3f, 1.0f); glClearDepthf (1.0f); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Generate vertices glEnableVertexAttribArray (0); generateVertices (vertices, m_numPrimitives, m_rnd); glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, &vertices[0]); // Draw glDrawArrays(GL_TRIANGLES, 0, (int)vertices.size() / 4); log << TestLog::Message << "// Primitives drawn." << TestLog::EndMessage; // Create sync object m_syncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); GLU_CHECK_MSG ("Sync object created"); log << TestLog::Message << "// Sync object created." << TestLog::EndMessage; if (m_caseOptions & CASE_FLUSH_BEFORE_WAIT) glFlush(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT) glFinish(); // Wait for sync object GLenum waitValue = 0; if (m_waitCommand & COMMAND_WAIT_SYNC) { DE_ASSERT(m_timeout == GL_TIMEOUT_IGNORED); DE_ASSERT(m_waitFlags == 0); glWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glWaitSync called"); log << TestLog::Message << "// Wait command glWaitSync called with GL_TIMEOUT_IGNORED." << TestLog::EndMessage; } if (m_waitCommand & COMMAND_CLIENT_WAIT_SYNC) { waitValue = glClientWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glClientWaitSync called"); log << TestLog::Message << "// glClientWaitSync return value:" << TestLog::EndMessage; switch (waitValue) { case GL_ALREADY_SIGNALED: log << TestLog::Message << "// GL_ALREADY_SIGNALED" << TestLog::EndMessage; break; case GL_TIMEOUT_EXPIRED: log << TestLog::Message << "// GL_TIMEOUT_EXPIRED" << TestLog::EndMessage; break; case GL_CONDITION_SATISFIED: log << TestLog::Message << "// GL_CONDITION_SATISFIED" << TestLog::EndMessage; break; case GL_WAIT_FAILED: log << TestLog::Message << "// GL_WAIT_FAILED" << TestLog::EndMessage; testOk = false; break; default: TCU_FAIL("// Illegal return value!"); } } glFinish(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT && waitValue != GL_ALREADY_SIGNALED) { testOk = false; log << TestLog::Message << "// Expected glClientWaitSync to return GL_ALREADY_SIGNALED." << TestLog::EndMessage; } // Delete sync object if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; GLU_CHECK_MSG ("Sync object deleted"); log << TestLog::Message << "// Sync object deleted." << TestLog::EndMessage; } // Evaluate test result log << TestLog::Message << "// Test result: " << (testOk ? "Passed!" : "Failed!") << TestLog::EndMessage; if (!testOk) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } log << TestLog::Message << "// Sync objects created and deleted successfully." << TestLog::EndMessage; return (++m_iterNdx < NUM_CASE_ITERATIONS) ? CONTINUE : STOP; } SyncTests::SyncTests (Context& context) : TestCaseGroup(context, "fence_sync", "Fence Sync Tests") { } SyncTests::~SyncTests (void) { } void SyncTests::init (void) { // Fence sync tests. addChild(new FenceSyncCase(m_context, "wait_sync_smalldraw", "", 10, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "wait_sync_largedraw", "", 10000, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_largedraw", "", 10000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_largedraw", "", 10000, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_auto", "", 10000, COMMAND_CLIENT_WAIT_SYNC, GL_SYNC_FLUSH_COMMANDS_BIT, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_manual", "", 10000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FLUSH_BEFORE_WAIT)); addChild(new FenceSyncCase(m_context, "client_wait_sync_noflush", "", 10000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_finish", "", 10000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FINISH_BEFORE_WAIT)); } } // Functional } // gles3 } // deqp <|endoftext|>
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WATCHER is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Watcher. If not, see <http://www.gnu.org/licenses/>. */ #include "replayState.h" #include <deque> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <libwatcher/message.h> #include "sharedStream.h" #include "Assert.h" #include "database.h" #include "watcherd.h" #include "logger.h" using namespace util; using namespace watcher; using namespace watcher::event; INIT_LOGGER(ReplayState, "ReplayState"); //< default value for number of events to prefetch from the database const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */ const unsigned int DEFAULT_STEP = 250U /* ms */; /** Internal structure used for implementing the class. Used to avoid * dependencies for the user of the class. These would normally be private * members of ReplayState. */ struct ReplayState::impl { boost::weak_ptr<SharedStream> conn; std::deque<MessagePtr> events; boost::asio::deadline_timer timer; Timestamp ts; // the current effective time Timestamp last_event; // timestamp of last event retrieved from db float speed; //< playback speed unsigned int bufsiz; //< number of database rows to prefetch Timestamp step; enum run_state { paused, running } state; timeval wall_time; //< used to correct for clock skew Timestamp delta; /* * Lock used for event queue. This is required due to the seek() member * function, which can be called from a different thread. */ boost::mutex lock; impl(SharedStreamPtr& ptr, boost::asio::io_service& ios) : conn(ptr), timer(ios), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE), step(DEFAULT_STEP), state(paused), delta(0) { TRACE_ENTER(); wall_time.tv_sec = 0; wall_time.tv_usec = 0; TRACE_EXIT(); } }; ReplayState::ReplayState(boost::asio::io_service& ios, SharedStreamPtr ptr, Timestamp t, float playback_speed) : impl_(new impl(ptr, ios)) { TRACE_ENTER(); Assert<Bad_arg>(t >= 0); impl_->ts = t; impl_->last_event = t; speed(playback_speed); TRACE_EXIT(); } Timestamp ReplayState::tell() const { TRACE_ENTER(); TRACE_EXIT_RET(impl_->ts); return impl_->ts; } ReplayState& ReplayState::pause() { TRACE_ENTER(); LOG_DEBUG("cancelling timer"); impl_->timer.cancel(); impl_->state = impl::paused; TRACE_EXIT(); return *this; } ReplayState& ReplayState::seek(Timestamp t) { TRACE_ENTER(); impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); impl_->ts = t; if (t == -1) impl_->last_event = std::numeric_limits<Timestamp>::max(); else impl_->last_event = t; } if (oldstate == impl::running) run(); TRACE_EXIT(); return *this; } ReplayState& ReplayState::speed(float f) { TRACE_ENTER(); Assert<Bad_arg>(f != 0); /* If speed changes direction, need to clear the event list. * Check for sign change by noting that positive*negative==negative */ if (impl_->speed * f < 0) { impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); /* * Avoid setting .last_event when SpeedMessage is received * prior to the first StartMessage. */ if (impl_->ts != 0 && impl_->ts != -1) impl_->last_event = impl_->ts; impl_->speed = f; } if (oldstate == impl::running) run(); } else impl_->speed = f; LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event); TRACE_EXIT(); return *this; } ReplayState& ReplayState::buffer_size(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->bufsiz = n; TRACE_EXIT(); return *this; } ReplayState& ReplayState::time_step(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->step = n; TRACE_EXIT(); return *this; } namespace { /* function object for accepting events output from Database::getEvents() */ struct event_output { std::deque<MessagePtr>& q; event_output(std::deque<MessagePtr>& qq) : q(qq) {} void operator() (MessagePtr m) { q.push_back(m); } }; } /** Schedule an asynchronous task to replay events from the database to a GUI * client. If the local cache of upcoming events is empty, prefetch a block of * events from the database. * * The code is written such that it will work when playing events forward or in * reverse. */ void ReplayState::run() { TRACE_ENTER(); boost::mutex::scoped_lock L(impl_->lock); if (impl_->events.empty()) { // queue is empty, pre-fetch more items from the DB boost::function<void(MessagePtr)> cb(event_output(impl_->events)); LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event); get_db_handle().getEvents(cb, impl_->last_event, (impl_->speed >= 0) ? Database::forward : Database::reverse, impl_->bufsiz); if (!impl_->events.empty()) { LOG_DEBUG("got " << impl_->events.size() << " events from the db query"); /* When starting to replay, assume that time T=0 is the time of the * first event in the stream. * T= -1 is EOF. * Convert to timestamp of first item in the returned events. * * When playing in reverse, the first item in the list is the last event in the database. */ if (impl_->ts == 0 || impl_->ts == -1) impl_->ts = impl_->events.front()->timestamp; // save timestamp of last event retrieved to avoid duplication impl_->last_event = impl_->events.back()->timestamp; } } if (! impl_->events.empty()) { /* * Calculate for the skew introduced by the time required to process the events. Skew is calculated * as the difference between the actual time taken and the expected time. This gets * subtracted from the wait for the next event to catch up. */ timeval tv; gettimeofday(&tv, 0); Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000; LOG_DEBUG("skew=" << skew << " delta=" << impl_->delta); skew -= impl_->delta; LOG_DEBUG("calculated skew of " << skew << " ms"); if (skew < 0) { LOG_DEBUG("something strange happened, skew < delta ??"); skew = 0; } memcpy(&impl_->wall_time, &tv, sizeof(tv)); // time until next event impl_->delta = impl_->events.front()->timestamp - impl_->ts; // update our notion of the current time after the timer expires impl_->ts = impl_->events.front()->timestamp; /* Adjust for playback speed. Note that when playing events in reverse, both speed * delta will be negative, which will turn delta into a positive value for the * async_wait() call, which is exactly what is required. */ impl_->delta = (Timestamp)(impl_->delta/impl_->speed); /* Correct for skew */ impl_->delta -= skew; if (impl_->delta < 0) impl_->delta = 0; LOG_DEBUG("Next event in " << impl_->delta << " ms"); impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta)); impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error)); impl_->state = impl::running; } else { /* * FIXME what should happen when the end of the event stream is reached? * One option would be to convert to live stream at this point. */ LOG_DEBUG("reached end of database, pausing playback"); impl_->state = impl::paused; } TRACE_EXIT(); } /** Replay events to a GUI client when a timer expires. * * The run() member function is reponsible for prefetching events from the * database and storing them in the class object. When a timer expires, run * through the locally stored events and send those that occurred within the * last time slice. The task is then rescheduled when the next most recent * event needs to be transmitted. */ void ReplayState::timer_handler(const boost::system::error_code& ec) { TRACE_ENTER(); if (ec == boost::asio::error::operation_aborted) LOG_DEBUG("timer was cancelled"); else if (impl_->state == impl::paused) { LOG_DEBUG("timer expired but state is paused!"); } else { std::vector<MessagePtr> msgs; { boost::mutex::scoped_lock L(impl_->lock); while (! impl_->events.empty()) { MessagePtr m = impl_->events.front(); /* Replay all events in the current time step. Use the absolute value * of the difference in order for forward and reverse replay to work * properly. */ if (abs(m->timestamp - impl_->ts) >= impl_->step) break; msgs.push_back(m); impl_->events.pop_front(); } } SharedStreamPtr srv = impl_->conn.lock(); if (srv) { /* connection is still alive */ srv->sendMessage(msgs); run(); // reschedule this task } } TRACE_EXIT(); } /* This is required to be defined, otherwise a the default dtor will cause a * compiler error due to use of scoped_ptr with an incomplete type. */ ReplayState::~ReplayState() { TRACE_ENTER(); TRACE_EXIT(); } float ReplayState::speed() const { return impl_->speed; } <commit_msg>fix race condition which drops some events from being sent to the client<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions * * This file is part of WATCHER. * * WATCHER is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * WATCHER is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Watcher. If not, see <http://www.gnu.org/licenses/>. */ #include "replayState.h" #include <deque> #include <boost/bind.hpp> #include <boost/thread.hpp> #include <libwatcher/message.h> #include "sharedStream.h" #include "Assert.h" #include "database.h" #include "watcherd.h" #include "logger.h" using namespace util; using namespace watcher; using namespace watcher::event; INIT_LOGGER(ReplayState, "ReplayState"); //< default value for number of events to prefetch from the database const unsigned int DEFAULT_BUFFER_SIZE = 20U; /* db rows */ const unsigned int DEFAULT_STEP = 250U /* ms */; /** Internal structure used for implementing the class. Used to avoid * dependencies for the user of the class. These would normally be private * members of ReplayState. */ struct ReplayState::impl { boost::weak_ptr<SharedStream> conn; std::deque<MessagePtr> events; boost::asio::deadline_timer timer; Timestamp ts; // the current effective time Timestamp last_event; // timestamp of last event retrieved from db float speed; //< playback speed unsigned int bufsiz; //< number of database rows to prefetch Timestamp step; enum run_state { paused, running } state; timeval wall_time; //< used to correct for clock skew Timestamp delta; /* * Lock used for event queue. This is required due to the seek() member * function, which can be called from a different thread. */ boost::mutex lock; impl(SharedStreamPtr& ptr, boost::asio::io_service& ios) : conn(ptr), timer(ios), ts(0), last_event(0), bufsiz(DEFAULT_BUFFER_SIZE), step(DEFAULT_STEP), state(paused), delta(0) { TRACE_ENTER(); wall_time.tv_sec = 0; wall_time.tv_usec = 0; TRACE_EXIT(); } }; ReplayState::ReplayState(boost::asio::io_service& ios, SharedStreamPtr ptr, Timestamp t, float playback_speed) : impl_(new impl(ptr, ios)) { TRACE_ENTER(); Assert<Bad_arg>(t >= 0); impl_->ts = t; impl_->last_event = t; speed(playback_speed); TRACE_EXIT(); } Timestamp ReplayState::tell() const { TRACE_ENTER(); TRACE_EXIT_RET(impl_->ts); return impl_->ts; } ReplayState& ReplayState::pause() { TRACE_ENTER(); LOG_DEBUG("cancelling timer"); impl_->timer.cancel(); impl_->state = impl::paused; TRACE_EXIT(); return *this; } ReplayState& ReplayState::seek(Timestamp t) { TRACE_ENTER(); impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); impl_->ts = t; if (t == -1) impl_->last_event = std::numeric_limits<Timestamp>::max(); else impl_->last_event = t; } if (oldstate == impl::running) run(); TRACE_EXIT(); return *this; } ReplayState& ReplayState::speed(float f) { TRACE_ENTER(); Assert<Bad_arg>(f != 0); /* If speed changes direction, need to clear the event list. * Check for sign change by noting that positive*negative==negative */ if (impl_->speed * f < 0) { impl::run_state oldstate; { boost::mutex::scoped_lock L(impl_->lock); oldstate = impl_->state; pause(); impl_->events.clear(); /* * Avoid setting .last_event when SpeedMessage is received * prior to the first StartMessage. */ if (impl_->ts != 0 && impl_->ts != -1) impl_->last_event = impl_->ts; impl_->speed = f; } if (oldstate == impl::running) run(); } else impl_->speed = f; LOG_DEBUG("ts=" << impl_->ts << " last_event=" << impl_->last_event); TRACE_EXIT(); return *this; } ReplayState& ReplayState::buffer_size(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->bufsiz = n; TRACE_EXIT(); return *this; } ReplayState& ReplayState::time_step(unsigned int n) { TRACE_ENTER(); Assert<Bad_arg>(n != 0); impl_->step = n; TRACE_EXIT(); return *this; } namespace { /* function object for accepting events output from Database::getEvents() */ struct event_output { std::deque<MessagePtr>& q; event_output(std::deque<MessagePtr>& qq) : q(qq) {} void operator() (MessagePtr m) { q.push_back(m); } }; } /** Schedule an asynchronous task to replay events from the database to a GUI * client. If the local cache of upcoming events is empty, prefetch a block of * events from the database. * * The code is written such that it will work when playing events forward or in * reverse. */ void ReplayState::run() { TRACE_ENTER(); boost::mutex::scoped_lock L(impl_->lock); if (impl_->events.empty()) { // queue is empty, pre-fetch more items from the DB boost::function<void(MessagePtr)> cb(event_output(impl_->events)); LOG_DEBUG("fetching events " << (impl_->speed > 0 ? "> " : "< ") << impl_->last_event); get_db_handle().getEvents(cb, impl_->last_event, (impl_->speed >= 0) ? Database::forward : Database::reverse, impl_->bufsiz); if (!impl_->events.empty()) { LOG_DEBUG("got " << impl_->events.size() << " events from the db query"); /* When starting to replay, assume that time T=0 is the time of the * first event in the stream. * T= -1 is EOF. * Convert to timestamp of first item in the returned events. * * When playing in reverse, the first item in the list is the last event in the database. */ if (impl_->ts == 0 || impl_->ts == -1) impl_->ts = impl_->events.front()->timestamp; // save timestamp of last event retrieved to avoid duplication impl_->last_event = impl_->events.back()->timestamp; } } if (! impl_->events.empty()) { /* * Calculate for the skew introduced by the time required to process the events. Skew is calculated * as the difference between the actual time taken and the expected time. This gets * subtracted from the wait for the next event to catch up. */ timeval tv; gettimeofday(&tv, 0); Timestamp skew = (tv.tv_sec - impl_->wall_time.tv_sec) * 1000 + (tv.tv_usec - impl_->wall_time.tv_usec) / 1000; LOG_DEBUG("skew=" << skew << " delta=" << impl_->delta); skew -= impl_->delta; LOG_DEBUG("calculated skew of " << skew << " ms"); if (skew < 0) { LOG_DEBUG("something strange happened, skew < delta ??"); skew = 0; } memcpy(&impl_->wall_time, &tv, sizeof(tv)); // time until next event impl_->delta = impl_->events.front()->timestamp - impl_->ts; // update our notion of the current time after the timer expires impl_->ts = impl_->events.front()->timestamp; /* Adjust for playback speed. Note that when playing events in reverse, both speed * delta will be negative, which will turn delta into a positive value for the * async_wait() call, which is exactly what is required. */ impl_->delta = (Timestamp)(impl_->delta/impl_->speed); /* Correct for skew */ impl_->delta -= skew; if (impl_->delta < 0) impl_->delta = 0; LOG_DEBUG("Next event in " << impl_->delta << " ms"); impl_->state = impl::running; impl_->timer.expires_from_now(boost::posix_time::millisec(impl_->delta)); impl_->timer.async_wait(boost::bind(&ReplayState::timer_handler, shared_from_this(), boost::asio::placeholders::error)); } else { /* * FIXME what should happen when the end of the event stream is reached? * One option would be to convert to live stream at this point. */ LOG_DEBUG("reached end of database, pausing playback"); impl_->state = impl::paused; } TRACE_EXIT(); } /** Replay events to a GUI client when a timer expires. * * The run() member function is reponsible for prefetching events from the * database and storing them in the class object. When a timer expires, run * through the locally stored events and send those that occurred within the * last time slice. The task is then rescheduled when the next most recent * event needs to be transmitted. */ void ReplayState::timer_handler(const boost::system::error_code& ec) { TRACE_ENTER(); if (ec == boost::asio::error::operation_aborted) LOG_DEBUG("timer was cancelled"); else if (impl_->state == impl::paused) { LOG_DEBUG("timer expired but state is paused!"); } else { std::vector<MessagePtr> msgs; { boost::mutex::scoped_lock L(impl_->lock); while (! impl_->events.empty()) { MessagePtr m = impl_->events.front(); /* Replay all events in the current time step. Use the absolute value * of the difference in order for forward and reverse replay to work * properly. */ if (abs(m->timestamp - impl_->ts) >= impl_->step) break; msgs.push_back(m); impl_->events.pop_front(); } } SharedStreamPtr srv = impl_->conn.lock(); if (srv) { /* connection is still alive */ srv->sendMessage(msgs); run(); // reschedule this task } } TRACE_EXIT(); } /* This is required to be defined, otherwise a the default dtor will cause a * compiler error due to use of scoped_ptr with an incomplete type. */ ReplayState::~ReplayState() { TRACE_ENTER(); TRACE_EXIT(); } float ReplayState::speed() const { return impl_->speed; } <|endoftext|>
<commit_before>/* * Event Manager by quckly * Version: 1.0 * */ #include "q_events.h" EventManager Events; EventManager::EventManager() { m_hook = false; //m_args = std::vector<EventArg>(16); } void EventManager::RegisterEvent(const int _msg_id, EventCallback _func) { // Check for exist for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++) if (iter->msg_id == _msg_id && iter->func == _func) return; m_regevents.push_back(EventRegister(_msg_id, _func)); } void EventManager::RegisterEvent(const char* msg_name, EventCallback func) { RegisterEvent(ID(msg_name), func); } int EventManager::ID(const char* msg_name) { return GET_USER_MSG_ID(PLID, msg_name, NULL); } // Get args int EventManager::GetArgInt(int num) { if (num < 0 || num >= m_args.size()) return 0; return m_args[num].value.iValue; } float EventManager::GetArgFloat(int num) { if (num < 0 || num >= m_args.size()) return 0.0; return m_args[num].value.flValue; } const char* EventManager::GetArgString(int num) { if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string) return nullptr; return m_args[num].str.c_str(); } // Set Args void EventManager::SetArg(int num, int set) { if (num < 0 || num >= m_args.size()) return; m_args[num].value.iValue = set; } void EventManager::SetArg(int num, float set) { if (num < 0 || num >= m_args.size()) return; m_args[num].value.flValue = set; } void EventManager::SetArg(int num, const char* set) { if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string) return; m_args[num].str = set; } // Handlers void EventManager::EM_MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed) { m_hook = false; for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++) { if (msg_type == iter->msg_id) { m_hook = true; m_msg_dest = msg_dest; m_msg_type = msg_type; m_origin = pOrigin; m_ed = ed; RETURN_META(MRES_SUPERCEDE); } } RETURN_META(MRES_IGNORED); } void EventManager::EM_MessageEnd() { if (m_hook) { int cb_return = ER_IGNORED, _cbret; // Execute all registered events for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++) { if (m_msg_type == iter->msg_id) { _cbret = iter->func(m_msg_dest, m_msg_type, m_origin, m_ed); if (_cbret == ER_SUPERCEDE) cb_return = ER_SUPERCEDE; } } if (cb_return == ER_SUPERCEDE) { RETURN_META(MRES_SUPERCEDE); } // Send message MESSAGE_BEGIN(m_msg_dest, m_msg_type, m_origin, m_ed); for (auto iter = m_args.cbegin(); iter != m_args.cend(); iter++) { switch (iter->m_type) { case at_byte: WRITE_BYTE(iter->value.iValue); break; case at_char: WRITE_CHAR(iter->value.iValue); break; case at_short: WRITE_SHORT(iter->value.iValue); break; case at_long: WRITE_LONG(iter->value.iValue); break; case at_angle: WRITE_ANGLE(iter->value.flValue); break; case at_coord: WRITE_COORD(iter->value.flValue); break; case at_string: WRITE_STRING(iter->str.c_str()); break; case at_entity: WRITE_ENTITY(iter->value.iValue); break; } } MESSAGE_END(); // Clear m_args.clear(); m_hook = false; RETURN_META(MRES_SUPERCEDE); } RETURN_META(MRES_IGNORED); } void EventManager::EM_WriteByte(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_byte, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteChar(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_char, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteShort(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_short, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteLong(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_long, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteAngle(float flValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_angle, flValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteCoord(float flValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_coord, flValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteString(const char *sz) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_string, sz)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteEntity(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_entity, iValue)); RETURN_META(MRES_SUPERCEDE); }<commit_msg>Fixed SUPERCEDE return in EventManager<commit_after>/* * Event Manager by quckly.ru * Version: 1.1 * */ #include "q_events.h" EventManager Events; EventManager::EventManager() { m_hook = false; //m_args = std::vector<EventArg>(16); } void EventManager::RegisterEvent(const int _msg_id, EventCallback _func) { // Check for exist for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++) if (iter->msg_id == _msg_id && iter->func == _func) return; m_regevents.push_back(EventRegister(_msg_id, _func)); } void EventManager::RegisterEvent(const char* msg_name, EventCallback func) { RegisterEvent(ID(msg_name), func); } int EventManager::ID(const char* msg_name) { return GET_USER_MSG_ID(PLID, msg_name, NULL); } // Get args int EventManager::GetArgInt(int num) { if (num < 0 || num >= m_args.size()) return 0; return m_args[num].value.iValue; } float EventManager::GetArgFloat(int num) { if (num < 0 || num >= m_args.size()) return 0.0; return m_args[num].value.flValue; } const char* EventManager::GetArgString(int num) { if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string) return nullptr; return m_args[num].str.c_str(); } // Set Args void EventManager::SetArg(int num, int set) { if (num < 0 || num >= m_args.size()) return; m_args[num].value.iValue = set; } void EventManager::SetArg(int num, float set) { if (num < 0 || num >= m_args.size()) return; m_args[num].value.flValue = set; } void EventManager::SetArg(int num, const char* set) { if (num < 0 || num >= m_args.size() || m_args[num].m_type != at_string) return; m_args[num].str = set; } // Handlers void EventManager::EM_MessageBegin(int msg_dest, int msg_type, const float *pOrigin, edict_t *ed) { m_args.clear(); m_hook = false; for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++) { if (msg_type == iter->msg_id) { m_hook = true; m_msg_dest = msg_dest; m_msg_type = msg_type; m_origin = pOrigin; m_ed = ed; RETURN_META(MRES_SUPERCEDE); } } RETURN_META(MRES_IGNORED); } void EventManager::EM_MessageEnd() { if (m_hook) { m_hook = false; int cb_return = ER_IGNORED, _cbret; // Execute all registered events for (auto iter = m_regevents.cbegin(); iter != m_regevents.cend(); iter++) { if (m_msg_type == iter->msg_id) { _cbret = iter->func(m_msg_dest, m_msg_type, m_origin, m_ed); if (_cbret == ER_SUPERCEDE) cb_return = ER_SUPERCEDE; } } if (cb_return == ER_SUPERCEDE) { RETURN_META(MRES_SUPERCEDE); } // Send message MESSAGE_BEGIN(m_msg_dest, m_msg_type, m_origin, m_ed); for (auto iter = m_args.cbegin(); iter != m_args.cend(); iter++) { switch (iter->m_type) { case at_byte: WRITE_BYTE(iter->value.iValue); break; case at_char: WRITE_CHAR(iter->value.iValue); break; case at_short: WRITE_SHORT(iter->value.iValue); break; case at_long: WRITE_LONG(iter->value.iValue); break; case at_angle: WRITE_ANGLE(iter->value.flValue); break; case at_coord: WRITE_COORD(iter->value.flValue); break; case at_string: WRITE_STRING(iter->str.c_str()); break; case at_entity: WRITE_ENTITY(iter->value.iValue); break; } } MESSAGE_END(); RETURN_META(MRES_SUPERCEDE); } RETURN_META(MRES_IGNORED); } void EventManager::EM_WriteByte(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_byte, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteChar(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_char, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteShort(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_short, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteLong(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_long, iValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteAngle(float flValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_angle, flValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteCoord(float flValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_coord, flValue)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteString(const char *sz) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_string, sz)); RETURN_META(MRES_SUPERCEDE); } void EventManager::EM_WriteEntity(int iValue) { if (!m_hook) RETURN_META(MRES_IGNORED); m_args.push_back(EventArg(at_entity, iValue)); RETURN_META(MRES_SUPERCEDE); }<|endoftext|>
<commit_before>#ifndef LIA_DETAIL_TYPE_TRAITS_HPP #define LIA_DETAIL_TYPE_TRAITS_HPP // Includes #include <type_traits> #include <utility> #include <cstddef> #include <array> namespace lia { template<typename T> using Type = typename T::type; template<typename... Args> using CommonType = Type<std::common_type<Args...>>; template<typename T> using UnderlyingType = Type<std::underlying_type<T>>; template<typename T, T t> using Const = std::integral_constant<T,t>; template<int i> using Integer = Const<int,i>; template<typename T> struct identity { using type = T; }; template<typename...> struct void_ { using type = void; }; template<typename... T> using Void = typename void_<T...>::type; template<bool T, typename...> struct boolean : Const<bool, T> {}; template<bool T, typename... Args> using Bool = Type<boolean<T,Args...>>; template<typename If, typename Then, typename Else> using Conditional = Type<std::conditional<If::value, Then, Else>>; template<typename T> using Not = Bool<!T::value>; template<typename... Args> struct Any : Bool<true> {}; template<typename T, typename... Args> struct Any<T, Args...> : Conditional<T, Bool<true>, Any<Args...>> {}; template<typename... Args> struct All : Bool<true> {}; template<typename T, typename... Args> struct All<T, Args...> : Conditional<T, All<Args...>, Bool<false>> {}; template<typename T> struct is_allocator { private: using yes = char; using no = struct { char stuff[2]; }; template<class Cont> static yes test(typename Cont::template rebind<Cont>::other*); template<class Cont> static no test(...); public: static constexpr bool value = sizeof(test<T>(0)) == sizeof(yes); }; template<bool Cond, typename Specialization, typename Target> struct rebind_allocator {}; template<typename Alloc, typename Target> struct rebind_allocator<true, Alloc, Target> { using type = typename Alloc::template rebind<Target>::other; }; template<typename T, typename Target> struct rebind_allocator<false, T, Target> { using type = T; }; template<typename T, typename Target> using RebindAllocator = Type<rebind_allocator<is_allocator<T>::value, T, Target>>; template<typename Specialization, typename Target> struct rebind {}; // Sensible default: assume first parameter is for the target template<template<typename...> class Cont, typename T, typename... Ts, typename Target> struct rebind<Cont<T, Ts...>, Target> { using type = Cont<Target, RebindAllocator<Ts, Target>...>; }; template<typename Old, size_t N, typename Target> struct rebind<std::array<Old, N>, Target> { using type = std::array<Target, N>; }; template<typename Specialization, typename Target> using Rebind = typename rebind<Specialization, Target>::type; template<typename Signature, typename Anon = void> struct result_of_impl {}; template<typename Function, typename... Args> struct result_of_impl<Function(Args...), Void<decltype(std::declval<Function>()(std::declval<Args>()...))>> { using type = decltype(std::declval<Function>()(std::declval<Args>()...)); }; template<typename Signature> using ResultOf = Type<result_of_impl<Signature>>; template<typename... Args> using EnableIf = Type<std::enable_if<All<Args...>::value>>; template<typename... Args> using DisableIf = Type<std::enable_if<Not<All<Args...>>::value>>; template<typename T> using Decay = Type<std::decay<T>>; template<typename T> using RemoveRef = Type<std::remove_reference<T>>; template<typename T> using RemoveCV = Type<std::remove_cv<T>>; template<typename T> using RemoveConst = Type<std::remove_const<T>>; template<typename T> using RemoveVolatile = Type<std::remove_volatile<T>>; template<typename T> using RemoveExtents = Type<std::remove_all_extents<T>>; template<typename T> using RemovePointer = Type<std::remove_pointer<T>>; template<typename T> using AddLValueRef = Type<std::add_lvalue_reference<T>>; template<typename T> using AddRValueRef = Type<std::add_rvalue_reference<T>>; template<typename T> using AddCV = Type<std::add_cv<T>>; template<typename T> using AddConst = Type<std::add_const<T>>; template<typename T> using AddVolatile = Type<std::add_volatile<T>>; template<typename T> using AddPointer = Type<std::add_pointer<T>>; template<typename T> using Signed = Type<std::make_signed<T>>; template<typename T> using Unsigned = Type<std::make_unsigned<T>>; template<typename T> using Unqualified = RemoveCV<RemoveRef<T>>; template<typename T> using ValueType = typename Unqualified<T>::value_type; template<typename T> using NestedValueType = ValueType<ValueType<T>>; template<typename T> constexpr AddConst<T>& as_const(T& t) { return t; } template<typename T> constexpr T abs(T t) { return t < 0 ? -t : t; } template<typename T> constexpr T min(T&& t) { return std::forward<T>(t); } template<typename T, typename U> constexpr auto min(T&& t, U&& u) -> CommonType<T,U> { return t < u ? std::forward<T>(t) : std::forward<U>(u); } template<typename T, typename U, typename... Args> constexpr auto min(T&& t, U&& u, Args&&... args) -> CommonType<T,U,Args...> { return min(min(std::forward<T>(t), std::forward<U>(u)), std::forward<Args>(args)...); } template<typename T> constexpr T max(T&& t) { return std::forward<T>(t); } template<typename T, typename U> constexpr auto max(T&& t, U&& u) -> CommonType<T,U> { return t > u ? std::forward<T>(t) : std::forward<U>(u); } template<typename T, typename U, typename... Args> constexpr auto max(T&& t, U&& u, Args&&... args) -> CommonType<T,U,Args...> { return max(max(std::forward<T>(t), std::forward<U>(u)), std::forward<Args>(args)...); } struct has_append_impl { template<typename T> static auto test(T* t) -> decltype(t->append(0), Bool<true>()) {} template<typename> static auto test(...) -> Bool<false>; }; template<typename T> struct has_append : decltype(has_append_impl::test<T>(0)) {}; template<typename T> struct is_nested_container { private: using yes = char; using no = struct { char stuff[2]; }; template<class Cont> static yes test(typename Cont::value_type::value_type*); template<class Cont> static no test(...); public: static constexpr bool value = sizeof(test<T>(0)) == sizeof(yes); }; struct has_begin_impl { template<typename T> static auto test(T* t) -> decltype(t->begin(), Bool<true>()) {} template<typename> static auto test(...) -> Bool<false>; }; struct has_end_impl { template<typename T> static auto test(T* t) -> decltype(t->end(), Bool<true>()) {} template<typename> static auto test(...) -> Bool<false>; }; template<typename T> struct has_begin : decltype(has_begin_impl::test<T>()) {}; template<typename T> struct has_end : decltype(has_end_impl::test<T>()) {}; template<typename T> struct has_begin_end : Bool<has_begin<T>() && has_end<T>()> {}; } // lia #endif // LIA_DETAIL_TYPE_TRAITS_HPP<commit_msg>Fix for has_begin and has_end traits<commit_after>#ifndef LIA_DETAIL_TYPE_TRAITS_HPP #define LIA_DETAIL_TYPE_TRAITS_HPP // Includes #include <type_traits> #include <utility> #include <cstddef> #include <array> namespace lia { template<typename T> using Type = typename T::type; template<typename... Args> using CommonType = Type<std::common_type<Args...>>; template<typename T> using UnderlyingType = Type<std::underlying_type<T>>; template<typename T, T t> using Const = std::integral_constant<T,t>; template<int i> using Integer = Const<int,i>; template<typename T> struct identity { using type = T; }; template<typename...> struct void_ { using type = void; }; template<typename... T> using Void = typename void_<T...>::type; template<bool T, typename...> struct boolean : Const<bool, T> {}; template<bool T, typename... Args> using Bool = Type<boolean<T,Args...>>; template<typename If, typename Then, typename Else> using Conditional = Type<std::conditional<If::value, Then, Else>>; template<typename T> using Not = Bool<!T::value>; template<typename... Args> struct Any : Bool<true> {}; template<typename T, typename... Args> struct Any<T, Args...> : Conditional<T, Bool<true>, Any<Args...>> {}; template<typename... Args> struct All : Bool<true> {}; template<typename T, typename... Args> struct All<T, Args...> : Conditional<T, All<Args...>, Bool<false>> {}; template<typename T> struct is_allocator { private: using yes = char; using no = struct { char stuff[2]; }; template<class Cont> static yes test(typename Cont::template rebind<Cont>::other*); template<class Cont> static no test(...); public: static constexpr bool value = sizeof(test<T>(0)) == sizeof(yes); }; template<bool Cond, typename Specialization, typename Target> struct rebind_allocator {}; template<typename Alloc, typename Target> struct rebind_allocator<true, Alloc, Target> { using type = typename Alloc::template rebind<Target>::other; }; template<typename T, typename Target> struct rebind_allocator<false, T, Target> { using type = T; }; template<typename T, typename Target> using RebindAllocator = Type<rebind_allocator<is_allocator<T>::value, T, Target>>; template<typename Specialization, typename Target> struct rebind {}; // Sensible default: assume first parameter is for the target template<template<typename...> class Cont, typename T, typename... Ts, typename Target> struct rebind<Cont<T, Ts...>, Target> { using type = Cont<Target, RebindAllocator<Ts, Target>...>; }; template<typename Old, size_t N, typename Target> struct rebind<std::array<Old, N>, Target> { using type = std::array<Target, N>; }; template<typename Specialization, typename Target> using Rebind = typename rebind<Specialization, Target>::type; template<typename Signature, typename Anon = void> struct result_of_impl {}; template<typename Function, typename... Args> struct result_of_impl<Function(Args...), Void<decltype(std::declval<Function>()(std::declval<Args>()...))>> { using type = decltype(std::declval<Function>()(std::declval<Args>()...)); }; template<typename Signature> using ResultOf = Type<result_of_impl<Signature>>; template<typename... Args> using EnableIf = Type<std::enable_if<All<Args...>::value>>; template<typename... Args> using DisableIf = Type<std::enable_if<Not<All<Args...>>::value>>; template<typename T> using Decay = Type<std::decay<T>>; template<typename T> using RemoveRef = Type<std::remove_reference<T>>; template<typename T> using RemoveCV = Type<std::remove_cv<T>>; template<typename T> using RemoveConst = Type<std::remove_const<T>>; template<typename T> using RemoveVolatile = Type<std::remove_volatile<T>>; template<typename T> using RemoveExtents = Type<std::remove_all_extents<T>>; template<typename T> using RemovePointer = Type<std::remove_pointer<T>>; template<typename T> using AddLValueRef = Type<std::add_lvalue_reference<T>>; template<typename T> using AddRValueRef = Type<std::add_rvalue_reference<T>>; template<typename T> using AddCV = Type<std::add_cv<T>>; template<typename T> using AddConst = Type<std::add_const<T>>; template<typename T> using AddVolatile = Type<std::add_volatile<T>>; template<typename T> using AddPointer = Type<std::add_pointer<T>>; template<typename T> using Signed = Type<std::make_signed<T>>; template<typename T> using Unsigned = Type<std::make_unsigned<T>>; template<typename T> using Unqualified = RemoveCV<RemoveRef<T>>; template<typename T> using ValueType = typename Unqualified<T>::value_type; template<typename T> using NestedValueType = ValueType<ValueType<T>>; template<typename T> constexpr AddConst<T>& as_const(T& t) { return t; } template<typename T> constexpr T abs(T t) { return t < 0 ? -t : t; } template<typename T> constexpr T min(T&& t) { return std::forward<T>(t); } template<typename T, typename U> constexpr auto min(T&& t, U&& u) -> CommonType<T,U> { return t < u ? std::forward<T>(t) : std::forward<U>(u); } template<typename T, typename U, typename... Args> constexpr auto min(T&& t, U&& u, Args&&... args) -> CommonType<T,U,Args...> { return min(min(std::forward<T>(t), std::forward<U>(u)), std::forward<Args>(args)...); } template<typename T> constexpr T max(T&& t) { return std::forward<T>(t); } template<typename T, typename U> constexpr auto max(T&& t, U&& u) -> CommonType<T,U> { return t > u ? std::forward<T>(t) : std::forward<U>(u); } template<typename T, typename U, typename... Args> constexpr auto max(T&& t, U&& u, Args&&... args) -> CommonType<T,U,Args...> { return max(max(std::forward<T>(t), std::forward<U>(u)), std::forward<Args>(args)...); } struct has_append_impl { template<typename T> static auto test(T* t) -> decltype(t->append(0), Bool<true>()) {} template<typename> static auto test(...) -> Bool<false>; }; template<typename T> struct has_append : decltype(has_append_impl::test<T>(0)) {}; template<typename T> struct is_nested_container { private: using yes = char; using no = struct { char stuff[2]; }; template<class Cont> static yes test(typename Cont::value_type::value_type*); template<class Cont> static no test(...); public: static constexpr bool value = sizeof(test<T>(0)) == sizeof(yes); }; struct has_begin_impl { template<typename T> static auto test(T* t) -> decltype(t->begin(), Bool<true>()) {} template<typename> static auto test(...) -> Bool<false>; }; struct has_end_impl { template<typename T> static auto test(T* t) -> decltype(t->end(), Bool<true>()) {} template<typename> static auto test(...) -> Bool<false>; }; template<typename T> struct has_begin : decltype(has_begin_impl::test<T>(0)) {}; template<typename T> struct has_end : decltype(has_end_impl::test<T>(0)) {}; template<typename T> struct has_begin_end : Bool<has_begin<T>() && has_end<T>()> {}; } // lia #endif // LIA_DETAIL_TYPE_TRAITS_HPP<|endoftext|>
<commit_before>#include <Internal/Logger/LoggerImpl.hpp> #include <Utility/Utilities/Include/Logging/LogLevel.hpp> #include <Utility/Utilities/Include/Logging/LogTag.hpp> #include <Utility/Utilities/Include/Logging/LogTextData.hpp> #include <Utility/Utilities/Include/Logging/LogLevelConverter.hpp> #include <Utility/Utilities/Include/Logging/LogTagConverter.hpp> #include <Utility/Utilities/Include/Logging/HelpFunctions.hpp> #include <Utility/Utilities/Include/IO/FileMap/FileMap.hpp> #include <Utility/Utilities/Include/String/VA_ListToString.hpp> #include <Utility/Utilities/Include/String/StringHelper.hpp> #include <iostream> #include <algorithm> #include <chrono> #include <random> #include <Windows.h> namespace DoremiEngine { namespace Logging { using namespace Doremi::Utilities; using namespace Doremi::Utilities::Logging; void threadWork(bool* p_applicationOnline, Memory::CircleBuffer<LogTextData>* p_localBuffer, Memory::CircleBuffer<LogTextData>* m_outGoingBuffer); LoggerImpl::LoggerImpl() : m_localBuffer(nullptr), m_outGoingBuffer(nullptr), m_fileMap(nullptr), m_mutex(nullptr), m_applicationRunning(nullptr) { // http://en.cppreference.com/w/cpp/numeric/random std::random_device randomDevice; std::mt19937 randomEngine(randomDevice()); const std::uniform_int_distribution<int> distribution(1, INT_MAX); m_uniqueId = distribution(randomEngine); std::cout << "Filemap uniqueId: " << m_uniqueId << std::endl; Initialize(); } LoggerImpl::~LoggerImpl() { if(m_localBuffer != nullptr) { delete m_localBuffer; } if(m_outGoingBuffer != nullptr) { delete m_outGoingBuffer; } if(m_fileMap != nullptr) { delete m_fileMap; } if(m_mutex != nullptr) { delete m_mutex; } if(m_applicationRunning != nullptr) { delete m_applicationRunning; } } void LoggerImpl::Initialize() { m_localBuffer = new Memory::CircleBuffer<LogTextData>(); m_outGoingBuffer = new Memory::CircleBuffer<LogTextData>(); // TODORT // TODOXX // TODOCONFIG our hardcode better value from empirical tests // Create localbuffer m_localBuffer->Initialize(10000, nullptr); // Create mutex m_mutex = CreateFileMapMutex(); // Fetch shared memory from fileMap void* fileMapMemory = InitializeFileMap(Constants::IPC_FILEMAP_SIZE); // Intiailize outgoing buffer with shared memory and mutex m_outGoingBuffer->Initialize(fileMapMemory, Constants::IPC_FILEMAP_SIZE, m_mutex); m_applicationRunning = new bool(true); std::thread outGoingLoggingThread(threadWork, m_applicationRunning, m_localBuffer, m_outGoingBuffer); outGoingLoggingThread.detach(); #ifdef NO_LOGGER #else StartLoggingProcess(); #endif } void LoggerImpl::LT(const std::string& p_function, const size_t& p_line, const LogTag& p_logTag, const LogLevel& p_logLevel, const char* p_format, ...) { // Build a string from va_list va_list args; va_start(args, p_format); std::string message; String::toString(message, p_format, args); va_end(args); Logging::LogTextData data; // Function const std::size_t functionLength = p_function.copy(data.function, std::max(p_function.size(), Constants::LONGEST_FUNCTION_NAME), 0); data.function[functionLength] = '\0'; // Line data.line = p_line; // Message const std::size_t messageLength = message.copy(data.message, std::max(message.size(), Constants::LONGEST_FUNCTION_NAME), 0); data.message[messageLength] = '\0'; // Level and tag data.logLevel = p_logLevel; data.logTag = p_logTag; using namespace Memory; Memory::CircleBufferHeader header; header.packageSize = sizeof(LogTextData); header.packageType = CircleBufferType(CircleBufferTypeEnum::TEXT); bool succeed = false; #ifdef NO_LOGGER m_localBuffer->Produce(header, &data); #else while(!succeed) // TODORT Might not need while loop { succeed = m_localBuffer->Produce(header, &data); } #endif } void* LoggerImpl::InitializeFileMap(const std::size_t& p_size) { m_fileMap = new IO::FileMap(); void* memory = m_fileMap->Initialize(Logging::BuildFileMapName(m_uniqueId), p_size); if(memory != nullptr) { return memory; } else { throw std::runtime_error("Failed to initialize filemap."); } } IO::Mutex* LoggerImpl::CreateFileMapMutex() { IO::Mutex* mutex = new IO::FileMapMutex(); const bool success = mutex->Initialize(Constants::IPC_FILEMAP_MUTEX_NAME); if(success) { return mutex; } else { delete mutex; throw std::runtime_error("Failed to initialize filemap mutex."); } } std::wstring LoggerImpl::BuildLoggingProcessArgumentString() { const std::wstring applicationPathW = String::s2ws(Constants::LOGGING_PROCESS_NAME).c_str(); const std::wstring arguments = std::wstring(applicationPathW + std::wstring(L" ") + std::to_wstring(m_uniqueId)); return arguments; } void LoggerImpl::StartLoggingProcess() { PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; ZeroMemory(&processInformation, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startupInfo, sizeof(STARTUPINFO)); startupInfo.cb = sizeof(STARTUPINFO); std::wstring& arguments = BuildLoggingProcessArgumentString(); if(!CreateProcess(NULL, &arguments[0], 0, 0, 0, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, 0, 0, &startupInfo, &processInformation)) { std::cout << GetLastError() << std::endl; throw std::runtime_error("Creating loggingprocess failed."); } CloseHandle(processInformation.hProcess); CloseHandle(processInformation.hThread); } void threadWork(bool* p_applicationOnline, Memory::CircleBuffer<LogTextData>* p_localBuffer, Memory::CircleBuffer<LogTextData>* m_outGoingBuffer) { bool messageExist = true; LogTextData* data = new LogTextData(); Memory::CircleBufferHeader* header = new Memory::CircleBufferHeader(); bool succeed = false; // As long as the application is running or if there are some messages ongoing while(*p_applicationOnline || messageExist) // TODORT, this might crash on crash.... { using namespace std::literals; messageExist = p_localBuffer->Consume(header, data); if(messageExist) { #ifdef NO_LOGGER m_outGoingBuffer->Produce(*header, data); #else succeed = false; while(!succeed) { succeed = m_outGoingBuffer->Produce(*header, data); } #endif } // std::this_thread::sleep_for(2s); } delete data; delete header; } } } <commit_msg>Using processId over arbitrary random for filemap<commit_after>#include <Internal/Logger/LoggerImpl.hpp> #include <Utility/Utilities/Include/Logging/LogLevel.hpp> #include <Utility/Utilities/Include/Logging/LogTag.hpp> #include <Utility/Utilities/Include/Logging/LogTextData.hpp> #include <Utility/Utilities/Include/Logging/LogLevelConverter.hpp> #include <Utility/Utilities/Include/Logging/LogTagConverter.hpp> #include <Utility/Utilities/Include/Logging/HelpFunctions.hpp> #include <Utility/Utilities/Include/IO/FileMap/FileMap.hpp> #include <Utility/Utilities/Include/String/VA_ListToString.hpp> #include <Utility/Utilities/Include/String/StringHelper.hpp> #include <iostream> #include <algorithm> #include <chrono> #include <Windows.h> namespace DoremiEngine { namespace Logging { using namespace Doremi::Utilities; using namespace Doremi::Utilities::Logging; void threadWork(bool* p_applicationOnline, Memory::CircleBuffer<LogTextData>* p_localBuffer, Memory::CircleBuffer<LogTextData>* m_outGoingBuffer); LoggerImpl::LoggerImpl() : m_localBuffer(nullptr), m_outGoingBuffer(nullptr), m_fileMap(nullptr), m_mutex(nullptr), m_applicationRunning(nullptr) { m_uniqueId = GetCurrentProcessId(); Initialize(); } LoggerImpl::~LoggerImpl() { if(m_localBuffer != nullptr) { delete m_localBuffer; } if(m_outGoingBuffer != nullptr) { delete m_outGoingBuffer; } if(m_fileMap != nullptr) { delete m_fileMap; } if(m_mutex != nullptr) { delete m_mutex; } if(m_applicationRunning != nullptr) { delete m_applicationRunning; } } void LoggerImpl::Initialize() { m_localBuffer = new Memory::CircleBuffer<LogTextData>(); m_outGoingBuffer = new Memory::CircleBuffer<LogTextData>(); // TODORT // TODOXX // TODOCONFIG our hardcode better value from empirical tests // Create localbuffer m_localBuffer->Initialize(10000, nullptr); // Create mutex m_mutex = CreateFileMapMutex(); // Fetch shared memory from fileMap void* fileMapMemory = InitializeFileMap(Constants::IPC_FILEMAP_SIZE); // Intiailize outgoing buffer with shared memory and mutex m_outGoingBuffer->Initialize(fileMapMemory, Constants::IPC_FILEMAP_SIZE, m_mutex); m_applicationRunning = new bool(true); std::thread outGoingLoggingThread(threadWork, m_applicationRunning, m_localBuffer, m_outGoingBuffer); outGoingLoggingThread.detach(); #ifdef NO_LOGGER #else StartLoggingProcess(); #endif } void LoggerImpl::LT(const std::string& p_function, const size_t& p_line, const LogTag& p_logTag, const LogLevel& p_logLevel, const char* p_format, ...) { // Build a string from va_list va_list args; va_start(args, p_format); std::string message; String::toString(message, p_format, args); va_end(args); Logging::LogTextData data; // Function const std::size_t functionLength = p_function.copy(data.function, std::max(p_function.size(), Constants::LONGEST_FUNCTION_NAME), 0); data.function[functionLength] = '\0'; // Line data.line = p_line; // Message const std::size_t messageLength = message.copy(data.message, std::max(message.size(), Constants::LONGEST_FUNCTION_NAME), 0); data.message[messageLength] = '\0'; // Level and tag data.logLevel = p_logLevel; data.logTag = p_logTag; using namespace Memory; Memory::CircleBufferHeader header; header.packageSize = sizeof(LogTextData); header.packageType = CircleBufferType(CircleBufferTypeEnum::TEXT); bool succeed = false; #ifdef NO_LOGGER m_localBuffer->Produce(header, &data); #else while(!succeed) // TODORT Might not need while loop { succeed = m_localBuffer->Produce(header, &data); } #endif } void* LoggerImpl::InitializeFileMap(const std::size_t& p_size) { m_fileMap = new IO::FileMap(); void* memory = m_fileMap->Initialize(Logging::BuildFileMapName(m_uniqueId), p_size); if(memory != nullptr) { return memory; } else { throw std::runtime_error("Failed to initialize filemap."); } } IO::Mutex* LoggerImpl::CreateFileMapMutex() { IO::Mutex* mutex = new IO::FileMapMutex(); const bool success = mutex->Initialize(Constants::IPC_FILEMAP_MUTEX_NAME); if(success) { return mutex; } else { delete mutex; throw std::runtime_error("Failed to initialize filemap mutex."); } } std::wstring LoggerImpl::BuildLoggingProcessArgumentString() { const std::wstring applicationPathW = String::s2ws(Constants::LOGGING_PROCESS_NAME).c_str(); const std::wstring arguments = std::wstring(applicationPathW + std::wstring(L" ") + std::to_wstring(m_uniqueId)); return arguments; } void LoggerImpl::StartLoggingProcess() { PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; ZeroMemory(&processInformation, sizeof(PROCESS_INFORMATION)); ZeroMemory(&startupInfo, sizeof(STARTUPINFO)); startupInfo.cb = sizeof(STARTUPINFO); std::wstring& arguments = BuildLoggingProcessArgumentString(); if(!CreateProcess(NULL, &arguments[0], 0, 0, 0, CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT, 0, 0, &startupInfo, &processInformation)) { std::cout << GetLastError() << std::endl; throw std::runtime_error("Creating loggingprocess failed."); } CloseHandle(processInformation.hProcess); CloseHandle(processInformation.hThread); } void threadWork(bool* p_applicationOnline, Memory::CircleBuffer<LogTextData>* p_localBuffer, Memory::CircleBuffer<LogTextData>* m_outGoingBuffer) { bool messageExist = true; LogTextData* data = new LogTextData(); Memory::CircleBufferHeader* header = new Memory::CircleBufferHeader(); bool succeed = false; // As long as the application is running or if there are some messages ongoing while(*p_applicationOnline || messageExist) // TODORT, this might crash on crash.... { using namespace std::literals; messageExist = p_localBuffer->Consume(header, data); if(messageExist) { #ifdef NO_LOGGER m_outGoingBuffer->Produce(*header, data); #else succeed = false; while(!succeed) { succeed = m_outGoingBuffer->Produce(*header, data); } #endif } // std::this_thread::sleep_for(2s); } delete data; delete header; } } } <|endoftext|>
<commit_before>// @(#)root/roostats:$Id$ // Author: Kyle Cranmer 28/07/2008 /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ///////////////////////////////////////// // RooStats // // namespace for classes and functions of the RooStats package ///////////////////////////////////////// #include "Rtypes.h" #if !defined(R__SOLARIS) && !defined(R__ACC) && !defined(R__FBSD) NamespaceImp(RooStats) #endif #include "TTree.h" #include "RooUniform.h" #include "RooProdPdf.h" #include "RooExtendPdf.h" #include "RooSimultaneous.h" #include "RooStats/ModelConfig.h" #include "RooStats/RooStatsUtils.h" #include <typeinfo> using namespace std; // this file is only for the documentation of RooStats namespace namespace RooStats { void FactorizePdf(const RooArgSet &observables, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) { // utility function to factorize constraint terms from a pdf // (from G. Petrucciani) const std::type_info & id = typeid(pdf); if (id == typeid(RooProdPdf)) { RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf); RooArgList list(prod->pdfList()); for (int i = 0, n = list.getSize(); i < n; ++i) { RooAbsPdf *pdfi = (RooAbsPdf *) list.at(i); FactorizePdf(observables, *pdfi, obsTerms, constraints); } } else if (id == typeid(RooExtendPdf)) { TIterator *iter = pdf.serverIterator(); // extract underlying pdf which is extended; first server is the pdf; second server is the number of events variable RooAbsPdf *updf = dynamic_cast<RooAbsPdf *>(iter->Next()); assert(updf != 0); delete iter; FactorizePdf(observables, *updf, obsTerms, constraints); } else if (id == typeid(RooSimultaneous)) { //|| id == typeid(RooSimultaneousOpt)) { RooSimultaneous *sim = dynamic_cast<RooSimultaneous *>(&pdf); assert(sim != 0); RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().clone(sim->indexCat().GetName()); for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) { cat->setBin(ic); FactorizePdf(observables, *sim->getPdf(cat->getLabel()), obsTerms, constraints); } delete cat; } else if (pdf.dependsOn(observables)) { if (!obsTerms.contains(pdf)) obsTerms.add(pdf); } else { if (!constraints.contains(pdf)) constraints.add(pdf); } } void FactorizePdf(RooStats::ModelConfig &model, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) { // utility function to factorize constraint terms from a pdf // (from G. Petrucciani) if (!model.GetObservables() ) { oocoutE((TObject*)0,InputArguments) << "RooStatsUtils::FactorizePdf - invalid input model: missing observables" << endl; return; } return FactorizePdf(*model.GetObservables(), pdf, obsTerms, constraints); } RooAbsPdf * MakeNuisancePdf(RooAbsPdf &pdf, const RooArgSet &observables, const char *name) { // make a nuisance pdf by factorizing out all constraint terms in a common pdf RooArgList obsTerms, constraints; FactorizePdf(observables, pdf, obsTerms, constraints); if(constraints.getSize() == 0) { oocoutW((TObject *)0, Eval) << "RooStatsUtils::MakeNuisancePdf - no constraints found on nuisance parameters in the input model" << endl; return 0; } else if(constraints.getSize() == 1) { return dynamic_cast<RooAbsPdf *>(constraints.first()->clone(name)); } return new RooProdPdf(name,"", constraints); } RooAbsPdf * MakeNuisancePdf(const RooStats::ModelConfig &model, const char *name) { // make a nuisance pdf by factorizing out all constraint terms in a common pdf if (!model.GetPdf() || !model.GetObservables() ) { oocoutE((TObject*)0, InputArguments) << "RooStatsUtils::MakeNuisancePdf - invalid input model: missing pdf and/or observables" << endl; return 0; } return MakeNuisancePdf(*model.GetPdf(), *model.GetObservables(), name); } RooAbsPdf * StripConstraints(RooAbsPdf &pdf, const RooArgSet &observables) { const std::type_info & id = typeid(pdf); if (id == typeid(RooProdPdf)) { RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf); RooArgList list(prod->pdfList()); RooArgList newList; for (int i = 0, n = list.getSize(); i < n; ++i) { RooAbsPdf *pdfi = (RooAbsPdf *) list.at(i); RooAbsPdf *newPdfi = StripConstraints(*pdfi, observables); if(newPdfi != NULL) newList.add(*newPdfi); } if(newList.getSize() == 0) return NULL; // only constraints in product // return single component (no longer a product) else if(newList.getSize() == 1) return dynamic_cast<RooAbsPdf *>(newList.at(0)->clone(TString::Format("%s_unconstrained", newList.at(0)->GetName()))); else return new RooProdPdf(TString::Format("%s_unconstrained", prod->GetName()).Data(), TString::Format("%s without constraints", prod->GetTitle()).Data(), newList); } else if (id == typeid(RooExtendPdf)) { TIterator *iter = pdf.serverIterator(); // extract underlying pdf which is extended; first server is the pdf; second server is the number of events variable RooAbsPdf *uPdf = dynamic_cast<RooAbsPdf *>(iter->Next()); RooAbsReal *extended_term = dynamic_cast<RooAbsReal *>(iter->Next()); assert(uPdf != NULL); assert(extended_term != NULL); assert(iter->Next() == NULL); delete iter; RooAbsPdf *newUPdf = StripConstraints(*uPdf, observables); if(newUPdf == NULL) return NULL; // only constraints in underlying pdf else return new RooExtendPdf(TString::Format("%s_unconstrained", pdf.GetName()).Data(), TString::Format("%s without constraints", pdf.GetTitle()).Data(), *newUPdf, *extended_term); } else if (id == typeid(RooSimultaneous)) { //|| id == typeid(RooSimultaneousOpt)) { RooSimultaneous *sim = dynamic_cast<RooSimultaneous *>(&pdf); assert(sim != NULL); RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().Clone(); assert(cat != NULL); RooArgList pdfList; for (int ic = 0, nc = cat->numBins((const char *)NULL); ic < nc; ++ic) { cat->setBin(ic); RooAbsPdf *newPdf = StripConstraints(*sim->getPdf(cat->getLabel()), observables); if(newPdf == NULL) { delete cat; return NULL; } // all channels must have observables pdfList.add(*newPdf); } return new RooSimultaneous(TString::Format("%s_unconstrained", sim->GetName()).Data(), TString::Format("%s without constraints", sim->GetTitle()).Data(), pdfList, *cat); } else if (pdf.dependsOn(observables)) { return (RooAbsPdf *) pdf.clone(TString::Format("%s_unconstrained", pdf.GetName()).Data()); } return 0; // just a constraint term } RooAbsPdf * MakeUnconstrainedPdf(RooAbsPdf &pdf, const RooArgSet &observables, const char *name) { // make a clone pdf without all constraint terms in a common pdf RooAbsPdf * unconstrainedPdf = StripConstraints(pdf, observables); if(!unconstrainedPdf) { oocoutE((TObject *)NULL, InputArguments) << "RooStats::MakeUnconstrainedPdf - invalid observable list passed (observables not found in original pdf) or invalid pdf passed (without observables)" << endl; return NULL; } if(name != NULL) unconstrainedPdf->SetName(name); return unconstrainedPdf; } RooAbsPdf * MakeUnconstrainedPdf(const RooStats::ModelConfig &model, const char *name) { // make a clone pdf without all constraint terms in a common pdf if(!model.GetPdf() || !model.GetObservables()) { oocoutE((TObject *)NULL, InputArguments) << "RooStatsUtils::MakeUnconstrainedPdf - invalid input model: missing pdf and/or observables" << endl; return NULL; } return MakeUnconstrainedPdf(*model.GetPdf(), *model.GetObservables(), name); } // Helper class for GetAsTTree class BranchStore { public: std::map<TString, Double_t> varVals; double inval; BranchStore(const vector <TString> &params = vector <TString>(), double _inval = -999.) { inval = _inval; for(unsigned int i = 0;i<params.size();i++) varVals[params[i]] = _inval; } void AssignToTTree(TTree &myTree) { for(std::map<TString, Double_t>::iterator it = varVals.begin();it!=varVals.end();it++) { const TString& name = it->first; myTree.Branch( name, &varVals[name], TString::Format("%s/D", name.Data())); } } void ResetValues() { for(std::map<TString, Double_t>::iterator it = varVals.begin();it!=varVals.end();it++) { const TString& name = it->first; varVals[name] = inval; } } }; BranchStore* CreateBranchStore(const RooDataSet& data) { if (data.numEntries() == 0) { return new BranchStore; } vector <TString> V; const RooArgSet* aset = data.get(0); RooAbsArg *arg(0); TIterator *it = aset->createIterator(); for(;(arg = dynamic_cast<RooAbsArg*>(it->Next()));) { RooRealVar *rvar = dynamic_cast<RooRealVar*>(arg); if (rvar == NULL) continue; V.push_back(rvar->GetName()); if (rvar->hasAsymError()) { V.push_back(TString::Format("%s_errlo", rvar->GetName())); V.push_back(TString::Format("%s_errhi", rvar->GetName())); } else if (rvar->hasError()) { V.push_back(TString::Format("%s_err", rvar->GetName())); } } delete it; return new BranchStore(V); } void FillTree(TTree &myTree, const RooDataSet &data) { BranchStore *bs = CreateBranchStore(data); bs->AssignToTTree(myTree); for(int entry = 0;entry<data.numEntries();entry++) { bs->ResetValues(); const RooArgSet* aset = data.get(entry); RooAbsArg *arg(0); RooLinkedListIter it = aset->iterator(); for(;(arg = dynamic_cast<RooAbsArg*>(it.Next()));) { RooRealVar *rvar = dynamic_cast<RooRealVar*>(arg); if (rvar == NULL) continue; bs->varVals[rvar->GetName()] = rvar->getValV(); if (rvar->hasAsymError()) { bs->varVals[TString::Format("%s_errlo", rvar->GetName())] = rvar->getAsymErrorLo(); bs->varVals[TString::Format("%s_errhi", rvar->GetName())] = rvar->getAsymErrorHi(); } else if (rvar->hasError()) { bs->varVals[TString::Format("%s_err", rvar->GetName())] = rvar->getError(); } } myTree.Fill(); } delete bs; } TTree * GetAsTTree(TString name, TString desc, const RooDataSet& data) { TTree* myTree = new TTree(name, desc); FillTree(*myTree, data); return myTree; } } <commit_msg>from Gabriel: fix a crash in FactorizePdf when some categories are missing see http://root.cern.ch/phpBB3/viewtopic.php?f=15&t=15694<commit_after>// @(#)root/roostats:$Id$ // Author: Kyle Cranmer 28/07/2008 /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ///////////////////////////////////////// // RooStats // // namespace for classes and functions of the RooStats package ///////////////////////////////////////// #include "Rtypes.h" #if !defined(R__SOLARIS) && !defined(R__ACC) && !defined(R__FBSD) NamespaceImp(RooStats) #endif #include "TTree.h" #include "RooUniform.h" #include "RooProdPdf.h" #include "RooExtendPdf.h" #include "RooSimultaneous.h" #include "RooStats/ModelConfig.h" #include "RooStats/RooStatsUtils.h" #include <typeinfo> using namespace std; // this file is only for the documentation of RooStats namespace namespace RooStats { void FactorizePdf(const RooArgSet &observables, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) { // utility function to factorize constraint terms from a pdf // (from G. Petrucciani) const std::type_info & id = typeid(pdf); if (id == typeid(RooProdPdf)) { RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf); RooArgList list(prod->pdfList()); for (int i = 0, n = list.getSize(); i < n; ++i) { RooAbsPdf *pdfi = (RooAbsPdf *) list.at(i); FactorizePdf(observables, *pdfi, obsTerms, constraints); } } else if (id == typeid(RooExtendPdf)) { TIterator *iter = pdf.serverIterator(); // extract underlying pdf which is extended; first server is the pdf; second server is the number of events variable RooAbsPdf *updf = dynamic_cast<RooAbsPdf *>(iter->Next()); assert(updf != 0); delete iter; FactorizePdf(observables, *updf, obsTerms, constraints); } else if (id == typeid(RooSimultaneous)) { //|| id == typeid(RooSimultaneousOpt)) { RooSimultaneous *sim = dynamic_cast<RooSimultaneous *>(&pdf); assert(sim != 0); RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().clone(sim->indexCat().GetName()); for (int ic = 0, nc = cat->numBins((const char *)0); ic < nc; ++ic) { cat->setBin(ic); RooAbsPdf* catPdf = sim->getPdf(cat->getLabel()); // it is possible that a pdf is not defined for every category if (catPdf != 0) FactorizePdf(observables, *catPdf, obsTerms, constraints); } delete cat; } else if (pdf.dependsOn(observables)) { if (!obsTerms.contains(pdf)) obsTerms.add(pdf); } else { if (!constraints.contains(pdf)) constraints.add(pdf); } } void FactorizePdf(RooStats::ModelConfig &model, RooAbsPdf &pdf, RooArgList &obsTerms, RooArgList &constraints) { // utility function to factorize constraint terms from a pdf // (from G. Petrucciani) if (!model.GetObservables() ) { oocoutE((TObject*)0,InputArguments) << "RooStatsUtils::FactorizePdf - invalid input model: missing observables" << endl; return; } return FactorizePdf(*model.GetObservables(), pdf, obsTerms, constraints); } RooAbsPdf * MakeNuisancePdf(RooAbsPdf &pdf, const RooArgSet &observables, const char *name) { // make a nuisance pdf by factorizing out all constraint terms in a common pdf RooArgList obsTerms, constraints; FactorizePdf(observables, pdf, obsTerms, constraints); if(constraints.getSize() == 0) { oocoutW((TObject *)0, Eval) << "RooStatsUtils::MakeNuisancePdf - no constraints found on nuisance parameters in the input model" << endl; return 0; } else if(constraints.getSize() == 1) { return dynamic_cast<RooAbsPdf *>(constraints.first()->clone(name)); } return new RooProdPdf(name,"", constraints); } RooAbsPdf * MakeNuisancePdf(const RooStats::ModelConfig &model, const char *name) { // make a nuisance pdf by factorizing out all constraint terms in a common pdf if (!model.GetPdf() || !model.GetObservables() ) { oocoutE((TObject*)0, InputArguments) << "RooStatsUtils::MakeNuisancePdf - invalid input model: missing pdf and/or observables" << endl; return 0; } return MakeNuisancePdf(*model.GetPdf(), *model.GetObservables(), name); } RooAbsPdf * StripConstraints(RooAbsPdf &pdf, const RooArgSet &observables) { const std::type_info & id = typeid(pdf); if (id == typeid(RooProdPdf)) { RooProdPdf *prod = dynamic_cast<RooProdPdf *>(&pdf); RooArgList list(prod->pdfList()); RooArgList newList; for (int i = 0, n = list.getSize(); i < n; ++i) { RooAbsPdf *pdfi = (RooAbsPdf *) list.at(i); RooAbsPdf *newPdfi = StripConstraints(*pdfi, observables); if(newPdfi != NULL) newList.add(*newPdfi); } if(newList.getSize() == 0) return NULL; // only constraints in product // return single component (no longer a product) else if(newList.getSize() == 1) return dynamic_cast<RooAbsPdf *>(newList.at(0)->clone(TString::Format("%s_unconstrained", newList.at(0)->GetName()))); else return new RooProdPdf(TString::Format("%s_unconstrained", prod->GetName()).Data(), TString::Format("%s without constraints", prod->GetTitle()).Data(), newList); } else if (id == typeid(RooExtendPdf)) { TIterator *iter = pdf.serverIterator(); // extract underlying pdf which is extended; first server is the pdf; second server is the number of events variable RooAbsPdf *uPdf = dynamic_cast<RooAbsPdf *>(iter->Next()); RooAbsReal *extended_term = dynamic_cast<RooAbsReal *>(iter->Next()); assert(uPdf != NULL); assert(extended_term != NULL); assert(iter->Next() == NULL); delete iter; RooAbsPdf *newUPdf = StripConstraints(*uPdf, observables); if(newUPdf == NULL) return NULL; // only constraints in underlying pdf else return new RooExtendPdf(TString::Format("%s_unconstrained", pdf.GetName()).Data(), TString::Format("%s without constraints", pdf.GetTitle()).Data(), *newUPdf, *extended_term); } else if (id == typeid(RooSimultaneous)) { //|| id == typeid(RooSimultaneousOpt)) { RooSimultaneous *sim = dynamic_cast<RooSimultaneous *>(&pdf); assert(sim != NULL); RooAbsCategoryLValue *cat = (RooAbsCategoryLValue *) sim->indexCat().Clone(); assert(cat != NULL); RooArgList pdfList; for (int ic = 0, nc = cat->numBins((const char *)NULL); ic < nc; ++ic) { cat->setBin(ic); RooAbsPdf* catPdf = sim->getPdf(cat->getLabel()); RooAbsPdf* newPdf = NULL; // it is possible that a pdf is not defined for every category if (catPdf != NULL) newPdf = StripConstraints(*catPdf, observables); if (newPdf == NULL) { delete cat; return NULL; } // all channels must have observables pdfList.add(*newPdf); } return new RooSimultaneous(TString::Format("%s_unconstrained", sim->GetName()).Data(), TString::Format("%s without constraints", sim->GetTitle()).Data(), pdfList, *cat); } else if (pdf.dependsOn(observables)) { return (RooAbsPdf *) pdf.clone(TString::Format("%s_unconstrained", pdf.GetName()).Data()); } return NULL; // just a constraint term } RooAbsPdf * MakeUnconstrainedPdf(RooAbsPdf &pdf, const RooArgSet &observables, const char *name) { // make a clone pdf without all constraint terms in a common pdf RooAbsPdf * unconstrainedPdf = StripConstraints(pdf, observables); if(!unconstrainedPdf) { oocoutE((TObject *)NULL, InputArguments) << "RooStats::MakeUnconstrainedPdf - invalid observable list passed (observables not found in original pdf) or invalid pdf passed (without observables)" << endl; return NULL; } if(name != NULL) unconstrainedPdf->SetName(name); return unconstrainedPdf; } RooAbsPdf * MakeUnconstrainedPdf(const RooStats::ModelConfig &model, const char *name) { // make a clone pdf without all constraint terms in a common pdf if(!model.GetPdf() || !model.GetObservables()) { oocoutE((TObject *)NULL, InputArguments) << "RooStatsUtils::MakeUnconstrainedPdf - invalid input model: missing pdf and/or observables" << endl; return NULL; } return MakeUnconstrainedPdf(*model.GetPdf(), *model.GetObservables(), name); } // Helper class for GetAsTTree class BranchStore { public: std::map<TString, Double_t> varVals; double inval; BranchStore(const vector <TString> &params = vector <TString>(), double _inval = -999.) { inval = _inval; for(unsigned int i = 0;i<params.size();i++) varVals[params[i]] = _inval; } void AssignToTTree(TTree &myTree) { for(std::map<TString, Double_t>::iterator it = varVals.begin();it!=varVals.end();it++) { const TString& name = it->first; myTree.Branch( name, &varVals[name], TString::Format("%s/D", name.Data())); } } void ResetValues() { for(std::map<TString, Double_t>::iterator it = varVals.begin();it!=varVals.end();it++) { const TString& name = it->first; varVals[name] = inval; } } }; BranchStore* CreateBranchStore(const RooDataSet& data) { if (data.numEntries() == 0) { return new BranchStore; } vector <TString> V; const RooArgSet* aset = data.get(0); RooAbsArg *arg(0); TIterator *it = aset->createIterator(); for(;(arg = dynamic_cast<RooAbsArg*>(it->Next()));) { RooRealVar *rvar = dynamic_cast<RooRealVar*>(arg); if (rvar == NULL) continue; V.push_back(rvar->GetName()); if (rvar->hasAsymError()) { V.push_back(TString::Format("%s_errlo", rvar->GetName())); V.push_back(TString::Format("%s_errhi", rvar->GetName())); } else if (rvar->hasError()) { V.push_back(TString::Format("%s_err", rvar->GetName())); } } delete it; return new BranchStore(V); } void FillTree(TTree &myTree, const RooDataSet &data) { BranchStore *bs = CreateBranchStore(data); bs->AssignToTTree(myTree); for(int entry = 0;entry<data.numEntries();entry++) { bs->ResetValues(); const RooArgSet* aset = data.get(entry); RooAbsArg *arg(0); RooLinkedListIter it = aset->iterator(); for(;(arg = dynamic_cast<RooAbsArg*>(it.Next()));) { RooRealVar *rvar = dynamic_cast<RooRealVar*>(arg); if (rvar == NULL) continue; bs->varVals[rvar->GetName()] = rvar->getValV(); if (rvar->hasAsymError()) { bs->varVals[TString::Format("%s_errlo", rvar->GetName())] = rvar->getAsymErrorLo(); bs->varVals[TString::Format("%s_errhi", rvar->GetName())] = rvar->getAsymErrorHi(); } else if (rvar->hasError()) { bs->varVals[TString::Format("%s_err", rvar->GetName())] = rvar->getError(); } } myTree.Fill(); } delete bs; } TTree * GetAsTTree(TString name, TString desc, const RooDataSet& data) { TTree* myTree = new TTree(name, desc); FillTree(*myTree, data); return myTree; } } <|endoftext|>
<commit_before><commit_msg>WaE: unused variable 'aText'<commit_after><|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2021, Julien Coupey. All rights reserved (see LICENSE). */ #include <mutex> #include <thread> #include "algorithms/heuristics/heuristics.h" #include "algorithms/local_search/local_search.h" #include "problems/cvrp/cvrp.h" #include "problems/cvrp/operators/cross_exchange.h" #include "problems/cvrp/operators/intra_cross_exchange.h" #include "problems/cvrp/operators/intra_exchange.h" #include "problems/cvrp/operators/intra_mixed_exchange.h" #include "problems/cvrp/operators/intra_or_opt.h" #include "problems/cvrp/operators/intra_relocate.h" #include "problems/cvrp/operators/mixed_exchange.h" #include "problems/cvrp/operators/or_opt.h" #include "problems/cvrp/operators/pd_shift.h" #include "problems/cvrp/operators/relocate.h" #include "problems/cvrp/operators/reverse_two_opt.h" #include "problems/cvrp/operators/route_exchange.h" #include "problems/cvrp/operators/swap_star.h" #include "problems/cvrp/operators/two_opt.h" #include "problems/cvrp/operators/unassigned_exchange.h" #include "problems/tsp/tsp.h" #include "utils/helpers.h" namespace vroom { using RawSolution = std::vector<RawRoute>; using LocalSearch = ls::LocalSearch<RawRoute, cvrp::UnassignedExchange, cvrp::SwapStar, cvrp::CrossExchange, cvrp::MixedExchange, cvrp::TwoOpt, cvrp::ReverseTwoOpt, cvrp::Relocate, cvrp::OrOpt, cvrp::IntraExchange, cvrp::IntraCrossExchange, cvrp::IntraMixedExchange, cvrp::IntraRelocate, cvrp::IntraOrOpt, cvrp::PDShift, cvrp::RouteExchange>; const std::vector<HeuristicParameters> CVRP::homogeneous_parameters = {HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.7), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.1), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.6), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.9), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.4), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.8), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.1), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 2.4), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.9), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.5), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.5), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.6), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5)}; const std::vector<HeuristicParameters> CVRP::heterogeneous_parameters = {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 2.2)}; CVRP::CVRP(const Input& input) : VRP(input) { } Solution CVRP::solve(unsigned exploration_level, unsigned nb_threads, const Timeout& timeout, const std::vector<HeuristicParameters>& h_param) const { if (_input.vehicles.size() == 1 and !_input.has_skills() and _input.zero_amount().size() == 0 and !_input.has_shipments()) { // This is a plain TSP, no need to go through the trouble below. std::vector<Index> job_ranks(_input.jobs.size()); std::iota(job_ranks.begin(), job_ranks.end(), 0); TSP p(_input, job_ranks, 0); RawRoute r(_input, 0); r.set_route(_input, p.raw_solve(nb_threads, timeout)); return utils::format_solution(_input, {r}); } // Use vector of parameters when passed for debugging, else use // predefined parameter set. const auto& parameters = (!h_param.empty()) ? h_param : (_input.has_homogeneous_locations()) ? homogeneous_parameters : heterogeneous_parameters; unsigned max_nb_jobs_removal = exploration_level; unsigned nb_init_solutions = h_param.size(); if (nb_init_solutions == 0) { // Local search parameter. nb_init_solutions = 4 * (exploration_level + 1); if (exploration_level >= 4) { nb_init_solutions += 4; } if (exploration_level >= 5) { nb_init_solutions += 4; } } assert(nb_init_solutions <= parameters.size()); std::vector<RawSolution> solutions(nb_init_solutions); std::vector<utils::SolutionIndicators> sol_indicators(nb_init_solutions); // Split the work among threads. std::vector<std::vector<std::size_t>> thread_ranks(nb_threads, std::vector<std::size_t>()); for (std::size_t i = 0; i < nb_init_solutions; ++i) { thread_ranks[i % nb_threads].push_back(i); } std::exception_ptr ep = nullptr; std::mutex ep_m; auto run_solve = [&](const std::vector<std::size_t>& param_ranks) { try { // Decide time allocated for each search. Timeout search_time; if (timeout.has_value()) { search_time = timeout.value() / param_ranks.size(); } for (auto rank : param_ranks) { auto& p = parameters[rank]; switch (p.heuristic) { case HEURISTIC::BASIC: solutions[rank] = heuristics::basic<RawSolution>(_input, p.init, p.regret_coeff); break; case HEURISTIC::DYNAMIC: solutions[rank] = heuristics::dynamic_vehicle_choice<RawSolution>(_input, p.init, p.regret_coeff); break; } // Local search phase. LocalSearch ls(_input, solutions[rank], max_nb_jobs_removal, search_time); ls.run(); // Store solution indicators. sol_indicators[rank] = ls.indicators(); } } catch (...) { ep_m.lock(); ep = std::current_exception(); ep_m.unlock(); } }; std::vector<std::thread> solving_threads; for (const auto& param_ranks : thread_ranks) { solving_threads.emplace_back(run_solve, param_ranks); } for (auto& t : solving_threads) { t.join(); } if (ep != nullptr) { std::rethrow_exception(ep); } auto best_indic = std::min_element(sol_indicators.cbegin(), sol_indicators.cend()); return utils::format_solution(_input, solutions[std::distance(sol_indicators.cbegin(), best_indic)]); } } // namespace vroom <commit_msg>Do not solve a TSP with max_tasks binding constraint, fixes #603<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2021, Julien Coupey. All rights reserved (see LICENSE). */ #include <mutex> #include <thread> #include "algorithms/heuristics/heuristics.h" #include "algorithms/local_search/local_search.h" #include "problems/cvrp/cvrp.h" #include "problems/cvrp/operators/cross_exchange.h" #include "problems/cvrp/operators/intra_cross_exchange.h" #include "problems/cvrp/operators/intra_exchange.h" #include "problems/cvrp/operators/intra_mixed_exchange.h" #include "problems/cvrp/operators/intra_or_opt.h" #include "problems/cvrp/operators/intra_relocate.h" #include "problems/cvrp/operators/mixed_exchange.h" #include "problems/cvrp/operators/or_opt.h" #include "problems/cvrp/operators/pd_shift.h" #include "problems/cvrp/operators/relocate.h" #include "problems/cvrp/operators/reverse_two_opt.h" #include "problems/cvrp/operators/route_exchange.h" #include "problems/cvrp/operators/swap_star.h" #include "problems/cvrp/operators/two_opt.h" #include "problems/cvrp/operators/unassigned_exchange.h" #include "problems/tsp/tsp.h" #include "utils/helpers.h" namespace vroom { using RawSolution = std::vector<RawRoute>; using LocalSearch = ls::LocalSearch<RawRoute, cvrp::UnassignedExchange, cvrp::SwapStar, cvrp::CrossExchange, cvrp::MixedExchange, cvrp::TwoOpt, cvrp::ReverseTwoOpt, cvrp::Relocate, cvrp::OrOpt, cvrp::IntraExchange, cvrp::IntraCrossExchange, cvrp::IntraMixedExchange, cvrp::IntraRelocate, cvrp::IntraOrOpt, cvrp::PDShift, cvrp::RouteExchange>; const std::vector<HeuristicParameters> CVRP::homogeneous_parameters = {HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.7), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.1), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.6), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.9), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 2.4), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.8), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.2), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.1), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 2.4), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.2), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.9), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 1.5), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.5), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.3), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 1.5), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 0.4), HeuristicParameters(HEURISTIC::BASIC, INIT::NONE, 1.6), HeuristicParameters(HEURISTIC::BASIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::BASIC, INIT::FURTHEST, 0.5)}; const std::vector<HeuristicParameters> CVRP::heterogeneous_parameters = {HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.9), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.3), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 2.1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.8), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.4), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.6), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 0.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1.2), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 0.5), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::NONE, 0.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::HIGHER_AMOUNT, 1), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 1.7), HeuristicParameters(HEURISTIC::DYNAMIC, INIT::FURTHEST, 2.2)}; CVRP::CVRP(const Input& input) : VRP(input) { } Solution CVRP::solve(unsigned exploration_level, unsigned nb_threads, const Timeout& timeout, const std::vector<HeuristicParameters>& h_param) const { if (_input.vehicles.size() == 1 and !_input.has_skills() and _input.zero_amount().size() == 0 and !_input.has_shipments() and (_input.jobs.size() <= _input.vehicles[0].max_tasks)) { // This is a plain TSP, no need to go through the trouble below. std::vector<Index> job_ranks(_input.jobs.size()); std::iota(job_ranks.begin(), job_ranks.end(), 0); TSP p(_input, job_ranks, 0); RawRoute r(_input, 0); r.set_route(_input, p.raw_solve(nb_threads, timeout)); return utils::format_solution(_input, {r}); } // Use vector of parameters when passed for debugging, else use // predefined parameter set. const auto& parameters = (!h_param.empty()) ? h_param : (_input.has_homogeneous_locations()) ? homogeneous_parameters : heterogeneous_parameters; unsigned max_nb_jobs_removal = exploration_level; unsigned nb_init_solutions = h_param.size(); if (nb_init_solutions == 0) { // Local search parameter. nb_init_solutions = 4 * (exploration_level + 1); if (exploration_level >= 4) { nb_init_solutions += 4; } if (exploration_level >= 5) { nb_init_solutions += 4; } } assert(nb_init_solutions <= parameters.size()); std::vector<RawSolution> solutions(nb_init_solutions); std::vector<utils::SolutionIndicators> sol_indicators(nb_init_solutions); // Split the work among threads. std::vector<std::vector<std::size_t>> thread_ranks(nb_threads, std::vector<std::size_t>()); for (std::size_t i = 0; i < nb_init_solutions; ++i) { thread_ranks[i % nb_threads].push_back(i); } std::exception_ptr ep = nullptr; std::mutex ep_m; auto run_solve = [&](const std::vector<std::size_t>& param_ranks) { try { // Decide time allocated for each search. Timeout search_time; if (timeout.has_value()) { search_time = timeout.value() / param_ranks.size(); } for (auto rank : param_ranks) { auto& p = parameters[rank]; switch (p.heuristic) { case HEURISTIC::BASIC: solutions[rank] = heuristics::basic<RawSolution>(_input, p.init, p.regret_coeff); break; case HEURISTIC::DYNAMIC: solutions[rank] = heuristics::dynamic_vehicle_choice<RawSolution>(_input, p.init, p.regret_coeff); break; } // Local search phase. LocalSearch ls(_input, solutions[rank], max_nb_jobs_removal, search_time); ls.run(); // Store solution indicators. sol_indicators[rank] = ls.indicators(); } } catch (...) { ep_m.lock(); ep = std::current_exception(); ep_m.unlock(); } }; std::vector<std::thread> solving_threads; for (const auto& param_ranks : thread_ranks) { solving_threads.emplace_back(run_solve, param_ranks); } for (auto& t : solving_threads) { t.join(); } if (ep != nullptr) { std::rethrow_exception(ep); } auto best_indic = std::min_element(sol_indicators.cbegin(), sol_indicators.cend()); return utils::format_solution(_input, solutions[std::distance(sol_indicators.cbegin(), best_indic)]); } } // namespace vroom <|endoftext|>
<commit_before>/* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #pragma once #ifndef _QI_CLOCK_HPP_ #define _QI_CLOCK_HPP_ #include <qi/api.hpp> #include <qi/types.hpp> #include <boost/chrono.hpp> namespace qi { typedef boost::chrono::duration<int64_t, boost::nano> Duration; typedef boost::chrono::duration<int64_t, boost::nano> NanoSeconds; typedef boost::chrono::duration<int64_t, boost::micro> MicroSeconds; typedef boost::chrono::duration<int64_t, boost::milli> MilliSeconds; typedef boost::chrono::duration<int64_t> Seconds; typedef boost::chrono::duration<int64_t, boost::ratio<60> > Minutes; typedef boost::chrono::duration<int64_t, boost::ratio<3600> > Hours; class QI_API SteadyClock { public: typedef int64_t rep; typedef boost::nano period; // clock counts nanoseconds typedef boost::chrono::duration<rep, period> duration; typedef boost::chrono::time_point<SteadyClock> time_point; BOOST_STATIC_CONSTEXPR bool is_steady = boost::chrono::steady_clock::is_steady; public: typedef boost::chrono::time_point<SteadyClock> SteadyClockTimePoint; enum Expect { Expect_SoonerOrLater, Expect_Later, Expect_Sooner }; // Returns a time_point representing the current value of the clock. static SteadyClockTimePoint now(); // Convert the time point to a number of milliseconds on 32 bits. // Since the 32 bits number overflows every 2^32 ms ~ 50 days, // this is a lossy operation. static uint32_t toUint32ms(const SteadyClockTimePoint &t) throw(); static int32_t toInt32ms(const SteadyClockTimePoint &t) throw(); // Get a time point from a number of milliseconds on 32 bits. // // Since the 32 bits number overflows every ~50 days, an infinity of // time points match a given 32 bits number (all modulo ~50 days). // This function picks the result near the guess timepoint depending on // the expect argument: // // if expect == LATER, result is expected to be later than guess: // // guess <= result < guess + period // // if expect == SOONER, result is expected to be sooner than guess: // // guess - period < result <= guess // // if expect == SOONER_OR_LATER, pick the nearest result: // // guess - period/2 < result <= guess + period/2 // // where period == 2^32 ms ~ 50 days static time_point fromUint32ms(uint32_t t_ms, SteadyClockTimePoint guess, Expect expect=Expect_SoonerOrLater) throw(); static time_point fromInt32ms(int32_t t_ms, SteadyClockTimePoint guess, Expect expect=Expect_SoonerOrLater) throw(); }; class QI_API WallClock { public: typedef int64_t rep; typedef boost::nano period; // clock counts nanoseconds typedef boost::chrono::duration<rep, period> duration; typedef boost::chrono::time_point<WallClock> time_point; BOOST_STATIC_CONSTEXPR bool is_steady = false; public: typedef boost::chrono::time_point<WallClock> WallClockTimePoint; // Returns a time_point representing the current value of the clock. static WallClockTimePoint now(); // Converts a system clock time point to std::time_t static std::time_t to_time_t(const WallClockTimePoint& t) throw(); // Converts std::time_t to a system clock time point static WallClockTimePoint from_time_t(const std::time_t &t) throw(); }; typedef SteadyClock::SteadyClockTimePoint SteadyClockTimePoint; typedef WallClock::WallClockTimePoint WallClockTimePoint; inline SteadyClockTimePoint steadyClockNow() { return SteadyClock::now(); } inline WallClockTimePoint wallClockNow() { return WallClock::now(); } // Blocks the execution of the current thread for at least d. QI_API void sleepFor(const qi::Duration& d); template <class Rep, class Period> inline void sleepFor(const boost::chrono::duration<Rep, Period>& d); // Blocks the execution of the current thread until t has been // reached. // // This is equivalent to sleep_for(t-steady_clock::now()) QI_API void sleepUntil(const SteadyClockTimePoint &t); template <class Duration> inline void sleepUntil(const boost::chrono::time_point<SteadyClock, Duration>& t); // Blocks the execution of the current thread until t has been // reached. // Adjustments of the clock are taken into account. // Thus the duration of the block might, but might not, be less // or more than t - system_clock::now() QI_API void sleepUntil(const WallClockTimePoint& t); template <class Duration> inline void sleepUntil(const boost::chrono::time_point<WallClock, Duration>& t); } #include <qi/clock.hxx> #endif // _QI_OS_HPP_ <commit_msg>clock: export template instanciation for use by qitype<commit_after>/* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #pragma once #ifndef _QI_CLOCK_HPP_ #define _QI_CLOCK_HPP_ #include <qi/api.hpp> #include <qi/types.hpp> #include <boost/chrono.hpp> namespace qi { typedef boost::chrono::duration<int64_t, boost::nano> Duration; typedef boost::chrono::duration<int64_t, boost::nano> NanoSeconds; typedef boost::chrono::duration<int64_t, boost::micro> MicroSeconds; typedef boost::chrono::duration<int64_t, boost::milli> MilliSeconds; typedef boost::chrono::duration<int64_t> Seconds; typedef boost::chrono::duration<int64_t, boost::ratio<60> > Minutes; typedef boost::chrono::duration<int64_t, boost::ratio<3600> > Hours; class QI_API SteadyClock { public: typedef int64_t rep; typedef boost::nano period; // clock counts nanoseconds typedef boost::chrono::duration<rep, period> duration; typedef boost::chrono::time_point<SteadyClock> time_point; BOOST_STATIC_CONSTEXPR bool is_steady = boost::chrono::steady_clock::is_steady; public: typedef boost::chrono::time_point<SteadyClock> SteadyClockTimePoint; enum Expect { Expect_SoonerOrLater, Expect_Later, Expect_Sooner }; // Returns a time_point representing the current value of the clock. static SteadyClockTimePoint now(); // Convert the time point to a number of milliseconds on 32 bits. // Since the 32 bits number overflows every 2^32 ms ~ 50 days, // this is a lossy operation. static uint32_t toUint32ms(const SteadyClockTimePoint &t) throw(); static int32_t toInt32ms(const SteadyClockTimePoint &t) throw(); // Get a time point from a number of milliseconds on 32 bits. // // Since the 32 bits number overflows every ~50 days, an infinity of // time points match a given 32 bits number (all modulo ~50 days). // This function picks the result near the guess timepoint depending on // the expect argument: // // if expect == LATER, result is expected to be later than guess: // // guess <= result < guess + period // // if expect == SOONER, result is expected to be sooner than guess: // // guess - period < result <= guess // // if expect == SOONER_OR_LATER, pick the nearest result: // // guess - period/2 < result <= guess + period/2 // // where period == 2^32 ms ~ 50 days static time_point fromUint32ms(uint32_t t_ms, SteadyClockTimePoint guess, Expect expect=Expect_SoonerOrLater) throw(); static time_point fromInt32ms(int32_t t_ms, SteadyClockTimePoint guess, Expect expect=Expect_SoonerOrLater) throw(); }; class QI_API WallClock { public: typedef int64_t rep; typedef boost::nano period; // clock counts nanoseconds typedef boost::chrono::duration<rep, period> duration; typedef boost::chrono::time_point<WallClock> time_point; BOOST_STATIC_CONSTEXPR bool is_steady = false; public: typedef boost::chrono::time_point<WallClock> WallClockTimePoint; // Returns a time_point representing the current value of the clock. static WallClockTimePoint now(); // Converts a system clock time point to std::time_t static std::time_t to_time_t(const WallClockTimePoint& t) throw(); // Converts std::time_t to a system clock time point static WallClockTimePoint from_time_t(const std::time_t &t) throw(); }; typedef SteadyClock::SteadyClockTimePoint SteadyClockTimePoint; typedef WallClock::WallClockTimePoint WallClockTimePoint; inline SteadyClockTimePoint steadyClockNow() { return SteadyClock::now(); } inline WallClockTimePoint wallClockNow() { return WallClock::now(); } // Blocks the execution of the current thread for at least d. QI_API void sleepFor(const qi::Duration& d); template <class Rep, class Period> inline void sleepFor(const boost::chrono::duration<Rep, Period>& d); // Blocks the execution of the current thread until t has been // reached. // // This is equivalent to sleep_for(t-steady_clock::now()) QI_API void sleepUntil(const SteadyClockTimePoint &t); template <class Duration> inline void sleepUntil(const boost::chrono::time_point<SteadyClock, Duration>& t); // Blocks the execution of the current thread until t has been // reached. // Adjustments of the clock are taken into account. // Thus the duration of the block might, but might not, be less // or more than t - system_clock::now() QI_API void sleepUntil(const WallClockTimePoint& t); template <class Duration> inline void sleepUntil(const boost::chrono::time_point<WallClock, Duration>& t); } #ifdef __APPLE__ //export template instanciation for RTTI issues across libraries. (mostly for OSX) template class QI_API boost::chrono::duration<int64_t, boost::nano>; template class QI_API boost::chrono::duration<int64_t, boost::micro>; template class QI_API boost::chrono::duration<int64_t, boost::milli>; template class QI_API boost::chrono::duration<int64_t>; template class QI_API boost::chrono::duration<int64_t, boost::ratio<60> >; template class QI_API boost::chrono::duration<int64_t, boost::ratio<3600> >; template class QI_API boost::chrono::time_point<qi::SteadyClock>; template class QI_API boost::chrono::time_point<qi::WallClock>; #endif #include <qi/clock.hxx> #endif // _QI_OS_HPP_ <|endoftext|>
<commit_before>#include "bulkDataCallback.h" BulkDataCallback::BulkDataCallback() { ACS_TRACE("BulkDataCallback::BulkDataCallback"); state_m = CB_UNS; substate_m = CB_SUB_UNS; dim_m = 0; count_m = 0; loop_m = 5; waitPeriod_m.set(0L, 400000L); frameCount_m = 0; errorCounter = 0; bufParam_p = 0; timeout_m = false; working_m = false; error_m = false; // erComp_p = 0; } BulkDataCallback::~BulkDataCallback() { ACS_TRACE("BulkDataCallback::~BulkDataCallback"); } int BulkDataCallback::handle_start(void) { //ACS_TRACE("BulkDataCallback::handle_start"); // cout << "BulkDataCallback::handle_start - state_m: " << state_m << endl; //if(timeout_m == true) //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_start - timeout_m == true !!!")); timeout_m = false; error_m = false; state_m = CB_UNS; substate_m = CB_SUB_UNS; frameCount_m = 1; // we need to wait for 1 following frame before doing anything else return 0; } int BulkDataCallback::handle_stop (void) { //ACS_TRACE("BulkDataCallback::handle_stop"); // cout << "CCCCCCCCCCCCCCCCC enter stop state " << state_m << " " << substate_m << endl; try { int locLoop; int res; locLoop = loop_m; while ( (frameCount_m != 0) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } // we didn't receive the first frame yet if(state_m == CB_UNS) { int res = cbStop(); errorCounter = 0; return res; } if((state_m == CB_SEND_PARAM) || (state_m == CB_SEND_DATA)) { if (substate_m == CB_SUB_INIT) { substate_m = CB_SUB_UNS; return 0; } locLoop = loop_m; while((count_m != dim_m) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } if ( locLoop == 0 ) { ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_stop timeout expired, not all data received")); timeout_m = true; //cleaning the recv buffer ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); char buf[BUFSIZ]; int bufSize = sizeof(buf); //cout << "sssssss: " << bufSize << endl; int nn = 1; while(nn > 0) { nn = svch->peer().recv(buf,bufSize); //cout << "nnnnnnn: " << nn << endl; } //return -1; } if(state_m == CB_SEND_PARAM) { //res ignored by reactor if (dim_m != 0) res = cbStart(bufParam_p); if(bufParam_p) bufParam_p->release(); } state_m = CB_UNS; substate_m = CB_SUB_UNS; return 0; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.log(); /* TBD what do to after several attempts ? */ errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } //erComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, "ulkDataCallback::handle_stop"); error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::handle_stop"); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } return 0; } int BulkDataCallback::handle_destroy (void) { //ACS_TRACE("BulkDataCallback::handle_destroy"); //cout << "BulkDataCallback::handle_destroy" << endl; delete this; return 0; } int BulkDataCallback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *frame_info, const ACE_Addr &) { working_m = true; //ACS_TRACE("BulkDataCallback::receive_frame"); //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::receive_frame for flow %s", flowname_m.c_str())); // cout << "BulkDataCallback::receive_frame - state_m: " << state_m << endl; if(timeout_m == true) ACS_SHORT_LOG((LM_INFO, "BulkDataCallback::receive_frame - timeout_m true !!!")); try { CORBA::ULong val1, val2; int res; if(state_m == CB_UNS) { char tmp[255]; ACE_OS::strcpy(tmp, frame->rd_ptr()); string strDataInfo(tmp); istringstream iss(strDataInfo); iss >> val1 >> val2; // cout << "CCCCCCCCCCCCCCC " << val1 << " " << val2 << endl; if(val1 == 1) { state_m = CB_SEND_PARAM; substate_m = CB_SUB_INIT; bufParam_p = new ACE_Message_Block(val2); } else if(val1 == 2) { state_m = CB_SEND_DATA; substate_m = CB_SUB_INIT; } else { state_m = CB_UNS; substate_m = CB_SUB_UNS; } dim_m = val2; count_m = 0; frameCount_m = 0; working_m = false; return 0; } if(state_m == CB_SEND_PARAM) { if ( dim_m == 0 ) { res = cbStart(); errorCounter = 0; working_m = false; return res; } bufParam_p->copy(frame->rd_ptr(),frame->length()); count_m += frame->length(); errorCounter = 0; working_m = false; return 0; } if (state_m == CB_SEND_DATA) { res = cbReceive(frame); // if(timeout_m == true) // { // //cout << "!!!!!!! in receive_frame timeout_m == true after timeout - set it to false" << endl; // timeout_m = false; // } count_m += frame->length(); errorCounter = 0; working_m = false; return res; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.log(); /* TBD what do to after several attempts ? */ errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::receive_frame"); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } working_m = false; return 0; } void BulkDataCallback::setFlowname (const char * flowname_p) { ACS_TRACE("BulkDataCallback::setFlowname"); //ACS_SHORT_LOG((LM_INFO,"RRRRRRRRRRRRRRRRR BulkDataCallback::flowname for flow %s", flow_name)); flowname_m = flowname_p; string flwName(flowname_p); string flwNumber(flwName, 4, 1); flowNumber_m = atol(flwNumber.c_str()); } void BulkDataCallback::setSleepTime(ACE_Time_Value locWaitPeriod) { ACS_TRACE("BulkDataCallback::setSleepTime"); waitPeriod_m = locWaitPeriod; } void BulkDataCallback::setSafeTimeout(CORBA::ULong locLoop) { ACS_TRACE("BulkDataCallback::setSafeTimeout"); loop_m = locLoop; } CORBA::Boolean BulkDataCallback::isTimeout() { ACS_TRACE("BulkDataCallback::isTimeout"); return timeout_m; } CORBA::Boolean BulkDataCallback::isWorking() { ACS_TRACE("BulkDataCallback::isWorking"); return working_m; } CORBA::Boolean BulkDataCallback::isError() { ACS_TRACE("BulkDataCallback::isError"); return error_m; } <commit_msg>corrected bug in receiver callback<commit_after>#include "bulkDataCallback.h" BulkDataCallback::BulkDataCallback() { ACS_TRACE("BulkDataCallback::BulkDataCallback"); state_m = CB_UNS; substate_m = CB_SUB_UNS; dim_m = 0; count_m = 0; loop_m = 5; waitPeriod_m.set(0L, 400000L); frameCount_m = 0; errorCounter = 0; bufParam_p = 0; timeout_m = false; working_m = false; error_m = false; // erComp_p = 0; } BulkDataCallback::~BulkDataCallback() { ACS_TRACE("BulkDataCallback::~BulkDataCallback"); } int BulkDataCallback::handle_start(void) { //ACS_TRACE("BulkDataCallback::handle_start"); // cout << "BulkDataCallback::handle_start - state_m: " << state_m << endl; //if(timeout_m == true) //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_start - timeout_m == true !!!")); timeout_m = false; error_m = false; state_m = CB_UNS; substate_m = CB_SUB_UNS; frameCount_m = 1; // we need to wait for 1 following frame before doing anything else return 0; } int BulkDataCallback::handle_stop (void) { //ACS_TRACE("BulkDataCallback::handle_stop"); // cout << "CCCCCCCCCCCCCCCCC enter stop state " << state_m << " " << substate_m << endl; try { int locLoop; int res; locLoop = loop_m; while ( (frameCount_m != 0) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } // we didn't receive the first frame yet if(state_m == CB_UNS) { int res = cbStop(); errorCounter = 0; return res; } if((state_m == CB_SEND_PARAM) || (state_m == CB_SEND_DATA)) { if (substate_m == CB_SUB_INIT) { substate_m = CB_SUB_UNS; return 0; } locLoop = loop_m; while((count_m != dim_m) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } if ( locLoop == 0 ) { ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_stop timeout expired, not all data received")); timeout_m = true; //cleaning the recv buffer ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); char buf[BUFSIZ]; int bufSize = sizeof(buf); //cout << "sssssss: " << bufSize << endl; int nn = 1; while(nn > 0) { nn = svch->peer().recv(buf,bufSize); //cout << "nnnnnnn: " << nn << endl; } //return -1; } if(state_m == CB_SEND_PARAM) { //res ignored by reactor if (dim_m != 0) res = cbStart(bufParam_p); if(bufParam_p) bufParam_p->release(); } state_m = CB_UNS; substate_m = CB_SUB_UNS; return 0; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.log(); /* TBD what do to after several attempts ? */ errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } //erComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, "ulkDataCallback::handle_stop"); error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::handle_stop"); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } return 0; } int BulkDataCallback::handle_destroy (void) { //ACS_TRACE("BulkDataCallback::handle_destroy"); //cout << "BulkDataCallback::handle_destroy" << endl; delete this; return 0; } int BulkDataCallback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *frame_info, const ACE_Addr &) { working_m = true; //ACS_TRACE("BulkDataCallback::receive_frame"); //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::receive_frame for flow %s", flowname_m.c_str())); // cout << "BulkDataCallback::receive_frame - state_m: " << state_m << endl; if(timeout_m == true) ACS_SHORT_LOG((LM_INFO, "BulkDataCallback::receive_frame - timeout_m true !!!")); try { CORBA::ULong val1, val2; int res; if(state_m == CB_UNS) { char tmp[255]; ACE_OS::strcpy(tmp, frame->rd_ptr()); string strDataInfo(tmp); istringstream iss(strDataInfo); iss >> val1 >> val2; // cout << "CCCCCCCCCCCCCCC " << val1 << " " << val2 << endl; if(val1 == 1) { state_m = CB_SEND_PARAM; substate_m = CB_SUB_INIT; if(val2 != 0) bufParam_p = new ACE_Message_Block(val2); else bufParam_p = 0; } else if(val1 == 2) { state_m = CB_SEND_DATA; substate_m = CB_SUB_INIT; } else { state_m = CB_UNS; substate_m = CB_SUB_UNS; } dim_m = val2; count_m = 0; frameCount_m = 0; working_m = false; return 0; } if(state_m == CB_SEND_PARAM) { if ( dim_m == 0 ) { res = cbStart(); errorCounter = 0; working_m = false; return res; } bufParam_p->copy(frame->rd_ptr(),frame->length()); count_m += frame->length(); errorCounter = 0; working_m = false; return 0; } if (state_m == CB_SEND_DATA) { res = cbReceive(frame); // if(timeout_m == true) // { // //cout << "!!!!!!! in receive_frame timeout_m == true after timeout - set it to false" << endl; // timeout_m = false; // } count_m += frame->length(); errorCounter = 0; working_m = false; return res; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.log(); /* TBD what do to after several attempts ? */ errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::receive_frame"); err.log(); errorCounter++; if(errorCounter == maxErrorRepetition) { errorCounter = 0; //return 0; } error_m = true; } working_m = false; return 0; } void BulkDataCallback::setFlowname (const char * flowname_p) { ACS_TRACE("BulkDataCallback::setFlowname"); //ACS_SHORT_LOG((LM_INFO,"RRRRRRRRRRRRRRRRR BulkDataCallback::flowname for flow %s", flow_name)); flowname_m = flowname_p; string flwName(flowname_p); string flwNumber(flwName, 4, 1); flowNumber_m = atol(flwNumber.c_str()); } void BulkDataCallback::setSleepTime(ACE_Time_Value locWaitPeriod) { ACS_TRACE("BulkDataCallback::setSleepTime"); waitPeriod_m = locWaitPeriod; } void BulkDataCallback::setSafeTimeout(CORBA::ULong locLoop) { ACS_TRACE("BulkDataCallback::setSafeTimeout"); loop_m = locLoop; } CORBA::Boolean BulkDataCallback::isTimeout() { ACS_TRACE("BulkDataCallback::isTimeout"); return timeout_m; } CORBA::Boolean BulkDataCallback::isWorking() { ACS_TRACE("BulkDataCallback::isWorking"); return working_m; } CORBA::Boolean BulkDataCallback::isError() { ACS_TRACE("BulkDataCallback::isError"); return error_m; } <|endoftext|>
<commit_before>#ifndef ecmdUtils_H #define ecmdUtils_H // Copyright ********************************************************** // // File ecmdDataBuffer.H // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 2003 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ****************************************************** /* $Header$ */ /** * @file ecmdUtils.H * @brief Useful functions for use throughout the ecmd C API * */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <inttypes.h> #include <string> #include <vector> //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //-------------------------------------------------------------------- // Macros //-------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- /* Functions in here are defined as extern C for the following reasons: 1) Keeps Function names small by preventing C++ "mangling" 2) Allows (C-based) perl interpreter to access these functions */ extern "C" { /** @name Gen Functions */ //@{ /** * @brief Default function for converting hex strings to unsigned int arrays * @retval First element of the parsed data, or 0xFFFFFFFF if error * @param o_numPtr The array that stores the data parsed from the input string * @param i_hexChars input string of hex data- alignment stuff handled by Left and Right functions * @param startPos * @see ecmdGenB32FromHexRight * @see ecmdGenB32FromHexLeft */ uint32_t ecmdGenB32FromHex (uint32_t * o_numPtr, const char * i_hexChars, int startPos); /** * @brief Convert a string of left-aligned Hex chars into an unsigned int array * @retval The first element of the parsed string data, or 0xFFFFFFFF if error * @param o_numPtr The array that stores the data parsed from the input string * @param i_hexChars A string of hex characters * @see ecmdGenB32FromHexRight * @see ecmdGenB32FromHex */ uint32_t ecmdGenB32FromHexLeft (uint32_t * o_numPtr, const char * i_hexChars); /** * @brief Convert a string of right-aligned Hex chars into an unsigned int array * @retval The first element of the parsed string data, or 0xFFFFFFFF if error * @param o_numPtr The array that stores the data parsed from the input string * @param i_hexChars A string of hex characters * @param i_expectBits The number of defined bits in the o_numPtr array returned * @see ecmdGenB32FromHex * @see ecmdGenB32FromHexLeft */ uint32_t ecmdGenB32FromHexRight (uint32_t * o_numPtr, const char * i_hexChars, int i_expectBits = 0); //@} /** @name Command Line Parsing Functions */ //@{ /** * @brief Iterates over argv, looking for given option string, removes it if found * @retval 1 if option found, 0 otherwise * @param io_argc Pointer to number of elements in io_argv array * @param io_argv Array of strings passed in from command line * @param i_option Option to look for * @see ecmdParseOptionWithArgs */ int ecmdParseOption (int * io_argc, char ** io_argv[], const char * i_option); /** * @brief Iterates over argv, looking for given option string, removes it if found * @retval Value of option arg if found, NULL otherwise * @param io_argc Pointer to number of elements in io_argv array * @param io_argv Array of strings passed in from command line * @param i_option Option to look for * @see ecmdParseOptionWithArgs */ char * ecmdParseOptionWithArgs(int * io_argc, char ** io_argv[], const char * i_option); void ecmdParseTokens (std::string & line, std::vector<std::string> & tokens); //@} /** @brief Initializes data structures and code to loop over configured and selected elements of the system @param io_target Initial ecmdChipTarget that may contain information used in building the struct to loop over @retval ECMD_SUCCESS if initialization succeeded, error code if otherwise @see ecmdConfigLooperNext */ int ecmdConfigLooperInit (ecmdChipTarget & io_target); /** @brief Loops over configured and selected elements of the system, updating target to point to them @param io_target ecmdChipTarget that contains info about next target to process @retval 1 if io_target is valid, 0 if it is not @see ecmdConfigLooperInit */ int ecmdConfigLooperNext (ecmdChipTarget & io_target); /** @brief Reads data from data string into data buffer based on a format type @retval ECMD_SUCCESS if data is well-formatted, non-zero otherwise @param o_data ecmdDataBuffer where data from data string is placed. @param i_dataStr string of characters containing data @param i_format Flag that tells how to parse the data string, e.g., "b" = binary, "x" = hex left */ int ecmdReadDataFormatted (ecmdDataBuffer & o_data, const char * i_dataStr, std::string & i_format); /** @brief Formats data from data buffer into a string according to format flag and returns the string @retval String of formatted data @param i_data ecmdDataBuffer where data to format is stored @param i_format Flag that tells how to parse the data into a string, e.g., "b" = binary, "x" = hex left @param address A base address value that can be used in formating certain data- i.e., data from memory */ std::string ecmdWriteDataFormatted (ecmdDataBuffer & i_data, std::string & i_format, int address = 0); } /* Extern C */ #endif <commit_msg>Fixed compile errors<commit_after>#ifndef ecmdUtils_H #define ecmdUtils_H // Copyright ********************************************************** // // File ecmdDataBuffer.H // // IBM Confidential // OCO Source Materials // 9400 Licensed Internal Code // (C) COPYRIGHT IBM CORP. 2003 // // The source code for this program is not published or otherwise // divested of its trade secrets, irrespective of what has been // deposited with the U.S. Copyright Office. // // End Copyright ****************************************************** /* $Header$ */ /** * @file ecmdUtils.H * @brief Useful functions for use throughout the ecmd C API * */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <inttypes.h> #include <string> #include <vector> #include <ecmdClientCapi.H> //---------------------------------------------------------------------- // Constants //---------------------------------------------------------------------- //-------------------------------------------------------------------- // Macros //-------------------------------------------------------------------- //---------------------------------------------------------------------- // Global Variables //---------------------------------------------------------------------- //---------------------------------------------------------------------- // User Types //---------------------------------------------------------------------- /* Functions in here are defined as extern C for the following reasons: 1) Keeps Function names small by preventing C++ "mangling" 2) Allows (C-based) perl interpreter to access these functions */ extern "C" { /** @name Gen Functions */ //@{ /** * @brief Default function for converting hex strings to unsigned int arrays * @retval First element of the parsed data, or 0xFFFFFFFF if error * @param o_numPtr The array that stores the data parsed from the input string * @param i_hexChars input string of hex data- alignment stuff handled by Left and Right functions * @param startPos * @see ecmdGenB32FromHexRight * @see ecmdGenB32FromHexLeft */ uint32_t ecmdGenB32FromHex (uint32_t * o_numPtr, const char * i_hexChars, int startPos); /** * @brief Convert a string of left-aligned Hex chars into an unsigned int array * @retval The first element of the parsed string data, or 0xFFFFFFFF if error * @param o_numPtr The array that stores the data parsed from the input string * @param i_hexChars A string of hex characters * @see ecmdGenB32FromHexRight * @see ecmdGenB32FromHex */ uint32_t ecmdGenB32FromHexLeft (uint32_t * o_numPtr, const char * i_hexChars); /** * @brief Convert a string of right-aligned Hex chars into an unsigned int array * @retval The first element of the parsed string data, or 0xFFFFFFFF if error * @param o_numPtr The array that stores the data parsed from the input string * @param i_hexChars A string of hex characters * @param i_expectBits The number of defined bits in the o_numPtr array returned * @see ecmdGenB32FromHex * @see ecmdGenB32FromHexLeft */ uint32_t ecmdGenB32FromHexRight (uint32_t * o_numPtr, const char * i_hexChars, int i_expectBits = 0); //@} /** @name Command Line Parsing Functions */ //@{ /** * @brief Iterates over argv, looking for given option string, removes it if found * @retval 1 if option found, 0 otherwise * @param io_argc Pointer to number of elements in io_argv array * @param io_argv Array of strings passed in from command line * @param i_option Option to look for * @see ecmdParseOptionWithArgs */ int ecmdParseOption (int * io_argc, char ** io_argv[], const char * i_option); /** * @brief Iterates over argv, looking for given option string, removes it if found * @retval Value of option arg if found, NULL otherwise * @param io_argc Pointer to number of elements in io_argv array * @param io_argv Array of strings passed in from command line * @param i_option Option to look for * @see ecmdParseOptionWithArgs */ char * ecmdParseOptionWithArgs(int * io_argc, char ** io_argv[], const char * i_option); void ecmdParseTokens (std::string & line, std::vector<std::string> & tokens); //@} /** @brief Initializes data structures and code to loop over configured and selected elements of the system @param io_target Initial ecmdChipTarget that may contain information used in building the struct to loop over @retval ECMD_SUCCESS if initialization succeeded, error code if otherwise @see ecmdConfigLooperNext */ int ecmdConfigLooperInit (ecmdChipTarget & io_target); /** @brief Loops over configured and selected elements of the system, updating target to point to them @param io_target ecmdChipTarget that contains info about next target to process @retval 1 if io_target is valid, 0 if it is not @see ecmdConfigLooperInit */ int ecmdConfigLooperNext (ecmdChipTarget & io_target); /** @brief Reads data from data string into data buffer based on a format type @retval ECMD_SUCCESS if data is well-formatted, non-zero otherwise @param o_data ecmdDataBuffer where data from data string is placed. @param i_dataStr string of characters containing data @param i_format Flag that tells how to parse the data string, e.g., "b" = binary, "x" = hex left */ int ecmdReadDataFormatted (ecmdDataBuffer & o_data, const char * i_dataStr, std::string & i_format); /** @brief Formats data from data buffer into a string according to format flag and returns the string @retval String of formatted data @param i_data ecmdDataBuffer where data to format is stored @param i_format Flag that tells how to parse the data into a string, e.g., "b" = binary, "x" = hex left @param address A base address value that can be used in formating certain data- i.e., data from memory */ std::string ecmdWriteDataFormatted (ecmdDataBuffer & i_data, std::string & i_format, int address = 0); } /* Extern C */ #endif <|endoftext|>
<commit_before>/* * QuaZIP - a Qt/C++ wrapper for the ZIP/UNZIP package * Copyright (C) 2005 Sergey A. Tachenov * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **/ #include "quazipfile.h" using namespace std; QuaZipFile::QuaZipFile(): zip(NULL), internal(true), zipError(UNZ_OK) { } QuaZipFile::QuaZipFile(QObject *parent): QIODevice(parent), zip(NULL), internal(true), zipError(UNZ_OK) { } QuaZipFile::QuaZipFile(const QString& zipName, QObject *parent): QIODevice(parent), internal(true), zipError(UNZ_OK) { zip=new QuaZip(zipName); Q_CHECK_PTR(zip); } QuaZipFile::QuaZipFile(const QString& zipName, const QString& fileName, QuaZip::CaseSensitivity cs, QObject *parent): QIODevice(parent), internal(true), zipError(UNZ_OK) { zip=new QuaZip(zipName); Q_CHECK_PTR(zip); this->fileName=fileName; this->caseSensitivity=cs; } QuaZipFile::QuaZipFile(QuaZip *zip, QObject *parent): QIODevice(parent), zip(zip), internal(false), zipError(UNZ_OK) { } QuaZipFile::~QuaZipFile() { if(isOpen()) close(); if(internal) delete zip; } QString QuaZipFile::getZipName()const { return zip==NULL?QString():zip->getZipName(); } QString QuaZipFile::getActualFileName()const { setZipError(UNZ_OK); if(zip==NULL) return QString(); QString name=zip->getCurrentFileName(); if(name.isNull()) setZipError(zip->getZipError()); return name; } void QuaZipFile::setZipName(const QString& zipName) { if(isOpen()) { qWarning("QuaZipFile::setZipName(): file is already open - can not set ZIP name"); return; } if(zip!=NULL&&internal) delete zip; zip=new QuaZip(zipName); Q_CHECK_PTR(zip); internal=true; } void QuaZipFile::setZip(QuaZip *zip) { if(isOpen()) { qWarning("QuaZipFile::setZip(): file is already open - can not set ZIP"); return; } if(this->zip!=NULL&&internal) delete this->zip; this->zip=zip; this->fileName=QString(); internal=false; } void QuaZipFile::setFileName(const QString& fileName, QuaZip::CaseSensitivity cs) { if(zip==NULL) { qWarning("QuaZipFile::setFileName(): call setZipName() first"); return; } if(!internal) { qWarning("QuaZipFile::setFileName(): should not be used when not using internal QuaZip"); return; } if(isOpen()) { qWarning("QuaZipFile::setFileName(): can not set file name for already opened file"); return; } this->fileName=fileName; this->caseSensitivity=cs; } void QuaZipFile::setZipError(int zipError)const { QuaZipFile *fakeThis=(QuaZipFile*)this; // non-const fakeThis->zipError=zipError; if(zipError==UNZ_OK) fakeThis->setErrorString(QString()); else fakeThis->setErrorString(tr("ZIP/UNZIP API error %1").arg(zipError)); } bool QuaZipFile::open(OpenMode mode) { return open(mode, NULL); } bool QuaZipFile::open(OpenMode mode, int *method, int *level, bool raw, const char *password) { resetZipError(); if(isOpen()) { qWarning("QuaZipFile::open(): already opened"); return false; } if((mode&ReadOnly)&&!(mode&WriteOnly)) { if(internal) { if(!zip->open(QuaZip::mdUnzip)) { setZipError(zip->getZipError()); return false; } if(!zip->setCurrentFile(fileName, caseSensitivity)) { setZipError(zip->getZipError()); zip->close(); return false; } } else if(zip->getMode()!=QuaZip::mdUnzip) { qWarning("QuaZipFile::open(): file open mode %d incompatible with ZIP open mode %d", (int)mode, (int)zip->getMode()); return false; } setZipError(unzOpenCurrentFile3(zip->getUnzFile(), method, level, raw, password)); if(zipError==UNZ_OK) { setOpenMode(mode); return true; } else return false; } qWarning("QuaZipFile::open(): open mode %d not supported", (int)mode); return false; } qint64 QuaZipFile::pos()const { if(zip==NULL) { qWarning("QuaZipFile::pos(): call setZipName() or setZip() first"); return -1; } return unztell(zip->getUnzFile()); } bool QuaZipFile::atEnd()const { if(zip==NULL) { qWarning("QuaZipFile::atEnd(): call setZipName() or setZip() first"); return false; } return unzeof(zip->getUnzFile())==1; } void QuaZipFile::close() { resetZipError(); if(zip->getMode()!=QuaZip::mdUnzip) return; if(!isOpen()) { qWarning("QuaZipFile::close(): file isn't open"); return; } setZipError(unzCloseCurrentFile(zip->getUnzFile())); if(zipError==UNZ_OK) setOpenMode(QIODevice::NotOpen); else return; zip->close(); setZipError(zip->getZipError()); } qint64 QuaZipFile::readData(char *data, qint64 maxSize) { return unzReadCurrentFile(zip->getUnzFile(), data, (unsigned)maxSize); } qint64 QuaZipFile::writeData(const char*, qint64) { qWarning("Write mode not supported"); return -1; } <commit_msg>Fixed: QuaZipFile::close(): close zip only if it is internal.<commit_after>/* * QuaZIP - a Qt/C++ wrapper for the ZIP/UNZIP package * Copyright (C) 2005 Sergey A. Tachenov * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **/ #include "quazipfile.h" using namespace std; QuaZipFile::QuaZipFile(): zip(NULL), internal(true), zipError(UNZ_OK) { } QuaZipFile::QuaZipFile(QObject *parent): QIODevice(parent), zip(NULL), internal(true), zipError(UNZ_OK) { } QuaZipFile::QuaZipFile(const QString& zipName, QObject *parent): QIODevice(parent), internal(true), zipError(UNZ_OK) { zip=new QuaZip(zipName); Q_CHECK_PTR(zip); } QuaZipFile::QuaZipFile(const QString& zipName, const QString& fileName, QuaZip::CaseSensitivity cs, QObject *parent): QIODevice(parent), internal(true), zipError(UNZ_OK) { zip=new QuaZip(zipName); Q_CHECK_PTR(zip); this->fileName=fileName; this->caseSensitivity=cs; } QuaZipFile::QuaZipFile(QuaZip *zip, QObject *parent): QIODevice(parent), zip(zip), internal(false), zipError(UNZ_OK) { } QuaZipFile::~QuaZipFile() { if(isOpen()) close(); if(internal) delete zip; } QString QuaZipFile::getZipName()const { return zip==NULL?QString():zip->getZipName(); } QString QuaZipFile::getActualFileName()const { setZipError(UNZ_OK); if(zip==NULL) return QString(); QString name=zip->getCurrentFileName(); if(name.isNull()) setZipError(zip->getZipError()); return name; } void QuaZipFile::setZipName(const QString& zipName) { if(isOpen()) { qWarning("QuaZipFile::setZipName(): file is already open - can not set ZIP name"); return; } if(zip!=NULL&&internal) delete zip; zip=new QuaZip(zipName); Q_CHECK_PTR(zip); internal=true; } void QuaZipFile::setZip(QuaZip *zip) { if(isOpen()) { qWarning("QuaZipFile::setZip(): file is already open - can not set ZIP"); return; } if(this->zip!=NULL&&internal) delete this->zip; this->zip=zip; this->fileName=QString(); internal=false; } void QuaZipFile::setFileName(const QString& fileName, QuaZip::CaseSensitivity cs) { if(zip==NULL) { qWarning("QuaZipFile::setFileName(): call setZipName() first"); return; } if(!internal) { qWarning("QuaZipFile::setFileName(): should not be used when not using internal QuaZip"); return; } if(isOpen()) { qWarning("QuaZipFile::setFileName(): can not set file name for already opened file"); return; } this->fileName=fileName; this->caseSensitivity=cs; } void QuaZipFile::setZipError(int zipError)const { QuaZipFile *fakeThis=(QuaZipFile*)this; // non-const fakeThis->zipError=zipError; if(zipError==UNZ_OK) fakeThis->setErrorString(QString()); else fakeThis->setErrorString(tr("ZIP/UNZIP API error %1").arg(zipError)); } bool QuaZipFile::open(OpenMode mode) { return open(mode, NULL); } bool QuaZipFile::open(OpenMode mode, int *method, int *level, bool raw, const char *password) { resetZipError(); if(isOpen()) { qWarning("QuaZipFile::open(): already opened"); return false; } if((mode&ReadOnly)&&!(mode&WriteOnly)) { if(internal) { if(!zip->open(QuaZip::mdUnzip)) { setZipError(zip->getZipError()); return false; } if(!zip->setCurrentFile(fileName, caseSensitivity)) { setZipError(zip->getZipError()); zip->close(); return false; } } else if(zip->getMode()!=QuaZip::mdUnzip) { qWarning("QuaZipFile::open(): file open mode %d incompatible with ZIP open mode %d", (int)mode, (int)zip->getMode()); return false; } setZipError(unzOpenCurrentFile3(zip->getUnzFile(), method, level, raw, password)); if(zipError==UNZ_OK) { setOpenMode(mode); return true; } else return false; } qWarning("QuaZipFile::open(): open mode %d not supported", (int)mode); return false; } qint64 QuaZipFile::pos()const { if(zip==NULL) { qWarning("QuaZipFile::pos(): call setZipName() or setZip() first"); return -1; } return unztell(zip->getUnzFile()); } bool QuaZipFile::atEnd()const { if(zip==NULL) { qWarning("QuaZipFile::atEnd(): call setZipName() or setZip() first"); return false; } return unzeof(zip->getUnzFile())==1; } void QuaZipFile::close() { resetZipError(); if(zip->getMode()!=QuaZip::mdUnzip) return; if(!isOpen()) { qWarning("QuaZipFile::close(): file isn't open"); return; } setZipError(unzCloseCurrentFile(zip->getUnzFile())); if(zipError==UNZ_OK) setOpenMode(QIODevice::NotOpen); else return; if(internal) { zip->close(); setZipError(zip->getZipError()); } } qint64 QuaZipFile::readData(char *data, qint64 maxSize) { return unzReadCurrentFile(zip->getUnzFile(), data, (unsigned)maxSize); } qint64 QuaZipFile::writeData(const char*, qint64) { qWarning("Write mode not supported"); return -1; } <|endoftext|>
<commit_before>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" #include "Engine.h" #include "App.h" #include "Input.h" #include "ObjectGui.h" #include "WidgetLabel.h" //解决跨平台字符集兼容问题 #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //角色要初始化,着色器要初始化, virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。 virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //设置是否显示鼠标 virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。 virtual void SetControlMode(ControlMode mode); //控制模式 virtual ControlMode GetControlMode() const; //获取控制模式 private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //控制游戏中移动 CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //控制模式 int m_nOldMouseX; //上一个鼠标坐标X int m_nOldMouseY; //上一个鼠标坐标Y CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel->SetFontSize(80); //设置字体大小 m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓 m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船"); void CSysControlLocal::Update(float ifps) { Update_Mouse(ifps); Update_Keyboard(ifps); Update_XPad360(ifps); } m_nOldMouseX = 0; m_nOldMouseY = 0; } void CSysControlLocal::Shutdown() { g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); delete m_pControlsApp; m_pControlsApp = NULL; delete m_pControlsXPad360; m_pControlsXPad360 = NULL; delete m_pTestMessageLabel; m_pTestMessageLabel = NULL; delete m_pTest3DUI; m_pTest3DUI = NULL; } int CSysControlLocal::GetState(int state) { return m_pControlsApp->GetState(state); } int CSysControlLocal::ClearState(int state) { return m_pControlsApp->ClearState(state); } float CSysControlLocal::GetMouseDX() { return m_pControlsApp->GetMouseDX(); } float CSysControlLocal::GetMouseDY() { return m_pControlsApp->GetMouseDY(); } void CSysControlLocal::SetMouseGrab(int g) { g_Engine.pApp->SetMouseGrab(g); g_Engine.pGui->SetMouseShow(!g); } int CSysControlLocal::GetMouseGrab() { return g_Engine.pApp->GetMouseGrab(); } void CSysControlLocal::SetControlMode(ControlMode mode) { m_nControlMode = mode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } void CSysControlLocal::Update_Mouse(float ifps) { float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快 float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢 m_pControlsApp->SetMouseDX(dx); m_pControlsApp->SetMouseDY(dy); if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive()) { g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2); } }<commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" #include "Engine.h" #include "App.h" #include "Engine.h" #include "App.h" #include "Input.h" #include "ObjectGui.h" #include "WidgetLabel.h" //解决跨平台字符集兼容问题 #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //角色要初始化,着色器要初始化, virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //鼠标状态,键盘状态,人物状态,子弹状态等等。 virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //设置是否显示鼠标 virtual int GetMouseGrab(); //获取鼠标状态,是显示呢还是不显示的状态。 virtual void SetControlMode(ControlMode mode); //控制模式 virtual ControlMode GetControlMode() const; //获取控制模式 private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //控制游戏中移动 CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //控制模式 int m_nOldMouseX; //上一个鼠标坐标X int m_nOldMouseY; //上一个鼠标坐标Y CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); SetControlMode(CONTROL_KEYBORAD_MOUSE); m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/"); m_pTest3DUI->SetMouseShow(0); m_pTest3DUI->SetBackground(1); m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f)); m_pTest3DUI->SetScreenSize(800, 400); m_pTest3DUI->SetControlDistance(1000.0f); m_pTest3DUI->CreateMaterial("gui_base"); //show in game m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f))); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui()); //初始化文字标签 m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER); m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f)); m_pTestMessageLabel->SetFontSize(80); //设置字体大小 m_pTestMessageLabel->SetFontOutline(1); //设置字体轮廓 m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船"); void CSysControlLocal::Update(float ifps) { Update_Mouse(ifps); Update_Keyboard(ifps); Update_XPad360(ifps); } m_nOldMouseX = 0; m_nOldMouseY = 0; } void CSysControlLocal::Shutdown() { g_Engine.pApp->SetMouseGrab(0); g_Engine.pApp->SetMouseShow(0); delete m_pControlsApp; m_pControlsApp = NULL; delete m_pControlsXPad360; m_pControlsXPad360 = NULL; delete m_pTestMessageLabel; m_pTestMessageLabel = NULL; delete m_pTest3DUI; m_pTest3DUI = NULL; } int CSysControlLocal::GetState(int state) { return m_pControlsApp->GetState(state); } int CSysControlLocal::ClearState(int state) { return m_pControlsApp->ClearState(state); } float CSysControlLocal::GetMouseDX() { return m_pControlsApp->GetMouseDX(); } float CSysControlLocal::GetMouseDY() { return m_pControlsApp->GetMouseDY(); } void CSysControlLocal::SetMouseGrab(int g) { g_Engine.pApp->SetMouseGrab(g); g_Engine.pGui->SetMouseShow(!g); } int CSysControlLocal::GetMouseGrab() { return g_Engine.pApp->GetMouseGrab(); } void CSysControlLocal::SetControlMode(ControlMode mode) { m_nControlMode = mode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } CSysControl::ControlMode CSysControlLocal::GetControlMode() const { return m_nControlMode; } void CSysControlLocal::Update_Mouse(float ifps) { float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大,鼠标移动越快 float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小,鼠标移动越慢 m_pControlsApp->SetMouseDX(dx); m_pControlsApp->SetMouseDY(dy); if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive()) { g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2); } m_nOldMouseX = g_Engine.pApp->GetMouseX(); m_nOldMouseY = g_Engine.pApp->GetMouseY(); }<|endoftext|>
<commit_before>#pragma once /* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ /** * \file * \brief Various macros for qi. (deprecated, export API, disallow copy, ..) * \includename{qi/macro.hpp} * \verbatim * This header file contains various macros for qi. * * - import/export symbol (:cpp:macro:`QI_IMPORT_API`, * :cpp:macro:`QI_EXPORT_API`) * - mark function and header as deprecated (:cpp:macro:`QI_DEPRECATED_HEADER`, * :cpp:macro:`QI_API_DEPRECATED`) * - generate compiler warning (:cpp:macro:`QI_COMPILER_WARNING`) * - disallow copy and assign (:cpp:macro:`QI_DISALLOW_COPY_AND_ASSIGN`) * \endverbatim */ #ifndef _QI_MACRO_HPP_ # define _QI_MACRO_HPP_ # include <qi/preproc.hpp> #include <boost/predef/compiler.h> #include <boost/config.hpp> /** * \def QI_API_DEPRECATED * \brief Compiler flags to mark a function as deprecated. It will generate a * compiler warning. */ #if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED __declspec(deprecated) #else # define QI_API_DEPRECATED #endif /** * \def QI_API_DEPRECATED_MSG(msg__) * \brief Compiler flags to mark a function as deprecated. It will generate a * compiler warning. * \param msg__ A message providing a workaround. */ #if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED_MSG(msg__) __attribute__((deprecated(#msg__))) #elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED_MSG(msg__) __declspec(deprecated(#msg__)) #else # define QI_API_DEPRECATED_MSG(msg__) #endif /** * \def QI_NORETURN * \brief Portable noreturn attribute, used to declare that a function does not return */ #if defined(__GNUC__) # define QI_NORETURN __attribute__((noreturn)) #elif defined(_MSC_VER) /// Portable noreturn attribute, used to declare that a function does not return # define QI_NORETURN __declspec(noreturn) #else # define QI_NORETURN #endif /** * \def QI_HAS_VARIABLE_LENGTH_ARRAY * \brief Mark compilers supporting variable length array (VLA) */ #if defined(__GNUC__) && !defined(__clang__) # define QI_HAS_VARIABLE_LENGTH_ARRAY 1 #else # define QI_HAS_VARIABLE_LENGTH_ARRAY 0 #endif // For shared library /** * \return the proper type specification for import/export * \param libname the name of your library. * This macro will use two preprocessor defines: * libname_EXPORTS (cmake convention) and libname_STATIC_BUILD. * Those macro can be unset or set to 0 to mean false, or set to empty or 1 to * mean true. * The first one must be true if the current compilation unit is within the library. * The second must be true if the library was built as a static archive. * The proper way to use this macro is to: * - Have your buildsystem set mylib_EXPORTS when building MYLIB * - Have your buildsystem produce a config.h file that * \#define mylib_STATIC_BUILD to 1 or empty if it is a static build, and * not define mylib_STATIC_BUILD or define it to 0 otherwise * In one header, write * \#include <mylib/config.h> * \#define MYLIB_API QI_LIB_API(mylib) */ #define QI_LIB_API(libname) QI_LIB_API_(BOOST_PP_CAT(libname, _EXPORTS), BOOST_PP_CAT(libname, _STATIC_BUILD)) #define QI_LIB_API_(IS_BUILDING_LIB, IS_LIB_STATIC_BUILD) \ QI_LIB_API_NORMALIZED(_QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_ , IS_BUILDING_LIB)), _QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_, IS_LIB_STATIC_BUILD))) /** * \def QI_IMPORT_API * \brief Compiler flags to import a function or a class. */ /** * \def QI_EXPORT_API * \brief Compiler flags to export a function or a class. */ /** * \def QI_LIB_API_NORMALIZED(a, b) * \brief Each platform must provide a QI_LIB_API_NORMALIZED(isBuilding, isStatic) */ #if defined _WIN32 || defined __CYGWIN__ # define QI_EXPORT_API __declspec(dllexport) # define QI_IMPORT_API __declspec(dllimport) # define QI_LIB_API_NORMALIZED(exporting, isstatic) BOOST_PP_CAT(BOOST_PP_CAT(_QI_LIB_API_NORMALIZED_, exporting), isstatic) # define _QI_LIB_API_NORMALIZED_00 QI_IMPORT_API # define _QI_LIB_API_NORMALIZED_10 QI_EXPORT_API # define _QI_LIB_API_NORMALIZED_11 # define _QI_LIB_API_NORMALIZED_01 #elif __GNUC__ >= 4 # define QI_EXPORT_API __attribute__ ((visibility("default"))) # define QI_IMPORT_API QI_EXPORT_API # define QI_LIB_API_NORMALIZED(a, b) QI_EXPORT_API #else # define QI_IMPORT_API # define QI_EXPORT_API # define QI_LIB_API_NORMALIZED(a, b) #endif //! \cond internal // Macros adapted from opencv2.2 #if defined(_MSC_VER) #define QI_DO_PRAGMA(x) __pragma(x) #define __ALSTR2__(x) #x #define __ALSTR1__(x) __ALSTR2__(x) #define _ALMSVCLOC_ __FILE__ "("__ALSTR1__(__LINE__)") : " #define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_ALMSVCLOC_ _msg)) #elif defined(__GNUC__) #define QI_DO_PRAGMA(x) _Pragma (BOOST_PP_STRINGIZE(x)) #define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_msg)) #else #define QI_DO_PRAGMA(x) #define QI_MSG_PRAGMA(_msg) #endif //! \endcond /** * \def QI_COMPILER_WARNING(x) * \brief Generate a compiler warning. * \param x The string displayed as the warning. */ #if defined(QI_NO_COMPILER_WARNING) # define QI_COMPILER_WARNING(x) #else # define QI_COMPILER_WARNING(x) QI_MSG_PRAGMA("Warning: " #x) #endif /** * \def QI_DEPRECATED_HEADER(x) * \brief Generate a compiler warning stating a header is deprecated. * add a message to explain what user should do */ #if !defined(WITH_DEPRECATED) || defined(QI_NO_DEPRECATED_HEADER) # define QI_DEPRECATED_HEADER(x) #else # define QI_DEPRECATED_HEADER(x) QI_MSG_PRAGMA("\ This file includes at least one deprecated or antiquated ALDEBARAN header \ which may be removed without further notice in the next version. \ Please consult the changelog for details. " #x) #endif #ifdef __cplusplus namespace qi { template <typename T> struct IsClonable; }; #endif /** * \brief A macro used to deprecate another macro. Generate a compiler warning * when the given macro is used. * \param name The name of the macro. * \verbatim * Example: * * .. code-block:: cpp * * #define MAX(x,y)(QI_DEPRECATE_MACRO(MAX), x > y ? x : y) * \endverbatim */ #define QI_DEPRECATE_MACRO(name) \ QI_COMPILER_WARNING(name macro is deprecated.) /** * \deprecated Use boost::noncopyable instead. * * \verbatim * Example: * * .. code-block:: cpp * * class Foo : private boost::nonpyable * {}; * \endverbatim * * \brief A macro to disallow copy constructor and operator= * \param type The class name of which we want to forbid copy. * * \verbatim * .. note:: * This macro should always be in the private (or protected) section of a * class. * * Example: * * .. code-block:: cpp * * class Foo { * Foo(); * private: * QI_DISALLOW_COPY_AND_ASSIGN(Foo); * }; * \endverbatim */ #define QI_DISALLOW_COPY_AND_ASSIGN(type) \ QI_DEPRECATE_MACRO(QI_DISALLOW_COPY_AND_ASSIGN) \ type(type const &); \ void operator=(type const &); \ using _qi_not_clonable = int; \ template<typename U> friend struct ::qi::IsClonable /** * \def QI_WARN_UNUSED_RESULT * \brief This macro tags a result as unused. */ #if defined(__GNUC__) # define QI_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define QI_WARN_UNUSED_RESULT #endif /** * \def QI_ATTR_UNUSED * \brief This macro tags a attribute as unused. */ #if defined(__GNUC__) # define QI_ATTR_UNUSED __attribute__((unused)) #else # define QI_ATTR_UNUSED #endif /** * \brief This macro tags a parameter as unused. * * \verbatim * Example: * * .. code-block:: cpp * * int zero(int QI_UNUSED(x)) * { * return 0; * } * \endverbatim */ #define QI_UNUSED(x) /** * This macro prevents the compiler from emitting warning when a variable is defined but not used. * * Note: You may not use this macro to declare that a function parameters is unused. For such uses, * see QI_UNUSED. * * \verbatim * Example: * * .. code-block:: cpp * * void foo(std::vector<int> vec) * { * auto size = vec.size(); * // QI_ASSERT expands to nothing if debug informations are disabled in the compilation * // configuration, which would make the `size` variable unused. * QI_IGNORE_UNUSED(size); * QI_ASSERT(size > 2); * } * \endverbatim */ #define QI_IGNORE_UNUSED(x) (void)x /** * \def QI_UNIQ_DEF(A) * \brief A macro to append the line number of the parent macro usage, to define a * function in or a variable and avoid name collision. */ #define QI_UNIQ_DEF_LEVEL2_(A, B) A ## __uniq__ ## B #define QI_UNIQ_DEF_LEVEL1_(A, B) QI_UNIQ_DEF_LEVEL2_(A, B) #define QI_UNIQ_DEF(A) QI_UNIQ_DEF_LEVEL1_(A, __LINE__) /** * \def QI_NOEXCEPT(cond) * \brief Specify that a function may throw or not. Do nothing if noexcept is not available. * */ #define QI_NOEXCEPT(cond) BOOST_NOEXCEPT_IF(cond) /** * \def QI_NOEXCEPT_EXPR(expr) * \brief Specify that a function may throw if the given expression may throw. * Do nothing if noexcept is not available. */ #define QI_NOEXCEPT_EXPR(expr) BOOST_NOEXCEPT_IF(BOOST_NOEXCEPT_EXPR(expr)) /** * \def QI_WARNING_PUSH() * \brief Pushes the current state of warning flags so it can be retrieved later with QI_WARNING_POP. */ #if BOOST_COMP_MSVC # define QI_WARNING_PUSH() QI_DO_PRAGMA(warning(push)) #elif BOOST_COMP_GNUC # define QI_WARNING_PUSH() QI_DO_PRAGMA(GCC diagnostic push) #elif BOOST_COMP_CLANG # define QI_WARNING_PUSH() QI_DO_PRAGMA(clang diagnostic push) #endif /** * \def QI_WARNING_DISABLE(msvcCode, gccName) * \brief Disables the warning that is identified by msvcCode under MSVC or gccName under GCC and * Clang. */ #if BOOST_COMP_MSVC # define QI_WARNING_DISABLE(code, _) \ QI_DO_PRAGMA(warning(disable: code)) #elif BOOST_COMP_GNUC # define QI_WARNING_DISABLE(_, name) \ QI_DO_PRAGMA(GCC diagnostic ignored BOOST_PP_STRINGIZE(BOOST_PP_CAT(-W, name))) #elif BOOST_COMP_CLANG # define QI_WARNING_DISABLE(_, name) \ QI_DO_PRAGMA(clang diagnostic ignored BOOST_PP_STRINGIZE(BOOST_PP_CAT(-W, name))) #endif /** * \def QI_WARNING_POP() * \brief Pops the last state of warning flags that was pushed with QI_WARNING_PUSH(). */ #if BOOST_COMP_MSVC # define QI_WARNING_POP() QI_DO_PRAGMA(warning(pop)) #elif BOOST_COMP_GNUC # define QI_WARNING_POP() QI_DO_PRAGMA(GCC diagnostic pop) #elif BOOST_COMP_CLANG # define QI_WARNING_POP() QI_DO_PRAGMA(clang diagnostic pop) #endif /** * \def QI_FALLTHROUGH * \brief Declares that the current case in a switch falls through the next case. It is mandatory to * append a semicolon after this macro. */ #if defined(__has_cpp_attribute) && __cplusplus >= 201703L # if __has_cpp_attribute(fallthrough) # define QI_FALLTHROUGH [[fallthrough]] # endif #endif #ifndef QI_FALLTHROUGH # if __GNUC__ >= 7 # define QI_FALLTHROUGH __attribute__((fallthrough)) # elif defined(__clang__) && __cplusplus >= 201103L && \ defined(__has_feature) && defined(__has_warning) # if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") # define QI_FALLTHROUGH [[clang::fallthrough]] # endif # endif #endif #ifndef QI_FALLTHROUGH # define QI_FALLTHROUGH ((void)0) #endif #endif // _QI_MACRO_HPP_ <commit_msg>qi.macro: Improves `QI_WARN_UNUSED_RESULT` documentation.<commit_after>#pragma once /* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ /** * \file * \brief Various macros for qi. (deprecated, export API, disallow copy, ..) * \includename{qi/macro.hpp} * \verbatim * This header file contains various macros for qi. * * - import/export symbol (:cpp:macro:`QI_IMPORT_API`, * :cpp:macro:`QI_EXPORT_API`) * - mark function and header as deprecated (:cpp:macro:`QI_DEPRECATED_HEADER`, * :cpp:macro:`QI_API_DEPRECATED`) * - generate compiler warning (:cpp:macro:`QI_COMPILER_WARNING`) * - disallow copy and assign (:cpp:macro:`QI_DISALLOW_COPY_AND_ASSIGN`) * \endverbatim */ #ifndef _QI_MACRO_HPP_ # define _QI_MACRO_HPP_ # include <qi/preproc.hpp> #include <boost/predef/compiler.h> #include <boost/config.hpp> /** * \def QI_API_DEPRECATED * \brief Compiler flags to mark a function as deprecated. It will generate a * compiler warning. */ #if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED __declspec(deprecated) #else # define QI_API_DEPRECATED #endif /** * \def QI_API_DEPRECATED_MSG(msg__) * \brief Compiler flags to mark a function as deprecated. It will generate a * compiler warning. * \param msg__ A message providing a workaround. */ #if defined(__GNUC__) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED_MSG(msg__) __attribute__((deprecated(#msg__))) #elif defined(_MSC_VER) && !defined(QI_NO_API_DEPRECATED) # define QI_API_DEPRECATED_MSG(msg__) __declspec(deprecated(#msg__)) #else # define QI_API_DEPRECATED_MSG(msg__) #endif /** * \def QI_NORETURN * \brief Portable noreturn attribute, used to declare that a function does not return */ #if defined(__GNUC__) # define QI_NORETURN __attribute__((noreturn)) #elif defined(_MSC_VER) /// Portable noreturn attribute, used to declare that a function does not return # define QI_NORETURN __declspec(noreturn) #else # define QI_NORETURN #endif /** * \def QI_HAS_VARIABLE_LENGTH_ARRAY * \brief Mark compilers supporting variable length array (VLA) */ #if defined(__GNUC__) && !defined(__clang__) # define QI_HAS_VARIABLE_LENGTH_ARRAY 1 #else # define QI_HAS_VARIABLE_LENGTH_ARRAY 0 #endif // For shared library /** * \return the proper type specification for import/export * \param libname the name of your library. * This macro will use two preprocessor defines: * libname_EXPORTS (cmake convention) and libname_STATIC_BUILD. * Those macro can be unset or set to 0 to mean false, or set to empty or 1 to * mean true. * The first one must be true if the current compilation unit is within the library. * The second must be true if the library was built as a static archive. * The proper way to use this macro is to: * - Have your buildsystem set mylib_EXPORTS when building MYLIB * - Have your buildsystem produce a config.h file that * \#define mylib_STATIC_BUILD to 1 or empty if it is a static build, and * not define mylib_STATIC_BUILD or define it to 0 otherwise * In one header, write * \#include <mylib/config.h> * \#define MYLIB_API QI_LIB_API(mylib) */ #define QI_LIB_API(libname) QI_LIB_API_(BOOST_PP_CAT(libname, _EXPORTS), BOOST_PP_CAT(libname, _STATIC_BUILD)) #define QI_LIB_API_(IS_BUILDING_LIB, IS_LIB_STATIC_BUILD) \ QI_LIB_API_NORMALIZED(_QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_ , IS_BUILDING_LIB)), _QI_IS_ONE_OR_EMPTY(BOOST_PP_CAT(_, IS_LIB_STATIC_BUILD))) /** * \def QI_IMPORT_API * \brief Compiler flags to import a function or a class. */ /** * \def QI_EXPORT_API * \brief Compiler flags to export a function or a class. */ /** * \def QI_LIB_API_NORMALIZED(a, b) * \brief Each platform must provide a QI_LIB_API_NORMALIZED(isBuilding, isStatic) */ #if defined _WIN32 || defined __CYGWIN__ # define QI_EXPORT_API __declspec(dllexport) # define QI_IMPORT_API __declspec(dllimport) # define QI_LIB_API_NORMALIZED(exporting, isstatic) BOOST_PP_CAT(BOOST_PP_CAT(_QI_LIB_API_NORMALIZED_, exporting), isstatic) # define _QI_LIB_API_NORMALIZED_00 QI_IMPORT_API # define _QI_LIB_API_NORMALIZED_10 QI_EXPORT_API # define _QI_LIB_API_NORMALIZED_11 # define _QI_LIB_API_NORMALIZED_01 #elif __GNUC__ >= 4 # define QI_EXPORT_API __attribute__ ((visibility("default"))) # define QI_IMPORT_API QI_EXPORT_API # define QI_LIB_API_NORMALIZED(a, b) QI_EXPORT_API #else # define QI_IMPORT_API # define QI_EXPORT_API # define QI_LIB_API_NORMALIZED(a, b) #endif //! \cond internal // Macros adapted from opencv2.2 #if defined(_MSC_VER) #define QI_DO_PRAGMA(x) __pragma(x) #define __ALSTR2__(x) #x #define __ALSTR1__(x) __ALSTR2__(x) #define _ALMSVCLOC_ __FILE__ "("__ALSTR1__(__LINE__)") : " #define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_ALMSVCLOC_ _msg)) #elif defined(__GNUC__) #define QI_DO_PRAGMA(x) _Pragma (BOOST_PP_STRINGIZE(x)) #define QI_MSG_PRAGMA(_msg) QI_DO_PRAGMA(message (_msg)) #else #define QI_DO_PRAGMA(x) #define QI_MSG_PRAGMA(_msg) #endif //! \endcond /** * \def QI_COMPILER_WARNING(x) * \brief Generate a compiler warning. * \param x The string displayed as the warning. */ #if defined(QI_NO_COMPILER_WARNING) # define QI_COMPILER_WARNING(x) #else # define QI_COMPILER_WARNING(x) QI_MSG_PRAGMA("Warning: " #x) #endif /** * \def QI_DEPRECATED_HEADER(x) * \brief Generate a compiler warning stating a header is deprecated. * add a message to explain what user should do */ #if !defined(WITH_DEPRECATED) || defined(QI_NO_DEPRECATED_HEADER) # define QI_DEPRECATED_HEADER(x) #else # define QI_DEPRECATED_HEADER(x) QI_MSG_PRAGMA("\ This file includes at least one deprecated or antiquated ALDEBARAN header \ which may be removed without further notice in the next version. \ Please consult the changelog for details. " #x) #endif #ifdef __cplusplus namespace qi { template <typename T> struct IsClonable; }; #endif /** * \brief A macro used to deprecate another macro. Generate a compiler warning * when the given macro is used. * \param name The name of the macro. * \verbatim * Example: * * .. code-block:: cpp * * #define MAX(x,y)(QI_DEPRECATE_MACRO(MAX), x > y ? x : y) * \endverbatim */ #define QI_DEPRECATE_MACRO(name) \ QI_COMPILER_WARNING(name macro is deprecated.) /** * \deprecated Use boost::noncopyable instead. * * \verbatim * Example: * * .. code-block:: cpp * * class Foo : private boost::nonpyable * {}; * \endverbatim * * \brief A macro to disallow copy constructor and operator= * \param type The class name of which we want to forbid copy. * * \verbatim * .. note:: * This macro should always be in the private (or protected) section of a * class. * * Example: * * .. code-block:: cpp * * class Foo { * Foo(); * private: * QI_DISALLOW_COPY_AND_ASSIGN(Foo); * }; * \endverbatim */ #define QI_DISALLOW_COPY_AND_ASSIGN(type) \ QI_DEPRECATE_MACRO(QI_DISALLOW_COPY_AND_ASSIGN) \ type(type const &); \ void operator=(type const &); \ using _qi_not_clonable = int; \ template<typename U> friend struct ::qi::IsClonable /** * \def QI_WARN_UNUSED_RESULT * \brief Warns if the return value of the function is discarded. * * If a function declared QI_WARN_UNUSED_RESULT is called from a discarded-value expression other * than a cast to void, the compiler is encouraged to issue a warning. */ #if defined(__GNUC__) # define QI_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define QI_WARN_UNUSED_RESULT #endif /** * \def QI_ATTR_UNUSED * \brief This macro tags a attribute as unused. */ #if defined(__GNUC__) # define QI_ATTR_UNUSED __attribute__((unused)) #else # define QI_ATTR_UNUSED #endif /** * \brief This macro tags a parameter as unused. * * \verbatim * Example: * * .. code-block:: cpp * * int zero(int QI_UNUSED(x)) * { * return 0; * } * \endverbatim */ #define QI_UNUSED(x) /** * This macro prevents the compiler from emitting warning when a variable is defined but not used. * * Note: You may not use this macro to declare that a function parameters is unused. For such uses, * see QI_UNUSED. * * \verbatim * Example: * * .. code-block:: cpp * * void foo(std::vector<int> vec) * { * auto size = vec.size(); * // QI_ASSERT expands to nothing if debug informations are disabled in the compilation * // configuration, which would make the `size` variable unused. * QI_IGNORE_UNUSED(size); * QI_ASSERT(size > 2); * } * \endverbatim */ #define QI_IGNORE_UNUSED(x) (void)x /** * \def QI_UNIQ_DEF(A) * \brief A macro to append the line number of the parent macro usage, to define a * function in or a variable and avoid name collision. */ #define QI_UNIQ_DEF_LEVEL2_(A, B) A ## __uniq__ ## B #define QI_UNIQ_DEF_LEVEL1_(A, B) QI_UNIQ_DEF_LEVEL2_(A, B) #define QI_UNIQ_DEF(A) QI_UNIQ_DEF_LEVEL1_(A, __LINE__) /** * \def QI_NOEXCEPT(cond) * \brief Specify that a function may throw or not. Do nothing if noexcept is not available. * */ #define QI_NOEXCEPT(cond) BOOST_NOEXCEPT_IF(cond) /** * \def QI_NOEXCEPT_EXPR(expr) * \brief Specify that a function may throw if the given expression may throw. * Do nothing if noexcept is not available. */ #define QI_NOEXCEPT_EXPR(expr) BOOST_NOEXCEPT_IF(BOOST_NOEXCEPT_EXPR(expr)) /** * \def QI_WARNING_PUSH() * \brief Pushes the current state of warning flags so it can be retrieved later with QI_WARNING_POP. */ #if BOOST_COMP_MSVC # define QI_WARNING_PUSH() QI_DO_PRAGMA(warning(push)) #elif BOOST_COMP_GNUC # define QI_WARNING_PUSH() QI_DO_PRAGMA(GCC diagnostic push) #elif BOOST_COMP_CLANG # define QI_WARNING_PUSH() QI_DO_PRAGMA(clang diagnostic push) #endif /** * \def QI_WARNING_DISABLE(msvcCode, gccName) * \brief Disables the warning that is identified by msvcCode under MSVC or gccName under GCC and * Clang. */ #if BOOST_COMP_MSVC # define QI_WARNING_DISABLE(code, _) \ QI_DO_PRAGMA(warning(disable: code)) #elif BOOST_COMP_GNUC # define QI_WARNING_DISABLE(_, name) \ QI_DO_PRAGMA(GCC diagnostic ignored BOOST_PP_STRINGIZE(BOOST_PP_CAT(-W, name))) #elif BOOST_COMP_CLANG # define QI_WARNING_DISABLE(_, name) \ QI_DO_PRAGMA(clang diagnostic ignored BOOST_PP_STRINGIZE(BOOST_PP_CAT(-W, name))) #endif /** * \def QI_WARNING_POP() * \brief Pops the last state of warning flags that was pushed with QI_WARNING_PUSH(). */ #if BOOST_COMP_MSVC # define QI_WARNING_POP() QI_DO_PRAGMA(warning(pop)) #elif BOOST_COMP_GNUC # define QI_WARNING_POP() QI_DO_PRAGMA(GCC diagnostic pop) #elif BOOST_COMP_CLANG # define QI_WARNING_POP() QI_DO_PRAGMA(clang diagnostic pop) #endif /** * \def QI_FALLTHROUGH * \brief Declares that the current case in a switch falls through the next case. It is mandatory to * append a semicolon after this macro. */ #if defined(__has_cpp_attribute) && __cplusplus >= 201703L # if __has_cpp_attribute(fallthrough) # define QI_FALLTHROUGH [[fallthrough]] # endif #endif #ifndef QI_FALLTHROUGH # if __GNUC__ >= 7 # define QI_FALLTHROUGH __attribute__((fallthrough)) # elif defined(__clang__) && __cplusplus >= 201103L && \ defined(__has_feature) && defined(__has_warning) # if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough") # define QI_FALLTHROUGH [[clang::fallthrough]] # endif # endif #endif #ifndef QI_FALLTHROUGH # define QI_FALLTHROUGH ((void)0) #endif #endif // _QI_MACRO_HPP_ <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" namespace dai { /// RawCameraControl structure struct RawCameraControl : public RawBuffer { enum class Command : uint8_t { START_STREAM = 1, STOP_STREAM = 2, STILL_CAPTURE = 3, MOVE_LENS = 4, /* [1] lens position: 0-255 */ AF_TRIGGER = 5, AE_MANUAL = 6, /* [1] exposure time [us] * [2] sensitivity [iso] * [3] frame duration [us] */ AE_AUTO = 7, AWB_MODE = 8, /* [1] awb_mode: AutoWhiteBalanceMode */ SCENE_MODE = 9, /* [1] scene_mode: SceneMode */ ANTIBANDING_MODE = 10, /* [1] antibanding_mode: AntiBandingMode */ EXPOSURE_COMPENSATION = 11, /* [1] value */ AE_LOCK = 13, /* [1] ae_lock_mode: bool */ AE_TARGET_FPS_RANGE = 14, /* [1] min_fps * [2] max_fps */ AWB_LOCK = 16, /* [1] awb_lock_mode: bool */ CAPTURE_INTENT = 17, /* [1] capture_intent_mode: CaptureIntent */ CONTROL_MODE = 18, /* [1] control_mode: ControlMode */ FRAME_DURATION = 21, /* [1] frame_duration */ SENSITIVITY = 23, /* [1] iso_val */ EFFECT_MODE = 24, /* [1] effect_mode: EffectMode */ AF_MODE = 26, /* [1] af_mode: AutoFocusMode */ NOISE_REDUCTION_STRENGTH = 27, /* [1] value */ SATURATION = 28, /* [1] value */ BRIGHTNESS = 31, /* [1] value */ STREAM_FORMAT = 33, /* [1] format */ RESOLUTION = 34, /* [1] width * [2] height */ SHARPNESS = 35, /* [1] value */ CUSTOM_USECASE = 40, /* [1] value */ CUSTOM_CAPT_MODE = 41, /* [1] value */ CUSTOM_EXP_BRACKETS = 42, /* [1] val1 * [2] val2 * [3] val3 */ CUSTOM_CAPTURE = 43, /* [1] value */ CONTRAST = 44, /* [1] value */ AE_REGION = 45, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ AF_REGION = 46, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ LUMA_DENOISE = 47, /* [1] value */ CHROMA_DENOISE = 48, /* [1] value */ }; enum class AutoFocusMode : uint8_t { /// Autofocus disabled. Suitable for manual focus OFF = 0, /// Runs autofocus once at startup, and at subsequent trigger commands AUTO, /// TODO MACRO, /// Runs autofocus when the scene is detected as out-of-focus CONTINUOUS_VIDEO, CONTINUOUS_PICTURE, EDOF, }; enum class AutoWhiteBalanceMode : uint8_t { OFF = 0, AUTO, INCANDESCENT, FLUORESCENT, WARM_FLUORESCENT, DAYLIGHT, CLOUDY_DAYLIGHT, TWILIGHT, SHADE, }; enum class SceneMode : uint8_t { UNSUPPORTED = 0, FACE_PRIORITY, ACTION, PORTRAIT, LANDSCAPE, NIGHT, NIGHT_PORTRAIT, THEATRE, BEACH, SNOW, SUNSET, STEADYPHOTO, FIREWORKS, SPORTS, PARTY, CANDLELIGHT, BARCODE, }; enum class AntiBandingMode : uint8_t { OFF = 0, MAINS_50_HZ, MAINS_60_HZ, AUTO, }; enum class CaptureIntent : uint8_t { CUSTOM = 0, PREVIEW, STILL_CAPTURE, VIDEO_RECORD, VIDEO_SNAPSHOT, ZERO_SHUTTER_LAG, }; enum class ControlMode : uint8_t { OFF = 0, AUTO, USE_SCENE_MODE, }; enum class EffectMode : uint8_t { OFF = 0, MONO, NEGATIVE, SOLARIZE, SEPIA, POSTERIZE, WHITEBOARD, BLACKBOARD, AQUA, }; struct ManualExposureParams { uint32_t exposureTimeUs; uint32_t sensitivityIso; uint32_t frameDurationUs; NLOHMANN_DEFINE_TYPE_INTRUSIVE(ManualExposureParams, exposureTimeUs, sensitivityIso, frameDurationUs); }; // AE_REGION / AF_REGION struct RegionParams { uint16_t x; uint16_t y; uint16_t width; uint16_t height; // Set to 1 for now. TODO uint32_t priority; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RegionParams, x, y, width, height, priority); }; uint64_t cmdMask = 0; AutoFocusMode autoFocusMode = AutoFocusMode::CONTINUOUS_VIDEO; /** * Lens/VCM position, range: 0..255. Used with `autoFocusMode = OFF`. * With current IMX378 modules: * - max 255: macro focus, at 8cm distance * - infinite focus at about 120..130 (may vary from module to module) * - lower values lead to out-of-focus (lens too close to the sensor array) */ uint8_t lensPosition = 0; ManualExposureParams expManual; RegionParams aeRegion, afRegion; AutoWhiteBalanceMode awbMode; SceneMode sceneMode; AntiBandingMode antiBandingMode; EffectMode effectMode; bool aeLockMode; bool awbLockMode; int8_t expCompensation; // -9 .. 9 int8_t brightness; // -10 .. 10 int8_t contrast; // -10 .. 10 int8_t saturation; // -10 .. 10 uint8_t sharpness; // 0 .. 4 uint8_t lumaDenoise; // 0 .. 4 uint8_t chromaDenoise; // 0 .. 4 void setCommand(Command cmd, bool value = true) { uint64_t mask = 1ull << (uint8_t)cmd; if(value) { cmdMask |= mask; } else { cmdMask &= ~mask; } } void clearCommand(Command cmd) { setCommand(cmd, false); } bool getCommand(Command cmd) { return !!(cmdMask & (1ull << (uint8_t)cmd)); } void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::CameraControl; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawCameraControl, cmdMask, autoFocusMode, lensPosition, expManual, aeRegion, afRegion, awbMode, sceneMode, antiBandingMode, aeLockMode, awbLockMode, effectMode, expCompensation, brightness, contrast, saturation, sharpness, lumaDenoise, chromaDenoise); }; } // namespace dai <commit_msg>CameraControl: add EXTERNAL_TRIGGER command, with num frames config<commit_after>#pragma once #include <cstdint> #include <nlohmann/json.hpp> #include <vector> #include "DatatypeEnum.hpp" #include "RawBuffer.hpp" namespace dai { /// RawCameraControl structure struct RawCameraControl : public RawBuffer { enum class Command : uint8_t { START_STREAM = 1, STOP_STREAM = 2, STILL_CAPTURE = 3, MOVE_LENS = 4, /* [1] lens position: 0-255 */ AF_TRIGGER = 5, AE_MANUAL = 6, /* [1] exposure time [us] * [2] sensitivity [iso] * [3] frame duration [us] */ AE_AUTO = 7, AWB_MODE = 8, /* [1] awb_mode: AutoWhiteBalanceMode */ SCENE_MODE = 9, /* [1] scene_mode: SceneMode */ ANTIBANDING_MODE = 10, /* [1] antibanding_mode: AntiBandingMode */ EXPOSURE_COMPENSATION = 11, /* [1] value */ AE_LOCK = 13, /* [1] ae_lock_mode: bool */ AE_TARGET_FPS_RANGE = 14, /* [1] min_fps * [2] max_fps */ AWB_LOCK = 16, /* [1] awb_lock_mode: bool */ CAPTURE_INTENT = 17, /* [1] capture_intent_mode: CaptureIntent */ CONTROL_MODE = 18, /* [1] control_mode: ControlMode */ FRAME_DURATION = 21, /* [1] frame_duration */ SENSITIVITY = 23, /* [1] iso_val */ EFFECT_MODE = 24, /* [1] effect_mode: EffectMode */ AF_MODE = 26, /* [1] af_mode: AutoFocusMode */ NOISE_REDUCTION_STRENGTH = 27, /* [1] value */ SATURATION = 28, /* [1] value */ BRIGHTNESS = 31, /* [1] value */ STREAM_FORMAT = 33, /* [1] format */ RESOLUTION = 34, /* [1] width * [2] height */ SHARPNESS = 35, /* [1] value */ CUSTOM_USECASE = 40, /* [1] value */ CUSTOM_CAPT_MODE = 41, /* [1] value */ CUSTOM_EXP_BRACKETS = 42, /* [1] val1 * [2] val2 * [3] val3 */ CUSTOM_CAPTURE = 43, /* [1] value */ CONTRAST = 44, /* [1] value */ AE_REGION = 45, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ AF_REGION = 46, /* [1] x * [2] y * [3] width * [4] height * [5] priority */ LUMA_DENOISE = 47, /* [1] value */ CHROMA_DENOISE = 48, /* [1] value */ EXTERNAL_TRIGGER = 50, }; enum class AutoFocusMode : uint8_t { /// Autofocus disabled. Suitable for manual focus OFF = 0, /// Runs autofocus once at startup, and at subsequent trigger commands AUTO, /// TODO MACRO, /// Runs autofocus when the scene is detected as out-of-focus CONTINUOUS_VIDEO, CONTINUOUS_PICTURE, EDOF, }; enum class AutoWhiteBalanceMode : uint8_t { OFF = 0, AUTO, INCANDESCENT, FLUORESCENT, WARM_FLUORESCENT, DAYLIGHT, CLOUDY_DAYLIGHT, TWILIGHT, SHADE, }; enum class SceneMode : uint8_t { UNSUPPORTED = 0, FACE_PRIORITY, ACTION, PORTRAIT, LANDSCAPE, NIGHT, NIGHT_PORTRAIT, THEATRE, BEACH, SNOW, SUNSET, STEADYPHOTO, FIREWORKS, SPORTS, PARTY, CANDLELIGHT, BARCODE, }; enum class AntiBandingMode : uint8_t { OFF = 0, MAINS_50_HZ, MAINS_60_HZ, AUTO, }; enum class CaptureIntent : uint8_t { CUSTOM = 0, PREVIEW, STILL_CAPTURE, VIDEO_RECORD, VIDEO_SNAPSHOT, ZERO_SHUTTER_LAG, }; enum class ControlMode : uint8_t { OFF = 0, AUTO, USE_SCENE_MODE, }; enum class EffectMode : uint8_t { OFF = 0, MONO, NEGATIVE, SOLARIZE, SEPIA, POSTERIZE, WHITEBOARD, BLACKBOARD, AQUA, }; struct ManualExposureParams { uint32_t exposureTimeUs; uint32_t sensitivityIso; uint32_t frameDurationUs; NLOHMANN_DEFINE_TYPE_INTRUSIVE(ManualExposureParams, exposureTimeUs, sensitivityIso, frameDurationUs); }; // AE_REGION / AF_REGION struct RegionParams { uint16_t x; uint16_t y; uint16_t width; uint16_t height; // Set to 1 for now. TODO uint32_t priority; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RegionParams, x, y, width, height, priority); }; uint64_t cmdMask = 0; AutoFocusMode autoFocusMode = AutoFocusMode::CONTINUOUS_VIDEO; /** * Lens/VCM position, range: 0..255. Used with `autoFocusMode = OFF`. * With current IMX378 modules: * - max 255: macro focus, at 8cm distance * - infinite focus at about 120..130 (may vary from module to module) * - lower values lead to out-of-focus (lens too close to the sensor array) */ uint8_t lensPosition = 0; ManualExposureParams expManual; RegionParams aeRegion, afRegion; AutoWhiteBalanceMode awbMode; SceneMode sceneMode; AntiBandingMode antiBandingMode; EffectMode effectMode; bool aeLockMode; bool awbLockMode; int8_t expCompensation; // -9 .. 9 int8_t brightness; // -10 .. 10 int8_t contrast; // -10 .. 10 int8_t saturation; // -10 .. 10 uint8_t sharpness; // 0 .. 4 uint8_t lumaDenoise; // 0 .. 4 uint8_t chromaDenoise; // 0 .. 4 uint8_t lowPowerNumFramesBurst; void setCommand(Command cmd, bool value = true) { uint64_t mask = 1ull << (uint8_t)cmd; if(value) { cmdMask |= mask; } else { cmdMask &= ~mask; } } void clearCommand(Command cmd) { setCommand(cmd, false); } bool getCommand(Command cmd) { return !!(cmdMask & (1ull << (uint8_t)cmd)); } void serialize(std::vector<std::uint8_t>& metadata, DatatypeEnum& datatype) const override { nlohmann::json j = *this; metadata = nlohmann::json::to_msgpack(j); datatype = DatatypeEnum::CameraControl; }; NLOHMANN_DEFINE_TYPE_INTRUSIVE(RawCameraControl, cmdMask, autoFocusMode, lensPosition, expManual, aeRegion, afRegion, awbMode, sceneMode, antiBandingMode, aeLockMode, awbLockMode, effectMode, expCompensation, brightness, contrast, saturation, sharpness, lumaDenoise, chromaDenoise, lowPowerNumFramesBurst); }; } // namespace dai <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #ifndef _Stroika_Foundation_Common_Compare_inl_ #define _Stroika_Foundation_Common_Compare_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika::Foundation::Common { /* ******************************************************************************** ***************************** ThreeWayComparer<T> ****************************** ******************************************************************************** */ template <typename T, typename... ARGS> constexpr ThreeWayComparer<T, ARGS...>::ThreeWayComparer (ARGS... args) : fArgs_ (make_tuple (args...)) { } template <typename T, typename... ARGS> template <class TT, class UU, typename Q, enable_if_t<Private_::HasThreeWayComparer_v<Q>>*> constexpr auto ThreeWayComparer<T, ARGS...>::operator() (UU&& lhs, TT&& rhs) const { #if qCompilerAndStdLib_make_from_tuple_Buggy if constexpr (tuple_size_v<decltype (fArgs_)> == 0) { return typename Q::ThreeWayComparer{}(lhs, rhs); } else { return make_from_tuple<typename Q::ThreeWayComparer> (fArgs_) (lhs, rhs); } #else return make_from_tuple<typename Q::ThreeWayComparer> (fArgs_) (lhs, rhs); #endif } template <typename T, typename... ARGS> template <class TT, class UU, typename Q, enable_if_t<Private_::HasThreeWayComparerTemplate_v<Q>>*> constexpr auto ThreeWayComparer<T, ARGS...>::operator() (UU&& lhs, TT&& rhs) const { #if qCompilerAndStdLib_make_from_tuple_Buggy if constexpr (tuple_size_v<decltype (fArgs_)> == 0) { return typename Q::template ThreeWayComparer<>{}(lhs, rhs); } else { return make_from_tuple<typename Q::template ThreeWayComparer<>> (fArgs_) (lhs, rhs); } #else return make_from_tuple<typename Q::template ThreeWayComparer<>> (fArgs_) (lhs, rhs); #endif } template <typename T, typename... ARGS> template <class TT, class UU, typename Q, enable_if_t<not Private_::HasThreeWayComparer_v<Q> and not Private_::HasThreeWayComparerTemplate_v<Q>>*> constexpr auto ThreeWayComparer<T, ARGS...>::operator() (UU&& lhs, TT&& rhs) const { return compare_three_way<UU, TT>{}(forward<TT> (lhs), forward<TT> (rhs)); } /* ******************************************************************************** ************************* ThreeWayCompare<LT, RT> ****************************** ******************************************************************************** */ template <typename LT, typename RT> constexpr Common::strong_ordering ThreeWayCompare (LT&& lhs, RT&& rhs) { return compare_three_way<LT, RT>{}(forward<LT> (lhs), forward<RT> (rhs)); // soon - maybe now - replace with - return ThreeWayComparer<LT>{}(forward<LT> (lhs), forward<RT> (rhs)); } /* ******************************************************************************** *************** OptionalThreeWayCompare<T, TCOMPARER> ************************** ******************************************************************************** */ template <typename T, typename TCOMPARER> constexpr OptionalThreeWayComparer<T, TCOMPARER>::OptionalThreeWayComparer (const TCOMPARER& comparer) : fTComparer_ (comparer) { } template <typename T, typename TCOMPARER> constexpr strong_ordering OptionalThreeWayComparer<T, TCOMPARER>::operator() (const optional<T>& lhs, const optional<T>& rhs) const { if (lhs and rhs) { return fTComparer_ (*lhs, *rhs); } if (not lhs and not rhs) { return kEqual; } // treat missing as less than present if (lhs) { return kGreater; } else { return kLess; } } /* ******************************************************************************** *************************** CompareResultNormalizer **************************** ******************************************************************************** */ template <typename FROM_INT_TYPE> inline strong_ordering CompareResultNormalizer (FROM_INT_TYPE f) { if (f == 0) { return Common::kEqual; } else { Assert (f < 0 or f > 0); return f < 0 ? Common::kLess : Common::kGreater; } } /* ******************************************************************************** ****************** IsPotentiallyComparerRelation<FUNCTOR> ********************** ******************************************************************************** */ namespace PRIVATE_ { template <typename FUNCTOR_ARG, typename FUNCTOR, typename RESULT = result_of_t<FUNCTOR (FUNCTOR_ARG, FUNCTOR_ARG)>> constexpr bool IsPotentiallyComparerRelation_Helper_ (nullptr_t) { return Configuration::is_callable<FUNCTOR>::value and is_convertible_v<RESULT, bool>; } template <typename FUNCTOR_ARG, typename FUNCTOR> constexpr bool IsPotentiallyComparerRelation_Helper_ (...) { return false; } } template <typename FUNCTOR_ARG, typename FUNCTOR> constexpr bool IsPotentiallyComparerRelation () { return PRIVATE_::IsPotentiallyComparerRelation_Helper_<FUNCTOR_ARG, FUNCTOR> (nullptr); } template <typename FUNCTOR_ARG, typename FUNCTOR> constexpr bool IsPotentiallyComparerRelation (const FUNCTOR&) { return IsPotentiallyComparerRelation<FUNCTOR_ARG, FUNCTOR> (); } /* ******************************************************************************** ********************* IsEqualsComparer<COMPARER> ******************************* ******************************************************************************** */ template <typename COMPARER> constexpr bool IsEqualsComparer () { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals; } template <typename COMPARER> constexpr bool IsEqualsComparer (const COMPARER&) { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals; } /* ******************************************************************************** ********************* IsStrictInOrderComparer<COMPARER> ************************ ******************************************************************************** */ template <typename COMPARER> constexpr bool IsStrictInOrderComparer () { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder; } template <typename COMPARER> constexpr bool IsStrictInOrderComparer (const COMPARER&) { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder; } /* ******************************************************************************** ********** ComparisonRelationDeclaration<TYPE, ACTUAL_COMPARER> **************** ******************************************************************************** */ template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> constexpr ComparisonRelationType ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::kComparisonRelationKind; template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (const ACTUAL_COMPARER& actualComparer) : fActualComparer (actualComparer) { } template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (ACTUAL_COMPARER&& actualComparer) : fActualComparer (move (actualComparer)) { } template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> template <typename LT, typename RT> inline constexpr bool ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::operator() (LT&& lhs, RT&& rhs) const { return fActualComparer (forward<LT> (lhs), forward<RT> (rhs)); } /* ******************************************************************************** **************************** DeclareEqualsComparer ***************************** ******************************************************************************** */ template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (const FUNCTOR& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{f}; } template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (FUNCTOR&& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{move (f)}; } /* ******************************************************************************** ********************************* DeclareInOrderComparer *********************** ******************************************************************************** */ template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (const FUNCTOR& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{f}; } template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (FUNCTOR&& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{move (f)}; } /* ******************************************************************************** ********************* InOrderComparerAdapter<BASE_COMPARER> ******************** ******************************************************************************** */ template <typename BASE_COMPARER> constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (const BASE_COMPARER& baseComparer) : fBASE_COMPARER_ (baseComparer) { } template <typename BASE_COMPARER> constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (BASE_COMPARER&& baseComparer) : fBASE_COMPARER_ (move (baseComparer)) { } template <typename BASE_COMPARER> template <typename T> constexpr inline bool InOrderComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const { /* * It would be nice to be able to use switch statement but use constexpr if because * inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05 */ constexpr auto kRelationKind = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind; auto baseComparison = fBASE_COMPARER_ (lhs, rhs); if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) { return kRelationKind; } if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) { return baseComparison and not fBASE_COMPARER_ (rhs, lhs); } if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) { return baseComparison < 0; } AssertNotReached (); return false; } /* ******************************************************************************** ********************* EqualsComparerAdapter<BASE_COMPARER> ********************* ******************************************************************************** */ template <typename BASE_COMPARER> constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (const BASE_COMPARER& baseComparer) : fBASE_COMPARER_ (baseComparer) { } template <typename BASE_COMPARER> constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (BASE_COMPARER&& baseComparer) : fBASE_COMPARER_ (move (baseComparer)) { } template <typename BASE_COMPARER> template <typename T> constexpr bool EqualsComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const { /* * It would be nice to be able to use switch statement but use constexpr if because * inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05 */ constexpr auto kRelationKind = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind; auto baseComparison = fBASE_COMPARER_ (lhs, rhs); if constexpr (kRelationKind == ComparisonRelationType::eEquals) { return baseComparison; } if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) { return not baseComparison and not fBASE_COMPARER_ (rhs, lhs); } if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) { return baseComparison and fBASE_COMPARER_ (rhs, lhs); } if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) { return baseComparison == kEqual; } AssertNotReached (); return false; } /* ******************************************************************************** ********************* ThreeWayComparerAdapter<BASE_COMPARER> ******************* ******************************************************************************** */ template <typename BASE_COMPARER> constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (const BASE_COMPARER& baseComparer) : fBASE_COMPARER_ (baseComparer) { } template <typename BASE_COMPARER> constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (BASE_COMPARER&& baseComparer) : fBASE_COMPARER_ (move (baseComparer)) { } template <typename BASE_COMPARER> template <typename T> constexpr strong_ordering ThreeWayComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const { /* * It would be nice to be able to use switch statement but use constexpr if because * inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05 */ constexpr auto kRelationKind = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind; auto baseComparison = fBASE_COMPARER_ (lhs, rhs); if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) { return baseComparison ? kLess : (fBASE_COMPARER_ (rhs, lhs) ? kGreater : kEqual); } if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) { return baseComparison; } AssertNotReached (); return kEqual; } } #endif /*_Stroika_Foundation_Common_Compare_inl_*/ <commit_msg>switch use of Common::ThreeWayComparer to compare_three_way and added deprecation use warning<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ #ifndef _Stroika_Foundation_Common_Compare_inl_ #define _Stroika_Foundation_Common_Compare_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika::Foundation::Common { DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wdeprecated\""); /* ******************************************************************************** ***************************** ThreeWayComparer<T> ****************************** ******************************************************************************** */ template <typename T, typename... ARGS> constexpr ThreeWayComparer<T, ARGS...>::ThreeWayComparer (ARGS... args) : fArgs_ (make_tuple (args...)) { } template <typename T, typename... ARGS> template <class TT, class UU, typename Q, enable_if_t<Private_::HasThreeWayComparer_v<Q>>*> constexpr auto ThreeWayComparer<T, ARGS...>::operator() (UU&& lhs, TT&& rhs) const { #if qCompilerAndStdLib_make_from_tuple_Buggy if constexpr (tuple_size_v<decltype (fArgs_)> == 0) { return typename Q::ThreeWayComparer{}(lhs, rhs); } else { return make_from_tuple<typename Q::ThreeWayComparer> (fArgs_) (lhs, rhs); } #else return make_from_tuple<typename Q::ThreeWayComparer> (fArgs_) (lhs, rhs); #endif } template <typename T, typename... ARGS> template <class TT, class UU, typename Q, enable_if_t<Private_::HasThreeWayComparerTemplate_v<Q>>*> constexpr auto ThreeWayComparer<T, ARGS...>::operator() (UU&& lhs, TT&& rhs) const { #if qCompilerAndStdLib_make_from_tuple_Buggy if constexpr (tuple_size_v<decltype (fArgs_)> == 0) { return typename Q::template ThreeWayComparer<>{}(lhs, rhs); } else { return make_from_tuple<typename Q::template ThreeWayComparer<>> (fArgs_) (lhs, rhs); } #else return make_from_tuple<typename Q::template ThreeWayComparer<>> (fArgs_) (lhs, rhs); #endif } template <typename T, typename... ARGS> template <class TT, class UU, typename Q, enable_if_t<not Private_::HasThreeWayComparer_v<Q> and not Private_::HasThreeWayComparerTemplate_v<Q>>*> constexpr auto ThreeWayComparer<T, ARGS...>::operator() (UU&& lhs, TT&& rhs) const { return compare_three_way<UU, TT>{}(forward<TT> (lhs), forward<TT> (rhs)); } DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wdeprecated\""); /* ******************************************************************************** ************************* ThreeWayCompare<LT, RT> ****************************** ******************************************************************************** */ template <typename LT, typename RT> constexpr Common::strong_ordering ThreeWayCompare (LT&& lhs, RT&& rhs) { return compare_three_way<LT, RT>{}(forward<LT> (lhs), forward<RT> (rhs)); // soon - maybe now - replace with - return ThreeWayComparer<LT>{}(forward<LT> (lhs), forward<RT> (rhs)); } /* ******************************************************************************** *************** OptionalThreeWayCompare<T, TCOMPARER> ************************** ******************************************************************************** */ template <typename T, typename TCOMPARER> constexpr OptionalThreeWayComparer<T, TCOMPARER>::OptionalThreeWayComparer (const TCOMPARER& comparer) : fTComparer_ (comparer) { } template <typename T, typename TCOMPARER> constexpr strong_ordering OptionalThreeWayComparer<T, TCOMPARER>::operator() (const optional<T>& lhs, const optional<T>& rhs) const { if (lhs and rhs) { return fTComparer_ (*lhs, *rhs); } if (not lhs and not rhs) { return kEqual; } // treat missing as less than present if (lhs) { return kGreater; } else { return kLess; } } /* ******************************************************************************** *************************** CompareResultNormalizer **************************** ******************************************************************************** */ template <typename FROM_INT_TYPE> inline strong_ordering CompareResultNormalizer (FROM_INT_TYPE f) { if (f == 0) { return Common::kEqual; } else { Assert (f < 0 or f > 0); return f < 0 ? Common::kLess : Common::kGreater; } } /* ******************************************************************************** ****************** IsPotentiallyComparerRelation<FUNCTOR> ********************** ******************************************************************************** */ namespace PRIVATE_ { template <typename FUNCTOR_ARG, typename FUNCTOR, typename RESULT = result_of_t<FUNCTOR (FUNCTOR_ARG, FUNCTOR_ARG)>> constexpr bool IsPotentiallyComparerRelation_Helper_ (nullptr_t) { return Configuration::is_callable<FUNCTOR>::value and is_convertible_v<RESULT, bool>; } template <typename FUNCTOR_ARG, typename FUNCTOR> constexpr bool IsPotentiallyComparerRelation_Helper_ (...) { return false; } } template <typename FUNCTOR_ARG, typename FUNCTOR> constexpr bool IsPotentiallyComparerRelation () { return PRIVATE_::IsPotentiallyComparerRelation_Helper_<FUNCTOR_ARG, FUNCTOR> (nullptr); } template <typename FUNCTOR_ARG, typename FUNCTOR> constexpr bool IsPotentiallyComparerRelation (const FUNCTOR&) { return IsPotentiallyComparerRelation<FUNCTOR_ARG, FUNCTOR> (); } /* ******************************************************************************** ********************* IsEqualsComparer<COMPARER> ******************************* ******************************************************************************** */ template <typename COMPARER> constexpr bool IsEqualsComparer () { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals; } template <typename COMPARER> constexpr bool IsEqualsComparer (const COMPARER&) { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eEquals; } /* ******************************************************************************** ********************* IsStrictInOrderComparer<COMPARER> ************************ ******************************************************************************** */ template <typename COMPARER> constexpr bool IsStrictInOrderComparer () { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder; } template <typename COMPARER> constexpr bool IsStrictInOrderComparer (const COMPARER&) { return ExtractComparisonTraits<COMPARER>::kComparisonRelationKind == ComparisonRelationType::eStrictInOrder; } /* ******************************************************************************** ********** ComparisonRelationDeclaration<TYPE, ACTUAL_COMPARER> **************** ******************************************************************************** */ template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> constexpr ComparisonRelationType ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::kComparisonRelationKind; template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (const ACTUAL_COMPARER& actualComparer) : fActualComparer (actualComparer) { } template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> inline constexpr ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::ComparisonRelationDeclaration (ACTUAL_COMPARER&& actualComparer) : fActualComparer (move (actualComparer)) { } template <ComparisonRelationType KIND, typename ACTUAL_COMPARER> template <typename LT, typename RT> inline constexpr bool ComparisonRelationDeclaration<KIND, ACTUAL_COMPARER>::operator() (LT&& lhs, RT&& rhs) const { return fActualComparer (forward<LT> (lhs), forward<RT> (rhs)); } /* ******************************************************************************** **************************** DeclareEqualsComparer ***************************** ******************************************************************************** */ template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (const FUNCTOR& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{f}; } template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR> DeclareEqualsComparer (FUNCTOR&& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eEquals, FUNCTOR>{move (f)}; } /* ******************************************************************************** ********************************* DeclareInOrderComparer *********************** ******************************************************************************** */ template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (const FUNCTOR& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{f}; } template <typename FUNCTOR> constexpr inline Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR> DeclareInOrderComparer (FUNCTOR&& f) { return Common::ComparisonRelationDeclaration<ComparisonRelationType::eStrictInOrder, FUNCTOR>{move (f)}; } /* ******************************************************************************** ********************* InOrderComparerAdapter<BASE_COMPARER> ******************** ******************************************************************************** */ template <typename BASE_COMPARER> constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (const BASE_COMPARER& baseComparer) : fBASE_COMPARER_ (baseComparer) { } template <typename BASE_COMPARER> constexpr inline InOrderComparerAdapter<BASE_COMPARER>::InOrderComparerAdapter (BASE_COMPARER&& baseComparer) : fBASE_COMPARER_ (move (baseComparer)) { } template <typename BASE_COMPARER> template <typename T> constexpr inline bool InOrderComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const { /* * It would be nice to be able to use switch statement but use constexpr if because * inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05 */ constexpr auto kRelationKind = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind; auto baseComparison = fBASE_COMPARER_ (lhs, rhs); if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) { return kRelationKind; } if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) { return baseComparison and not fBASE_COMPARER_ (rhs, lhs); } if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) { return baseComparison < 0; } AssertNotReached (); return false; } /* ******************************************************************************** ********************* EqualsComparerAdapter<BASE_COMPARER> ********************* ******************************************************************************** */ template <typename BASE_COMPARER> constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (const BASE_COMPARER& baseComparer) : fBASE_COMPARER_ (baseComparer) { } template <typename BASE_COMPARER> constexpr EqualsComparerAdapter<BASE_COMPARER>::EqualsComparerAdapter (BASE_COMPARER&& baseComparer) : fBASE_COMPARER_ (move (baseComparer)) { } template <typename BASE_COMPARER> template <typename T> constexpr bool EqualsComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const { /* * It would be nice to be able to use switch statement but use constexpr if because * inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05 */ constexpr auto kRelationKind = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind; auto baseComparison = fBASE_COMPARER_ (lhs, rhs); if constexpr (kRelationKind == ComparisonRelationType::eEquals) { return baseComparison; } if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) { return not baseComparison and not fBASE_COMPARER_ (rhs, lhs); } if constexpr (kRelationKind == ComparisonRelationType::eInOrderOrEquals) { return baseComparison and fBASE_COMPARER_ (rhs, lhs); } if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) { return baseComparison == kEqual; } AssertNotReached (); return false; } /* ******************************************************************************** ********************* ThreeWayComparerAdapter<BASE_COMPARER> ******************* ******************************************************************************** */ template <typename BASE_COMPARER> constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (const BASE_COMPARER& baseComparer) : fBASE_COMPARER_ (baseComparer) { } template <typename BASE_COMPARER> constexpr ThreeWayComparerAdapter<BASE_COMPARER>::ThreeWayComparerAdapter (BASE_COMPARER&& baseComparer) : fBASE_COMPARER_ (move (baseComparer)) { } template <typename BASE_COMPARER> template <typename T> constexpr strong_ordering ThreeWayComparerAdapter<BASE_COMPARER>::operator() (const T& lhs, const T& rhs) const { /* * It would be nice to be able to use switch statement but use constexpr if because * inappropriate 'cases' that wouldn't get executed might not compile -- LGP 2020-05-05 */ constexpr auto kRelationKind = ExtractComparisonTraits<BASE_COMPARER>::kComparisonRelationKind; auto baseComparison = fBASE_COMPARER_ (lhs, rhs); if constexpr (kRelationKind == ComparisonRelationType::eStrictInOrder) { return baseComparison ? kLess : (fBASE_COMPARER_ (rhs, lhs) ? kGreater : kEqual); } if constexpr (kRelationKind == ComparisonRelationType::eThreeWayCompare) { return baseComparison; } AssertNotReached (); return kEqual; } } #endif /*_Stroika_Foundation_Common_Compare_inl_*/ <|endoftext|>
<commit_before>/* * test/suicide.cpp * Copyright 2013 Google Inc. All Rights Reserved. * * 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 "backward.hpp" #include "test/test.hpp" #include <cstdio> #ifndef _WIN32 #include <sys/resource.h> #endif using namespace backward; void badass_function() { char *ptr = (char *)42; *ptr = 42; } TEST_SEGFAULT(invalid_write) { badass_function(); } int you_shall_not_pass() { char *ptr = (char *)42; int v = *ptr; return v; } TEST_SEGFAULT(invalid_read) { int v = you_shall_not_pass(); std::cout << "v=" << v << std::endl; } void abort_abort_I_repeat_abort_abort() { std::cout << "Jumping off the boat!" << std::endl; abort(); } TEST_ABORT(calling_abort) { abort_abort_I_repeat_abort_abort(); } // aarch64 and mips does not trap Division by zero #if !defined(__aarch64__) && !defined(__mips__) volatile int zero = 0; int divide_by_zero() { std::cout << "And the wild black hole appears..." << std::endl; int v = 42 / zero; return v; } TEST_DIVZERO(divide_by_zero) { int v = divide_by_zero(); std::cout << "v=" << v << std::endl; } #endif // Darwin does not allow RLIMIT_STACK to be reduced #ifndef __APPLE__ int bye_bye_stack(int i) { return bye_bye_stack(i + 1) + bye_bye_stack(i * 2); } TEST_SEGFAULT(stackoverflow) { #ifndef _WIN32 struct rlimit limit; limit.rlim_max = 8096; setrlimit(RLIMIT_STACK, &limit); #endif int r = bye_bye_stack(42); std::cout << "r=" << r << std::endl; } #endif <commit_msg>Fix tests on PowerPC and RISC-V<commit_after>/* * test/suicide.cpp * Copyright 2013 Google Inc. All Rights Reserved. * * 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 "backward.hpp" #include "test/test.hpp" #include <cstdio> #ifndef _WIN32 #include <sys/resource.h> #endif using namespace backward; void badass_function() { char *ptr = (char *)42; *ptr = 42; } TEST_SEGFAULT(invalid_write) { badass_function(); } int you_shall_not_pass() { char *ptr = (char *)42; int v = *ptr; return v; } TEST_SEGFAULT(invalid_read) { int v = you_shall_not_pass(); std::cout << "v=" << v << std::endl; } void abort_abort_I_repeat_abort_abort() { std::cout << "Jumping off the boat!" << std::endl; abort(); } TEST_ABORT(calling_abort) { abort_abort_I_repeat_abort_abort(); } // aarch64, mips, PowerPC and RISC-V do not trap Division by zero #if !defined(__aarch64__) && !defined(__mips__) && !defined (__powerpc__) && !defined (__riscv) volatile int zero = 0; int divide_by_zero() { std::cout << "And the wild black hole appears..." << std::endl; int v = 42 / zero; return v; } TEST_DIVZERO(divide_by_zero) { int v = divide_by_zero(); std::cout << "v=" << v << std::endl; } #endif // Darwin does not allow RLIMIT_STACK to be reduced #ifndef __APPLE__ int bye_bye_stack(int i) { return bye_bye_stack(i + 1) + bye_bye_stack(i * 2); } TEST_SEGFAULT(stackoverflow) { #ifndef _WIN32 struct rlimit limit; limit.rlim_max = 8096; setrlimit(RLIMIT_STACK, &limit); #endif int r = bye_bye_stack(42); std::cout << "r=" << r << std::endl; } #endif <|endoftext|>
<commit_before>/** * \file * \brief deliverSignals() declaration * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-04-28 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_DELIVERSIGNALS_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_DELIVERSIGNALS_HPP_ namespace distortos { namespace synchronization { /** * \brief Delivers all unmasked signals that are pending/queued for current thread. * * Currently just a stub. */ void deliverSignals(); } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_DELIVERSIGNALS_HPP_ <commit_msg>deliverSignals.hpp: remove info about stub implementation of synchronization::deliverSignals()<commit_after>/** * \file * \brief deliverSignals() declaration * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-05-01 */ #ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_DELIVERSIGNALS_HPP_ #define INCLUDE_DISTORTOS_SYNCHRONIZATION_DELIVERSIGNALS_HPP_ namespace distortos { namespace synchronization { /** * \brief Delivers all unmasked signals that are pending/queued for current thread. */ void deliverSignals(); } // namespace synchronization } // namespace distortos #endif // INCLUDE_DISTORTOS_SYNCHRONIZATION_DELIVERSIGNALS_HPP_ <|endoftext|>
<commit_before>#include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include "Blur.h" #include "Sharpen.h" #include "Sobel.h" #define METHOD_REFERENCE (1<<1) #define METHOD_HALIDE_CPU (1<<2) #define METHOD_HALIDE_GPU (1<<3) #define METHOD_OPENCL (1<<4) using namespace improsa; using namespace std; struct _options_ { map<string, Filter*> filters; map<string, unsigned int> methods; _options_() { filters["blur"] = new Blur(); filters["sharpen"] = new Sharpen(); filters["sobel"] = new Sobel(); methods["reference"] = METHOD_REFERENCE; methods["opencl"] = METHOD_OPENCL; #if ENABLE_HALIDE methods["halide_cpu"] = METHOD_HALIDE_CPU; methods["halide_gpu"] = METHOD_HALIDE_GPU; #endif } } Options; void clinfo(); void printUsage(); int updateStatus(const char *format, va_list args); int main(int argc, char *argv[]) { size_t size = 0; Filter *filter = NULL; unsigned int method = 0; Filter::Params params; // Parse arguments for (int i = 1; i < argc; i++) { if (!filter && Options.filters.find(argv[i]) != Options.filters.end()) { filter = Options.filters[argv[i]]; } else if (!method && Options.methods.find(argv[i]) != Options.methods.end()) { method = Options.methods[argv[i]]; } else if (!strcmp(argv[i], "-cldevice")) { ++i; if (i >= argc) { cout << "Platform/device index required with -cldevice." << endl; exit(1); } char *next; params.platformIndex = strtoul(argv[i], &next, 10); if (strlen(next) == 0 || next[0] != ':') { cout << "Invalid platform/device index." << endl; exit(1); } params.deviceIndex = strtoul(++next, &next, 10); if (strlen(next) != 0) { cout << "Invalid platform/device index." << endl; exit(1); } } else if (!strcmp(argv[i], "-clinfo")) { clinfo(); exit(0); } else { char *next; size_t sz = strtoul(argv[i], &next, 10); if (strlen(next) > 0 || size != 0 || sz == 0) { cout << "Invalid argument '" << argv[i] << "'" << endl; printUsage(); exit(1); } size = sz; } } if (size == 0 || filter == NULL || method == 0) { printUsage(); exit(1); } // Allocate input/output images Image input = {new unsigned char[size*size*4], size, size}; Image output = {new unsigned char[size*size*4], size, size}; // Initialize input image with random data for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { setPixel(input, x, y, 0, rand()/RAND_MAX); setPixel(input, x, y, 1, rand()/RAND_MAX); setPixel(input, x, y, 2, rand()/RAND_MAX); setPixel(input, x, y, 3, 255); } } // Run filter filter->setStatusCallback(updateStatus); switch (method) { case METHOD_REFERENCE: filter->runReference(input, output); break; case METHOD_HALIDE_CPU: filter->runHalideCPU(input, output, params); break; case METHOD_HALIDE_GPU: filter->runHalideGPU(input, output, params); break; case METHOD_OPENCL: filter->runOpenCL(input, output, params); break; default: assert(false && "Invalid method."); } return 0; } void clinfo() { #define MAX_PLATFORMS 8 #define MAX_DEVICES 8 #define MAX_NAME 256 cl_uint numPlatforms, numDevices; cl_platform_id platforms[MAX_PLATFORMS]; cl_device_id devices[MAX_DEVICES]; char name[MAX_NAME]; cl_int err; err = clGetPlatformIDs(MAX_PLATFORMS, platforms, &numPlatforms); if (err != CL_SUCCESS) { cout << "Error retrieving platforms (" << err << ")" << endl; return; } if (numPlatforms == 0) { cout << "No platforms found." << endl; return; } for (int p = 0; p < numPlatforms; p++) { clGetPlatformInfo(platforms[p], CL_PLATFORM_NAME, MAX_NAME, name, NULL); cout << endl << "Platform " << p << ": " << name << endl; err = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, MAX_DEVICES, devices, &numDevices); if (err != CL_SUCCESS) { cout << "Error retrieving devices (" << err << ")" << endl; continue; } if (numDevices == 0) { cout << "No devices found." << endl; continue; } for (int d = 0; d < numDevices; d++) { clGetDeviceInfo(devices[d], CL_DEVICE_NAME, MAX_NAME, name, NULL); cout << "-> Device " << d << ": " << name << endl; } } cout << endl; } void printUsage() { cout << endl << "Usage: improsa SIZE FILTER METHOD [-cldevice P:D]"; cout << endl << " improsa -clinfo" << endl; cout << endl << "Where FILTER is one of:" << endl; map<string, Filter*>::iterator fItr; for (fItr = Options.filters.begin(); fItr != Options.filters.end(); fItr++) { cout << "\t" << fItr->first << endl; } cout << endl << "Where METHOD is one of:" << endl; map<string, unsigned int>::iterator mItr; for (mItr = Options.methods.begin(); mItr != Options.methods.end(); mItr++) { cout << "\t" << mItr->first << endl; } cout << endl << "If specifying an OpenCL device with -cldevice, " << endl << "P and D correspond to the platform and device " << endl << "indices reported by running -clinfo." << endl; cout << endl; } int updateStatus(const char *format, va_list args) { vprintf(format, args); printf("\n"); return 0; } <commit_msg>Fixed random image generation.<commit_after>#include <cassert> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include "Blur.h" #include "Sharpen.h" #include "Sobel.h" #define METHOD_REFERENCE (1<<1) #define METHOD_HALIDE_CPU (1<<2) #define METHOD_HALIDE_GPU (1<<3) #define METHOD_OPENCL (1<<4) using namespace improsa; using namespace std; struct _options_ { map<string, Filter*> filters; map<string, unsigned int> methods; _options_() { filters["blur"] = new Blur(); filters["sharpen"] = new Sharpen(); filters["sobel"] = new Sobel(); methods["reference"] = METHOD_REFERENCE; methods["opencl"] = METHOD_OPENCL; #if ENABLE_HALIDE methods["halide_cpu"] = METHOD_HALIDE_CPU; methods["halide_gpu"] = METHOD_HALIDE_GPU; #endif } } Options; void clinfo(); void printUsage(); int updateStatus(const char *format, va_list args); int main(int argc, char *argv[]) { size_t size = 0; Filter *filter = NULL; unsigned int method = 0; Filter::Params params; // Parse arguments for (int i = 1; i < argc; i++) { if (!filter && Options.filters.find(argv[i]) != Options.filters.end()) { filter = Options.filters[argv[i]]; } else if (!method && Options.methods.find(argv[i]) != Options.methods.end()) { method = Options.methods[argv[i]]; } else if (!strcmp(argv[i], "-cldevice")) { ++i; if (i >= argc) { cout << "Platform/device index required with -cldevice." << endl; exit(1); } char *next; params.platformIndex = strtoul(argv[i], &next, 10); if (strlen(next) == 0 || next[0] != ':') { cout << "Invalid platform/device index." << endl; exit(1); } params.deviceIndex = strtoul(++next, &next, 10); if (strlen(next) != 0) { cout << "Invalid platform/device index." << endl; exit(1); } } else if (!strcmp(argv[i], "-clinfo")) { clinfo(); exit(0); } else { char *next; size_t sz = strtoul(argv[i], &next, 10); if (strlen(next) > 0 || size != 0 || sz == 0) { cout << "Invalid argument '" << argv[i] << "'" << endl; printUsage(); exit(1); } size = sz; } } if (size == 0 || filter == NULL || method == 0) { printUsage(); exit(1); } // Allocate input/output images Image input = {new unsigned char[size*size*4], size, size}; Image output = {new unsigned char[size*size*4], size, size}; // Initialize input image with random data for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { setPixel(input, x, y, 0, rand()/(float)RAND_MAX); setPixel(input, x, y, 1, rand()/(float)RAND_MAX); setPixel(input, x, y, 2, rand()/(float)RAND_MAX); setPixel(input, x, y, 3, 255); } } // Run filter filter->setStatusCallback(updateStatus); switch (method) { case METHOD_REFERENCE: filter->runReference(input, output); break; case METHOD_HALIDE_CPU: filter->runHalideCPU(input, output, params); break; case METHOD_HALIDE_GPU: filter->runHalideGPU(input, output, params); break; case METHOD_OPENCL: filter->runOpenCL(input, output, params); break; default: assert(false && "Invalid method."); } return 0; } void clinfo() { #define MAX_PLATFORMS 8 #define MAX_DEVICES 8 #define MAX_NAME 256 cl_uint numPlatforms, numDevices; cl_platform_id platforms[MAX_PLATFORMS]; cl_device_id devices[MAX_DEVICES]; char name[MAX_NAME]; cl_int err; err = clGetPlatformIDs(MAX_PLATFORMS, platforms, &numPlatforms); if (err != CL_SUCCESS) { cout << "Error retrieving platforms (" << err << ")" << endl; return; } if (numPlatforms == 0) { cout << "No platforms found." << endl; return; } for (int p = 0; p < numPlatforms; p++) { clGetPlatformInfo(platforms[p], CL_PLATFORM_NAME, MAX_NAME, name, NULL); cout << endl << "Platform " << p << ": " << name << endl; err = clGetDeviceIDs(platforms[p], CL_DEVICE_TYPE_ALL, MAX_DEVICES, devices, &numDevices); if (err != CL_SUCCESS) { cout << "Error retrieving devices (" << err << ")" << endl; continue; } if (numDevices == 0) { cout << "No devices found." << endl; continue; } for (int d = 0; d < numDevices; d++) { clGetDeviceInfo(devices[d], CL_DEVICE_NAME, MAX_NAME, name, NULL); cout << "-> Device " << d << ": " << name << endl; } } cout << endl; } void printUsage() { cout << endl << "Usage: improsa SIZE FILTER METHOD [-cldevice P:D]"; cout << endl << " improsa -clinfo" << endl; cout << endl << "Where FILTER is one of:" << endl; map<string, Filter*>::iterator fItr; for (fItr = Options.filters.begin(); fItr != Options.filters.end(); fItr++) { cout << "\t" << fItr->first << endl; } cout << endl << "Where METHOD is one of:" << endl; map<string, unsigned int>::iterator mItr; for (mItr = Options.methods.begin(); mItr != Options.methods.end(); mItr++) { cout << "\t" << mItr->first << endl; } cout << endl << "If specifying an OpenCL device with -cldevice, " << endl << "P and D correspond to the platform and device " << endl << "indices reported by running -clinfo." << endl; cout << endl; } int updateStatus(const char *format, va_list args) { vprintf(format, args); printf("\n"); return 0; } <|endoftext|>
<commit_before>// // panic.cpp // Firedrake // // Created by Sidney Just // Copyright (c) 2014 by Sidney Just // 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 <machine/cpu.h> #include <machine/interrupts/interrupts.h> #include <libc/stdarg.h> #include <libc/stdio.h> #include <libc/backtrace.h> #include "panic.h" #include "kalloc.h" #include "kprintf.h" #define PANIC_STACK_SIZE 512 #define PANIC_HEAP_SIZE 2048 static bool _panic_initialized = false; void panic_die_fancy(const char *buffer) { Sys::CPU *cpu = Sys::CPU::GetCurrentCPU(); Sys::CPUState *state = cpu->GetLastState(); kprintf("\n\16\24Kernel Panic!\16\27\n"); kprintf("Reason: \""); kprintf(buffer); kprintf("\"\n"); kprintf("Crashing CPU: \16\031%i\16\27\n", cpu->GetID()); if(state) { kprintf("CPU State (interrupt vector \16\0310x%x\16\27):\n", state->interrupt); kprintf(" eax: \16\031%08x\16\27, ecx: \16\031%08x\16\27, edx: \16\031%08x\16\27, ebx: \16\031%08x\16\27\n", state->eax, state->ecx, state->edx, state->ebx); kprintf(" esp: \16\031%08x\16\27, ebp: \16\031%08x\16\27, esi: \16\031%08x\16\27, edi: \16\031%08x\16\27\n", state->esp, state->ebp, state->esi, state->edi); kprintf(" eip: \16\031%08x\16\27, eflags: \16\031%08x\16\27.\n", state->eip, state->eflags); } void *frames[10]; int num = state ? backtrace_np((void *)state->ebp, frames, 10) : backtrace(frames, 10); for(int i = 0; i < num; i ++) { kprintf("(%2i) %08x\n", (num - 1) - i, reinterpret_cast<uint32_t>(frames[i])); } kprintf("CPU halt"); } void panic_die_barebone(const char *buffer) { kprintf("\n\16\24Kernel Panic!\16\27\n"); kprintf("Reason: \""); kprintf(buffer); kprintf("\"\n\nCPU halt"); } void panic_die(const char *buffer) { if(!_panic_initialized) { panic_die_barebone(buffer); return; } panic_die_fancy(buffer); } void panic_stack(const char *reason, va_list args) { char buffer[PANIC_STACK_SIZE]; vsnprintf(buffer, PANIC_STACK_SIZE, reason, args); panic_die(buffer); } void panic_heap(const char *reason, va_list args) { char *buffer = reinterpret_cast<char *>(kalloc(PANIC_HEAP_SIZE)); if(!buffer) { panic_stack(reason, args); return; } vsnprintf(buffer, PANIC_HEAP_SIZE, reason, args); panic_die(buffer); } void panic(const char *reason, ...) { if(_panic_initialized) { // Tear down the system properly to avoid other code to be executed Sys::DisableInterrupts(); Sys::APIC::BroadcastIPI(0x39, false); } va_list args; va_start(args, reason); /*_panic_initialized ? panic_heap(reason, args) :*/ panic_stack(reason, args); va_end(args); while(1) { Sys::DisableInterrupts(); Sys::CPUHalt(); } } void panic_init() { _panic_initialized = true; } <commit_msg>Panic is now completely non-locking<commit_after>// // panic.cpp // Firedrake // // Created by Sidney Just // Copyright (c) 2014 by Sidney Just // 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 <machine/cpu.h> #include <machine/interrupts/interrupts.h> #include <libc/stdarg.h> #include <libc/stdio.h> #include <libc/backtrace.h> #include "panic.h" #include "kprintf.h" static char _panicScribbleArea[4096]; static bool _panic_initialized = false; void panic_die(const char *buffer) { Sys::CPU *cpu = Sys::CPU::GetCurrentCPU(); Sys::CPUState *state = cpu->GetLastState(); kprintf("\n\16\24Kernel Panic!\16\27\n"); kprintf("Reason: \""); kprintf(buffer); kprintf("\"\n"); kprintf("Crashing CPU: \16\031%i\16\27\n", cpu->GetID()); if(state) { kprintf("CPU State (interrupt vector \16\0310x%x\16\27):\n", state->interrupt); kprintf(" eax: \16\031%08x\16\27, ecx: \16\031%08x\16\27, edx: \16\031%08x\16\27, ebx: \16\031%08x\16\27\n", state->eax, state->ecx, state->edx, state->ebx); kprintf(" esp: \16\031%08x\16\27, ebp: \16\031%08x\16\27, esi: \16\031%08x\16\27, edi: \16\031%08x\16\27\n", state->esp, state->ebp, state->esi, state->edi); kprintf(" eip: \16\031%08x\16\27, eflags: \16\031%08x\16\27.\n", state->eip, state->eflags); } void *frames[10]; int num = state ? backtrace_np((void *)state->ebp, frames, 10) : backtrace(frames, 10); for(int i = 0; i < num; i ++) kprintf("(%2i) %08x\n", (num - 1) - i, reinterpret_cast<uint32_t>(frames[i])); if(state) { kprintf("Kernel backtrace:\n"); int num = backtrace(frames, 10); for(int i = 0; i < num; i ++) kprintf("(%2i) %08x\n", (num - 1) - i, reinterpret_cast<uint32_t>(frames[i])); } kprintf("CPU halt"); } void panic(const char *reason, ...) { if(_panic_initialized) { // Tear down the system properly to avoid other code to be executed Sys::DisableInterrupts(); Sys::APIC::BroadcastIPI(0x39, false); } va_list args; va_start(args, reason); vsnprintf(_panicScribbleArea, 4096, reason, args); panic_die(_panicScribbleArea); va_end(args); while(1) { Sys::DisableInterrupts(); Sys::CPUHalt(); } } void panic_init() { _panic_initialized = true; } <|endoftext|>
<commit_before>#include "load_balancer.h" #include "worker_thread.h" #include "graph_engine.h" const int MAX_STOLEN_VERTICES = 1024; load_balancer::load_balancer(graph_engine &_graph, worker_thread &_owner): owner(_owner), graph(_graph) { steal_thread_id = (owner.get_worker_id() + 1) % graph.get_num_threads(); // TODO can I have a better way to do it? completed_stolen_vertices = (fifo_queue<vertex_id_t> *) malloc( graph.get_num_threads() * sizeof(fifo_queue<vertex_id_t>)); for (int i = 0; i < graph.get_num_threads(); i++) { new (completed_stolen_vertices + i) fifo_queue<vertex_id_t>( _owner.get_node_id(), PAGE_SIZE, true); } num_completed_stolen_vertices = 0; } load_balancer::~load_balancer() { for (int i = 0; i < graph.get_num_threads(); i++) completed_stolen_vertices[i].~fifo_queue<vertex_id_t>(); free(completed_stolen_vertices); } /** * This steals vertices from other threads. It tries to steal more vertices * than it can process, and the remaining vertices will be placed in its * own activated vertex queue. */ int load_balancer::steal_activated_vertices(vertex_id_t vertex_buf[], int buf_size) { if (steal_thread_id == owner.get_worker_id()) steal_thread_id = (steal_thread_id + 1) % graph.get_num_threads(); int num_tries = 0; vertex_id_t *steal_buf = new vertex_id_t[MAX_STOLEN_VERTICES]; int num; do { worker_thread *t = graph.get_thread(steal_thread_id); num_tries++; num = t->steal_activated_vertices(steal_buf, MAX_STOLEN_VERTICES); // If we can't steal vertices from the thread, we should move // to the next thread. if (num == 0) steal_thread_id = (steal_thread_id + 1) % graph.get_num_threads(); // If we have tried to steal vertices from all threads. } while (num == 0 && num_tries < graph.get_num_threads()); int ret = min(buf_size, num); memcpy(vertex_buf, steal_buf, sizeof(vertex_buf[0]) * ret); // We stole more vertices than we can process this time. // The vertices stolen from another thread will also be placed in // the queue for currently activated vertices. if (num - ret > 0) owner.curr_activated_vertices.init(steal_buf + ret, num - ret, true); delete [] steal_buf; return ret; } void load_balancer::process_completed_stolen_vertices() { if (num_completed_stolen_vertices == 0) return; int num_tot = 0; for (int i = 0; i < graph.get_num_threads(); i++) { fifo_queue<vertex_id_t> &q = completed_stolen_vertices[i]; if (!q.is_empty()) { worker_thread *t = graph.get_thread(i); int num_completed = q.get_num_entries(); num_tot += num_completed; stack_array<vertex_id_t> buf(num_completed); int ret = q.fetch(buf.data(), num_completed); assert(ret == num_completed); t->return_vertices(buf.data(), num_completed); } } assert(num_tot == num_completed_stolen_vertices); num_completed_stolen_vertices = 0; } void load_balancer::return_vertices(vertex_id_t ids[], int num) { for (int i = 0; i < num; i++) { int part_id = graph.get_partitioner()->map(ids[i]); if (completed_stolen_vertices[part_id].is_full()) { completed_stolen_vertices[part_id].expand_queue( completed_stolen_vertices[part_id].get_size() * 2); } completed_stolen_vertices[part_id].push_back(ids[i]); } num_completed_stolen_vertices += num; } void load_balancer::reset() { for (int i = 0; i < graph.get_num_threads(); i++) assert(completed_stolen_vertices[i].is_empty()); assert(num_completed_stolen_vertices == 0); } <commit_msg>[Graph]: fix a bug in load balancer.<commit_after>#include "load_balancer.h" #include "worker_thread.h" #include "graph_engine.h" const int MAX_STOLEN_VERTICES = 1024; load_balancer::load_balancer(graph_engine &_graph, worker_thread &_owner): owner(_owner), graph(_graph) { steal_thread_id = (owner.get_worker_id() + 1) % graph.get_num_threads(); // TODO can I have a better way to do it? completed_stolen_vertices = (fifo_queue<vertex_id_t> *) malloc( graph.get_num_threads() * sizeof(fifo_queue<vertex_id_t>)); for (int i = 0; i < graph.get_num_threads(); i++) { new (completed_stolen_vertices + i) fifo_queue<vertex_id_t>( _owner.get_node_id(), PAGE_SIZE, true); } num_completed_stolen_vertices = 0; } load_balancer::~load_balancer() { for (int i = 0; i < graph.get_num_threads(); i++) completed_stolen_vertices[i].~fifo_queue<vertex_id_t>(); free(completed_stolen_vertices); } /** * This steals vertices from other threads. It tries to steal more vertices * than it can process, and the remaining vertices will be placed in its * own activated vertex queue. */ int load_balancer::steal_activated_vertices(vertex_id_t vertex_buf[], int buf_size) { if (steal_thread_id == owner.get_worker_id()) steal_thread_id = (steal_thread_id + 1) % graph.get_num_threads(); int num_tries = 0; int num; do { worker_thread *t = graph.get_thread(steal_thread_id); num_tries++; num = t->steal_activated_vertices(vertex_buf, buf_size); // If we can't steal vertices from the thread, we should move // to the next thread. if (num == 0) steal_thread_id = (steal_thread_id + 1) % graph.get_num_threads(); // If we have tried to steal vertices from all threads. } while (num == 0 && num_tries < graph.get_num_threads()); return num; } void load_balancer::process_completed_stolen_vertices() { if (num_completed_stolen_vertices == 0) return; int num_tot = 0; for (int i = 0; i < graph.get_num_threads(); i++) { fifo_queue<vertex_id_t> &q = completed_stolen_vertices[i]; if (!q.is_empty()) { worker_thread *t = graph.get_thread(i); int num_completed = q.get_num_entries(); num_tot += num_completed; stack_array<vertex_id_t> buf(num_completed); int ret = q.fetch(buf.data(), num_completed); assert(ret == num_completed); t->return_vertices(buf.data(), num_completed); } } assert(num_tot == num_completed_stolen_vertices); num_completed_stolen_vertices = 0; } void load_balancer::return_vertices(vertex_id_t ids[], int num) { for (int i = 0; i < num; i++) { int part_id = graph.get_partitioner()->map(ids[i]); if (completed_stolen_vertices[part_id].is_full()) { completed_stolen_vertices[part_id].expand_queue( completed_stolen_vertices[part_id].get_size() * 2); } completed_stolen_vertices[part_id].push_back(ids[i]); } num_completed_stolen_vertices += num; } void load_balancer::reset() { for (int i = 0; i < graph.get_num_threads(); i++) assert(completed_stolen_vertices[i].is_empty()); assert(num_completed_stolen_vertices == 0); } <|endoftext|>
<commit_before>// // cgp-projects // // Created by HUJI Computer Graphics course staff, 2013. // Tweaked by HUJI Computer Games Programming staff 2014 // Expanded by Amir Blum 2015 // OpenGL Headers #include <GL/glew.h> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif // OpenAL Headers #ifdef __APPLE__ #include <OpenAL/al.h> #include <OpenAL/alc.h> #else #include <AL/al.h> #include <AL/alc.h> #endif #include <AL/alut.h> // GLM headers #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // for glm::value_ptr using namespace glm; #include "World.h" #include "ShaderIO.h" #include "InputManager.h" #include "Camera.h" #include <iostream> static const std::string BACKGROUND_MUSIC = "assets/sounds/BSG_battle.wav"; /** Internal Definitions */ #define WINDOW_WIDTH (1024) // initial width of the window // #define WINDOW_HEIGHT (768) // initial height of the window // #define WINDOW_POS_X (100) // initial X position of the window // #define WINDOW_POS_Y (100) // initial Y position of the window // #define RC_OK (0) // Everything went ok // #define RC_INVALID_ARGUMENTS (1) // Invalid arguments given to the program // #define RC_INPUT_ERROR (2) // Invalid input to the program // #define ARGUMENTS_PROGRAM (0) // program name position on argv // #define ARGUMENTS_INPUTFILE (1) // given input file position on argv // #define ARGUMENTS_REQUIRED (2) // number of required arguments // /** Key definitions */ #define KEY_ESC ('\e') // Key used to terminate the program - ESC // #define KEY_RESET ('r') /** display callback */ void display(void); /** window reshape callback */ void windowResize(int width, int height); /** keyboardDown callback */ void keyboardDown(unsigned char key, int x, int y); /** keyboardUp callback */ void keyboardUp(unsigned char key, int x, int y); /** mouse click callback */ void mouse(int button, int state, int x, int y) ; /** mouse dragging callback */ void motion(int x, int y) ; // Game-related objects World *_world; /** main function */ int main(int argc, char* argv[]) { std::cout << "Starting ex3..." << std::endl; // Initialize GLUT glutInit(&argc, argv) ; #ifdef __APPLE__ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_3_2_CORE_PROFILE) ; #else glutInitContextVersion(3, 3); glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG); glutInitContextProfile(GLUT_CORE_PROFILE); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); #endif glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow("CGP Ex 3"); // Initialize GLEW glewExperimental = GL_TRUE; int glewStatus = glewInit(); if (glewStatus != GLEW_OK) { std::cerr << "Unable to initialize GLEW ... exiting" << std::endl; exit(1); } // GLEW has a "bug" where it sets a glError. According to the wiki this // can be safely ignored, so we clear the error here: glGetError(); #ifdef __APPLE__ GLint sync = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); #endif // Enable opengl drawing features glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Set callback functions: glutDisplayFunc(display) ; glutReshapeFunc(windowResize) ; glutKeyboardFunc(keyboardDown); glutKeyboardUpFunc(keyboardUp); glutMouseFunc(mouse); glutMotionFunc(motion); glutPassiveMotionFunc(motion); glutSetCursor(GLUT_CURSOR_NONE); // Initialize ALUT (& background music) alutInit(&argc, argv); ALuint backgroundBuffer, backgroundSource; backgroundBuffer = alutCreateBufferFromFile(BACKGROUND_MUSIC.c_str()); ALenum alutError = alutGetError(); if (alutError != AL_NO_ERROR) { std::cout << "Error loading background music: " << alutGetErrorString(alutError) << std::endl; } alGenSources(1, &backgroundSource); alSourcei(backgroundSource, AL_BUFFER, backgroundBuffer); alSourcei(backgroundSource, AL_LOOPING, true); alSourcePlay(backgroundSource); // Initialize random seed srand(time(NULL)); // Set up game _world = new World(); // Set clear color to black: glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Start events/drawing loop glutMainLoop(); return 0; } int oldTimeSinceStart = 0; bool drawGlow = false; void display(void) { // Update the delta int timeSinceStart = glutGet(GLUT_ELAPSED_TIME); int deltaTime = timeSinceStart - oldTimeSinceStart; oldTimeSinceStart = timeSinceStart; // Update the game state float dt = (float)deltaTime / 1000.0f; _world->recursiveUpdate(dt); // Drawing time // Clear the screen buffer glClearColor(0.15f, 0.0f, 0.2f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Tell the world to draw itself _world->recursiveRender(); // Swap those buffers so someone will actually see the results... // glutSwapBuffers(); // Refresh the display glutPostRedisplay(); } // This method is called when the window is resized float _screenWidth, _screenHeight; void windowResize(int w, int h) { _screenWidth = w; _screenHeight = h; // set the new viewport // glViewport(0, 0, w, h); // set the perspective of the camera Camera::MainCamera()->resize(w, h); // Refresh the display // glutPostRedisplay(); } /******************************************************************** * Function : keyboard * Arguments : key : the key that was pressed * x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles all the keyboard input from the user. * It supports terminating the application when the KEY_QUIT is pressed. * \******************************************************************/ void keyboardDown(unsigned char key, int x, int y) { unsigned int lower_key = tolower(key); if (lower_key == KEY_ESC) { exit(RC_OK); } else if (lower_key == KEY_RESET) { delete _world; _world = new World; Camera::MainCamera()->resize(_screenWidth, _screenHeight); } InputManager::Instance().handleKeyDown(lower_key, x, y); } /******************************************************************** * Function : keyboardUp * Arguments : key : the key that was relased * x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles all the keyboard input from the user. * It supports terminating the application when the KEY_QUIT is pressed. * \******************************************************************/ void keyboardUp(unsigned char key, int x, int y) { unsigned int lower_key = tolower(key); InputManager::Instance().handleKeyUp(lower_key, x, y); } /******************************************************************** * Function : mouse * Arguments : button : the button that was engaged in some action * state : the new state of that button * x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles mouse actions. * \******************************************************************/ void mouse(int button, int state, int x, int y) { if(button == GLUT_LEFT_BUTTON) { } else if (button == GLUT_RIGHT_BUTTON) { } return; } /******************************************************************** * Function : motion * Arguments : x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles mouse dragging events. * \******************************************************************/ void motion(int x, int y) { float oglX = x / _screenWidth; float oglY = y / _screenHeight; oglX = oglX * 2.0f - 1.0f; oglY = oglY * -2.0f + 1.0f; InputManager::Instance().handleMouseMove(oglX, oglY); } <commit_msg>Added fullscreen<commit_after>// // cgp-projects // // Created by HUJI Computer Graphics course staff, 2013. // Tweaked by HUJI Computer Games Programming staff 2014 // Expanded by Amir Blum 2015 // OpenGL Headers #include <GL/glew.h> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/freeglut.h> #endif // OpenAL Headers #ifdef __APPLE__ #include <OpenAL/al.h> #include <OpenAL/alc.h> #else #include <AL/al.h> #include <AL/alc.h> #endif #include <AL/alut.h> // GLM headers #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // for glm::value_ptr using namespace glm; #include "World.h" #include "ShaderIO.h" #include "InputManager.h" #include "Camera.h" #include <iostream> static const std::string BACKGROUND_MUSIC = "assets/sounds/BSG_battle.wav"; /** Internal Definitions */ #define WINDOW_WIDTH (1024) // initial width of the window // #define WINDOW_HEIGHT (768) // initial height of the window // #define WINDOW_POS_X (100) // initial X position of the window // #define WINDOW_POS_Y (100) // initial Y position of the window // #define RC_OK (0) // Everything went ok // #define RC_INVALID_ARGUMENTS (1) // Invalid arguments given to the program // #define RC_INPUT_ERROR (2) // Invalid input to the program // #define ARGUMENTS_PROGRAM (0) // program name position on argv // #define ARGUMENTS_INPUTFILE (1) // given input file position on argv // #define ARGUMENTS_REQUIRED (2) // number of required arguments // /** Key definitions */ #define KEY_ESC ('\e') // Key used to terminate the program - ESC // #define KEY_RESET ('r') #define KEY_FULLSCREEN ('f') /** display callback */ void display(void); /** window reshape callback */ void windowResize(int width, int height); /** keyboardDown callback */ void keyboardDown(unsigned char key, int x, int y); /** keyboardUp callback */ void keyboardUp(unsigned char key, int x, int y); /** mouse click callback */ void mouse(int button, int state, int x, int y) ; /** mouse dragging callback */ void motion(int x, int y) ; // Game-related objects World *_world; /** main function */ int main(int argc, char* argv[]) { std::cout << "Starting ex3..." << std::endl; // Initialize GLUT glutInit(&argc, argv) ; #ifdef __APPLE__ glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_3_2_CORE_PROFILE) ; #else glutInitContextVersion(3, 3); glutInitContextFlags(GLUT_FORWARD_COMPATIBLE | GLUT_DEBUG); glutInitContextProfile(GLUT_CORE_PROFILE); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); #endif glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutInitWindowPosition(WINDOW_POS_X, WINDOW_POS_Y); glutCreateWindow("CGP Ex 3"); // Initialize GLEW glewExperimental = GL_TRUE; int glewStatus = glewInit(); if (glewStatus != GLEW_OK) { std::cerr << "Unable to initialize GLEW ... exiting" << std::endl; exit(1); } // GLEW has a "bug" where it sets a glError. According to the wiki this // can be safely ignored, so we clear the error here: glGetError(); #ifdef __APPLE__ GLint sync = 1; CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); #endif // Enable opengl drawing features glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Set callback functions: glutDisplayFunc(display) ; glutReshapeFunc(windowResize) ; glutKeyboardFunc(keyboardDown); glutKeyboardUpFunc(keyboardUp); glutMouseFunc(mouse); glutMotionFunc(motion); glutPassiveMotionFunc(motion); glutSetCursor(GLUT_CURSOR_NONE); // Initialize ALUT (& background music) alutInit(&argc, argv); ALuint backgroundBuffer, backgroundSource; backgroundBuffer = alutCreateBufferFromFile(BACKGROUND_MUSIC.c_str()); ALenum alutError = alutGetError(); if (alutError != AL_NO_ERROR) { std::cout << "Error loading background music: " << alutGetErrorString(alutError) << std::endl; } alGenSources(1, &backgroundSource); alSourcei(backgroundSource, AL_BUFFER, backgroundBuffer); alSourcei(backgroundSource, AL_LOOPING, true); alSourcePlay(backgroundSource); // Initialize random seed srand(time(NULL)); // Set up game _world = new World(); // Set clear color to black: glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Start events/drawing loop glutMainLoop(); return 0; } int oldTimeSinceStart = 0; bool drawGlow = false; void display(void) { // Update the delta int timeSinceStart = glutGet(GLUT_ELAPSED_TIME); int deltaTime = timeSinceStart - oldTimeSinceStart; oldTimeSinceStart = timeSinceStart; // Update the game state float dt = (float)deltaTime / 1000.0f; _world->recursiveUpdate(dt); // Drawing time // Clear the screen buffer glClearColor(0.15f, 0.0f, 0.2f, 1.0f); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Tell the world to draw itself _world->recursiveRender(); // Swap those buffers so someone will actually see the results... // glutSwapBuffers(); // Refresh the display glutPostRedisplay(); } // This method is called when the window is resized int _screenWidth, _screenHeight; void windowResize(int w, int h) { _screenWidth = w; _screenHeight = h; // set the new viewport // glViewport(0, 0, w, h); // set the perspective of the camera Camera::MainCamera()->resize(w, h); // Refresh the display // glutPostRedisplay(); } void toggleFullscreen() { static bool fullscreen = false; static int previousWidth, previousHeight; static int previousX, previousY; if (!fullscreen) { previousWidth = _screenWidth; previousHeight = _screenHeight; previousX = glutGet(GLUT_WINDOW_X); previousY = glutGet(GLUT_WINDOW_Y); glutFullScreen(); fullscreen = true; } else { glutReshapeWindow(previousWidth, previousHeight); glutPositionWindow(previousX, previousY); fullscreen = false; } } /******************************************************************** * Function : keyboard * Arguments : key : the key that was pressed * x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles all the keyboard input from the user. * It supports terminating the application when the KEY_QUIT is pressed. * \******************************************************************/ void keyboardDown(unsigned char key, int x, int y) { unsigned int lower_key = tolower(key); if (lower_key == KEY_ESC) { exit(RC_OK); } else if (lower_key == KEY_RESET) { delete _world; _world = new World; Camera::MainCamera()->resize(_screenWidth, _screenHeight); } else if (lower_key == KEY_FULLSCREEN) { toggleFullscreen(); } InputManager::Instance().handleKeyDown(lower_key, x, y); } /******************************************************************** * Function : keyboardUp * Arguments : key : the key that was relased * x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles all the keyboard input from the user. * It supports terminating the application when the KEY_QUIT is pressed. * \******************************************************************/ void keyboardUp(unsigned char key, int x, int y) { unsigned int lower_key = tolower(key); InputManager::Instance().handleKeyUp(lower_key, x, y); } /******************************************************************** * Function : mouse * Arguments : button : the button that was engaged in some action * state : the new state of that button * x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles mouse actions. * \******************************************************************/ void mouse(int button, int state, int x, int y) { if(button == GLUT_LEFT_BUTTON) { } else if (button == GLUT_RIGHT_BUTTON) { } return; } /******************************************************************** * Function : motion * Arguments : x : x value of the current mouse location * y : y value of the current mouse location * Returns : n/a * Throws : n/a * * Purpose : This function handles mouse dragging events. * \******************************************************************/ void motion(int x, int y) { float oglX = x / _screenWidth; float oglY = y / _screenHeight; oglX = oglX * 2.0f - 1.0f; oglY = oglY * -2.0f + 1.0f; InputManager::Instance().handleMouseMove(oglX, oglY); } <|endoftext|>
<commit_before>//===- IRPrinting.cpp -----------------------------------------------------===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= #include "PassDetail.h" #include "mlir/IR/Module.h" #include "mlir/Pass/PassManager.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormatVariadic.h" using namespace mlir; using namespace mlir::detail; namespace { class IRPrinterInstrumentation : public PassInstrumentation { public: /// A filter function to decide if the given pass should be printed. Returns /// true if the pass should be printed, false otherwise. using ShouldPrintFn = std::function<bool(Pass *)>; IRPrinterInstrumentation(ShouldPrintFn &&shouldPrintBeforePass, ShouldPrintFn &&shouldPrintAfterPass, bool printModuleScope, raw_ostream &out) : shouldPrintBeforePass(shouldPrintBeforePass), shouldPrintAfterPass(shouldPrintAfterPass), printModuleScope(printModuleScope), out(out) { assert((shouldPrintBeforePass || shouldPrintAfterPass) && "expected atleast one valid filter function"); } private: /// Instrumentation hooks. void runBeforePass(Pass *pass, Operation *op) override; void runAfterPass(Pass *pass, Operation *op) override; void runAfterPassFailed(Pass *pass, Operation *op) override; /// Filter functions for before and after pass execution. ShouldPrintFn shouldPrintBeforePass, shouldPrintAfterPass; /// Flag to toggle if the printer should always print at module scope. bool printModuleScope; /// The stream to output to. raw_ostream &out; }; } // end anonymous namespace /// Returns true if the given pass is hidden from IR printing. static bool isHiddenPass(Pass *pass) { return isAdaptorPass(pass) || isa<VerifierPass>(pass); } static void printIR(Operation *op, bool printModuleScope, raw_ostream &out) { // Check to see if we are printing the top-level module. auto module = dyn_cast<ModuleOp>(op); if (module && !op->getBlock()) return module.print(out << "\n"); // Otherwise, check to see if we are not printing at module scope. if (!printModuleScope) return op->print(out << "\n"); // Otherwise, we are printing at module scope. out << " ('" << op->getName() << "' operation"; if (auto symbolName = op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())) out << ": @" << symbolName.getValue(); out << ")\n"; // Find the top-level module operation. auto *topLevelOp = op; while (auto *parentOp = topLevelOp->getParentOp()) topLevelOp = parentOp; // Check to see if the top-level operation is actually a module in the case of // invalid-ir. if (auto module = dyn_cast<ModuleOp>(topLevelOp)) module.print(out); else topLevelOp->print(out); } /// Instrumentation hooks. void IRPrinterInstrumentation::runBeforePass(Pass *pass, Operation *op) { // Skip hidden passes and passes that the user filtered out. if (!shouldPrintBeforePass || isHiddenPass(pass) || !shouldPrintBeforePass(pass)) return; out << formatv("*** IR Dump Before {0} ***", pass->getName()); printIR(op, printModuleScope, out); out << "\n\n"; } void IRPrinterInstrumentation::runAfterPass(Pass *pass, Operation *op) { // Skip hidden passes and passes that the user filtered out. if (!shouldPrintAfterPass || isHiddenPass(pass) || !shouldPrintAfterPass(pass)) return; out << formatv("*** IR Dump After {0} ***", pass->getName()); printIR(op, printModuleScope, out); out << "\n\n"; } void IRPrinterInstrumentation::runAfterPassFailed(Pass *pass, Operation *op) { // Skip adaptor passes and passes that the user filtered out. if (!shouldPrintAfterPass || isAdaptorPass(pass) || !shouldPrintAfterPass(pass)) return; out << formatv("*** IR Dump After {0} Failed ***", pass->getName()); printIR(op, printModuleScope, out); out << "\n\n"; } //===----------------------------------------------------------------------===// // PassManager //===----------------------------------------------------------------------===// /// Add an instrumentation to print the IR before and after pass execution. void PassManager::enableIRPrinting( std::function<bool(Pass *)> shouldPrintBeforePass, std::function<bool(Pass *)> shouldPrintAfterPass, bool printModuleScope, raw_ostream &out) { addInstrumentation(std::make_unique<IRPrinterInstrumentation>( std::move(shouldPrintBeforePass), std::move(shouldPrintAfterPass), printModuleScope, out)); } <commit_msg>NFC: Print the generic op form after pass failure.<commit_after>//===- IRPrinting.cpp -----------------------------------------------------===// // // Copyright 2019 The MLIR Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= #include "PassDetail.h" #include "mlir/IR/Module.h" #include "mlir/Pass/PassManager.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormatVariadic.h" using namespace mlir; using namespace mlir::detail; namespace { class IRPrinterInstrumentation : public PassInstrumentation { public: /// A filter function to decide if the given pass should be printed. Returns /// true if the pass should be printed, false otherwise. using ShouldPrintFn = std::function<bool(Pass *)>; IRPrinterInstrumentation(ShouldPrintFn &&shouldPrintBeforePass, ShouldPrintFn &&shouldPrintAfterPass, bool printModuleScope, raw_ostream &out) : shouldPrintBeforePass(shouldPrintBeforePass), shouldPrintAfterPass(shouldPrintAfterPass), printModuleScope(printModuleScope), out(out) { assert((shouldPrintBeforePass || shouldPrintAfterPass) && "expected atleast one valid filter function"); } private: /// Instrumentation hooks. void runBeforePass(Pass *pass, Operation *op) override; void runAfterPass(Pass *pass, Operation *op) override; void runAfterPassFailed(Pass *pass, Operation *op) override; /// Filter functions for before and after pass execution. ShouldPrintFn shouldPrintBeforePass, shouldPrintAfterPass; /// Flag to toggle if the printer should always print at module scope. bool printModuleScope; /// The stream to output to. raw_ostream &out; }; } // end anonymous namespace /// Returns true if the given pass is hidden from IR printing. static bool isHiddenPass(Pass *pass) { return isAdaptorPass(pass) || isa<VerifierPass>(pass); } static void printIR(Operation *op, bool printModuleScope, raw_ostream &out, OpPrintingFlags flags) { // Check to see if we are printing the top-level module. auto module = dyn_cast<ModuleOp>(op); if (module && !op->getBlock()) return module.print(out << "\n", flags); // Otherwise, check to see if we are not printing at module scope. if (!printModuleScope) return op->print(out << "\n", flags); // Otherwise, we are printing at module scope. out << " ('" << op->getName() << "' operation"; if (auto symbolName = op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())) out << ": @" << symbolName.getValue(); out << ")\n"; // Find the top-level module operation. auto *topLevelOp = op; while (auto *parentOp = topLevelOp->getParentOp()) topLevelOp = parentOp; // Check to see if the top-level operation is actually a module in the case of // invalid-ir. if (auto module = dyn_cast<ModuleOp>(topLevelOp)) module.print(out, flags); else topLevelOp->print(out, flags); } /// Instrumentation hooks. void IRPrinterInstrumentation::runBeforePass(Pass *pass, Operation *op) { // Skip hidden passes and passes that the user filtered out. if (!shouldPrintBeforePass || isHiddenPass(pass) || !shouldPrintBeforePass(pass)) return; out << formatv("*** IR Dump Before {0} ***", pass->getName()); printIR(op, printModuleScope, out, OpPrintingFlags()); out << "\n\n"; } void IRPrinterInstrumentation::runAfterPass(Pass *pass, Operation *op) { // Skip hidden passes and passes that the user filtered out. if (!shouldPrintAfterPass || isHiddenPass(pass) || !shouldPrintAfterPass(pass)) return; out << formatv("*** IR Dump After {0} ***", pass->getName()); printIR(op, printModuleScope, out, OpPrintingFlags()); out << "\n\n"; } void IRPrinterInstrumentation::runAfterPassFailed(Pass *pass, Operation *op) { // Skip adaptor passes and passes that the user filtered out. if (!shouldPrintAfterPass || isAdaptorPass(pass) || !shouldPrintAfterPass(pass)) return; out << formatv("*** IR Dump After {0} Failed ***", pass->getName()); printIR(op, printModuleScope, out, OpPrintingFlags().printGenericOpForm()); out << "\n\n"; } //===----------------------------------------------------------------------===// // PassManager //===----------------------------------------------------------------------===// /// Add an instrumentation to print the IR before and after pass execution. void PassManager::enableIRPrinting( std::function<bool(Pass *)> shouldPrintBeforePass, std::function<bool(Pass *)> shouldPrintAfterPass, bool printModuleScope, raw_ostream &out) { addInstrumentation(std::make_unique<IRPrinterInstrumentation>( std::move(shouldPrintBeforePass), std::move(shouldPrintAfterPass), printModuleScope, out)); } <|endoftext|>
<commit_before>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 <dcmtk/dcmdata/libi2d/i2dimgs.h> #include <boost/gil/extension/numeric/affine.hpp> #include <boost/gil/extension/numeric/resample.hpp> #include <boost/gil/extension/numeric/sampler.hpp> #include <boost/gil/typedefs.hpp> #include <boost/log/trivial.hpp> #include <algorithm> #include <utility> #include "src/jpeg2000Compression.h" #include "src/jpegCompression.h" #include "src/opencvinterpolationframe.h" #include "src/rawCompression.h" #include "src/zlibWrapper.h" namespace wsiToDicomConverter { OpenCVInterpolationFrame::OpenCVInterpolationFrame( OpenSlidePtr *osptr, int64_t locationX, int64_t locationY, int32_t level, int64_t frameWidthDownsampled, int64_t frameHeightDownsampled, int64_t frameWidth, int64_t frameHeight, DCM_Compression compression, int quality, JpegSubsampling subsampling, int64_t levelWidth, int64_t levelHeight, int64_t level0Width, int64_t level0Height, bool storeRawBytes, DICOMFileFrameRegionReader *frame_region_reader, const cv::InterpolationFlags openCVInterpolationMethod) : Frame(locationX, locationY, frameWidth, frameHeight, compression, quality, subsampling, storeRawBytes) { osptr_ = osptr; level_ = level; frameWidthDownsampled_ = frameWidthDownsampled; frameHeightDownsampled_ = frameHeightDownsampled; levelWidth_ = levelWidth; levelHeight_ = levelHeight; level0Width_ = level0Width; level0Height_ = level0Height; dcmFrameRegionReader_ = frame_region_reader; resized_ = frameWidth_ != frameWidthDownsampled_ || frameHeight_ != frameHeightDownsampled_; openCVInterpolationMethod_ = openCVInterpolationMethod; if (resized_) { /*Images padded with pixels outside of the frame to enable resampling algorithms which sample the surrounding pixels to incporate neighboring pixel values that reside outside of the frames pixels that are being resized. Actual padding = unscaledMaxPadding * scaling factor. */ const int unscaledMaxPadding = 5; widthScaleFactor_ = frameWidthDownsampled_ / frameWidth_; heightScaleFactor_ = frameHeightDownsampled_ / frameHeight_; int max_pad_width = unscaledMaxPadding * static_cast<int>(ceil(widthScaleFactor_)); int max_pad_height = unscaledMaxPadding * static_cast<int>(ceil(heightScaleFactor_)); padLeft_ = std::min<int>(max_pad_width, locationX_); padTop_ = std::min<int>(max_pad_height, locationY_); int padRight = std::min<int>(std::max<int>(0, levelWidth_ - (locationX_ + frameWidthDownsampled_)), max_pad_width); int padBottom = std::min<int>(std::max<int>(0, levelHeight_ - (locationY_ + frameHeightDownsampled_)), max_pad_height); scalefactorNormPadding(&padLeft_, widthScaleFactor_); scalefactorNormPadding(&padRight, widthScaleFactor_); scalefactorNormPadding(&padTop_, heightScaleFactor_); scalefactorNormPadding(&padBottom, heightScaleFactor_); padWidth_ = padLeft_ + padRight; padHeight_ = padTop_ + padBottom; } else { widthScaleFactor_ = 1; heightScaleFactor_ = 1; padLeft_ = 0; padTop_ = 0; padWidth_ = 0; padHeight_ = 0; } } OpenCVInterpolationFrame::~OpenCVInterpolationFrame() {} void OpenCVInterpolationFrame::scalefactorNormPadding(int *padding, int scalefactor) { *padding = (*padding / scalefactor) * scalefactor; } void OpenCVInterpolationFrame::incSourceFrameReadCounter() { if (dcmFrameRegionReader_->dicomFileCount() != 0) { // Computes frames which downsample region will access from and increments // source frame counter. dcmFrameRegionReader_->incSourceFrameReadCounter(locationX_ - padLeft_, locationY_ - padTop_, frameWidthDownsampled_ + padWidth_, frameHeightDownsampled_ + padHeight_); } } void OpenCVInterpolationFrame::sliceFrame() { // Downsamples a rectangular region a layer of a SVS and compresses frame // output. // Allocate memory to retrieve layer data from openslide std::unique_ptr<uint32_t[]> buf_bytes = std::make_unique<uint32_t[]>( static_cast<size_t>((frameWidthDownsampled_ + padWidth_) * (frameHeightDownsampled_ + padHeight_))); // If progressively downsampling then dcmFrameRegionReader_ contains // previous level downsample files and their assocciated frames. If no // files are contained, either the highest resolution image is being // downsampled or progressive downsampling is not being used. If this is // the case the image is retrieved using openslide. const bool dcmFrameRegionReaderNotInitalized = dcmFrameRegionReader_->dicomFileCount() == 0; if (dcmFrameRegionReaderNotInitalized) { // Open slide API samples using xy coordinages from level 0 image. // upsample coordinates to level 0 to compute sampleing site. const int64_t Level0_x = ((locationX_ - padLeft_) * level0Width_) / levelWidth_; const int64_t Level0_y = ((locationY_ - padTop_) * level0Height_) / levelHeight_; // Open slide read region returns ARGB formated pixels // Values are pre-multiplied with alpha // https://github.com/openslide/openslide/wiki/PremultipliedARGB openslide_read_region(osptr_->osr(), buf_bytes.get(), Level0_x, Level0_y, level_, frameWidthDownsampled_ + padWidth_, frameHeightDownsampled_ + padHeight_); if (openslide_get_error(osptr_->osr())) { BOOST_LOG_TRIVIAL(error) << openslide_get_error(osptr_->osr()); throw 1; } // Uncommon, openslide C++ API premults RGB by alpha. // if alpha is not zero reverse transform to get RGB // https://openslide.org/api/openslide_8h.html const int yend = frameHeightDownsampled_ + padHeight_; int yoffset = 0; for (uint32_t y = 0; y < yend; ++y) { const int xend = frameWidthDownsampled_ + padWidth_ + yoffset; for (uint32_t x = yoffset; x < xend; ++x) { const uint32_t pixel = buf_bytes[x]; // Pixel value to be downsampled const int alpha = pixel >> 24; // Alpha value of pixel if (alpha == 0) { // If transparent skip continue; } uint32_t red = (pixel >> 16) & 0xFF; // Get RGB Bytes uint32_t green = (pixel >> 8) & 0xFF; uint32_t blue = pixel & 0xFF; // Uncommon, openslide C++ API premults RGB by alpha. // if alpha is not zero reverse transform to get RGB // https://openslide.org/api/openslide_8h.html if (alpha != 0xFF) { red = red * 255 / alpha; green = green * 255 / alpha; blue = blue * 255 / alpha; } // Swap red and blue channel for dicom compatiability. buf_bytes[x] = (alpha << 24) | (blue << 16) | (green << 8) | red; } yoffset += frameWidthDownsampled_ + padWidth_; } } else { if (!dcmFrameRegionReader_->readRegion(locationX_ - padLeft_, locationY_ - padTop_, frameWidthDownsampled_ + padWidth_, frameHeightDownsampled_ + padHeight_, buf_bytes.get())) { BOOST_LOG_TRIVIAL(error) << "Error occured decoding previous level " "region."; throw 1; } } const size_t frame_mem_size = static_cast<size_t>(frameWidth_ * frameHeight_); std::unique_ptr<uint32_t[]> raw_bytes; if (!resized_) { // If image is not being resized move memory from buffer to raw_bytes raw_bytes = std::move(buf_bytes); } else { // Initalize OpenCV image with source image bits padded out to // provide context beyond frame boundry. cv::Mat source_image(frameHeightDownsampled_+padHeight_, frameWidthDownsampled_+padWidth_, CV_8UC4, buf_bytes.get()); cv::Mat resized_image; const int resize_width = frameWidth_ + (padWidth_ / widthScaleFactor_); const int resize_height = frameHeight_ + (padHeight_ / heightScaleFactor_); /* ResizeFlags cv::INTER_NEAREST = 0, cv::INTER_LINEAR = 1, cv::INTER_CUBIC = 2, cv::INTER_AREA = 3, cv::INTER_LANCZOS4 = 4, cv::INTER_LINEAR_EXACT = 5, cv::INTER_NEAREST_EXACT = 6, cv::INTER_MAX = 7, */ // Open CV resize image cv::resize(source_image, resized_image, cv::Size(resize_width, resize_height), 0, 0, openCVInterpolationMethod_); // Copy area of intrest from resized source image to raw bytres buffer raw_bytes = std::make_unique<uint32_t[]>(frame_mem_size); const int xstart = padLeft_ / widthScaleFactor_; const int ystart = padTop_ / heightScaleFactor_; const int yend = frameHeight_ + ystart; uint32_t raw_offset = 0; uint32_t source_yoffset = ystart * resize_width; uint32_t* resized_source_img = reinterpret_cast<uint32_t*>(resized_image.data); for (uint32_t y = ystart; y < yend; ++y) { const uint32_t xend = frameWidth_+xstart + source_yoffset; for (uint32_t x = xstart+source_yoffset; x < xend; ++x) { raw_bytes[raw_offset] = resized_source_img[x]; raw_offset += 1; } source_yoffset += resize_width; } } // Create a boot::gil view of memory in downsample_bytes boost::gil::rgba8c_view_t gil = boost::gil::interleaved_view( frameWidth_, frameHeight_, (const boost::gil::rgba8c_pixel_t *)raw_bytes.get(), frameWidth_ * sizeof(uint32_t)); // Create gil::image to copy bytes into boost::gil::rgb8_image_t exp(frameWidth_, frameHeight_); boost::gil::rgb8_view_t rgbView = view(exp); boost::gil::copy_pixels(gil, rgbView); // Compress memory (RAW, jpeg, or jpeg2000) uint64_t size; std::unique_ptr<uint8_t[]>mem = std::move(compressor_->compress(rgbView, &size)); setDicomFrameBytes(std::move(mem), size); if (!storeRawBytes_) { rawCompressedBytes_ = nullptr; rawCompressedBytesSize_ = 0; } else { rawCompressedBytes_ = std::move(compress_memory( reinterpret_cast<uint8_t*>(raw_bytes.get()), frame_mem_size * sizeof(uint32_t), &rawCompressedBytesSize_)); } done_ = true; } } // namespace wsiToDicomConverter <commit_msg>Update opencvinterpolationframe.cpp<commit_after>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 <dcmtk/dcmdata/libi2d/i2dimgs.h> #include <boost/gil/extension/numeric/affine.hpp> #include <boost/gil/extension/numeric/resample.hpp> #include <boost/gil/extension/numeric/sampler.hpp> #include <boost/gil/typedefs.hpp> #include <boost/log/trivial.hpp> #include <algorithm> #include <utility> #include "src/jpeg2000Compression.h" #include "src/jpegCompression.h" #include "src/opencvinterpolationframe.h" #include "src/rawCompression.h" #include "src/zlibWrapper.h" namespace wsiToDicomConverter { OpenCVInterpolationFrame::OpenCVInterpolationFrame( OpenSlidePtr *osptr, int64_t locationX, int64_t locationY, int32_t level, int64_t frameWidthDownsampled, int64_t frameHeightDownsampled, int64_t frameWidth, int64_t frameHeight, DCM_Compression compression, int quality, JpegSubsampling subsampling, int64_t levelWidth, int64_t levelHeight, int64_t level0Width, int64_t level0Height, bool storeRawBytes, DICOMFileFrameRegionReader *frame_region_reader, const cv::InterpolationFlags openCVInterpolationMethod) : Frame(locationX, locationY, frameWidth, frameHeight, compression, quality, subsampling, storeRawBytes) { osptr_ = osptr; level_ = level; frameWidthDownsampled_ = frameWidthDownsampled; frameHeightDownsampled_ = frameHeightDownsampled; levelWidth_ = levelWidth; levelHeight_ = levelHeight; level0Width_ = level0Width; level0Height_ = level0Height; dcmFrameRegionReader_ = frame_region_reader; resized_ = frameWidth_ != frameWidthDownsampled_ || frameHeight_ != frameHeightDownsampled_; openCVInterpolationMethod_ = openCVInterpolationMethod; if (resized_) { /*Images padded with pixels outside of the frame to enable resampling algorithms which sample the surrounding pixels to incporate neighboring pixel values that reside outside of the frames pixels that are being resized. Actual padding = unscaledMaxPadding * scaling factor. */ widthScaleFactor_ = frameWidthDownsampled_ / frameWidth_; heightScaleFactor_ = frameHeightDownsampled_ / frameHeight_; int max_pad_width; int max_pad_height; if (openCVInterpolationMethod == cv::INTER_AREA || openCVInterpolationMethod == cv::INTER_NEAREST) { max_pad_width = 0; max_pad_height = 0; } else { max_pad_width = 8; max_pad_height = 8; } padLeft_ = std::min<int>(max_pad_width, locationX_); padTop_ = std::min<int>(max_pad_height, locationY_); int padRight = std::min<int>(std::max<int>(0, levelWidth_ - (locationX_ + frameWidthDownsampled_)), max_pad_width); int padBottom = std::min<int>(std::max<int>(0, levelHeight_ - (locationY_ + frameHeightDownsampled_)), max_pad_height); scalefactorNormPadding(&padLeft_, widthScaleFactor_); scalefactorNormPadding(&padRight, widthScaleFactor_); scalefactorNormPadding(&padTop_, heightScaleFactor_); scalefactorNormPadding(&padBottom, heightScaleFactor_); padWidth_ = padLeft_ + padRight; padHeight_ = padTop_ + padBottom; } else { widthScaleFactor_ = 1; heightScaleFactor_ = 1; padLeft_ = 0; padTop_ = 0; padWidth_ = 0; padHeight_ = 0; } } OpenCVInterpolationFrame::~OpenCVInterpolationFrame() {} void OpenCVInterpolationFrame::scalefactorNormPadding(int *padding, int scalefactor) { if (*padding <= 0) { return; } *padding += scalefactor - (*padding % scalefactor); } void OpenCVInterpolationFrame::incSourceFrameReadCounter() { if (dcmFrameRegionReader_->dicomFileCount() != 0) { // Computes frames which downsample region will access from and increments // source frame counter. dcmFrameRegionReader_->incSourceFrameReadCounter(locationX_ - padLeft_, locationY_ - padTop_, frameWidthDownsampled_ + padWidth_, frameHeightDownsampled_ + padHeight_); } } void OpenCVInterpolationFrame::sliceFrame() { // Downsamples a rectangular region a layer of a SVS and compresses frame // output. // Allocate memory to retrieve layer data from openslide std::unique_ptr<uint32_t[]> buf_bytes = std::make_unique<uint32_t[]>( static_cast<size_t>((frameWidthDownsampled_ + padWidth_) * (frameHeightDownsampled_ + padHeight_))); // If progressively downsampling then dcmFrameRegionReader_ contains // previous level downsample files and their assocciated frames. If no // files are contained, either the highest resolution image is being // downsampled or progressive downsampling is not being used. If this is // the case the image is retrieved using openslide. const bool dcmFrameRegionReaderNotInitalized = dcmFrameRegionReader_->dicomFileCount() == 0; if (dcmFrameRegionReaderNotInitalized) { // Open slide API samples using xy coordinages from level 0 image. // upsample coordinates to level 0 to compute sampleing site. const int64_t Level0_x = ((locationX_ - padLeft_) * level0Width_) / levelWidth_; const int64_t Level0_y = ((locationY_ - padTop_) * level0Height_) / levelHeight_; // Open slide read region returns ARGB formated pixels // Values are pre-multiplied with alpha // https://github.com/openslide/openslide/wiki/PremultipliedARGB openslide_read_region(osptr_->osr(), buf_bytes.get(), Level0_x, Level0_y, level_, frameWidthDownsampled_ + padWidth_, frameHeightDownsampled_ + padHeight_); if (openslide_get_error(osptr_->osr())) { BOOST_LOG_TRIVIAL(error) << openslide_get_error(osptr_->osr()); throw 1; } // Uncommon, openslide C++ API premults RGB by alpha. // if alpha is not zero reverse transform to get RGB // https://openslide.org/api/openslide_8h.html const int yend = frameHeightDownsampled_ + padHeight_; int yoffset = 0; for (uint32_t y = 0; y < yend; ++y) { const int xend = frameWidthDownsampled_ + padWidth_ + yoffset; for (uint32_t x = yoffset; x < xend; ++x) { const uint32_t pixel = buf_bytes[x]; // Pixel value to be downsampled const int alpha = pixel >> 24; // Alpha value of pixel if (alpha == 0) { // If transparent skip continue; } uint32_t red = (pixel >> 16) & 0xFF; // Get RGB Bytes uint32_t green = (pixel >> 8) & 0xFF; uint32_t blue = pixel & 0xFF; // Uncommon, openslide C++ API premults RGB by alpha. // if alpha is not zero reverse transform to get RGB // https://openslide.org/api/openslide_8h.html if (alpha != 0xFF) { red = red * 255 / alpha; green = green * 255 / alpha; blue = blue * 255 / alpha; } // Swap red and blue channel for dicom compatiability. buf_bytes[x] = (alpha << 24) | (blue << 16) | (green << 8) | red; } yoffset += frameWidthDownsampled_ + padWidth_; } } else { if (!dcmFrameRegionReader_->readRegion(locationX_ - padLeft_, locationY_ - padTop_, frameWidthDownsampled_ + padWidth_, frameHeightDownsampled_ + padHeight_, buf_bytes.get())) { BOOST_LOG_TRIVIAL(error) << "Error occured decoding previous level " "region."; throw 1; } } const size_t frame_mem_size = static_cast<size_t>(frameWidth_ * frameHeight_); std::unique_ptr<uint32_t[]> raw_bytes; if (!resized_) { // If image is not being resized move memory from buffer to raw_bytes raw_bytes = std::move(buf_bytes); } else { // Initalize OpenCV image with source image bits padded out to // provide context beyond frame boundry. cv::Mat source_image(frameHeightDownsampled_+padHeight_, frameWidthDownsampled_+padWidth_, CV_8UC4, buf_bytes.get()); cv::Mat resized_image; const int resize_width = frameWidth_ + (padWidth_ / widthScaleFactor_); const int resize_height = frameHeight_ + (padHeight_ / heightScaleFactor_); /* ResizeFlags cv::INTER_NEAREST = 0, cv::INTER_LINEAR = 1, cv::INTER_CUBIC = 2, cv::INTER_AREA = 3, cv::INTER_LANCZOS4 = 4, cv::INTER_LINEAR_EXACT = 5, cv::INTER_NEAREST_EXACT = 6, cv::INTER_MAX = 7, */ // Open CV resize image cv::resize(source_image, resized_image, cv::Size(resize_width, resize_height), 0, 0, openCVInterpolationMethod_); // Copy area of intrest from resized source image to raw bytres buffer raw_bytes = std::make_unique<uint32_t[]>(frame_mem_size); const int xstart = padLeft_ / widthScaleFactor_; const int ystart = padTop_ / heightScaleFactor_; const int yend = frameHeight_ + ystart; uint32_t raw_offset = 0; uint32_t source_yoffset = ystart * resize_width; uint32_t* resized_source_img = reinterpret_cast<uint32_t*>(resized_image.data); for (uint32_t y = ystart; y < yend; ++y) { const uint32_t xend = frameWidth_+xstart + source_yoffset; for (uint32_t x = xstart+source_yoffset; x < xend; ++x) { raw_bytes[raw_offset] = resized_source_img[x]; raw_offset += 1; } source_yoffset += resize_width; } } // Create a boot::gil view of memory in downsample_bytes boost::gil::rgba8c_view_t gil = boost::gil::interleaved_view( frameWidth_, frameHeight_, (const boost::gil::rgba8c_pixel_t *)raw_bytes.get(), frameWidth_ * sizeof(uint32_t)); // Create gil::image to copy bytes into boost::gil::rgb8_image_t exp(frameWidth_, frameHeight_); boost::gil::rgb8_view_t rgbView = view(exp); boost::gil::copy_pixels(gil, rgbView); // Compress memory (RAW, jpeg, or jpeg2000) uint64_t size; std::unique_ptr<uint8_t[]>mem = std::move(compressor_->compress(rgbView, &size)); setDicomFrameBytes(std::move(mem), size); if (!storeRawBytes_) { rawCompressedBytes_ = nullptr; rawCompressedBytesSize_ = 0; } else { rawCompressedBytes_ = std::move(compress_memory( reinterpret_cast<uint8_t*>(raw_bytes.get()), frame_mem_size * sizeof(uint32_t), &rawCompressedBytesSize_)); } done_ = true; } } // namespace wsiToDicomConverter <|endoftext|>
<commit_before>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) 2013 Adrien Devresse <[email protected]>, CERN * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <davix_internal.hpp> #include "davpropxmlparser.hpp" #include <utils/davix_logger_internal.hpp> #include <status/davixstatusrequest.hpp> #include <datetime/datetime_utils.hpp> #include <string_utils/stringutils.hpp> using namespace StrUtil; namespace Davix { const Xml::XmlPTree prop_node(Xml::ElementStart, "propstat"); const Xml::XmlPTree prop_collection(Xml::ElementStart, "collection"); static Xml::XmlPTree* webDavTree = NULL; static boost::once_flag _l_init = BOOST_ONCE_INIT; struct DavPropXMLParser::DavxPropXmlIntern{ DavxPropXmlIntern() : _stack(), _props(), _current_props(), _last_response_status(500), _last_filename(){ _stack.reserve(10); char_buffer.reserve(1024); } // node stack std::vector<Xml::XmlPTree> _stack; // props std::deque<FileProperties> _props; FileProperties _current_props; int _last_response_status; std::string _last_filename; // buffer std::string char_buffer; inline void appendChars(const char *buff, size_t len){ char_buffer.append(std::string(buff, len)); } inline void clear(){ char_buffer.clear(); } inline void add_new_elem(){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " properties detected "); _current_props.clear(); _current_props.filename = _last_filename; // setup the current filename _current_props.info.mode = 0777 | S_IFREG; // default : fake access to everything } inline void store_new_elem(){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " end of properties... "); if( _last_response_status > 100 && _last_response_status < 400){ _props.push_back(_current_props); }else{ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, "Bad status code ! properties dropped"); } } }; typedef void (*properties_cb)(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name); static void check_last_modified(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " getlastmodified found -> parse it "); time_t t = parse_standard_date(name.c_str()); if(t == -1){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, " getlastmodified parsing error : corrupted value ... ignored"); t = 0; } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " getlastmodified found -> value {} ", t); par._current_props.info.mtime = t; } static void check_creation_date(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, "creationdate found -> parse it"); time_t t = parse_standard_date(name.c_str()); if(t == -1){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, " creationdate parsing error : corrupted value ... ignored"); t = 0; } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " creationdate found -> value {} ", t); par._current_props.info.ctime = t; } static void check_is_directory(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ (void) name; DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " directory pattern found -> set flag IS_DIR"); par._current_props.info.mode |= S_IFDIR; par._current_props.info.mode &= ~(S_IFREG); } static void check_content_length(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " content length found -> parse it"); try{ const unsigned long mysize = toType<unsigned long, std::string>()(name); DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " content length found -> {}", mysize); par._current_props.info.size = static_cast<off_t>(mysize); }catch(...){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, " Invalid content length value in dav response"); } } static void check_mode_ext(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, "mode_t extension for LCGDM found -> parse it"); const unsigned long mymode = strtoul(name.c_str(), NULL, 8); if(mymode == ULONG_MAX){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, "Invalid mode_t value for the LCGDM extension"); errno =0; return; } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, fmt::sprintf(" mode_t extension found -> 0%o", (mode_t) mymode).c_str()); par._current_props.info.mode = (mode_t) mymode; } static void check_href(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ std::string _href(name); rtrim(_href, isSlash()); // remove trailing slash std::string::reverse_iterator it = std::find(_href.rbegin(), _href.rend(), '/'); if( it == _href.rend()){ par._last_filename.assign(_href); }else{ par._last_filename.assign(it.base(), _href.end()); } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " href/filename parsed -> {} ", par._last_filename.c_str() ); } static void check_status(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " status found -> parse it"); std::string str_status(name); ltrim(str_status, StrUtil::isSpace()); std::string::iterator it1, it2; it1 = std::find(str_status.begin(), str_status.end(), ' '); if( it1 != str_status.end()){ it2 = std::find(it1+1, str_status.end(), ' '); std::string str_status_parsed(it1+1, it2); unsigned long res = strtoul(str_status_parsed.c_str(), NULL, 10); if(res != ULONG_MAX){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " status value : {}", res); par._last_response_status = res; return; } } DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, "Invalid dav status field value"); errno =0; } void init_webdavTree(){ // Nodes list webDavTree = new Xml::XmlPTree(Xml::ElementStart, "multistatus"); webDavTree->addChild(Xml::XmlPTree(Xml::ElementStart, "response")); Xml::XmlPTree::iterator it = webDavTree->beginChildren(); it->addChild(Xml::XmlPTree(Xml::ElementStart, "href", Xml::XmlPTree::ChildrenList(), (void*) &check_href)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "propstat")); it = (--it->endChildren()); it->addChild(Xml::XmlPTree(Xml::ElementStart, "status", Xml::XmlPTree::ChildrenList(), (void*) &check_status)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "prop")); it = (--it->endChildren()); it->addChild(Xml::XmlPTree(Xml::ElementStart, "getlastmodified", Xml::XmlPTree::ChildrenList(), (void*) &check_last_modified)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "creationdate", Xml::XmlPTree::ChildrenList(), (void*) &check_creation_date)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "getcontentlength", Xml::XmlPTree::ChildrenList(), (void*) &check_content_length)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "mode", Xml::XmlPTree::ChildrenList(), (void*) &check_mode_ext)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "resourcetype")); it = (--it->endChildren()); it->addChild(Xml::XmlPTree(Xml::ElementStart, "collection", Xml::XmlPTree::ChildrenList(), (void*) &check_is_directory)); } DavPropXMLParser::DavPropXMLParser() : d_ptr(new DavxPropXmlIntern()) { boost::call_once(init_webdavTree, _l_init); } DavPropXMLParser::~DavPropXMLParser(){ delete d_ptr; } std::deque<FileProperties> & DavPropXMLParser::getProperties(){ return d_ptr->_props; } int DavPropXMLParser::parserStartElemCb(int parent, const char *nspace, const char *name, const char **atts){ (void) parent; (void) name; (void) nspace; (void) atts; // add elem to stack Xml::XmlPTree node(Xml::ElementStart, name); d_ptr->_stack.push_back(node); // if beginning of prop, add new element if(node.compareNode(prop_node)){ d_ptr->add_new_elem(); } return 1; } int DavPropXMLParser::parserCdataCb(int state, const char *cdata, size_t len){ (void) state; d_ptr->appendChars(cdata, len); return 0; } int DavPropXMLParser::parserEndElemCb(int state, const char *nspace, const char *name){ (void) state; (void) nspace; Xml::XmlPTree node(Xml::ElementStart, name); // find potential interesting data std::vector<Xml::XmlPTree::ptr_type> chain; if(d_ptr->char_buffer.size() != 0 || node.compareNode(prop_collection)){ chain = webDavTree->findChain(d_ptr->_stack); if(chain.size() > 0){ properties_cb cb = ((properties_cb) chain.at(chain.size()-1)->getMeta()); if(cb){ StrUtil::trim(d_ptr->char_buffer); cb(*d_ptr, d_ptr->char_buffer); } } } // push props if(node.compareNode(prop_node)){ d_ptr->store_new_elem(); } // cleaning work if(d_ptr->_stack.size() == 0) throw DavixException(davix_scope_xml_parser(),StatusCode::ParsingError, "Corrupted Parser Stack, Invalid XML"); d_ptr->_stack.pop_back(); d_ptr->clear(); return 0; } } // namespace Davix <commit_msg>desallocate properly WebDav XML tree when libdavix is unloaded<commit_after>/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) 2013 Adrien Devresse <[email protected]>, CERN * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <davix_internal.hpp> #include "davpropxmlparser.hpp" #include <utils/davix_logger_internal.hpp> #include <status/davixstatusrequest.hpp> #include <datetime/datetime_utils.hpp> #include <string_utils/stringutils.hpp> using namespace StrUtil; namespace Davix { const Xml::XmlPTree prop_node(Xml::ElementStart, "propstat"); const Xml::XmlPTree prop_collection(Xml::ElementStart, "collection"); static Ptr::Scoped<Xml::XmlPTree> webDavTree; static boost::once_flag _l_init = BOOST_ONCE_INIT; struct DavPropXMLParser::DavxPropXmlIntern{ DavxPropXmlIntern() : _stack(), _props(), _current_props(), _last_response_status(500), _last_filename(){ _stack.reserve(10); char_buffer.reserve(1024); } // node stack std::vector<Xml::XmlPTree> _stack; // props std::deque<FileProperties> _props; FileProperties _current_props; int _last_response_status; std::string _last_filename; // buffer std::string char_buffer; inline void appendChars(const char *buff, size_t len){ char_buffer.append(std::string(buff, len)); } inline void clear(){ char_buffer.clear(); } inline void add_new_elem(){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " properties detected "); _current_props.clear(); _current_props.filename = _last_filename; // setup the current filename _current_props.info.mode = 0777 | S_IFREG; // default : fake access to everything } inline void store_new_elem(){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " end of properties... "); if( _last_response_status > 100 && _last_response_status < 400){ _props.push_back(_current_props); }else{ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, "Bad status code ! properties dropped"); } } }; typedef void (*properties_cb)(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name); static void check_last_modified(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " getlastmodified found -> parse it "); time_t t = parse_standard_date(name.c_str()); if(t == -1){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, " getlastmodified parsing error : corrupted value ... ignored"); t = 0; } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " getlastmodified found -> value {} ", t); par._current_props.info.mtime = t; } static void check_creation_date(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, "creationdate found -> parse it"); time_t t = parse_standard_date(name.c_str()); if(t == -1){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, " creationdate parsing error : corrupted value ... ignored"); t = 0; } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " creationdate found -> value {} ", t); par._current_props.info.ctime = t; } static void check_is_directory(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ (void) name; DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " directory pattern found -> set flag IS_DIR"); par._current_props.info.mode |= S_IFDIR; par._current_props.info.mode &= ~(S_IFREG); } static void check_content_length(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " content length found -> parse it"); try{ const unsigned long mysize = toType<unsigned long, std::string>()(name); DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " content length found -> {}", mysize); par._current_props.info.size = static_cast<off_t>(mysize); }catch(...){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, " Invalid content length value in dav response"); } } static void check_mode_ext(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, "mode_t extension for LCGDM found -> parse it"); const unsigned long mymode = strtoul(name.c_str(), NULL, 8); if(mymode == ULONG_MAX){ DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, "Invalid mode_t value for the LCGDM extension"); errno =0; return; } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, fmt::sprintf(" mode_t extension found -> 0%o", (mode_t) mymode).c_str()); par._current_props.info.mode = (mode_t) mymode; } static void check_href(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ std::string _href(name); rtrim(_href, isSlash()); // remove trailing slash std::string::reverse_iterator it = std::find(_href.rbegin(), _href.rend(), '/'); if( it == _href.rend()){ par._last_filename.assign(_href); }else{ par._last_filename.assign(it.base(), _href.end()); } DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " href/filename parsed -> {} ", par._last_filename.c_str() ); } static void check_status(DavPropXMLParser::DavxPropXmlIntern & par, const std::string & name){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " status found -> parse it"); std::string str_status(name); ltrim(str_status, StrUtil::isSpace()); std::string::iterator it1, it2; it1 = std::find(str_status.begin(), str_status.end(), ' '); if( it1 != str_status.end()){ it2 = std::find(it1+1, str_status.end(), ' '); std::string str_status_parsed(it1+1, it2); unsigned long res = strtoul(str_status_parsed.c_str(), NULL, 10); if(res != ULONG_MAX){ DAVIX_SLOG(DAVIX_LOG_DEBUG, DAVIX_LOG_XML, " status value : {}", res); par._last_response_status = res; return; } } DAVIX_SLOG(DAVIX_LOG_VERBOSE, DAVIX_LOG_XML, "Invalid dav status field value"); errno =0; } void init_webdavTree(){ // Nodes list webDavTree.reset(new Xml::XmlPTree(Xml::ElementStart, "multistatus")); webDavTree->addChild(Xml::XmlPTree(Xml::ElementStart, "response")); Xml::XmlPTree::iterator it = webDavTree->beginChildren(); it->addChild(Xml::XmlPTree(Xml::ElementStart, "href", Xml::XmlPTree::ChildrenList(), (void*) &check_href)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "propstat")); it = (--it->endChildren()); it->addChild(Xml::XmlPTree(Xml::ElementStart, "status", Xml::XmlPTree::ChildrenList(), (void*) &check_status)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "prop")); it = (--it->endChildren()); it->addChild(Xml::XmlPTree(Xml::ElementStart, "getlastmodified", Xml::XmlPTree::ChildrenList(), (void*) &check_last_modified)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "creationdate", Xml::XmlPTree::ChildrenList(), (void*) &check_creation_date)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "getcontentlength", Xml::XmlPTree::ChildrenList(), (void*) &check_content_length)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "mode", Xml::XmlPTree::ChildrenList(), (void*) &check_mode_ext)); it->addChild(Xml::XmlPTree(Xml::ElementStart, "resourcetype")); it = (--it->endChildren()); it->addChild(Xml::XmlPTree(Xml::ElementStart, "collection", Xml::XmlPTree::ChildrenList(), (void*) &check_is_directory)); } DavPropXMLParser::DavPropXMLParser() : d_ptr(new DavxPropXmlIntern()) { boost::call_once(init_webdavTree, _l_init); } DavPropXMLParser::~DavPropXMLParser(){ delete d_ptr; } std::deque<FileProperties> & DavPropXMLParser::getProperties(){ return d_ptr->_props; } int DavPropXMLParser::parserStartElemCb(int parent, const char *nspace, const char *name, const char **atts){ (void) parent; (void) name; (void) nspace; (void) atts; // add elem to stack Xml::XmlPTree node(Xml::ElementStart, name); d_ptr->_stack.push_back(node); // if beginning of prop, add new element if(node.compareNode(prop_node)){ d_ptr->add_new_elem(); } return 1; } int DavPropXMLParser::parserCdataCb(int state, const char *cdata, size_t len){ (void) state; d_ptr->appendChars(cdata, len); return 0; } int DavPropXMLParser::parserEndElemCb(int state, const char *nspace, const char *name){ (void) state; (void) nspace; Xml::XmlPTree node(Xml::ElementStart, name); // find potential interesting data std::vector<Xml::XmlPTree::ptr_type> chain; if(d_ptr->char_buffer.size() != 0 || node.compareNode(prop_collection)){ chain = webDavTree->findChain(d_ptr->_stack); if(chain.size() > 0){ properties_cb cb = ((properties_cb) chain.at(chain.size()-1)->getMeta()); if(cb){ StrUtil::trim(d_ptr->char_buffer); cb(*d_ptr, d_ptr->char_buffer); } } } // push props if(node.compareNode(prop_node)){ d_ptr->store_new_elem(); } // cleaning work if(d_ptr->_stack.size() == 0) throw DavixException(davix_scope_xml_parser(),StatusCode::ParsingError, "Corrupted Parser Stack, Invalid XML"); d_ptr->_stack.pop_back(); d_ptr->clear(); return 0; } } // namespace Davix <|endoftext|>
<commit_before>#pragma once #include "acmacs-base/string.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/to-string.hh" #include "acmacs-base/range.hh" // Simplified version of https://github.com/joboccara/NamedType // Also see https://github.com/Enhex/phantom_type // ---------------------------------------------------------------------- namespace acmacs { template <typename T, typename Tag> class named_t { public: using value_type = T; explicit constexpr named_t() = default; template <typename T2> explicit constexpr named_t(T2&& value) : value_(std::forward<T2>(value)) {} // template <typename T2, typename = std::enable_if_t<std::is_same_v<T, size_t>>> // explicit constexpr named_t(T2 value) : value_(static_cast<T>(value)) {} // template <typename TT> using is_not_reference_t = typename std::enable_if<!std::is_reference<TT>::value, void>::type; // explicit constexpr named_t(const T& value) : value_(value) {} // explicit constexpr named_t(T&& value) : value_(std::move(value)) {} // template <typename T2 = T, typename = is_not_reference_t<T2>> explicit constexpr named_t(T2&& value) : value_(std::move(value)) {} constexpr T& get() noexcept { return value_; } constexpr const T& get() const noexcept { return value_; } constexpr T& operator*() noexcept { return value_; } constexpr const T& operator*() const noexcept { return value_; } constexpr const T* operator->() const noexcept { return &value_; } explicit constexpr operator T&() noexcept { return value_; } explicit constexpr operator const T&() const noexcept { return value_; } private: T value_; }; template <typename T, typename Tag> constexpr bool operator==(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T, typename Tag> constexpr bool operator!=(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return !operator==(lhs, rhs); } template <typename T, typename Tag> inline std::string to_string(const named_t<T, Tag>& nt) { return acmacs::to_string(nt.get()); } // ---------------------------------------------------------------------- template <typename Tag> class named_size_t : public named_t<size_t, Tag> { public: template <typename T> explicit constexpr named_size_t(T&& value) : named_t<size_t, Tag>(static_cast<size_t>(std::forward<T>(value))) {} constexpr auto& operator++() { ++this->get(); return *this; } constexpr auto& operator--() { --this->get(); return *this; } }; template <typename T> constexpr bool operator<(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() < rhs.get(); } template <typename T> constexpr bool operator<=(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() <= rhs.get(); } template <typename T> constexpr bool operator>(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() > rhs.get(); } template <typename T> constexpr bool operator>=(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() >= rhs.get(); } template <typename Tag> range(int, named_size_t<Tag>) -> range<named_size_t<Tag>>; template <typename Tag> range(size_t, named_size_t<Tag>) -> range<named_size_t<Tag>>; template <typename Tag> range(named_size_t<Tag>) -> range<named_size_t<Tag>>; template <typename Tag> range(named_size_t<Tag>, named_size_t<Tag>) -> range<named_size_t<Tag>>; // ---------------------------------------------------------------------- template <typename Tag> class named_string_t : public named_t<std::string, Tag> { public: using named_t<std::string, Tag>::named_t; bool empty() const noexcept { return this->get().empty(); } size_t size() const noexcept { return this->get().size(); } char operator[](size_t pos) const { return this->get()[pos]; } size_t find(const char* s, size_t pos = 0) const noexcept { return this->get().find(s, pos); } size_t find(char ch, size_t pos = 0) const noexcept { return this->get().find(ch, pos); } constexpr operator std::string_view() const noexcept { return this->get(); } int compare(const named_string_t<Tag>& rhs) const { return ::string::compare(this->get(), rhs.get()); } void assign(std::string_view source) { this->get().assign(source); } }; template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const std::string& rhs) noexcept { return lhs.get() == rhs; } template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const char* rhs) noexcept { return lhs.get() == rhs; } template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, std::string_view rhs) noexcept { return lhs.get() == rhs; } template <typename T, typename R> constexpr bool operator!=(const named_string_t<T>& lhs, R&& rhs) noexcept { return !operator==(lhs, std::forward<R>(rhs)); } template <typename T> constexpr bool operator<(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() < rhs.get(); } } // namespace acmacs // ---------------------------------------------------------------------- // template <typename T, typename Tag> struct fmt::formatter<acmacs::named_t<T, Tag>> : fmt::formatter<T> { // template <typename FormatCtx> auto format(const acmacs::named_t<T, Tag>& nt, FormatCtx& ctx) { return fmt::formatter<T>::format(nt.get(), ctx); } // }; template <typename Tag> struct fmt::formatter<acmacs::named_size_t<Tag>> : fmt::formatter<size_t> { template <typename FormatCtx> auto format(const acmacs::named_size_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<size_t>::format(nt.get(), ctx); } }; template <typename Tag> struct fmt::formatter<acmacs::named_string_t<Tag>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::named_string_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<std::string>::format(nt.get(), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>named_vector_t<commit_after>#pragma once #include "acmacs-base/string.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/to-string.hh" #include "acmacs-base/range.hh" // Simplified version of https://github.com/joboccara/NamedType // Also see https://github.com/Enhex/phantom_type // ---------------------------------------------------------------------- namespace acmacs { template <typename T, typename Tag> class named_t { public: using value_type = T; explicit constexpr named_t() = default; template <typename T2> explicit constexpr named_t(T2&& value) : value_(std::forward<T2>(value)) {} // template <typename T2, typename = std::enable_if_t<std::is_same_v<T, size_t>>> // explicit constexpr named_t(T2 value) : value_(static_cast<T>(value)) {} // template <typename TT> using is_not_reference_t = typename std::enable_if<!std::is_reference<TT>::value, void>::type; // explicit constexpr named_t(const T& value) : value_(value) {} // explicit constexpr named_t(T&& value) : value_(std::move(value)) {} // template <typename T2 = T, typename = is_not_reference_t<T2>> explicit constexpr named_t(T2&& value) : value_(std::move(value)) {} constexpr T& get() noexcept { return value_; } constexpr const T& get() const noexcept { return value_; } constexpr T& operator*() noexcept { return value_; } constexpr const T& operator*() const noexcept { return value_; } constexpr const T* operator->() const noexcept { return &value_; } explicit constexpr operator T&() noexcept { return value_; } explicit constexpr operator const T&() const noexcept { return value_; } private: T value_; }; template <typename T, typename Tag> constexpr bool operator==(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T, typename Tag> constexpr bool operator!=(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return !operator==(lhs, rhs); } template <typename T, typename Tag> inline std::string to_string(const named_t<T, Tag>& nt) { return acmacs::to_string(nt.get()); } // ---------------------------------------------------------------------- template <typename Tag> class named_size_t : public named_t<size_t, Tag> { public: template <typename T> explicit constexpr named_size_t(T&& value) : named_t<size_t, Tag>(static_cast<size_t>(std::forward<T>(value))) {} constexpr auto& operator++() { ++this->get(); return *this; } constexpr auto& operator--() { --this->get(); return *this; } }; template <typename T> constexpr bool operator<(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() < rhs.get(); } template <typename T> constexpr bool operator<=(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() <= rhs.get(); } template <typename T> constexpr bool operator>(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() > rhs.get(); } template <typename T> constexpr bool operator>=(const named_size_t<T>& lhs, const named_size_t<T>& rhs) noexcept { return lhs.get() >= rhs.get(); } template <typename Tag> range(int, named_size_t<Tag>) -> range<named_size_t<Tag>>; template <typename Tag> range(size_t, named_size_t<Tag>) -> range<named_size_t<Tag>>; template <typename Tag> range(named_size_t<Tag>) -> range<named_size_t<Tag>>; template <typename Tag> range(named_size_t<Tag>, named_size_t<Tag>) -> range<named_size_t<Tag>>; // ---------------------------------------------------------------------- template <typename Tag> class named_string_t : public named_t<std::string, Tag> { public: using named_t<std::string, Tag>::named_t; bool empty() const noexcept { return this->get().empty(); } size_t size() const noexcept { return this->get().size(); } char operator[](size_t pos) const { return this->get()[pos]; } size_t find(const char* s, size_t pos = 0) const noexcept { return this->get().find(s, pos); } size_t find(char ch, size_t pos = 0) const noexcept { return this->get().find(ch, pos); } constexpr operator std::string_view() const noexcept { return this->get(); } int compare(const named_string_t<Tag>& rhs) const { return ::string::compare(this->get(), rhs.get()); } void assign(std::string_view source) { this->get().assign(source); } }; template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const std::string& rhs) noexcept { return lhs.get() == rhs; } template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const char* rhs) noexcept { return lhs.get() == rhs; } template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, std::string_view rhs) noexcept { return lhs.get() == rhs; } template <typename T, typename R> constexpr bool operator!=(const named_string_t<T>& lhs, R&& rhs) noexcept { return !operator==(lhs, std::forward<R>(rhs)); } template <typename T> constexpr bool operator<(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() < rhs.get(); } // ---------------------------------------------------------------------- template <typename T, typename Tag> class named_vector_t : public named_t<std::vector<T>, Tag> { public: using value_type = T; using named_t<std::vector<T>, Tag>::named_t; constexpr auto begin() const { return this->get().begin(); } constexpr auto end() const { return this->get().end(); } constexpr auto begin() { return this->get().begin(); } constexpr auto end() { return this->get().end(); } constexpr auto rbegin() { return this->get().rbegin(); } constexpr auto rend() { return this->get().rend(); } // for std::back_inserter constexpr void push_back(const T& val) { this->get().push_back(val); } constexpr void push_back(T&& val) { this->get().push_back(std::forward<T>(val)); } void remove(const T& val) { if (const auto found = std::find(begin(), end(), val); found != end()) this->get().erase(found); } // set like bool exists(const T& val) const { return std::find(begin(), end(), val) != end(); } void insert_if_not_present(const T& val) { if (!exists(val)) push_back(val); } void insert_if_not_present(T&& val) { if (!exist(val)) push_back(std::forward<T>(val)); } void merge_in(const named_vector_t<T, Tag>& another) { for (const auto& val : another) insert_if_not_present(val); } }; } // namespace acmacs // ---------------------------------------------------------------------- // template <typename T, typename Tag> struct fmt::formatter<acmacs::named_t<T, Tag>> : fmt::formatter<T> { // template <typename FormatCtx> auto format(const acmacs::named_t<T, Tag>& nt, FormatCtx& ctx) { return fmt::formatter<T>::format(nt.get(), ctx); } // }; template <typename Tag> struct fmt::formatter<acmacs::named_size_t<Tag>> : fmt::formatter<size_t> { template <typename FormatCtx> auto format(const acmacs::named_size_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<size_t>::format(nt.get(), ctx); } }; template <typename Tag> struct fmt::formatter<acmacs::named_string_t<Tag>> : fmt::formatter<std::string> { template <typename FormatCtx> auto format(const acmacs::named_string_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<std::string>::format(nt.get(), ctx); } }; template <typename T, typename Tag> struct fmt::formatter<acmacs::named_vector_t<T, Tag>> : fmt::formatter<std::vector<T>> { template <typename FormatCtx> auto format(const acmacs::named_vector_t<T, Tag>& vec, FormatCtx& ctx) { return fmt::formatter<std::vector<T>>::format(vec.get(), ctx); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#pragma once #include <string> #include "acmacs-base/throw.hh" #include "acmacs-base/size.hh" // ---------------------------------------------------------------------- class TextStyle { public: enum class Slant { Normal, Italic }; enum class Weight { Normal, Bold }; inline TextStyle() : mSlant(Slant::Normal), mWeight(Weight::Normal) {} inline TextStyle(std::string aFontFamily, Slant aSlant = Slant::Normal, Weight aWeight = Weight::Normal) : mFontFamily(aFontFamily), mSlant(aSlant), mWeight(aWeight) {} inline TextStyle(std::string aFontFamily, std::string aSlant, std::string aWeight) : mFontFamily(aFontFamily) { slant(aSlant); weight(aWeight); } inline std::string font_family() const { return mFontFamily; } inline Slant slant() const { return mSlant; } inline Weight weight() const { return mWeight; } inline std::string slant_as_stirng() const { switch (mSlant) { case Slant::Normal: return "normal"; case Slant::Italic: return "italic"; } return "normal"; } inline std::string weight_as_stirng() const { switch (mWeight) { case Weight::Normal: return "normal"; case Weight::Bold: return "bold"; } return "normal"; } inline std::string& font_family() { return mFontFamily; } inline TextStyle& font_family(std::string s) { mFontFamily = s; return *this; } inline void font_family(const char* s, size_t len) { mFontFamily.assign(s, len); } inline TextStyle& slant(Slant aSlant) { mSlant = aSlant; return *this; } inline TextStyle& slant(std::string aSlant) { if (aSlant == "normal") mSlant = Slant::Normal; else if (aSlant == "italic") mSlant = Slant::Italic; else THROW_OR_CERR(std::runtime_error("Unrecognized TextStyle slant: " + aSlant)); return *this; } inline void slant(const char* s, size_t len) { slant(std::string(s, len)); } inline TextStyle& weight(Weight aWeight) { mWeight = aWeight; return *this; } inline TextStyle& weight(std::string aWeight) { if (aWeight == "normal") mWeight = Weight::Normal; else if (aWeight == "bold") mWeight = Weight::Bold; else THROW_OR_CERR(std::runtime_error("Unrecognized TextStyle weight: " + aWeight)); return *this; } inline void weight(const char* s, size_t len) { weight(std::string(s, len)); } private: std::string mFontFamily; Slant mSlant; Weight mWeight; }; // class TextStyle // ---------------------------------------------------------------------- namespace acmacs { class LabelStyle { public: inline LabelStyle() = default; inline bool shown() const { return mShown; } inline acmacs::Offset offset() const { return mOffset; } inline const TextStyle& text_style() const { return mStyle; } inline double size() const { return mSize; } inline Color color() const { return mColor; } inline Rotation rotation() const { return mRotation; } inline double interline() const { return mInterline; } inline LabelStyle& shown(bool aShown) { mShown = aShown; return *this; } inline LabelStyle& offset(const acmacs::Offset& aOffset) { mOffset = aOffset; return *this; } inline LabelStyle& text_style(const TextStyle& aTextStyle) { mStyle = aTextStyle; return *this; } inline LabelStyle& size(double aSize) { mSize = aSize; return *this; } inline LabelStyle& color(Color aColor) { mColor = aColor; return *this; } inline LabelStyle& rotation(Rotation aRotation) { mRotation = aRotation; return *this; } inline LabelStyle& interline(double aInterline) { mInterline = aInterline; return *this; } private: bool mShown{true}; acmacs::Offset mOffset; TextStyle mStyle; double mSize{1.0}; Color mColor{"black"}; Rotation mRotation{NoRotation}; double mInterline{0.2}; }; // class LabelStyle } // namespace acmacs // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>TextStyle moved to acmacs namespace<commit_after>#pragma once #include <string> #include "acmacs-base/throw.hh" #include "acmacs-base/size.hh" // ---------------------------------------------------------------------- namespace acmacs { class TextStyle { public: enum class Slant { Normal, Italic }; enum class Weight { Normal, Bold }; inline TextStyle() : mSlant(Slant::Normal), mWeight(Weight::Normal) {} inline TextStyle(std::string aFontFamily, Slant aSlant = Slant::Normal, Weight aWeight = Weight::Normal) : mFontFamily(aFontFamily), mSlant(aSlant), mWeight(aWeight) {} inline TextStyle(std::string aFontFamily, std::string aSlant, std::string aWeight) : mFontFamily(aFontFamily) { slant(aSlant); weight(aWeight); } inline std::string font_family() const { return mFontFamily; } inline Slant slant() const { return mSlant; } inline Weight weight() const { return mWeight; } inline std::string slant_as_stirng() const { switch (mSlant) { case Slant::Normal: return "normal"; case Slant::Italic: return "italic"; } return "normal"; } inline std::string weight_as_stirng() const { switch (mWeight) { case Weight::Normal: return "normal"; case Weight::Bold: return "bold"; } return "normal"; } inline std::string& font_family() { return mFontFamily; } inline TextStyle& font_family(std::string s) { mFontFamily = s; return *this; } inline void font_family(const char* s, size_t len) { mFontFamily.assign(s, len); } inline TextStyle& slant(Slant aSlant) { mSlant = aSlant; return *this; } inline TextStyle& slant(std::string aSlant) { if (aSlant == "normal") mSlant = Slant::Normal; else if (aSlant == "italic") mSlant = Slant::Italic; else THROW_OR_CERR(std::runtime_error("Unrecognized TextStyle slant: " + aSlant)); return *this; } inline void slant(const char* s, size_t len) { slant(std::string(s, len)); } inline TextStyle& weight(Weight aWeight) { mWeight = aWeight; return *this; } inline TextStyle& weight(std::string aWeight) { if (aWeight == "normal") mWeight = Weight::Normal; else if (aWeight == "bold") mWeight = Weight::Bold; else THROW_OR_CERR(std::runtime_error("Unrecognized TextStyle weight: " + aWeight)); return *this; } inline void weight(const char* s, size_t len) { weight(std::string(s, len)); } private: std::string mFontFamily; Slant mSlant; Weight mWeight; }; // class TextStyle // ---------------------------------------------------------------------- class LabelStyle { public: inline LabelStyle() = default; inline bool shown() const { return mShown; } inline acmacs::Offset offset() const { return mOffset; } inline const TextStyle& text_style() const { return mStyle; } inline double size() const { return mSize; } inline Color color() const { return mColor; } inline Rotation rotation() const { return mRotation; } inline double interline() const { return mInterline; } inline LabelStyle& shown(bool aShown) { mShown = aShown; return *this; } inline LabelStyle& offset(const acmacs::Offset& aOffset) { mOffset = aOffset; return *this; } inline LabelStyle& text_style(const TextStyle& aTextStyle) { mStyle = aTextStyle; return *this; } inline LabelStyle& size(double aSize) { mSize = aSize; return *this; } inline LabelStyle& color(Color aColor) { mColor = aColor; return *this; } inline LabelStyle& rotation(Rotation aRotation) { mRotation = aRotation; return *this; } inline LabelStyle& interline(double aInterline) { mInterline = aInterline; return *this; } private: bool mShown{true}; acmacs::Offset mOffset; TextStyle mStyle; double mSize{1.0}; Color mColor{"black"}; Rotation mRotation{NoRotation}; double mInterline{0.2}; }; // class LabelStyle } // namespace acmacs // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#pragma ident "$Id: ANSITime.cpp 1162 2008-03-27 21:18:13Z snelsen $" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ #include <cmath> #include "ANSITime.hpp" #include "TimeConstants.hpp" using namespace gpstk; namespace Rinex3 { ANSITime& ANSITime::operator=( const ANSITime& right ) throw() { time = right.time; return *this; } CommonTime ANSITime::convertToCommonTime() const throw(InvalidRequest) { try { return CommonTime( ( MJD_JDAY + UNIX_MJD + time / SEC_PER_DAY ), ( time % SEC_PER_DAY ), 0., timeSystem ); } catch (InvalidParameter& ip) { InvalidRequest ir(ip); GPSTK_THROW(ir); } } void ANSITime::convertFromCommonTime( const CommonTime& ct ) throw(InvalidRequest) { /// This is the earliest CommonTime for which ANSITimes are valid. static const CommonTime MIN_CT = ANSITime(0); /// This is the latest CommonTime for which ANSITimes are valid. /// 2^31 - 1 seconds static const CommonTime MAX_CT = ANSITime(2147483647); if ( ct < MIN_CT || ct > MAX_CT ) { InvalidRequest ir("Unable to convert given CommonTime to ANSITime."); GPSTK_THROW(ir); } long jday, sod; double fsod; TimeSystem timeSys; ct.get( jday, sod, fsod, timeSys ); time = static_cast<time_t>((jday - MJD_JDAY - UNIX_MJD) * SEC_PER_DAY + sod); timeSystem = timeSys; } std::string ANSITime::printf( const std::string& fmt) const throw( gpstk::StringUtils::StringException ) { try { using gpstk::StringUtils::formattedPrint; std::string rv( fmt ); rv = formattedPrint( rv, getFormatPrefixInt() + "K", "Klu", time ); return rv; } catch( gpstk::StringUtils::StringException& se ) { GPSTK_RETHROW( se ); } } std::string ANSITime::printError( const std::string& fmt) const throw( gpstk::StringUtils::StringException ) { try { using gpstk::StringUtils::formattedPrint; std::string rv( fmt ); rv = formattedPrint( rv, getFormatPrefixInt() + "K", "Ks", getError().c_str() ); return rv; } catch( gpstk::StringUtils::StringException& se ) { GPSTK_RETHROW( se ); } } bool ANSITime::setFromInfo( const IdToValue& info ) throw() { using namespace gpstk::StringUtils; IdToValue::const_iterator i = info.find('K'); if( i != info.end() ) { time = asInt( i->second ); } return true; } bool ANSITime::isValid() const throw() { ANSITime temp; temp.convertFromCommonTime( convertToCommonTime() ); if( *this == temp ) { return true; } return false; } void ANSITime::reset() throw() { time = 0; timeSystem = Unknown; } bool ANSITime::operator==( const ANSITime& right ) const throw() { if( timeSystem == right.timeSystem && fabs(time - right.time) < CommonTime::eps ) { return true; } return false; } bool ANSITime::operator!=( const ANSITime& right ) const throw() { return ( !operator==( right ) ); } bool ANSITime::operator<( const ANSITime& right ) const throw() { return ( timeSystem == right.timeSystem && time < right.time ); } bool ANSITime::operator>( const ANSITime& right ) const throw() { return ( !operator<=( right ) ); } bool ANSITime::operator<=( const ANSITime& right ) const throw() { return ( operator<( right ) || operator==( right ) ); } bool ANSITime::operator>=( const ANSITime& right ) const throw() { return ( !operator<( right ) ); } } // namespace <commit_msg>testing ANSITime::isValid()<commit_after>#pragma ident "$Id: ANSITime.cpp 1162 2008-03-27 21:18:13Z snelsen $" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ #include <cmath> #include "ANSITime.hpp" #include "TimeConstants.hpp" using namespace gpstk; namespace Rinex3 { ANSITime& ANSITime::operator=( const ANSITime& right ) throw() { time = right.time; return *this; } CommonTime ANSITime::convertToCommonTime() const throw(InvalidRequest) { try { return CommonTime( ( MJD_JDAY + UNIX_MJD + time / SEC_PER_DAY ), ( time % SEC_PER_DAY ), 0., timeSystem ); } catch (InvalidParameter& ip) { InvalidRequest ir(ip); GPSTK_THROW(ir); } } void ANSITime::convertFromCommonTime( const CommonTime& ct ) throw(InvalidRequest) { /// This is the earliest CommonTime for which ANSITimes are valid. static const CommonTime MIN_CT = ANSITime(0); /// This is the latest CommonTime for which ANSITimes are valid. /// 2^31 - 1 seconds static const CommonTime MAX_CT = ANSITime(2147483647); if ( ct < MIN_CT || ct > MAX_CT ) { InvalidRequest ir("Unable to convert given CommonTime to ANSITime."); GPSTK_THROW(ir); } long jday, sod; double fsod; TimeSystem timeSys; ct.get( jday, sod, fsod, timeSys ); time = static_cast<time_t>((jday - MJD_JDAY - UNIX_MJD) * SEC_PER_DAY + sod); timeSystem = timeSys; } std::string ANSITime::printf( const std::string& fmt) const throw( gpstk::StringUtils::StringException ) { try { using gpstk::StringUtils::formattedPrint; std::string rv( fmt ); rv = formattedPrint( rv, getFormatPrefixInt() + "K", "Klu", time ); return rv; } catch( gpstk::StringUtils::StringException& se ) { GPSTK_RETHROW( se ); } } std::string ANSITime::printError( const std::string& fmt) const throw( gpstk::StringUtils::StringException ) { try { using gpstk::StringUtils::formattedPrint; std::string rv( fmt ); rv = formattedPrint( rv, getFormatPrefixInt() + "K", "Ks", getError().c_str() ); return rv; } catch( gpstk::StringUtils::StringException& se ) { GPSTK_RETHROW( se ); } } bool ANSITime::setFromInfo( const IdToValue& info ) throw() { using namespace gpstk::StringUtils; IdToValue::const_iterator i = info.find('K'); if( i != info.end() ) { time = asInt( i->second ); } return true; } bool ANSITime::isValid() const throw() { CommonTime tempCT; ANSITime temp; tempCT = temp.convertToCommonTime(); cout << "ANSITime: convertToCommonTime() called ok"; temp.convertFromCommonTime( tempCT ); cout << "ANSITime: convertFromCommonTime() called ok"; // temp.convertFromCommonTime( convertToCommonTime() ); if( *this == temp ) { return true; } return false; } void ANSITime::reset() throw() { time = 0; timeSystem = Unknown; } bool ANSITime::operator==( const ANSITime& right ) const throw() { if( timeSystem == right.timeSystem && fabs(time - right.time) < CommonTime::eps ) { return true; } return false; } bool ANSITime::operator!=( const ANSITime& right ) const throw() { return ( !operator==( right ) ); } bool ANSITime::operator<( const ANSITime& right ) const throw() { return ( timeSystem == right.timeSystem && time < right.time ); } bool ANSITime::operator>( const ANSITime& right ) const throw() { return ( !operator<=( right ) ); } bool ANSITime::operator<=( const ANSITime& right ) const throw() { return ( operator<( right ) || operator==( right ) ); } bool ANSITime::operator>=( const ANSITime& right ) const throw() { return ( !operator<( right ) ); } } // namespace <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net) * 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 Ondrej Danek 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 "Round.h" #include "Game.h" #include "GameException.h" #include "Util.h" namespace Duel6 { Round::Round(Game& game, Int32 roundNumber, std::vector<Player>& players, const std::string& levelPath, bool mirror, Size background) : game(game), roundNumber(roundNumber), world(game, levelPath, mirror, background), deathMode(false), waterFillWait(0), showYouAreHere(D6_YOU_ARE_HERE_DURATION), gameOverWait(0), winner(-1) { preparePlayers(); } void Round::splitScreenView(Player& player, Int32 x, Int32 y) { const Video& video = game.getAppService().getVideo(); PlayerView view(x, y, video.getScreen().getClientWidth() / 2 - 4, video.getScreen().getClientHeight() / 2 - 4); player.setView(view); player.setInfoBarPosition(x + view.getWidth() / 2 - 76, y + 35); } void Round::setPlayerViews() { const Video& video = game.getAppService().getVideo(); std::vector<Player>& players = world.getPlayers(); for (Player& player : players) { player.prepareCam(video, game.getSettings().getScreenMode(), game.getSettings().getScreenZoom(), world.getLevel().getWidth(), world.getLevel().getHeight()); } if (game.getSettings().getScreenMode() == ScreenMode::FullScreen) { Size index = 0; Size partition = video.getScreen().getClientWidth() / players.size(); for (Player& player : players) { player.setView(PlayerView(0, 40, video.getScreen().getClientWidth(), video.getScreen().getClientHeight() - 40)); player.setInfoBarPosition(partition * index + partition / 2 - 80, 35); index++; } return; } else { if (players.size() == 2) { splitScreenView(players[0], video.getScreen().getClientWidth() / 4 + 2, 2); splitScreenView(players[1], video.getScreen().getClientWidth() / 4 + 2, video.getScreen().getClientHeight() / 2 + 2); } if (players.size() == 3) { splitScreenView(players[0], 2, 2); splitScreenView(players[1], video.getScreen().getClientWidth() / 2 + 2, 2); splitScreenView(players[2], video.getScreen().getClientWidth() / 4 + 2, video.getScreen().getClientHeight() / 2 + 2); } if (players.size() == 4) { splitScreenView(players[0], 2, 2); splitScreenView(players[1], video.getScreen().getClientWidth() / 2 + 2, 2); splitScreenView(players[2], 2, video.getScreen().getClientHeight() / 2 + 2); splitScreenView(players[3], video.getScreen().getClientWidth() / 2 + 2, video.getScreen().getClientHeight() / 2 + 2); } } } bool Round::isPossibleStartingPosition(const Level& level, Int32 x, Int32 y) { if (level.isWall(x, y, true) || level.isWater(x, y)) { return false; } while (y-- > 0) { if (level.isWater(x, y)) { return false; } if (level.isWall(x, y, true)) { return true; } } return false; } void Round::findStartingPositions(std::queue<std::pair<Int32, Int32>>& startingPositions) { const Level& level = world.getLevel(); std::vector<std::pair<Int32, Int32>> possibleStartingPositions; for (Int32 y = 1; y < level.getHeight(); y++) { for (Int32 x = 0; x < level.getWidth(); x++) { if (isPossibleStartingPosition(level, x, y)) { possibleStartingPositions.push_back(std::pair<Int32, Int32>(x, y)); } } } if (possibleStartingPositions.empty()) { D6_THROW(GameException, "No acceptable starting positions found in this level"); } for (Size i = 0; i < world.getPlayers().size(); ++i) { Int32 arbitraryPosition = rand() % possibleStartingPositions.size(); startingPositions.push(possibleStartingPositions[arbitraryPosition]); } } void Round::preparePlayers() { game.getAppService().getConsole().printLine(D6_L("...Preparing players")); std::queue<std::pair<Int32, Int32>> startingPositions; findStartingPositions(startingPositions); for (Player& player : world.getPlayers()) { auto& ammoRange = game.getSettings().getAmmoRange(); Int32 ammo = ammoRange.first + rand() % (ammoRange.second - ammoRange.first + 1); std::pair<Int32, Int32>& position = startingPositions.front(); player.startGame(world, position.first, position.second, ammo); startingPositions.pop(); player.setBonus(D6_BONUS_INVUL, 2); } setPlayerViews(); } void Round::checkWinner() { int numAlive = 0; Player* lastAlive = nullptr; for (Player& player : world.getPlayers()) { if (!player.isDead()) { numAlive++; lastAlive = &player; } } if (numAlive < 2) { winner = 1; gameOverWait = D6_GAME_OVER_WAIT; if (numAlive == 1) { world.getMessageQueue().add(*lastAlive, D6_L("You have won - press ESC to quit or F1 for another round")); lastAlive->getPerson().addWins(1); } else { for (const Player& player : world.getPlayers()) { world.getMessageQueue().add(player, D6_L("End of round - no winner")); } } game.getResources().getGameOverSound().play(); } else if (numAlive == 2 && world.getPlayers().size() > 2) { deathMode = true; } } void Round::update(Float32 elapsedTime) { // Check if there's a winner if (winner == -1) { checkWinner(); } if (hasWinner()) { gameOverWait = std::max(gameOverWait - elapsedTime, 0.0f); if (gameOverWait < (D6_GAME_OVER_WAIT - D6_ROUND_OVER_WAIT)) { return; } } for (Player& player : world.getPlayers()) { player.update(world, game.getSettings().getScreenMode(), elapsedTime); } world.update(elapsedTime); if (deathMode) { waterFillWait += elapsedTime; if(waterFillWait > D6_RAISE_WATER_WAIT) { waterFillWait = 0; //world.raiseWater(); } } showYouAreHere = std::max(showYouAreHere - 3 * elapsedTime, 0.0f); } void Round::keyEvent(SDL_Keycode keyCode, Uint16 keyModifiers) { // Switch between fullscreen and split screen mode if (keyCode == SDLK_F2 && world.getPlayers().size() < 5) { switchScreenMode(); } // Turn on/off player statistics if (keyCode == SDLK_F4) { game.getSettings().setShowRanking(!game.getSettings().isShowRanking()); } // Save screenshot if (keyCode == SDLK_F10) { std::string name = Util::saveScreenTga(game.getAppService().getVideo()); game.getAppService().getConsole().printLine(Format(D6_L("Screenshot saved to {0}")) << name); } } void Round::switchScreenMode() { GameSettings& settings = game.getSettings(); settings.setScreenMode((settings.getScreenMode() == ScreenMode::FullScreen) ? ScreenMode::SplitScreen : ScreenMode::FullScreen); setPlayerViews(); game.getRenderer().initScreen(); } bool Round::isOver() const { return hasWinner() && gameOverWait <= 0; } bool Round::isLast() const { return game.getSettings().isRoundLimit() && roundNumber + 1 == game.getSettings().getMaxRounds(); } } <commit_msg>Fix water raising<commit_after>/* * Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net) * 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 Ondrej Danek 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 "Round.h" #include "Game.h" #include "GameException.h" #include "Util.h" namespace Duel6 { Round::Round(Game& game, Int32 roundNumber, std::vector<Player>& players, const std::string& levelPath, bool mirror, Size background) : game(game), roundNumber(roundNumber), world(game, levelPath, mirror, background), deathMode(false), waterFillWait(0), showYouAreHere(D6_YOU_ARE_HERE_DURATION), gameOverWait(0), winner(-1) { preparePlayers(); } void Round::splitScreenView(Player& player, Int32 x, Int32 y) { const Video& video = game.getAppService().getVideo(); PlayerView view(x, y, video.getScreen().getClientWidth() / 2 - 4, video.getScreen().getClientHeight() / 2 - 4); player.setView(view); player.setInfoBarPosition(x + view.getWidth() / 2 - 76, y + 35); } void Round::setPlayerViews() { const Video& video = game.getAppService().getVideo(); std::vector<Player>& players = world.getPlayers(); for (Player& player : players) { player.prepareCam(video, game.getSettings().getScreenMode(), game.getSettings().getScreenZoom(), world.getLevel().getWidth(), world.getLevel().getHeight()); } if (game.getSettings().getScreenMode() == ScreenMode::FullScreen) { Size index = 0; Size partition = video.getScreen().getClientWidth() / players.size(); for (Player& player : players) { player.setView(PlayerView(0, 40, video.getScreen().getClientWidth(), video.getScreen().getClientHeight() - 40)); player.setInfoBarPosition(partition * index + partition / 2 - 80, 35); index++; } return; } else { if (players.size() == 2) { splitScreenView(players[0], video.getScreen().getClientWidth() / 4 + 2, 2); splitScreenView(players[1], video.getScreen().getClientWidth() / 4 + 2, video.getScreen().getClientHeight() / 2 + 2); } if (players.size() == 3) { splitScreenView(players[0], 2, 2); splitScreenView(players[1], video.getScreen().getClientWidth() / 2 + 2, 2); splitScreenView(players[2], video.getScreen().getClientWidth() / 4 + 2, video.getScreen().getClientHeight() / 2 + 2); } if (players.size() == 4) { splitScreenView(players[0], 2, 2); splitScreenView(players[1], video.getScreen().getClientWidth() / 2 + 2, 2); splitScreenView(players[2], 2, video.getScreen().getClientHeight() / 2 + 2); splitScreenView(players[3], video.getScreen().getClientWidth() / 2 + 2, video.getScreen().getClientHeight() / 2 + 2); } } } bool Round::isPossibleStartingPosition(const Level& level, Int32 x, Int32 y) { if (level.isWall(x, y, true) || level.isWater(x, y)) { return false; } while (y-- > 0) { if (level.isWater(x, y)) { return false; } if (level.isWall(x, y, true)) { return true; } } return false; } void Round::findStartingPositions(std::queue<std::pair<Int32, Int32>>& startingPositions) { const Level& level = world.getLevel(); std::vector<std::pair<Int32, Int32>> possibleStartingPositions; for (Int32 y = 1; y < level.getHeight(); y++) { for (Int32 x = 0; x < level.getWidth(); x++) { if (isPossibleStartingPosition(level, x, y)) { possibleStartingPositions.push_back(std::pair<Int32, Int32>(x, y)); } } } if (possibleStartingPositions.empty()) { D6_THROW(GameException, "No acceptable starting positions found in this level"); } for (Size i = 0; i < world.getPlayers().size(); ++i) { Int32 arbitraryPosition = rand() % possibleStartingPositions.size(); startingPositions.push(possibleStartingPositions[arbitraryPosition]); } } void Round::preparePlayers() { game.getAppService().getConsole().printLine(D6_L("...Preparing players")); std::queue<std::pair<Int32, Int32>> startingPositions; findStartingPositions(startingPositions); for (Player& player : world.getPlayers()) { auto& ammoRange = game.getSettings().getAmmoRange(); Int32 ammo = ammoRange.first + rand() % (ammoRange.second - ammoRange.first + 1); std::pair<Int32, Int32>& position = startingPositions.front(); player.startGame(world, position.first, position.second, ammo); startingPositions.pop(); player.setBonus(D6_BONUS_INVUL, 2); } setPlayerViews(); } void Round::checkWinner() { int numAlive = 0; Player* lastAlive = nullptr; for (Player& player : world.getPlayers()) { if (!player.isDead()) { numAlive++; lastAlive = &player; } } if (numAlive < 2) { winner = 1; gameOverWait = D6_GAME_OVER_WAIT; if (numAlive == 1) { world.getMessageQueue().add(*lastAlive, D6_L("You have won - press ESC to quit or F1 for another round")); lastAlive->getPerson().addWins(1); } else { for (const Player& player : world.getPlayers()) { world.getMessageQueue().add(player, D6_L("End of round - no winner")); } } game.getResources().getGameOverSound().play(); } else if (numAlive == 2 && world.getPlayers().size() > 2) { deathMode = true; } } void Round::update(Float32 elapsedTime) { // Check if there's a winner if (winner == -1) { checkWinner(); } if (hasWinner()) { gameOverWait = std::max(gameOverWait - elapsedTime, 0.0f); if (gameOverWait < (D6_GAME_OVER_WAIT - D6_ROUND_OVER_WAIT)) { return; } } for (Player& player : world.getPlayers()) { player.update(world, game.getSettings().getScreenMode(), elapsedTime); } world.update(elapsedTime); if (deathMode) { waterFillWait += elapsedTime; if(waterFillWait > D6_RAISE_WATER_WAIT) { waterFillWait = 0; world.raiseWater(); } } showYouAreHere = std::max(showYouAreHere - 3 * elapsedTime, 0.0f); } void Round::keyEvent(SDL_Keycode keyCode, Uint16 keyModifiers) { // Switch between fullscreen and split screen mode if (keyCode == SDLK_F2 && world.getPlayers().size() < 5) { switchScreenMode(); } // Turn on/off player statistics if (keyCode == SDLK_F4) { game.getSettings().setShowRanking(!game.getSettings().isShowRanking()); } // Save screenshot if (keyCode == SDLK_F10) { std::string name = Util::saveScreenTga(game.getAppService().getVideo()); game.getAppService().getConsole().printLine(Format(D6_L("Screenshot saved to {0}")) << name); } } void Round::switchScreenMode() { GameSettings& settings = game.getSettings(); settings.setScreenMode((settings.getScreenMode() == ScreenMode::FullScreen) ? ScreenMode::SplitScreen : ScreenMode::FullScreen); setPlayerViews(); game.getRenderer().initScreen(); } bool Round::isOver() const { return hasWinner() && gameOverWait <= 0; } bool Round::isLast() const { return game.getSettings().isRoundLimit() && roundNumber + 1 == game.getSettings().getMaxRounds(); } } <|endoftext|>
<commit_before>/* Copyright 2016 Jonathan Bayle, Thomas Medioni 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 <vivace/vivace.hpp> #include "cyclist.hpp" using namespace vivace; #include <exception> #include <iostream> #include <string> #include <sstream> using namespace std; #include <glm/glm.hpp> using namespace glm; class Game: public Object_full_aggregator { public: Game() //character(true) { bg_colour = al_color_hsv(0., .8, .2); //johnny = unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter>(al_load_bitmap("data/johnny_running.png")); for (int i=0; i<8; i++) { //ALLEGRO_BITMAP* bmp = al_create_sub_bitmap(johnny.get(), 35*i, 0, 35, 68); //character.add_frame(shared_ptr<ALLEGRO_BITMAP>(bmp, al_bitmap_deleter()), 0.1); } add(player_); } virtual void update(double delta_t) { if (delta_t >= 1.) { cerr << "lag!" << endl; } else { //pos.x += speed.x * 50. * delta_t; //pos.y += speed.y * 50. * delta_t; } Object_full_aggregator::update(delta_t); //character.update(delta_t); sum_t += delta_t; if (sum_t >= 1.) { sum_t = 0; mk_fps_string(delta_t); } }; virtual void draw() { al_clear_to_color(bg_colour); //al_draw_bitmap(character.current().get(), 380+pos.x, 280-pos.y, 0); Object_full_aggregator::draw(); al_draw_text(debug_font(), al_map_rgb_f(1,1,1), 792, 8, ALLEGRO_ALIGN_RIGHT, fps_string.c_str()); al_flip_display(); }; virtual void handle(const ALLEGRO_EVENT& event) { float vecval = 0.; switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: cerr << "Bye!" << endl; throw 1; /* // Handle Keyboard events case ALLEGRO_EVENT_KEY_DOWN: vecval = 1.; case ALLEGRO_EVENT_KEY_UP: switch (event.keyboard.keycode) { case ALLEGRO_KEY_UP: //speed.y = vecval; break; case ALLEGRO_KEY_DOWN: //speed.y = -vecval; break; case ALLEGRO_KEY_LEFT: //speed.x = -vecval; break; case ALLEGRO_KEY_RIGHT: //speed.x = vecval; break; } // normalize(vecX({0.})) is undefined! //if (speed != vec2(0., 0.)) { // speed is 1 for all directions //speed = normalize(speed); //} break; case ALLEGRO_EVENT_KEY_CHAR: break; */ } Object_full_aggregator::handle(event); }; private: double sum_t = 0.; string fps_string; ALLEGRO_COLOR bg_colour; //Animation<shared_ptr<ALLEGRO_BITMAP>> character; //unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter> johnny; //vec2 pos{0., 0.}; // position in meter //vec2 speed{0., 0.}; // in meter per seconds PlayerCyclist player_; void mk_fps_string(double delta_t) { ostringstream oss; oss << static_cast<int>(1/delta_t) << " fps"; fps_string = oss.str(); }; }; int main(void) { try { Vivace engine("GAME_NAME"s, ""s); unique_ptr<ALLEGRO_DISPLAY, al_display_deleter> dsp(al_create_display(800, 600)); Game game; Basic_loop main_loop(1/30., game); main_loop.register_event_source(al_get_display_event_source(dsp.get())); main_loop.register_event_source(al_get_keyboard_event_source()); main_loop.run(); } catch (const std::exception& ex) { std::cerr << ex.what() << std::endl; } catch (int ex) {} } <commit_msg>fix warning<commit_after>/* Copyright 2016 Jonathan Bayle, Thomas Medioni 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 <vivace/vivace.hpp> #include "cyclist.hpp" using namespace vivace; #include <exception> #include <iostream> #include <string> #include <sstream> using namespace std; #include <glm/glm.hpp> using namespace glm; class Game: public Object_full_aggregator { public: Game() //character(true) { bg_colour = al_color_hsv(0., .8, .2); //johnny = unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter>(al_load_bitmap("data/johnny_running.png")); for (int i=0; i<8; i++) { //ALLEGRO_BITMAP* bmp = al_create_sub_bitmap(johnny.get(), 35*i, 0, 35, 68); //character.add_frame(shared_ptr<ALLEGRO_BITMAP>(bmp, al_bitmap_deleter()), 0.1); } add(player_); } virtual void update(double delta_t) { if (delta_t >= 1.) { cerr << "lag!" << endl; } else { //pos.x += speed.x * 50. * delta_t; //pos.y += speed.y * 50. * delta_t; } Object_full_aggregator::update(delta_t); //character.update(delta_t); sum_t += delta_t; if (sum_t >= 1.) { sum_t = 0; mk_fps_string(delta_t); } }; virtual void draw() { al_clear_to_color(bg_colour); //al_draw_bitmap(character.current().get(), 380+pos.x, 280-pos.y, 0); Object_full_aggregator::draw(); al_draw_text(debug_font(), al_map_rgb_f(1,1,1), 792, 8, ALLEGRO_ALIGN_RIGHT, fps_string.c_str()); al_flip_display(); }; virtual void handle(const ALLEGRO_EVENT& event) { // float vecval = 0.; switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: cerr << "Bye!" << endl; throw 1; /* // Handle Keyboard events case ALLEGRO_EVENT_KEY_DOWN: vecval = 1.; case ALLEGRO_EVENT_KEY_UP: switch (event.keyboard.keycode) { case ALLEGRO_KEY_UP: //speed.y = vecval; break; case ALLEGRO_KEY_DOWN: //speed.y = -vecval; break; case ALLEGRO_KEY_LEFT: //speed.x = -vecval; break; case ALLEGRO_KEY_RIGHT: //speed.x = vecval; break; } // normalize(vecX({0.})) is undefined! //if (speed != vec2(0., 0.)) { // speed is 1 for all directions //speed = normalize(speed); //} break; case ALLEGRO_EVENT_KEY_CHAR: break; */ } Object_full_aggregator::handle(event); }; private: double sum_t = 0.; string fps_string; ALLEGRO_COLOR bg_colour; //Animation<shared_ptr<ALLEGRO_BITMAP>> character; //unique_ptr<ALLEGRO_BITMAP, al_bitmap_deleter> johnny; //vec2 pos{0., 0.}; // position in meter //vec2 speed{0., 0.}; // in meter per seconds PlayerCyclist player_; void mk_fps_string(double delta_t) { ostringstream oss; oss << static_cast<int>(1/delta_t) << " fps"; fps_string = oss.str(); }; }; int main(void) { try { Vivace engine("GAME_NAME"s, ""s); unique_ptr<ALLEGRO_DISPLAY, al_display_deleter> dsp(al_create_display(800, 600)); Game game; Basic_loop main_loop(1/30., game); main_loop.register_event_source(al_get_display_event_source(dsp.get())); main_loop.register_event_source(al_get_keyboard_event_source()); main_loop.run(); } catch (const std::exception& ex) { std::cerr << ex.what() << std::endl; } catch (int ex) {} } <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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 <sys/time.h> #include <algorithm> #include <map> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "paddle/contrib/inference/paddle_inference_api_impl.h" namespace paddle { namespace { // Timer for timer class Timer { public: double start; double startu; void tic() { struct timeval tp; gettimeofday(&tp, NULL); start = tp.tv_sec; startu = tp.tv_usec; } double toc() { struct timeval tp; gettimeofday(&tp, NULL); double used_time_ms = (tp.tv_sec - start) * 1000.0 + (tp.tv_usec - startu) / 1000.0; return used_time_ms; } }; template <class T> std::string num2str(T a) { std::stringstream istr; istr << a; return istr.str(); } } // namespace bool PaddlePredictorImpl::Init() { VLOG(3) << "Predictor::init()"; // TODO(panyx0718): Should CPU vs GPU device be decided by id? if (config_.device >= 0) { place_ = paddle::platform::CUDAPlace(config_.device); } else { place_ = paddle::platform::CPUPlace(); } paddle::framework::InitDevices(false); executor_.reset(new paddle::framework::Executor(place_)); scope_.reset(new paddle::framework::Scope()); // Initialize the inference program if (!config_.model_dir.empty()) { // Parameters are saved in separate files sited in // the specified `dirname`. inference_program_ = paddle::inference::Load( executor_.get(), scope_.get(), config_.model_dir); } else if (!config_.prog_file.empty() && !config_.param_file.empty()) { // All parameters are saved in a single file. // The file names should be consistent with that used // in Python API `fluid.io.save_inference_model`. inference_program_ = paddle::inference::Load( executor_.get(), scope_.get(), config_.prog_file, config_.param_file); } else { LOG(ERROR) << "fail to load inference model."; return false; } ctx_ = executor_->Prepare(*inference_program_, 0); // Create variables // TODO(panyx0718): Why need to test share_variables here? if (config_.share_variables) { executor_->CreateVariables(*inference_program_, scope_.get(), 0); } // Get the feed_target_names and fetch_target_names feed_target_names_ = inference_program_->GetFeedTargetNames(); fetch_target_names_ = inference_program_->GetFetchTargetNames(); return true; } bool PaddlePredictorImpl::Run(const std::vector<PaddleTensor> &inputs, std::vector<PaddleTensor> *output_data) { VLOG(3) << "Predictor::predict"; Timer timer; timer.tic(); // set feed variable std::map<std::string, const paddle::framework::LoDTensor *> feed_targets; std::vector<paddle::framework::LoDTensor> feeds; if (!SetFeed(inputs, &feeds)) { LOG(ERROR) << "fail to set feed"; return false; } for (size_t i = 0; i < feed_target_names_.size(); ++i) { feed_targets[feed_target_names_[i]] = &feeds[i]; } // get fetch variable std::map<std::string, paddle::framework::LoDTensor *> fetch_targets; std::vector<paddle::framework::LoDTensor> fetchs; fetchs.resize(fetch_target_names_.size()); for (size_t i = 0; i < fetch_target_names_.size(); ++i) { fetch_targets[fetch_target_names_[i]] = &fetchs[i]; } // Run the inference program // if share variables, we need not create variables executor_->RunPreparedContext(ctx_.get(), scope_.get(), &feed_targets, &fetch_targets, !config_.share_variables); if (!GetFetch(fetchs, output_data)) { LOG(ERROR) << "fail to get fetchs"; return false; } VLOG(3) << "predict cost: " << timer.toc() << "ms"; return true; } std::unique_ptr<PaddlePredictor> PaddlePredictorImpl::Clone() { VLOG(3) << "Predictor::clone"; std::unique_ptr<PaddlePredictor> cls(new PaddlePredictorImpl(config_)); if (!cls->InitShared()) { LOG(ERROR) << "fail to call InitShared"; return nullptr; } // fix manylinux compile error. return cls; } // TODO(panyx0718): Consider merge with Init()? bool PaddlePredictorImpl::InitShared() { VLOG(3) << "Predictor::init_shared"; // 1. Define place, executor, scope if (this->config_.device >= 0) { place_ = paddle::platform::CUDAPlace(); } else { place_ = paddle::platform::CPUPlace(); } this->executor_.reset(new paddle::framework::Executor(this->place_)); this->scope_.reset(new paddle::framework::Scope()); // Initialize the inference program if (!this->config_.model_dir.empty()) { // Parameters are saved in separate files sited in // the specified `dirname`. this->inference_program_ = paddle::inference::Load( this->executor_.get(), this->scope_.get(), this->config_.model_dir); } else if (!this->config_.prog_file.empty() && !this->config_.param_file.empty()) { // All parameters are saved in a single file. // The file names should be consistent with that used // in Python API `fluid.io.save_inference_model`. this->inference_program_ = paddle::inference::Load(this->executor_.get(), this->scope_.get(), this->config_.prog_file, this->config_.param_file); } this->ctx_ = this->executor_->Prepare(*this->inference_program_, 0); // 3. create variables // TODO(panyx0718): why test share_variables. if (config_.share_variables) { this->executor_->CreateVariables( *this->inference_program_, this->scope_.get(), 0); } // 4. Get the feed_target_names and fetch_target_names this->feed_target_names_ = this->inference_program_->GetFeedTargetNames(); this->fetch_target_names_ = this->inference_program_->GetFetchTargetNames(); return true; } bool PaddlePredictorImpl::SetFeed( const std::vector<PaddleTensor> &inputs, std::vector<paddle::framework::LoDTensor> *feeds) { VLOG(3) << "Predictor::set_feed"; if (inputs.size() != feed_target_names_.size()) { LOG(ERROR) << "wrong feed input size."; return false; } for (size_t i = 0; i < feed_target_names_.size(); ++i) { paddle::framework::LoDTensor input; paddle::framework::DDim ddim = paddle::framework::make_ddim(inputs[i].shape); void *input_ptr; if (inputs[i].dtype == PaddleDType::INT64) { input_ptr = input.mutable_data<int64_t>(ddim, paddle::platform::CPUPlace()); } else if (inputs[i].dtype == PaddleDType::FLOAT32) { input_ptr = input.mutable_data<float>(ddim, paddle::platform::CPUPlace()); } else { LOG(ERROR) << "unsupported feed type " << inputs[i].dtype; return false; } // TODO(panyx0718): Init LoDTensor from existing memcpy to save a copy. std::memcpy(static_cast<void *>(input_ptr), inputs[i].data.data, inputs[i].data.length); feeds->push_back(input); LOG(ERROR) << "Actual feed type " << feeds->back().type().name(); } return true; } bool PaddlePredictorImpl::GetFetch( const std::vector<paddle::framework::LoDTensor> &fetchs, std::vector<PaddleTensor> *outputs) { VLOG(3) << "Predictor::get_fetch"; outputs->resize(fetchs.size()); for (size_t i = 0; i < fetchs.size(); ++i) { // TODO(panyx0718): Support fetch of other types. if (fetchs[i].type() != typeid(float)) { LOG(ERROR) << "only support fetching float now."; return false; } std::vector<int> shape; auto dims_i = fetchs[i].dims(); auto lod = fetchs[i].lod(); const float *output_ptr = fetchs[i].data<float>(); // const int64_t* output_ptr = fetchs[i].data<int64_t>(); auto num = fetchs[i].numel(); std::vector<float> data; if (0 == lod.size()) { std::copy(output_ptr, output_ptr + num, std::back_inserter(data)); for (int j = 0; j < dims_i.size(); ++j) { shape.push_back(dims_i[j]); } } else { // for batch detection // image[0] -> output[0] shape {145, 6} // image[1] -> output[1] shape {176, 6} // then, // the batch output shape {321, 6} // the lod {{0, 145, 321}} // so we should append output[0] to {176, 6} size_t max_dim = 0; for (size_t j = 1; j < lod[0].size(); j++) { max_dim = std::max(max_dim, lod[0][j] - lod[0][j - 1]); } size_t common_dim = lod[0].back() == 0 ? 0 : num / lod[0].back(); if (max_dim > 0) { data.resize((lod[0].size() - 1) * max_dim * common_dim, 0); } for (size_t j = 1; j < lod[0].size(); j++) { size_t start = lod[0][j - 1] * common_dim; size_t end = lod[0][j] * common_dim; if (end > start) { std::copy(output_ptr + start, output_ptr + end, data.begin() + (j - 1) * max_dim * common_dim); } } shape.push_back(lod[0].size() - 1); shape.push_back(max_dim); for (int j = 1; j < dims_i.size(); ++j) { shape.push_back(dims_i[j]); } } outputs->at(i).shape = shape; outputs->at(i).data.length = sizeof(float) * data.size(); outputs->at(i).data.data = malloc(outputs->at(i).data.length); std::memcpy( outputs->at(i).data.data, data.data(), outputs->at(i).data.length); outputs->at(i).dtype = PaddleDType::FLOAT32; // TODO(panyx0718): support other types? fill tensor name? avoid a copy. } return true; } std::unique_ptr<PaddlePredictorImpl> CreatePaddlePredictorImpl( const VisConfig &config) { VLOG(3) << "create PaddlePredictorImpl"; // 1. GPU memeroy std::vector<std::string> flags; if (config.fraction_of_gpu_memory >= 0.0f || config.fraction_of_gpu_memory <= 0.95f) { flags.push_back("dummpy"); std::string flag = "--fraction_of_gpu_memory_to_use=" + num2str<float>(config.fraction_of_gpu_memory); flags.push_back(flag); VLOG(3) << "set flag: " << flag; framework::InitGflags(flags); } std::unique_ptr<PaddlePredictorImpl> predictor( new PaddlePredictorImpl(config)); if (!predictor->Init()) { return nullptr; } return predictor; } } // namespace paddle <commit_msg>PaddlePredictorImpl::Clone return unique_ptr<commit_after>/* Copyright (c) 2018 PaddlePaddle 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 <sys/time.h> #include <algorithm> #include <map> #include <set> #include <sstream> #include <string> #include <utility> #include <vector> #include "paddle/contrib/inference/paddle_inference_api_impl.h" namespace paddle { namespace { // Timer for timer class Timer { public: double start; double startu; void tic() { struct timeval tp; gettimeofday(&tp, NULL); start = tp.tv_sec; startu = tp.tv_usec; } double toc() { struct timeval tp; gettimeofday(&tp, NULL); double used_time_ms = (tp.tv_sec - start) * 1000.0 + (tp.tv_usec - startu) / 1000.0; return used_time_ms; } }; template <class T> std::string num2str(T a) { std::stringstream istr; istr << a; return istr.str(); } } // namespace bool PaddlePredictorImpl::Init() { VLOG(3) << "Predictor::init()"; // TODO(panyx0718): Should CPU vs GPU device be decided by id? if (config_.device >= 0) { place_ = paddle::platform::CUDAPlace(config_.device); } else { place_ = paddle::platform::CPUPlace(); } paddle::framework::InitDevices(false); executor_.reset(new paddle::framework::Executor(place_)); scope_.reset(new paddle::framework::Scope()); // Initialize the inference program if (!config_.model_dir.empty()) { // Parameters are saved in separate files sited in // the specified `dirname`. inference_program_ = paddle::inference::Load( executor_.get(), scope_.get(), config_.model_dir); } else if (!config_.prog_file.empty() && !config_.param_file.empty()) { // All parameters are saved in a single file. // The file names should be consistent with that used // in Python API `fluid.io.save_inference_model`. inference_program_ = paddle::inference::Load( executor_.get(), scope_.get(), config_.prog_file, config_.param_file); } else { LOG(ERROR) << "fail to load inference model."; return false; } ctx_ = executor_->Prepare(*inference_program_, 0); // Create variables // TODO(panyx0718): Why need to test share_variables here? if (config_.share_variables) { executor_->CreateVariables(*inference_program_, scope_.get(), 0); } // Get the feed_target_names and fetch_target_names feed_target_names_ = inference_program_->GetFeedTargetNames(); fetch_target_names_ = inference_program_->GetFetchTargetNames(); return true; } bool PaddlePredictorImpl::Run(const std::vector<PaddleTensor> &inputs, std::vector<PaddleTensor> *output_data) { VLOG(3) << "Predictor::predict"; Timer timer; timer.tic(); // set feed variable std::map<std::string, const paddle::framework::LoDTensor *> feed_targets; std::vector<paddle::framework::LoDTensor> feeds; if (!SetFeed(inputs, &feeds)) { LOG(ERROR) << "fail to set feed"; return false; } for (size_t i = 0; i < feed_target_names_.size(); ++i) { feed_targets[feed_target_names_[i]] = &feeds[i]; } // get fetch variable std::map<std::string, paddle::framework::LoDTensor *> fetch_targets; std::vector<paddle::framework::LoDTensor> fetchs; fetchs.resize(fetch_target_names_.size()); for (size_t i = 0; i < fetch_target_names_.size(); ++i) { fetch_targets[fetch_target_names_[i]] = &fetchs[i]; } // Run the inference program // if share variables, we need not create variables executor_->RunPreparedContext(ctx_.get(), scope_.get(), &feed_targets, &fetch_targets, !config_.share_variables); if (!GetFetch(fetchs, output_data)) { LOG(ERROR) << "fail to get fetchs"; return false; } VLOG(3) << "predict cost: " << timer.toc() << "ms"; return true; } std::unique_ptr<PaddlePredictor> PaddlePredictorImpl::Clone() { VLOG(3) << "Predictor::clone"; std::unique_ptr<PaddlePredictor> cls(nullptr); if (!cls->InitShared()) { LOG(ERROR) << "fail to call InitShared"; } else { cls.reset(new PaddlePredictorImpl(config_)); } // fix manylinux compile error. return cls; } // TODO(panyx0718): Consider merge with Init()? bool PaddlePredictorImpl::InitShared() { VLOG(3) << "Predictor::init_shared"; // 1. Define place, executor, scope if (this->config_.device >= 0) { place_ = paddle::platform::CUDAPlace(); } else { place_ = paddle::platform::CPUPlace(); } this->executor_.reset(new paddle::framework::Executor(this->place_)); this->scope_.reset(new paddle::framework::Scope()); // Initialize the inference program if (!this->config_.model_dir.empty()) { // Parameters are saved in separate files sited in // the specified `dirname`. this->inference_program_ = paddle::inference::Load( this->executor_.get(), this->scope_.get(), this->config_.model_dir); } else if (!this->config_.prog_file.empty() && !this->config_.param_file.empty()) { // All parameters are saved in a single file. // The file names should be consistent with that used // in Python API `fluid.io.save_inference_model`. this->inference_program_ = paddle::inference::Load(this->executor_.get(), this->scope_.get(), this->config_.prog_file, this->config_.param_file); } this->ctx_ = this->executor_->Prepare(*this->inference_program_, 0); // 3. create variables // TODO(panyx0718): why test share_variables. if (config_.share_variables) { this->executor_->CreateVariables( *this->inference_program_, this->scope_.get(), 0); } // 4. Get the feed_target_names and fetch_target_names this->feed_target_names_ = this->inference_program_->GetFeedTargetNames(); this->fetch_target_names_ = this->inference_program_->GetFetchTargetNames(); return true; } bool PaddlePredictorImpl::SetFeed( const std::vector<PaddleTensor> &inputs, std::vector<paddle::framework::LoDTensor> *feeds) { VLOG(3) << "Predictor::set_feed"; if (inputs.size() != feed_target_names_.size()) { LOG(ERROR) << "wrong feed input size."; return false; } for (size_t i = 0; i < feed_target_names_.size(); ++i) { paddle::framework::LoDTensor input; paddle::framework::DDim ddim = paddle::framework::make_ddim(inputs[i].shape); void *input_ptr; if (inputs[i].dtype == PaddleDType::INT64) { input_ptr = input.mutable_data<int64_t>(ddim, paddle::platform::CPUPlace()); } else if (inputs[i].dtype == PaddleDType::FLOAT32) { input_ptr = input.mutable_data<float>(ddim, paddle::platform::CPUPlace()); } else { LOG(ERROR) << "unsupported feed type " << inputs[i].dtype; return false; } // TODO(panyx0718): Init LoDTensor from existing memcpy to save a copy. std::memcpy(static_cast<void *>(input_ptr), inputs[i].data.data, inputs[i].data.length); feeds->push_back(input); LOG(ERROR) << "Actual feed type " << feeds->back().type().name(); } return true; } bool PaddlePredictorImpl::GetFetch( const std::vector<paddle::framework::LoDTensor> &fetchs, std::vector<PaddleTensor> *outputs) { VLOG(3) << "Predictor::get_fetch"; outputs->resize(fetchs.size()); for (size_t i = 0; i < fetchs.size(); ++i) { // TODO(panyx0718): Support fetch of other types. if (fetchs[i].type() != typeid(float)) { LOG(ERROR) << "only support fetching float now."; return false; } std::vector<int> shape; auto dims_i = fetchs[i].dims(); auto lod = fetchs[i].lod(); const float *output_ptr = fetchs[i].data<float>(); // const int64_t* output_ptr = fetchs[i].data<int64_t>(); auto num = fetchs[i].numel(); std::vector<float> data; if (0 == lod.size()) { std::copy(output_ptr, output_ptr + num, std::back_inserter(data)); for (int j = 0; j < dims_i.size(); ++j) { shape.push_back(dims_i[j]); } } else { // for batch detection // image[0] -> output[0] shape {145, 6} // image[1] -> output[1] shape {176, 6} // then, // the batch output shape {321, 6} // the lod {{0, 145, 321}} // so we should append output[0] to {176, 6} size_t max_dim = 0; for (size_t j = 1; j < lod[0].size(); j++) { max_dim = std::max(max_dim, lod[0][j] - lod[0][j - 1]); } size_t common_dim = lod[0].back() == 0 ? 0 : num / lod[0].back(); if (max_dim > 0) { data.resize((lod[0].size() - 1) * max_dim * common_dim, 0); } for (size_t j = 1; j < lod[0].size(); j++) { size_t start = lod[0][j - 1] * common_dim; size_t end = lod[0][j] * common_dim; if (end > start) { std::copy(output_ptr + start, output_ptr + end, data.begin() + (j - 1) * max_dim * common_dim); } } shape.push_back(lod[0].size() - 1); shape.push_back(max_dim); for (int j = 1; j < dims_i.size(); ++j) { shape.push_back(dims_i[j]); } } outputs->at(i).shape = shape; outputs->at(i).data.length = sizeof(float) * data.size(); outputs->at(i).data.data = malloc(outputs->at(i).data.length); std::memcpy( outputs->at(i).data.data, data.data(), outputs->at(i).data.length); outputs->at(i).dtype = PaddleDType::FLOAT32; // TODO(panyx0718): support other types? fill tensor name? avoid a copy. } return true; } std::unique_ptr<PaddlePredictorImpl> CreatePaddlePredictorImpl( const VisConfig &config) { VLOG(3) << "create PaddlePredictorImpl"; // 1. GPU memeroy std::vector<std::string> flags; if (config.fraction_of_gpu_memory >= 0.0f || config.fraction_of_gpu_memory <= 0.95f) { flags.push_back("dummpy"); std::string flag = "--fraction_of_gpu_memory_to_use=" + num2str<float>(config.fraction_of_gpu_memory); flags.push_back(flag); VLOG(3) << "set flag: " << flag; framework::InitGflags(flags); } std::unique_ptr<PaddlePredictorImpl> predictor( new PaddlePredictorImpl(config)); if (!predictor->Init()) { return nullptr; } return predictor; } } // namespace paddle <|endoftext|>
<commit_before>/* molecule_wrap.cc * Copyright 2014 Cubane Canada, Inc. * * Released under the MIT license -- see MIT-LICENSE for details */ #include "./molecule_wrap.h" #include "./using_v8.h" #include "./get_inchi.h" #include "./get_inchi_data.h" #include "./get_inchi_worker.h" static Persistent<Function> m_molecule_wrap_constructor; void Molecule_wrap::Init(v8::Handle<v8::Object> exports) { Local<FunctionTemplate> tpl = FunctionTemplate::New(Molecule_wrap::New); tpl->SetClassName(NanSymbol("Molecule")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // prototype NODE_SET_PROTOTYPE_METHOD(tpl, "GetInChI", Molecule_wrap::GetInChI); m_molecule_wrap_constructor = Persistent<Function>::New(tpl->GetFunction()); exports->Set(NanSymbol("Molecule"), m_molecule_wrap_constructor); } NAN_METHOD(Molecule_wrap::New) { NanScope(); // check for arguments Molecule_wrap * m = new Molecule_wrap; Handle<Object> in = args[0]->ToObject(); m->addAtoms(in->Get(NanSymbol("atoms"))); m->addBonds(in->Get(NanSymbol("bonds"))); m->addStereo(in->Get(NanSymbol("stereo0D"))); m->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(Molecule_wrap::GetInChI) { NanScope(); Molecule_wrap * m = ObjectWrap::Unwrap<Molecule_wrap>(args.This()); NanCallback * callback = new NanCallback(args[0].As<Function>()); NanAsyncQueueWorker(new GetINCHIWorker(callback, &(m->mol))); NanReturnUndefined(); } void Molecule_wrap::addAtoms(Handle<Value> a) { Handle<Array> atoms = a.As<Array>(); // atoms is an array of v8::String for (uint32_t i = 0; i < atoms->Length(); i += 1) { Handle<Object> atom = atoms->Get(i)->ToObject(); mol.addAtom(InchiAtom::makeFromObject(atom)); } } template<typename T> T getIf(Handle<Object> atom, const char * k) { Handle<String> key = NanSymbol(k); return getIf<T, Handle<String> >(atom, key); } template<typename T, typename K> T getIf(Handle<Object> atom, K key) { return atom->Has(key) ? T(atom->Get(key)->NumberValue()) : 0; } const InchiAtom InchiAtom::makeFromObject(Handle<Object> atom) { char * elname = NanCString(atom->Get(NanSymbol("elname")), 0); InchiAtom ret(elname); delete[] elname; ret.data_.x = getIf<double>(atom, "x"); ret.data_.y = getIf<double>(atom, "y"); ret.data_.z = getIf<double>(atom, "z"); // ignore bond information; stored separately Handle<Array> num_iso_H = atom->Get(NanSymbol("num_iso_H")).As<Array>(); if (!num_iso_H->IsNull() && !num_iso_H->IsUndefined()) { for (int i = 0; i < (NUM_H_ISOTOPES+1); i += 1) { ret.data_.num_iso_H[i] = getIf<S_CHAR>(num_iso_H, i); } } ret.data_.isotopic_mass = getIf<AT_NUM>(atom, "isotopic_mass"); ret.data_.radical = getIf<S_CHAR>(atom, "radical"); ret.data_.charge = getIf<S_CHAR>(atom, "charge"); return ret; } void Molecule_wrap::addBonds(Handle<Value> b) { Handle<Array> bonds = b.As<Array>(); // bonds is an array of v8::Object for (uint32_t i = 0; i < bonds->Length(); i += 1) { Handle<Object> bond = bonds->Get(i)->ToObject(); int from = bond->Get(NanSymbol("from"))->NumberValue(); int to = bond->Get(NanSymbol("to"))->NumberValue(); int order = bond->Get(NanSymbol("order"))->NumberValue(); InchiBond b = (order ? InchiBond(from, to, order) : InchiBond(from, to)); mol.addBond(b); } } void Molecule_wrap::addStereo(Handle<Value> s) { if (s->IsNull() || s->IsUndefined()) { return; } Handle<Array> stereos = s.As<Array>(); for (uint32_t i = 0; i < stereos->Length(); i += 1) { Handle<Object> stereo = stereos->Get(i)->ToObject(); mol.addStereo(InchiStereo::makeFromObject(stereo)); } } const InchiStereo InchiStereo::makeFromObject(Handle<Object> stereo) { InchiStereo ret; Local<Array> neighbors = stereo->Get(NanSymbol("neighbor")).As<Array>(); for (uint32_t i = 0; i < STEREO0D_NEIGHBORS; i += 1) { ret.data_.neighbor[i] = getIf<AT_NUM>(neighbors, i); } ret.data_.central_atom = getIf<AT_NUM>(stereo, "central_atom"); ret.data_.type = getIf<S_CHAR>(stereo, "type"); ret.data_.parity = getIf<S_CHAR>(stereo, "parity"); return ret; } <commit_msg>inchilib: avoid fancy templates<commit_after>/* molecule_wrap.cc * Copyright 2014 Cubane Canada, Inc. * * Released under the MIT license -- see MIT-LICENSE for details */ #include "./molecule_wrap.h" #include "./using_v8.h" #include "./get_inchi.h" #include "./get_inchi_data.h" #include "./get_inchi_worker.h" static Persistent<Function> m_molecule_wrap_constructor; void Molecule_wrap::Init(v8::Handle<v8::Object> exports) { Local<FunctionTemplate> tpl = FunctionTemplate::New(Molecule_wrap::New); tpl->SetClassName(NanSymbol("Molecule")); tpl->InstanceTemplate()->SetInternalFieldCount(1); // prototype NODE_SET_PROTOTYPE_METHOD(tpl, "GetInChI", Molecule_wrap::GetInChI); m_molecule_wrap_constructor = Persistent<Function>::New(tpl->GetFunction()); exports->Set(NanSymbol("Molecule"), m_molecule_wrap_constructor); } NAN_METHOD(Molecule_wrap::New) { NanScope(); // check for arguments Molecule_wrap * m = new Molecule_wrap; Handle<Object> in = args[0]->ToObject(); m->addAtoms(in->Get(NanSymbol("atoms"))); m->addBonds(in->Get(NanSymbol("bonds"))); m->addStereo(in->Get(NanSymbol("stereo0D"))); m->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(Molecule_wrap::GetInChI) { NanScope(); Molecule_wrap * m = ObjectWrap::Unwrap<Molecule_wrap>(args.This()); NanCallback * callback = new NanCallback(args[0].As<Function>()); NanAsyncQueueWorker(new GetINCHIWorker(callback, &(m->mol))); NanReturnUndefined(); } void Molecule_wrap::addAtoms(Handle<Value> a) { Handle<Array> atoms = a.As<Array>(); // atoms is an array of v8::String for (uint32_t i = 0; i < atoms->Length(); i += 1) { Handle<Object> atom = atoms->Get(i)->ToObject(); mol.addAtom(InchiAtom::makeFromObject(atom)); } } template<typename T> T getIf(Handle<Object> atom, const char * k) { Handle<String> key = NanSymbol(k); return atom->Has(key) ? T(atom->Get(key)->NumberValue()) : 0; } template<typename T> T getIf(Handle<Object> atom, uint32_t key) { return atom->Has(key) ? T(atom->Get(key)->NumberValue()) : 0; } const InchiAtom InchiAtom::makeFromObject(Handle<Object> atom) { char * elname = NanCString(atom->Get(NanSymbol("elname")), 0); InchiAtom ret(elname); delete[] elname; ret.data_.x = getIf<double>(atom, "x"); ret.data_.y = getIf<double>(atom, "y"); ret.data_.z = getIf<double>(atom, "z"); // ignore bond information; stored separately Handle<Array> num_iso_H = atom->Get(NanSymbol("num_iso_H")).As<Array>(); if (!num_iso_H->IsNull() && !num_iso_H->IsUndefined()) { for (int i = 0; i < (NUM_H_ISOTOPES+1); i += 1) { ret.data_.num_iso_H[i] = getIf<S_CHAR>(num_iso_H, i); } } ret.data_.isotopic_mass = getIf<AT_NUM>(atom, "isotopic_mass"); ret.data_.radical = getIf<S_CHAR>(atom, "radical"); ret.data_.charge = getIf<S_CHAR>(atom, "charge"); return ret; } void Molecule_wrap::addBonds(Handle<Value> b) { Handle<Array> bonds = b.As<Array>(); // bonds is an array of v8::Object for (uint32_t i = 0; i < bonds->Length(); i += 1) { Handle<Object> bond = bonds->Get(i)->ToObject(); int from = bond->Get(NanSymbol("from"))->NumberValue(); int to = bond->Get(NanSymbol("to"))->NumberValue(); int order = bond->Get(NanSymbol("order"))->NumberValue(); InchiBond b = (order ? InchiBond(from, to, order) : InchiBond(from, to)); mol.addBond(b); } } void Molecule_wrap::addStereo(Handle<Value> s) { if (s->IsNull() || s->IsUndefined()) { return; } Handle<Array> stereos = s.As<Array>(); for (uint32_t i = 0; i < stereos->Length(); i += 1) { Handle<Object> stereo = stereos->Get(i)->ToObject(); mol.addStereo(InchiStereo::makeFromObject(stereo)); } } const InchiStereo InchiStereo::makeFromObject(Handle<Object> stereo) { InchiStereo ret; Local<Array> neighbors = stereo->Get(NanSymbol("neighbor")).As<Array>(); for (uint32_t i = 0; i < STEREO0D_NEIGHBORS; i += 1) { ret.data_.neighbor[i] = getIf<AT_NUM>(neighbors, i); } ret.data_.central_atom = getIf<AT_NUM>(stereo, "central_atom"); ret.data_.type = getIf<S_CHAR>(stereo, "type"); ret.data_.parity = getIf<S_CHAR>(stereo, "parity"); return ret; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Characters_ToString_inl_ #define _Stroika_Foundation_Characters_ToString_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <exception> #include <filesystem> #include <typeindex> #include <typeinfo> #include <wchar.h> #include "../Configuration/Concepts.h" #include "../Configuration/Enumeration.h" #include "FloatConversion.h" #include "StringBuilder.h" namespace Stroika::Foundation::Characters { /* ******************************************************************************** ********************************* ToString ************************************* ******************************************************************************** */ template <> String ToString (const exception_ptr& t); template <> String ToString (const type_info& t); template <> String ToString (const type_index& t); String ToString (const char* t); /* * From section from section 3.9.1 of http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf * There are five standard signed integer types : signed char, short int, int, * long int, and long long int. In this list, each type provides at least as much * storage as those preceding it in the list. * For each of the standard signed integer types, there exists a corresponding (but different) * standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int, * and unsigned long long int, each of which occupies the same amount of storage and has the * same alignment requirements. */ template <> String ToString (const bool& t); template <> String ToString (const signed char& t); template <> String ToString (const short int& t); template <> String ToString (const int& t); template <> String ToString (const long int& t); template <> String ToString (const long long int& t); template <> String ToString (const unsigned char& t); template <> String ToString (const unsigned short& t); template <> String ToString (const unsigned int& t); template <> String ToString (const unsigned long& t); template <> String ToString (const unsigned long long& t); template <> String ToString (const std::filesystem::path& t); namespace Private_ { STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (ToString, (x.ToString ())); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (beginenditerable, (x.begin () != x.end ())); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (pair, (x.first, x.second)); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (KeyValuePair, (x.fKey, x.fValue)); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (CountedValue, (x.fValue, x.fCount)); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (name, (x.name (), x.name ())); template <typename T> inline String ToString_ (const T& t, enable_if_t<has_ToString<T>::value>* = 0) { return t.ToString (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_beginenditerable<T>::value and not has_ToString<T>::value and not is_convertible_v<T, String>>* = 0) { StringBuilder sb; sb << L"["; bool didFirst{false}; for (auto i : t) { if (didFirst) { sb << L", "; } else { sb << L" "; } sb << ToString (i); didFirst = true; } if (didFirst) { sb << L" "; } sb << L"]"; return sb.str (); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, String>>* = 0) { constexpr size_t kMaxLen2Display_{100}; // no idea what a good value here will be or if we should provide ability to override. I suppose // users can template-specialize ToString(const String&)??? return L"'"sv + static_cast<String> (t).LimitLength (kMaxLen2Display_) + L"'"sv; } String ToString_ex_ (const exception& t); template <typename T> inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, const exception&>>* = 0) { return ToString_ex_ (t); } template <typename T> inline String ToString_ ([[maybe_unused]] const T& t, enable_if_t<is_convertible_v<T, tuple<>>>* = 0) { return L"{}"sv; } template <typename T1> String ToString_ (const tuple<T1>& t) { StringBuilder sb; sb << L"{"; sb << ToString (t); sb << L"}"; return sb.str (); } template <typename T1, typename T2> String ToString_ (const tuple<T1, T2>& t) { StringBuilder sb; sb << L"{"; sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)); sb << L"}"; return sb.str (); } template <typename T1, typename T2, typename T3> String ToString_ (const tuple<T1, T2, T3>& t) { StringBuilder sb; sb << L"{"; sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t)); sb << L"}"; return sb.str (); } template <typename T1, typename T2, typename T3, typename T4> String ToString_ (const tuple<T1, T2, T3>& t) { StringBuilder sb; sb << L"{"; sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t)) + L", " + ToString (get<3> (t)); sb << L"}"; return sb.str (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_pair<T>::value>* = 0) { StringBuilder sb; sb << L"{"; sb << ToString (t.first) << L": " << ToString (t.second); sb << L"}"; return sb.str (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_KeyValuePair<T>::value>* = 0) { StringBuilder sb; sb << L"{"; sb << ToString (t.fKey) << L": " << ToString (t.fValue); sb << L"}"; return sb.str (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_CountedValue<T>::value>* = 0) { StringBuilder sb; sb << L"{"; sb << L"'" << ToString (t.fValue) << L"': " << ToString (t.fCount); sb << L"}"; return sb.str (); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_enum_v<T>>* = 0) { // SHOULD MAYBE only do if can detect is-defined Configuration::DefaultNames<T>, but right now not easy, and // not a problem: just don't call this, or replace it with a specific specialization of ToString return Configuration::DefaultNames<T>{}.GetName (t); } template <typename T, size_t SZ> String ToString_array_ (const T (&arr)[SZ]) { StringBuilder sb; sb << L"["; for (size_t i = 0; i < SZ; ++i) { sb << L" " << ToString (arr[i]); if (i + 1 < SZ) { sb << L","; } else { sb << L" "; } } sb << L"]"; return sb.str (); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_array_v<T> and not is_convertible_v<T, String>>* = 0) { return ToString_array_ (t); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_floating_point_v<T>>* = 0) { return Float2String (t); } template <typename T> inline String ToString_ (const shared_ptr<T>& pt) { return (pt == nullptr) ? L"nullptr"sv : ToString (*pt); } template <typename T> inline String ToString_ (const optional<T>& o) { return o.has_value () ? Characters::ToString (*o) : L"[missing]"sv; } } template <> inline String ToString (const signed char& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const short int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const long int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const long long int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned char& t) { return ToString (t, std::ios_base::hex); } template <> inline String ToString (const unsigned short& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned long& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned long long& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const std::filesystem::path& t) { return ToString (t.wstring ()); // wrap in 'ToString' for surrounding quotes } template <typename T> inline String ToString (const T& t) { return Private_::ToString_ (t); } } #endif /*_Stroika_Foundation_Characters_ToString_inl_*/ <commit_msg>ToString() support for std::byte<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Characters_ToString_inl_ #define _Stroika_Foundation_Characters_ToString_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <exception> #include <filesystem> #include <typeindex> #include <typeinfo> #include <wchar.h> #include "../Configuration/Concepts.h" #include "../Configuration/Enumeration.h" #include "FloatConversion.h" #include "StringBuilder.h" namespace Stroika::Foundation::Characters { /* ******************************************************************************** ********************************* ToString ************************************* ******************************************************************************** */ template <> String ToString (const exception_ptr& t); template <> String ToString (const type_info& t); template <> String ToString (const type_index& t); String ToString (const char* t); /* * From section from section 3.9.1 of http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf * There are five standard signed integer types : signed char, short int, int, * long int, and long long int. In this list, each type provides at least as much * storage as those preceding it in the list. * For each of the standard signed integer types, there exists a corresponding (but different) * standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int, * and unsigned long long int, each of which occupies the same amount of storage and has the * same alignment requirements. */ template <> String ToString (const bool& t); template <> String ToString (const signed char& t); template <> String ToString (const short int& t); template <> String ToString (const int& t); template <> String ToString (const long int& t); template <> String ToString (const long long int& t); template <> String ToString (const unsigned char& t); template <> String ToString (const unsigned short& t); template <> String ToString (const unsigned int& t); template <> String ToString (const unsigned long& t); template <> String ToString (const unsigned long long& t); template <> String ToString (const std::filesystem::path& t); namespace Private_ { STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (ToString, (x.ToString ())); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (beginenditerable, (x.begin () != x.end ())); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (pair, (x.first, x.second)); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (KeyValuePair, (x.fKey, x.fValue)); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (CountedValue, (x.fValue, x.fCount)); STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (name, (x.name (), x.name ())); template <typename T> inline String ToString_ (const T& t, enable_if_t<has_ToString<T>::value>* = 0) { return t.ToString (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_beginenditerable<T>::value and not has_ToString<T>::value and not is_convertible_v<T, String>>* = 0) { StringBuilder sb; sb << L"["; bool didFirst{false}; for (auto i : t) { if (didFirst) { sb << L", "; } else { sb << L" "; } sb << ToString (i); didFirst = true; } if (didFirst) { sb << L" "; } sb << L"]"; return sb.str (); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, String>>* = 0) { constexpr size_t kMaxLen2Display_{100}; // no idea what a good value here will be or if we should provide ability to override. I suppose // users can template-specialize ToString(const String&)??? return L"'"sv + static_cast<String> (t).LimitLength (kMaxLen2Display_) + L"'"sv; } String ToString_ex_ (const exception& t); template <typename T> inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, const exception&>>* = 0) { return ToString_ex_ (t); } template <typename T> inline String ToString_ ([[maybe_unused]] const T& t, enable_if_t<is_convertible_v<T, tuple<>>>* = 0) { return L"{}"sv; } template <typename T1> String ToString_ (const tuple<T1>& t) { StringBuilder sb; sb << L"{"; sb << ToString (t); sb << L"}"; return sb.str (); } template <typename T1, typename T2> String ToString_ (const tuple<T1, T2>& t) { StringBuilder sb; sb << L"{"; sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)); sb << L"}"; return sb.str (); } template <typename T1, typename T2, typename T3> String ToString_ (const tuple<T1, T2, T3>& t) { StringBuilder sb; sb << L"{"; sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t)); sb << L"}"; return sb.str (); } template <typename T1, typename T2, typename T3, typename T4> String ToString_ (const tuple<T1, T2, T3>& t) { StringBuilder sb; sb << L"{"; sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t)) + L", " + ToString (get<3> (t)); sb << L"}"; return sb.str (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_pair<T>::value>* = 0) { StringBuilder sb; sb << L"{"; sb << ToString (t.first) << L": " << ToString (t.second); sb << L"}"; return sb.str (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_KeyValuePair<T>::value>* = 0) { StringBuilder sb; sb << L"{"; sb << ToString (t.fKey) << L": " << ToString (t.fValue); sb << L"}"; return sb.str (); } template <typename T> String ToString_ (const T& t, enable_if_t<has_CountedValue<T>::value>* = 0) { StringBuilder sb; sb << L"{"; sb << L"'" << ToString (t.fValue) << L"': " << ToString (t.fCount); sb << L"}"; return sb.str (); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_enum_v<T>>* = 0) { // SHOULD MAYBE only do if can detect is-defined Configuration::DefaultNames<T>, but right now not easy, and // not a problem: just don't call this, or replace it with a specific specialization of ToString return Configuration::DefaultNames<T>{}.GetName (t); } template <typename T, size_t SZ> String ToString_array_ (const T (&arr)[SZ]) { StringBuilder sb; sb << L"["; for (size_t i = 0; i < SZ; ++i) { sb << L" " << ToString (arr[i]); if (i + 1 < SZ) { sb << L","; } else { sb << L" "; } } sb << L"]"; return sb.str (); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_array_v<T> and not is_convertible_v<T, String>>* = 0) { return ToString_array_ (t); } template <typename T> inline String ToString_ (const T& t, enable_if_t<is_floating_point_v<T>>* = 0) { return Float2String (t); } template <typename T> inline String ToString_ (const shared_ptr<T>& pt) { return (pt == nullptr) ? L"nullptr"sv : ToString (*pt); } template <typename T> inline String ToString_ (const optional<T>& o) { return o.has_value () ? Characters::ToString (*o) : L"[missing]"sv; } } template <> inline String ToString (const signed char& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const short int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const long int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const long long int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned char& t) { return ToString (t, std::ios_base::hex); } template <> inline String ToString (const unsigned short& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned int& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned long& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const unsigned long long& t) { return ToString (t, std::ios_base::dec); } template <> inline String ToString (const std::byte& t) { return ToString (static_cast<unsigned char> (t), std::ios_base::hex); } template <> inline String ToString (const std::filesystem::path& t) { return ToString (t.wstring ()); // wrap in 'ToString' for surrounding quotes } template <typename T> inline String ToString (const T& t) { return Private_::ToString_ (t); } } #endif /*_Stroika_Foundation_Characters_ToString_inl_*/ <|endoftext|>
<commit_before>#include "external/petscvector/common/fem2D.h" namespace pascinference { namespace common { template<> Fem2D<PetscVector>::Fem2D(Decomposition<PetscVector> *decomposition1, Decomposition<PetscVector> *decomposition2, double fem_reduce) : Fem<PetscVector>(decomposition1, decomposition2, fem_reduce){ LOG_FUNC_BEGIN this->grid1 = (BGMGraphGrid2D<PetscVector>*)(this->decomposition1->get_graph()); this->grid2 = (BGMGraphGrid2D<PetscVector>*)(this->decomposition2->get_graph()); #ifdef USE_CUDA /* compute optimal kernel calls */ externalcontent->cuda_occupancy(); externalcontent->gridSize_reduce = (decomposition2->get_Tlocal() + externalcontent->blockSize_reduce - 1)/ externalcontent->blockSize_reduce; externalcontent->gridSize_prolongate = (decomposition2->get_Tlocal() + externalcontent->blockSize_prolongate - 1)/ externalcontent->blockSize_prolongate; #endif this->diff = 1; /* time */ this->diff_x = (grid1->get_width()-1)/(double)(grid2->get_width()-1); this->diff_y = (grid1->get_height()-1)/(double)(grid2->get_height()-1); if(this->is_reduced()){ this->bounding_box1 = new int[4]; set_value_array(4, this->bounding_box1, 0); /* initial values */ this->bounding_box2 = new int[4]; set_value_array(4, this->bounding_box2, 0); /* initial values */ compute_overlaps(); } LOG_FUNC_END } template<> void Fem2D<PetscVector>::compute_decomposition_reduced() { LOG_FUNC_BEGIN /* decomposition1 has to be set */ this->grid1 = (BGMGraphGrid2D<PetscVector>*)(this->decomposition1->get_graph()); if(this->is_reduced()){ int T_reduced = 1; int width_reduced = ceil(grid1->get_width()*this->fem_reduce); int height_reduced = ceil(grid1->get_height()*this->fem_reduce); this->grid2 = new BGMGraphGrid2D<PetscVector>(width_reduced, height_reduced); this->grid2->process_grid(); /* decompose second grid based on the decomposition of the first grid */ this->grid2->decompose(this->grid1, this->bounding_box1, this->bounding_box2); this->grid2->print(coutMaster); /* compute new decomposition */ this->decomposition2 = new Decomposition<PetscVector>(T_reduced, *(this->grid2), this->decomposition1->get_K(), this->decomposition1->get_xdim(), this->decomposition1->get_DDT_size(), this->decomposition1->get_DDR_size()); compute_overlaps(); } else { /* there is not reduction of the data, we can reuse the decomposition */ this->set_decomposition_reduced(this->decomposition1); this->grid2 = this->grid1; } #ifdef USE_CUDA /* compute optimal kernel calls */ externalcontent->cuda_occupancy(); externalcontent->gridSize_reduce = (decomposition2->get_Tlocal() + externalcontent->blockSize_reduce - 1)/ externalcontent->blockSize_reduce; externalcontent->gridSize_prolongate = (decomposition2->get_Tlocal() + externalcontent->blockSize_prolongate - 1)/ externalcontent->blockSize_prolongate; #endif this->diff = 1; /* time */ this->diff_x = (grid1->get_width()-1)/(double)(grid2->get_width()-1); this->diff_y = (grid1->get_height()-1)/(double)(grid2->get_height()-1); LOG_FUNC_END } template<> void Fem2D<PetscVector>::reduce_gamma(GeneralVector<PetscVector> *gamma1, GeneralVector<PetscVector> *gamma2) const { LOG_FUNC_BEGIN double *gammak1_arr; double *gammak2_arr; Vec gamma1_Vec = gamma1->get_vector(); Vec gamma2_Vec = gamma2->get_vector(); Vec gammak1_Vec; Vec gammak2_Vec; IS gammak1_is; IS gammak2_is; /* stuff for getting subvector for local computation */ IS gammak1_overlap_is; Vec gammak1_overlap_Vec; int *DD_permutation1 = grid1->get_DD_permutation(); int *DD_invpermutation1 = grid1->get_DD_invpermutation(); int *DD_permutation2 = grid2->get_DD_permutation(); int *DD_invpermutation2 = grid2->get_DD_invpermutation(); int Rbegin1 = this->decomposition1->get_Rbegin(); int Rbegin2 = this->decomposition2->get_Rbegin(); int width1 = grid1->get_width(); int width2 = grid2->get_width(); int width_overlap1 = bounding_box1[1] - bounding_box1[0] + 1; int height_overlap1 = bounding_box1[3] - bounding_box1[2] + 1; for(int k=0;k<this->decomposition2->get_K();k++){ /* get gammak */ this->decomposition1->createIS_gammaK(&gammak1_is, k); this->decomposition2->createIS_gammaK(&gammak2_is, k); TRYCXX( VecGetSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecGetSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); /* get local necessary part for local computation */ TRYCXX( ISCreateGeneral(PETSC_COMM_SELF,overlap1_idx_size,overlap1_idx,PETSC_USE_POINTER,&gammak1_overlap_is) ); TRYCXX( VecGetSubVector(gammak1_Vec, gammak1_overlap_is, &gammak1_overlap_Vec) ); #ifndef USE_CUDA /* sequential version */ TRYCXX( VecGetArray(gammak1_overlap_Vec,&gammak1_arr) ); TRYCXX( VecGetArray(gammak2_Vec,&gammak2_arr) ); //TODO: OpenMP? for(int r2=0; r2 < this->decomposition2->get_Rlocal(); r2++){ int id2 = DD_permutation2[Rbegin2 + r2]; int id_y2 = floor(id2/(double)width2); int id_x2 = id2 - id_y2*width2; /* coordinates in overlap */ double center_x1 = (id_x2)*this->diff_x - bounding_box1[0]; double left_x1 = (id_x2-1)*this->diff_x - bounding_box1[0]; double right_x1 = (id_x2+1)*this->diff_x - bounding_box1[0]; double center_y1 = (id_y2)*this->diff_y - bounding_box1[2]; double left_y1 = (id_y2-1)*this->diff_y - bounding_box1[2]; double right_y1 = (id_y2+1)*this->diff_y - bounding_box1[2]; double mysum = 0.0; int counter = 0; for(int x1 = floor(left_x1); x1 < right_x1; x1++){ for(int y1 = floor(left_y1); y1 < right_y1; y1++){ if(x1 >= 0 && x1 < width_overlap1 && y1 >= 0 && y1 < height_overlap1){ mysum += gammak1_arr[y1*width_overlap1 + x1]; counter += 1; } } } gammak2_arr[r2] = mysum;// /(double)counter; // coutAll << "r2 = " << r2 << ", counter = " << counter << ", mysum = " << mysum << std::endl; } // coutAll.synchronize(); TRYCXX( VecRestoreArray(gammak1_overlap_Vec,&gammak1_arr) ); TRYCXX( VecRestoreArray(gammak2_Vec,&gammak2_arr) ); #else /* cuda version */ externalcontent->cuda_femhat_reduce_data(gammak1_overlap_Vec, gammak2_Vec, this->decomposition1->get_T(), this->decomposition2->get_T(), this->decomposition1->get_Tbegin(), this->decomposition2->get_Tbegin(), this->decomposition1->get_Tlocal(), this->decomposition2->get_Tlocal(), left_t1_idx, left_t2_idx, this->diff); #endif /* restore local necessary part for local computation */ TRYCXX( VecRestoreSubVector(gammak1_Vec, gammak1_overlap_is, &gammak1_overlap_Vec) ); TRYCXX( ISDestroy(&gammak1_overlap_is) ); TRYCXX( VecRestoreSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecRestoreSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); TRYCXX( ISDestroy(&gammak1_is) ); TRYCXX( ISDestroy(&gammak2_is) ); } LOG_FUNC_END } template<> void Fem2D<PetscVector>::prolongate_gamma(GeneralVector<PetscVector> *gamma2, GeneralVector<PetscVector> *gamma1) const { LOG_FUNC_BEGIN double *gammak1_arr; double *gammak2_arr; Vec gamma1_Vec = gamma1->get_vector(); Vec gamma2_Vec = gamma2->get_vector(); Vec gammak1_Vec; Vec gammak2_Vec; IS gammak1_is; IS gammak2_is; /* stuff for getting subvector for local computation */ IS gammak2_overlap_is; Vec gammak2_overlap_Vec; int *DD_permutation1 = grid1->get_DD_permutation(); int *DD_invpermutation1 = grid1->get_DD_invpermutation(); int *DD_permutation2 = grid2->get_DD_permutation(); int *DD_invpermutation2 = grid2->get_DD_invpermutation(); int Rbegin1 = this->decomposition1->get_Rbegin(); int Rbegin2 = this->decomposition2->get_Rbegin(); int width1 = grid1->get_width(); int height1 = grid1->get_height(); int width2 = grid2->get_width(); int height2 = grid2->get_height(); int width_overlap2 = bounding_box2[1] - bounding_box2[0] + 1; int height_overlap2 = bounding_box2[3] - bounding_box2[2] + 1; for(int k=0;k<this->decomposition1->get_K();k++){ /* get gammak */ this->decomposition1->createIS_gammaK(&gammak1_is, k); this->decomposition2->createIS_gammaK(&gammak2_is, k); TRYCXX( VecGetSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecGetSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); /* get local necessary part for local computation */ TRYCXX( ISCreateGeneral(PETSC_COMM_SELF,overlap2_idx_size,overlap2_idx,PETSC_USE_POINTER,&gammak2_overlap_is) ); TRYCXX( VecGetSubVector(gammak2_Vec, gammak2_overlap_is, &gammak2_overlap_Vec) ); #ifndef USE_CUDA /* sequential version */ TRYCXX( VecGetArray(gammak1_Vec,&gammak1_arr) ); TRYCXX( VecGetArray(gammak2_overlap_Vec,&gammak2_arr) ); //TODO: OpenMP? for(int r1=0; r1 < this->decomposition1->get_Rlocal(); r1++){ int id1 = DD_invpermutation1[Rbegin1 + r1]; int id_y1 = floor(id1/(double)width1); int id_x1 = id1 - id_y1*width1; /* coordinates in overlap */ int center_x2 = floor((id_x1)/this->diff_x) - bounding_box2[0]; int center_y2 = floor((id_y1)/this->diff_y) - bounding_box2[2]; // gammak1_arr[r1] = GlobalManager.get_rank()/(double)GlobalManager.get_size(); // gammak1_arr[r1] = id1/((double)(width1*height1)); gammak1_arr[r1] = gammak2_arr[center_y2*width_overlap2 + center_x2]; // coutAll << "r1 = " << r1 << ", value = " << gammak2_arr[center_y2*width_overlap2 + center_x2] << std::endl; } // coutAll.synchronize(); TRYCXX( VecRestoreArray(gammak1_Vec,&gammak1_arr) ); TRYCXX( VecRestoreArray(gammak2_overlap_Vec,&gammak2_arr) ); #else /* cuda version */ externalcontent->cuda_femhat_reduce_data(gammak1_overlap_Vec, gammak2_Vec, this->decomposition1->get_T(), this->decomposition2->get_T(), this->decomposition1->get_Tbegin(), this->decomposition2->get_Tbegin(), this->decomposition1->get_Tlocal(), this->decomposition2->get_Tlocal(), left_t1_idx, left_t2_idx, this->diff); #endif /* restore local necessary part for local computation */ TRYCXX( VecRestoreSubVector(gammak2_Vec, gammak2_overlap_is, &gammak2_overlap_Vec) ); TRYCXX( ISDestroy(&gammak2_overlap_is) ); TRYCXX( VecRestoreSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecRestoreSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); TRYCXX( ISDestroy(&gammak1_is) ); TRYCXX( ISDestroy(&gammak2_is) ); } TRYCXX( VecRestoreArray(gamma1_Vec,&gammak1_arr) ); TRYCXX( VecRestoreArray(gamma2_Vec,&gammak2_arr) ); LOG_FUNC_END } } } /* end of namespace */ <commit_msg>working on gpu<commit_after>#include "external/petscvector/common/fem2D.h" namespace pascinference { namespace common { template<> Fem2D<PetscVector>::Fem2D(Decomposition<PetscVector> *decomposition1, Decomposition<PetscVector> *decomposition2, double fem_reduce) : Fem<PetscVector>(decomposition1, decomposition2, fem_reduce){ LOG_FUNC_BEGIN this->grid1 = (BGMGraphGrid2D<PetscVector>*)(this->decomposition1->get_graph()); this->grid2 = (BGMGraphGrid2D<PetscVector>*)(this->decomposition2->get_graph()); #ifdef USE_CUDA /* compute optimal kernel calls */ externalcontent->cuda_occupancy(); externalcontent->gridSize_reduce = (decomposition2->get_Tlocal() + externalcontent->blockSize_reduce - 1)/ externalcontent->blockSize_reduce; externalcontent->gridSize_prolongate = (decomposition2->get_Tlocal() + externalcontent->blockSize_prolongate - 1)/ externalcontent->blockSize_prolongate; #endif this->diff = 1; /* time */ this->diff_x = (grid1->get_width()-1)/(double)(grid2->get_width()-1); this->diff_y = (grid1->get_height()-1)/(double)(grid2->get_height()-1); if(this->is_reduced()){ this->bounding_box1 = new int[4]; set_value_array(4, this->bounding_box1, 0); /* initial values */ this->bounding_box2 = new int[4]; set_value_array(4, this->bounding_box2, 0); /* initial values */ compute_overlaps(); } LOG_FUNC_END } template<> void Fem2D<PetscVector>::compute_decomposition_reduced() { LOG_FUNC_BEGIN /* decomposition1 has to be set */ this->grid1 = (BGMGraphGrid2D<PetscVector>*)(this->decomposition1->get_graph()); if(this->is_reduced()){ int T_reduced = 1; int width_reduced = ceil(grid1->get_width()*this->fem_reduce); int height_reduced = ceil(grid1->get_height()*this->fem_reduce); this->grid2 = new BGMGraphGrid2D<PetscVector>(width_reduced, height_reduced); this->grid2->process_grid(); /* decompose second grid based on the decomposition of the first grid */ this->grid2->decompose(this->grid1, this->bounding_box1, this->bounding_box2); this->grid2->print(coutMaster); /* compute new decomposition */ this->decomposition2 = new Decomposition<PetscVector>(T_reduced, *(this->grid2), this->decomposition1->get_K(), this->decomposition1->get_xdim(), this->decomposition1->get_DDT_size(), this->decomposition1->get_DDR_size()); compute_overlaps(); } else { /* there is not reduction of the data, we can reuse the decomposition */ this->set_decomposition_reduced(this->decomposition1); this->grid2 = this->grid1; } #ifdef USE_CUDA /* compute optimal kernel calls */ externalcontent->cuda_occupancy(); externalcontent->gridSize_reduce = (decomposition2->get_Tlocal() + externalcontent->blockSize_reduce - 1)/ externalcontent->blockSize_reduce; externalcontent->gridSize_prolongate = (decomposition2->get_Tlocal() + externalcontent->blockSize_prolongate - 1)/ externalcontent->blockSize_prolongate; #endif this->diff = 1; /* time */ this->diff_x = (grid1->get_width()-1)/(double)(grid2->get_width()-1); this->diff_y = (grid1->get_height()-1)/(double)(grid2->get_height()-1); LOG_FUNC_END } template<> void Fem2D<PetscVector>::reduce_gamma(GeneralVector<PetscVector> *gamma1, GeneralVector<PetscVector> *gamma2) const { LOG_FUNC_BEGIN double *gammak1_arr; double *gammak2_arr; Vec gamma1_Vec = gamma1->get_vector(); Vec gamma2_Vec = gamma2->get_vector(); Vec gammak1_Vec; Vec gammak2_Vec; IS gammak1_is; IS gammak2_is; /* stuff for getting subvector for local computation */ IS gammak1_overlap_is; Vec gammak1_overlap_Vec; int *DD_permutation1 = grid1->get_DD_permutation(); int *DD_invpermutation1 = grid1->get_DD_invpermutation(); int *DD_permutation2 = grid2->get_DD_permutation(); int *DD_invpermutation2 = grid2->get_DD_invpermutation(); int Rbegin1 = this->decomposition1->get_Rbegin(); int Rbegin2 = this->decomposition2->get_Rbegin(); int width1 = grid1->get_width(); int width2 = grid2->get_width(); int width_overlap1 = bounding_box1[1] - bounding_box1[0] + 1; int height_overlap1 = bounding_box1[3] - bounding_box1[2] + 1; for(int k=0;k<this->decomposition2->get_K();k++){ /* get gammak */ this->decomposition1->createIS_gammaK(&gammak1_is, k); this->decomposition2->createIS_gammaK(&gammak2_is, k); TRYCXX( VecGetSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecGetSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); /* get local necessary part for local computation */ TRYCXX( ISCreateGeneral(PETSC_COMM_SELF,overlap1_idx_size,overlap1_idx,PETSC_USE_POINTER,&gammak1_overlap_is) ); TRYCXX( VecGetSubVector(gammak1_Vec, gammak1_overlap_is, &gammak1_overlap_Vec) ); #ifndef USE_CUDA /* sequential version */ TRYCXX( VecGetArray(gammak1_overlap_Vec,&gammak1_arr) ); TRYCXX( VecGetArray(gammak2_Vec,&gammak2_arr) ); //TODO: OpenMP? for(int r2=0; r2 < this->decomposition2->get_Rlocal(); r2++){ int id2 = DD_permutation2[Rbegin2 + r2]; int id_y2 = floor(id2/(double)width2); int id_x2 = id2 - id_y2*width2; /* coordinates in overlap */ double center_x1 = (id_x2)*this->diff_x - bounding_box1[0]; double left_x1 = (id_x2-1)*this->diff_x - bounding_box1[0]; double right_x1 = (id_x2+1)*this->diff_x - bounding_box1[0]; double center_y1 = (id_y2)*this->diff_y - bounding_box1[2]; double left_y1 = (id_y2-1)*this->diff_y - bounding_box1[2]; double right_y1 = (id_y2+1)*this->diff_y - bounding_box1[2]; double mysum = 0.0; int counter = 0; for(int x1 = floor(left_x1); x1 < right_x1; x1++){ for(int y1 = floor(left_y1); y1 < right_y1; y1++){ if(x1 >= 0 && x1 < width_overlap1 && y1 >= 0 && y1 < height_overlap1){ mysum += gammak1_arr[y1*width_overlap1 + x1]; counter += 1; } } } gammak2_arr[r2] = mysum;// /(double)counter; // coutAll << "r2 = " << r2 << ", counter = " << counter << ", mysum = " << mysum << std::endl; } // coutAll.synchronize(); TRYCXX( VecRestoreArray(gammak1_overlap_Vec,&gammak1_arr) ); TRYCXX( VecRestoreArray(gammak2_Vec,&gammak2_arr) ); #else /* cuda version */ externalcontent->cuda_reduce_data(gammak1_overlap_Vec, gammak2_Vec, this->decomposition1->get_T(), this->decomposition2->get_T(), this->decomposition1->get_Tbegin(), this->decomposition2->get_Tbegin(), this->decomposition1->get_Tlocal(), this->decomposition2->get_Tlocal(), left_t1_idx, left_t2_idx, this->diff); #endif /* restore local necessary part for local computation */ TRYCXX( VecRestoreSubVector(gammak1_Vec, gammak1_overlap_is, &gammak1_overlap_Vec) ); TRYCXX( ISDestroy(&gammak1_overlap_is) ); TRYCXX( VecRestoreSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecRestoreSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); TRYCXX( ISDestroy(&gammak1_is) ); TRYCXX( ISDestroy(&gammak2_is) ); } LOG_FUNC_END } template<> void Fem2D<PetscVector>::prolongate_gamma(GeneralVector<PetscVector> *gamma2, GeneralVector<PetscVector> *gamma1) const { LOG_FUNC_BEGIN double *gammak1_arr; double *gammak2_arr; Vec gamma1_Vec = gamma1->get_vector(); Vec gamma2_Vec = gamma2->get_vector(); Vec gammak1_Vec; Vec gammak2_Vec; IS gammak1_is; IS gammak2_is; /* stuff for getting subvector for local computation */ IS gammak2_overlap_is; Vec gammak2_overlap_Vec; int *DD_permutation1 = grid1->get_DD_permutation(); int *DD_invpermutation1 = grid1->get_DD_invpermutation(); int *DD_permutation2 = grid2->get_DD_permutation(); int *DD_invpermutation2 = grid2->get_DD_invpermutation(); int Rbegin1 = this->decomposition1->get_Rbegin(); int Rbegin2 = this->decomposition2->get_Rbegin(); int width1 = grid1->get_width(); int height1 = grid1->get_height(); int width2 = grid2->get_width(); int height2 = grid2->get_height(); int width_overlap2 = bounding_box2[1] - bounding_box2[0] + 1; int height_overlap2 = bounding_box2[3] - bounding_box2[2] + 1; for(int k=0;k<this->decomposition1->get_K();k++){ /* get gammak */ this->decomposition1->createIS_gammaK(&gammak1_is, k); this->decomposition2->createIS_gammaK(&gammak2_is, k); TRYCXX( VecGetSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecGetSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); /* get local necessary part for local computation */ TRYCXX( ISCreateGeneral(PETSC_COMM_SELF,overlap2_idx_size,overlap2_idx,PETSC_USE_POINTER,&gammak2_overlap_is) ); TRYCXX( VecGetSubVector(gammak2_Vec, gammak2_overlap_is, &gammak2_overlap_Vec) ); #ifndef USE_CUDA /* sequential version */ TRYCXX( VecGetArray(gammak1_Vec,&gammak1_arr) ); TRYCXX( VecGetArray(gammak2_overlap_Vec,&gammak2_arr) ); //TODO: OpenMP? for(int r1=0; r1 < this->decomposition1->get_Rlocal(); r1++){ int id1 = DD_invpermutation1[Rbegin1 + r1]; int id_y1 = floor(id1/(double)width1); int id_x1 = id1 - id_y1*width1; /* coordinates in overlap */ int center_x2 = floor((id_x1)/this->diff_x) - bounding_box2[0]; int center_y2 = floor((id_y1)/this->diff_y) - bounding_box2[2]; // gammak1_arr[r1] = GlobalManager.get_rank()/(double)GlobalManager.get_size(); // gammak1_arr[r1] = id1/((double)(width1*height1)); gammak1_arr[r1] = gammak2_arr[center_y2*width_overlap2 + center_x2]; // coutAll << "r1 = " << r1 << ", value = " << gammak2_arr[center_y2*width_overlap2 + center_x2] << std::endl; } // coutAll.synchronize(); TRYCXX( VecRestoreArray(gammak1_Vec,&gammak1_arr) ); TRYCXX( VecRestoreArray(gammak2_overlap_Vec,&gammak2_arr) ); #else /* cuda version */ externalcontent->cuda_reduce_data(gammak1_overlap_Vec, gammak2_Vec, this->decomposition1->get_T(), this->decomposition2->get_T(), this->decomposition1->get_Tbegin(), this->decomposition2->get_Tbegin(), this->decomposition1->get_Tlocal(), this->decomposition2->get_Tlocal(), left_t1_idx, left_t2_idx, this->diff); #endif /* restore local necessary part for local computation */ TRYCXX( VecRestoreSubVector(gammak2_Vec, gammak2_overlap_is, &gammak2_overlap_Vec) ); TRYCXX( ISDestroy(&gammak2_overlap_is) ); TRYCXX( VecRestoreSubVector(gamma1_Vec, gammak1_is, &gammak1_Vec) ); TRYCXX( VecRestoreSubVector(gamma2_Vec, gammak2_is, &gammak2_Vec) ); TRYCXX( ISDestroy(&gammak1_is) ); TRYCXX( ISDestroy(&gammak2_is) ); } TRYCXX( VecRestoreArray(gamma1_Vec,&gammak1_arr) ); TRYCXX( VecRestoreArray(gamma2_Vec,&gammak2_arr) ); LOG_FUNC_END } } } /* end of namespace */ <|endoftext|>
<commit_before>#include <iostream> #include "DNest4/code/DNest4.h" #include "Rosenbrock.h" using namespace DNest4; int main(int argc, char** argv) { start<Rosenbrock>(argc, argv); return 0; } <commit_msg>Use randh2<commit_after>#include <iostream> #include "DNest4/code/DNest4.h" #include "Rosenbrock.h" using namespace DNest4; int main(int argc, char** argv) { RNG::randh_is_randh2 = true; start<Rosenbrock>(argc, argv); return 0; } <|endoftext|>
<commit_before>// Test that the timestamp is not included in the produced pch file with // -fno-pch-timestamp. // Check timestamp is included by default. // RUN: %clang_cc1 -x c++-header -emit-pch -o %t %S/Inputs/pragma-once2-pch.h // RUN: touch -m -a -t 201008011501 %S/Inputs/pragma-once2.h // RUN: not %clang_cc1 -include-pch %t %s 2>&1 | FileCheck -check-prefix=CHECK-TIMESTAMP %s // Check bitcode output as well. // RUN: llvm-bcanalyzer -dump %t | FileCheck -check-prefix=CHECK-BITCODE-TIMESTAMP-ON %s // Check timestamp inclusion is disabled by -fno-pch-timestamp. // RUN: %clang_cc1 -x c++-header -emit-pch -o %t %S/Inputs/pragma-once2-pch.h -fno-pch-timestamp // RUN: touch -m -a -t 201008011502 %S/Inputs/pragma-once2.h // RUN: %clang_cc1 -include-pch %t %s 2>&1 // Check bitcode output as well. // RUN: llvm-bcanalyzer -dump %t | FileCheck -check-prefix=CHECK-BITCODE-TIMESTAMP-OFF %s #include "Inputs/pragma-once2.h" void g() { f(); } // CHECK-BITCODE-TIMESTAMP-ON: <INPUT_FILE abbrevid={{.*}} op0={{.*}} op1={{.*}} op2={{[^0]}} // CHECK-BITCODE-TIMESTAMP-OFF: <INPUT_FILE abbrevid={{.*}} op0={{.*}} op1={{.*}} op2={{[0]}} // CHECK-TIMESTAMP: fatal error: file {{.*}} has been modified since the precompiled header {{.*}} was built <commit_msg>The test added in r275267 does not work on read-only checkouts because of the use of touch -m -t. Following Tom Rybka suggestion, the test files are now copied to a temporary directory first.<commit_after>// Test that the timestamp is not included in the produced pch file with // -fno-pch-timestamp. // Copying files allow for read-only checkouts to run this test. // RUN: cp %S/Inputs/pragma-once2-pch.h %T // RUN: cp %S/Inputs/pragma-once2.h %T // RUN: cp %s %t1.cpp // Check timestamp is included by default. // RUN: %clang_cc1 -x c++-header -emit-pch -o %t %T/pragma-once2-pch.h // RUN: touch -m -a -t 201008011501 %T/pragma-once2.h // RUN: not %clang_cc1 -include-pch %t %t1.cpp 2>&1 | FileCheck -check-prefix=CHECK-TIMESTAMP %s // Check bitcode output as well. // RUN: llvm-bcanalyzer -dump %t | FileCheck -check-prefix=CHECK-BITCODE-TIMESTAMP-ON %s // Check timestamp inclusion is disabled by -fno-pch-timestamp. // RUN: %clang_cc1 -x c++-header -emit-pch -o %t %T/pragma-once2-pch.h -fno-pch-timestamp // RUN: touch -m -a -t 201008011502 %T/pragma-once2.h // RUN: %clang_cc1 -include-pch %t %t1.cpp 2>&1 // Check bitcode output as well. // RUN: llvm-bcanalyzer -dump %t | FileCheck -check-prefix=CHECK-BITCODE-TIMESTAMP-OFF %s #include "pragma-once2.h" void g() { f(); } // CHECK-BITCODE-TIMESTAMP-ON: <INPUT_FILE abbrevid={{.*}} op0={{.*}} op1={{.*}} op2={{[^0]}} // CHECK-BITCODE-TIMESTAMP-OFF: <INPUT_FILE abbrevid={{.*}} op0={{.*}} op1={{.*}} op2={{[0]}} // CHECK-TIMESTAMP: fatal error: file {{.*}} has been modified since the precompiled header {{.*}} was built <|endoftext|>
<commit_before>#include <crow.h> #include <json.h> #include <mustache.h> #include <boost/program_options.hpp> #include <sstream> #include <iostream> #include <fstream> #include <map> #include <string> #include <thread> #include <random> #include <list> #include <chrono> using namespace boost::program_options; using std::chrono::system_clock; struct transaction { std::string from; std::string to; int money; }; std::map<std::string, std::string> name_pass_map; std::map<std::string, int> name_money_map; std::map<std::string, std::string> name_token_map; std::map<std::string, int> name_seed_map; std::map<system_clock::time_point, transaction> transaction_map; std::mutex money_mutex; crow::json::wvalue json_from_transaction(const transaction& t) { crow::json::wvalue jv; jv["from"] = t.from; jv["to"] = t.to; jv["money"] = t.money; return jv; } std::string file_to_string(const std::string& filename) { std::ifstream ifs(filename.c_str()); if (!ifs.is_open()) throw std::runtime_error("could not open JSON file : " + filename); return std::string( (std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); } std::string token_from_header(const crow::ci_map& header) { std::stringstream ss; auto it = header.find("User-Agent"); ss << it->second; return ss.str(); } void fill_user_pass(const crow::json::rvalue& val) { for (int i = 0; i < val["users"].size(); ++i) name_pass_map.insert( std::make_pair( val["users"][i]["name"].s(), val["users"][i]["pass"].s())); } void fill_user_money(const crow::json::rvalue& val) { for (int i = 0; i < val["users"].size(); ++i) name_money_map.insert( std::make_pair( val["users"][i]["name"].s(), (int)val["users"][i]["money"].d())); } bool authenticate(const std::string& user, const std::string& token, int seed) { auto seed_it = name_seed_map.find(user); auto token_it = name_token_map.find(user); if (seed_it == name_seed_map.end() || token_it == name_token_map.end()) return false; if (seed_it->second != seed || token_it->second != token) return false; return true; } int main(int ac, char** av) { unsigned short port = 8080; std::string path = "./"; std::string data_file = "data.JSON"; std::default_random_engine generator; std::uniform_int_distribution<int> distribution(1, 65535); auto seed_value = std::bind(distribution, generator); try { options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("input-path,i", value<std::string>(), "input path for files") ("data-file,d", value<std::string>(), "JSON data file") ("port,p", value<unsigned short>(), "listening port") ; variables_map vm; store(command_line_parser(ac, av).options(desc).run(), vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } if (vm.count("input-path")) { path = vm["input-path"].as<std::string>(); } if (vm.count("data-file")) { data_file = vm["data-file"].as<std::string>(); } if (vm.count("port")) { port = vm["port"].as<unsigned short>(); } data_file = path + data_file; crow::SimpleApp app; crow::mustache::set_base("./"); std::string data_str = file_to_string("./data.JSON"); crow::json::rvalue val = crow::json::load(data_str); fill_user_pass(val); fill_user_money(val); CROW_ROUTE(app, "/") ([]{ crow::mustache::context ctx; return crow::mustache::load("index.html").render(); }); CROW_ROUTE(app, "/index.html") ([]{ crow::mustache::context ctx; return crow::mustache::load("index.html").render(); }); CROW_ROUTE(app, "/do_stuff.js") ([]{ crow::mustache::context ctx; return crow::mustache::load("do_stuff.js").render(); }); CROW_ROUTE(app, "/LARPstyle.css") ([]{ crow::mustache::context ctx; return crow::mustache::load("LARPstyle.css").render(); }); CROW_ROUTE(app, "/api/list/") ([]{ crow::json::wvalue x; int i = 0; for (auto it : name_money_map) { x["message"][i]["name"] = it.first; // x["message"][i]["money"] = it.second; std::string status = "offline"; if (name_token_map.find(it.first) != name_token_map.end()) status = "online"; x["message"][i]["status"] = status; i++; } return x; }); CROW_ROUTE(app, "/api/history/") ([](const crow::request& req){ std::string user_name = ""; int seed = 0; std::string token = token_from_header(req.headers); if (req.url_params.get("user")) { user_name = req.url_params.get("user"); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("seed")) { seed = atoi(req.url_params.get("seed")); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (!authenticate(user_name, token, seed)) { CROW_LOG_DEBUG << "failed authentication?"; return crow::response(500, "HACKER!!!!"); } crow::json::wvalue jv; money_mutex.lock(); auto temp_map = transaction_map; money_mutex.unlock(); for (auto it : temp_map) { if ((user_name != it.second.from) && (user_name != it.second.to)) continue; int i = 0; std::time_t tt; tt = system_clock::to_time_t(it.first); jv[i]["at"] = ctime(&tt); jv[i]["from"] = it.second.from; jv[i]["to"] = it.second.to; jv[i]["money"] = it.second.money; i++; } return crow::response(jv); }); CROW_ROUTE(app, "/api/login/") ([&](const crow::request& req){ std::string user_name = ""; std::string user_pass = ""; if (req.url_params.get("user")) { user_name = req.url_params.get("user"); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("pass")) { user_pass = req.url_params.get("pass"); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } std::string token = token_from_header(req.headers); auto name_pass_it = name_pass_map.find(user_name); if (name_pass_it == name_pass_map.end()) { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (name_pass_it->second != user_pass) return crow::response(500, "login failed!"); // register new token int seed = seed_value(); name_seed_map.insert(std::make_pair(user_name, seed)); name_token_map.insert(std::make_pair(user_name, token)); auto money_it = name_money_map.find(user_name); crow::json::wvalue jv; jv["money"] = money_it->second; jv["seed"] = seed; return crow::response(jv); }); CROW_ROUTE(app, "/api/send/") ([](const crow::request& req){ std::string from_name = ""; std::string to_name = ""; int value = 0; int seed = 0; if (req.url_params.get("from")) { from_name = req.url_params.get("from"); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("to")) { to_name = req.url_params.get("to"); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("value")) { value = atoi(req.url_params.get("value")); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("seed")) { seed = atoi(req.url_params.get("seed")); } else { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } // check user has right (own the account) std::string token = token_from_header(req.headers); auto from_it = name_money_map.find(from_name); auto to_it = name_money_map.find(to_name); if (!authenticate(from_name, token, seed)) { CROW_LOG_DEBUG << "failed authentication?"; return crow::response(500, "HACKER!!!!"); } if (from_it == name_money_map.end()) { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (to_it == name_money_map.end()) { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (value < 0) { CROW_LOG_DEBUG << "Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (from_it == to_it) return crow::response(400, "'from' and 'to' are the same"); if (value > from_it->second) return crow::response(400, "'from' doesn't have enough money"); money_mutex.lock(); from_it->second -= value; to_it->second += value; transaction t; t.from = from_it->first; t.to = to_it->first; t.money = value; transaction_map.insert( std::make_pair( system_clock::now(), t)); money_mutex.unlock(); return crow::response(json_from_transaction(t)); }); app.port(port).multithreaded().run(); } catch (std::exception& ex) { std::cerr << "exception (std) : " << ex.what() << std::endl; return -1; } return 0; } <commit_msg>more log<commit_after>#include <crow.h> #include <json.h> #include <mustache.h> #include <boost/program_options.hpp> #include <sstream> #include <iostream> #include <fstream> #include <map> #include <string> #include <thread> #include <random> #include <list> #include <chrono> using namespace boost::program_options; using std::chrono::system_clock; struct transaction { std::string from; std::string to; int money; }; std::map<std::string, std::string> name_pass_map; std::map<std::string, int> name_money_map; std::map<std::string, std::string> name_token_map; std::map<std::string, int> name_seed_map; std::map<system_clock::time_point, transaction> transaction_map; std::mutex money_mutex; crow::json::wvalue json_from_transaction(const transaction& t) { crow::json::wvalue jv; jv["from"] = t.from; jv["to"] = t.to; jv["money"] = t.money; return jv; } std::string file_to_string(const std::string& filename) { std::ifstream ifs(filename.c_str()); if (!ifs.is_open()) throw std::runtime_error("could not open JSON file : " + filename); return std::string( (std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); } std::string token_from_header(const crow::ci_map& header) { std::stringstream ss; auto it = header.find("User-Agent"); ss << it->second; return ss.str(); } void fill_user_pass(const crow::json::rvalue& val) { for (int i = 0; i < val["users"].size(); ++i) name_pass_map.insert( std::make_pair( val["users"][i]["name"].s(), val["users"][i]["pass"].s())); } void fill_user_money(const crow::json::rvalue& val) { for (int i = 0; i < val["users"].size(); ++i) name_money_map.insert( std::make_pair( val["users"][i]["name"].s(), (int)val["users"][i]["money"].d())); } bool authenticate(const std::string& user, const std::string& token, int seed) { auto seed_it = name_seed_map.find(user); auto token_it = name_token_map.find(user); if (seed_it == name_seed_map.end() || token_it == name_token_map.end()) return false; if (seed_it->second != seed || token_it->second != token) return false; return true; } int main(int ac, char** av) { unsigned short port = 8080; std::string path = "./"; std::string data_file = "data.JSON"; std::default_random_engine generator; std::uniform_int_distribution<int> distribution(1, 65535); auto seed_value = std::bind(distribution, generator); try { options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("input-path,i", value<std::string>(), "input path for files") ("data-file,d", value<std::string>(), "JSON data file") ("port,p", value<unsigned short>(), "listening port") ; variables_map vm; store(command_line_parser(ac, av).options(desc).run(), vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } if (vm.count("input-path")) { path = vm["input-path"].as<std::string>(); } if (vm.count("data-file")) { data_file = vm["data-file"].as<std::string>(); } if (vm.count("port")) { port = vm["port"].as<unsigned short>(); } data_file = path + data_file; crow::SimpleApp app; crow::mustache::set_base("./"); std::string data_str = file_to_string("./data.JSON"); crow::json::rvalue val = crow::json::load(data_str); fill_user_pass(val); fill_user_money(val); CROW_ROUTE(app, "/") ([]{ crow::mustache::context ctx; return crow::mustache::load("index.html").render(); }); CROW_ROUTE(app, "/index.html") ([]{ crow::mustache::context ctx; return crow::mustache::load("index.html").render(); }); CROW_ROUTE(app, "/do_stuff.js") ([]{ crow::mustache::context ctx; return crow::mustache::load("do_stuff.js").render(); }); CROW_ROUTE(app, "/LARPstyle.css") ([]{ crow::mustache::context ctx; return crow::mustache::load("LARPstyle.css").render(); }); CROW_ROUTE(app, "/api/list/") ([]{ crow::json::wvalue x; int i = 0; for (auto it : name_money_map) { x["message"][i]["name"] = it.first; // x["message"][i]["money"] = it.second; std::string status = "offline"; if (name_token_map.find(it.first) != name_token_map.end()) status = "online"; x["message"][i]["status"] = status; i++; } return x; }); CROW_ROUTE(app, "/api/history/") ([](const crow::request& req){ std::string user_name = ""; int seed = 0; std::string token = token_from_header(req.headers); if (req.url_params.get("user")) { user_name = req.url_params.get("user"); } else { CROW_LOG_DEBUG << "(0) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("seed")) { seed = atoi(req.url_params.get("seed")); } else { CROW_LOG_DEBUG << "(1) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (!authenticate(user_name, token, seed)) { CROW_LOG_DEBUG << "failed authentication?"; return crow::response(500, "HACKER!!!!"); } crow::json::wvalue jv; money_mutex.lock(); auto temp_map = transaction_map; money_mutex.unlock(); for (auto it : temp_map) { if ((user_name != it.second.from) && (user_name != it.second.to)) continue; int i = 0; std::time_t tt; tt = system_clock::to_time_t(it.first); jv[i]["at"] = ctime(&tt); jv[i]["from"] = it.second.from; jv[i]["to"] = it.second.to; jv[i]["money"] = it.second.money; i++; } return crow::response(jv); }); CROW_ROUTE(app, "/api/login/") ([&](const crow::request& req){ std::string user_name = ""; std::string user_pass = ""; if (req.url_params.get("user")) { user_name = req.url_params.get("user"); } else { CROW_LOG_DEBUG << "(0) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("pass")) { user_pass = req.url_params.get("pass"); } else { CROW_LOG_DEBUG << "(1) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } std::string token = token_from_header(req.headers); auto name_pass_it = name_pass_map.find(user_name); if (name_pass_it == name_pass_map.end()) { CROW_LOG_DEBUG << "(2) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (name_pass_it->second != user_pass) return crow::response(500, "login failed!"); // register new token int seed = seed_value(); name_seed_map.insert(std::make_pair(user_name, seed)); name_token_map.insert(std::make_pair(user_name, token)); auto money_it = name_money_map.find(user_name); crow::json::wvalue jv; jv["money"] = money_it->second; jv["seed"] = seed; return crow::response(jv); }); CROW_ROUTE(app, "/api/send/") ([](const crow::request& req){ std::string from_name = ""; std::string to_name = ""; int value = 0; int seed = 0; if (req.url_params.get("from")) { from_name = req.url_params.get("from"); } else { CROW_LOG_DEBUG << "(0) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("to")) { to_name = req.url_params.get("to"); } else { CROW_LOG_DEBUG << "(1) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("value")) { value = atoi(req.url_params.get("value")); } else { CROW_LOG_DEBUG << "(2) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (req.url_params.get("seed")) { seed = atoi(req.url_params.get("seed")); } else { CROW_LOG_DEBUG << "(3) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } // check user has right (own the account) std::string token = token_from_header(req.headers); auto from_it = name_money_map.find(from_name); auto to_it = name_money_map.find(to_name); if (!authenticate(from_name, token, seed)) { CROW_LOG_DEBUG << "failed authentication?"; return crow::response(500, "HACKER!!!!"); } if (from_it == name_money_map.end()) { CROW_LOG_DEBUG << "(4) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (to_it == name_money_map.end()) { CROW_LOG_DEBUG << "(5) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (value < 0) { CROW_LOG_DEBUG << "(6) Hacking detected!"; return crow::response(400, "HACKER!!!!"); } if (from_it == to_it) return crow::response(400, "'from' and 'to' are the same"); if (value > from_it->second) return crow::response(400, "'from' doesn't have enough money"); money_mutex.lock(); from_it->second -= value; to_it->second += value; transaction t; t.from = from_it->first; t.to = to_it->first; t.money = value; transaction_map.insert( std::make_pair( system_clock::now(), t)); money_mutex.unlock(); return crow::response(json_from_transaction(t)); }); app.port(port).multithreaded().run(); } catch (std::exception& ex) { std::cerr << "exception (std) : " << ex.what() << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>/* * Author(s): * - Cedric Gestes <[email protected]> * - Chris Kilner <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include <qi/messaging/src/network/endpoint_context.hpp> #include <qi/messaging/src/network/network.hpp> namespace qi { namespace detail { std::string endpointTypeAsString(EndpointType type) { if (type == SERVER_ENDPOINT) { return "Server"; } if (type == CLIENT_ENDPOINT) { return "Client"; } if (type == PUBLISHER_ENDPOINT) { return "Publisher"; } if (type == SUBSCRIBER_ENDPOINT) { return "Subscriber"; } return "Unknown"; } EndpointContext::EndpointContext(): type(CLIENT_ENDPOINT), name(""), endpointID(getUUID()), contextID(""), machineID(getFirstMacAddress()), processID(getProcessID()), port(0) {} EndpointContext::EndpointContext( const EndpointType& pType, const std::string& pName, const std::string& pEndpointID, const std::string& pContextID, const std::string& pMachineID, const int& pProcessID, const int& pPort) : type(pType), name(pName), endpointID(pEndpointID), contextID(pContextID), machineID(pMachineID), processID(pProcessID), port(pPort) {} } } <commit_msg>Gave endpoint a default UNDEFINED TYPE<commit_after>/* * Author(s): * - Cedric Gestes <[email protected]> * - Chris Kilner <[email protected]> * * Copyright (C) 2010 Aldebaran Robotics */ #include <qi/messaging/src/network/endpoint_context.hpp> #include <qi/messaging/src/network/network.hpp> namespace qi { namespace detail { std::string endpointTypeAsString(EndpointType type) { if (type == SERVER_ENDPOINT) { return "Server"; } if (type == CLIENT_ENDPOINT) { return "Client"; } if (type == PUBLISHER_ENDPOINT) { return "Publisher"; } if (type == SUBSCRIBER_ENDPOINT) { return "Subscriber"; } return "Unknown"; } EndpointContext::EndpointContext(): type(UNDEFINED_ENDPOINT), name(""), endpointID(getUUID()), contextID(""), machineID(getFirstMacAddress()), processID(getProcessID()), port(0) {} EndpointContext::EndpointContext( const EndpointType& pType, const std::string& pName, const std::string& pEndpointID, const std::string& pContextID, const std::string& pMachineID, const int& pProcessID, const int& pPort) : type(pType), name(pName), endpointID(pEndpointID), contextID(pContextID), machineID(pMachineID), processID(pProcessID), port(pPort) {} } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPickingTool.h" #include "mitkToolManager.h" #include "mitkProperties.h" // us #include <usModule.h> #include <usModuleResource.h> #include <usGetModuleContext.h> #include <usModuleContext.h> #include "mitkImageCast.h" #include "mitkImageTimeSelector.h" #include "mitkITKImageImport.h" #include "mitkImageAccessByItk.h" #include "mitkImageTimeSelector.h" #include <itkConnectedThresholdImageFilter.h> namespace mitk { MITK_TOOL_MACRO(MitkSegmentation_EXPORT, PickingTool, "PickingTool"); } mitk::PickingTool::PickingTool() : m_WorkingData(NULL) { m_PointSetNode = mitk::DataNode::New(); m_PointSetNode->GetPropertyList()->SetProperty("name", mitk::StringProperty::New("Picking_Seedpoint")); m_PointSetNode->GetPropertyList()->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PointSet = mitk::PointSet::New(); m_PointSetNode->SetData(m_PointSet); m_SeedPointInteractor = mitk::SinglePointDataInteractor::New(); m_SeedPointInteractor->LoadStateMachine("PointSet.xml"); m_SeedPointInteractor->SetEventConfig("PointSetConfig.xml"); m_SeedPointInteractor->SetDataNode(m_PointSetNode); //Watch for point added or modified itk::SimpleMemberCommand<PickingTool>::Pointer pointAddedCommand = itk::SimpleMemberCommand<PickingTool>::New(); pointAddedCommand->SetCallbackFunction(this, &mitk::PickingTool::OnPointAdded); m_PointSetAddObserverTag = m_PointSet->AddObserver( mitk::PointSetAddEvent(), pointAddedCommand); //create new node for picked region m_ResultNode = mitk::DataNode::New(); // set some properties m_ResultNode->SetProperty("name", mitk::StringProperty::New("result")); m_ResultNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_ResultNode->SetProperty("color", mitk::ColorProperty::New(1, 1, 0)); m_ResultNode->SetProperty("layer", mitk::IntProperty::New(1)); m_ResultNode->SetProperty("opacity", mitk::FloatProperty::New(0.33f)); } mitk::PickingTool::~PickingTool() { m_PointSet->RemoveObserver(m_PointSetAddObserverTag); } const char** mitk::PickingTool::GetXPM() const { return NULL; } const char* mitk::PickingTool::GetName() const { return "Picking"; } us::ModuleResource mitk::PickingTool::GetIconResource() const { us::Module* module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Pick_48x48.png"); return resource; } void mitk::PickingTool::Activated() { DataStorage* dataStorage = this->GetDataStorage(); m_WorkingData = this->GetWorkingData(); //add to datastorage and enable interaction if (!dataStorage->Exists(m_PointSetNode)) dataStorage->Add(m_PointSetNode, m_WorkingData); // now add result to data tree dataStorage->Add(m_ResultNode, m_WorkingData); } void mitk::PickingTool::Deactivated() { m_PointSet->Clear(); //remove from data storage and disable interaction GetDataStorage()->Remove(m_PointSetNode); GetDataStorage()->Remove( m_ResultNode); } mitk::DataNode* mitk::PickingTool::GetReferenceData(){ return this->m_ToolManager->GetReferenceData(0); } mitk::DataStorage* mitk::PickingTool::GetDataStorage(){ return this->m_ToolManager->GetDataStorage(); } mitk::DataNode* mitk::PickingTool::GetWorkingData(){ return this->m_ToolManager->GetWorkingData(0); } mitk::DataNode::Pointer mitk::PickingTool::GetPointSetNode() { return m_PointSetNode; } void mitk::PickingTool::OnPointAdded() { if (m_WorkingData != this->GetWorkingData()) { DataStorage* dataStorage = this->GetDataStorage(); if (dataStorage->Exists(m_PointSetNode)) { dataStorage->Remove(m_PointSetNode); dataStorage->Add(m_PointSetNode, this->GetWorkingData()); } if (dataStorage->Exists(m_ResultNode)) { dataStorage->Remove(m_ResultNode); dataStorage->Add(m_ResultNode, this->GetWorkingData()); } m_WorkingData = this->GetWorkingData(); } //Perform region growing/picking int timeStep = mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1") )->GetTimeStep(); mitk::PointSet::PointType seedPoint = m_PointSet->GetPointSet(timeStep)->GetPoints()->Begin().Value(); //as we want to pick a region from our segmentation image use the working data from ToolManager mitk::Image::Pointer orgImage = dynamic_cast<mitk::Image*> (m_ToolManager->GetWorkingData(0)->GetData()); if (orgImage.IsNotNull()) { if (orgImage->GetDimension() == 4) { //there may be 4D segmentation data even though we currently don't support that mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(orgImage); timeSelector->SetTimeNr( timeStep ); timeSelector->UpdateLargestPossibleRegion(); mitk::Image* timedImage = timeSelector->GetOutput(); AccessByItk_2( timedImage , StartRegionGrowing, timedImage->GetGeometry(), seedPoint); } else if (orgImage->GetDimension() == 3) { AccessByItk_2(orgImage, StartRegionGrowing, orgImage->GetGeometry(), seedPoint); } this->m_PointSet->Clear(); } } template<typename TPixel, unsigned int VImageDimension> void mitk::PickingTool::StartRegionGrowing(itk::Image<TPixel, VImageDimension>* itkImage, mitk::BaseGeometry* imageGeometry, mitk::PointSet::PointType seedPoint) { typedef itk::Image<TPixel, VImageDimension> InputImageType; typedef typename InputImageType::IndexType IndexType; typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType; typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New(); // convert world coordinates to image indices IndexType seedIndex; imageGeometry->WorldToIndex( seedPoint, seedIndex); //perform region growing in desired segmented region regionGrower->SetInput( itkImage ); regionGrower->AddSeed( seedIndex ); regionGrower->SetLower( 1 ); regionGrower->SetUpper( 255 ); try { regionGrower->Update(); } catch(const itk::ExceptionObject&) { return; // can't work } catch( ... ) { return; } //Store result and preview mitk::Image::Pointer resultImage = mitk::ImportItkImage(regionGrower->GetOutput(),imageGeometry)->Clone(); m_ResultNode->SetData( resultImage ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::PickingTool::ConfirmSegmentation() { mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetProperty("name", mitk::StringProperty::New(m_WorkingData->GetName() + "_picked")); float rgb[3] = { 1.0f, 0.0f, 0.0f }; m_WorkingData->GetColor(rgb); newNode->SetProperty("color", mitk::ColorProperty::New(rgb)); float opacity = 1.0f; m_WorkingData->GetOpacity(opacity, NULL); newNode->SetProperty("opacity", mitk::FloatProperty::New(opacity)); newNode->SetData(m_ResultNode->GetData()); GetDataStorage()->Add(newNode, this->GetReferenceData()); m_ResultNode->SetData(NULL); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } <commit_msg>Changed color back to green<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPickingTool.h" #include "mitkToolManager.h" #include "mitkProperties.h" // us #include <usModule.h> #include <usModuleResource.h> #include <usGetModuleContext.h> #include <usModuleContext.h> #include "mitkImageCast.h" #include "mitkImageTimeSelector.h" #include "mitkITKImageImport.h" #include "mitkImageAccessByItk.h" #include "mitkImageTimeSelector.h" #include <itkConnectedThresholdImageFilter.h> namespace mitk { MITK_TOOL_MACRO(MitkSegmentation_EXPORT, PickingTool, "PickingTool"); } mitk::PickingTool::PickingTool() : m_WorkingData(NULL) { m_PointSetNode = mitk::DataNode::New(); m_PointSetNode->GetPropertyList()->SetProperty("name", mitk::StringProperty::New("Picking_Seedpoint")); m_PointSetNode->GetPropertyList()->SetProperty("helper object", mitk::BoolProperty::New(true)); m_PointSet = mitk::PointSet::New(); m_PointSetNode->SetData(m_PointSet); m_SeedPointInteractor = mitk::SinglePointDataInteractor::New(); m_SeedPointInteractor->LoadStateMachine("PointSet.xml"); m_SeedPointInteractor->SetEventConfig("PointSetConfig.xml"); m_SeedPointInteractor->SetDataNode(m_PointSetNode); //Watch for point added or modified itk::SimpleMemberCommand<PickingTool>::Pointer pointAddedCommand = itk::SimpleMemberCommand<PickingTool>::New(); pointAddedCommand->SetCallbackFunction(this, &mitk::PickingTool::OnPointAdded); m_PointSetAddObserverTag = m_PointSet->AddObserver( mitk::PointSetAddEvent(), pointAddedCommand); //create new node for picked region m_ResultNode = mitk::DataNode::New(); // set some properties m_ResultNode->SetProperty("name", mitk::StringProperty::New("result")); m_ResultNode->SetProperty("helper object", mitk::BoolProperty::New(true)); m_ResultNode->SetProperty("color", mitk::ColorProperty::New(0, 1, 0)); m_ResultNode->SetProperty("layer", mitk::IntProperty::New(1)); m_ResultNode->SetProperty("opacity", mitk::FloatProperty::New(0.33f)); } mitk::PickingTool::~PickingTool() { m_PointSet->RemoveObserver(m_PointSetAddObserverTag); } const char** mitk::PickingTool::GetXPM() const { return NULL; } const char* mitk::PickingTool::GetName() const { return "Picking"; } us::ModuleResource mitk::PickingTool::GetIconResource() const { us::Module* module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Pick_48x48.png"); return resource; } void mitk::PickingTool::Activated() { DataStorage* dataStorage = this->GetDataStorage(); m_WorkingData = this->GetWorkingData(); //add to datastorage and enable interaction if (!dataStorage->Exists(m_PointSetNode)) dataStorage->Add(m_PointSetNode, m_WorkingData); // now add result to data tree dataStorage->Add(m_ResultNode, m_WorkingData); } void mitk::PickingTool::Deactivated() { m_PointSet->Clear(); //remove from data storage and disable interaction GetDataStorage()->Remove(m_PointSetNode); GetDataStorage()->Remove( m_ResultNode); } mitk::DataNode* mitk::PickingTool::GetReferenceData(){ return this->m_ToolManager->GetReferenceData(0); } mitk::DataStorage* mitk::PickingTool::GetDataStorage(){ return this->m_ToolManager->GetDataStorage(); } mitk::DataNode* mitk::PickingTool::GetWorkingData(){ return this->m_ToolManager->GetWorkingData(0); } mitk::DataNode::Pointer mitk::PickingTool::GetPointSetNode() { return m_PointSetNode; } void mitk::PickingTool::OnPointAdded() { if (m_WorkingData != this->GetWorkingData()) { DataStorage* dataStorage = this->GetDataStorage(); if (dataStorage->Exists(m_PointSetNode)) { dataStorage->Remove(m_PointSetNode); dataStorage->Add(m_PointSetNode, this->GetWorkingData()); } if (dataStorage->Exists(m_ResultNode)) { dataStorage->Remove(m_ResultNode); dataStorage->Add(m_ResultNode, this->GetWorkingData()); } m_WorkingData = this->GetWorkingData(); } //Perform region growing/picking int timeStep = mitk::BaseRenderer::GetInstance( mitk::BaseRenderer::GetRenderWindowByName("stdmulti.widget1") )->GetTimeStep(); mitk::PointSet::PointType seedPoint = m_PointSet->GetPointSet(timeStep)->GetPoints()->Begin().Value(); //as we want to pick a region from our segmentation image use the working data from ToolManager mitk::Image::Pointer orgImage = dynamic_cast<mitk::Image*> (m_ToolManager->GetWorkingData(0)->GetData()); if (orgImage.IsNotNull()) { if (orgImage->GetDimension() == 4) { //there may be 4D segmentation data even though we currently don't support that mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(orgImage); timeSelector->SetTimeNr( timeStep ); timeSelector->UpdateLargestPossibleRegion(); mitk::Image* timedImage = timeSelector->GetOutput(); AccessByItk_2( timedImage , StartRegionGrowing, timedImage->GetGeometry(), seedPoint); } else if (orgImage->GetDimension() == 3) { AccessByItk_2(orgImage, StartRegionGrowing, orgImage->GetGeometry(), seedPoint); } this->m_PointSet->Clear(); } } template<typename TPixel, unsigned int VImageDimension> void mitk::PickingTool::StartRegionGrowing(itk::Image<TPixel, VImageDimension>* itkImage, mitk::BaseGeometry* imageGeometry, mitk::PointSet::PointType seedPoint) { typedef itk::Image<TPixel, VImageDimension> InputImageType; typedef typename InputImageType::IndexType IndexType; typedef itk::ConnectedThresholdImageFilter<InputImageType, InputImageType> RegionGrowingFilterType; typename RegionGrowingFilterType::Pointer regionGrower = RegionGrowingFilterType::New(); // convert world coordinates to image indices IndexType seedIndex; imageGeometry->WorldToIndex( seedPoint, seedIndex); //perform region growing in desired segmented region regionGrower->SetInput( itkImage ); regionGrower->AddSeed( seedIndex ); regionGrower->SetLower( 1 ); regionGrower->SetUpper( 255 ); try { regionGrower->Update(); } catch(const itk::ExceptionObject&) { return; // can't work } catch( ... ) { return; } //Store result and preview mitk::Image::Pointer resultImage = mitk::ImportItkImage(regionGrower->GetOutput(),imageGeometry)->Clone(); m_ResultNode->SetData( resultImage ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void mitk::PickingTool::ConfirmSegmentation() { mitk::DataNode::Pointer newNode = mitk::DataNode::New(); newNode->SetProperty("name", mitk::StringProperty::New(m_WorkingData->GetName() + "_picked")); float rgb[3] = { 1.0f, 0.0f, 0.0f }; m_WorkingData->GetColor(rgb); newNode->SetProperty("color", mitk::ColorProperty::New(rgb)); float opacity = 1.0f; m_WorkingData->GetOpacity(opacity, NULL); newNode->SetProperty("opacity", mitk::FloatProperty::New(opacity)); newNode->SetData(m_ResultNode->GetData()); GetDataStorage()->Add(newNode, this->GetReferenceData()); m_ResultNode->SetData(NULL); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } <|endoftext|>
<commit_before>#include <mos/gfx/text.hpp> #include <mos/util.hpp> #include <glm/glm.hpp> #include <iostream> #include <glm/gtc/matrix_transform.hpp> namespace mos { namespace gfx { Text::Text(const std::string &txt, const Font &font, const glm::mat4 &transform, const float spacing) : model_("Text", std::make_shared<Mesh>(Mesh()), transform), font_(font), spacing(spacing) { model_.material.albedo = glm::vec3(1.0f); model_.material.opacity = 0.0f; model_.material.emission = glm::vec3(1.0f); model_.material.albedo_map = font.texture; text(txt); } Text::~Text() {} std::string Text::text() const { return text_; } void Text::text(const std::string &text) { if (text_.compare(text) != 0) { text_ = text; std::vector<std::string> lines = mos::split(text_, '\n'); model_.mesh->clear(); float line_index = 0.0f; const float line_height = -1.0f; int triangle_index = 0; for (auto & line : lines) { float index = 0.0f; for (auto & c : line) { auto character = font_.characters.at(c); float u1 = character.x / ((float)font_.texture->width()); float u2 = (character.x + character.width) / (float)font_.texture->width(); float v1 = character.y / ((float)font_.texture->height()); float v2 = ((character.y + character.height) / ((float)font_.texture->height())); float offset_y = -(character.y_offset - font_.base()) / font_.height(); float offset_x = character.x_offset / font_.height(); float rect_h = -character.height / font_.height(); float rect_w = character.width / font_.height(); float advance = character.x_advance / font_.height(); float z = index / 2000.0f; //TODO: Optimize to four vertices model_.mesh->vertices.push_back( Vertex(glm::vec3(index + offset_x, rect_h + offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u1, v2))); model_.mesh->vertices.push_back(Vertex( glm::vec3(index + rect_w + offset_x, offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u2, v1))); model_.mesh->vertices.push_back(Vertex(glm::vec3(index + offset_x, offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u1, v1))); model_.mesh->triangles.push_back({triangle_index++, triangle_index++, triangle_index++}); model_.mesh->vertices.push_back( Vertex(glm::vec3(index + offset_x, rect_h + offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u1, v2))); model_.mesh->vertices.push_back(Vertex(glm::vec3(index + rect_w + offset_x, rect_h + offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u2, v2))); model_.mesh->vertices.push_back(Vertex( glm::vec3(index + rect_w + offset_x, offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u2, v1))); model_.mesh->triangles.push_back({triangle_index++, triangle_index++, triangle_index++}); index += advance + spacing; } line_index += line_height; } } } float Text::width() const { if (model_.mesh->vertices.size() > 2){ glm::vec2 p1 = glm::vec2(model_.mesh->vertices.begin()->position); glm::vec2 p2 = glm::vec2((model_.mesh->vertices.end() - 2)->position); return glm::distance(p1, p2); } else { return 0.0f; } } float Text::height() const { return font_.height(); } void Text::position(const glm::vec2 &position) { model_.transform = glm::translate(glm::mat4(1.0f), glm::vec3(position.x, position.y, 0.0f)); } void Text::position(const glm::vec3 & position) { model_.transform = glm::translate(glm::mat4(1.0f), position); } glm::vec2 Text::position() const { return glm::vec2(model_.position()); } void Text::scale(const float scale) { model_.transform = glm::scale(model_.transform, glm::vec3(scale, scale, scale)); } void Text::material(const Material &material) { model_.material = material; } void Text::transform(const glm::mat4 & transform) { model_.transform = transform; } glm::mat4 Text::transform() const { return model_.transform; } Model Text::model() const { return model_; } Text &Text::operator=(const std::string &input) { text(input); return *this; } Text &Text::operator+=(const std::string &input) { text(text() + input); return *this; } } } <commit_msg>Optimize text rendering.<commit_after>#include <mos/gfx/text.hpp> #include <mos/util.hpp> #include <glm/glm.hpp> #include <iostream> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/io.hpp> namespace mos { namespace gfx { Text::Text(const std::string &txt, const Font &font, const glm::mat4 &transform, const float spacing) : model_("Text", std::make_shared<Mesh>(Mesh()), transform), font_(font), spacing(spacing) { model_.material.albedo = glm::vec3(1.0f); model_.material.opacity = 0.0f; model_.material.emission = glm::vec3(1.0f); model_.material.albedo_map = font.texture; text(txt); } Text::~Text() {} std::string Text::text() const { return text_; } void Text::text(const std::string &text) { if (text_.compare(text) != 0) { text_ = text; std::vector<std::string> lines = mos::split(text_, '\n'); model_.mesh->clear(); float line_index = 0.0f; const float line_height = -1.0f; int triangle_index = 0; for (auto & line : lines) { float index = 0.0f; for (auto & c : line) { auto character = font_.characters.at(c); float u1 = character.x / ((float)font_.texture->width()); float u2 = (character.x + character.width) / (float)font_.texture->width(); float v1 = character.y / ((float)font_.texture->height()); float v2 = ((character.y + character.height) / ((float)font_.texture->height())); float offset_y = -(character.y_offset - font_.base()) / font_.height(); float offset_x = character.x_offset / font_.height(); float rect_h = -character.height / font_.height(); float rect_w = character.width / font_.height(); float advance = character.x_advance / font_.height(); float z = index / 2000.0f; model_.mesh->vertices.push_back( Vertex(glm::vec3(index + offset_x, rect_h + offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u1, v2))); model_.mesh->vertices.push_back(Vertex( glm::vec3(index + rect_w + offset_x, offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u2, v1))); model_.mesh->vertices.push_back(Vertex(glm::vec3(index + offset_x, offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u1, v1))); model_.mesh->triangles.push_back({triangle_index++, triangle_index++, triangle_index++}); model_.mesh->vertices.push_back(Vertex(glm::vec3(index + rect_w + offset_x, rect_h + offset_y + line_index, z), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f), glm::vec2(u2, v2))); model_.mesh->triangles.push_back({triangle_index - 3, triangle_index++, triangle_index -3}); index += advance + spacing; } line_index += line_height; } } } float Text::width() const { if (model_.mesh->vertices.size() > 2){ glm::vec2 p1 = glm::vec2(model_.mesh->vertices.begin()->position); glm::vec2 p2 = glm::vec2((model_.mesh->vertices.end() - 2)->position); return glm::distance(p1, p2); } else { return 0.0f; } } float Text::height() const { return font_.height(); } void Text::position(const glm::vec2 &position) { model_.transform = glm::translate(glm::mat4(1.0f), glm::vec3(position.x, position.y, 0.0f)); } void Text::position(const glm::vec3 & position) { model_.transform = glm::translate(glm::mat4(1.0f), position); } glm::vec2 Text::position() const { return glm::vec2(model_.position()); } void Text::scale(const float scale) { model_.transform = glm::scale(model_.transform, glm::vec3(scale, scale, scale)); } void Text::material(const Material &material) { model_.material = material; } void Text::transform(const glm::mat4 & transform) { model_.transform = transform; } glm::mat4 Text::transform() const { return model_.transform; } Model Text::model() const { return model_; } Text &Text::operator=(const std::string &input) { text(input); return *this; } Text &Text::operator+=(const std::string &input) { text(text() + input); return *this; } } } <|endoftext|>
<commit_before>#ifndef ARBITER_IS_AMALGAMATION #include <arbiter/arbiter.hpp> #include <arbiter/drivers/s3.hpp> #endif #include <algorithm> #include <cctype> #include <chrono> #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <thread> #ifndef ARBITER_IS_AMALGAMATION #include <arbiter/arbiter.hpp> #include <arbiter/drivers/fs.hpp> #include <arbiter/third/xml/xml.hpp> #include <arbiter/util/crypto.hpp> #endif namespace arbiter { namespace { const std::string baseUrl(".s3.amazonaws.com/"); std::string getQueryString(const Query& query) { std::string result; bool first(true); for (const auto& q : query) { result += (first ? "?" : "&") + q.first + "=" + q.second; first = false; } return result; } struct Resource { Resource(std::string fullPath) { const std::size_t split(fullPath.find("/")); bucket = fullPath.substr(0, split); if (split != std::string::npos) { object = fullPath.substr(split + 1); } } std::string buildPath(Query query = Query()) const { const std::string queryString(getQueryString(query)); return "http://" + bucket + baseUrl + object + queryString; } std::string bucket; std::string object; }; typedef Xml::xml_node<> XmlNode; const std::string badResponse("Unexpected contents in AWS response"); } namespace drivers { AwsAuth::AwsAuth(const std::string access, const std::string hidden) : m_access(access) , m_hidden(hidden) { } std::unique_ptr<AwsAuth> AwsAuth::find(std::string user) { std::unique_ptr<AwsAuth> auth; if (user.empty()) { user = getenv("AWS_PROFILE") ? getenv("AWS_PROFILE") : "default"; } drivers::Fs fs; std::unique_ptr<std::string> file(fs.tryGet("~/.aws/credentials")); // First, try reading credentials file. if (file) { std::size_t index(0); std::size_t pos(0); std::vector<std::string> lines; do { index = file->find('\n', pos); std::string line(file->substr(pos, index - pos)); line.erase( std::remove_if(line.begin(), line.end(), ::isspace), line.end()); lines.push_back(line); pos = index + 1; } while (index != std::string::npos); if (lines.size() >= 3) { std::size_t i(0); const std::string userFind("[" + user + "]"); const std::string accessFind("aws_access_key_id="); const std::string hiddenFind("aws_secret_access_key="); while (i < lines.size() - 2 && !auth) { if (lines[i].find(userFind) != std::string::npos) { const std::string& accessLine(lines[i + 1]); const std::string& hiddenLine(lines[i + 2]); std::size_t accessPos(accessLine.find(accessFind)); std::size_t hiddenPos(hiddenLine.find(hiddenFind)); if ( accessPos != std::string::npos && hiddenPos != std::string::npos) { const std::string access( accessLine.substr( accessPos + accessFind.size(), accessLine.find(';'))); const std::string hidden( hiddenLine.substr( hiddenPos + hiddenFind.size(), hiddenLine.find(';'))); auth.reset(new AwsAuth(access, hidden)); } } ++i; } } } // Fall back to environment settings. if (!auth) { if (getenv("AWS_ACCESS_KEY_ID") && getenv("AWS_SECRET_ACCESS_KEY")) { auth.reset( new AwsAuth( getenv("AWS_ACCESS_KEY_ID"), getenv("AWS_SECRET_ACCESS_KEY"))); } else if ( getenv("AMAZON_ACCESS_KEY_ID") && getenv("AMAZON_SECRET_ACCESS_KEY")) { auth.reset( new AwsAuth( getenv("AMAZON_ACCESS_KEY_ID"), getenv("AMAZON_SECRET_ACCESS_KEY"))); } } return auth; } std::string AwsAuth::access() const { return m_access; } std::string AwsAuth::hidden() const { return m_hidden; } S3::S3(HttpPool& pool, const AwsAuth auth) : m_pool(pool) , m_auth(auth) { } std::unique_ptr<S3> S3::create(HttpPool& pool, const Json::Value& json) { std::unique_ptr<S3> s3; if (!json.isNull() && json.isMember("access") & json.isMember("hidden")) { AwsAuth auth(json["access"].asString(), json["hidden"].asString()); s3.reset(new S3(pool, auth)); } else if (!json.isNull()) { auto auth(AwsAuth::find(json["user"].asString())); if (auth) s3.reset(new S3(pool, *auth)); } return s3; } bool S3::get(std::string rawPath, std::vector<char>& data) const { return buildRequestAndGet(rawPath, Query(), data); } bool S3::buildRequestAndGet( std::string rawPath, const Query& query, std::vector<char>& data, const Headers userHeaders) const { rawPath = Http::sanitize(rawPath); const Resource resource(rawPath); const std::string path(resource.buildPath(query)); Headers headers(httpGetHeaders(rawPath)); for (const auto& h : userHeaders) headers[h.first] = h.second; auto http(m_pool.acquire()); HttpResponse res(http.get(path, headers)); if (res.ok()) { data = res.data(); return true; } else { return false; } } void S3::put(std::string rawPath, const std::vector<char>& data) const { const Resource resource(rawPath); const std::string path(resource.buildPath()); const Headers headers(httpPutHeaders(rawPath)); auto http(m_pool.acquire()); if (!http.put(path, data, headers).ok()) { throw ArbiterError("Couldn't S3 PUT to " + rawPath); } } std::vector<std::string> S3::glob(std::string path, bool verbose) const { std::vector<std::string> results; path.pop_back(); // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html const Resource resource(path); const std::string& bucket(resource.bucket); const std::string& object(resource.object); const std::string prefix(resource.object.empty() ? "" : resource.object); Query query; if (prefix.size()) query["prefix"] = prefix; bool more(false); std::vector<char> data; do { if (verbose) std::cout << "." << std::flush; if (!buildRequestAndGet(resource.bucket + "/", query, data)) { throw ArbiterError("Couldn't S3 GET " + resource.bucket); } data.push_back('\0'); Xml::xml_document<> xml; try { xml.parse<0>(data.data()); } catch (Xml::parse_error) { throw ArbiterError("Could not parse S3 response."); } if (XmlNode* topNode = xml.first_node("ListBucketResult")) { if (XmlNode* truncNode = topNode->first_node("IsTruncated")) { std::string t(truncNode->value()); std::transform(t.begin(), t.end(), t.begin(), tolower); more = (t == "true"); } if (XmlNode* conNode = topNode->first_node("Contents")) { for ( ; conNode; conNode = conNode->next_sibling()) { if (XmlNode* keyNode = conNode->first_node("Key")) { std::string key(keyNode->value()); // The prefix may contain slashes (i.e. is a sub-dir) // but we only include the top level after that. if (key.find('/', prefix.size()) == std::string::npos) { results.push_back("s3://" + bucket + "/" + key); if (more) { query["marker"] = object + key.substr(prefix.size()); } } } else { throw ArbiterError(badResponse); } } } else { throw ArbiterError(badResponse); } } else { throw ArbiterError(badResponse); } xml.clear(); } while (more); return results; } Headers S3::httpGetHeaders(std::string filePath) const { const std::string httpDate(getHttpDate()); const std::string signedEncoded( getSignedEncodedString( "GET", filePath, httpDate)); Headers headers; headers["Date"] = httpDate; headers["Authorization"] = "AWS " + m_auth.access() + ":" + signedEncoded; return headers; } Headers S3::httpPutHeaders(std::string filePath) const { const std::string httpDate(getHttpDate()); const std::string signedEncoded( getSignedEncodedString( "PUT", filePath, httpDate, "application/octet-stream")); Headers headers; headers["Content-Type"] = "application/octet-stream"; headers["Date"] = httpDate; headers["Authorization"] = "AWS " + m_auth.access() + ":" + signedEncoded; headers["Transfer-Encoding"] = ""; headers["Expect"] = ""; return headers; } std::string S3::getHttpDate() const { time_t rawTime; char charBuf[80]; time(&rawTime); #ifndef ARBITER_WINDOWS tm* timeInfoPtr = localtime(&rawTime); #else tm timeInfo; localtime_s(&timeInfo, &rawTime); tm* timeInfoPtr(&timeInfo); #endif strftime(charBuf, 80, "%a, %d %b %Y %H:%M:%S %z", timeInfoPtr); std::string stringBuf(charBuf); return stringBuf; } std::string S3::getSignedEncodedString( std::string command, std::string file, std::string httpDate, std::string contentType) const { const std::string toSign(getStringToSign( command, file, httpDate, contentType)); const std::vector<char> signedData(signString(toSign)); return encodeBase64(signedData); } std::string S3::getStringToSign( std::string command, std::string file, std::string httpDate, std::string contentType) const { return command + "\n" + "\n" + contentType + "\n" + httpDate + "\n" + "/" + file; } std::vector<char> S3::signString(std::string input) const { return crypto::hmacSha1(m_auth.hidden(), input); } std::string S3::encodeBase64(std::vector<char> data) const { std::vector<uint8_t> input; for (std::size_t i(0); i < data.size(); ++i) { char c(data[i]); input.push_back(*reinterpret_cast<uint8_t*>(&c)); } const std::string vals( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); std::size_t fullSteps(input.size() / 3); while (input.size() % 3) input.push_back(0); uint8_t* pos(input.data()); uint8_t* end(input.data() + fullSteps * 3); std::string output(fullSteps * 4, '_'); std::size_t outIndex(0); const uint32_t mask(0x3F); while (pos != end) { uint32_t chunk((*pos) << 16 | *(pos + 1) << 8 | *(pos + 2)); output[outIndex++] = vals[(chunk >> 18) & mask]; output[outIndex++] = vals[(chunk >> 12) & mask]; output[outIndex++] = vals[(chunk >> 6) & mask]; output[outIndex++] = vals[chunk & mask]; pos += 3; } if (end != input.data() + input.size()) { const std::size_t num(pos - end == 1 ? 2 : 3); uint32_t chunk(*(pos) << 16 | *(pos + 1) << 8 | *(pos + 2)); output.push_back(vals[(chunk >> 18) & mask]); output.push_back(vals[(chunk >> 12) & mask]); if (num == 3) output.push_back(vals[(chunk >> 6) & mask]); } while (output.size() % 4) output.push_back('='); return output; } // These functions allow a caller to directly pass additional headers into // their GET request. This is only applicable when using the S3 driver // directly, as these are not available through the Arbiter. std::vector<char> S3::getBinary(std::string rawPath, Headers headers) const { std::vector<char> data; const std::string stripped(Arbiter::stripType(rawPath)); if (!buildRequestAndGet(stripped, Query(), data, headers)) { throw ArbiterError("Couldn't S3 GET " + rawPath); } return data; } std::string S3::get(std::string rawPath, Headers headers) const { std::vector<char> data(getBinary(rawPath, headers)); return std::string(data.begin(), data.end()); } } // namespace drivers } // namespace arbiter <commit_msg>Default AWS user if no JSON config is passed.<commit_after>#ifndef ARBITER_IS_AMALGAMATION #include <arbiter/arbiter.hpp> #include <arbiter/drivers/s3.hpp> #endif #include <algorithm> #include <cctype> #include <chrono> #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <thread> #ifndef ARBITER_IS_AMALGAMATION #include <arbiter/arbiter.hpp> #include <arbiter/drivers/fs.hpp> #include <arbiter/third/xml/xml.hpp> #include <arbiter/util/crypto.hpp> #endif namespace arbiter { namespace { const std::string baseUrl(".s3.amazonaws.com/"); std::string getQueryString(const Query& query) { std::string result; bool first(true); for (const auto& q : query) { result += (first ? "?" : "&") + q.first + "=" + q.second; first = false; } return result; } struct Resource { Resource(std::string fullPath) { const std::size_t split(fullPath.find("/")); bucket = fullPath.substr(0, split); if (split != std::string::npos) { object = fullPath.substr(split + 1); } } std::string buildPath(Query query = Query()) const { const std::string queryString(getQueryString(query)); return "http://" + bucket + baseUrl + object + queryString; } std::string bucket; std::string object; }; typedef Xml::xml_node<> XmlNode; const std::string badResponse("Unexpected contents in AWS response"); } namespace drivers { AwsAuth::AwsAuth(const std::string access, const std::string hidden) : m_access(access) , m_hidden(hidden) { } std::unique_ptr<AwsAuth> AwsAuth::find(std::string user) { std::unique_ptr<AwsAuth> auth; if (user.empty()) { user = getenv("AWS_PROFILE") ? getenv("AWS_PROFILE") : "default"; } drivers::Fs fs; std::unique_ptr<std::string> file(fs.tryGet("~/.aws/credentials")); // First, try reading credentials file. if (file) { std::size_t index(0); std::size_t pos(0); std::vector<std::string> lines; do { index = file->find('\n', pos); std::string line(file->substr(pos, index - pos)); line.erase( std::remove_if(line.begin(), line.end(), ::isspace), line.end()); lines.push_back(line); pos = index + 1; } while (index != std::string::npos); if (lines.size() >= 3) { std::size_t i(0); const std::string userFind("[" + user + "]"); const std::string accessFind("aws_access_key_id="); const std::string hiddenFind("aws_secret_access_key="); while (i < lines.size() - 2 && !auth) { if (lines[i].find(userFind) != std::string::npos) { const std::string& accessLine(lines[i + 1]); const std::string& hiddenLine(lines[i + 2]); std::size_t accessPos(accessLine.find(accessFind)); std::size_t hiddenPos(hiddenLine.find(hiddenFind)); if ( accessPos != std::string::npos && hiddenPos != std::string::npos) { const std::string access( accessLine.substr( accessPos + accessFind.size(), accessLine.find(';'))); const std::string hidden( hiddenLine.substr( hiddenPos + hiddenFind.size(), hiddenLine.find(';'))); auth.reset(new AwsAuth(access, hidden)); } } ++i; } } } // Fall back to environment settings. if (!auth) { if (getenv("AWS_ACCESS_KEY_ID") && getenv("AWS_SECRET_ACCESS_KEY")) { auth.reset( new AwsAuth( getenv("AWS_ACCESS_KEY_ID"), getenv("AWS_SECRET_ACCESS_KEY"))); } else if ( getenv("AMAZON_ACCESS_KEY_ID") && getenv("AMAZON_SECRET_ACCESS_KEY")) { auth.reset( new AwsAuth( getenv("AMAZON_ACCESS_KEY_ID"), getenv("AMAZON_SECRET_ACCESS_KEY"))); } } return auth; } std::string AwsAuth::access() const { return m_access; } std::string AwsAuth::hidden() const { return m_hidden; } S3::S3(HttpPool& pool, const AwsAuth auth) : m_pool(pool) , m_auth(auth) { } std::unique_ptr<S3> S3::create(HttpPool& pool, const Json::Value& json) { std::unique_ptr<S3> s3; if (!json.isNull() && json.isMember("access") & json.isMember("hidden")) { AwsAuth auth(json["access"].asString(), json["hidden"].asString()); s3.reset(new S3(pool, auth)); } else { auto auth(AwsAuth::find(json.isNull() ? "" : json["user"].asString())); if (auth) s3.reset(new S3(pool, *auth)); } return s3; } bool S3::get(std::string rawPath, std::vector<char>& data) const { return buildRequestAndGet(rawPath, Query(), data); } bool S3::buildRequestAndGet( std::string rawPath, const Query& query, std::vector<char>& data, const Headers userHeaders) const { rawPath = Http::sanitize(rawPath); const Resource resource(rawPath); const std::string path(resource.buildPath(query)); Headers headers(httpGetHeaders(rawPath)); for (const auto& h : userHeaders) headers[h.first] = h.second; auto http(m_pool.acquire()); HttpResponse res(http.get(path, headers)); if (res.ok()) { data = res.data(); return true; } else { return false; } } void S3::put(std::string rawPath, const std::vector<char>& data) const { const Resource resource(rawPath); const std::string path(resource.buildPath()); const Headers headers(httpPutHeaders(rawPath)); auto http(m_pool.acquire()); if (!http.put(path, data, headers).ok()) { throw ArbiterError("Couldn't S3 PUT to " + rawPath); } } std::vector<std::string> S3::glob(std::string path, bool verbose) const { std::vector<std::string> results; path.pop_back(); // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html const Resource resource(path); const std::string& bucket(resource.bucket); const std::string& object(resource.object); const std::string prefix(resource.object.empty() ? "" : resource.object); Query query; if (prefix.size()) query["prefix"] = prefix; bool more(false); std::vector<char> data; do { if (verbose) std::cout << "." << std::flush; if (!buildRequestAndGet(resource.bucket + "/", query, data)) { throw ArbiterError("Couldn't S3 GET " + resource.bucket); } data.push_back('\0'); Xml::xml_document<> xml; try { xml.parse<0>(data.data()); } catch (Xml::parse_error) { throw ArbiterError("Could not parse S3 response."); } if (XmlNode* topNode = xml.first_node("ListBucketResult")) { if (XmlNode* truncNode = topNode->first_node("IsTruncated")) { std::string t(truncNode->value()); std::transform(t.begin(), t.end(), t.begin(), tolower); more = (t == "true"); } if (XmlNode* conNode = topNode->first_node("Contents")) { for ( ; conNode; conNode = conNode->next_sibling()) { if (XmlNode* keyNode = conNode->first_node("Key")) { std::string key(keyNode->value()); // The prefix may contain slashes (i.e. is a sub-dir) // but we only include the top level after that. if (key.find('/', prefix.size()) == std::string::npos) { results.push_back("s3://" + bucket + "/" + key); if (more) { query["marker"] = object + key.substr(prefix.size()); } } } else { throw ArbiterError(badResponse); } } } else { throw ArbiterError(badResponse); } } else { throw ArbiterError(badResponse); } xml.clear(); } while (more); return results; } Headers S3::httpGetHeaders(std::string filePath) const { const std::string httpDate(getHttpDate()); const std::string signedEncoded( getSignedEncodedString( "GET", filePath, httpDate)); Headers headers; headers["Date"] = httpDate; headers["Authorization"] = "AWS " + m_auth.access() + ":" + signedEncoded; return headers; } Headers S3::httpPutHeaders(std::string filePath) const { const std::string httpDate(getHttpDate()); const std::string signedEncoded( getSignedEncodedString( "PUT", filePath, httpDate, "application/octet-stream")); Headers headers; headers["Content-Type"] = "application/octet-stream"; headers["Date"] = httpDate; headers["Authorization"] = "AWS " + m_auth.access() + ":" + signedEncoded; headers["Transfer-Encoding"] = ""; headers["Expect"] = ""; return headers; } std::string S3::getHttpDate() const { time_t rawTime; char charBuf[80]; time(&rawTime); #ifndef ARBITER_WINDOWS tm* timeInfoPtr = localtime(&rawTime); #else tm timeInfo; localtime_s(&timeInfo, &rawTime); tm* timeInfoPtr(&timeInfo); #endif strftime(charBuf, 80, "%a, %d %b %Y %H:%M:%S %z", timeInfoPtr); std::string stringBuf(charBuf); return stringBuf; } std::string S3::getSignedEncodedString( std::string command, std::string file, std::string httpDate, std::string contentType) const { const std::string toSign(getStringToSign( command, file, httpDate, contentType)); const std::vector<char> signedData(signString(toSign)); return encodeBase64(signedData); } std::string S3::getStringToSign( std::string command, std::string file, std::string httpDate, std::string contentType) const { return command + "\n" + "\n" + contentType + "\n" + httpDate + "\n" + "/" + file; } std::vector<char> S3::signString(std::string input) const { return crypto::hmacSha1(m_auth.hidden(), input); } std::string S3::encodeBase64(std::vector<char> data) const { std::vector<uint8_t> input; for (std::size_t i(0); i < data.size(); ++i) { char c(data[i]); input.push_back(*reinterpret_cast<uint8_t*>(&c)); } const std::string vals( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); std::size_t fullSteps(input.size() / 3); while (input.size() % 3) input.push_back(0); uint8_t* pos(input.data()); uint8_t* end(input.data() + fullSteps * 3); std::string output(fullSteps * 4, '_'); std::size_t outIndex(0); const uint32_t mask(0x3F); while (pos != end) { uint32_t chunk((*pos) << 16 | *(pos + 1) << 8 | *(pos + 2)); output[outIndex++] = vals[(chunk >> 18) & mask]; output[outIndex++] = vals[(chunk >> 12) & mask]; output[outIndex++] = vals[(chunk >> 6) & mask]; output[outIndex++] = vals[chunk & mask]; pos += 3; } if (end != input.data() + input.size()) { const std::size_t num(pos - end == 1 ? 2 : 3); uint32_t chunk(*(pos) << 16 | *(pos + 1) << 8 | *(pos + 2)); output.push_back(vals[(chunk >> 18) & mask]); output.push_back(vals[(chunk >> 12) & mask]); if (num == 3) output.push_back(vals[(chunk >> 6) & mask]); } while (output.size() % 4) output.push_back('='); return output; } // These functions allow a caller to directly pass additional headers into // their GET request. This is only applicable when using the S3 driver // directly, as these are not available through the Arbiter. std::vector<char> S3::getBinary(std::string rawPath, Headers headers) const { std::vector<char> data; const std::string stripped(Arbiter::stripType(rawPath)); if (!buildRequestAndGet(stripped, Query(), data, headers)) { throw ArbiterError("Couldn't S3 GET " + rawPath); } return data; } std::string S3::get(std::string rawPath, Headers headers) const { std::vector<char> data(getBinary(rawPath, headers)); return std::string(data.begin(), data.end()); } } // namespace drivers } // namespace arbiter <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -Wall -Wuninitialized -verify %s int foo(int x); int bar(int* x); int boo(int& x); int far(const int& x); // Test self-references within initializers which are guaranteed to be // uninitialized. int a = a; // no-warning: used to signal intended lack of initialization. int b = b + 1; // expected-warning {{variable 'b' is uninitialized when used within its own initialization}} int c = (c + c); // expected-warning 2 {{variable 'c' is uninitialized when used within its own initialization}} void test() { int d = ({ d + d ;}); // expected-warning {{variable 'd' is uninitialized when used within its own initialization}} } int e = static_cast<long>(e) + 1; // expected-warning {{variable 'e' is uninitialized when used within its own initialization}} int f = foo(f); // expected-warning {{variable 'f' is uninitialized when used within its own initialization}} // Thes don't warn as they don't require the value. int g = sizeof(g); void* ptr = &ptr; int h = bar(&h); int i = boo(i); int j = far(j); int k = __alignof__(k); // Test self-references with record types. class A { // Non-POD class. public: enum count { ONE, TWO, THREE }; int num; static int count; int get() const { return num; } int get2() { return num; } void set(int x) { num = x; } static int zero() { return 0; } A() {} A(A const &a) {} A(int x) {} A(int *x) {} A(A *a) {} ~A(); }; A getA() { return A(); } A getA(int x) { return A(); } A getA(A* a) { return A(); } void setupA() { A a1; a1.set(a1.get()); A a2(a1.get()); A a3(a1); A a4(&a4); A a5(a5.zero()); A a6(a6.ONE); A a7 = getA(); A a8 = getA(a8.TWO); A a9 = getA(&a9); A a10(a10.count); A a11(a11); // expected-warning {{variable 'a11' is uninitialized when used within its own initialization}} A a12(a12.get()); // expected-warning {{variable 'a12' is uninitialized when used within its own initialization}} A a13(a13.num); // expected-warning {{variable 'a13' is uninitialized when used within its own initialization}} A a14 = A(a14); // expected-warning {{variable 'a14' is uninitialized when used within its own initialization}} A a15 = getA(a15.num); // expected-warning {{variable 'a15' is uninitialized when used within its own initialization}} A a16(&a16.num); // expected-warning {{variable 'a16' is uninitialized when used within its own initialization}} A a17(a17.get2()); // expected-warning {{variable 'a17' is uninitialized when used within its own initialization}} } struct B { // POD struct. int x; int *y; }; B getB() { return B(); }; B getB(int x) { return B(); }; B getB(int *x) { return B(); }; B getB(B *b) { return B(); }; void setupB() { B b1; B b2(b1); B b3 = { 5, &b3.x }; B b4 = getB(); B b5 = getB(&b5); B b6 = getB(&b6.x); // Silence unused warning (void) b2; (void) b4; B b7(b7); // expected-warning {{variable 'b7' is uninitialized when used within its own initialization}} B b8 = getB(b8.x); // expected-warning {{variable 'b8' is uninitialized when used within its own initialization}} B b9 = getB(b9.y); // expected-warning {{variable 'b9' is uninitialized when used within its own initialization}} } // Also test similar constructs in a field's initializer. struct S { int x; void *ptr; S(bool (*)[1]) : x(x) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[2]) : x(x + 1) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[3]) : x(x + x) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[4]) : x(static_cast<long>(x) + 1) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[5]) : x(foo(x)) {} // FIXME: This should warn! // These don't actually require the value of x and so shouldn't warn. S(char (*)[1]) : x(sizeof(x)) {} // rdar://8610363 S(char (*)[2]) : ptr(&ptr) {} S(char (*)[3]) : x(__alignof__(x)) {} S(char (*)[4]) : x(bar(&x)) {} S(char (*)[5]) : x(boo(x)) {} S(char (*)[6]) : x(far(x)) {} }; struct C { char a[100], *e; } car = { .e = car.a }; // <rdar://problem/10398199> namespace rdar10398199 { class FooBase { protected: ~FooBase() {} }; class Foo : public FooBase { public: operator int&() const; }; void stuff(); template <typename T> class FooImpl : public Foo { T val; public: FooImpl(const T &x) : val(x) {} ~FooImpl() { stuff(); } }; template <typename T> FooImpl<T> makeFoo(const T& x) { return FooImpl<T>(x); } void test() { const Foo &x = makeFoo(42); const int&y = makeFoo(42u); (void)x; (void)y; }; } // PR 12325 - this was a false uninitialized value warning due to // a broken CFG. int pr12325(int params) { int x = ({ while (false) ; int _v = params; if (false) ; _v; // no-warning }); return x; } <commit_msg>Add -Wuninitialized test for C++11 lambdas.<commit_after>// RUN: %clang_cc1 -fsyntax-only -Wall -Wuninitialized -std=c++11 -verify %s int foo(int x); int bar(int* x); int boo(int& x); int far(const int& x); // Test self-references within initializers which are guaranteed to be // uninitialized. int a = a; // no-warning: used to signal intended lack of initialization. int b = b + 1; // expected-warning {{variable 'b' is uninitialized when used within its own initialization}} int c = (c + c); // expected-warning 2 {{variable 'c' is uninitialized when used within its own initialization}} void test() { int d = ({ d + d ;}); // expected-warning {{variable 'd' is uninitialized when used within its own initialization}} } int e = static_cast<long>(e) + 1; // expected-warning {{variable 'e' is uninitialized when used within its own initialization}} int f = foo(f); // expected-warning {{variable 'f' is uninitialized when used within its own initialization}} // Thes don't warn as they don't require the value. int g = sizeof(g); void* ptr = &ptr; int h = bar(&h); int i = boo(i); int j = far(j); int k = __alignof__(k); // Test self-references with record types. class A { // Non-POD class. public: enum count { ONE, TWO, THREE }; int num; static int count; int get() const { return num; } int get2() { return num; } void set(int x) { num = x; } static int zero() { return 0; } A() {} A(A const &a) {} A(int x) {} A(int *x) {} A(A *a) {} ~A(); }; A getA() { return A(); } A getA(int x) { return A(); } A getA(A* a) { return A(); } void setupA() { A a1; a1.set(a1.get()); A a2(a1.get()); A a3(a1); A a4(&a4); A a5(a5.zero()); A a6(a6.ONE); A a7 = getA(); A a8 = getA(a8.TWO); A a9 = getA(&a9); A a10(a10.count); A a11(a11); // expected-warning {{variable 'a11' is uninitialized when used within its own initialization}} A a12(a12.get()); // expected-warning {{variable 'a12' is uninitialized when used within its own initialization}} A a13(a13.num); // expected-warning {{variable 'a13' is uninitialized when used within its own initialization}} A a14 = A(a14); // expected-warning {{variable 'a14' is uninitialized when used within its own initialization}} A a15 = getA(a15.num); // expected-warning {{variable 'a15' is uninitialized when used within its own initialization}} A a16(&a16.num); // expected-warning {{variable 'a16' is uninitialized when used within its own initialization}} A a17(a17.get2()); // expected-warning {{variable 'a17' is uninitialized when used within its own initialization}} } struct B { // POD struct. int x; int *y; }; B getB() { return B(); }; B getB(int x) { return B(); }; B getB(int *x) { return B(); }; B getB(B *b) { return B(); }; void setupB() { B b1; B b2(b1); B b3 = { 5, &b3.x }; B b4 = getB(); B b5 = getB(&b5); B b6 = getB(&b6.x); // Silence unused warning (void) b2; (void) b4; B b7(b7); // expected-warning {{variable 'b7' is uninitialized when used within its own initialization}} B b8 = getB(b8.x); // expected-warning {{variable 'b8' is uninitialized when used within its own initialization}} B b9 = getB(b9.y); // expected-warning {{variable 'b9' is uninitialized when used within its own initialization}} } // Also test similar constructs in a field's initializer. struct S { int x; void *ptr; S(bool (*)[1]) : x(x) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[2]) : x(x + 1) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[3]) : x(x + x) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[4]) : x(static_cast<long>(x) + 1) {} // expected-warning {{field is uninitialized when used here}} S(bool (*)[5]) : x(foo(x)) {} // FIXME: This should warn! // These don't actually require the value of x and so shouldn't warn. S(char (*)[1]) : x(sizeof(x)) {} // rdar://8610363 S(char (*)[2]) : ptr(&ptr) {} S(char (*)[3]) : x(__alignof__(x)) {} S(char (*)[4]) : x(bar(&x)) {} S(char (*)[5]) : x(boo(x)) {} S(char (*)[6]) : x(far(x)) {} }; struct C { char a[100], *e; } car = { .e = car.a }; // <rdar://problem/10398199> namespace rdar10398199 { class FooBase { protected: ~FooBase() {} }; class Foo : public FooBase { public: operator int&() const; }; void stuff(); template <typename T> class FooImpl : public Foo { T val; public: FooImpl(const T &x) : val(x) {} ~FooImpl() { stuff(); } }; template <typename T> FooImpl<T> makeFoo(const T& x) { return FooImpl<T>(x); } void test() { const Foo &x = makeFoo(42); const int&y = makeFoo(42u); (void)x; (void)y; }; } // PR 12325 - this was a false uninitialized value warning due to // a broken CFG. int pr12325(int params) { int x = ({ while (false) ; int _v = params; if (false) ; _v; // no-warning }); return x; } // Test lambda expressions with -Wuninitialized int test_lambda() { auto f1 = [] (int x, int y) { int z; return x + y + z; }; // expected-warning {{C++11 requires lambda with omitted result type to consist of a single return statement}} expected-warning{{variable 'z' is uninitialized when used here}} expected-note {{initialize the variable 'z' to silence this warning}} return f1(1, 2); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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/url_request/url_request_job_manager.h" #include <algorithm> #include "build/build_config.h" #include "base/string_util.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_about_job.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #if defined(OS_WIN) #include "net/url_request/url_request_ftp_job.h" #else // TODO(playmobil): Implement on non-windows platforms. #endif #include "net/url_request/url_request_http_job.h" #include "net/url_request/url_request_view_cache_job.h" // The built-in set of protocol factories namespace { struct SchemeToFactory { const char* scheme; URLRequest::ProtocolFactory* factory; }; } // namespace static const SchemeToFactory kBuiltinFactories[] = { { "http", URLRequestHttpJob::Factory }, { "https", URLRequestHttpJob::Factory }, { "file", URLRequestFileJob::Factory }, #if defined(OS_WIN) { "ftp", URLRequestFtpJob::Factory }, #else // TODO(playmobil): Implement on non-windows platforms. #endif { "about", URLRequestAboutJob::Factory }, { "view-cache", URLRequestViewCacheJob::Factory }, }; URLRequestJobManager::URLRequestJobManager() { #ifndef NDEBUG allowed_thread_ = 0; allowed_thread_initialized_ = false; #endif } URLRequestJob* URLRequestJobManager::CreateJob(URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif // If we are given an invalid URL, then don't even try to inspect the scheme. if (!request->url().is_valid()) return new URLRequestErrorJob(request, net::ERR_INVALID_URL); // We do this here to avoid asking interceptors about unsupported schemes. const std::string& scheme = request->url().scheme(); // already lowercase if (!SupportsScheme(scheme)) return new URLRequestErrorJob(request, net::ERR_UNKNOWN_URL_SCHEME); // THREAD-SAFETY NOTICE: // We do not need to acquire the lock here since we are only reading our // data structures. They should only be modified on the current thread. // See if the request should be intercepted. if (!(request->load_flags() & net::LOAD_DISABLE_INTERCEPT)) { InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeIntercept(request); if (job) return job; } } // See if the request should be handled by a registered protocol factory. // If the registered factory returns null, then we want to fall-back to the // built-in protocol factory. FactoryMap::const_iterator i = factories_.find(scheme); if (i != factories_.end()) { URLRequestJob* job = i->second(request, scheme); if (job) return job; } // See if the request should be handled by a built-in protocol factory. for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { if (scheme == kBuiltinFactories[i].scheme) { URLRequestJob* job = (kBuiltinFactories[i].factory)(request, scheme); DCHECK(job); // The built-in factories are not expected to fail! return job; } } // If we reached here, then it means that a registered protocol factory // wasn't interested in handling the URL. That is fairly unexpected, and we // don't know have a specific error to report here :-( return new URLRequestErrorJob(request, net::ERR_FAILED); } URLRequestJob* URLRequestJobManager::MaybeInterceptRedirect( URLRequest* request, const GURL& location) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptRedirect(request, location); if (job) return job; } return NULL; } URLRequestJob* URLRequestJobManager::MaybeInterceptResponse( URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptResponse(request); if (job) return job; } return NULL; } bool URLRequestJobManager::SupportsScheme(const std::string& scheme) const { // The set of registered factories may change on another thread. { AutoLock locked(lock_); if (factories_.find(scheme) != factories_.end()) return true; } for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme)) return true; return false; } URLRequest::ProtocolFactory* URLRequestJobManager::RegisterProtocolFactory( const std::string& scheme, URLRequest::ProtocolFactory* factory) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); URLRequest::ProtocolFactory* old_factory; FactoryMap::iterator i = factories_.find(scheme); if (i != factories_.end()) { old_factory = i->second; } else { old_factory = NULL; } if (factory) { factories_[scheme] = factory; } else if (i != factories_.end()) { // uninstall any old one factories_.erase(i); } return old_factory; } void URLRequestJobManager::RegisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); DCHECK(std::find(interceptors_.begin(), interceptors_.end(), interceptor) == interceptors_.end()); interceptors_.push_back(interceptor); } void URLRequestJobManager::UnregisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); InterceptorList::iterator i = std::find(interceptors_.begin(), interceptors_.end(), interceptor); DCHECK(i != interceptors_.end()); interceptors_.erase(i); } <commit_msg>[Second attempt]<commit_after>// Copyright (c) 2006-2008 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/url_request/url_request_job_manager.h" #include <algorithm> #include "build/build_config.h" #include "base/string_util.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_about_job.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #if defined(OS_WIN) #include "net/url_request/url_request_ftp_job.h" #else #include "net/url_request/url_request_new_ftp_job.h" #endif #include "net/url_request/url_request_http_job.h" #include "net/url_request/url_request_view_cache_job.h" // The built-in set of protocol factories namespace { struct SchemeToFactory { const char* scheme; URLRequest::ProtocolFactory* factory; }; } // namespace static const SchemeToFactory kBuiltinFactories[] = { { "http", URLRequestHttpJob::Factory }, { "https", URLRequestHttpJob::Factory }, { "file", URLRequestFileJob::Factory }, #if defined(OS_WIN) { "ftp", URLRequestFtpJob::Factory }, #else { "ftp", URLRequestNewFtpJob::Factory }, #endif { "about", URLRequestAboutJob::Factory }, { "view-cache", URLRequestViewCacheJob::Factory }, }; URLRequestJobManager::URLRequestJobManager() { #ifndef NDEBUG allowed_thread_ = 0; allowed_thread_initialized_ = false; #endif } URLRequestJob* URLRequestJobManager::CreateJob(URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif // If we are given an invalid URL, then don't even try to inspect the scheme. if (!request->url().is_valid()) return new URLRequestErrorJob(request, net::ERR_INVALID_URL); // We do this here to avoid asking interceptors about unsupported schemes. const std::string& scheme = request->url().scheme(); // already lowercase if (!SupportsScheme(scheme)) return new URLRequestErrorJob(request, net::ERR_UNKNOWN_URL_SCHEME); // THREAD-SAFETY NOTICE: // We do not need to acquire the lock here since we are only reading our // data structures. They should only be modified on the current thread. // See if the request should be intercepted. if (!(request->load_flags() & net::LOAD_DISABLE_INTERCEPT)) { InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeIntercept(request); if (job) return job; } } // See if the request should be handled by a registered protocol factory. // If the registered factory returns null, then we want to fall-back to the // built-in protocol factory. FactoryMap::const_iterator i = factories_.find(scheme); if (i != factories_.end()) { URLRequestJob* job = i->second(request, scheme); if (job) return job; } // See if the request should be handled by a built-in protocol factory. for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { if (scheme == kBuiltinFactories[i].scheme) { URLRequestJob* job = (kBuiltinFactories[i].factory)(request, scheme); DCHECK(job); // The built-in factories are not expected to fail! return job; } } // If we reached here, then it means that a registered protocol factory // wasn't interested in handling the URL. That is fairly unexpected, and we // don't know have a specific error to report here :-( return new URLRequestErrorJob(request, net::ERR_FAILED); } URLRequestJob* URLRequestJobManager::MaybeInterceptRedirect( URLRequest* request, const GURL& location) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptRedirect(request, location); if (job) return job; } return NULL; } URLRequestJob* URLRequestJobManager::MaybeInterceptResponse( URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptResponse(request); if (job) return job; } return NULL; } bool URLRequestJobManager::SupportsScheme(const std::string& scheme) const { // The set of registered factories may change on another thread. { AutoLock locked(lock_); if (factories_.find(scheme) != factories_.end()) return true; } for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme)) return true; return false; } URLRequest::ProtocolFactory* URLRequestJobManager::RegisterProtocolFactory( const std::string& scheme, URLRequest::ProtocolFactory* factory) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); URLRequest::ProtocolFactory* old_factory; FactoryMap::iterator i = factories_.find(scheme); if (i != factories_.end()) { old_factory = i->second; } else { old_factory = NULL; } if (factory) { factories_[scheme] = factory; } else if (i != factories_.end()) { // uninstall any old one factories_.erase(i); } return old_factory; } void URLRequestJobManager::RegisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); DCHECK(std::find(interceptors_.begin(), interceptors_.end(), interceptor) == interceptors_.end()); interceptors_.push_back(interceptor); } void URLRequestJobManager::UnregisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); InterceptorList::iterator i = std::find(interceptors_.begin(), interceptors_.end(), interceptor); DCHECK(i != interceptors_.end()); interceptors_.erase(i); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Bitcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } <commit_msg>qt: Make error message for failed export a little friendlier<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Bitcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } } <|endoftext|>
<commit_before>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of knor * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __KNOR_DENSE_MATRIX_HPP__ #define __KNOR_DENSE_MATRIX_HPP__ #include <omp.h> #include <cmath> #include <vector> #include <limits> #include "io.hpp" #include "exception.hpp" namespace knor { namespace base { // A rowmajor dense matrix template <typename T> class dense_matrix { private: std::vector<T> mat; size_t nrow; size_t ncol; public: typedef dense_matrix* rawptr; dense_matrix() { nrow = 0; ncol = 0; } dense_matrix(const size_t nrow, const size_t ncol, bool zeros=false) : nrow(nrow), ncol(ncol) { if (zeros) mat.assign(nrow*ncol, 0); else mat.resize(nrow*ncol); } static rawptr create() { return new dense_matrix(); } static rawptr create(const size_t nrow, const size_t ncol, bool zeros=false) { return new dense_matrix(nrow, ncol, zeros); } static rawptr create(dense_matrix* other) { rawptr ret = new dense_matrix(other->get_nrow(), other->get_ncol()); std::copy(other->as_pointer(), other->as_pointer()+(other->get_nrow()*other->get_ncol()), ret->as_pointer()); return ret; } const size_t get_nrow() const { return nrow; } const size_t get_ncol() const { return ncol; } void set_nrow(const size_t nrow) { this->nrow = nrow; } void set_ncol(const size_t ncol) { this->ncol = ncol; } void set(const T* d) { std::copy(&(d[0]), &(d[nrow*ncol]), mat.begin()); } void set_row(const T* d, const size_t rid) { std::copy(&(d[0]), &(d[ncol]), &(mat[rid*ncol])); } /* Do a translation from raw id's to indexes in the distance matrix */ const T& get(const size_t row, const size_t col) { return mat[row*ncol+col]; } void set(const size_t row, const size_t col, const T val) { mat[(row*ncol)+col] = val; } std::vector<T>& as_vector() { return mat; } T* as_pointer() { return &mat[0]; } // dim = 0 is row wise mean // dim = 1 is col wise mean void mean(std::vector<double>& mean, const size_t dim=1) { if (dim == 1) { mean.assign(ncol, 0); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mean[col] += mat[row*ncol+col]; } } for (size_t i = 0; i < mean.size(); i++) mean[i] /= (double)nrow; } else if (dim == 0) { mean.assign(nrow, 0); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mean[row] += mat[row*ncol+col]; } } for (size_t i = 0; i < mean.size(); i++) mean[i] /= (double)ncol; } } dense_matrix* operator-(std::vector<T>& v) { assert(nrow == ncol); dense_matrix* ret = create(this); T* retp = ret->as_pointer(); if (v.size() == nrow) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { retp[row*ncol+col] -= v[row]; } } } else if (v.size() == ncol) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { retp[row*ncol+col] -= v[col]; } } } else { throw parameter_exception("vector size is neither == nrow / ncol"); } return ret; } dense_matrix* operator*(dense_matrix& other) { dense_matrix* res = create(this->nrow, other.get_ncol(), true); double* rp = res->as_pointer(); // lhs is this object and rhs is other #pragma omp parallel for for (size_t lrow = 0; lrow < this->nrow; lrow++) { printf("Thread %d working ...\n", omp_get_thread_num()); for (size_t rrow = 0; rrow < other.get_nrow(); rrow++) { for (size_t rcol = 0; rcol < other.get_ncol(); rcol++) { rp[lrow*other.get_ncol()+rcol] += mat[lrow*ncol+rrow] * other.get(rrow, rcol); } } } return res; } dense_matrix* operator-(dense_matrix& other) { assert(nrow == other.get_nrow() && ncol == other.get_ncol()); dense_matrix* res = create(nrow, ncol); double* rp = res->as_pointer(); double* otherp = other.as_pointer(); for (size_t i = 0; i < nrow*ncol; i++) rp[i] = mat[i] - otherp[i]; return res; } dense_matrix* operator+(dense_matrix& other) { assert(nrow == other.get_nrow() && ncol == other.get_ncol()); dense_matrix* res = create(nrow, ncol); double* rp = res->as_pointer(); double* otherp = other.as_pointer(); for (size_t i = 0; i < nrow*ncol; i++) rp[i] = mat[i] + otherp[i]; return res; } void operator+=(dense_matrix& other) { assert(nrow == other.get_nrow() && ncol == other.get_ncol()); double* otherp = other.as_pointer(); for (size_t i = 0; i < nrow*ncol; i++) mat[i] += otherp[i]; } T frobenius_norm() { T sum = 0; for (size_t i = 0; i < nrow*ncol; i++) sum += mat[i]*mat[i]; return std::sqrt(sum); } void sum(const unsigned axis, std::vector<T>& res) { // column wise if (axis == 0) { res.assign(ncol, 0); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { res[col] += mat[row*ncol+col]; } } } else if (axis == 1) { /* row wise */ res.assign(nrow, 0); #pragma omp parallel for for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { res[row] += mat[row*ncol+col]; } } } else { throw parameter_exception("axis for sum must be 0 or 1"); } } T sum() { T sum = 0; for (size_t i = 0; i < nrow*ncol; i++) sum += mat[i]; return sum; } dense_matrix& operator/=(const T val) { for (size_t i = 0; i < nrow*ncol; i++) mat[i] /= val; return *this; } dense_matrix& operator/=(std::vector<T> v) { if (v.size() == nrow) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mat[row*ncol+col] /= v[row]; } } } else if (v.size() == ncol) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mat[row*ncol+col] /= v[col]; } } } else { throw std::runtime_error("Vector division must have size = nrow/ncol"); } return *this; } // Raise every element to the power `exp` and assign void pow_eq(T exp) { for (size_t i = 0; i < nrow*ncol; i++) mat[i] = std::pow(mat[i], exp); } bool operator==(dense_matrix& other) { if (nrow != other.get_nrow() || ncol != other.get_ncol()) return false; for (size_t i = 0; i < ncol*nrow; i++) { if (mat[i] != other.as_pointer()[i]) return false; } return true; } void copy_from(dense_matrix* dm) { resize(dm->get_nrow(), dm->get_ncol()); std::copy(dm->as_pointer(), dm->as_pointer()+(dm->get_nrow()*dm->get_ncol()), mat.begin()); } void argmax(size_t axis, std::vector<unsigned>& idx) { std::vector<T> vals; // axis = 1: row wise if (axis == 0) { idx.assign(nrow, 0); vals.assign(nrow, std::numeric_limits<double>::min()); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { T val = mat[row*ncol+col]; if (val > vals[row]) { vals[row] = val; idx[row] = col; } } } // axis = 0: col wise } else if (axis == 1) { idx.assign(ncol, 0); vals.assign(ncol, std::numeric_limits<double>::min()); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { T val = mat[row*ncol+col]; if (val > vals[col]) { vals[col] = val; idx[col] = row; } } } } else { throw parameter_exception("axis for argmax must be 0 or 1"); } } void resize(const size_t nrow, const size_t ncol) { mat.resize(nrow*ncol); this->nrow = nrow; this->ncol = ncol; } void print() { print_mat<T>(as_pointer(), nrow, ncol); } }; } } // End namespace knor, base #endif <commit_msg>dense matrix minor methods for fcm<commit_after>/* * Copyright 2016 neurodata (http://neurodata.io/) * Written by Disa Mhembere ([email protected]) * * This file is part of knor * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __KNOR_DENSE_MATRIX_HPP__ #define __KNOR_DENSE_MATRIX_HPP__ #include <omp.h> #include <cmath> #include <vector> #include <limits> #include "io.hpp" #include "exception.hpp" namespace knor { namespace base { // A rowmajor dense matrix template <typename T> class dense_matrix { private: std::vector<T> mat; size_t nrow; size_t ncol; public: typedef dense_matrix* rawptr; dense_matrix() { nrow = 0; ncol = 0; } dense_matrix(const size_t nrow, const size_t ncol, bool zeros=false) : nrow(nrow), ncol(ncol) { if (zeros) mat.assign(nrow*ncol, 0); else mat.resize(nrow*ncol); } static rawptr create() { return new dense_matrix(); } static rawptr create(const size_t nrow, const size_t ncol, bool zeros=false) { return new dense_matrix(nrow, ncol, zeros); } static rawptr create(dense_matrix* other) { rawptr ret = new dense_matrix(other->get_nrow(), other->get_ncol()); std::copy(other->as_pointer(), other->as_pointer()+(other->get_nrow()*other->get_ncol()), ret->as_pointer()); return ret; } const size_t get_nrow() const { return nrow; } const size_t get_ncol() const { return ncol; } void set_nrow(const size_t nrow) { this->nrow = nrow; } void set_ncol(const size_t ncol) { this->ncol = ncol; } void set(const T* d) { std::copy(&(d[0]), &(d[nrow*ncol]), mat.begin()); } void set_row(const T* d, const size_t rid) { std::copy(&(d[0]), &(d[ncol]), &(mat[rid*ncol])); } /* Do a translation from raw id's to indexes in the distance matrix */ const T& get(const size_t row, const size_t col) { return mat[row*ncol+col]; } void set(const size_t row, const size_t col, const T val) { mat[(row*ncol)+col] = val; } std::vector<T>& as_vector() { return mat; } T* as_pointer() { return &mat[0]; } // dim = 0 is row wise mean // dim = 1 is col wise mean void mean(std::vector<double>& mean, const size_t dim=1) { if (dim == 1) { mean.assign(ncol, 0); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mean[col] += mat[row*ncol+col]; } } for (size_t i = 0; i < mean.size(); i++) mean[i] /= (double)nrow; } else if (dim == 0) { mean.assign(nrow, 0); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mean[row] += mat[row*ncol+col]; } } for (size_t i = 0; i < mean.size(); i++) mean[i] /= (double)ncol; } } dense_matrix* operator-(std::vector<T>& v) { assert(nrow == ncol); dense_matrix* ret = create(this); T* retp = ret->as_pointer(); if (v.size() == nrow) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { retp[row*ncol+col] -= v[row]; } } } else if (v.size() == ncol) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { retp[row*ncol+col] -= v[col]; } } } else { throw parameter_exception("vector size is neither == nrow / ncol"); } return ret; } dense_matrix* operator*(dense_matrix& other) { dense_matrix* res = create(this->nrow, other.get_ncol(), true); double* rp = res->as_pointer(); // lhs is this object and rhs is other #pragma omp parallel for for (size_t lrow = 0; lrow < this->nrow; lrow++) { for (size_t rrow = 0; rrow < other.get_nrow(); rrow++) { for (size_t rcol = 0; rcol < other.get_ncol(); rcol++) { rp[lrow*other.get_ncol()+rcol] += mat[lrow*ncol+rrow] * other.get(rrow, rcol); } } } return res; } dense_matrix* operator-(dense_matrix& other) { assert(nrow == other.get_nrow() && ncol == other.get_ncol()); dense_matrix* res = create(nrow, ncol); double* rp = res->as_pointer(); double* otherp = other.as_pointer(); for (size_t i = 0; i < nrow*ncol; i++) rp[i] = mat[i] - otherp[i]; return res; } dense_matrix* operator+(dense_matrix& other) { assert(nrow == other.get_nrow() && ncol == other.get_ncol()); dense_matrix* res = create(nrow, ncol); double* rp = res->as_pointer(); double* otherp = other.as_pointer(); for (size_t i = 0; i < nrow*ncol; i++) rp[i] = mat[i] + otherp[i]; return res; } void operator+=(dense_matrix& other) { assert(nrow == other.get_nrow() && ncol == other.get_ncol()); double* otherp = other.as_pointer(); for (size_t i = 0; i < nrow*ncol; i++) mat[i] += otherp[i]; } void peq(const size_t row, size_t col, T val) { mat[row*ncol+col] += val; } T frobenius_norm() { T sum = 0; for (size_t i = 0; i < nrow*ncol; i++) sum += mat[i]*mat[i]; return std::sqrt(sum); } void zero() { std::fill(mat.begin(), mat.end(), 0); } void sum(const unsigned axis, std::vector<T>& res) { // column wise if (axis == 0) { res.assign(ncol, 0); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { res[col] += mat[row*ncol+col]; } } } else if (axis == 1) { /* row wise */ res.assign(nrow, 0); #pragma omp parallel for for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { res[row] += mat[row*ncol+col]; } } } else { throw parameter_exception("axis for sum must be 0 or 1"); } } T sum() { T sum = 0; for (size_t i = 0; i < nrow*ncol; i++) sum += mat[i]; return sum; } dense_matrix& operator/=(const T val) { for (size_t i = 0; i < nrow*ncol; i++) mat[i] /= val; return *this; } dense_matrix& operator/=(std::vector<T> v) { if (nrow == ncol) throw parameter_exception("Cannot determine which axis " "to div for square matrix."); if (v.size() == nrow) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mat[row*ncol+col] /= v[row]; } } } else if (v.size() == ncol) { for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { mat[row*ncol+col] /= v[col]; } } } else { throw std::runtime_error("Vector division must have size = nrow/ncol"); } return *this; } // Raise every element to the power `exp` and assign void pow_eq(T exp) { for (size_t i = 0; i < nrow*ncol; i++) mat[i] = std::pow(mat[i], exp); } bool operator==(dense_matrix& other) { if (nrow != other.get_nrow() || ncol != other.get_ncol()) return false; for (size_t i = 0; i < ncol*nrow; i++) { if (mat[i] != other.as_pointer()[i]) return false; } return true; } void copy_from(dense_matrix* dm) { resize(dm->get_nrow(), dm->get_ncol()); std::copy(dm->as_pointer(), dm->as_pointer()+(dm->get_nrow()*dm->get_ncol()), mat.begin()); } void argmax(size_t axis, std::vector<unsigned>& idx) { std::vector<T> vals; // axis = 1: row wise if (axis == 0) { idx.assign(nrow, 0); vals.assign(nrow, std::numeric_limits<double>::min()); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { T val = mat[row*ncol+col]; if (val > vals[row]) { vals[row] = val; idx[row] = col; } } } // axis = 0: col wise } else if (axis == 1) { idx.assign(ncol, 0); vals.assign(ncol, std::numeric_limits<double>::min()); for (size_t row = 0; row < nrow; row++) { for (size_t col = 0; col < ncol; col++) { T val = mat[row*ncol+col]; if (val > vals[col]) { vals[col] = val; idx[col] = row; } } } } else { throw parameter_exception("axis for argmax must be 0 or 1"); } } void resize(const size_t nrow, const size_t ncol) { mat.resize(nrow*ncol); this->nrow = nrow; this->ncol = ncol; } void print() { print_mat<T>(as_pointer(), nrow, ncol); } }; } } // End namespace knor, base #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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/url_request/url_request_job_manager.h" #include <algorithm> #include "build/build_config.h" #include "base/string_util.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_about_job.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #if defined(OS_WIN) #include "net/url_request/url_request_ftp_job.h" #else #include "net/url_request/url_request_new_ftp_job.h" #endif #include "net/url_request/url_request_http_job.h" #include "net/url_request/url_request_view_cache_job.h" // The built-in set of protocol factories namespace { struct SchemeToFactory { const char* scheme; URLRequest::ProtocolFactory* factory; }; } // namespace static const SchemeToFactory kBuiltinFactories[] = { { "http", URLRequestHttpJob::Factory }, { "https", URLRequestHttpJob::Factory }, { "file", URLRequestFileJob::Factory }, #if defined(OS_WIN) { "ftp", URLRequestFtpJob::Factory }, #else { "ftp", URLRequestNewFtpJob::Factory }, #endif { "about", URLRequestAboutJob::Factory }, { "view-cache", URLRequestViewCacheJob::Factory }, }; URLRequestJobManager::URLRequestJobManager() { #ifndef NDEBUG allowed_thread_ = 0; allowed_thread_initialized_ = false; #endif } URLRequestJob* URLRequestJobManager::CreateJob(URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif // If we are given an invalid URL, then don't even try to inspect the scheme. if (!request->url().is_valid()) return new URLRequestErrorJob(request, net::ERR_INVALID_URL); // We do this here to avoid asking interceptors about unsupported schemes. const std::string& scheme = request->url().scheme(); // already lowercase if (!SupportsScheme(scheme)) return new URLRequestErrorJob(request, net::ERR_UNKNOWN_URL_SCHEME); // THREAD-SAFETY NOTICE: // We do not need to acquire the lock here since we are only reading our // data structures. They should only be modified on the current thread. // See if the request should be intercepted. if (!(request->load_flags() & net::LOAD_DISABLE_INTERCEPT)) { InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeIntercept(request); if (job) return job; } } // See if the request should be handled by a registered protocol factory. // If the registered factory returns null, then we want to fall-back to the // built-in protocol factory. FactoryMap::const_iterator i = factories_.find(scheme); if (i != factories_.end()) { URLRequestJob* job = i->second(request, scheme); if (job) return job; } // See if the request should be handled by a built-in protocol factory. for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { if (scheme == kBuiltinFactories[i].scheme) { URLRequestJob* job = (kBuiltinFactories[i].factory)(request, scheme); DCHECK(job); // The built-in factories are not expected to fail! return job; } } // If we reached here, then it means that a registered protocol factory // wasn't interested in handling the URL. That is fairly unexpected, and we // don't know have a specific error to report here :-( return new URLRequestErrorJob(request, net::ERR_FAILED); } URLRequestJob* URLRequestJobManager::MaybeInterceptRedirect( URLRequest* request, const GURL& location) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptRedirect(request, location); if (job) return job; } return NULL; } URLRequestJob* URLRequestJobManager::MaybeInterceptResponse( URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptResponse(request); if (job) return job; } return NULL; } bool URLRequestJobManager::SupportsScheme(const std::string& scheme) const { // The set of registered factories may change on another thread. { AutoLock locked(lock_); if (factories_.find(scheme) != factories_.end()) return true; } for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme)) return true; return false; } URLRequest::ProtocolFactory* URLRequestJobManager::RegisterProtocolFactory( const std::string& scheme, URLRequest::ProtocolFactory* factory) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); URLRequest::ProtocolFactory* old_factory; FactoryMap::iterator i = factories_.find(scheme); if (i != factories_.end()) { old_factory = i->second; } else { old_factory = NULL; } if (factory) { factories_[scheme] = factory; } else if (i != factories_.end()) { // uninstall any old one factories_.erase(i); } return old_factory; } void URLRequestJobManager::RegisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); DCHECK(std::find(interceptors_.begin(), interceptors_.end(), interceptor) == interceptors_.end()); interceptors_.push_back(interceptor); } void URLRequestJobManager::UnregisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); InterceptorList::iterator i = std::find(interceptors_.begin(), interceptors_.end(), interceptor); DCHECK(i != interceptors_.end()); interceptors_.erase(i); } <commit_msg>Revert the previous checkin r19037 because it causes test_shell to crash when running LayoutTests/security/block-test.html.<commit_after>// Copyright (c) 2006-2008 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/url_request/url_request_job_manager.h" #include <algorithm> #include "build/build_config.h" #include "base/string_util.h" #include "net/base/load_flags.h" #include "net/base/net_errors.h" #include "net/url_request/url_request_about_job.h" #include "net/url_request/url_request_error_job.h" #include "net/url_request/url_request_file_job.h" #if defined(OS_WIN) #include "net/url_request/url_request_ftp_job.h" #else // TODO(playmobil): Implement on non-windows platforms. #endif #include "net/url_request/url_request_http_job.h" #include "net/url_request/url_request_view_cache_job.h" // The built-in set of protocol factories namespace { struct SchemeToFactory { const char* scheme; URLRequest::ProtocolFactory* factory; }; } // namespace static const SchemeToFactory kBuiltinFactories[] = { { "http", URLRequestHttpJob::Factory }, { "https", URLRequestHttpJob::Factory }, { "file", URLRequestFileJob::Factory }, #if defined(OS_WIN) { "ftp", URLRequestFtpJob::Factory }, #else // TODO(playmobil): Implement on non-windows platforms. #endif { "about", URLRequestAboutJob::Factory }, { "view-cache", URLRequestViewCacheJob::Factory }, }; URLRequestJobManager::URLRequestJobManager() { #ifndef NDEBUG allowed_thread_ = 0; allowed_thread_initialized_ = false; #endif } URLRequestJob* URLRequestJobManager::CreateJob(URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif // If we are given an invalid URL, then don't even try to inspect the scheme. if (!request->url().is_valid()) return new URLRequestErrorJob(request, net::ERR_INVALID_URL); // We do this here to avoid asking interceptors about unsupported schemes. const std::string& scheme = request->url().scheme(); // already lowercase if (!SupportsScheme(scheme)) return new URLRequestErrorJob(request, net::ERR_UNKNOWN_URL_SCHEME); // THREAD-SAFETY NOTICE: // We do not need to acquire the lock here since we are only reading our // data structures. They should only be modified on the current thread. // See if the request should be intercepted. if (!(request->load_flags() & net::LOAD_DISABLE_INTERCEPT)) { InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeIntercept(request); if (job) return job; } } // See if the request should be handled by a registered protocol factory. // If the registered factory returns null, then we want to fall-back to the // built-in protocol factory. FactoryMap::const_iterator i = factories_.find(scheme); if (i != factories_.end()) { URLRequestJob* job = i->second(request, scheme); if (job) return job; } // See if the request should be handled by a built-in protocol factory. for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { if (scheme == kBuiltinFactories[i].scheme) { URLRequestJob* job = (kBuiltinFactories[i].factory)(request, scheme); DCHECK(job); // The built-in factories are not expected to fail! return job; } } // If we reached here, then it means that a registered protocol factory // wasn't interested in handling the URL. That is fairly unexpected, and we // don't know have a specific error to report here :-( return new URLRequestErrorJob(request, net::ERR_FAILED); } URLRequestJob* URLRequestJobManager::MaybeInterceptRedirect( URLRequest* request, const GURL& location) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptRedirect(request, location); if (job) return job; } return NULL; } URLRequestJob* URLRequestJobManager::MaybeInterceptResponse( URLRequest* request) const { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif if ((request->load_flags() & net::LOAD_DISABLE_INTERCEPT) || (request->status().status() == URLRequestStatus::CANCELED) || !request->url().is_valid() || !SupportsScheme(request->url().scheme())) return NULL; InterceptorList::const_iterator i; for (i = interceptors_.begin(); i != interceptors_.end(); ++i) { URLRequestJob* job = (*i)->MaybeInterceptResponse(request); if (job) return job; } return NULL; } bool URLRequestJobManager::SupportsScheme(const std::string& scheme) const { // The set of registered factories may change on another thread. { AutoLock locked(lock_); if (factories_.find(scheme) != factories_.end()) return true; } for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme)) return true; return false; } URLRequest::ProtocolFactory* URLRequestJobManager::RegisterProtocolFactory( const std::string& scheme, URLRequest::ProtocolFactory* factory) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); URLRequest::ProtocolFactory* old_factory; FactoryMap::iterator i = factories_.find(scheme); if (i != factories_.end()) { old_factory = i->second; } else { old_factory = NULL; } if (factory) { factories_[scheme] = factory; } else if (i != factories_.end()) { // uninstall any old one factories_.erase(i); } return old_factory; } void URLRequestJobManager::RegisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); DCHECK(std::find(interceptors_.begin(), interceptors_.end(), interceptor) == interceptors_.end()); interceptors_.push_back(interceptor); } void URLRequestJobManager::UnregisterRequestInterceptor( URLRequest::Interceptor* interceptor) { #ifndef NDEBUG DCHECK(IsAllowedThread()); #endif AutoLock locked(lock_); InterceptorList::iterator i = std::find(interceptors_.begin(), interceptors_.end(), interceptor); DCHECK(i != interceptors_.end()); interceptors_.erase(i); } <|endoftext|>
<commit_before>//solution to exercise 10.25 #include<iostream> #include <functional> #include <algorithm> void wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz) { wy_elimdups(vs); // sort words by size, but maintain alphabetical order for words of the same size std::stable_sort(vs.begin(), vs.end(), [](const std::string &s1, const std::string &s2){return s1.size() < s2.size();}); //using bind and check size auto wc = std::partition(vs.begin(), vs.end(), bind(check_size, std::placeholders::_1, sz)); std::for_each(wc, vs.end(), [](const std::string &s) {std::cout << s;}); } //check_size function to check size bool check_size(const std::vector<int> &vec, std::string :: size_type sz ){ return vec.size() >= sz; } <commit_msg>Update ex10_25.cpp<commit_after>//solution to exercise 10.25 #include<iostream> #include <functional> #include <algorithm> #include<vector> #include<string> void wy_elimdups(std::vector<std::string> &vs) { for (auto element : vs) std::cout << element << " "; std::cout << "\n"; } //check_size function to check size bool check_size( const std::string &vs, const std::vector<std::string>::size_type sz) { return vs.size() >= sz; } void wy_biggies_partition(std::vector<std::string> &vs, const std::vector<std::string>::size_type sz) { wy_elimdups(vs); // sort words by size, but maintain alphabetical order for words of the same size std::stable_sort(vs.begin(), vs.end(), [](const std::string &s1, const std::string &s2){return s1.size() < s2.size(); }); //using bind and check size auto wc = std::partition(vs.begin(), vs.end(),bind(check_size, std::placeholders::_1,sz)); std::for_each(vs.begin(),wc , [](const std::string &s) {std::cout << s<<" "; }); } int main() { return 0; } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013 Danny Y., Rapptz // 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. #ifndef SOL_TABLE_HPP #define SOL_TABLE_HPP #include "proxy.hpp" #include "stack.hpp" #include "function_types.hpp" #include "userdata.hpp" namespace sol { class table : public reference { friend class state; template<typename T, typename U> typename stack::get_return<T>::type single_get(U&& key) const { push(); stack::push(state(), std::forward<U>(key)); lua_gettable(state(), -2); type_assert(state(), -1, type_of<T>()); auto&& result = stack::pop<T>(state()); lua_pop(state(), 1); return result; } template<std::size_t I, typename Tup, typename... Ret> typename std::tuple_element<I, std::tuple<typename stack::get_return<Ret>::type...>>::type element_get(types<Ret...>, Tup&& key) const { typedef typename std::tuple_element<I, std::tuple<Ret...>>::type T; return single_get<T>(std::get<I>(key)); } template<typename Tup, typename... Ret, std::size_t... I> typename return_type<typename stack::get_return<Ret>::type...>::type tuple_get(types<Ret...> t, indices<I...>, Tup&& tup) const { return std::make_tuple(element_get<I>(t, std::forward<Tup>(tup))...); } template<typename Tup, typename Ret> typename stack::get_return<Ret>::type tuple_get(types<Ret> t, indices<0>, Tup&& tup) const { return element_get<0>(t, std::forward<Tup>(tup)); } template<typename... Ret, typename... Keys> typename return_type<typename stack::get_return<Ret>::type...>::type get(types<Ret...> t, Keys&&... keys) const { static_assert(sizeof...(Keys) == sizeof...(Ret), "Must have same number of keys as return values"); return tuple_get(t, t, std::make_tuple(std::forward<Keys>(keys)...)); } public: table() noexcept : reference() {} table(lua_State* L, int index = -1) : reference(L, index) { type_assert(L, index, type::table); } template<typename T, typename Key> bool is(Key&& key) const { push(); stack::push(state(), std::forward<Key>(key)); lua_gettable(state(), -2); auto expected = type_of<T>(); auto actual = lua_type(state(), -1); lua_pop(state(), 1); return (static_cast<int>(expected) == actual) || (expected == type::poly); } template<typename... Ret, typename... Keys> typename return_type<typename stack::get_return<Ret>::type...>::type get(Keys&&... keys) const { return get(types<Ret...>(), std::forward<Keys>(keys)...); } template<typename T, typename U> table& set(T&& key, U&& value) { push(); stack::push(state(), std::forward<T>(key)); stack::push(state(), std::forward<U>(value)); lua_settable(state(), -3); lua_pop(state(), 1); return *this; } template<typename T> table& set_userdata(userdata<T>& user) { return set_userdata(user.name(), user); } template<typename Key, typename T> table& set_userdata(Key&& key, userdata<T>& user) { push(); stack::push(state(), std::forward<Key>(key)); stack::push(state(), user); lua_settable(state(), -3); lua_pop(state(), 1); return *this; } template<typename Key> table create_table(Key&& key, int narr = 0, int nrec = 0) { lua_createtable(state(), narr, nrec); table result(state()); lua_pop(state(), 1); set(std::forward<Key>(key), result); return result; } template<typename Fun> void foreach(Fun&& f) { using Signature = decltype(&Fun::operator()); using Key = typename function_traits<Signature>::template arg<0>; using Value = typename function_traits<Signature>::template arg<1>; push(); lua_pushnil(state()); while (lua_next(state(), -2) != 0) { f(stack::getter<Unqualified<Key>>::get(state(), -2), stack::getter<Unqualified<Value>>::get(state(),-1)); lua_pop(state(), 1); } } template<typename Fun> void foreach_proxy(Fun&& f) { using Signature = decltype(&Fun::operator()); using Key = typename function_traits<Signature>::template arg<0>; push(); lua_pushnil(state()); while (lua_next(state(), -2) != 0) { Key k = stack::getter<Unqualified<Key>>::get(state(), -2); f(k, proxy<table,Key>(*this, k)); lua_pop(state(), 1); } } size_t size() const { push(); return lua_rawlen(state(), -1); } template<typename T> proxy<table, T> operator[](T&& key) { return proxy<table, T>(*this, std::forward<T>(key)); } template<typename T> proxy<const table, T> operator[](T&& key) const { return proxy<const table, T>(*this, std::forward<T>(key)); } void pop(int n = 1) const noexcept { lua_pop(state(), n); } template<typename... Args, typename R, typename Key> table& set_function(Key&& key, R fun_ptr(Args...)){ set_resolved_function(std::forward<Key>(key), fun_ptr); return *this; } template<typename Sig, typename Key> table& set_function(Key&& key, Sig* fun_ptr){ set_resolved_function(std::forward<Key>(key), fun_ptr); return *this; } template<typename... Args, typename R, typename C, typename T, typename Key> table& set_function(Key&& key, R (C::*mem_ptr)(Args...), T&& obj) { set_resolved_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj)); return *this; } template<typename Sig, typename C, typename T, typename Key> table& set_function(Key&& key, Sig C::* mem_ptr, T&& obj) { set_resolved_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj)); return *this; } template<typename... Sig, typename Fx, typename Key> table& set_function(Key&& key, Fx&& fx) { set_fx(types<Sig...>(), std::forward<Key>(key), std::forward<Fx>(fx)); return *this; } private: template<typename R, typename... Args, typename Fx, typename Key, typename = typename std::result_of<Fx(Args...)>::type> void set_fx(types<R(Args...)>, Key&& key, Fx&& fx) { set_resolved_function<R(Args...)>(std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename... Args, typename Fx, typename Key, typename R = typename std::result_of<Fx(Args...)>::type> void set_fx(types<Args...>, Key&& key, Fx&& fx){ set_fx(types<R(Args...)>(), std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename Fx, typename Key> void set_fx(types<>, Key&& key, Fx&& fx) { typedef Unqualified<Unwrap<Fx>> fx_t; typedef decltype(&fx_t::operator()) Sig; set_fx(types<function_signature_t<Sig>>(), std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename... Sig, typename... Args, typename Key> void set_resolved_function(Key&& key, Args&&... args) { std::string fkey(std::forward<Key>(key)); push(); int tabletarget = lua_gettop(state()); stack::push<function_sig_t<Sig...>>(state(), std::forward<Args>(args)...); lua_setfield(state(), tabletarget, fkey.c_str()); pop(); } }; } // sol #endif // SOL_TABLE_HPP <commit_msg>Fixed stack corruption in sol::table<commit_after>// The MIT License (MIT) // Copyright (c) 2013 Danny Y., Rapptz // 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. #ifndef SOL_TABLE_HPP #define SOL_TABLE_HPP #include "proxy.hpp" #include "stack.hpp" #include "function_types.hpp" #include "userdata.hpp" namespace sol { class table : public reference { friend class state; template<typename T, typename U> typename stack::get_return<T>::type single_get(U&& key) const { push(); stack::push(state(), std::forward<U>(key)); lua_gettable(state(), -2); type_assert(state(), -1, type_of<T>()); auto&& result = stack::pop<T>(state()); lua_pop(state(), 1); return result; } template<std::size_t I, typename Tup, typename... Ret> typename std::tuple_element<I, std::tuple<typename stack::get_return<Ret>::type...>>::type element_get(types<Ret...>, Tup&& key) const { typedef typename std::tuple_element<I, std::tuple<Ret...>>::type T; return single_get<T>(std::get<I>(key)); } template<typename Tup, typename... Ret, std::size_t... I> typename return_type<typename stack::get_return<Ret>::type...>::type tuple_get(types<Ret...> t, indices<I...>, Tup&& tup) const { return std::make_tuple(element_get<I>(t, std::forward<Tup>(tup))...); } template<typename Tup, typename Ret> typename stack::get_return<Ret>::type tuple_get(types<Ret> t, indices<0>, Tup&& tup) const { return element_get<0>(t, std::forward<Tup>(tup)); } template<typename... Ret, typename... Keys> typename return_type<typename stack::get_return<Ret>::type...>::type get(types<Ret...> t, Keys&&... keys) const { static_assert(sizeof...(Keys) == sizeof...(Ret), "Must have same number of keys as return values"); return tuple_get(t, t, std::make_tuple(std::forward<Keys>(keys)...)); } public: table() noexcept : reference() {} table(lua_State* L, int index = -1) : reference(L, index) { type_assert(L, index, type::table); } template<typename T, typename Key> bool is(Key&& key) const { push(); stack::push(state(), std::forward<Key>(key)); lua_gettable(state(), -2); auto expected = type_of<T>(); auto actual = lua_type(state(), -1); lua_pop(state(), 2); return (static_cast<int>(expected) == actual) || (expected == type::poly); } template<typename... Ret, typename... Keys> typename return_type<typename stack::get_return<Ret>::type...>::type get(Keys&&... keys) const { return get(types<Ret...>(), std::forward<Keys>(keys)...); } template<typename T, typename U> table& set(T&& key, U&& value) { push(); stack::push(state(), std::forward<T>(key)); stack::push(state(), std::forward<U>(value)); lua_settable(state(), -3); lua_pop(state(), 1); return *this; } template<typename T> table& set_userdata(userdata<T>& user) { return set_userdata(user.name(), user); } template<typename Key, typename T> table& set_userdata(Key&& key, userdata<T>& user) { push(); stack::push(state(), std::forward<Key>(key)); stack::push(state(), user); lua_settable(state(), -3); lua_pop(state(), 1); return *this; } template<typename Key> table create_table(Key&& key, int narr = 0, int nrec = 0) { lua_createtable(state(), narr, nrec); table result(state()); lua_pop(state(), 1); set(std::forward<Key>(key), result); return result; } template<typename Fun> void foreach(Fun&& f) { using Signature = decltype(&Fun::operator()); using Key = typename function_traits<Signature>::template arg<0>; using Value = typename function_traits<Signature>::template arg<1>; push(); lua_pushnil(state()); while (lua_next(state(), -2) != 0) { f(stack::getter<Unqualified<Key>>::get(state(), -2), stack::getter<Unqualified<Value>>::get(state(),-1)); lua_pop(state(), 1); } lua_pop(state(), 1); } template<typename Fun> void foreach_proxy(Fun&& f) { using Signature = decltype(&Fun::operator()); using Key = typename function_traits<Signature>::template arg<0>; push(); lua_pushnil(state()); while (lua_next(state(), -2) != 0) { Key k = stack::getter<Unqualified<Key>>::get(state(), -2); f(k, proxy<table,Key>(*this, k)); lua_pop(state(), 1); } lua_pop(state(), 1); } size_t size() const { push(); return lua_rawlen(state(), -1); } template<typename T> proxy<table, T> operator[](T&& key) { return proxy<table, T>(*this, std::forward<T>(key)); } template<typename T> proxy<const table, T> operator[](T&& key) const { return proxy<const table, T>(*this, std::forward<T>(key)); } void pop(int n = 1) const noexcept { lua_pop(state(), n); } template<typename... Args, typename R, typename Key> table& set_function(Key&& key, R fun_ptr(Args...)){ set_resolved_function(std::forward<Key>(key), fun_ptr); return *this; } template<typename Sig, typename Key> table& set_function(Key&& key, Sig* fun_ptr){ set_resolved_function(std::forward<Key>(key), fun_ptr); return *this; } template<typename... Args, typename R, typename C, typename T, typename Key> table& set_function(Key&& key, R (C::*mem_ptr)(Args...), T&& obj) { set_resolved_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj)); return *this; } template<typename Sig, typename C, typename T, typename Key> table& set_function(Key&& key, Sig C::* mem_ptr, T&& obj) { set_resolved_function(std::forward<Key>(key), mem_ptr, std::forward<T>(obj)); return *this; } template<typename... Sig, typename Fx, typename Key> table& set_function(Key&& key, Fx&& fx) { set_fx(types<Sig...>(), std::forward<Key>(key), std::forward<Fx>(fx)); return *this; } private: template<typename R, typename... Args, typename Fx, typename Key, typename = typename std::result_of<Fx(Args...)>::type> void set_fx(types<R(Args...)>, Key&& key, Fx&& fx) { set_resolved_function<R(Args...)>(std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename... Args, typename Fx, typename Key, typename R = typename std::result_of<Fx(Args...)>::type> void set_fx(types<Args...>, Key&& key, Fx&& fx){ set_fx(types<R(Args...)>(), std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename Fx, typename Key> void set_fx(types<>, Key&& key, Fx&& fx) { typedef Unqualified<Unwrap<Fx>> fx_t; typedef decltype(&fx_t::operator()) Sig; set_fx(types<function_signature_t<Sig>>(), std::forward<Key>(key), std::forward<Fx>(fx)); } template<typename... Sig, typename... Args, typename Key> void set_resolved_function(Key&& key, Args&&... args) { std::string fkey(std::forward<Key>(key)); push(); int tabletarget = lua_gettop(state()); stack::push<function_sig_t<Sig...>>(state(), std::forward<Args>(args)...); lua_setfield(state(), tabletarget, fkey.c_str()); pop(); } }; } // sol #endif // SOL_TABLE_HPP <|endoftext|>
<commit_before>/** \brief A tool for rewriting information in ssoar data * \author Johannes Riedl * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_map> #include <unordered_set> #include <cstdio> #include <cstdlib> #include <cstring> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--input-format=(marc-21|marc-xml)] marc_input marc_output\n"; std::exit(EXIT_FAILURE); } void Assemble773Article(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &year = "", const std::string &pages = "", const std::string &volinfo = "", const std::string &edition = "") { if (not (title.empty() and volinfo.empty() and pages.empty() and year.empty() and edition.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) _773subfields->addSubfield('a', StringUtil::Trim(title)); if (not volinfo.empty()) _773subfields->addSubfield('g', "volume: " + volinfo); if (not pages.empty()) _773subfields->addSubfield('g', "pages: " + pages); if (not year.empty()) _773subfields->addSubfield('g', "year: " + year); if (not edition.empty()) _773subfields->addSubfield('g', "edition: " + edition); } void Assemble773Book(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &authors = "", const std::string &year = "", const std::string &pages = "", const std::string &isbn = "") { if (not (title.empty() and authors.empty() and year.empty() and pages.empty() and isbn.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) { if (not authors.empty()) _773subfields->addSubfield('t', StringUtil::Trim(title)); else _773subfields->addSubfield('a', StringUtil::Trim(title)); } if (not authors.empty()) _773subfields->addSubfield('a', authors); if (not year.empty()) _773subfields->addSubfield('d', year); if ( not pages.empty()) _773subfields->addSubfield('g', "pages:" + pages); if (not isbn.empty()) _773subfields->addSubfield('o', isbn); } void ParseSuperior(const std::string &_500aContent, MARC::Subfields * const _773subfields) { // Belegung nach BSZ-Konkordanz // 773 $a "Geistiger Schöpfer" // 773 08 $i "Beziehungskennzeichnung" (== Übergerordnetes Werk) // 773 $d Jahr // 773 $t Titel (wenn Autor nicht vorhanden, dann stattdessen $a) // 773 $g Bandzählung [und weitere Angaben] // 773 $o "Sonstige Identifier für die andere Ausgabe" (ISBN) // 500 Structure for books // Must be checked first since it is more explicit // Normally it is Author(s) : Title. Year. S. xxx. ISBN static const std::string book_regex_1("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*S\\.\\s*([\\d\\-]+)\\.\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(book_regex)); // Authors : Title. Year. Pages static const std::string book_regex_2("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\sS\\.\\s([\\d\\-]+))"); static RegexMatcher * const book_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_1)); // Authors : Title. Year. ISBN static const std::string book_regex_3("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_2)); // 500 Structure fields for articles // Normally Journal ; Edition String ; Page (??) static const std::string article_regex_1("^([^;]*)\\s*;\\s*([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(article_regex)); // Journal; Pages static const std::string article_regex_2("^([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_1)); // Journal (Year) static const std::string article_regex_3("^(.*)\\s*\\((\\d{4})\\)"); static RegexMatcher * const article_matcher_3(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_2)); if (book_matcher_1->matched(_500aContent)) { const std::string authors((*book_matcher_1)[1]); const std::string title((*book_matcher_1)[2]); const std::string year((*book_matcher_1)[3]); const std::string pages((*book_matcher_1)[4]); const std::string isbn((*book_matcher_1)[5]); Assemble773Book(_773subfields, title, authors, year, pages, isbn); } else if (book_matcher_2->matched(_500aContent)) { const std::string authors((*book_matcher_2)[1]); const std::string title((*book_matcher_2)[2]); const std::string year((*book_matcher_2)[3]); Assemble773Book(_773subfields, title, authors, year); } else if (book_matcher_3->matched(_500aContent)) { const std::string authors((*book_matcher_3)[1]); const std::string title((*book_matcher_3)[2]); const std::string year((*book_matcher_3)[3]); const std::string isbn((*book_matcher_3)[4]); Assemble773Book(_773subfields, title, authors, year, "", isbn); } else if (article_matcher_1->matched(_500aContent)) { const std::string title((*article_matcher_1)[1]); const std::string volinfo((*article_matcher_1)[2]); const std::string page((*article_matcher_1)[3]); Assemble773Article(_773subfields, title, "", page, volinfo, ""); } else if (article_matcher_2->matched(_500aContent)) { // See whether we can extract further information const std::string title_and_spec((*article_matcher_2)[1]); const std::string pages((*article_matcher_2)[2]); static const std::string title_and_spec_regex("^([^(]*)\\s*\\((\\d{4})\\)\\s*(\\d+)\\s*"); static RegexMatcher * const title_and_spec_matcher(RegexMatcher::RegexMatcherFactoryOrDie(title_and_spec_regex)); if (title_and_spec_matcher->matched(title_and_spec)) { const std::string title((*title_and_spec_matcher)[1]); const std::string year((*title_and_spec_matcher)[2]); const std::string edition((*title_and_spec_matcher)[3]); Assemble773Article(_773subfields, title, year, pages, "", edition); } else Assemble773Article(_773subfields, title_and_spec, "", pages); } else if (article_matcher_3->matched(_500aContent)) { const std::string title((*article_matcher_3)[1]); const std::string year((*article_matcher_3)[2]); Assemble773Article(_773subfields, title, year); } else LOG_WARNING("No matching regex for " + _500aContent); } void InsertSigelTo003(MARC::Record * const record, bool * const modified_record) { record->insertField("003", "INSERT_VALID_SIGEL_HERE"); *modified_record = true; } // Rewrite to 041$h or get date from 008 void InsertLanguageInto041(MARC::Record * const record, bool * const modified_record) { for (auto &field : record->getTagRange("041")) { if (field.hasSubfield('h')) return; // Possibly the information is already in the $a field static const std::string valid_language_regex("([a-zA-Z]{3})$"); static RegexMatcher * const valid_language_matcher(RegexMatcher::RegexMatcherFactoryOrDie(valid_language_regex)); std::string language; if (valid_language_matcher->matched(field.getFirstSubfieldWithCode('a'))) { field.replaceSubfieldCode('a', 'h'); *modified_record = true; return; } else { const std::string _008Field(record->getFirstFieldContents("008")); if (not valid_language_matcher->matched(_008Field)) { LOG_WARNING("Invalid language code " + language); continue; } record->addSubfield("041", 'h', language); *modified_record = true; return; } } } void InsertYearTo264c(MARC::Record * const record, bool * const modified_record) { for (auto field : record->getTagRange("264")) { if (field.hasSubfieldCode('c')) return; // Extract year from 008 if available const std::string _008Field(record->getFirstFieldContents("008")); const std::string year(_008Field.substr(7,4)); record->addSubfield("264", 'c', year); *modified_record = true; return; } } void RewriteSuperiorReference(MARC::Record * const record, bool * const modified_record) { if (record->findTag("773") != record->end()) return; // Check if we have matching 500 field const std::string superior_string("^In:[\\s]*(.*)"); RegexMatcher * const superior_matcher(RegexMatcher::RegexMatcherFactory(superior_string)); for (auto &field : record->getTagRange("500")) { const auto subfields(field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == 'a' and superior_matcher->matched(subfield.value_)) { MARC::Subfields new773Subfields; // Parse Field Contents ParseSuperior((*superior_matcher)[1], &new773Subfields); // Write 773 Field if (not new773Subfields.empty()) { record->insertField("773", new773Subfields, '0', '8'); *modified_record = true; } } } } } void ProcessRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer) { unsigned record_count(0), modified_count(0); while (MARC::Record record = marc_reader->read()) { ++record_count; bool modified_record(false); InsertSigelTo003(&record, &modified_record); InsertLanguageInto041(&record, &modified_record); InsertYearTo264c(&record, &modified_record); RewriteSuperiorReference(&record, &modified_record); marc_writer->write(record); if (modified_record) ++modified_count; } LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records"); } } // unnamed namespace int Main(int argc, char **argv) { ::progname = argv[0]; MARC::FileType reader_type(MARC::FileType::AUTO); if (argc == 4) { if (std::strcmp(argv[1], "--input-format=marc-21") == 0) reader_type = MARC::FileType::BINARY; else if (std::strcmp(argv[1], "--input-format=marc-xml") == 0) reader_type = MARC::FileType::XML; else Usage(); ++argv, --argc; } if (argc != 3) Usage(); const std::string marc_input_filename(argv[1]); const std::string marc_output_filename(argv[2]); if (unlikely(marc_input_filename == marc_output_filename)) LOG_ERROR("Title data input file name equals output file name!"); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, reader_type)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename)); ProcessRecords(marc_reader.get() , marc_writer.get()); return EXIT_SUCCESS; } <commit_msg>Added missing empty line<commit_after>/** \brief A tool for rewriting information in ssoar data * \author Johannes Riedl * * \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_map> #include <unordered_set> #include <cstdio> #include <cstdlib> #include <cstring> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "MiscUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "TextUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " [--input-format=(marc-21|marc-xml)] marc_input marc_output\n"; std::exit(EXIT_FAILURE); } void Assemble773Article(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &year = "", const std::string &pages = "", const std::string &volinfo = "", const std::string &edition = "") { if (not (title.empty() and volinfo.empty() and pages.empty() and year.empty() and edition.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) _773subfields->addSubfield('a', StringUtil::Trim(title)); if (not volinfo.empty()) _773subfields->addSubfield('g', "volume: " + volinfo); if (not pages.empty()) _773subfields->addSubfield('g', "pages: " + pages); if (not year.empty()) _773subfields->addSubfield('g', "year: " + year); if (not edition.empty()) _773subfields->addSubfield('g', "edition: " + edition); } void Assemble773Book(MARC::Subfields * const _773subfields, const std::string &title = "", const std::string &authors = "", const std::string &year = "", const std::string &pages = "", const std::string &isbn = "") { if (not (title.empty() and authors.empty() and year.empty() and pages.empty() and isbn.empty())) _773subfields->addSubfield('i', "In:"); if (not title.empty()) { if (not authors.empty()) _773subfields->addSubfield('t', StringUtil::Trim(title)); else _773subfields->addSubfield('a', StringUtil::Trim(title)); } if (not authors.empty()) _773subfields->addSubfield('a', authors); if (not year.empty()) _773subfields->addSubfield('d', year); if ( not pages.empty()) _773subfields->addSubfield('g', "pages:" + pages); if (not isbn.empty()) _773subfields->addSubfield('o', isbn); } void ParseSuperior(const std::string &_500aContent, MARC::Subfields * const _773subfields) { // Belegung nach BSZ-Konkordanz // 773 $a "Geistiger Schöpfer" // 773 08 $i "Beziehungskennzeichnung" (== Übergerordnetes Werk) // 773 $d Jahr // 773 $t Titel (wenn Autor nicht vorhanden, dann stattdessen $a) // 773 $g Bandzählung [und weitere Angaben] // 773 $o "Sonstige Identifier für die andere Ausgabe" (ISBN) // 500 Structure for books // Must be checked first since it is more explicit // Normally it is Author(s) : Title. Year. S. xxx. ISBN static const std::string book_regex_1("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*S\\.\\s*([\\d\\-]+)\\.\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(book_regex)); // Authors : Title. Year. Pages static const std::string book_regex_2("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\sS\\.\\s([\\d\\-]+))"); static RegexMatcher * const book_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_1)); // Authors : Title. Year. ISBN static const std::string book_regex_3("^([^:]*):\\s*(.+)?\\s*(\\d{4})\\.(?=\\s*ISBN\\s*([\\d\\-X]+))"); static RegexMatcher * const book_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(book_regex_2)); // 500 Structure fields for articles // Normally Journal ; Edition String ; Page (??) static const std::string article_regex_1("^([^;]*)\\s*;\\s*([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher_1(RegexMatcher::RegexMatcherFactoryOrDie(article_regex)); // Journal; Pages static const std::string article_regex_2("^([^;]*)\\s*;\\s*([\\d\\-]*)\\s*"); static RegexMatcher * const article_matcher_2(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_1)); // Journal (Year) static const std::string article_regex_3("^(.*)\\s*\\((\\d{4})\\)"); static RegexMatcher * const article_matcher_3(RegexMatcher::RegexMatcherFactoryOrDie(article_regex_2)); if (book_matcher_1->matched(_500aContent)) { const std::string authors((*book_matcher_1)[1]); const std::string title((*book_matcher_1)[2]); const std::string year((*book_matcher_1)[3]); const std::string pages((*book_matcher_1)[4]); const std::string isbn((*book_matcher_1)[5]); Assemble773Book(_773subfields, title, authors, year, pages, isbn); } else if (book_matcher_2->matched(_500aContent)) { const std::string authors((*book_matcher_2)[1]); const std::string title((*book_matcher_2)[2]); const std::string year((*book_matcher_2)[3]); Assemble773Book(_773subfields, title, authors, year); } else if (book_matcher_3->matched(_500aContent)) { const std::string authors((*book_matcher_3)[1]); const std::string title((*book_matcher_3)[2]); const std::string year((*book_matcher_3)[3]); const std::string isbn((*book_matcher_3)[4]); Assemble773Book(_773subfields, title, authors, year, "", isbn); } else if (article_matcher_1->matched(_500aContent)) { const std::string title((*article_matcher_1)[1]); const std::string volinfo((*article_matcher_1)[2]); const std::string page((*article_matcher_1)[3]); Assemble773Article(_773subfields, title, "", page, volinfo, ""); } else if (article_matcher_2->matched(_500aContent)) { // See whether we can extract further information const std::string title_and_spec((*article_matcher_2)[1]); const std::string pages((*article_matcher_2)[2]); static const std::string title_and_spec_regex("^([^(]*)\\s*\\((\\d{4})\\)\\s*(\\d+)\\s*"); static RegexMatcher * const title_and_spec_matcher(RegexMatcher::RegexMatcherFactoryOrDie(title_and_spec_regex)); if (title_and_spec_matcher->matched(title_and_spec)) { const std::string title((*title_and_spec_matcher)[1]); const std::string year((*title_and_spec_matcher)[2]); const std::string edition((*title_and_spec_matcher)[3]); Assemble773Article(_773subfields, title, year, pages, "", edition); } else Assemble773Article(_773subfields, title_and_spec, "", pages); } else if (article_matcher_3->matched(_500aContent)) { const std::string title((*article_matcher_3)[1]); const std::string year((*article_matcher_3)[2]); Assemble773Article(_773subfields, title, year); } else LOG_WARNING("No matching regex for " + _500aContent); } void InsertSigelTo003(MARC::Record * const record, bool * const modified_record) { record->insertField("003", "INSERT_VALID_SIGEL_HERE"); *modified_record = true; } // Rewrite to 041$h or get date from 008 void InsertLanguageInto041(MARC::Record * const record, bool * const modified_record) { for (auto &field : record->getTagRange("041")) { if (field.hasSubfield('h')) return; // Possibly the information is already in the $a field static const std::string valid_language_regex("([a-zA-Z]{3})$"); static RegexMatcher * const valid_language_matcher(RegexMatcher::RegexMatcherFactoryOrDie(valid_language_regex)); std::string language; if (valid_language_matcher->matched(field.getFirstSubfieldWithCode('a'))) { field.replaceSubfieldCode('a', 'h'); *modified_record = true; return; } else { const std::string _008Field(record->getFirstFieldContents("008")); if (not valid_language_matcher->matched(_008Field)) { LOG_WARNING("Invalid language code " + language); continue; } record->addSubfield("041", 'h', language); *modified_record = true; return; } } } void InsertYearTo264c(MARC::Record * const record, bool * const modified_record) { for (auto field : record->getTagRange("264")) { if (field.hasSubfieldCode('c')) return; // Extract year from 008 if available const std::string _008Field(record->getFirstFieldContents("008")); const std::string year(_008Field.substr(7,4)); record->addSubfield("264", 'c', year); *modified_record = true; return; } } void RewriteSuperiorReference(MARC::Record * const record, bool * const modified_record) { if (record->findTag("773") != record->end()) return; // Check if we have matching 500 field const std::string superior_string("^In:[\\s]*(.*)"); RegexMatcher * const superior_matcher(RegexMatcher::RegexMatcherFactory(superior_string)); for (auto &field : record->getTagRange("500")) { const auto subfields(field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == 'a' and superior_matcher->matched(subfield.value_)) { MARC::Subfields new773Subfields; // Parse Field Contents ParseSuperior((*superior_matcher)[1], &new773Subfields); // Write 773 Field if (not new773Subfields.empty()) { record->insertField("773", new773Subfields, '0', '8'); *modified_record = true; } } } } } void ProcessRecords(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer) { unsigned record_count(0), modified_count(0); while (MARC::Record record = marc_reader->read()) { ++record_count; bool modified_record(false); InsertSigelTo003(&record, &modified_record); InsertLanguageInto041(&record, &modified_record); InsertYearTo264c(&record, &modified_record); RewriteSuperiorReference(&record, &modified_record); marc_writer->write(record); if (modified_record) ++modified_count; } LOG_INFO("Modified " + std::to_string(modified_count) + " of " + std::to_string(record_count) + " records"); } } // unnamed namespace int Main(int argc, char **argv) { ::progname = argv[0]; MARC::FileType reader_type(MARC::FileType::AUTO); if (argc == 4) { if (std::strcmp(argv[1], "--input-format=marc-21") == 0) reader_type = MARC::FileType::BINARY; else if (std::strcmp(argv[1], "--input-format=marc-xml") == 0) reader_type = MARC::FileType::XML; else Usage(); ++argv, --argc; } if (argc != 3) Usage(); const std::string marc_input_filename(argv[1]); const std::string marc_output_filename(argv[2]); if (unlikely(marc_input_filename == marc_output_filename)) LOG_ERROR("Title data input file name equals output file name!"); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename, reader_type)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename)); ProcessRecords(marc_reader.get() , marc_writer.get()); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* kopetecommand.cpp - Command Copyright (c) 2003 by Jason Keirstead <[email protected]> Copyright (c) 2005 by Michel Hermier <[email protected]> Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopetecommand.h" #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include "kopeteuiglobal.h" #include <kauthorized.h> #include <kdebug.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <qstringlist.h> class Kopete::Command::Private { public: QString command; QString help; QString formatString; uint minArgs; int maxArgs; bool processing; Kopete::Command::Types types; }; Kopete::Command::Command( QObject *parent, const QString &command, const char* handlerSlot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs, const KShortcut &cut, const QString &pix ) : KAction( command[0].toUpper() + command.right( command.length() - 1).toLower(), pix, cut, this, SLOT(slotAction()) ,0l, (command.toLower() + QString::fromLatin1("_command")).toLatin1()) , d(new Private) { connect(parent,SIGNAL(destroyed()),this,SLOT(deleteLAter())); init( command, handlerSlot, help, type, formatString, minArgs, maxArgs ); } Kopete::Command::~Command() { delete d; } void Kopete::Command::init( const QString &command, const char* slot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs ) { m_command = command; m_help = help; m_type = type; m_formatString = formatString; m_minArgs = minArgs; m_maxArgs = maxArgs; m_processing = false; if(m_type == Kopete::CommandHandler::Normal ) { QObject::connect(this, SIGNAL( handleCommand(const QString &, Kopete::ChatSession *)), parent(), slot ); } } void Kopete::Command::slotAction() { Kopete::ChatSession *manager = Kopete::ChatSessionManager::self()->activeView()->msgManager(); QString args; if( m_minArgs > 0 ) { args = KInputDialog::getText( i18n("Enter Arguments"), i18n("Enter the arguments to %1:").arg(m_command) ); if( args.isNull() ) return; } processCommand( args, manager, true ); } void Kopete::Command::processCommand( const QString &args, Kopete::ChatSession *manager, bool gui ) { QStringList mArgs = Kopete::CommandHandler::parseArguments( args ); if( m_processing ) { printError( i18n("Alias \"%1\" expands to itself.").arg( text() ), manager, gui ); } else if( mArgs.count() < m_minArgs ) { printError( i18n("\"%1\" requires at least %n argument.", "\"%1\" requires at least %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( m_maxArgs > -1 && (int)mArgs.count() > m_maxArgs ) { printError( i18n("\"%1\" has a maximum of %n argument.", "\"%1\" has a maximum of %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( !KAuthorized::authorizeKAction( name() ) ) { printError( i18n("You are not authorized to perform the command \"%1\".").arg(text()), manager, gui ); } else { m_processing = true; if( m_type == Kopete::CommandHandler::UserAlias || m_type == Kopete::CommandHandler::SystemAlias ) { QString formatString = m_formatString; // Translate %s to the whole string and %n to current nickname formatString.replace( QString::fromLatin1("%n"), manager->myself()->nickName() ); formatString.replace( QString::fromLatin1("%s"), args ); // Translate %1..%N to word1..wordN while( mArgs.count() > 0 ) { formatString = formatString.arg( mArgs.front() ); mArgs.pop_front(); } kdDebug(14010) << "New Command after processing alias: " << formatString << endl; Kopete::CommandHandler::commandHandler()->processMessage( QString::fromLatin1("/") + formatString, manager ); } else { emit( handleCommand( args, manager ) ); } m_processing = false; } } void Kopete::Command::printError( const QString &error, Kopete::ChatSession *manager, bool gui ) const { if( gui ) { KMessageBox::error( Kopete::UI::Global::mainWidget(), error, i18n("Command Error") ); } else { Kopete::Message msg( manager->myself(), manager->members(), error, Kopete::Message::Internal, Kopete::Message::PlainText ); manager->appendMessage( msg ); } } #include "kopetecommand.moc" <commit_msg>Misspelled slot<commit_after>/* kopetecommand.cpp - Command Copyright (c) 2003 by Jason Keirstead <[email protected]> Copyright (c) 2005 by Michel Hermier <[email protected]> Kopete (c) 2002-2005 by the Kopete developers <[email protected]> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopetecommand.h" #include "kopetechatsessionmanager.h" #include "kopeteview.h" #include "kopeteuiglobal.h" #include <kauthorized.h> #include <kdebug.h> #include <kinputdialog.h> #include <klocale.h> #include <kmessagebox.h> #include <qstringlist.h> class Kopete::Command::Private { public: QString command; QString help; QString formatString; uint minArgs; int maxArgs; bool processing; Kopete::Command::Types types; }; Kopete::Command::Command( QObject *parent, const QString &command, const char* handlerSlot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs, const KShortcut &cut, const QString &pix ) : KAction( command[0].toUpper() + command.right( command.length() - 1).toLower(), pix, cut, this, SLOT(slotAction()) ,0l, (command.toLower() + QString::fromLatin1("_command")).toLatin1()) , d(new Private) { connect(parent,SIGNAL(destroyed()),this,SLOT(deleteLater())); init( command, handlerSlot, help, type, formatString, minArgs, maxArgs ); } Kopete::Command::~Command() { delete d; } void Kopete::Command::init( const QString &command, const char* slot, const QString &help, Kopete::CommandHandler::CommandType type, const QString &formatString, uint minArgs, int maxArgs ) { m_command = command; m_help = help; m_type = type; m_formatString = formatString; m_minArgs = minArgs; m_maxArgs = maxArgs; m_processing = false; if(m_type == Kopete::CommandHandler::Normal ) { QObject::connect(this, SIGNAL( handleCommand(const QString &, Kopete::ChatSession *)), parent(), slot ); } } void Kopete::Command::slotAction() { Kopete::ChatSession *manager = Kopete::ChatSessionManager::self()->activeView()->msgManager(); QString args; if( m_minArgs > 0 ) { args = KInputDialog::getText( i18n("Enter Arguments"), i18n("Enter the arguments to %1:").arg(m_command) ); if( args.isNull() ) return; } processCommand( args, manager, true ); } void Kopete::Command::processCommand( const QString &args, Kopete::ChatSession *manager, bool gui ) { QStringList mArgs = Kopete::CommandHandler::parseArguments( args ); if( m_processing ) { printError( i18n("Alias \"%1\" expands to itself.").arg( text() ), manager, gui ); } else if( mArgs.count() < m_minArgs ) { printError( i18n("\"%1\" requires at least %n argument.", "\"%1\" requires at least %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( m_maxArgs > -1 && (int)mArgs.count() > m_maxArgs ) { printError( i18n("\"%1\" has a maximum of %n argument.", "\"%1\" has a maximum of %n arguments.", m_minArgs) .arg( text() ), manager, gui ); } else if( !KAuthorized::authorizeKAction( name() ) ) { printError( i18n("You are not authorized to perform the command \"%1\".").arg(text()), manager, gui ); } else { m_processing = true; if( m_type == Kopete::CommandHandler::UserAlias || m_type == Kopete::CommandHandler::SystemAlias ) { QString formatString = m_formatString; // Translate %s to the whole string and %n to current nickname formatString.replace( QString::fromLatin1("%n"), manager->myself()->nickName() ); formatString.replace( QString::fromLatin1("%s"), args ); // Translate %1..%N to word1..wordN while( mArgs.count() > 0 ) { formatString = formatString.arg( mArgs.front() ); mArgs.pop_front(); } kdDebug(14010) << "New Command after processing alias: " << formatString << endl; Kopete::CommandHandler::commandHandler()->processMessage( QString::fromLatin1("/") + formatString, manager ); } else { emit( handleCommand( args, manager ) ); } m_processing = false; } } void Kopete::Command::printError( const QString &error, Kopete::ChatSession *manager, bool gui ) const { if( gui ) { KMessageBox::error( Kopete::UI::Global::mainWidget(), error, i18n("Command Error") ); } else { Kopete::Message msg( manager->myself(), manager->members(), error, Kopete::Message::Internal, Kopete::Message::PlainText ); manager->appendMessage( msg ); } } #include "kopetecommand.moc" <|endoftext|>
<commit_before>#include "Natives.h" #include <vector> #include <Windows.h> #include <lua.hpp> #include <cstdint> #include <Psapi.h> #include <BeaEngine\BeaEngine.h> #include "BytePattern.h" #include "BytePatternGen.h" #include "PEImage.h" static HMODULE BaseImageModule; static size_t BaseImageModuleSize; static uint32_t GetMaxReadableSize(void *ptr) { MEMORY_BASIC_INFORMATION mbi; if (VirtualQuery(ptr, &mbi, sizeof(mbi)) == 0) { return 0; } DWORD protect = PAGE_GUARD | PAGE_NOCACHE | PAGE_NOACCESS; if (mbi.State & MEM_FREE || !mbi.Protect & protect) { return 0; } return mbi.RegionSize - ((uint32_t)ptr - (uint32_t)mbi.BaseAddress); } void NativesRegister(lua_State *L) { BaseImageModule = GetModuleHandle(NULL); MODULEINFO mi = { 0 }; GetModuleInformation(GetCurrentProcess(), BaseImageModule, &mi, sizeof(mi)); BaseImageModuleSize = mi.SizeOfImage; luaL_newmetatable(L, "luape.pattern"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, [](lua_State *L) -> int { Pattern *pattern = *reinterpret_cast<Pattern **>(luaL_checkudata(L, 1, "luape.pattern")); BytePattern::DestroyPattern(pattern); return 0; }); lua_rawset(L, -3); luaL_newmetatable(L, "luape.peimage"); lua_pushstring(L, "__index"); lua_newtable(L); luaL_Reg pe_methods[] = { { "load", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); const char *path = luaL_checkstring(L, 2); try { image->Load(path); } catch (const std::exception& e) { delete image; return luaL_error(L, "Load PE file failed: %s", e.what()); } return 0; } }, { "unload", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { image->Unload(); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 0; } }, { "getImageBase", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { lua_pushunsigned(L, image->image_base()); } else { lua_pushnil(L); } return 1; } }, { "getSize", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { lua_pushunsigned(L, image->size()); } else { lua_pushnil(L); } return 1; } }, { "getMappedBaseAddress", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { lua_pushunsigned(L, (lua_Unsigned)image->data()); } else { lua_pushnil(L); } return 1; } }, { "findAddressByRVA", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); uint32_t rva = luaL_checkinteger(L, 2); if (image->IsLoaded()) { auto ptr = image->FindPointerByRVA(rva); if (ptr) { lua_pushunsigned(L, (lua_Unsigned)ptr); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { "findRVAByFileOffset", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); uint32_t offset = luaL_checkinteger(L, 2); if (image->IsLoaded()) { auto rva = image->FindRVAByFileOffset(offset); if (rva) { lua_pushunsigned(L, (lua_Unsigned)rva); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { "findFileOffsetByPattern", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { Pattern *p = *reinterpret_cast<Pattern **>(luaL_checkudata(L, 2, "luape.pattern")); const void *ptr = BytePattern::Find(p, image->data(), image->size()); if (ptr) { lua_pushunsigned(L, reinterpret_cast<const uint8_t *>(ptr)-image->data()); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { NULL, NULL } }; luaL_setfuncs(L, pe_methods, 0); lua_rawset(L, -3); lua_pushstring(L, "__gc"); lua_pushcfunction(L, [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); delete image; return 0; }); lua_rawset(L, -3); lua_newtable(L); luaL_Reg natives[] = { { "newPE", [](lua_State *L) -> int { PEImage * image = new PEImage(); if (lua_gettop(L) > 0) { const char *path = luaL_checkstring(L, 1); try { image->Load(path); } catch (const std::exception& e) { delete image; return luaL_error(L, "Load PE file failed: %s", e.what()); } } *reinterpret_cast<PEImage **>(lua_newuserdata(L, sizeof(PEImage *))) = image; luaL_setmetatable(L, "luape.peimage"); return 1; } }, { "generatePatternString", [](lua_State *L) -> int { lua_Unsigned addr = luaL_checkunsigned(L, 1); lua_Unsigned size = GetMaxReadableSize((void *)addr); if (lua_isnumber(L, 2)) { lua_Unsigned size_arg = lua_tounsigned(L, 2); if (size_arg < size) { size = size_arg; } } if (addr && size > 0) { uint8_t *ptr = (uint8_t *)addr; const std::string& pstr = BytePatternGen(ptr, ptr + size); if (pstr.length() > 0) { lua_pushstring(L, pstr.c_str()); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { "selectFile", [](lua_State *L) -> int { const char *title = NULL; if (lua_gettop(L) > 0) { title = luaL_checkstring(L, 1); } char fn[256]; fn[0] = 0; OPENFILENAMEA ofn = { 0 }; ofn.lStructSize = sizeof(ofn); ofn.lpstrFilter = NULL; ofn.lpstrFile = fn; ofn.nMaxFile = sizeof(fn); ofn.nFilterIndex = 1; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; ofn.lpstrTitle = title; if (GetOpenFileNameA(&ofn) && ofn.lpstrFile[0]) { lua_pushstring(L, fn); } else { lua_pushnil(L); } return 1; } }, { "setClipboard", [](lua_State *L) -> int { const char *content = luaL_checkstring(L, 1); int len = strlen(content); if (len > 0) { HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len + 1); memcpy(GlobalLock(hMem), content, len); GlobalUnlock(hMem); OpenClipboard(0); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); } return 0; } }, { "loadLibrary", [](lua_State *L) -> int { const char *name = luaL_checkstring(L, 1); auto module = LoadLibraryA(name); if (!module) { lua_pushfstring(L, "Loadlibrary error: %d", GetLastError()); return lua_error(L); } else { lua_pushlightuserdata(L, module); } return 1; } }, { "freeLibrary", [](lua_State *L) -> int { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); void *module = lua_touserdata(L, 1); if (FreeLibrary(reinterpret_cast<HMODULE>(module)) != TRUE) { lua_pushfstring(L, "FreeLibrary error: %d", GetLastError()); return lua_error(L); } return 0; } }, { "pattern", [](lua_State *L) -> int { const char *pattern = luaL_checkstring(L, 1); if (strlen(pattern) == 0) { lua_pushfstring(L, "empty pattern string"); return lua_error(L); } *reinterpret_cast<Pattern **>(lua_newuserdata(L, sizeof(Pattern *))) = BytePattern::CreatePattern(pattern); luaL_getmetatable(L, "luape.pattern"); lua_setmetatable(L, -2); return 1; } }, { "findPatternOffset", [](lua_State *L) -> int { Pattern *p = *reinterpret_cast<Pattern **>(luaL_checkudata(L, 1, "luape.pattern")); uint8_t *base = reinterpret_cast<uint8_t *>(BaseImageModule); const void *ptr = BytePattern::Find(p, base, BaseImageModuleSize); if (ptr) { lua_pushunsigned(L, reinterpret_cast<const uint8_t *>(ptr)-base); } else { lua_pushnil(L); } return 1; } }, { "getBaseAddress", [](lua_State *L) -> int { lua_pushunsigned(L, reinterpret_cast<uint32_t>(BaseImageModule)); return 1; } }, { "diasm", [](lua_State *L) -> int { lua_Unsigned addr = luaL_checkunsigned(L, 1); int lines = luaL_checkinteger(L, 2); uint32_t size = GetMaxReadableSize((void *)addr); lua_newtable(L); int rv = lua_gettop(L); DISASM d; int len, i = 0; bool error = false; memset(&d, 0, sizeof(DISASM)); d.EIP = (UIntPtr)addr; d.SecurityBlock = size; while (!error && i < lines) { len = Disasm(&d); if (len != UNKNOWN_OPCODE && len != OUT_OF_BLOCK) { lua_pushstring(L, d.CompleteInstr); lua_rawseti(L, rv, i + 1); d.EIP += (UIntPtr)len; ++i; } else { error = true; } } return 1; } }, { NULL, NULL } }; luaL_setfuncs(L, natives, 0); char cwd[MAX_PATH + 1]; GetCurrentDirectoryA(MAX_PATH, cwd); lua_pushstring(L, "cwd"); lua_pushstring(L, cwd); lua_rawset(L, -3); lua_setglobal(L, "luape"); }<commit_msg>reset cwd after selectFile<commit_after>#include "Natives.h" #include <vector> #include <Windows.h> #include <lua.hpp> #include <cstdint> #include <Psapi.h> #include <BeaEngine\BeaEngine.h> #include "BytePattern.h" #include "BytePatternGen.h" #include "PEImage.h" static HMODULE BaseImageModule; static size_t BaseImageModuleSize; static char CWD[MAX_PATH + 1]; static uint32_t GetMaxReadableSize(void *ptr) { MEMORY_BASIC_INFORMATION mbi; if (VirtualQuery(ptr, &mbi, sizeof(mbi)) == 0) { return 0; } DWORD protect = PAGE_GUARD | PAGE_NOCACHE | PAGE_NOACCESS; if (mbi.State & MEM_FREE || !mbi.Protect & protect) { return 0; } return mbi.RegionSize - ((uint32_t)ptr - (uint32_t)mbi.BaseAddress); } void NativesRegister(lua_State *L) { BaseImageModule = GetModuleHandle(NULL); MODULEINFO mi = { 0 }; GetModuleInformation(GetCurrentProcess(), BaseImageModule, &mi, sizeof(mi)); BaseImageModuleSize = mi.SizeOfImage; GetCurrentDirectoryA(MAX_PATH, CWD); luaL_newmetatable(L, "luape.pattern"); lua_pushstring(L, "__gc"); lua_pushcfunction(L, [](lua_State *L) -> int { Pattern *pattern = *reinterpret_cast<Pattern **>(luaL_checkudata(L, 1, "luape.pattern")); BytePattern::DestroyPattern(pattern); return 0; }); lua_rawset(L, -3); luaL_newmetatable(L, "luape.peimage"); lua_pushstring(L, "__index"); lua_newtable(L); luaL_Reg pe_methods[] = { { "load", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); const char *path = luaL_checkstring(L, 2); try { image->Load(path); } catch (const std::exception& e) { delete image; return luaL_error(L, "Load PE file failed: %s", e.what()); } return 0; } }, { "unload", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { image->Unload(); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); } return 0; } }, { "getImageBase", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { lua_pushunsigned(L, image->image_base()); } else { lua_pushnil(L); } return 1; } }, { "getSize", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { lua_pushunsigned(L, image->size()); } else { lua_pushnil(L); } return 1; } }, { "getMappedBaseAddress", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { lua_pushunsigned(L, (lua_Unsigned)image->data()); } else { lua_pushnil(L); } return 1; } }, { "findAddressByRVA", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); uint32_t rva = luaL_checkinteger(L, 2); if (image->IsLoaded()) { auto ptr = image->FindPointerByRVA(rva); if (ptr) { lua_pushunsigned(L, (lua_Unsigned)ptr); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { "findRVAByFileOffset", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); uint32_t offset = luaL_checkinteger(L, 2); if (image->IsLoaded()) { auto rva = image->FindRVAByFileOffset(offset); if (rva) { lua_pushunsigned(L, (lua_Unsigned)rva); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { "findFileOffsetByPattern", [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); if (image->IsLoaded()) { Pattern *p = *reinterpret_cast<Pattern **>(luaL_checkudata(L, 2, "luape.pattern")); const void *ptr = BytePattern::Find(p, image->data(), image->size()); if (ptr) { lua_pushunsigned(L, reinterpret_cast<const uint8_t *>(ptr)-image->data()); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { NULL, NULL } }; luaL_setfuncs(L, pe_methods, 0); lua_rawset(L, -3); lua_pushstring(L, "__gc"); lua_pushcfunction(L, [](lua_State *L) -> int { PEImage *image = *reinterpret_cast<PEImage **>(luaL_checkudata(L, 1, "luape.peimage")); delete image; return 0; }); lua_rawset(L, -3); lua_newtable(L); char cwd[MAX_PATH + 1]; GetCurrentDirectoryA(MAX_PATH, cwd); lua_pushstring(L, "cwd"); lua_pushstring(L, cwd); lua_rawset(L, -3); luaL_Reg natives[] = { { "newPE", [](lua_State *L) -> int { PEImage * image = new PEImage(); if (lua_gettop(L) > 0) { const char *path = luaL_checkstring(L, 1); try { image->Load(path); } catch (const std::exception& e) { delete image; return luaL_error(L, "Load PE file failed: %s", e.what()); } } *reinterpret_cast<PEImage **>(lua_newuserdata(L, sizeof(PEImage *))) = image; luaL_setmetatable(L, "luape.peimage"); return 1; } }, { "generatePatternString", [](lua_State *L) -> int { lua_Unsigned addr = luaL_checkunsigned(L, 1); lua_Unsigned size = GetMaxReadableSize((void *)addr); if (lua_isnumber(L, 2)) { lua_Unsigned size_arg = lua_tounsigned(L, 2); if (size_arg < size) { size = size_arg; } } if (addr && size > 0) { uint8_t *ptr = (uint8_t *)addr; const std::string& pstr = BytePatternGen(ptr, ptr + size); if (pstr.length() > 0) { lua_pushstring(L, pstr.c_str()); } else { lua_pushnil(L); } } else { lua_pushnil(L); } return 1; } }, { "selectFile", [](lua_State *L) -> int { const char *title = NULL; if (lua_gettop(L) > 0) { title = luaL_checkstring(L, 1); } char fn[256]; fn[0] = 0; OPENFILENAMEA ofn = { 0 }; ofn.lStructSize = sizeof(ofn); ofn.lpstrFilter = NULL; ofn.lpstrFile = fn; ofn.nMaxFile = sizeof(fn); ofn.nFilterIndex = 1; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; ofn.lpstrTitle = title; if (GetOpenFileNameA(&ofn) && ofn.lpstrFile[0]) { lua_pushstring(L, fn); } else { lua_pushnil(L); } SetCurrentDirectoryA(CWD); return 1; } }, { "setClipboard", [](lua_State *L) -> int { const char *content = luaL_checkstring(L, 1); int len = strlen(content); if (len > 0) { HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len + 1); memcpy(GlobalLock(hMem), content, len); GlobalUnlock(hMem); OpenClipboard(0); EmptyClipboard(); SetClipboardData(CF_TEXT, hMem); CloseClipboard(); } return 0; } }, { "loadLibrary", [](lua_State *L) -> int { const char *name = luaL_checkstring(L, 1); auto module = LoadLibraryA(name); if (!module) { lua_pushfstring(L, "Loadlibrary error: %d", GetLastError()); return lua_error(L); } else { lua_pushlightuserdata(L, module); } return 1; } }, { "freeLibrary", [](lua_State *L) -> int { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); void *module = lua_touserdata(L, 1); if (FreeLibrary(reinterpret_cast<HMODULE>(module)) != TRUE) { lua_pushfstring(L, "FreeLibrary error: %d", GetLastError()); return lua_error(L); } return 0; } }, { "pattern", [](lua_State *L) -> int { const char *pattern = luaL_checkstring(L, 1); if (strlen(pattern) == 0) { lua_pushfstring(L, "empty pattern string"); return lua_error(L); } *reinterpret_cast<Pattern **>(lua_newuserdata(L, sizeof(Pattern *))) = BytePattern::CreatePattern(pattern); luaL_getmetatable(L, "luape.pattern"); lua_setmetatable(L, -2); return 1; } }, { "findPatternOffset", [](lua_State *L) -> int { Pattern *p = *reinterpret_cast<Pattern **>(luaL_checkudata(L, 1, "luape.pattern")); uint8_t *base = reinterpret_cast<uint8_t *>(BaseImageModule); const void *ptr = BytePattern::Find(p, base, BaseImageModuleSize); if (ptr) { lua_pushunsigned(L, reinterpret_cast<const uint8_t *>(ptr)-base); } else { lua_pushnil(L); } return 1; } }, { "getBaseAddress", [](lua_State *L) -> int { lua_pushunsigned(L, reinterpret_cast<uint32_t>(BaseImageModule)); return 1; } }, { "diasm", [](lua_State *L) -> int { lua_Unsigned addr = luaL_checkunsigned(L, 1); int lines = luaL_checkinteger(L, 2); uint32_t size = GetMaxReadableSize((void *)addr); lua_newtable(L); int rv = lua_gettop(L); DISASM d; int len, i = 0; bool error = false; memset(&d, 0, sizeof(DISASM)); d.EIP = (UIntPtr)addr; d.SecurityBlock = size; while (!error && i < lines) { len = Disasm(&d); if (len != UNKNOWN_OPCODE && len != OUT_OF_BLOCK) { lua_pushstring(L, d.CompleteInstr); lua_rawseti(L, rv, i + 1); d.EIP += (UIntPtr)len; ++i; } else { error = true; } } return 1; } }, { NULL, NULL } }; luaL_setfuncs(L, natives, 0); lua_setglobal(L, "luape"); }<|endoftext|>
<commit_before>// // main.cpp // Sandbox // // Created by Cristiano Costantini on 10/10/15. // Copyright (c) 2015 cristcost.net. All rights reserved. // #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, const char * argv[]) { cout << "Sandbox project for Multiply exercise" << endl; return 0; } <commit_msg>playing with cpp<commit_after>// // main.cpp // Sandbox // // Created by Cristiano Costantini on 10/10/15. // Copyright (c) 2015 cristcost.net. All rights reserved. // #include <iostream> #include <fstream> #include <string> using namespace std; bool validateString(const char* string) { return false; } int main(int argc, const char * argv[]) { if(argc < 3) { cout << "Usage: multiply operand1 operand2" << endl; cout << "Example: multiply 123 321" << endl; exit(0); } if (!validateString(argv[1])) { cout << "Invalid operand 1" << endl; exit(0); } if (!validateString(argv[2])) { cout << "Invalid operand 2" << endl; exit(0); } cout << "Sandbox project for Multiply exercise" << endl; return 0; } <|endoftext|>
<commit_before>#include "editaliasdialog.h" #include "ui_editaliasdialog.h" #include "aliastablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "bitcoingui.h" #include "ui_interface.h" #include "bitcoinrpc.h" #include <QDataWidgetMapper> #include <QMessageBox> using namespace std; using namespace json_spirit; extern int nBestHeight; extern const CRPCTable tableRPC; int64 GetAliasNetworkFee(int nType, int nHeight); EditAliasDialog::EditAliasDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAliasDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->nameEdit, this); ui->transferEdit->setVisible(false); ui->transferLabel->setVisible(false); switch(mode) { case NewDataAlias: setWindowTitle(tr("New Data Alias")); break; case NewAlias: setWindowTitle(tr("New Alias")); break; case EditDataAlias: setWindowTitle(tr("Edit Data Alias")); ui->aliasEdit->setEnabled(false); break; case EditAlias: setWindowTitle(tr("Edit Alias")); ui->aliasEdit->setEnabled(false); break; case TransferAlias: setWindowTitle(tr("Transfer Alias")); ui->aliasEdit->setEnabled(false); ui->nameEdit->setEnabled(false); ui->transferEdit->setVisible(true); ui->transferLabel->setVisible(true); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAliasDialog::~EditAliasDialog() { delete ui; } void EditAliasDialog::setModel(WalletModel* walletModel, AliasTableModel *model) { this->model = model; this->walletModel = walletModel; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->aliasEdit, AliasTableModel::Name); mapper->addMapping(ui->nameEdit, AliasTableModel::Value); } void EditAliasDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAliasDialog::saveCurrentRow() { if(!model || !walletModel) return false; WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { model->editStatus = AliasTableModel::WALLET_UNLOCK_FAILURE; return false; } Array params; string strMethod; int64 newFee; int64 updateFee; std::string newFeeStr, updateFeeStr; QMessageBox::StandardButton retval; switch(mode) { case NewDataAlias: case NewAlias: newFee = 1; QMessageBox::StandardButton retval; updateFee = GetAliasNetworkFee(1, nBestHeight)/COIN; newFeeStr = strprintf("%"PRI64d, newFee); updateFeeStr = strprintf("%"PRI64d, updateFee); retval = QMessageBox::question(this, tr("Confirm new Alias"), tr("Warning: Creating new Alias will cost ") + QString::fromStdString(newFeeStr) + tr(" SYS, and activating will cost ") + QString::fromStdString(updateFeeStr) + " SYS<br><br>" + tr("Are you sure you wish to create an Alias?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { return false; } strMethod = string("aliasnew"); params.push_back(ui->aliasEdit->text().toStdString()); try { Value result = tableRPC.execute(strMethod, params); if (result.type() == array_type) { Array arr = result.get_array(); strMethod = string("aliasactivate"); params.clear(); params.push_back(ui->aliasEdit->text().toStdString()); params.push_back(arr[1].get_str()); params.push_back(ui->nameEdit->text().toStdString()); result = tableRPC.execute(strMethod, params); if (result.type() != null_type) { QMessageBox::information(this, windowTitle(), tr("New Alias created successfully! Alias will be active after 120 confirmations. GUID for the new Alias is: \"%1\"").arg(QString::fromStdString(arr[1].get_str())), QMessageBox::Ok, QMessageBox::Ok); return true; } } } catch (Object& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error creating new Alias: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); break; } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception creating new Alias"), QMessageBox::Ok, QMessageBox::Ok); break; } break; case EditDataAlias: case EditAlias: if(mapper->submit()) { updateFee = GetAliasNetworkFee(2, nBestHeight)/COIN; updateFeeStr = strprintf("%"PRI64d, updateFee); retval = QMessageBox::question(this, tr("Confirm Alias Update"), tr("Warning: Updating Alias will cost ") + QString::fromStdString(updateFeeStr) + "<br><br>" + tr("Are you sure you wish update this Alias?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { return false; } strMethod = string("aliasupdate"); params.push_back(ui->aliasEdit->text().toStdString()); params.push_back(ui->nameEdit->text().toStdString()); try { Value result = tableRPC.execute(strMethod, params); if (result.type() != null_type) { string strResult = result.get_str(); alias = ui->nameEdit->text() + ui->aliasEdit->text(); QMessageBox::information(this, windowTitle(), tr("Alias updated successfully! Update will take effect after 1 confirmation. Transaction Id for the update is: \"%1\"").arg(QString::fromStdString(strResult)), QMessageBox::Ok, QMessageBox::Ok); } } catch (Object& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error updating Alias: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); break; } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception updating Alias"), QMessageBox::Ok, QMessageBox::Ok); break; } } break; case TransferAlias: if(mapper->submit()) { updateFee = GetAliasNetworkFee(2, nBestHeight)/COIN; updateFeeStr = strprintf("%"PRI64d, updateFee); retval = QMessageBox::question(this, tr("Confirm Alias Transfer"), tr("Warning: Transfering Alias will cost ") + QString::fromStdString(updateFeeStr) + " SYS<br><br>" + tr("Are you sure you wish transfer this Alias?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { return false; } strMethod = string("aliasupdate"); params.push_back(ui->aliasEdit->text().toStdString()); params.push_back(ui->nameEdit->text().toStdString()); params.push_back(ui->transferEdit->text().toStdString()); try { Value result = tableRPC.execute(strMethod, params); if (result.type() != null_type) { string strResult = result.get_str(); alias = ui->nameEdit->text() + ui->aliasEdit->text()+ui->transferEdit->text(); QMessageBox::information(this, windowTitle(), tr("Alias transferred successfully! Transaction Id for the update is: \"%1\" <br><br>").arg(QString::fromStdString(strResult)) + tr("Please click refresh after 1 confirmation to update the Alias table."), QMessageBox::Ok, QMessageBox::Ok); } } catch (Object& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error transferring Alias: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); break; } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception transferring Alias"), QMessageBox::Ok, QMessageBox::Ok); break; } } break; } return !alias.isEmpty(); } void EditAliasDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AliasTableModel::OK: // Failed with unknown reason. Just reject. break; case AliasTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AliasTableModel::INVALID_ALIAS: QMessageBox::warning(this, windowTitle(), tr("The entered alias \"%1\" is not a valid Syscoin Alias.").arg(ui->aliasEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AliasTableModel::DUPLICATE_ALIAS: QMessageBox::warning(this, windowTitle(), tr("The entered alias \"%1\" is already taken.").arg(ui->aliasEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AliasTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAliasDialog::getAlias() const { return alias; } void EditAliasDialog::setAlias(const QString &alias) { this->alias = alias; ui->aliasEdit->setText(alias); } <commit_msg>Alias name spaces are trimmed on left and right while creating a new alias with QT interface. If after triming the QString is empty, shows a dialog requesting for trying again, and the on clicking Ok the New Alias Dialog is shown again with the Alias name field reset.<commit_after>#include "editaliasdialog.h" #include "ui_editaliasdialog.h" #include "aliastablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "bitcoingui.h" #include "ui_interface.h" #include "bitcoinrpc.h" #include <QDataWidgetMapper> #include <QMessageBox> using namespace std; using namespace json_spirit; extern int nBestHeight; extern const CRPCTable tableRPC; int64 GetAliasNetworkFee(int nType, int nHeight); EditAliasDialog::EditAliasDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAliasDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->nameEdit, this); ui->transferEdit->setVisible(false); ui->transferLabel->setVisible(false); switch(mode) { case NewDataAlias: setWindowTitle(tr("New Data Alias")); break; case NewAlias: setWindowTitle(tr("New Alias")); break; case EditDataAlias: setWindowTitle(tr("Edit Data Alias")); ui->aliasEdit->setEnabled(false); break; case EditAlias: setWindowTitle(tr("Edit Alias")); ui->aliasEdit->setEnabled(false); break; case TransferAlias: setWindowTitle(tr("Transfer Alias")); ui->aliasEdit->setEnabled(false); ui->nameEdit->setEnabled(false); ui->transferEdit->setVisible(true); ui->transferLabel->setVisible(true); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAliasDialog::~EditAliasDialog() { delete ui; } void EditAliasDialog::setModel(WalletModel* walletModel, AliasTableModel *model) { this->model = model; this->walletModel = walletModel; if(!model) return; mapper->setModel(model); mapper->addMapping(ui->aliasEdit, AliasTableModel::Name); mapper->addMapping(ui->nameEdit, AliasTableModel::Value); } void EditAliasDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAliasDialog::saveCurrentRow() { if(!model || !walletModel) return false; WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { model->editStatus = AliasTableModel::WALLET_UNLOCK_FAILURE; return false; } Array params; string strMethod; int64 newFee; int64 updateFee; std::string newFeeStr, updateFeeStr; QMessageBox::StandardButton retval; switch(mode) { case NewDataAlias: case NewAlias: if (ui->aliasEdit->text().trimmed().isEmpty()) { ui->aliasEdit->setText(""); QMessageBox::information(this, windowTitle(), tr("Empty name for Alias not allowed. Please try again"), QMessageBox::Ok, QMessageBox::Ok); return false; } newFee = 1; QMessageBox::StandardButton retval; updateFee = GetAliasNetworkFee(1, nBestHeight)/COIN; newFeeStr = strprintf("%"PRI64d, newFee); updateFeeStr = strprintf("%"PRI64d, updateFee); retval = QMessageBox::question(this, tr("Confirm new Alias"), tr("Warning: Creating new Alias will cost ") + QString::fromStdString(newFeeStr) + tr(" SYS, and activating will cost ") + QString::fromStdString(updateFeeStr) + " SYS<br><br>" + tr("Are you sure you wish to create an Alias?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { return false; } strMethod = string("aliasnew"); params.push_back(ui->aliasEdit->text().trimmed().toStdString()); try { Value result = tableRPC.execute(strMethod, params); if (result.type() == array_type) { Array arr = result.get_array(); strMethod = string("aliasactivate"); params.clear(); params.push_back(ui->aliasEdit->text().trimmed().toStdString()); params.push_back(arr[1].get_str()); params.push_back(ui->nameEdit->text().toStdString()); result = tableRPC.execute(strMethod, params); if (result.type() != null_type) { QMessageBox::information(this, windowTitle(), tr("New Alias created successfully! Alias will be active after 120 confirmations. GUID for the new Alias is: \"%1\"").arg(QString::fromStdString(arr[1].get_str())), QMessageBox::Ok, QMessageBox::Ok); return true; } } } catch (Object& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error creating new Alias: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); break; } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception creating new Alias"), QMessageBox::Ok, QMessageBox::Ok); break; } break; case EditDataAlias: case EditAlias: if(mapper->submit()) { updateFee = GetAliasNetworkFee(2, nBestHeight)/COIN; updateFeeStr = strprintf("%"PRI64d, updateFee); retval = QMessageBox::question(this, tr("Confirm Alias Update"), tr("Warning: Updating Alias will cost ") + QString::fromStdString(updateFeeStr) + "<br><br>" + tr("Are you sure you wish update this Alias?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { return false; } strMethod = string("aliasupdate"); params.push_back(ui->aliasEdit->text().toStdString()); params.push_back(ui->nameEdit->text().toStdString()); try { Value result = tableRPC.execute(strMethod, params); if (result.type() != null_type) { string strResult = result.get_str(); alias = ui->nameEdit->text() + ui->aliasEdit->text(); QMessageBox::information(this, windowTitle(), tr("Alias updated successfully! Update will take effect after 1 confirmation. Transaction Id for the update is: \"%1\"").arg(QString::fromStdString(strResult)), QMessageBox::Ok, QMessageBox::Ok); } } catch (Object& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error updating Alias: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); break; } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception updating Alias"), QMessageBox::Ok, QMessageBox::Ok); break; } } break; case TransferAlias: if(mapper->submit()) { updateFee = GetAliasNetworkFee(2, nBestHeight)/COIN; updateFeeStr = strprintf("%"PRI64d, updateFee); retval = QMessageBox::question(this, tr("Confirm Alias Transfer"), tr("Warning: Transfering Alias will cost ") + QString::fromStdString(updateFeeStr) + " SYS<br><br>" + tr("Are you sure you wish transfer this Alias?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { return false; } strMethod = string("aliasupdate"); params.push_back(ui->aliasEdit->text().toStdString()); params.push_back(ui->nameEdit->text().toStdString()); params.push_back(ui->transferEdit->text().toStdString()); try { Value result = tableRPC.execute(strMethod, params); if (result.type() != null_type) { string strResult = result.get_str(); alias = ui->nameEdit->text() + ui->aliasEdit->text()+ui->transferEdit->text(); QMessageBox::information(this, windowTitle(), tr("Alias transferred successfully! Transaction Id for the update is: \"%1\" <br><br>").arg(QString::fromStdString(strResult)) + tr("Please click refresh after 1 confirmation to update the Alias table."), QMessageBox::Ok, QMessageBox::Ok); } } catch (Object& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error transferring Alias: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); break; } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception transferring Alias"), QMessageBox::Ok, QMessageBox::Ok); break; } } break; } return !alias.isEmpty(); } void EditAliasDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AliasTableModel::OK: // Failed with unknown reason. Just reject. break; case AliasTableModel::NO_CHANGES: // No changes were made during edit operation. Just reject. break; case AliasTableModel::INVALID_ALIAS: QMessageBox::warning(this, windowTitle(), tr("The entered alias \"%1\" is not a valid Syscoin Alias.").arg(ui->aliasEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AliasTableModel::DUPLICATE_ALIAS: QMessageBox::warning(this, windowTitle(), tr("The entered alias \"%1\" is already taken.").arg(ui->aliasEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AliasTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); break; } return; } QDialog::accept(); } QString EditAliasDialog::getAlias() const { return alias; } void EditAliasDialog::setAlias(const QString &alias) { this->alias = alias; ui->aliasEdit->setText(alias); } <|endoftext|>
<commit_before><commit_msg>Removed unnecessary `friend` declaration and forward declaration.<commit_after><|endoftext|>
<commit_before>//===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==// // // This file defines the function verifier interface, that can be used for some // sanity checking of input to the system. // // Note that this does not provide full 'java style' security and verifications, // instead it just tries to ensure that code is well formed. // // . There are no duplicated names in a symbol table... ie there !exist a val // with the same name as something in the symbol table, but with a different // address as what is in the symbol table... // * Both of a binary operator's parameters are the same type // * Verify that the indices of mem access instructions match other operands // . Verify that arithmetic and other things are only performed on first class // types. No adding structures or arrays. // . All of the constants in a switch statement are of the correct type // . The code is in valid SSA form // . It should be illegal to put a label into any other type (like a structure) // or to return one. [except constant arrays!] // * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad // * PHI nodes must have an entry for each predecessor, with no extras. // . All basic blocks should only end with terminator insts, not contain them // * The entry node to a function must not have predecessors // * All Instructions must be embeded into a basic block // . Verify that none of the Value getType()'s are null. // . Function's cannot take a void typed parameter // * Verify that a function's argument list agrees with it's declared type. // . Verify that arrays and structures have fixed elements: No unsized arrays. // * It is illegal to specify a name for a void value. // * It is illegal to have a internal function that is just a declaration // * It is illegal to have a ret instruction that returns a value that does not // agree with the function return value type. // * Function call argument types match the function prototype // * All other things that are tested by asserts spread about the code... // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Verifier.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/iPHINode.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/iMemory.h" #include "llvm/Argument.h" #include "llvm/SymbolTable.h" #include "llvm/Support/CFG.h" #include "llvm/Support/InstVisitor.h" #include "Support/STLExtras.h" #include <algorithm> namespace { // Anonymous namespace for class struct Verifier : public FunctionPass, InstVisitor<Verifier> { bool Broken; Verifier() : Broken(false) {} virtual const char *getPassName() const { return "Module Verifier"; } bool doInitialization(Module *M) { verifySymbolTable(M->getSymbolTable()); return false; } bool runOnFunction(Function *F) { visit(F); return false; } bool doFinalization(Module *M) { // Scan through, checking all of the external function's linkage now... for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) if ((*I)->isExternal() && (*I)->hasInternalLinkage()) CheckFailed("Function Declaration has Internal Linkage!", (*I)); if (Broken) { cerr << "Broken module found, compilation aborted!\n"; abort(); } return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } // Verification methods... void verifySymbolTable(SymbolTable *ST); void visitFunction(Function *F); void visitBasicBlock(BasicBlock *BB); void visitPHINode(PHINode *PN); void visitBinaryOperator(BinaryOperator *B); void visitCallInst(CallInst *CI); void visitGetElementPtrInst(GetElementPtrInst *GEP); void visitLoadInst(LoadInst *LI); void visitStoreInst(StoreInst *SI); void visitInstruction(Instruction *I); // CheckFailed - A check failed, so print out the condition and the message // that failed. This provides a nice place to put a breakpoint if you want // to see why something is not correct. // inline void CheckFailed(const std::string &Message, const Value *V1 = 0, const Value *V2 = 0) { std::cerr << Message << "\n"; if (V1) { std::cerr << V1 << "\n"; } if (V2) { std::cerr << V2 << "\n"; } Broken = true; } }; } // Assert - We know that cond should be true, if not print an error message. #define Assert(C, M) \ do { if (!(C)) { CheckFailed(M); return; } } while (0) #define Assert1(C, M, V1) \ do { if (!(C)) { CheckFailed(M, V1); return; } } while (0) #define Assert2(C, M, V1, V2) \ do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0) // verifySymbolTable - Verify that a function or module symbol table is ok // void Verifier::verifySymbolTable(SymbolTable *ST) { if (ST == 0) return; // No symbol table to process // Loop over all of the types in the symbol table... for (SymbolTable::iterator TI = ST->begin(), TE = ST->end(); TI != TE; ++TI) for (SymbolTable::type_iterator I = TI->second.begin(), E = TI->second.end(); I != E; ++I) { Value *V = I->second; // Check that there are no void typed values in the symbol table. Values // with a void type cannot be put into symbol tables because they cannot // have names! Assert1(V->getType() != Type::VoidTy, "Values with void type are not allowed to have names!", V); } } // visitFunction - Verify that a function is ok. // void Verifier::visitFunction(Function *F) { if (F->isExternal()) return; verifySymbolTable(F->getSymbolTable()); // Check function arguments... const FunctionType *FT = F->getFunctionType(); const Function::ArgumentListType &ArgList = F->getArgumentList(); Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", F, FT); Assert2(FT->getParamTypes().size() == ArgList.size(), "# formal arguments must match # of arguments for function type!", F, FT); // Check that the argument values match the function type for this function... if (FT->getParamTypes().size() == ArgList.size()) { for (unsigned i = 0, e = ArgList.size(); i != e; ++i) Assert2(ArgList[i]->getType() == FT->getParamType(i), "Argument value does not match function argument type!", ArgList[i], FT->getParamType(i)); } // Check the entry node BasicBlock *Entry = F->getEntryNode(); Assert1(pred_begin(Entry) == pred_end(Entry), "Entry block to function must not have predecessors!", Entry); } // verifyBasicBlock - Verify that a basic block is well formed... // void Verifier::visitBasicBlock(BasicBlock *BB) { Assert1(BB->getTerminator(), "Basic Block does not have terminator!", BB); // Check that the terminator is ok as well... if (isa<ReturnInst>(BB->getTerminator())) { Instruction *I = BB->getTerminator(); Function *F = I->getParent()->getParent(); if (I->getNumOperands() == 0) Assert1(F->getReturnType() == Type::VoidTy, "Function returns no value, but ret instruction found that does!", I); else Assert2(F->getReturnType() == I->getOperand(0)->getType(), "Function return type does not match operand " "type of return inst!", I, F->getReturnType()); } } // visitPHINode - Ensure that a PHI node is well formed. void Verifier::visitPHINode(PHINode *PN) { std::vector<BasicBlock*> Preds(pred_begin(PN->getParent()), pred_end(PN->getParent())); // Loop over all of the incoming values, make sure that there are // predecessors for each one... // for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { // Make sure all of the incoming values are the right types... Assert2(PN->getType() == PN->getIncomingValue(i)->getType(), "PHI node argument type does not agree with PHI node type!", PN, PN->getIncomingValue(i)); BasicBlock *BB = PN->getIncomingBlock(i); std::vector<BasicBlock*>::iterator PI = find(Preds.begin(), Preds.end(), BB); Assert2(PI != Preds.end(), "PHI node has entry for basic block that" " is not a predecessor!", PN, BB); Preds.erase(PI); } // There should be no entries left in the predecessor list... for (std::vector<BasicBlock*>::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) Assert2(0, "PHI node does not have entry for a predecessor basic block!", PN, *I); visitInstruction(PN); } void Verifier::visitCallInst(CallInst *CI) { Assert1(isa<PointerType>(CI->getOperand(0)->getType()), "Called function must be a pointer!", CI); PointerType *FPTy = cast<PointerType>(CI->getOperand(0)->getType()); Assert1(isa<FunctionType>(FPTy->getElementType()), "Called function is not pointer to function type!", CI); FunctionType *FTy = cast<FunctionType>(FPTy->getElementType()); // Verify that the correct number of arguments are being passed if (FTy->isVarArg()) Assert1(CI->getNumOperands()-1 >= FTy->getNumParams(), "Called function requires more parameters than were provided!", CI); else Assert1(CI->getNumOperands()-1 == FTy->getNumParams(), "Incorrect number of arguments passed to called function!", CI); // Verify that all arguments to the call match the function type... for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) Assert2(CI->getOperand(i+1)->getType() == FTy->getParamType(i), "Call parameter type does not match function signature!", CI->getOperand(i+1), FTy->getParamType(i)); } // visitBinaryOperator - Check that both arguments to the binary operator are // of the same type! // void Verifier::visitBinaryOperator(BinaryOperator *B) { Assert2(B->getOperand(0)->getType() == B->getOperand(1)->getType(), "Both operands to a binary operator are not of the same type!", B->getOperand(0), B->getOperand(1)); visitInstruction(B); } void Verifier::visitGetElementPtrInst(GetElementPtrInst *GEP) { const Type *ElTy =MemAccessInst::getIndexedType(GEP->getOperand(0)->getType(), GEP->copyIndices(), true); Assert1(ElTy, "Invalid indices for GEP pointer type!", GEP); Assert2(PointerType::get(ElTy) == GEP->getType(), "GEP is not of right type for indices!", GEP, ElTy); visitInstruction(GEP); } void Verifier::visitLoadInst(LoadInst *LI) { const Type *ElTy = LoadInst::getIndexedType(LI->getOperand(0)->getType(), LI->copyIndices()); Assert1(ElTy, "Invalid indices for load pointer type!", LI); Assert2(ElTy == LI->getType(), "Load is not of right type for indices!", LI, ElTy); visitInstruction(LI); } void Verifier::visitStoreInst(StoreInst *SI) { const Type *ElTy = StoreInst::getIndexedType(SI->getOperand(1)->getType(), SI->copyIndices()); Assert1(ElTy, "Invalid indices for store pointer type!", SI); Assert2(ElTy == SI->getOperand(0)->getType(), "Stored value is not of right type for indices!", SI, ElTy); visitInstruction(SI); } // verifyInstruction - Verify that a non-terminator instruction is well formed. // void Verifier::visitInstruction(Instruction *I) { assert(I->getParent() && "Instruction not embedded in basic block!"); // Check that all uses of the instruction, if they are instructions // themselves, actually have parent basic blocks. If the use is not an // instruction, it is an error! // for (User::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) { Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!", *UI); Instruction *Used = cast<Instruction>(*UI); Assert2(Used->getParent() != 0, "Instruction referencing instruction not" " embeded in a basic block!", I, Used); } if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) Assert1(*UI != (User*)I, "Only PHI nodes may reference their own value!", I); } Assert1(I->getType() != Type::VoidTy || !I->hasName(), "Instruction has a name, but provides a void value!", I); } //===----------------------------------------------------------------------===// // Implement the public interfaces to this file... //===----------------------------------------------------------------------===// Pass *createVerifierPass() { return new Verifier(); } bool verifyFunction(const Function *F) { Verifier V; V.visit((Function*)F); return V.Broken; } // verifyModule - Check a module for errors, printing messages on stderr. // Return true if the module is corrupt. // bool verifyModule(const Module *M) { Verifier V; V.run((Module*)M); return V.Broken; } <commit_msg>* Update to work with Megapatch * Add two new checks: * PHI nodes must be the first thing in a basic block, all grouped together * All basic blocks should only end with terminator insts, not contain them<commit_after>//===-- Verifier.cpp - Implement the Module Verifier -------------*- C++ -*-==// // // This file defines the function verifier interface, that can be used for some // sanity checking of input to the system. // // Note that this does not provide full 'java style' security and verifications, // instead it just tries to ensure that code is well formed. // // . There are no duplicated names in a symbol table... ie there !exist a val // with the same name as something in the symbol table, but with a different // address as what is in the symbol table... // * Both of a binary operator's parameters are the same type // * Verify that the indices of mem access instructions match other operands // . Verify that arithmetic and other things are only performed on first class // types. No adding structures or arrays. // . All of the constants in a switch statement are of the correct type // . The code is in valid SSA form // . It should be illegal to put a label into any other type (like a structure) // or to return one. [except constant arrays!] // * Only phi nodes can be self referential: 'add int %0, %0 ; <int>:0' is bad // * PHI nodes must have an entry for each predecessor, with no extras. // * PHI nodes must be the first thing in a basic block, all grouped together // * All basic blocks should only end with terminator insts, not contain them // * The entry node to a function must not have predecessors // * All Instructions must be embeded into a basic block // . Verify that none of the Value getType()'s are null. // . Function's cannot take a void typed parameter // * Verify that a function's argument list agrees with it's declared type. // . Verify that arrays and structures have fixed elements: No unsized arrays. // * It is illegal to specify a name for a void value. // * It is illegal to have a internal function that is just a declaration // * It is illegal to have a ret instruction that returns a value that does not // agree with the function return value type. // * Function call argument types match the function prototype // * All other things that are tested by asserts spread about the code... // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Verifier.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/DerivedTypes.h" #include "llvm/iPHINode.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/iMemory.h" #include "llvm/SymbolTable.h" #include "llvm/Support/CFG.h" #include "llvm/Support/InstVisitor.h" #include "Support/STLExtras.h" #include <algorithm> namespace { // Anonymous namespace for class struct Verifier : public FunctionPass, InstVisitor<Verifier> { bool Broken; Verifier() : Broken(false) {} virtual const char *getPassName() const { return "Module Verifier"; } bool doInitialization(Module &M) { verifySymbolTable(M.getSymbolTable()); return false; } bool runOnFunction(Function &F) { visit(F); return false; } bool doFinalization(Module &M) { // Scan through, checking all of the external function's linkage now... for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (I->isExternal() && I->hasInternalLinkage()) CheckFailed("Function Declaration has Internal Linkage!", I); if (Broken) { cerr << "Broken module found, compilation aborted!\n"; abort(); } return false; } virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } // Verification methods... void verifySymbolTable(SymbolTable *ST); void visitFunction(Function &F); void visitBasicBlock(BasicBlock &BB); void visitPHINode(PHINode &PN); void visitBinaryOperator(BinaryOperator &B); void visitCallInst(CallInst &CI); void visitGetElementPtrInst(GetElementPtrInst &GEP); void visitLoadInst(LoadInst &LI); void visitStoreInst(StoreInst &SI); void visitInstruction(Instruction &I); void visitTerminatorInst(TerminatorInst &I); void visitReturnInst(ReturnInst &RI); // CheckFailed - A check failed, so print out the condition and the message // that failed. This provides a nice place to put a breakpoint if you want // to see why something is not correct. // inline void CheckFailed(const std::string &Message, const Value *V1 = 0, const Value *V2 = 0, const Value *V3 = 0, const Value *V4 = 0) { std::cerr << Message << "\n"; if (V1) std::cerr << *V1 << "\n"; if (V2) std::cerr << *V2 << "\n"; if (V3) std::cerr << *V3 << "\n"; if (V4) std::cerr << *V4 << "\n"; Broken = true; } }; } // Assert - We know that cond should be true, if not print an error message. #define Assert(C, M) \ do { if (!(C)) { CheckFailed(M); return; } } while (0) #define Assert1(C, M, V1) \ do { if (!(C)) { CheckFailed(M, V1); return; } } while (0) #define Assert2(C, M, V1, V2) \ do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0) #define Assert3(C, M, V1, V2, V3) \ do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0) #define Assert4(C, M, V1, V2, V3, V4) \ do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0) // verifySymbolTable - Verify that a function or module symbol table is ok // void Verifier::verifySymbolTable(SymbolTable *ST) { if (ST == 0) return; // No symbol table to process // Loop over all of the types in the symbol table... for (SymbolTable::iterator TI = ST->begin(), TE = ST->end(); TI != TE; ++TI) for (SymbolTable::type_iterator I = TI->second.begin(), E = TI->second.end(); I != E; ++I) { Value *V = I->second; // Check that there are no void typed values in the symbol table. Values // with a void type cannot be put into symbol tables because they cannot // have names! Assert1(V->getType() != Type::VoidTy, "Values with void type are not allowed to have names!", V); } } // visitFunction - Verify that a function is ok. // void Verifier::visitFunction(Function &F) { if (F.isExternal()) return; verifySymbolTable(F.getSymbolTable()); // Check function arguments... const FunctionType *FT = F.getFunctionType(); unsigned NumArgs = F.getArgumentList().size(); Assert2(!FT->isVarArg(), "Cannot define varargs functions in LLVM!", &F, FT); Assert2(FT->getParamTypes().size() == NumArgs, "# formal arguments must match # of arguments for function type!", &F, FT); // Check that the argument values match the function type for this function... if (FT->getParamTypes().size() == NumArgs) { unsigned i = 0; for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++i) Assert2(I->getType() == FT->getParamType(i), "Argument value does not match function argument type!", I, FT->getParamType(i)); } // Check the entry node BasicBlock *Entry = &F.getEntryNode(); Assert1(pred_begin(Entry) == pred_end(Entry), "Entry block to function must not have predecessors!", Entry); } // verifyBasicBlock - Verify that a basic block is well formed... // void Verifier::visitBasicBlock(BasicBlock &BB) { // Ensure that basic blocks have terminators! Assert1(BB.getTerminator(), "Basic Block does not have terminator!", &BB); } void Verifier::visitTerminatorInst(TerminatorInst &I) { // Ensure that terminators only exist at the end of the basic block. Assert1(&I == I.getParent()->getTerminator(), "Terminator found in the middle of a basic block!", I.getParent()); } void Verifier::visitReturnInst(ReturnInst &RI) { Function *F = RI.getParent()->getParent(); if (RI.getNumOperands() == 0) Assert1(F->getReturnType() == Type::VoidTy, "Function returns no value, but ret instruction found that does!", &RI); else Assert2(F->getReturnType() == RI.getOperand(0)->getType(), "Function return type does not match operand " "type of return inst!", &RI, F->getReturnType()); // Check to make sure that the return value has neccesary properties for // terminators... visitTerminatorInst(RI); } // visitPHINode - Ensure that a PHI node is well formed. void Verifier::visitPHINode(PHINode &PN) { // Ensure that the PHI nodes are all grouped together at the top of the block. // This can be tested by checking whether the instruction before this is // either nonexistant (because this is begin()) or is a PHI node. If not, // then there is some other instruction before a PHI. Assert2(PN.getPrev() == 0 || isa<PHINode>(PN.getPrev()), "PHI nodes not grouped at top of basic block!", &PN, PN.getParent()); std::vector<BasicBlock*> Preds(pred_begin(PN.getParent()), pred_end(PN.getParent())); // Loop over all of the incoming values, make sure that there are // predecessors for each one... // for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { // Make sure all of the incoming values are the right types... Assert2(PN.getType() == PN.getIncomingValue(i)->getType(), "PHI node argument type does not agree with PHI node type!", &PN, PN.getIncomingValue(i)); BasicBlock *BB = PN.getIncomingBlock(i); std::vector<BasicBlock*>::iterator PI = find(Preds.begin(), Preds.end(), BB); Assert2(PI != Preds.end(), "PHI node has entry for basic block that" " is not a predecessor!", &PN, BB); Preds.erase(PI); } // There should be no entries left in the predecessor list... for (std::vector<BasicBlock*>::iterator I = Preds.begin(), E = Preds.end(); I != E; ++I) Assert2(0, "PHI node does not have entry for a predecessor basic block!", &PN, *I); // Now we go through and check to make sure that if there is more than one // entry for a particular basic block in this PHI node, that the incoming // values are all identical. // std::vector<std::pair<BasicBlock*, Value*> > Values; Values.reserve(PN.getNumIncomingValues()); for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) Values.push_back(std::make_pair(PN.getIncomingBlock(i), PN.getIncomingValue(i))); // Sort the Values vector so that identical basic block entries are adjacent. std::sort(Values.begin(), Values.end()); // Check for identical basic blocks with differing incoming values... for (unsigned i = 1, e = PN.getNumIncomingValues(); i < e; ++i) Assert4(Values[i].first != Values[i-1].first || Values[i].second == Values[i-1].second, "PHI node has multiple entries for the same basic block with " "different incoming values!", &PN, Values[i].first, Values[i].second, Values[i-1].second); visitInstruction(PN); } void Verifier::visitCallInst(CallInst &CI) { Assert1(isa<PointerType>(CI.getOperand(0)->getType()), "Called function must be a pointer!", &CI); const PointerType *FPTy = cast<PointerType>(CI.getOperand(0)->getType()); Assert1(isa<FunctionType>(FPTy->getElementType()), "Called function is not pointer to function type!", &CI); const FunctionType *FTy = cast<FunctionType>(FPTy->getElementType()); // Verify that the correct number of arguments are being passed if (FTy->isVarArg()) Assert1(CI.getNumOperands()-1 >= FTy->getNumParams(), "Called function requires more parameters than were provided!",&CI); else Assert1(CI.getNumOperands()-1 == FTy->getNumParams(), "Incorrect number of arguments passed to called function!", &CI); // Verify that all arguments to the call match the function type... for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) Assert2(CI.getOperand(i+1)->getType() == FTy->getParamType(i), "Call parameter type does not match function signature!", CI.getOperand(i+1), FTy->getParamType(i)); } // visitBinaryOperator - Check that both arguments to the binary operator are // of the same type! // void Verifier::visitBinaryOperator(BinaryOperator &B) { Assert2(B.getOperand(0)->getType() == B.getOperand(1)->getType(), "Both operands to a binary operator are not of the same type!", B.getOperand(0), B.getOperand(1)); visitInstruction(B); } void Verifier::visitGetElementPtrInst(GetElementPtrInst &GEP) { const Type *ElTy = MemAccessInst::getIndexedType(GEP.getOperand(0)->getType(), GEP.copyIndices(), true); Assert1(ElTy, "Invalid indices for GEP pointer type!", &GEP); Assert2(PointerType::get(ElTy) == GEP.getType(), "GEP is not of right type for indices!", &GEP, ElTy); visitInstruction(GEP); } void Verifier::visitLoadInst(LoadInst &LI) { const Type *ElTy = LoadInst::getIndexedType(LI.getOperand(0)->getType(), LI.copyIndices()); Assert1(ElTy, "Invalid indices for load pointer type!", &LI); Assert2(ElTy == LI.getType(), "Load is not of right type for indices!", &LI, ElTy); visitInstruction(LI); } void Verifier::visitStoreInst(StoreInst &SI) { const Type *ElTy = StoreInst::getIndexedType(SI.getOperand(1)->getType(), SI.copyIndices()); Assert1(ElTy, "Invalid indices for store pointer type!", &SI); Assert2(ElTy == SI.getOperand(0)->getType(), "Stored value is not of right type for indices!", &SI, ElTy); visitInstruction(SI); } // verifyInstruction - Verify that a non-terminator instruction is well formed. // void Verifier::visitInstruction(Instruction &I) { Assert1(I.getParent(), "Instruction not embedded in basic block!", &I); // Check that all uses of the instruction, if they are instructions // themselves, actually have parent basic blocks. If the use is not an // instruction, it is an error! // for (User::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ++UI) { Assert1(isa<Instruction>(*UI), "Use of instruction is not an instruction!", *UI); Instruction *Used = cast<Instruction>(*UI); Assert2(Used->getParent() != 0, "Instruction referencing instruction not" " embeded in a basic block!", &I, Used); } if (!isa<PHINode>(I)) { // Check that non-phi nodes are not self referential for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE; ++UI) Assert1(*UI != (User*)&I, "Only PHI nodes may reference their own value!", &I); } Assert1(I.getType() != Type::VoidTy || !I.hasName(), "Instruction has a name, but provides a void value!", &I); } //===----------------------------------------------------------------------===// // Implement the public interfaces to this file... //===----------------------------------------------------------------------===// Pass *createVerifierPass() { return new Verifier(); } bool verifyFunction(const Function &F) { Verifier V; V.visit((Function&)F); return V.Broken; } // verifyModule - Check a module for errors, printing messages on stderr. // Return true if the module is corrupt. // bool verifyModule(const Module &M) { Verifier V; V.run((Module&)M); return V.Broken; } <|endoftext|>
<commit_before>/* * Syscoin Developers 2014 */ #include "myaliaslistpage.h" #include "ui_myaliaslistpage.h" #include "aliastablemodel.h" #include "clientmodel.h" #include "optionsmodel.h" #include "platformstyle.h" #include "walletmodel.h" #include "syscoingui.h" #include "editaliasdialog.h" #include "mywhitelistofferdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include "rpcserver.h" using namespace std; extern const CRPCTable tableRPC; MyAliasListPage::MyAliasListPage(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::MyAliasListPage), model(0), optionsModel(0), platformStyle(platformStyle) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!platformStyle->getImagesOnButtons()) { ui->exportButton->setIcon(QIcon()); ui->newAlias->setIcon(QIcon()); ui->transferButton->setIcon(QIcon()); ui->editButton->setIcon(QIcon()); ui->copyAlias->setIcon(QIcon()); ui->refreshButton->setIcon(QIcon()); ui->newPubKey->setIcon(QIcon()); ui->whitelistButton->setIcon(QIcon()); } else { ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/export")); ui->newAlias->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add")); ui->transferButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/alias")); ui->editButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editsys")); ui->copyAlias->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editcopy")); ui->refreshButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/refresh")); ui->newPubKey->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add")); ui->whitelistButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/address-book")); } ui->buttonBox->setVisible(false); ui->labelExplanation->setText(tr("These are your registered Syscoin Aliases. Alias operations (create, update, transfer) take 2-5 minutes to become active.")); // Context menu actions QAction *copyAliasAction = new QAction(ui->copyAlias->text(), this); QAction *copyAliasValueAction = new QAction(tr("Copy Va&lue"), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *transferAliasAction = new QAction(tr("&Transfer"), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAliasAction); contextMenu->addAction(copyAliasValueAction); contextMenu->addAction(editAction); contextMenu->addSeparator(); contextMenu->addAction(transferAliasAction); // Connect signals for context menu actions connect(copyAliasAction, SIGNAL(triggered()), this, SLOT(on_copyAlias_clicked())); connect(copyAliasValueAction, SIGNAL(triggered()), this, SLOT(onCopyAliasValueAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(on_editButton_clicked())); connect(transferAliasAction, SIGNAL(triggered()), this, SLOT(on_transferButton_clicked())); connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); } MyAliasListPage::~MyAliasListPage() { delete ui; } void MyAliasListPage::showEvent ( QShowEvent * event ) { if(!walletModel) return; /*if(walletModel->getEncryptionStatus() == WalletModel::Locked) { ui->labelExplanation->setText(tr("<font color='blue'>WARNING: Your wallet is currently locked. For security purposes you'll need to enter your passphrase in order to interact with Syscoin Aliases. Because your wallet is locked you must manually refresh this table after creating or updating an Alias. </font> <a href=\"http://lockedwallet.syscoin.org\">more info</a><br><br>These are your registered Syscoin Aliases. Alias updates take 1 confirmation to appear in this table.")); ui->labelExplanation->setTextFormat(Qt::RichText); ui->labelExplanation->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->labelExplanation->setOpenExternalLinks(true); }*/ } void MyAliasListPage::setModel(WalletModel *walletModel, AliasTableModel *model) { this->model = model; this->walletModel = walletModel; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); // Receive filter proxyModel->setFilterRole(AliasTableModel::TypeRole); proxyModel->setFilterFixedString(AliasTableModel::Alias); ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); // Set column widths ui->tableView->setColumnWidth(0, 500); //alias name ui->tableView->setColumnWidth(1, 500); //alias value ui->tableView->setColumnWidth(2, 75); //expires on ui->tableView->setColumnWidth(3, 75); //expires in ui->tableView->setColumnWidth(4, 75); //expired status ui->tableView->horizontalHeader()->setStretchLastSection(true); connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created alias connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAlias(QModelIndex,int,int))); selectionChanged(); } void MyAliasListPage::setOptionsModel(ClientModel* clientmodel, OptionsModel *optionsModel) { this->optionsModel = optionsModel; this->clientModel = clientmodel; } void MyAliasListPage::on_copyAlias_clicked() { GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Name); } void MyAliasListPage::onCopyAliasValueAction() { GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Value); } void MyAliasListPage::on_editButton_clicked() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAliasDialog dlg(EditAliasDialog::EditAlias); dlg.setModel(walletModel, model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void MyAliasListPage::on_transferButton_clicked() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAliasDialog dlg(EditAliasDialog::TransferAlias); dlg.setModel(walletModel, model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void MyAliasListPage::on_refreshButton_clicked() { if(!model) return; model->refreshAliasTable(); } void MyAliasListPage::on_whitelistButton_clicked() { MyWhitelistOfferDialog dlg(platformStyle); dlg.setModel(walletModel); dlg.exec(); } void MyAliasListPage::on_newAlias_clicked() { if(!model) return; EditAliasDialog dlg(EditAliasDialog::NewAlias); dlg.setModel(walletModel,model); if(dlg.exec()) { newAliasToSelect = dlg.getAlias(); } } void MyAliasListPage::on_newPubKey_clicked() { UniValue params; UniValue result = tableRPC.execute("generatepublickey", params); if (result.type() == UniValue::VARR) { const UniValue &resultArray = result.get_array(); const QString &resQStr = QString::fromStdString(resultArray[0].get_str()); QApplication::clipboard()->setText(resQStr, QClipboard::Clipboard); QApplication::clipboard()->setText(resQStr, QClipboard::Selection); QMessageBox::information(this, tr("New Public Key For Alias Transfer"), resQStr + tr(" has been copied to your clipboard!"), QMessageBox::Ok, QMessageBox::Ok); } else QMessageBox::critical(this, tr("New Public Key For Alias Transfer"), tr("Could not generate a new public key!"), QMessageBox::Ok, QMessageBox::Ok); } void MyAliasListPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { ui->copyAlias->setEnabled(true); ui->transferButton->setEnabled(true); ui->editButton->setEnabled(true); } else { ui->copyAlias->setEnabled(false); ui->transferButton->setEnabled(false); ui->editButton->setEnabled(false); } } void MyAliasListPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which alias was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AliasTableModel::Name); Q_FOREACH (const QModelIndex& index, indexes) { QVariant alias = table->model()->data(index); returnValue = alias.toString(); } if(returnValue.isEmpty()) { // If no alias entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void MyAliasListPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Alias Data"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Alias", AliasTableModel::Name, Qt::EditRole); writer.addColumn("Value", AliasTableModel::Value, Qt::EditRole); writer.addColumn("Expires On", AliasTableModel::ExpiresOn, Qt::EditRole); writer.addColumn("Expires In", AliasTableModel::ExpiresIn, Qt::EditRole); writer.addColumn("Expired", AliasTableModel::Expired, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void MyAliasListPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void MyAliasListPage::selectNewAlias(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AliasTableModel::Name, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAliasToSelect)) { // Select row of newly created alias, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAliasToSelect.clear(); } } <commit_msg>note on creating public key<commit_after>/* * Syscoin Developers 2014 */ #include "myaliaslistpage.h" #include "ui_myaliaslistpage.h" #include "aliastablemodel.h" #include "clientmodel.h" #include "optionsmodel.h" #include "platformstyle.h" #include "walletmodel.h" #include "syscoingui.h" #include "editaliasdialog.h" #include "mywhitelistofferdialog.h" #include "csvmodelwriter.h" #include "guiutil.h" #include <QSortFilterProxyModel> #include <QClipboard> #include <QMessageBox> #include <QMenu> #include "rpcserver.h" using namespace std; extern const CRPCTable tableRPC; MyAliasListPage::MyAliasListPage(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::MyAliasListPage), model(0), optionsModel(0), platformStyle(platformStyle) { ui->setupUi(this); QString theme = GUIUtil::getThemeName(); if (!platformStyle->getImagesOnButtons()) { ui->exportButton->setIcon(QIcon()); ui->newAlias->setIcon(QIcon()); ui->transferButton->setIcon(QIcon()); ui->editButton->setIcon(QIcon()); ui->copyAlias->setIcon(QIcon()); ui->refreshButton->setIcon(QIcon()); ui->newPubKey->setIcon(QIcon()); ui->whitelistButton->setIcon(QIcon()); } else { ui->exportButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/export")); ui->newAlias->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add")); ui->transferButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/alias")); ui->editButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editsys")); ui->copyAlias->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/editcopy")); ui->refreshButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/refresh")); ui->newPubKey->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/add")); ui->whitelistButton->setIcon(platformStyle->SingleColorIcon(":/icons/" + theme + "/address-book")); } ui->buttonBox->setVisible(false); ui->labelExplanation->setText(tr("These are your registered Syscoin Aliases. Alias operations (create, update, transfer) take 2-5 minutes to become active.")); // Context menu actions QAction *copyAliasAction = new QAction(ui->copyAlias->text(), this); QAction *copyAliasValueAction = new QAction(tr("Copy Va&lue"), this); QAction *editAction = new QAction(tr("&Edit"), this); QAction *transferAliasAction = new QAction(tr("&Transfer"), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAliasAction); contextMenu->addAction(copyAliasValueAction); contextMenu->addAction(editAction); contextMenu->addSeparator(); contextMenu->addAction(transferAliasAction); // Connect signals for context menu actions connect(copyAliasAction, SIGNAL(triggered()), this, SLOT(on_copyAlias_clicked())); connect(copyAliasValueAction, SIGNAL(triggered()), this, SLOT(onCopyAliasValueAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(on_editButton_clicked())); connect(transferAliasAction, SIGNAL(triggered()), this, SLOT(on_transferButton_clicked())); connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(on_editButton_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); // Pass through accept action from button box connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); } MyAliasListPage::~MyAliasListPage() { delete ui; } void MyAliasListPage::showEvent ( QShowEvent * event ) { if(!walletModel) return; /*if(walletModel->getEncryptionStatus() == WalletModel::Locked) { ui->labelExplanation->setText(tr("<font color='blue'>WARNING: Your wallet is currently locked. For security purposes you'll need to enter your passphrase in order to interact with Syscoin Aliases. Because your wallet is locked you must manually refresh this table after creating or updating an Alias. </font> <a href=\"http://lockedwallet.syscoin.org\">more info</a><br><br>These are your registered Syscoin Aliases. Alias updates take 1 confirmation to appear in this table.")); ui->labelExplanation->setTextFormat(Qt::RichText); ui->labelExplanation->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->labelExplanation->setOpenExternalLinks(true); }*/ } void MyAliasListPage::setModel(WalletModel *walletModel, AliasTableModel *model) { this->model = model; this->walletModel = walletModel; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); // Receive filter proxyModel->setFilterRole(AliasTableModel::TypeRole); proxyModel->setFilterFixedString(AliasTableModel::Alias); ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection); // Set column widths ui->tableView->setColumnWidth(0, 500); //alias name ui->tableView->setColumnWidth(1, 500); //alias value ui->tableView->setColumnWidth(2, 75); //expires on ui->tableView->setColumnWidth(3, 75); //expires in ui->tableView->setColumnWidth(4, 75); //expired status ui->tableView->horizontalHeader()->setStretchLastSection(true); connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created alias connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAlias(QModelIndex,int,int))); selectionChanged(); } void MyAliasListPage::setOptionsModel(ClientModel* clientmodel, OptionsModel *optionsModel) { this->optionsModel = optionsModel; this->clientModel = clientmodel; } void MyAliasListPage::on_copyAlias_clicked() { GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Name); } void MyAliasListPage::onCopyAliasValueAction() { GUIUtil::copyEntryData(ui->tableView, AliasTableModel::Value); } void MyAliasListPage::on_editButton_clicked() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAliasDialog dlg(EditAliasDialog::EditAlias); dlg.setModel(walletModel, model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void MyAliasListPage::on_transferButton_clicked() { if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAliasDialog dlg(EditAliasDialog::TransferAlias); dlg.setModel(walletModel, model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void MyAliasListPage::on_refreshButton_clicked() { if(!model) return; model->refreshAliasTable(); } void MyAliasListPage::on_whitelistButton_clicked() { MyWhitelistOfferDialog dlg(platformStyle); dlg.setModel(walletModel); dlg.exec(); } void MyAliasListPage::on_newAlias_clicked() { if(!model) return; EditAliasDialog dlg(EditAliasDialog::NewAlias); dlg.setModel(walletModel,model); if(dlg.exec()) { newAliasToSelect = dlg.getAlias(); } } void MyAliasListPage::on_newPubKey_clicked() { UniValue params; UniValue result = tableRPC.execute("generatepublickey", params); if (result.type() == UniValue::VARR) { const UniValue &resultArray = result.get_array(); const QString &resQStr = QString::fromStdString(resultArray[0].get_str()); QApplication::clipboard()->setText(resQStr, QClipboard::Clipboard); QApplication::clipboard()->setText(resQStr, QClipboard::Selection); QMessageBox::information(this, tr("New Public Key For Alias Transfer"), resQStr + tr(" has been copied to your clipboard! IMPORTANT: This key is for one-time use only! Do not re-use public keys for multiple aliases or transfers."), QMessageBox::Ok, QMessageBox::Ok); } else QMessageBox::critical(this, tr("New Public Key For Alias Transfer"), tr("Could not generate a new public key!"), QMessageBox::Ok, QMessageBox::Ok); } void MyAliasListPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { ui->copyAlias->setEnabled(true); ui->transferButton->setEnabled(true); ui->editButton->setEnabled(true); } else { ui->copyAlias->setEnabled(false); ui->transferButton->setEnabled(false); ui->editButton->setEnabled(false); } } void MyAliasListPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which alias was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AliasTableModel::Name); Q_FOREACH (const QModelIndex& index, indexes) { QVariant alias = table->model()->data(index); returnValue = alias.toString(); } if(returnValue.isEmpty()) { // If no alias entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void MyAliasListPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName( this, tr("Export Alias Data"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Alias", AliasTableModel::Name, Qt::EditRole); writer.addColumn("Value", AliasTableModel::Value, Qt::EditRole); writer.addColumn("Expires On", AliasTableModel::ExpiresOn, Qt::EditRole); writer.addColumn("Expires In", AliasTableModel::ExpiresIn, Qt::EditRole); writer.addColumn("Expired", AliasTableModel::Expired, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), QMessageBox::Abort, QMessageBox::Abort); } } void MyAliasListPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void MyAliasListPage::selectNewAlias(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AliasTableModel::Name, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAliasToSelect)) { // Select row of newly created alias, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAliasToSelect.clear(); } } <|endoftext|>
<commit_before>/** * \file * * \author Mattia Basaglia * * \copyright Copyright (C) 2013-2015 Mattia Basaglia * * This program 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "color_utils.hpp" namespace color_widgets { namespace detail { QColor color_from_lch(qreal hue, qreal chroma, qreal luma, qreal alpha ) { qreal h1 = hue*6; qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); QColor col; if ( h1 >= 0 && h1 < 1 ) col = QColor::fromRgbF(chroma,x,0); else if ( h1 < 2 ) col = QColor::fromRgbF(x,chroma,0); else if ( h1 < 3 ) col = QColor::fromRgbF(0,chroma,x); else if ( h1 < 4 ) col = QColor::fromRgbF(0,x,chroma); else if ( h1 < 5 ) col = QColor::fromRgbF(x,0,chroma); else if ( h1 < 6 ) col = QColor::fromRgbF(chroma,0,x); qreal m = luma - color_lumaF(col); return QColor::fromRgbF( qBound(0.0,col.redF()+m,1.0), qBound(0.0,col.greenF()+m,1.0), qBound(0.0,col.blueF()+m,1.0), alpha); } QColor color_from_hsl(qreal hue, qreal sat, qreal lig, qreal alpha ) { qreal chroma = (1 - qAbs(2*lig-1))*sat; qreal h1 = hue*6; qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); QColor col; if ( h1 >= 0 && h1 < 1 ) col = QColor::fromRgbF(chroma,x,0); else if ( h1 < 2 ) col = QColor::fromRgbF(x,chroma,0); else if ( h1 < 3 ) col = QColor::fromRgbF(0,chroma,x); else if ( h1 < 4 ) col = QColor::fromRgbF(0,x,chroma); else if ( h1 < 5 ) col = QColor::fromRgbF(x,0,chroma); else if ( h1 < 6 ) col = QColor::fromRgbF(chroma,0,x); qreal m = lig-chroma/2; return QColor::fromRgbF( qBound(0.0,col.redF()+m,1.0), qBound(0.0,col.greenF()+m,1.0), qBound(0.0,col.blueF()+m,1.0), alpha); } } // namespace detail } // namespace color_widgets <commit_msg>trying to fix #66<commit_after>/** * \file * * \author Mattia Basaglia * * \copyright Copyright (C) 2013-2015 Mattia Basaglia * * This program 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <cmath> #include "color_utils.hpp" namespace color_widgets { namespace detail { QColor color_from_lch(qreal hue, qreal chroma, qreal luma, qreal alpha ) { qreal h1 = hue*6; qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); QColor col; if ( h1 >= 0 && h1 < 1 ) col = QColor::fromRgbF(chroma,x,0); else if ( h1 < 2 ) col = QColor::fromRgbF(x,chroma,0); else if ( h1 < 3 ) col = QColor::fromRgbF(0,chroma,x); else if ( h1 < 4 ) col = QColor::fromRgbF(0,x,chroma); else if ( h1 < 5 ) col = QColor::fromRgbF(x,0,chroma); else if ( h1 < 6 ) col = QColor::fromRgbF(chroma,0,x); qreal m = luma - color_lumaF(col); return QColor::fromRgbF( qBound(0.0,col.redF()+m,1.0), qBound(0.0,col.greenF()+m,1.0), qBound(0.0,col.blueF()+m,1.0), alpha); } QColor color_from_hsl(qreal hue, qreal sat, qreal lig, qreal alpha ) { qreal chroma = (1 - qAbs(2*lig-1))*sat; qreal h1 = hue*6; qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); QColor col; if ( h1 >= 0 && h1 < 1 ) col = QColor::fromRgbF(chroma,x,0); else if ( h1 < 2 ) col = QColor::fromRgbF(x,chroma,0); else if ( h1 < 3 ) col = QColor::fromRgbF(0,chroma,x); else if ( h1 < 4 ) col = QColor::fromRgbF(0,x,chroma); else if ( h1 < 5 ) col = QColor::fromRgbF(x,0,chroma); else if ( h1 < 6 ) col = QColor::fromRgbF(chroma,0,x); qreal m = lig-chroma/2; return QColor::fromRgbF( qBound(0.0,col.redF()+m,1.0), qBound(0.0,col.greenF()+m,1.0), qBound(0.0,col.blueF()+m,1.0), alpha); } } // namespace detail } // namespace color_widgets <|endoftext|>
<commit_before>#include "AliFemtoDreamControlSample.h" #include "AliLog.h" #include "TDatabasePDG.h" #include "TLorentzVector.h" #include "TMath.h" ClassImp(AliFemtoDreamControlSample) AliFemtoDreamControlSample::AliFemtoDreamControlSample() : fHigherMath(nullptr), fPDGParticleSpecies(), fRejPairs(), fMultBins(), fRandom(), fPi(TMath::Pi()), fmode(AliFemtoDreamCollConfig::kNone), fSpinningDepth(0), fCorrelationRange(0.), fDeltaEtaMax(0.f), fDeltaPhiMax(0.f), fDoDeltaEtaDeltaPhiCut(false), fMult(0), fCent(0) { fRandom.SetSeed(0); } AliFemtoDreamControlSample::AliFemtoDreamControlSample( const AliFemtoDreamControlSample &samp) : fHigherMath(samp.fHigherMath), fPDGParticleSpecies(samp.fPDGParticleSpecies), fRejPairs(samp.fRejPairs), fMultBins(samp.fMultBins), fRandom(), fPi(TMath::Pi()), fmode(samp.fmode), fSpinningDepth(samp.fSpinningDepth), fCorrelationRange(samp.fCorrelationRange), fDeltaEtaMax(samp.fDeltaEtaMax), fDeltaPhiMax(samp.fDeltaPhiMax), fDoDeltaEtaDeltaPhiCut(samp.fDoDeltaEtaDeltaPhiCut), fMult(samp.fMult), fCent(samp.fCent) { fRandom.SetSeed(0); } AliFemtoDreamControlSample::AliFemtoDreamControlSample( AliFemtoDreamCollConfig *conf) : fHigherMath(new AliFemtoDreamHigherPairMath(conf)), fPDGParticleSpecies(conf->GetPDGCodes()), fRejPairs(conf->GetClosePairRej()), fMultBins(conf->GetMultBins()), fRandom(), fPi(TMath::Pi()), fmode(conf->GetControlMode()), fSpinningDepth(conf->GetSpinningDepth()), fCorrelationRange(conf->GetCorrelationRange()), fDeltaEtaMax(conf->GetDeltaEtaMax()), fDeltaPhiMax(conf->GetDeltaPhiMax()), fDoDeltaEtaDeltaPhiCut(false), fMult(0), fCent(0) { fRandom.SetSeed(0); } AliFemtoDreamControlSample& AliFemtoDreamControlSample::operator=( const AliFemtoDreamControlSample& samp) { if (this == &samp) { return *this; } this->fHigherMath = samp.fHigherMath; this->fPDGParticleSpecies = samp.fPDGParticleSpecies; this->fRejPairs = samp.fRejPairs; this->fMultBins = samp.fMultBins; this->fRandom.SetSeed(0); this->fPi = TMath::Pi(); this->fSpinningDepth = samp.fSpinningDepth; this->fDeltaEtaMax = samp.fDeltaEtaMax; this->fDeltaPhiMax = samp.fDeltaPhiMax; this->fDoDeltaEtaDeltaPhiCut = samp.fDoDeltaEtaDeltaPhiCut; this->fMult = samp.fMult; this->fCent = samp.fCent; return *this; } AliFemtoDreamControlSample::~AliFemtoDreamControlSample() { } void AliFemtoDreamControlSample::SetEvent( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles, AliFemtoDreamEvent *evt) { fMult = FindBin(evt->GetMultiplicity()); fCent = evt->GetV0MCentrality(); fHigherMath->SetBField(evt->GetMagneticField()); int HistCounter = 0; auto itPDGPar1 = fPDGParticleSpecies.begin(); auto itSpec1 = Particles.begin(); bool sameParticle = false; int minimumSize; while (itSpec1 != Particles.end()) { auto itSpec2 = itSpec1; auto itPDGPar2 = itPDGPar1; while (itSpec2 != Particles.end()) { fHigherMath->FillPairCounterSE(HistCounter, itSpec1->size(), itSpec2->size()); if (itSpec1 == itSpec2) { sameParticle = true; minimumSize = 1; } else { minimumSize = 0; sameParticle = false; } //if it is the same particle, then we need at least two to pair them 2*2 is the minimum if ((itSpec1->size() > minimumSize) && (itSpec2->size() > minimumSize)) { // for single particle pairs, this is pointless CorrelatedSample(*itSpec1, *itPDGPar1, *itSpec2, *itPDGPar2, sameParticle, HistCounter); UncorrelatedSample(*itSpec1, *itPDGPar1, *itSpec2, *itPDGPar2, sameParticle, HistCounter); } ++itSpec2; ++HistCounter; ++itPDGPar2; } itPDGPar1++; itSpec1++; } } int AliFemtoDreamControlSample::FindBin(float Multiplicity) { int binCounter = fMultBins.size(); for (std::vector<int>::reverse_iterator itBin = fMultBins.rbegin(); itBin != fMultBins.rend(); ++itBin) { binCounter--; if (Multiplicity >= *itBin) { break; } } return binCounter; } void AliFemtoDreamControlSample::CorrelatedSample( std::vector<AliFemtoDreamBasePart> &part1, int &PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int &PDGPart2, bool SameParticle, int HistCounter) { float RelativeK = 0; auto itPart1 = part1.begin(); bool CPR = fRejPairs.at(HistCounter); while (itPart1 != part1.end()) { auto itPart2 = SameParticle ? itPart1 + 1 : part2.begin(); while (itPart2 != part2.end()) { if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fHigherMath->PassesPairSelection(&(*itPart1), &(*itPart2), false)) { ++itPart2; continue; } } RelativeK = fHigherMath->FillSameEvent(HistCounter, fMult, fCent, itPart1->GetMomentum(), PDGPart1, itPart2->GetMomentum(), PDGPart2); fHigherMath->MassQA(HistCounter, RelativeK, itPart1->GetInvMass(), itPart2->GetInvMass()); fHigherMath->SEDetaDPhiPlots(HistCounter, *itPart1, PDGPart1, *itPart2, PDGPart2, RelativeK, true); itPart2++; } itPart1++; } } void AliFemtoDreamControlSample::UncorrelatedSample( std::vector<AliFemtoDreamBasePart> &part1, int &PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int &PDGPart2, bool SameParticle, int HistCounter) { if (fmode == AliFemtoDreamCollConfig::kPhiSpin || fmode == AliFemtoDreamCollConfig::kStravinsky) { PhiSpinning(part1, PDGPart1, part2, PDGPart2, SameParticle, HistCounter); } else if (fmode == AliFemtoDreamCollConfig::kCorrelatedPhi) { for (int iSpin = 0; iSpin < fSpinningDepth; ++iSpin) { LimitedPhiSpinning(part1, PDGPart1, part2, PDGPart2, SameParticle, HistCounter); } } else { Error("AliFemtoDreamControlSample::UncorrelatedSample", "None implemented mode\n"); } return; } void AliFemtoDreamControlSample::PhiSpinning( std::vector<AliFemtoDreamBasePart> &part1, int PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int PDGPart2, bool SameParticle, int HistCounter) { float RelativeK = 0; auto itPart1 = part1.begin(); bool CPR = fRejPairs.at(HistCounter); while (itPart1 != part1.end()) { auto itPart2 = SameParticle ? itPart1 + 1 : part2.begin(); while (itPart2 != part2.end()) { //in this case it does NOT work as intended since the new phi of the particle has to //be considered for this cut if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fHigherMath->PassesPairSelection(&(*itPart1), &(*itPart2), true)) { ++itPart2; continue; } } for (int i = 0; i < fSpinningDepth; ++i) { // randomized sample - who is the father??? RelativeK = fHigherMath->FillMixedEvent(HistCounter, fMult, fCent, itPart1->GetMomentum(), PDGPart1, itPart2->GetMomentum(), PDGPart2, fmode); fHigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, PDGPart1, *itPart2, PDGPart2, RelativeK, true); } itPart2++; } itPart1++; } } void AliFemtoDreamControlSample::LimitedPhiSpinning( std::vector<AliFemtoDreamBasePart> &part1, int PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int PDGPart2, bool SameParticle, int HistCounter) { //copy input to not touch the initial state & make it to pointers to do some nasty things. std::vector<AliFemtoDreamBasePart*> CopyPart1; std::vector<AliFemtoDreamBasePart*> CopyPart2; for (auto it : part1) { CopyPart1.emplace_back(new AliFemtoDreamBasePart(it)); } // randomize the sample: add references to all particles to a vector std::vector<AliFemtoDreamBasePart*> RandomizeMe; for (auto it : CopyPart1) { RandomizeMe.push_back(it); } // Only add the second particle, in case it is a different particle if (!SameParticle) { for (auto it : part2) { CopyPart2.emplace_back(new AliFemtoDreamBasePart(it)); } for (auto it : CopyPart2) { RandomizeMe.push_back(it); } } else { // if the particles are the same this should point to the same vector as particle 1 CopyPart2 = CopyPart1; } Randomizer(RandomizeMe); // calculate the relative momentum float RelativeK = 0; bool CPR = fRejPairs.at(HistCounter); auto itPart1 = CopyPart1.begin(); while (itPart1 != CopyPart1.end()) { auto itPart2 = SameParticle ? itPart1 + 1 : CopyPart2.begin(); while (itPart2 != (SameParticle ? CopyPart1 : CopyPart2).end()) { //in this case it does NOT work as intended since the new phi of the particle has to //be considered for this cut if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fHigherMath->PassesPairSelection(*itPart1, *itPart2, true)) { ++itPart2; continue; } } } // randomized sample - who is the father??? RelativeK = fHigherMath->FillMixedEvent(HistCounter, fMult, fCent, (*itPart1)->GetMomentum(), PDGPart1, (*itPart2)->GetMomentum(), PDGPart2, AliFemtoDreamCollConfig::kNone); fHigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, PDGPart1, *itPart2, PDGPart2, RelativeK, true); itPart2++; } itPart1++; } for (auto iDel : RandomizeMe) { delete iDel; } RandomizeMe.clear(); // it was checked with massif that there is no memory leak and even if the pointer and its members // still exist. // for (auto iTest : CopyPart1) { // if (iTest){ // Warning("LimitedPhiSpinning", // "This should be deleted, think about your code \n"); // } // } CopyPart1.clear(); CopyPart2.clear(); return; } void AliFemtoDreamControlSample::Randomizer( std::vector<AliFemtoDreamBasePart*> &part) { if (part.size() < 2) { Warning("AliFemtoDreamControlSample::Randomizer", "this should not happen, check the vector size\n"); } auto itPart1 = part.begin(); auto itPart2 = itPart1; // dummy vale to start the while while (itPart1 != part.end()) { // this doersn't work itPart2 = itPart1 + 1; //pick the next particle if (itPart2 == part.end()) { // if this is out of range, finish the while break; } // Get the momenta TVector3 Part1Mom = (*itPart1)->GetMomentum(); TVector3 Part2Mom = (*itPart2)->GetMomentum(); Part2Mom += Part1Mom; // give the first particle a phi kick Part1Mom.SetPhi( Part2Mom.Phi() + fRandom.Uniform(-fCorrelationRange, fCorrelationRange)); Part2Mom -= Part1Mom; (*itPart1)->SetMomentum(Part1Mom); (*itPart2)->SetMomentum(Part2Mom); itPart1 += 2; } } <commit_msg>Correct start angle for particle one in the phi spinning<commit_after>#include "AliFemtoDreamControlSample.h" #include "AliLog.h" #include "TDatabasePDG.h" #include "TLorentzVector.h" #include "TMath.h" ClassImp(AliFemtoDreamControlSample) AliFemtoDreamControlSample::AliFemtoDreamControlSample() : fHigherMath(nullptr), fPDGParticleSpecies(), fRejPairs(), fMultBins(), fRandom(), fPi(TMath::Pi()), fmode(AliFemtoDreamCollConfig::kNone), fSpinningDepth(0), fCorrelationRange(0.), fDeltaEtaMax(0.f), fDeltaPhiMax(0.f), fDoDeltaEtaDeltaPhiCut(false), fMult(0), fCent(0) { fRandom.SetSeed(0); } AliFemtoDreamControlSample::AliFemtoDreamControlSample( const AliFemtoDreamControlSample &samp) : fHigherMath(samp.fHigherMath), fPDGParticleSpecies(samp.fPDGParticleSpecies), fRejPairs(samp.fRejPairs), fMultBins(samp.fMultBins), fRandom(), fPi(TMath::Pi()), fmode(samp.fmode), fSpinningDepth(samp.fSpinningDepth), fCorrelationRange(samp.fCorrelationRange), fDeltaEtaMax(samp.fDeltaEtaMax), fDeltaPhiMax(samp.fDeltaPhiMax), fDoDeltaEtaDeltaPhiCut(samp.fDoDeltaEtaDeltaPhiCut), fMult(samp.fMult), fCent(samp.fCent) { fRandom.SetSeed(0); } AliFemtoDreamControlSample::AliFemtoDreamControlSample( AliFemtoDreamCollConfig *conf) : fHigherMath(new AliFemtoDreamHigherPairMath(conf)), fPDGParticleSpecies(conf->GetPDGCodes()), fRejPairs(conf->GetClosePairRej()), fMultBins(conf->GetMultBins()), fRandom(), fPi(TMath::Pi()), fmode(conf->GetControlMode()), fSpinningDepth(conf->GetSpinningDepth()), fCorrelationRange(conf->GetCorrelationRange()), fDeltaEtaMax(conf->GetDeltaEtaMax()), fDeltaPhiMax(conf->GetDeltaPhiMax()), fDoDeltaEtaDeltaPhiCut(false), fMult(0), fCent(0) { fRandom.SetSeed(0); } AliFemtoDreamControlSample& AliFemtoDreamControlSample::operator=( const AliFemtoDreamControlSample& samp) { if (this == &samp) { return *this; } this->fHigherMath = samp.fHigherMath; this->fPDGParticleSpecies = samp.fPDGParticleSpecies; this->fRejPairs = samp.fRejPairs; this->fMultBins = samp.fMultBins; this->fRandom.SetSeed(0); this->fPi = TMath::Pi(); this->fSpinningDepth = samp.fSpinningDepth; this->fDeltaEtaMax = samp.fDeltaEtaMax; this->fDeltaPhiMax = samp.fDeltaPhiMax; this->fDoDeltaEtaDeltaPhiCut = samp.fDoDeltaEtaDeltaPhiCut; this->fMult = samp.fMult; this->fCent = samp.fCent; return *this; } AliFemtoDreamControlSample::~AliFemtoDreamControlSample() { } void AliFemtoDreamControlSample::SetEvent( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles, AliFemtoDreamEvent *evt) { fMult = FindBin(evt->GetMultiplicity()); fCent = evt->GetV0MCentrality(); fHigherMath->SetBField(evt->GetMagneticField()); int HistCounter = 0; auto itPDGPar1 = fPDGParticleSpecies.begin(); auto itSpec1 = Particles.begin(); bool sameParticle = false; int minimumSize; while (itSpec1 != Particles.end()) { auto itSpec2 = itSpec1; auto itPDGPar2 = itPDGPar1; while (itSpec2 != Particles.end()) { fHigherMath->FillPairCounterSE(HistCounter, itSpec1->size(), itSpec2->size()); if (itSpec1 == itSpec2) { sameParticle = true; minimumSize = 1; } else { minimumSize = 0; sameParticle = false; } //if it is the same particle, then we need at least two to pair them 2*2 is the minimum if ((itSpec1->size() > minimumSize) && (itSpec2->size() > minimumSize)) { // for single particle pairs, this is pointless CorrelatedSample(*itSpec1, *itPDGPar1, *itSpec2, *itPDGPar2, sameParticle, HistCounter); UncorrelatedSample(*itSpec1, *itPDGPar1, *itSpec2, *itPDGPar2, sameParticle, HistCounter); } ++itSpec2; ++HistCounter; ++itPDGPar2; } itPDGPar1++; itSpec1++; } } int AliFemtoDreamControlSample::FindBin(float Multiplicity) { int binCounter = fMultBins.size(); for (std::vector<int>::reverse_iterator itBin = fMultBins.rbegin(); itBin != fMultBins.rend(); ++itBin) { binCounter--; if (Multiplicity >= *itBin) { break; } } return binCounter; } void AliFemtoDreamControlSample::CorrelatedSample( std::vector<AliFemtoDreamBasePart> &part1, int &PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int &PDGPart2, bool SameParticle, int HistCounter) { float RelativeK = 0; auto itPart1 = part1.begin(); bool CPR = fRejPairs.at(HistCounter); while (itPart1 != part1.end()) { auto itPart2 = SameParticle ? itPart1 + 1 : part2.begin(); while (itPart2 != part2.end()) { if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fHigherMath->PassesPairSelection(&(*itPart1), &(*itPart2), false)) { ++itPart2; continue; } } RelativeK = fHigherMath->FillSameEvent(HistCounter, fMult, fCent, itPart1->GetMomentum(), PDGPart1, itPart2->GetMomentum(), PDGPart2); fHigherMath->MassQA(HistCounter, RelativeK, itPart1->GetInvMass(), itPart2->GetInvMass()); fHigherMath->SEDetaDPhiPlots(HistCounter, *itPart1, PDGPart1, *itPart2, PDGPart2, RelativeK, true); itPart2++; } itPart1++; } } void AliFemtoDreamControlSample::UncorrelatedSample( std::vector<AliFemtoDreamBasePart> &part1, int &PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int &PDGPart2, bool SameParticle, int HistCounter) { if (fmode == AliFemtoDreamCollConfig::kPhiSpin || fmode == AliFemtoDreamCollConfig::kStravinsky) { PhiSpinning(part1, PDGPart1, part2, PDGPart2, SameParticle, HistCounter); } else if (fmode == AliFemtoDreamCollConfig::kCorrelatedPhi) { for (int iSpin = 0; iSpin < fSpinningDepth; ++iSpin) { LimitedPhiSpinning(part1, PDGPart1, part2, PDGPart2, SameParticle, HistCounter); } } else { Error("AliFemtoDreamControlSample::UncorrelatedSample", "None implemented mode\n"); } return; } void AliFemtoDreamControlSample::PhiSpinning( std::vector<AliFemtoDreamBasePart> &part1, int PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int PDGPart2, bool SameParticle, int HistCounter) { float RelativeK = 0; auto itPart1 = part1.begin(); bool CPR = fRejPairs.at(HistCounter); while (itPart1 != part1.end()) { auto itPart2 = SameParticle ? itPart1 + 1 : part2.begin(); while (itPart2 != part2.end()) { //in this case it does NOT work as intended since the new phi of the particle has to //be considered for this cut if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fHigherMath->PassesPairSelection(&(*itPart1), &(*itPart2), true)) { ++itPart2; continue; } } for (int i = 0; i < fSpinningDepth; ++i) { // randomized sample - who is the father??? RelativeK = fHigherMath->FillMixedEvent(HistCounter, fMult, fCent, itPart1->GetMomentum(), PDGPart1, itPart2->GetMomentum(), PDGPart2, fmode); fHigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, PDGPart1, *itPart2, PDGPart2, RelativeK, true); } itPart2++; } itPart1++; } } void AliFemtoDreamControlSample::LimitedPhiSpinning( std::vector<AliFemtoDreamBasePart> &part1, int PDGPart1, std::vector<AliFemtoDreamBasePart> &part2, int PDGPart2, bool SameParticle, int HistCounter) { //copy input to not touch the initial state & make it to pointers to do some nasty things. std::vector<AliFemtoDreamBasePart*> CopyPart1; std::vector<AliFemtoDreamBasePart*> CopyPart2; for (auto it : part1) { CopyPart1.emplace_back(new AliFemtoDreamBasePart(it)); } // randomize the sample: add references to all particles to a vector std::vector<AliFemtoDreamBasePart*> RandomizeMe; for (auto it : CopyPart1) { RandomizeMe.push_back(it); } // Only add the second particle, in case it is a different particle if (!SameParticle) { for (auto it : part2) { CopyPart2.emplace_back(new AliFemtoDreamBasePart(it)); } for (auto it : CopyPart2) { RandomizeMe.push_back(it); } } else { // if the particles are the same this should point to the same vector as particle 1 CopyPart2 = CopyPart1; } Randomizer(RandomizeMe); // calculate the relative momentum float RelativeK = 0; bool CPR = fRejPairs.at(HistCounter); auto itPart1 = CopyPart1.begin(); while (itPart1 != CopyPart1.end()) { auto itPart2 = SameParticle ? itPart1 + 1 : CopyPart2.begin(); while (itPart2 != (SameParticle ? CopyPart1 : CopyPart2).end()) { //in this case it does NOT work as intended since the new phi of the particle has to //be considered for this cut if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fDoDeltaEtaDeltaPhiCut && CPR) { if (fHigherMath->PassesPairSelection(*itPart1, *itPart2, true)) { ++itPart2; continue; } } } // randomized sample - who is the father??? RelativeK = fHigherMath->FillMixedEvent(HistCounter, fMult, fCent, (*itPart1)->GetMomentum(), PDGPart1, (*itPart2)->GetMomentum(), PDGPart2, AliFemtoDreamCollConfig::kNone); fHigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, PDGPart1, *itPart2, PDGPart2, RelativeK, true); itPart2++; } itPart1++; } for (auto iDel : RandomizeMe) { delete iDel; } RandomizeMe.clear(); // it was checked with massif that there is no memory leak and even if the pointer and its members // still exist. // for (auto iTest : CopyPart1) { // if (iTest){ // Warning("LimitedPhiSpinning", // "This should be deleted, think about your code \n"); // } // } CopyPart1.clear(); CopyPart2.clear(); return; } void AliFemtoDreamControlSample::Randomizer( std::vector<AliFemtoDreamBasePart*> &part) { if (part.size() < 2) { Warning("AliFemtoDreamControlSample::Randomizer", "this should not happen, check the vector size\n"); } auto itPart1 = part.begin(); auto itPart2 = itPart1; // dummy vale to start the while while (itPart1 != part.end()) { // this doersn't work itPart2 = itPart1 + 1; //pick the next particle if (itPart2 == part.end()) { // if this is out of range, finish the while break; } // Get the momenta TVector3 Part1Mom = (*itPart1)->GetMomentum(); TVector3 Part2Mom = (*itPart2)->GetMomentum(); Part2Mom += Part1Mom; // give the first particle a phi kick Part1Mom.SetPhi( Part1Mom.Phi() + fRandom.Uniform(-fCorrelationRange, fCorrelationRange)); Part2Mom -= Part1Mom; (*itPart1)->SetMomentum(Part1Mom); (*itPart2)->SetMomentum(Part2Mom); itPart1 += 2; } } <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #include <cstdlib> #include <algorithm> #include <cstring> #ifdef REALM_DEBUG #include <cstdio> #include <iostream> #include <iomanip> #endif #include <realm/utilities.hpp> #include <realm/array_string.hpp> #include <realm/impl/destroy_guard.hpp> #include <realm/column.hpp> using namespace realm; namespace { // Round up to nearest possible block length: 0, 1, 2, 4, 8, 16, 32, 64, 128, 256. We include 1 to store empty // strings in as little space as possible, because 0 can only store nulls. size_t round_up(size_t size) { REALM_ASSERT(size <= 256); if (size <= 2) return size; size--; size |= size >> 1; size |= size >> 2; size |= size >> 4; ++size; return size; } } // anonymous namespace bool ArrayString::is_null(size_t ndx) const { REALM_ASSERT_3(ndx, <, m_size); StringData sd = get(ndx); return sd.is_null(); } void ArrayString::set_null(size_t ndx) { REALM_ASSERT_3(ndx, <, m_size); StringData sd = realm::null(); set(ndx, sd); } void ArrayString::set(size_t ndx, StringData value) { REALM_ASSERT_3(ndx, <, m_size); REALM_ASSERT_3(value.size(), <, max_width); // otherwise we have to use another column type // Check if we need to copy before modifying copy_on_write(); // Throws // Make room for the new value plus a zero-termination if (m_width <= value.size()) { // if m_width == 0 and m_nullable == true, then entire array contains only null entries // if m_width == 0 and m_nullable == false, then entire array contains only "" entries if ((m_nullable ? value.is_null() : value.size() == 0) && m_width == 0) { return; // existing element in array already equals the value we want to set it to } // Calc min column width size_t new_width; if (m_width == 0 && value.size() == 0) new_width = ::round_up(1); // Entire Array is nulls; expand to m_width > 0 else new_width = ::round_up(value.size() + 1); // FIXME: Should we try to avoid double copying when realloc fails to preserve the address? alloc(m_size, new_width); // Throws char* base = m_data; char* new_end = base + m_size * new_width; // Expand the old values in reverse order if (0 < m_width) { const char* old_end = base + m_size * m_width; while (new_end != base) { *--new_end = char(*--old_end + (new_width - m_width)); { // extend 0-padding char* new_begin = new_end - (new_width - m_width); std::fill(new_begin, new_end, 0); new_end = new_begin; } { // copy string payload const char* old_begin = old_end - (m_width - 1); if (static_cast<size_t>(old_end - old_begin) < m_width) // non-null string new_end = std::copy_backward(old_begin, old_end, new_end); old_end = old_begin; } } } else { // m_width == 0. Expand to new width. while (new_end != base) { REALM_ASSERT_3(new_width, <=, max_width); *--new_end = static_cast<char>(new_width); { char* new_begin = new_end - (new_width - 1); std::fill(new_begin, new_end, 0); // Fill with zero bytes new_end = new_begin; } } } m_width = uint_least8_t(new_width); } REALM_ASSERT_3(0, <, m_width); // Set the value char* begin = m_data + (ndx * m_width); char* end = begin + (m_width - 1); begin = std::copy_n(value.data(), value.size(), begin); std::fill(begin, end, 0); // Pad with zero bytes static_assert(max_width <= max_width, "Padding size must fit in 7-bits"); if (value.is_null()) { REALM_ASSERT_3(m_width, <=, 128); *end = static_cast<char>(m_width); } else { int pad_size = int(end - begin); *end = char(pad_size); } } void ArrayString::insert(size_t ndx, StringData value) { REALM_ASSERT_3(ndx, <=, m_size); REALM_ASSERT(value.size() < max_width); // otherwise we have to use another column type // Check if we need to copy before modifying copy_on_write(); // Throws // Todo: Below code will perform up to 3 memcpy() operations in worst case. Todo, if we improve the // allocator to make a gap for the new value for us, we can have just 1. We can also have 2 by merging // memmove() and set(), but it's a bit complex. May be done after support of realm::null() is completed. // Allocate room for the new value alloc(m_size + 1, m_width); // Throws // Make gap for new value memmove(m_data + m_width * (ndx + 1), m_data + m_width * ndx, m_width * (m_size - ndx)); m_size++; // Set new value set(ndx, value); return; } void ArrayString::erase(size_t ndx) { REALM_ASSERT_3(ndx, <, m_size); // Check if we need to copy before modifying copy_on_write(); // Throws // move data backwards after deletion if (ndx < m_size - 1) { char* new_begin = m_data + ndx * m_width; char* old_begin = new_begin + m_width; char* old_end = m_data + m_size * m_width; std::copy_n(old_begin, old_end - old_begin, new_begin); } --m_size; // Update size in header set_header_size(m_size); } size_t ArrayString::calc_byte_len(size_t num_items, size_t width) const { return header_size + (num_items * width); } size_t ArrayString::calc_item_count(size_t bytes, size_t width) const noexcept { if (width == 0) return size_t(-1); // zero-width gives infinite space size_t bytes_without_header = bytes - header_size; return bytes_without_header / width; } size_t ArrayString::count(StringData value, size_t begin, size_t end) const noexcept { size_t num_matches = 0; size_t begin_2 = begin; for (;;) { size_t ndx = find_first(value, begin_2, end); if (ndx == not_found) break; ++num_matches; begin_2 = ndx + 1; } return num_matches; } size_t ArrayString::find_first(StringData value, size_t begin, size_t end) const noexcept { if (end == size_t(-1)) end = m_size; REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); if (m_width == 0) { if (m_nullable) // m_width == 0 implies that all elements in the array are NULL return value.is_null() && begin < m_size ? begin : npos; else return value.size() == 0 && begin < m_size ? begin : npos; } // A string can never be wider than the column width if (m_width <= value.size()) return size_t(-1); if (m_nullable ? value.is_null() : value.size() == 0) { for (size_t i = begin; i != end; ++i) { if (m_nullable ? is_null(i) : get(i).size() == 0) return i; } } else if (value.size() == 0) { const char* data = m_data + (m_width - 1); for (size_t i = begin; i != end; ++i) { size_t data_i_size = (m_width - 1) - data[i * m_width]; // left-hand-side tests if array element is NULL if (REALM_UNLIKELY(data_i_size == 0)) return i; } } else { for (size_t i = begin; i != end; ++i) { const char* data = m_data + (i * m_width); size_t j = 0; for (;;) { if (REALM_LIKELY(data[j] != value[j])) break; ++j; if (REALM_UNLIKELY(j == value.size())) { size_t data_size = (m_width - 1) - data[m_width - 1]; if (REALM_LIKELY(data_size == value.size())) return i; break; } } } } return not_found; } void ArrayString::find_all(IntegerColumn& result, StringData value, size_t add_offset, size_t begin, size_t end) { size_t begin_2 = begin; for (;;) { size_t ndx = find_first(value, begin_2, end); if (ndx == not_found) break; result.add(add_offset + ndx); // Throws begin_2 = ndx + 1; } } bool ArrayString::compare_string(const ArrayString& c) const noexcept { if (c.size() != size()) return false; for (size_t i = 0; i < size(); ++i) { if (get(i) != c.get(i)) return false; } return true; } ref_type ArrayString::bptree_leaf_insert(size_t ndx, StringData value, TreeInsertBase& state) { size_t leaf_size = size(); REALM_ASSERT_3(leaf_size, <=, REALM_MAX_BPNODE_SIZE); if (leaf_size < ndx) ndx = leaf_size; if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) { insert(ndx, value); // Throws return 0; // Leaf was not split } // Split leaf node ArrayString new_leaf(m_alloc, m_nullable); new_leaf.create(); // Throws if (ndx == leaf_size) { new_leaf.add(value); // Throws state.m_split_offset = ndx; } else { for (size_t i = ndx; i != leaf_size; ++i) new_leaf.add(get(i)); // Throws truncate(ndx); // Throws add(value); // Throws state.m_split_offset = ndx + 1; } state.m_split_size = leaf_size + 1; return new_leaf.get_ref(); } MemRef ArrayString::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const { REALM_ASSERT(is_attached()); // FIXME: This can be optimized as a single contiguous copy // operation. ArrayString array_slice(target_alloc, m_nullable); _impl::ShallowArrayDestroyGuard dg(&array_slice); array_slice.create(); // Throws size_t begin = offset; size_t end = offset + slice_size; for (size_t i = begin; i != end; ++i) { StringData value = get(i); array_slice.add(value); // Throws } dg.release(); return array_slice.get_mem(); } #ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug functions void ArrayString::string_stats() const { size_t total = 0; size_t longest = 0; for (size_t i = 0; i < m_size; ++i) { StringData str = get(i); size_t str_size = str.size() + 1; total += str_size; if (str_size > longest) longest = str_size; } size_t array_size = m_size * m_width; size_t zeroes = array_size - total; size_t zavg = zeroes / (m_size ? m_size : 1); // avoid possible div by zero std::cout << "Size: " << m_size << "\n"; std::cout << "Width: " << m_width << "\n"; std::cout << "Total: " << array_size << "\n"; std::cout << "Capacity: " << m_capacity << "\n\n"; std::cout << "Bytes string: " << total << "\n"; std::cout << " longest: " << longest << "\n"; std::cout << "Bytes zeroes: " << zeroes << "\n"; std::cout << " avg: " << zavg << "\n"; } void ArrayString::to_dot(std::ostream& out, StringData title) const { ref_type ref = get_ref(); if (title.size() != 0) { out << "subgraph cluster_" << ref << " {" << std::endl; out << " label = \"" << title << "\";" << std::endl; out << " color = white;" << std::endl; } out << "n" << std::hex << ref << std::dec << "[shape=none,label=<"; out << "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\"><TR>" << std::endl; // Header out << "<TD BGCOLOR=\"lightgrey\"><FONT POINT-SIZE=\"7\">"; out << "0x" << std::hex << ref << std::dec << "</FONT></TD>" << std::endl; for (size_t i = 0; i < m_size; ++i) out << "<TD>\"" << get(i) << "\"</TD>" << std::endl; out << "</TR></TABLE>>];" << std::endl; if (title.size() != 0) out << "}" << std::endl; to_dot_parent_edge(out); } #endif // LCOV_EXCL_STOP ignore debug functions <commit_msg>No need to branch.<commit_after>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #include <cstdlib> #include <algorithm> #include <cstring> #ifdef REALM_DEBUG #include <cstdio> #include <iostream> #include <iomanip> #endif #include <realm/utilities.hpp> #include <realm/array_string.hpp> #include <realm/impl/destroy_guard.hpp> #include <realm/column.hpp> using namespace realm; namespace { // Round up to nearest possible block length: 0, 1, 2, 4, 8, 16, 32, 64, 128, 256. We include 1 to store empty // strings in as little space as possible, because 0 can only store nulls. size_t round_up(size_t size) { REALM_ASSERT(size <= 256); if (size <= 2) return size; size--; size |= size >> 1; size |= size >> 2; size |= size >> 4; ++size; return size; } } // anonymous namespace bool ArrayString::is_null(size_t ndx) const { REALM_ASSERT_3(ndx, <, m_size); StringData sd = get(ndx); return sd.is_null(); } void ArrayString::set_null(size_t ndx) { REALM_ASSERT_3(ndx, <, m_size); StringData sd = realm::null(); set(ndx, sd); } void ArrayString::set(size_t ndx, StringData value) { REALM_ASSERT_3(ndx, <, m_size); REALM_ASSERT_3(value.size(), <, max_width); // otherwise we have to use another column type // Check if we need to copy before modifying copy_on_write(); // Throws // Make room for the new value plus a zero-termination if (m_width <= value.size()) { // if m_width == 0 and m_nullable == true, then entire array contains only null entries // if m_width == 0 and m_nullable == false, then entire array contains only "" entries if ((m_nullable ? value.is_null() : value.size() == 0) && m_width == 0) { return; // existing element in array already equals the value we want to set it to } // Calc min column width size_t new_width = ::round_up(value.size() + 1); // FIXME: Should we try to avoid double copying when realloc fails to preserve the address? alloc(m_size, new_width); // Throws char* base = m_data; char* new_end = base + m_size * new_width; // Expand the old values in reverse order if (0 < m_width) { const char* old_end = base + m_size * m_width; while (new_end != base) { *--new_end = char(*--old_end + (new_width - m_width)); { // extend 0-padding char* new_begin = new_end - (new_width - m_width); std::fill(new_begin, new_end, 0); new_end = new_begin; } { // copy string payload const char* old_begin = old_end - (m_width - 1); if (static_cast<size_t>(old_end - old_begin) < m_width) // non-null string new_end = std::copy_backward(old_begin, old_end, new_end); old_end = old_begin; } } } else { // m_width == 0. Expand to new width. while (new_end != base) { REALM_ASSERT_3(new_width, <=, max_width); *--new_end = static_cast<char>(new_width); { char* new_begin = new_end - (new_width - 1); std::fill(new_begin, new_end, 0); // Fill with zero bytes new_end = new_begin; } } } m_width = uint_least8_t(new_width); } REALM_ASSERT_3(0, <, m_width); // Set the value char* begin = m_data + (ndx * m_width); char* end = begin + (m_width - 1); begin = std::copy_n(value.data(), value.size(), begin); std::fill(begin, end, 0); // Pad with zero bytes static_assert(max_width <= max_width, "Padding size must fit in 7-bits"); if (value.is_null()) { REALM_ASSERT_3(m_width, <=, 128); *end = static_cast<char>(m_width); } else { int pad_size = int(end - begin); *end = char(pad_size); } } void ArrayString::insert(size_t ndx, StringData value) { REALM_ASSERT_3(ndx, <=, m_size); REALM_ASSERT(value.size() < max_width); // otherwise we have to use another column type // Check if we need to copy before modifying copy_on_write(); // Throws // Todo: Below code will perform up to 3 memcpy() operations in worst case. Todo, if we improve the // allocator to make a gap for the new value for us, we can have just 1. We can also have 2 by merging // memmove() and set(), but it's a bit complex. May be done after support of realm::null() is completed. // Allocate room for the new value alloc(m_size + 1, m_width); // Throws // Make gap for new value memmove(m_data + m_width * (ndx + 1), m_data + m_width * ndx, m_width * (m_size - ndx)); m_size++; // Set new value set(ndx, value); return; } void ArrayString::erase(size_t ndx) { REALM_ASSERT_3(ndx, <, m_size); // Check if we need to copy before modifying copy_on_write(); // Throws // move data backwards after deletion if (ndx < m_size - 1) { char* new_begin = m_data + ndx * m_width; char* old_begin = new_begin + m_width; char* old_end = m_data + m_size * m_width; std::copy_n(old_begin, old_end - old_begin, new_begin); } --m_size; // Update size in header set_header_size(m_size); } size_t ArrayString::calc_byte_len(size_t num_items, size_t width) const { return header_size + (num_items * width); } size_t ArrayString::calc_item_count(size_t bytes, size_t width) const noexcept { if (width == 0) return size_t(-1); // zero-width gives infinite space size_t bytes_without_header = bytes - header_size; return bytes_without_header / width; } size_t ArrayString::count(StringData value, size_t begin, size_t end) const noexcept { size_t num_matches = 0; size_t begin_2 = begin; for (;;) { size_t ndx = find_first(value, begin_2, end); if (ndx == not_found) break; ++num_matches; begin_2 = ndx + 1; } return num_matches; } size_t ArrayString::find_first(StringData value, size_t begin, size_t end) const noexcept { if (end == size_t(-1)) end = m_size; REALM_ASSERT(begin <= m_size && end <= m_size && begin <= end); if (m_width == 0) { if (m_nullable) // m_width == 0 implies that all elements in the array are NULL return value.is_null() && begin < m_size ? begin : npos; else return value.size() == 0 && begin < m_size ? begin : npos; } // A string can never be wider than the column width if (m_width <= value.size()) return size_t(-1); if (m_nullable ? value.is_null() : value.size() == 0) { for (size_t i = begin; i != end; ++i) { if (m_nullable ? is_null(i) : get(i).size() == 0) return i; } } else if (value.size() == 0) { const char* data = m_data + (m_width - 1); for (size_t i = begin; i != end; ++i) { size_t data_i_size = (m_width - 1) - data[i * m_width]; // left-hand-side tests if array element is NULL if (REALM_UNLIKELY(data_i_size == 0)) return i; } } else { for (size_t i = begin; i != end; ++i) { const char* data = m_data + (i * m_width); size_t j = 0; for (;;) { if (REALM_LIKELY(data[j] != value[j])) break; ++j; if (REALM_UNLIKELY(j == value.size())) { size_t data_size = (m_width - 1) - data[m_width - 1]; if (REALM_LIKELY(data_size == value.size())) return i; break; } } } } return not_found; } void ArrayString::find_all(IntegerColumn& result, StringData value, size_t add_offset, size_t begin, size_t end) { size_t begin_2 = begin; for (;;) { size_t ndx = find_first(value, begin_2, end); if (ndx == not_found) break; result.add(add_offset + ndx); // Throws begin_2 = ndx + 1; } } bool ArrayString::compare_string(const ArrayString& c) const noexcept { if (c.size() != size()) return false; for (size_t i = 0; i < size(); ++i) { if (get(i) != c.get(i)) return false; } return true; } ref_type ArrayString::bptree_leaf_insert(size_t ndx, StringData value, TreeInsertBase& state) { size_t leaf_size = size(); REALM_ASSERT_3(leaf_size, <=, REALM_MAX_BPNODE_SIZE); if (leaf_size < ndx) ndx = leaf_size; if (REALM_LIKELY(leaf_size < REALM_MAX_BPNODE_SIZE)) { insert(ndx, value); // Throws return 0; // Leaf was not split } // Split leaf node ArrayString new_leaf(m_alloc, m_nullable); new_leaf.create(); // Throws if (ndx == leaf_size) { new_leaf.add(value); // Throws state.m_split_offset = ndx; } else { for (size_t i = ndx; i != leaf_size; ++i) new_leaf.add(get(i)); // Throws truncate(ndx); // Throws add(value); // Throws state.m_split_offset = ndx + 1; } state.m_split_size = leaf_size + 1; return new_leaf.get_ref(); } MemRef ArrayString::slice(size_t offset, size_t slice_size, Allocator& target_alloc) const { REALM_ASSERT(is_attached()); // FIXME: This can be optimized as a single contiguous copy // operation. ArrayString array_slice(target_alloc, m_nullable); _impl::ShallowArrayDestroyGuard dg(&array_slice); array_slice.create(); // Throws size_t begin = offset; size_t end = offset + slice_size; for (size_t i = begin; i != end; ++i) { StringData value = get(i); array_slice.add(value); // Throws } dg.release(); return array_slice.get_mem(); } #ifdef REALM_DEBUG // LCOV_EXCL_START ignore debug functions void ArrayString::string_stats() const { size_t total = 0; size_t longest = 0; for (size_t i = 0; i < m_size; ++i) { StringData str = get(i); size_t str_size = str.size() + 1; total += str_size; if (str_size > longest) longest = str_size; } size_t array_size = m_size * m_width; size_t zeroes = array_size - total; size_t zavg = zeroes / (m_size ? m_size : 1); // avoid possible div by zero std::cout << "Size: " << m_size << "\n"; std::cout << "Width: " << m_width << "\n"; std::cout << "Total: " << array_size << "\n"; std::cout << "Capacity: " << m_capacity << "\n\n"; std::cout << "Bytes string: " << total << "\n"; std::cout << " longest: " << longest << "\n"; std::cout << "Bytes zeroes: " << zeroes << "\n"; std::cout << " avg: " << zavg << "\n"; } void ArrayString::to_dot(std::ostream& out, StringData title) const { ref_type ref = get_ref(); if (title.size() != 0) { out << "subgraph cluster_" << ref << " {" << std::endl; out << " label = \"" << title << "\";" << std::endl; out << " color = white;" << std::endl; } out << "n" << std::hex << ref << std::dec << "[shape=none,label=<"; out << "<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\"><TR>" << std::endl; // Header out << "<TD BGCOLOR=\"lightgrey\"><FONT POINT-SIZE=\"7\">"; out << "0x" << std::hex << ref << std::dec << "</FONT></TD>" << std::endl; for (size_t i = 0; i < m_size; ++i) out << "<TD>\"" << get(i) << "\"</TD>" << std::endl; out << "</TR></TABLE>>];" << std::endl; if (title.size() != 0) out << "}" << std::endl; to_dot_parent_edge(out); } #endif // LCOV_EXCL_STOP ignore debug functions <|endoftext|>
<commit_before>/*========================================================================= Program: Converter Base Class Language: C++ Copyright (c) Brigham and Women's Hospital. All rights reserved. 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 "rib_converter_base.h" RIBConverterBase::RIBConverterBase() { this->nodeHandle = NULL; } RIBConverterBase::RIBConverterBase(ros::NodeHandle *nh) { this->setNodeHandle(nh); } RIBConverterBase::RIBConverterBase(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh) { this->topicPublish = topicPublish; this->topicSubscribe = topicSubscribe; this->setNodeHandle(nh); } RIBConverterBase::~RIBConverterBase() { } void RIBConverterBase::setup(ros::NodeHandle* nh, uint32_t queuSize) { this->setNodeHandle(nh); this->setQueueSize(queueSize); } //void RIBConverterBase::setup(ros::NodeHandle* nh, igtl::Socket * socket, const char* topicSubscribe, const char* topicPublish) //{ // this->nodeHandle = nh; // this->socket = socket; // this->topicSubscribe = topicSubscribe; // this->topicPublish = topicPublish; //} <commit_msg>Call setQueue in setup function.<commit_after>/*========================================================================= Program: Converter Base Class Language: C++ Copyright (c) Brigham and Women's Hospital. All rights reserved. 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 "rib_converter_base.h" RIBConverterBase::RIBConverterBase() { this->nodeHandle = NULL; } RIBConverterBase::RIBConverterBase(ros::NodeHandle *nh) { this->setNodeHandle(nh); } RIBConverterBase::RIBConverterBase(const char* topicPublish, const char* topicSubscribe, ros::NodeHandle *nh) { this->topicPublish = topicPublish; this->topicSubscribe = topicSubscribe; this->setNodeHandle(nh); } RIBConverterBase::~RIBConverterBase() { } void RIBConverterBase::setup(ros::NodeHandle* nh, uint32_t queuSize) { this->setNodeHandle(nh); this->setQueue(nh); this->setQueueSize(queueSize); } //void RIBConverterBase::setup(ros::NodeHandle* nh, igtl::Socket * socket, const char* topicSubscribe, const char* topicPublish) //{ // this->nodeHandle = nh; // this->socket = socket; // this->topicSubscribe = topicSubscribe; // this->topicPublish = topicPublish; //} <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_COMPONENT_LINEARSOLVER_CGLINEARSOLVER_INL #define SOFA_COMPONENT_LINEARSOLVER_CGLINEARSOLVER_INL #include <SofaBaseLinearSolver/CGLinearSolver.h> #include <sofa/core/visual/VisualParams.h> #include <SofaBaseLinearSolver/FullMatrix.h> #include <SofaBaseLinearSolver/SparseMatrix.h> #include <SofaBaseLinearSolver/CompressedRowSparseMatrix.h> #include <sofa/simulation/MechanicalVisitor.h> #include <sofa/helper/system/thread/CTime.h> #include <sofa/helper/AdvancedTimer.h> #include <sofa/core/ObjectFactory.h> #include <iostream> namespace sofa { namespace component { namespace linearsolver { /// Linear system solver using the conjugate gradient iterative algorithm template<class TMatrix, class TVector> CGLinearSolver<TMatrix,TVector>::CGLinearSolver() : f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") ) , f_tolerance( initData(&f_tolerance,(SReal)1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") ) , f_smallDenominatorThreshold( initData(&f_smallDenominatorThreshold,(SReal)1e-5,"threshold","minimum value of the denominator in the conjugate Gradient solution") ) , f_warmStart( initData(&f_warmStart,false,"warmStart","Use previous solution as initial solution") ) , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") ) , f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") ) { f_graph.setWidget("graph"); #ifdef DISPLAY_TIME timeStamp = 1.0 / (SReal)sofa::helper::system::thread::CTime::getRefTicksPerSec(); #endif f_maxIter.setRequired(true); f_tolerance.setRequired(true); f_smallDenominatorThreshold.setRequired(true); } template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::init() { if(f_maxIter.getValue() < 0) { msg_warning() << "'iterations' must be a positive value" << msgendl << "default value used: 25"; f_maxIter.setValue(25); } if(f_tolerance.getValue() < 0.0) { msg_warning() << "'tolerance' must be a positive value" << msgendl << "default value used: 1e-5"; f_tolerance.setValue(1e-5); } if(f_smallDenominatorThreshold.getValue() < 0.0) { msg_warning() << "'threshold' must be a positive value" << msgendl << "default value used: 1e-5"; f_smallDenominatorThreshold.setValue(1e-5); } } template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::resetSystem() { f_graph.beginEdit()->clear(); f_graph.endEdit(); Inherit::resetSystem(); } template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(const sofa::core::MechanicalParams* mparams) { #ifdef DISPLAY_TIME sofa::helper::system::thread::CTime timer; time2 = (SReal) timer.getTime(); #endif Inherit::setSystemMBKMatrix(mparams); #ifdef DISPLAY_TIME time2 = ((SReal) timer.getTime() - time2) * timeStamp; #endif } /// Solve Mx=b template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::solve(Matrix& M, Vector& x, Vector& b) { #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printComment("ConjugateGradient"); #endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printNode("VectorAllocation"); #endif const core::ExecParams* params = core::ExecParams::defaultInstance(); typename Inherit::TempVectorContainer vtmp(this, params, M, x, b); Vector& p = *vtmp.createTempVector(); Vector& q = *vtmp.createTempVector(); Vector& r = *vtmp.createTempVector(); const bool verbose = f_verbose.getValue(); double rho, rho_1=0, alpha, beta; msg_info_when(verbose) << " CGLinearSolver, b = " << b ; /// Compute the initial residual r if( f_warmStart.getValue() ) { r = M * x; r.eq( b, r, -1.0 ); // initial residual r = b - Ax; } else { x.clear(); r = b; // initial residual } /// Compute the norm of the right-hand-side vector b double normb = b.norm(); std::map < std::string, sofa::helper::vector<SReal> >& graph = *f_graph.beginEdit(); sofa::helper::vector<SReal>& graph_error = graph[(this->isMultiGroup()) ? this->currentNode->getName()+std::string("-Error") : std::string("Error")]; graph_error.clear(); sofa::helper::vector<SReal>& graph_den = graph[(this->isMultiGroup()) ? this->currentNode->getName()+std::string("-Denominator") : std::string("Denominator")]; graph_den.clear(); graph_error.push_back(1); unsigned nb_iter; const char* endcond = "iterations"; #ifdef DISPLAY_TIME sofa::helper::system::thread::CTime timer; time1 = (SReal) timer.getTime(); #endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printCloseNode("VectorAllocation"); #endif for( nb_iter=1; nb_iter<=f_maxIter.getValue(); nb_iter++ ) { #ifdef SOFA_DUMP_VISITOR_INFO std::ostringstream comment; if (simulation::Visitor::isPrintActivated()) { comment << "Iteration_" << nb_iter; simulation::Visitor::printNode(comment.str()); } #endif /// Compute p = r^2 rho = r.dot(r); /// Compute the error from the norm of ρ and b double normr = sqrt(rho); double err = normr/normb; graph_error.push_back(err); /// Break condition = TOLERANCE criterion regarding the error err is reached if (err <= f_tolerance.getValue()) { /// Tolerance met at first step, tolerance value might not be relevant (do one more step) if(nb_iter == 1) { msg_warning() << "tolerance reached at first iteration of CG" << msgendl << "Check the 'tolerance' data field, you might decrease it"; } else { endcond = "tolerance"; #ifdef SOFA_DUMP_VISITOR_INFO if (simulation::Visitor::isPrintActivated()) simulation::Visitor::printCloseNode(comment.str()); #endif break; } } /// Compute the value of p, conjugate with x if( nb_iter==1 ) // FIRST step p = r; else // ALL other steps { beta = rho / rho_1; /// Update p = p*beta + r; cgstep_beta(params, p,r,beta); } if( verbose ) { msg_info() << "p : " << p; } /// Compute the matrix-vector product : M p q = M*p; if( verbose ) { msg_info() << "q = M p : " << q; } /// Compute the denominator : p M p double den = p.dot(q); graph_den.push_back(den); /// Break condition = THRESHOLD criterion regarding the denominator is reached (but do at least one iteration) if (fabs(den) <= f_smallDenominatorThreshold.getValue()) { /// Threshold met at first step, threshold value might not be relevant (do one more step) if(nb_iter == 1 && den != 0.0) { msg_warning() << "denominator threshold reached at first iteration of CG" << msgendl << "Check the 'threshold' data field, you might decrease it"; } else { endcond = "threshold"; if( verbose ) { msg_info() << "CGLinearSolver, den = " << den <<", smallDenominatorThreshold = " << f_smallDenominatorThreshold.getValue(); } #ifdef SOFA_DUMP_VISITOR_INFO if (simulation::Visitor::isPrintActivated()) simulation::Visitor::printCloseNode(comment.str()); #endif break; } } /// Compute the coefficient α for the conjugate direction alpha = rho/den; /// End of the CG step : update x and r cgstep_alpha(params, x,r,p,q,alpha); if( verbose ) { msg_info() << "den = " << den << ", alpha = " << alpha; msg_info() << "x : " << x; msg_info() << "r : " << r; } rho_1 = rho; #ifdef SOFA_DUMP_VISITOR_INFO if (simulation::Visitor::isPrintActivated()) simulation::Visitor::printCloseNode(comment.str()); #endif } #ifdef DISPLAY_TIME time1 = (SReal)(((SReal) timer.getTime() - time1) * timeStamp / (nb_iter-1)); #endif f_graph.endEdit(); sofa::helper::AdvancedTimer::valSet("CG iterations", nb_iter); // x is the solution of the system #ifdef DISPLAY_TIME dmsg_info() << " solve, CG = " << time1 << " build = " << time2; #endif dmsg_info() << "solve, nbiter = "<<nb_iter<<" stop because of "<<endcond; dmsg_info_when( verbose ) <<"solve, solution = "<< x ; vtmp.deleteTempVector(&p); vtmp.deleteTempVector(&q); vtmp.deleteTempVector(&r); } template<class TMatrix, class TVector> inline void CGLinearSolver<TMatrix,TVector>::cgstep_beta(const core::ExecParams* /*params*/, Vector& p, Vector& r, SReal beta) { // p = p*beta + r p *= beta; p += r; } template<class TMatrix, class TVector> inline void CGLinearSolver<TMatrix,TVector>::cgstep_alpha(const core::ExecParams* /*params*/, Vector& x, Vector& r, Vector& p, Vector& q, SReal alpha) { // x = x + alpha p x.peq(p,alpha); // r = r - alpha q r.peq(q,-alpha); } } // namespace linearsolver } // namespace component } // namespace sofa #endif // SOFA_COMPONENT_LINEARSOLVER_CGLINEARSOLVER_INL <commit_msg>CLEAN spaces<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #ifndef SOFA_COMPONENT_LINEARSOLVER_CGLINEARSOLVER_INL #define SOFA_COMPONENT_LINEARSOLVER_CGLINEARSOLVER_INL #include <SofaBaseLinearSolver/CGLinearSolver.h> #include <sofa/core/visual/VisualParams.h> #include <SofaBaseLinearSolver/FullMatrix.h> #include <SofaBaseLinearSolver/SparseMatrix.h> #include <SofaBaseLinearSolver/CompressedRowSparseMatrix.h> #include <sofa/simulation/MechanicalVisitor.h> #include <sofa/helper/system/thread/CTime.h> #include <sofa/helper/AdvancedTimer.h> #include <sofa/core/ObjectFactory.h> #include <iostream> namespace sofa { namespace component { namespace linearsolver { /// Linear system solver using the conjugate gradient iterative algorithm template<class TMatrix, class TVector> CGLinearSolver<TMatrix,TVector>::CGLinearSolver() : f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") ) , f_tolerance( initData(&f_tolerance,(SReal)1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") ) , f_smallDenominatorThreshold( initData(&f_smallDenominatorThreshold,(SReal)1e-5,"threshold","minimum value of the denominator in the conjugate Gradient solution") ) , f_warmStart( initData(&f_warmStart,false,"warmStart","Use previous solution as initial solution") ) , f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") ) , f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") ) { f_graph.setWidget("graph"); #ifdef DISPLAY_TIME timeStamp = 1.0 / (SReal)sofa::helper::system::thread::CTime::getRefTicksPerSec(); #endif f_maxIter.setRequired(true); f_tolerance.setRequired(true); f_smallDenominatorThreshold.setRequired(true); } template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::init() { if(f_maxIter.getValue() < 0) { msg_warning() << "'iterations' must be a positive value" << msgendl << "default value used: 25"; f_maxIter.setValue(25); } if(f_tolerance.getValue() < 0.0) { msg_warning() << "'tolerance' must be a positive value" << msgendl << "default value used: 1e-5"; f_tolerance.setValue(1e-5); } if(f_smallDenominatorThreshold.getValue() < 0.0) { msg_warning() << "'threshold' must be a positive value" << msgendl << "default value used: 1e-5"; f_smallDenominatorThreshold.setValue(1e-5); } } template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::resetSystem() { f_graph.beginEdit()->clear(); f_graph.endEdit(); Inherit::resetSystem(); } template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(const sofa::core::MechanicalParams* mparams) { #ifdef DISPLAY_TIME sofa::helper::system::thread::CTime timer; time2 = (SReal) timer.getTime(); #endif Inherit::setSystemMBKMatrix(mparams); #ifdef DISPLAY_TIME time2 = ((SReal) timer.getTime() - time2) * timeStamp; #endif } /// Solve Mx=b template<class TMatrix, class TVector> void CGLinearSolver<TMatrix,TVector>::solve(Matrix& M, Vector& x, Vector& b) { #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printComment("ConjugateGradient"); #endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printNode("VectorAllocation"); #endif const core::ExecParams* params = core::ExecParams::defaultInstance(); typename Inherit::TempVectorContainer vtmp(this, params, M, x, b); Vector& p = *vtmp.createTempVector(); Vector& q = *vtmp.createTempVector(); Vector& r = *vtmp.createTempVector(); const bool verbose = f_verbose.getValue(); double rho, rho_1=0, alpha, beta; msg_info_when(verbose) << " CGLinearSolver, b = " << b ; /// Compute the initial residual r if( f_warmStart.getValue() ) { r = M * x; r.eq( b, r, -1.0 ); // initial residual r = b - Ax; } else { x.clear(); r = b; // initial residual } /// Compute the norm of the right-hand-side vector b double normb = b.norm(); std::map < std::string, sofa::helper::vector<SReal> >& graph = *f_graph.beginEdit(); sofa::helper::vector<SReal>& graph_error = graph[(this->isMultiGroup()) ? this->currentNode->getName()+std::string("-Error") : std::string("Error")]; graph_error.clear(); sofa::helper::vector<SReal>& graph_den = graph[(this->isMultiGroup()) ? this->currentNode->getName()+std::string("-Denominator") : std::string("Denominator")]; graph_den.clear(); graph_error.push_back(1); unsigned nb_iter; const char* endcond = "iterations"; #ifdef DISPLAY_TIME sofa::helper::system::thread::CTime timer; time1 = (SReal) timer.getTime(); #endif #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::printCloseNode("VectorAllocation"); #endif for( nb_iter=1; nb_iter<=f_maxIter.getValue(); nb_iter++ ) { #ifdef SOFA_DUMP_VISITOR_INFO std::ostringstream comment; if (simulation::Visitor::isPrintActivated()) { comment << "Iteration_" << nb_iter; simulation::Visitor::printNode(comment.str()); } #endif /// Compute p = r^2 rho = r.dot(r); /// Compute the error from the norm of ρ and b double normr = sqrt(rho); double err = normr/normb; graph_error.push_back(err); /// Break condition = TOLERANCE criterion regarding the error err is reached if (err <= f_tolerance.getValue()) { /// Tolerance met at first step, tolerance value might not be relevant (do one more step) if(nb_iter == 1) { msg_warning() << "tolerance reached at first iteration of CG" << msgendl << "Check the 'tolerance' data field, you might decrease it"; } else { endcond = "tolerance"; #ifdef SOFA_DUMP_VISITOR_INFO if (simulation::Visitor::isPrintActivated()) simulation::Visitor::printCloseNode(comment.str()); #endif break; } } /// Compute the value of p, conjugate with x if( nb_iter==1 ) // FIRST step p = r; else // ALL other steps { beta = rho / rho_1; /// Update p = p*beta + r; cgstep_beta(params, p,r,beta); } if( verbose ) { msg_info() << "p : " << p; } /// Compute the matrix-vector product : M p q = M*p; if( verbose ) { msg_info() << "q = M p : " << q; } /// Compute the denominator : p M p double den = p.dot(q); graph_den.push_back(den); /// Break condition = THRESHOLD criterion regarding the denominator is reached (but do at least one iteration) if (fabs(den) <= f_smallDenominatorThreshold.getValue()) { /// Threshold met at first step, threshold value might not be relevant (do one more step) if(nb_iter == 1 && den != 0.0) { msg_warning() << "denominator threshold reached at first iteration of CG" << msgendl << "Check the 'threshold' data field, you might decrease it"; } else { endcond = "threshold"; if( verbose ) { msg_info() << "CGLinearSolver, den = " << den <<", smallDenominatorThreshold = " << f_smallDenominatorThreshold.getValue(); } #ifdef SOFA_DUMP_VISITOR_INFO if (simulation::Visitor::isPrintActivated()) simulation::Visitor::printCloseNode(comment.str()); #endif break; } } /// Compute the coefficient α for the conjugate direction alpha = rho/den; /// End of the CG step : update x and r cgstep_alpha(params, x,r,p,q,alpha); if( verbose ) { msg_info() << "den = " << den << ", alpha = " << alpha; msg_info() << "x : " << x; msg_info() << "r : " << r; } rho_1 = rho; #ifdef SOFA_DUMP_VISITOR_INFO if (simulation::Visitor::isPrintActivated()) simulation::Visitor::printCloseNode(comment.str()); #endif } #ifdef DISPLAY_TIME time1 = (SReal)(((SReal) timer.getTime() - time1) * timeStamp / (nb_iter-1)); #endif f_graph.endEdit(); sofa::helper::AdvancedTimer::valSet("CG iterations", nb_iter); // x is the solution of the system #ifdef DISPLAY_TIME dmsg_info() << " solve, CG = " << time1 << " build = " << time2; #endif dmsg_info() << "solve, nbiter = "<<nb_iter<<" stop because of "<<endcond; dmsg_info_when( verbose ) <<"solve, solution = "<< x ; vtmp.deleteTempVector(&p); vtmp.deleteTempVector(&q); vtmp.deleteTempVector(&r); } template<class TMatrix, class TVector> inline void CGLinearSolver<TMatrix,TVector>::cgstep_beta(const core::ExecParams* /*params*/, Vector& p, Vector& r, SReal beta) { // p = p*beta + r p *= beta; p += r; } template<class TMatrix, class TVector> inline void CGLinearSolver<TMatrix,TVector>::cgstep_alpha(const core::ExecParams* /*params*/, Vector& x, Vector& r, Vector& p, Vector& q, SReal alpha) { // x = x + alpha p x.peq(p,alpha); // r = r - alpha q r.peq(q,-alpha); } } // namespace linearsolver } // namespace component } // namespace sofa #endif // SOFA_COMPONENT_LINEARSOLVER_CGLINEARSOLVER_INL <|endoftext|>
<commit_before><commit_msg>Setup change to accept less RAM memory<commit_after>#include <stdio.h> #include <iostream> // std::cerr #include "samsonDirectories.h" // SAMSON_SETUP_FILE #include "au/CommandLine.h" // au::CommandLine #include "SamsonSetup.h" // Own interface #include <errno.h> #include "au/Format.h" // au::Format #include "logMsg.h" // LM_X #define SETUP_num_io_threads_per_device "num_io_threads_per_device" #define SETUP_DEFAULT_num_io_threads_per_device 1 #define SETUP_max_file_size "max_file_size" #define SETUP_DEFAULT_max_file_size 104857600 // 100Mb #define SETUP_num_processes "num_processes" #define SETUP_DEFAULT_num_processes 2 #define SETUP_memory "memory" #ifdef __LP64__ #define SETUP_DEFAULT_memory 2147483648 // 2Gb #else #define SETUP_DEFAULT_memory 0x6fffffff // 1Gb #endif #define SETUP_shared_memory_size_per_buffer "shm_size_per_buffer" #define SETUP_DEFAULT_shared_memory_size_per_buffer 67108864 // 64 Mb #define SETUP_DEFAULT_load_buffer_size 67108864 // 64 Mb #define SETUP_num_paralell_outputs "num_paralell_outputs" #define SETUP_DEFAULT_num_paralell_outputs 2 #define SETUP_timeout_secs_isolatedProcess "timeout_secs_isolatedProcess" #define SETUP_DEFAULT_timeout_secs_isolatedProcess 300 namespace ss { static SamsonSetup *samsonSetup = NULL; SamsonSetup *SamsonSetup::shared() { if( !samsonSetup) LM_X(1,("SamsonSetup not loaded. It should be initizalized at the begining of the main process")); return samsonSetup; } void destroy_samson_setup() { if( samsonSetup ) { delete samsonSetup; samsonSetup = NULL; } } void SamsonSetup::load() { samsonSetup = new SamsonSetup( ); } void SamsonSetup::load( std::string workingDirectory ) { samsonSetup = new SamsonSetup( workingDirectory ); atexit(destroy_samson_setup); } void SamsonSetup::createDirectory( std::string path ) { if( mkdir(path.c_str() , 0755) == -1 ) { if( errno != EEXIST ) LM_X(1,("Error creating directory %s", path.c_str())); } } SamsonSetup::SamsonSetup( ) { std::map<std::string,std::string> items; init( items ); } SamsonSetup::SamsonSetup( std::string workingDirectory ) { baseDirectory = workingDirectory; controllerDirectory = workingDirectory + "/controller"; dataDirectory = workingDirectory + "/data"; modulesDirectory = workingDirectory + "/modules"; setupDirectory = workingDirectory + "/etc"; setupFile = setupDirectory + "/setup.txt"; configDirectory = workingDirectory + "/config"; // Create directories if necessary createDirectory( workingDirectory ); createDirectory( controllerDirectory ); createDirectory( dataDirectory ); createDirectory( modulesDirectory ); createDirectory( setupDirectory ); createDirectory( configDirectory ); // Load values from file ( if exist ) std::map<std::string,std::string> items; FILE *file = fopen( setupFile.c_str() ,"r"); if (!file) { std::cerr << "Warning: Setup file "<< setupFile <<" not found\n"; } else { char line[2000]; while( fgets(line, sizeof(line), file)) { au::CommandLine c; c.parse(line); if( c.get_num_arguments() == 0 ) continue; // Skip comments std::string mainCommand = c.get_argument(0); if( mainCommand[0] == '#' ) continue; if (c.get_num_arguments() >= 2) { std::string name = c.get_argument(0); std::string value = c.get_argument(1); std::map<std::string,std::string>::iterator i = items.find( name ); if( i!= items.end() ) items.erase( i ); items.insert( std::pair<std::string , std::string>( name ,value ) ); } } fclose(file); } init( items ); } void SamsonSetup::init( std::map<std::string,std::string> &items ) { // General setup num_processes = getInt( items, SETUP_num_processes , SETUP_DEFAULT_num_processes ); // Disk management num_io_threads_per_device = getInt( items, SETUP_num_io_threads_per_device , SETUP_DEFAULT_num_io_threads_per_device ); max_file_size = getUInt64( items, SETUP_max_file_size, SETUP_DEFAULT_max_file_size); // Memory - System memory = getUInt64( items, SETUP_memory , SETUP_DEFAULT_memory); shared_memory_size_per_buffer = getUInt64( items, SETUP_shared_memory_size_per_buffer , SETUP_DEFAULT_shared_memory_size_per_buffer ); // IsolatedProcess timeout timeout_secs_isolatedProcess = getInt( items, SETUP_timeout_secs_isolatedProcess , SETUP_DEFAULT_timeout_secs_isolatedProcess ); // Default value for other fields load_buffer_size = SETUP_DEFAULT_load_buffer_size; // Derived parameters num_paralell_outputs = getInt( items, SETUP_num_paralell_outputs , SETUP_DEFAULT_num_paralell_outputs ); if( !check() ) { std::cerr << "Error in setup file " << setupFile << "\n"; exit(0); } } bool SamsonSetup::check() { /* if ( memory < 1024*1024*1024 ) { std::cerr << "Memory should be at least 1Gb\n"; return false; } */ if ( num_io_threads_per_device < 1) { std::cerr << "Minimum number of threads per device 1.\n"; return false; } if ( num_io_threads_per_device > 10) { std::cerr << "Maximum number of threads per device 10.\n"; return false; } int max_num_paralell_outputs = ( memory - num_processes*shared_memory_size_per_buffer ) / (2*max_file_size); if( num_paralell_outputs > max_num_paralell_outputs ) { LM_X(1,("Num of maximum paralell outputs is too high to the memory setup. Review num_paralell_outputs in setup.txt file. Current value %d Max value %d (memory(%lu) - num_processes(%d)*shared_memory_size_per_buffer(%lu) ) / (2*max_file_size(%lu))", num_paralell_outputs , max_num_paralell_outputs, memory, num_processes, shared_memory_size_per_buffer, max_file_size )); return false; } if ( num_paralell_outputs < 2 ) { std::cerr << "Error in the memory setup. Please, review setup since the maximum number of outputs has to be at least 2\n"; std::cerr << "Memory: " << au::Format::string( memory , "B" ) << "\n"; std::cerr << "Shared memory: " << au::Format::string( num_processes*shared_memory_size_per_buffer , "B" ) << "\n"; std::cerr << "Max file size: " << au::Format::string( max_file_size , "B" ) << "\n"; return false; } return true; } std::string SamsonSetup::dataFile( std::string filename ) { return samsonSetup->dataDirectory + "/" + filename; } size_t SamsonSetup::getUInt64(std::map<std::string,std::string> &items, std::string name , size_t defaultValue ) { std::map<std::string,std::string>::iterator i = items.find( name ); if( i == items.end() ) return defaultValue; else return atoll(i->second.c_str()); } int SamsonSetup::getInt(std::map<std::string,std::string> &items, std::string name , int defaultValue ) { std::map<std::string,std::string>::iterator i = items.find( name ); if( i == items.end() ) return defaultValue; else return atoi(i->second.c_str()); } } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH #define DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH #include <dune/common/fvector.hh> #include <dune/common/fmatrix.hh> #include <dune/pdelab/gridfunctionspace/localfunctionspace.hh> #include <dune/stuff/common/memory.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace BaseFunctionSet { // forward, to be used in the traits and to allow for specialization template< class PdelabSpaceImp, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class PdelabWrapper; template< class PdelabSpaceImp, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class PdelabWrapperTraits { public: typedef PdelabWrapper < PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols > derived_type; private: typedef PDELab::LocalFunctionSpace< PdelabSpaceImp, PDELab::TrialSpaceTag > PdelabLFSType; typedef FiniteElementInterfaceSwitch< typename PdelabSpaceImp::Traits::FiniteElementType > FESwitchType; public: typedef typename FESwitchType::Basis BackendType; typedef EntityImp EntityType; private: friend class PdelabWrapper < PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >; }; template< class PdelabSpaceType, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim > class PdelabWrapper< PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > : public BaseFunctionSetInterface< PdelabWrapperTraits< PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 >, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > { typedef PdelabWrapper < PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > ThisType; typedef BaseFunctionSetInterface < PdelabWrapperTraits< PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 >, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > BaseType; public: typedef PdelabWrapperTraits < PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1 > Traits; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; private: typedef typename Traits::PdelabLFSType PdelabLFSType; typedef typename Traits::FESwitchType FESwitchType; public: typedef DomainFieldImp DomainFieldType; static const unsigned int dimDomain = domainDim; typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType; typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = rangeDim; static const unsigned int dimRangeCols = 1; typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType; typedef Dune::FieldMatrix< RangeFieldType, dimRange, dimDomain > JacobianRangeType; PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent) : BaseType(ent) , order_(0) { PdelabLFSType* lfs_ptr = new PdelabLFSType(space); lfs_ptr->bind(this->entity()); lfs_ = std::unique_ptr< PdelabLFSType >(lfs_ptr); backend_ = std::unique_ptr< BackendType >(new BackendType(FESwitchType::basis(lfs_->finiteElement()))); order_ = backend_->order(); } PdelabWrapper(ThisType&& source) : BaseType(source.entity()) , order_(std::move(source.order_)) , lfs_(std::move(source.lfs_)) , backend_(std::move(source.backend_)) {} PdelabWrapper(const ThisType& /*other*/) = delete; ThisType& operator=(const ThisType& /*other*/) = delete; const BackendType& backend() const { return *backend_; } virtual size_t size() const DS_OVERRIDE { return backend_->size(); } virtual size_t order() const DS_OVERRIDE { return order_; } virtual void evaluate(const DomainType& xx, std::vector< RangeType >& ret) const DS_OVERRIDE { assert(ret.size() >= backend_->size()); backend_->evaluateFunction(xx, ret); } using BaseType::evaluate; virtual void jacobian(const DomainType& xx, std::vector< JacobianRangeType >& ret) const DS_OVERRIDE { assert(ret.size() >= backend_->size()); backend_->evaluateJacobian(xx, ret); DomainType tmp(0.0); const auto jocobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx); for (size_t ii = 0; ii < ret.size(); ++ii) { jocobian_inverse_transposed.mv(ret[ii][0], tmp); ret[ii][0] = tmp; } } // ... jacobian(...) using BaseType::jacobian; private: size_t order_; std::unique_ptr< const PdelabLFSType > lfs_; std::unique_ptr< const BackendType > backend_; }; // class PdelabWrapper } // namespace BaseFunctionSet } // namespace GDT } // namespace Dune #endif // DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH <commit_msg>[basefunctionset.pdelab] update * replaced override -> final in virtual functions * specialize for range 1x1 and give a static error otherwise * some notes and clean up<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH #define DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH #include <type_traits> #include <dune/common/fvector.hh> #include <dune/common/fmatrix.hh> #include <dune/common/typetraits.hh> #include <dune/pdelab/gridfunctionspace/localfunctionspace.hh> #include <dune/stuff/common/memory.hh> #include "interface.hh" namespace Dune { namespace GDT { namespace BaseFunctionSet { // forward, to be used in the traits and to allow for specialization template< class PdelabSpaceImp, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class PdelabWrapper { static_assert(Dune::AlwaysFalse< PdelabSpaceImp >::value, "Untested for arbitrary dimension!"); }; // forward, to allow for specialization template< class PdelabSpaceImp, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class PdelabWrapperTraits { static_assert(Dune::AlwaysFalse< PdelabSpaceImp >::value, "Untested for arbitrary dimension!"); }; //! Specialization for dimRange = 1, dimRangeRows = 1 template< class PdelabSpaceImp, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp > class PdelabWrapperTraits< PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > { public: typedef PdelabWrapper < PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > derived_type; private: typedef PDELab::LocalFunctionSpace< PdelabSpaceImp, PDELab::TrialSpaceTag > PdelabLFSType; typedef FiniteElementInterfaceSwitch< typename PdelabSpaceImp::Traits::FiniteElementType > FESwitchType; public: typedef typename FESwitchType::Basis BackendType; typedef EntityImp EntityType; private: friend class PdelabWrapper < PdelabSpaceImp, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >; }; //! Specialization for dimRange = 1, dimRangeRows = 1 template< class PdelabSpaceType, class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp > class PdelabWrapper< PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > : public BaseFunctionSetInterface< PdelabWrapperTraits< PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > { typedef PdelabWrapper < PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > ThisType; typedef BaseFunctionSetInterface < PdelabWrapperTraits< PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 >, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > BaseType; public: typedef PdelabWrapperTraits < PdelabSpaceType, EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1, 1 > Traits; typedef typename Traits::BackendType BackendType; typedef typename Traits::EntityType EntityType; private: typedef typename Traits::PdelabLFSType PdelabLFSType; typedef typename Traits::FESwitchType FESwitchType; public: typedef DomainFieldImp DomainFieldType; static const unsigned int dimDomain = domainDim; typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType; typedef RangeFieldImp RangeFieldType; static const unsigned int dimRange = 1; static const unsigned int dimRangeCols = 1; typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType; typedef Dune::FieldMatrix< RangeFieldType, dimRange, dimDomain > JacobianRangeType; PdelabWrapper(const PdelabSpaceType& space, const EntityType& ent, const size_t oo) : BaseType(ent) , order_(oo) , tmp_domain_(RangeFieldType(0)) { PdelabLFSType* lfs_ptr = new PdelabLFSType(space); lfs_ptr->bind(this->entity()); lfs_ = std::unique_ptr< PdelabLFSType >(lfs_ptr); backend_ = std::unique_ptr< BackendType >(new BackendType(FESwitchType::basis(lfs_->finiteElement()))); order_ = backend_->order(); } // PdelabWrapper(...) PdelabWrapper(ThisType&& source) : BaseType(source.entity()) , order_(std::move(source.order_)) , tmp_domain_(RangeFieldType(0)) , lfs_(std::move(source.lfs_)) , backend_(std::move(source.backend_)) {} PdelabWrapper(const ThisType& /*other*/) = delete; ThisType& operator=(const ThisType& /*other*/) = delete; const BackendType& backend() const { return *backend_; } virtual size_t size() const DS_FINAL { return backend_->size(); } virtual size_t order() const DS_FINAL { return order_; } virtual void evaluate(const DomainType& xx, std::vector< RangeType >& ret) const DS_FINAL { assert(ret.size() >= backend_->size()); backend_->evaluateFunction(xx, ret); } // ... evaluate(...) using BaseType::evaluate; virtual void jacobian(const DomainType& xx, std::vector< JacobianRangeType >& ret) const DS_FINAL { assert(ret.size() >= backend_->size()); backend_->evaluateJacobian(xx, ret); const auto jacobian_inverse_transposed = this->entity().geometry().jacobianInverseTransposed(xx); for (size_t ii = 0; ii < ret.size(); ++ii) { jacobian_inverse_transposed.mv(ret[ii][0], tmp_domain_); ret[ii][0] = tmp_domain_; } } // ... jacobian(...) using BaseType::jacobian; private: size_t order_; mutable DomainType tmp_domain_; std::unique_ptr< const PdelabLFSType > lfs_; std::unique_ptr< const BackendType > backend_; }; // class PdelabWrapper } // namespace BaseFunctionSet } // namespace GDT } // namespace Dune #endif // DUNE_GDT_BASEFUNCTIONSET_PDELAB_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH #define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH #include <vector> #include <dune/common/dynvector.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/interface.hh> #include <dune/stuff/common/vector.hh> #include <dune/stuff/common/matrix.hh> #include <dune/gdt/mapper/interface.hh> namespace Dune { namespace GDT { template< class VectorImp > class LocalDoFVector { public: typedef typename Dune::Stuff::LA::VectorInterface< typename VectorImp::Traits >::derived_type VectorType; typedef typename VectorType::ElementType ElementType; template< class M, class EntityType > LocalDoFVector(const MapperInterface< M >& mapper, const EntityType& entity, VectorType& vector) : indices_(mapper.numDofs(entity)) , vector_(vector) { mapper.globalIndices(entity, indices_); } ~LocalDoFVector() {} size_t size() const { return indices_.size(); } ElementType get(const size_t ii) const { assert(ii < indices_.size()); return vector_.get(indices_[ii]); } void set(const size_t ii, const ElementType& val) { assert(ii < indices_.size()); vector_.set(indices_[ii], val); } void add(const size_t ii, const ElementType& val) { assert(ii < indices_.size()); vector_.add(indices_[ii], val); } private: Dune::DynamicVector< size_t > indices_; VectorType& vector_; }; // class LocalDoFVector // forward, includes are below template< class SpaceImp, class VectorImp > class DiscreteFunctionDefaultConst; template< class SpaceImp, class VectorImp > class DiscreteFunctionDefault; // forward, to be used in the traits template< class SpaceImp, class VectorImp > class DiscreteFunctionLocalConst; template< class SpaceImp, class VectorImp > class DiscreteFunctionLocalConstTraits { public: typedef DiscreteFunctionLocalConst< SpaceImp, VectorImp > derived_type; typedef typename DiscreteFunctionDefaultConst< SpaceImp, VectorImp >::EntityType EntityType; }; template< class SpaceImp, class VectorImp > class DiscreteFunctionLocalConst : public Dune::Stuff::LocalFunctionInterface< DiscreteFunctionLocalConstTraits< SpaceImp, VectorImp >, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols > { public: typedef DiscreteFunctionLocalConstTraits< SpaceImp, VectorImp > Traits; typedef DiscreteFunctionDefaultConst< SpaceImp, VectorImp > DiscreteFunctionType; typedef typename DiscreteFunctionType::SpaceType SpaceType; typedef LocalDoFVector< typename DiscreteFunctionType::VectorType > LocalDoFVectorType; typedef typename DiscreteFunctionType::EntityType EntityType; typedef typename SpaceType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = SpaceType::dimDomain; typedef typename SpaceType::RangeFieldType RangeFieldType; static const unsigned int dimRange = SpaceType::dimRange; static const unsigned int dimRangeCols = SpaceType::dimRangeCols; private: typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType; public: typedef typename BaseFunctionSetType::DomainType DomainType; typedef typename BaseFunctionSetType::RangeType RangeType; typedef typename BaseFunctionSetType::JacobianRangeType JacobianRangeType; DiscreteFunctionLocalConst(const DiscreteFunctionType& func, const EntityType& ent) : function_(func) , entity_(ent) , base_(function_.space().baseFunctionSet(entity_)) , localVector_(function_.space().mapper(), entity_, const_cast< typename DiscreteFunctionType::VectorType& >(*(function_.vector()))) , tmpBaseValues_(base_.size(), RangeType(0)) , tmpBaseJacobianValues_(base_.size(), JacobianRangeType(0)) { assert(localVector_.size() == base_.size()); } virtual ~DiscreteFunctionLocalConst() {} const DiscreteFunctionType& discreteFunction() const { return function_; } const EntityType& entity() const { return entity_; } const LocalDoFVectorType& vector() const { return localVector_; } int order() const { return base_.order(); } size_t size() const { return base_.size(); } void evaluate(const DomainType& x, RangeType& ret) const { Dune::Stuff::Common::clear(ret); assert(localVector_.size() == tmpBaseValues_.size()); base_.evaluate(x, tmpBaseValues_); for (size_t ii = 0; ii < localVector_.size(); ++ii) { tmpBaseValues_[ii] *= localVector_.get(ii); ret += tmpBaseValues_[ii]; } } // ... evaluate(...) RangeType evaluate(const DomainType& xx) const { RangeType ret; evaluate(xx, ret); return ret; } void jacobian(const DomainType& x, JacobianRangeType& ret) const { Dune::Stuff::Common::clear(ret); assert(localVector_.size() == tmpBaseJacobianValues_.size()); base_.jacobian(x, tmpBaseJacobianValues_); for (size_t ii = 0; ii < localVector_.size(); ++ii) { tmpBaseJacobianValues_[ii] *= localVector_.get(ii); ret += tmpBaseJacobianValues_[ii]; } } // ... jacobian(...) JacobianRangeType jacobian(const DomainType& xx) const { JacobianRangeType ret; jacobian(xx, ret); return ret; } private: const DiscreteFunctionType& function_; const EntityType& entity_; const BaseFunctionSetType base_; protected: LocalDoFVectorType localVector_; private: mutable std::vector< RangeType > tmpBaseValues_; mutable std::vector< JacobianRangeType > tmpBaseJacobianValues_; }; // class DiscreteFunctionLocalConst // forward, to be used in the traits template< class SpaceImp, class VectorImp > class DiscreteFunctionLocal; template< class SpaceImp, class VectorImp > class DiscreteFunctionLocalTraits { public: typedef DiscreteFunctionLocal< SpaceImp, VectorImp > derived_type; typedef typename DiscreteFunctionDefault< SpaceImp, VectorImp >::EntityType EntityType; }; template< class SpaceImp, class VectorImp > class DiscreteFunctionLocal : public DiscreteFunctionLocalConst< SpaceImp, VectorImp > , public Dune::Stuff::LocalFunctionInterface< DiscreteFunctionLocalTraits< SpaceImp, VectorImp >, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols > { typedef DiscreteFunctionLocalConst< SpaceImp, VectorImp > BaseType; public: typedef DiscreteFunctionDefault< SpaceImp, VectorImp > DiscreteFunctionType; typedef typename DiscreteFunctionType::SpaceType SpaceType; typedef LocalDoFVector< typename DiscreteFunctionType::VectorType > LocalDoFVectorType; typedef typename DiscreteFunctionType::EntityType EntityType; typedef typename SpaceType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = SpaceType::dimDomain; typedef typename SpaceType::RangeFieldType RangeFieldType; static const unsigned int dimRange = SpaceType::dimRange; static const unsigned int dimRangeCols = SpaceType::dimRangeCols; private: typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType; public: typedef typename BaseFunctionSetType::DomainType DomainType; typedef typename BaseFunctionSetType::RangeType RangeType; typedef typename BaseFunctionSetType::JacobianRangeType JacobianRangeType; DiscreteFunctionLocal(const DiscreteFunctionType& func, const EntityType& entity) : BaseType(func, entity) {} ~DiscreteFunctionLocal() {} LocalDoFVectorType& vector() { return BaseType::localVector_; } }; // class DiscreteFunctionLocal } // namespace GDT } // namespace Dune #include "default.hh" #endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH <commit_msg>[discretefunction.local] updated to new functions from dune-stuff<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH #define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH #include <vector> #include <type_traits> #include <dune/stuff/common/memory.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/la/container/interface.hh> #include <dune/gdt/space/interface.hh> #include <dune/gdt/mapper/interface.hh> namespace Dune { namespace GDT { template< class VectorImp > class ConstLocalDoFVector { static_assert(std::is_base_of< Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!"); public: typedef VectorImp VectorType; typedef typename VectorType::ElementType ElementType; template< class M, class EntityType > ConstLocalDoFVector(const MapperInterface< M >& mapper, const EntityType& entity, const VectorType& vector) : vector_(vector) , indices_(mapper.numDofs(entity)) { mapper.globalIndices(entity, indices_); } ~ConstLocalDoFVector() {} size_t size() const { return indices_.size(); } ElementType get(const size_t ii) const { assert(ii < indices_.size()); return vector_.get(indices_[ii]); } private: const VectorType& vector_; protected: mutable Dune::DynamicVector< size_t > indices_; }; // class ConstLocalDoFVector template< class VectorImp > class LocalDoFVector : public ConstLocalDoFVector< VectorImp > { typedef ConstLocalDoFVector< VectorImp > BaseType; public: typedef typename BaseType::VectorType VectorType; typedef typename BaseType::ElementType ElementType; template< class M, class EntityType > LocalDoFVector(const MapperInterface< M >& mapper, const EntityType& entity, VectorType& vector) : BaseType(mapper, entity, vector) , vector_(vector) {} ~LocalDoFVector() {} void set(const size_t ii, const ElementType& val) { assert(ii < indices_.size()); vector_.set(indices_[ii], val); } void add(const size_t ii, const ElementType& val) { assert(ii < indices_.size()); vector_.add(indices_[ii], val); } private: using BaseType::indices_; VectorType& vector_; }; // class LocalDoFVector template< class SpaceImp, class VectorImp > class ConstLocalDiscreteFunction : public Stuff::LocalfunctionInterface< typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols > { static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits >, SpaceImp >::value, "SpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of< Dune::Stuff::LA::VectorInterface< typename VectorImp::Traits >, VectorImp >::value, "VectorImp has to be derived from Stuff::LA::VectorInterface!"); static_assert(std::is_same< typename SpaceImp::RangeFieldType, typename VectorImp::ElementType >::value, "Types do not match!"); typedef Stuff::LocalfunctionInterface < typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType, SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange, SpaceImp::dimRangeCols > BaseType; typedef ConstLocalDiscreteFunction< SpaceImp, VectorImp > ThisType; public: typedef SpaceImp SpaceType; typedef VectorImp VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRangeRows = BaseType::dimRangeCols; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; private: typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType; public: typedef ConstLocalDoFVector< VectorType > ConstLocalDoFVectorType; ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent) : space_(space) , entity_(ent) , base_(new BaseFunctionSetType(space_.baseFunctionSet(entity_))) , localVector_(new ConstLocalDoFVectorType(space_.mapper(), entity_, globalVector)) , tmpBaseValues_(base_->size(), RangeType(0)) , tmpBaseJacobianValues_(base_->size(), JacobianRangeType(0)) { assert(localVector_->size() == base_->size()); } ConstLocalDiscreteFunction(ThisType&& source) : space_(source.space_) , entity_(source.entity_) , base_(std::move(source.base_)) , localVector_(std::move(source.localVector_)) , tmpBaseValues_(std::move(source.tmpBaseValues_)) , tmpBaseJacobianValues_(std::move(source.tmpBaseJacobianValues_)) {} ConstLocalDiscreteFunction(const ThisType& other) = delete; ThisType& operator=(const ThisType& other) = delete; virtual ~ConstLocalDiscreteFunction() {} virtual const EntityType& entity() const override { return entity_; } const ConstLocalDoFVectorType& vector() const { return *localVector_; } virtual size_t order() const override { return base_->order(); } virtual void evaluate(const DomainType& x, RangeType& ret) const override { Dune::Stuff::Common::clear(ret); assert(localVector_->size() == tmpBaseValues_.size()); base_->evaluate(x, tmpBaseValues_); for (size_t ii = 0; ii < localVector_->size(); ++ii) { tmpBaseValues_[ii] *= localVector_->get(ii); ret += tmpBaseValues_[ii]; } } // ... evaluate(...) virtual void jacobian(const DomainType& x, JacobianRangeType& ret) const override { Dune::Stuff::Common::clear(ret); assert(localVector_->size() == tmpBaseJacobianValues_.size()); base_->jacobian(x, tmpBaseJacobianValues_); for (size_t ii = 0; ii < localVector_->size(); ++ii) { tmpBaseJacobianValues_[ii] *= localVector_->get(ii); ret += tmpBaseJacobianValues_[ii]; } } // ... jacobian(...) protected: const SpaceType& space_; const EntityType& entity_; std::unique_ptr< const BaseFunctionSetType > base_; std::unique_ptr< const ConstLocalDoFVectorType > localVector_; private: mutable std::vector< RangeType > tmpBaseValues_; mutable std::vector< JacobianRangeType > tmpBaseJacobianValues_; }; // class ConstLocalDiscreteFunction template< class SpaceImp, class VectorImp > class LocalDiscreteFunction : public ConstLocalDiscreteFunction< SpaceImp, VectorImp > { typedef ConstLocalDiscreteFunction< SpaceImp, VectorImp > BaseType; typedef LocalDiscreteFunction< SpaceImp, VectorImp > ThisType; public: typedef typename BaseType::SpaceType SpaceType; typedef typename BaseType::VectorType VectorType; typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRangeRows = BaseType::dimRangeCols; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; private: typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType; public: typedef LocalDoFVector< VectorType > LocalDoFVectorType; LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent) : BaseType(space, globalVector, ent) , localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector)) { assert(localVector_->size() == base_->size()); } LocalDiscreteFunction(ThisType&& source) : BaseType(std::move(source)) , localVector_(std::move(source.localVector_)) // <- I am not sure if this is valid {} LocalDiscreteFunction(const ThisType& other) = delete; ThisType& operator=(const ThisType& other) = delete; virtual ~LocalDiscreteFunction() {} LocalDoFVectorType& vector() { return *localVector_; } private: using BaseType::space_; using BaseType::entity_; using BaseType::base_; std::unique_ptr< LocalDoFVectorType > localVector_; }; // class LocalDiscreteFunction } // namespace GDT } // namespace Dune #endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH <|endoftext|>
<commit_before>// // Copyright (c) 2017 Ian Godin // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #include "grid_layout.h" #include <base/contract.h> namespace layout { //////////////////////////////////////// size_t grid_layout::add_columns( size_t n, double flex, int32_t pri ) { size_t result = _cols.size(); for ( size_t i = 0; i < n; ++i ) { auto a = std::make_shared<area>(); a->set_expansion_flex( flex ); a->set_expansion_priority( pri ); _cols.push_back( std::move( a ) ); } return result; } //////////////////////////////////////// size_t grid_layout::add_rows( size_t n, double flex, int32_t pri ) { size_t result = _rows.size(); for ( size_t i = 0; i < n; ++i ) { auto a = std::make_shared<area>(); a->set_expansion_flex( flex ); a->set_expansion_priority( pri ); _rows.push_back( std::move( a ) ); } return result; } //////////////////////////////////////// void grid_layout::add( const std::shared_ptr<area> &a, size_t x, size_t y, size_t w, size_t h ) { _areas.emplace_back( a, x, y, w, h ); } //////////////////////////////////////// void grid_layout::compute_bounds( void ) { // TODO Compute maximum size for grid. // Reset columns and rows to 0. for ( auto &c: _cols ) c->set_extent( 0, 0 ); for ( auto &r: _rows ) r->set_extent( 0, 0 ); std::list<std::shared_ptr<area>> tmp; for ( auto &c: _areas ) { auto a = c._area.lock(); if ( a ) { a->compute_bounds(); // Handle width double w = 0.0; tmp.clear(); for ( size_t x = 0; x < c._w; ++x ) { auto col = _cols.at( x + c._x ); w += col->width(); tmp.push_back( std::move( col ) ); } double extra = a->minimum_width() - w; expand_width( tmp, extra ); // Handle height double h = 0.0; tmp.clear(); for ( size_t y = 0; y < c._h; ++y ) { auto row = _rows.at( y + c._y ); h += row->height(); tmp.push_back( std::move( row ) ); } extra = a->minimum_height() - h; expand_height( tmp, extra ); } } double minw = 0.0; if ( !_cols.empty() ) { for ( auto &c: _cols ) { c->set_minimum_width( c->width() ); minw += c->minimum_width(); } minw += ( _cols.size() - 1 ) * _spacing[0]; } minw += _pad[0] + _pad[1]; double minh = 0.0; if ( !_rows.empty() ) { for ( auto &r: _rows ) { r->set_minimum_height( r->height() ); minh += r->minimum_height(); } minh += ( _rows.size() - 1 ) * _spacing[1]; } minh += _pad[2] + _pad[3]; set_minimum( minw, minh ); } //////////////////////////////////////// void grid_layout::compute_layout( void ) { // Set columns to minimum size and add any extra space std::list<std::shared_ptr<area>> tmp; for ( auto &c: _cols ) { c->set_size( c->minimum_size() ); tmp.push_back( c ); } expand_width( tmp, width() - minimum_width() ); // Now layout columns left to right double x = _pad[0]; for ( auto &c: _cols ) { c->set_position( { x, 0 } ); x += c->width() + _spacing[0]; } // Set rows to minimum size and add any extra space tmp.clear(); for ( auto &r: _rows ) { r->set_size( r->minimum_size() ); tmp.push_back( r ); } expand_height( tmp, height() - minimum_height() ); // Now layout rows top to bottom double y = _pad[2]; for ( auto &r: _rows ) { r->set_position( { 0, y } ); y += r->height() + _spacing[1]; } // Finally layout out areas according to the cell they occupy for ( auto &c: _areas ) { auto a = c._area.lock(); if ( a ) { auto l = _cols.at( c._x ); auto r = _cols.at( c._x + c._w - 1 ); auto t = _rows.at( c._y ); auto b = _rows.at( c._y + c._h - 1 ); a->set_x1( x1() + l->x1() ); a->set_y1( y1() + t->y1() ); a->set_x2( x1() + r->x2() ); a->set_y2( y1() + b->y2() ); a->compute_layout(); } } } //////////////////////////////////////// } <commit_msg>Fixed bug in grid layout.<commit_after>// // Copyright (c) 2017 Ian Godin // All rights reserved. // Copyrights licensed under the MIT License. // See the accompanying LICENSE.txt file for terms // #include "grid_layout.h" #include <base/contract.h> namespace layout { //////////////////////////////////////// size_t grid_layout::add_columns( size_t n, double flex, int32_t pri ) { size_t result = _cols.size(); for ( size_t i = 0; i < n; ++i ) { auto a = std::make_shared<area>(); a->set_expansion_flex( flex ); a->set_expansion_priority( pri ); _cols.push_back( std::move( a ) ); } return result; } //////////////////////////////////////// size_t grid_layout::add_rows( size_t n, double flex, int32_t pri ) { size_t result = _rows.size(); for ( size_t i = 0; i < n; ++i ) { auto a = std::make_shared<area>(); a->set_expansion_flex( flex ); a->set_expansion_priority( pri ); _rows.push_back( std::move( a ) ); } return result; } //////////////////////////////////////// void grid_layout::add( const std::shared_ptr<area> &a, size_t x, size_t y, size_t w, size_t h ) { _areas.emplace_back( a, x, y, w, h ); } //////////////////////////////////////// void grid_layout::compute_bounds( void ) { // TODO Compute maximum size for grid. // Reset columns and rows to 0. for ( auto &c: _cols ) c->set_extent( 0, 0 ); for ( auto &r: _rows ) r->set_extent( 0, 0 ); std::list<std::shared_ptr<area>> tmp; for ( auto &c: _areas ) { auto a = c._area.lock(); if ( a ) { a->compute_bounds(); // Handle width double w = 0.0; tmp.clear(); for ( size_t x = 0; x < c._w; ++x ) { auto col = _cols.at( c._x + x ); w += col->width(); tmp.push_back( std::move( col ) ); } double extra = a->minimum_width() - w; expand_width( tmp, extra ); // Handle height double h = 0.0; tmp.clear(); for ( size_t y = 0; y < c._h; ++y ) { auto row = _rows.at( c._y + y ); h += row->height(); tmp.push_back( std::move( row ) ); } extra = a->minimum_height() - h; expand_height( tmp, extra ); } } double minw = 0.0; if ( !_cols.empty() ) { for ( auto &c: _cols ) { c->set_minimum_width( c->width() ); minw += c->minimum_width(); } minw += ( _cols.size() - 1 ) * _spacing[0]; } minw += _pad[0] + _pad[1]; double minh = 0.0; if ( !_rows.empty() ) { for ( auto &r: _rows ) { r->set_minimum_height( r->height() ); minh += r->minimum_height(); } minh += ( _rows.size() - 1 ) * _spacing[1]; } minh += _pad[2] + _pad[3]; set_minimum( minw, minh ); } //////////////////////////////////////// void grid_layout::compute_layout( void ) { // Set columns to minimum size and add any extra space std::list<std::shared_ptr<area>> tmp; for ( auto &c: _cols ) { c->set_size( c->minimum_size() ); tmp.push_back( c ); } expand_width( tmp, width() - minimum_width() ); // Now layout columns left to right double x = _pad[0]; for ( auto &c: _cols ) { c->set_position( { x, 0 } ); x += c->width() + _spacing[0]; } // Set rows to minimum size and add any extra space tmp.clear(); for ( auto &r: _rows ) { r->set_size( r->minimum_size() ); tmp.push_back( r ); } expand_height( tmp, height() - minimum_height() ); // Now layout rows top to bottom double y = _pad[2]; for ( auto &r: _rows ) { r->set_position( { 0, y } ); y += r->height() + _spacing[1]; } // Finally layout out areas according to the cell they occupy for ( auto &c: _areas ) { auto a = c._area.lock(); if ( a ) { auto l = _cols.at( c._x ); auto r = _cols.at( c._x + c._w - 1 ); auto t = _rows.at( c._y ); auto b = _rows.at( c._y + c._h - 1 ); a->set_x1( x1() + l->x1() ); a->set_y1( y1() + t->y1() ); a->set_x2( x1() + r->x2() + 1 ); a->set_y2( y1() + b->y2() + 1 ); a->compute_layout(); } } } //////////////////////////////////////// } <|endoftext|>
<commit_before>// // Copyright 2011 Light Transport Entertainment, Inc. // // Licensed under BSD license // // node.js #include <v8.h> #include <node.h> // C++ #include <iostream> // RDMA CM #include <rdma/rdma_cma.h> using namespace v8; class EioData { public: EioData(); ~EioData(); }; extern "C" void init(Handle<Object> target) { // @todo } <commit_msg>Small impl.<commit_after>// // Copyright 2011 Light Transport Entertainment, Inc. // // Licensed under BSD license // // node.js #include <v8.h> #include <node.h> // C/C++ #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> // RDMA CM #include <rdma/rdma_cma.h> using namespace v8; typedef struct { struct ibv_context* ctx; ///< Context struct ibv_pd* pd; ///< Protection Domain struct ibv_cq* cq; ///< Completion Queue struct ibv_comp_channel* comp_channel; ///< Completion Event Channel } RDMAContext; typedef struct { bool connected; struct rdma_cm_id* id; struct ibv_qp* qp; struct ibv_mr* recv_mr; struct ibv_mr* send_mr; struct ibv_mr* rdma_local_mr; struct ibv_mr* rdma_remote_mr; struct ibv_mr peer_mr; } RDMAConnection; static void BuildRDMAContext(struct ibv_context* verbs) { RDMAContext* ctx = (RDMAContext*)malloc(sizeof(RDMAContext)); ctx->ctx = verbs; ctx->pd = ibv_alloc_pd(ctx->ctx); if (!ctx->pd) { fprintf(stderr, "Failed to operate ibv_alloc_pd()\n"); exit(-1); } ctx->comp_channel = ibv_create_comp_channel(ctx->ctx); if (!ctx->comp_channel) { fprintf(stderr, "Failed to operate ibv_create_comp_channel()\n"); exit(-1); } int cqe = 10; // # of completion queue elements. This could be arbitrary int comp_vector = 0; ctx->cq = ibv_create_cq(ctx->ctx, cqe, NULL, ctx->comp_channel, comp_vector); if (!ctx->cq) { fprintf(stderr, "Failed to operate ibv_create_qp()\n"); exit(-1); } if (ibv_req_notify_cq(ctx->cq, 0)) { fprintf(stderr, "Failed to operate ibv_req_notify_cq()\n"); exit(-1); } if (ibv_req_notify_cq(ctx->cq, 0)) { fprintf(stderr, "Failed to operate ibv_req_notify_cq()\n"); exit(-1); } } static void Connection(struct rdma_cm_id* id) { RDMAConnection* conn; struct ibv_qp_init_attr qp_attr; BuildRDMAContext(id->verbs); } class EioData { public: EioData(); ~EioData(); }; extern "C" void init(Handle<Object> target) { // @todo } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: intercept.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: abi $ $Date: 2003-04-04 11:41:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _INTERCEPT_HXX_ #define _INTERCEPT_HXX_ #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_ #include <com/sun/star/frame/XDispatchProviderInterceptor.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_ #include <com/sun/star/frame/XInterceptorInfo.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif class StatusChangeListenerContainer; class EmbedDocument_Impl; class DocumentHolder; class Interceptor : public ::cppu::WeakImplHelper3< ::com::sun::star::frame::XDispatchProviderInterceptor, ::com::sun::star::frame::XInterceptorInfo, ::com::sun::star::frame::XDispatch> { public: Interceptor(EmbedDocument_Impl* pOLEInterface,DocumentHolder* pDocH); ~Interceptor(); void generateFeatureStateEvent(); // overwritten to release the statuslistner. // XComponent virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& aListener ) throw( com::sun::star::uno::RuntimeException ); void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); //XDispatch virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& URL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& Arguments ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& Control, const ::com::sun::star::util::URL& URL ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& Control, const ::com::sun::star::util::URL& URL ) throw ( ::com::sun::star::uno::RuntimeException ); //XInterceptorInfo virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getInterceptedURLs( ) throw ( ::com::sun::star::uno::RuntimeException ); //XDispatchProvider ( inherited by XDispatchProviderInterceptor ) virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& URL, const ::rtl::OUString& TargetFrameName, sal_Int32 SearchFlags ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& Requests ) throw ( ::com::sun::star::uno::RuntimeException ); //XDispatchProviderInterceptor virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& NewDispatchProvider ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& NewSupplier ) throw ( ::com::sun::star::uno::RuntimeException ); private: osl::Mutex m_aMutex; EmbedDocument_Impl* m_pOLEInterface; DocumentHolder* m_pDocH; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatchProvider; static ::com::sun::star::uno::Sequence<::rtl::OUString> m_aInterceptedURL; cppu::OInterfaceContainerHelper* m_pDisposeEventListeners; StatusChangeListenerContainer* m_pStatCL; }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.94); FILE MERGED 2005/09/05 18:46:14 rt 1.4.94.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: intercept.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 18:56:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _INTERCEPT_HXX_ #define _INTERCEPT_HXX_ #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDERINTERCEPTOR_HPP_ #include <com/sun/star/frame/XDispatchProviderInterceptor.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XINTERCEPTORINFO_HPP_ #include <com/sun/star/frame/XInterceptorInfo.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_ #include <com/sun/star/frame/XDispatch.hpp> #endif class StatusChangeListenerContainer; class EmbedDocument_Impl; class DocumentHolder; class Interceptor : public ::cppu::WeakImplHelper3< ::com::sun::star::frame::XDispatchProviderInterceptor, ::com::sun::star::frame::XInterceptorInfo, ::com::sun::star::frame::XDispatch> { public: Interceptor(EmbedDocument_Impl* pOLEInterface,DocumentHolder* pDocH); ~Interceptor(); void generateFeatureStateEvent(); // overwritten to release the statuslistner. // XComponent virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& xListener ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& aListener ) throw( com::sun::star::uno::RuntimeException ); void SAL_CALL dispose() throw(::com::sun::star::uno::RuntimeException); //XDispatch virtual void SAL_CALL dispatch( const ::com::sun::star::util::URL& URL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& Arguments ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL addStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& Control, const ::com::sun::star::util::URL& URL ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeStatusListener( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XStatusListener >& Control, const ::com::sun::star::util::URL& URL ) throw ( ::com::sun::star::uno::RuntimeException ); //XInterceptorInfo virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getInterceptedURLs( ) throw ( ::com::sun::star::uno::RuntimeException ); //XDispatchProvider ( inherited by XDispatchProviderInterceptor ) virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > SAL_CALL queryDispatch( const ::com::sun::star::util::URL& URL, const ::rtl::OUString& TargetFrameName, sal_Int32 SearchFlags ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > > SAL_CALL queryDispatches( const ::com::sun::star::uno::Sequence< ::com::sun::star::frame::DispatchDescriptor >& Requests ) throw ( ::com::sun::star::uno::RuntimeException ); //XDispatchProviderInterceptor virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getSlaveDispatchProvider( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setSlaveDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& NewDispatchProvider ) throw ( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > SAL_CALL getMasterDispatchProvider( ) throw ( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setMasterDispatchProvider( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider >& NewSupplier ) throw ( ::com::sun::star::uno::RuntimeException ); private: osl::Mutex m_aMutex; EmbedDocument_Impl* m_pOLEInterface; DocumentHolder* m_pDocH; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xSlaveDispatchProvider; ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatchProvider > m_xMasterDispatchProvider; static ::com::sun::star::uno::Sequence<::rtl::OUString> m_aInterceptedURL; cppu::OInterfaceContainerHelper* m_pDisposeEventListeners; StatusChangeListenerContainer* m_pStatCL; }; #endif <|endoftext|>
<commit_before>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #include "rust_sched_loop.h" #include "rust_util.h" #include "rust_scheduler.h" #ifndef _WIN32 pthread_key_t rust_sched_loop::task_key; #else DWORD rust_sched_loop::task_key; #endif const size_t C_STACK_SIZE = 1024*1024; bool rust_sched_loop::tls_initialized = false; rust_sched_loop::rust_sched_loop(rust_scheduler *sched, int id, bool killed) : _log(this), id(id), should_exit(false), cached_c_stack(NULL), extra_c_stack(NULL), dead_task(NULL), killed(killed), pump_signal(NULL), kernel(sched->kernel), sched(sched), log_lvl(log_debug), min_stack_size(kernel->env->min_stack_size), local_region(kernel->env, false), // FIXME #2891: calculate a per-scheduler name. name("main") { LOGPTR(this, "new dom", (uintptr_t)this); rng_init(kernel, &rng, NULL); if (!tls_initialized) init_tls(); } void rust_sched_loop::activate(rust_task *task) { lock.must_have_lock(); task->ctx.next = &c_context; DLOG(this, task, "descheduling..."); lock.unlock(); prepare_c_stack(task); task->ctx.swap(c_context); task->cleanup_after_turn(); unprepare_c_stack(); lock.lock(); DLOG(this, task, "task has returned"); } void rust_sched_loop::fail() { _log.log(NULL, log_err, "domain %s @0x%" PRIxPTR " root task failed", name, this); kernel->fail(); } void rust_sched_loop::kill_all_tasks() { std::vector<rust_task*> all_tasks; { scoped_lock with(lock); // Any task created after this will be killed. See transition, below. killed = true; for (size_t i = 0; i < running_tasks.length(); i++) { rust_task *t = running_tasks[i]; t->ref(); all_tasks.push_back(t); } for (size_t i = 0; i < blocked_tasks.length(); i++) { rust_task *t = blocked_tasks[i]; t->ref(); all_tasks.push_back(t); } } while (!all_tasks.empty()) { rust_task *task = all_tasks.back(); all_tasks.pop_back(); task->kill(); task->deref(); } } size_t rust_sched_loop::number_of_live_tasks() { lock.must_have_lock(); return running_tasks.length() + blocked_tasks.length(); } /** * Delete any dead tasks. */ void rust_sched_loop::reap_dead_tasks() { lock.must_have_lock(); if (dead_task == NULL) { return; } // Dereferencing the task will probably cause it to be released // from the scheduler, which may end up trying to take this lock lock.unlock(); dead_task->delete_all_stacks(); // Deref the task, which may cause it to request us to release it dead_task->deref(); dead_task = NULL; lock.lock(); } void rust_sched_loop::release_task(rust_task *task) { // Nobody should have a ref to the task at this point assert(task->get_ref_count() == 0); // Now delete the task, which will require using this thread's // memory region. delete task; // Now release the task from the scheduler, which may trigger this // thread to exit sched->release_task(); } /** * Schedules a running task for execution. Only running tasks can be * activated. Blocked tasks have to be unblocked before they can be * activated. * * Returns NULL if no tasks can be scheduled. */ rust_task * rust_sched_loop::schedule_task() { lock.must_have_lock(); if (running_tasks.length() > 0) { size_t k = rng_gen_u32(kernel, &rng); size_t i = k % running_tasks.length(); return (rust_task *)running_tasks[i]; } return NULL; } void rust_sched_loop::log_state() { if (log_rt_task < log_debug) return; if (!running_tasks.is_empty()) { _log.log(NULL, log_debug, "running tasks:"); for (size_t i = 0; i < running_tasks.length(); i++) { _log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR, running_tasks[i]->name, running_tasks[i]); } } if (!blocked_tasks.is_empty()) { _log.log(NULL, log_debug, "blocked tasks:"); for (size_t i = 0; i < blocked_tasks.length(); i++) { _log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR ", blocked on: 0x%" PRIxPTR " '%s'", blocked_tasks[i]->name, blocked_tasks[i], blocked_tasks[i]->get_cond(), blocked_tasks[i]->get_cond_name()); } } } void rust_sched_loop::on_pump_loop(rust_signal *signal) { assert(pump_signal == NULL); assert(signal != NULL); pump_signal = signal; } void rust_sched_loop::pump_loop() { assert(pump_signal != NULL); pump_signal->signal(); } rust_sched_loop_state rust_sched_loop::run_single_turn() { DLOG(this, task, "scheduler %d resuming ...", id); lock.lock(); if (!should_exit) { assert(dead_task == NULL && "Tasks should only die after running"); DLOG(this, dom, "worker %d, number_of_live_tasks = %d", id, number_of_live_tasks()); rust_task *scheduled_task = schedule_task(); if (scheduled_task == NULL) { log_state(); DLOG(this, task, "all tasks are blocked, scheduler id %d yielding ...", id); lock.unlock(); return sched_loop_state_block; } scheduled_task->assert_is_running(); DLOG(this, task, "activating task %s 0x%" PRIxPTR ", state: %s", scheduled_task->name, (uintptr_t)scheduled_task, state_name(scheduled_task->get_state())); place_task_in_tls(scheduled_task); DLOG(this, task, "Running task %p on worker %d", scheduled_task, id); activate(scheduled_task); DLOG(this, task, "returned from task %s @0x%" PRIxPTR " in state '%s', worker id=%d" PRIxPTR, scheduled_task->name, (uintptr_t)scheduled_task, state_name(scheduled_task->get_state()), id); reap_dead_tasks(); lock.unlock(); return sched_loop_state_keep_going; } else { assert(running_tasks.is_empty() && "Should have no running tasks"); assert(blocked_tasks.is_empty() && "Should have no blocked tasks"); assert(dead_task == NULL && "Should have no dead tasks"); DLOG(this, dom, "finished main-loop %d", id); lock.unlock(); assert(!extra_c_stack); if (cached_c_stack) { destroy_exchange_stack(kernel->region(), cached_c_stack); cached_c_stack = NULL; } sched->release_task_thread(); return sched_loop_state_exit; } } rust_task * rust_sched_loop::create_task(rust_task *spawner, const char *name) { rust_task *task = new (this->kernel, "rust_task") rust_task(this, task_state_newborn, name, kernel->env->min_stack_size); DLOG(this, task, "created task: " PTR ", spawner: %s, name: %s", task, spawner ? spawner->name : "(none)", name); task->id = kernel->generate_task_id(); return task; } rust_task_list * rust_sched_loop::state_list(rust_task_state state) { switch (state) { case task_state_running: return &running_tasks; case task_state_blocked: return &blocked_tasks; default: return NULL; } } const char * rust_sched_loop::state_name(rust_task_state state) { switch (state) { case task_state_newborn: return "newborn"; case task_state_running: return "running"; case task_state_blocked: return "blocked"; case task_state_dead: return "dead"; default: assert(false); return ""; } } void rust_sched_loop::transition(rust_task *task, rust_task_state src, rust_task_state dst, rust_cond *cond, const char* cond_name) { scoped_lock with(lock); DLOG(this, task, "task %s " PTR " state change '%s' -> '%s' while in '%s'", name, (uintptr_t)this, state_name(src), state_name(dst), state_name(task->get_state())); assert(task->get_state() == src); rust_task_list *src_list = state_list(src); if (src_list) { src_list->remove(task); } rust_task_list *dst_list = state_list(dst); if (dst_list) { dst_list->append(task); } if (dst == task_state_dead) { assert(dead_task == NULL); dead_task = task; } task->set_state(dst, cond, cond_name); // If the entire runtime is failing, newborn tasks must be doomed. if (src == task_state_newborn && killed) { task->kill_inner(); } pump_loop(); } #ifndef _WIN32 void rust_sched_loop::init_tls() { int result = pthread_key_create(&task_key, NULL); assert(!result && "Couldn't create the TLS key!"); tls_initialized = true; } void rust_sched_loop::place_task_in_tls(rust_task *task) { int result = pthread_setspecific(task_key, task); assert(!result && "Couldn't place the task in TLS!"); task->record_stack_limit(); } #else void rust_sched_loop::init_tls() { task_key = TlsAlloc(); assert(task_key != TLS_OUT_OF_INDEXES && "Couldn't create the TLS key!"); tls_initialized = true; } void rust_sched_loop::place_task_in_tls(rust_task *task) { BOOL result = TlsSetValue(task_key, task); assert(result && "Couldn't place the task in TLS!"); task->record_stack_limit(); } #endif void rust_sched_loop::exit() { scoped_lock with(lock); DLOG(this, dom, "Requesting exit for thread %d", id); should_exit = true; pump_loop(); } // Before activating each task, make sure we have a C stack available. // It needs to be allocated ahead of time (while we're on our own // stack), because once we're on the Rust stack we won't have enough // room to do the allocation void rust_sched_loop::prepare_c_stack(rust_task *task) { assert(!extra_c_stack); if (!cached_c_stack && !task->have_c_stack()) { cached_c_stack = create_exchange_stack(kernel->region(), C_STACK_SIZE); } } void rust_sched_loop::unprepare_c_stack() { if (extra_c_stack) { destroy_exchange_stack(kernel->region(), extra_c_stack); extra_c_stack = NULL; } } // // Local Variables: // mode: C++ // fill-column: 70; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // End: // <commit_msg>don't deplete RNG entropy when there is only one runnable task<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #include "rust_sched_loop.h" #include "rust_util.h" #include "rust_scheduler.h" #ifndef _WIN32 pthread_key_t rust_sched_loop::task_key; #else DWORD rust_sched_loop::task_key; #endif const size_t C_STACK_SIZE = 1024*1024; bool rust_sched_loop::tls_initialized = false; rust_sched_loop::rust_sched_loop(rust_scheduler *sched, int id, bool killed) : _log(this), id(id), should_exit(false), cached_c_stack(NULL), extra_c_stack(NULL), dead_task(NULL), killed(killed), pump_signal(NULL), kernel(sched->kernel), sched(sched), log_lvl(log_debug), min_stack_size(kernel->env->min_stack_size), local_region(kernel->env, false), // FIXME #2891: calculate a per-scheduler name. name("main") { LOGPTR(this, "new dom", (uintptr_t)this); rng_init(kernel, &rng, NULL); if (!tls_initialized) init_tls(); } void rust_sched_loop::activate(rust_task *task) { lock.must_have_lock(); task->ctx.next = &c_context; DLOG(this, task, "descheduling..."); lock.unlock(); prepare_c_stack(task); task->ctx.swap(c_context); task->cleanup_after_turn(); unprepare_c_stack(); lock.lock(); DLOG(this, task, "task has returned"); } void rust_sched_loop::fail() { _log.log(NULL, log_err, "domain %s @0x%" PRIxPTR " root task failed", name, this); kernel->fail(); } void rust_sched_loop::kill_all_tasks() { std::vector<rust_task*> all_tasks; { scoped_lock with(lock); // Any task created after this will be killed. See transition, below. killed = true; for (size_t i = 0; i < running_tasks.length(); i++) { rust_task *t = running_tasks[i]; t->ref(); all_tasks.push_back(t); } for (size_t i = 0; i < blocked_tasks.length(); i++) { rust_task *t = blocked_tasks[i]; t->ref(); all_tasks.push_back(t); } } while (!all_tasks.empty()) { rust_task *task = all_tasks.back(); all_tasks.pop_back(); task->kill(); task->deref(); } } size_t rust_sched_loop::number_of_live_tasks() { lock.must_have_lock(); return running_tasks.length() + blocked_tasks.length(); } /** * Delete any dead tasks. */ void rust_sched_loop::reap_dead_tasks() { lock.must_have_lock(); if (dead_task == NULL) { return; } // Dereferencing the task will probably cause it to be released // from the scheduler, which may end up trying to take this lock lock.unlock(); dead_task->delete_all_stacks(); // Deref the task, which may cause it to request us to release it dead_task->deref(); dead_task = NULL; lock.lock(); } void rust_sched_loop::release_task(rust_task *task) { // Nobody should have a ref to the task at this point assert(task->get_ref_count() == 0); // Now delete the task, which will require using this thread's // memory region. delete task; // Now release the task from the scheduler, which may trigger this // thread to exit sched->release_task(); } /** * Schedules a running task for execution. Only running tasks can be * activated. Blocked tasks have to be unblocked before they can be * activated. * * Returns NULL if no tasks can be scheduled. */ rust_task * rust_sched_loop::schedule_task() { lock.must_have_lock(); size_t tasks = running_tasks.length(); if (tasks > 0) { size_t i = (tasks > 1) ? (rng_gen_u32(kernel, &rng) % tasks) : 0; return running_tasks[i]; } return NULL; } void rust_sched_loop::log_state() { if (log_rt_task < log_debug) return; if (!running_tasks.is_empty()) { _log.log(NULL, log_debug, "running tasks:"); for (size_t i = 0; i < running_tasks.length(); i++) { _log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR, running_tasks[i]->name, running_tasks[i]); } } if (!blocked_tasks.is_empty()) { _log.log(NULL, log_debug, "blocked tasks:"); for (size_t i = 0; i < blocked_tasks.length(); i++) { _log.log(NULL, log_debug, "\t task: %s @0x%" PRIxPTR ", blocked on: 0x%" PRIxPTR " '%s'", blocked_tasks[i]->name, blocked_tasks[i], blocked_tasks[i]->get_cond(), blocked_tasks[i]->get_cond_name()); } } } void rust_sched_loop::on_pump_loop(rust_signal *signal) { assert(pump_signal == NULL); assert(signal != NULL); pump_signal = signal; } void rust_sched_loop::pump_loop() { assert(pump_signal != NULL); pump_signal->signal(); } rust_sched_loop_state rust_sched_loop::run_single_turn() { DLOG(this, task, "scheduler %d resuming ...", id); lock.lock(); if (!should_exit) { assert(dead_task == NULL && "Tasks should only die after running"); DLOG(this, dom, "worker %d, number_of_live_tasks = %d", id, number_of_live_tasks()); rust_task *scheduled_task = schedule_task(); if (scheduled_task == NULL) { log_state(); DLOG(this, task, "all tasks are blocked, scheduler id %d yielding ...", id); lock.unlock(); return sched_loop_state_block; } scheduled_task->assert_is_running(); DLOG(this, task, "activating task %s 0x%" PRIxPTR ", state: %s", scheduled_task->name, (uintptr_t)scheduled_task, state_name(scheduled_task->get_state())); place_task_in_tls(scheduled_task); DLOG(this, task, "Running task %p on worker %d", scheduled_task, id); activate(scheduled_task); DLOG(this, task, "returned from task %s @0x%" PRIxPTR " in state '%s', worker id=%d" PRIxPTR, scheduled_task->name, (uintptr_t)scheduled_task, state_name(scheduled_task->get_state()), id); reap_dead_tasks(); lock.unlock(); return sched_loop_state_keep_going; } else { assert(running_tasks.is_empty() && "Should have no running tasks"); assert(blocked_tasks.is_empty() && "Should have no blocked tasks"); assert(dead_task == NULL && "Should have no dead tasks"); DLOG(this, dom, "finished main-loop %d", id); lock.unlock(); assert(!extra_c_stack); if (cached_c_stack) { destroy_exchange_stack(kernel->region(), cached_c_stack); cached_c_stack = NULL; } sched->release_task_thread(); return sched_loop_state_exit; } } rust_task * rust_sched_loop::create_task(rust_task *spawner, const char *name) { rust_task *task = new (this->kernel, "rust_task") rust_task(this, task_state_newborn, name, kernel->env->min_stack_size); DLOG(this, task, "created task: " PTR ", spawner: %s, name: %s", task, spawner ? spawner->name : "(none)", name); task->id = kernel->generate_task_id(); return task; } rust_task_list * rust_sched_loop::state_list(rust_task_state state) { switch (state) { case task_state_running: return &running_tasks; case task_state_blocked: return &blocked_tasks; default: return NULL; } } const char * rust_sched_loop::state_name(rust_task_state state) { switch (state) { case task_state_newborn: return "newborn"; case task_state_running: return "running"; case task_state_blocked: return "blocked"; case task_state_dead: return "dead"; default: assert(false); return ""; } } void rust_sched_loop::transition(rust_task *task, rust_task_state src, rust_task_state dst, rust_cond *cond, const char* cond_name) { scoped_lock with(lock); DLOG(this, task, "task %s " PTR " state change '%s' -> '%s' while in '%s'", name, (uintptr_t)this, state_name(src), state_name(dst), state_name(task->get_state())); assert(task->get_state() == src); rust_task_list *src_list = state_list(src); if (src_list) { src_list->remove(task); } rust_task_list *dst_list = state_list(dst); if (dst_list) { dst_list->append(task); } if (dst == task_state_dead) { assert(dead_task == NULL); dead_task = task; } task->set_state(dst, cond, cond_name); // If the entire runtime is failing, newborn tasks must be doomed. if (src == task_state_newborn && killed) { task->kill_inner(); } pump_loop(); } #ifndef _WIN32 void rust_sched_loop::init_tls() { int result = pthread_key_create(&task_key, NULL); assert(!result && "Couldn't create the TLS key!"); tls_initialized = true; } void rust_sched_loop::place_task_in_tls(rust_task *task) { int result = pthread_setspecific(task_key, task); assert(!result && "Couldn't place the task in TLS!"); task->record_stack_limit(); } #else void rust_sched_loop::init_tls() { task_key = TlsAlloc(); assert(task_key != TLS_OUT_OF_INDEXES && "Couldn't create the TLS key!"); tls_initialized = true; } void rust_sched_loop::place_task_in_tls(rust_task *task) { BOOL result = TlsSetValue(task_key, task); assert(result && "Couldn't place the task in TLS!"); task->record_stack_limit(); } #endif void rust_sched_loop::exit() { scoped_lock with(lock); DLOG(this, dom, "Requesting exit for thread %d", id); should_exit = true; pump_loop(); } // Before activating each task, make sure we have a C stack available. // It needs to be allocated ahead of time (while we're on our own // stack), because once we're on the Rust stack we won't have enough // room to do the allocation void rust_sched_loop::prepare_c_stack(rust_task *task) { assert(!extra_c_stack); if (!cached_c_stack && !task->have_c_stack()) { cached_c_stack = create_exchange_stack(kernel->region(), C_STACK_SIZE); } } void rust_sched_loop::unprepare_c_stack() { if (extra_c_stack) { destroy_exchange_stack(kernel->region(), extra_c_stack); extra_c_stack = NULL; } } // // Local Variables: // mode: C++ // fill-column: 70; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // End: // <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 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 "base/sys_string_conversions.h" #include <wchar.h> #include "base/string_piece.h" #include "base/utf_string_conversions.h" namespace base { std::string SysWideToUTF8(const std::wstring& wide) { // In theory this should be using the system-provided conversion rather // than our ICU, but this will do for now. return WideToUTF8(wide); } std::wstring SysUTF8ToWide(const StringPiece& utf8) { // In theory this should be using the system-provided conversion rather // than our ICU, but this will do for now. std::wstring out; UTF8ToWide(utf8.data(), utf8.size(), &out); return out; } std::string SysWideToNativeMB(const std::wstring& wide) { mbstate_t ps; // Calculate the number of multi-byte characters. We walk through the string // without writing the output, counting the number of multi-byte characters. size_t num_out_chars = 0; memset(&ps, 0, sizeof(ps)); for (size_t i = 0; i < wide.size(); ++i) { const wchar_t src = wide[i]; // Use a temp buffer since calling wcrtomb with an output of NULL does not // calculate the output length. char buf[16]; // Skip NULLs to avoid wcrtomb's special handling of them. size_t res = src ? wcrtomb(buf, src, &ps) : 0; switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-1): return std::string(); break; case 0: // We hit an embedded null byte, keep going. ++num_out_chars; break; default: num_out_chars += res; break; } } if (num_out_chars == 0) return std::string(); std::string out; out.resize(num_out_chars); // We walk the input string again, with |i| tracking the index of the // wide input, and |j| tracking the multi-byte output. memset(&ps, 0, sizeof(ps)); for (size_t i = 0, j = 0; i < wide.size(); ++i) { const wchar_t src = wide[i]; // We don't want wcrtomb to do it's funkiness for embedded NULLs. size_t res = src ? wcrtomb(&out[j], src, &ps) : 0; switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-1): return std::string(); break; case 0: // We hit an embedded null byte, keep going. ++j; // Output is already zeroed. break; default: j += res; break; } } return out; } std::wstring SysNativeMBToWide(const StringPiece& native_mb) { mbstate_t ps; // Calculate the number of wide characters. We walk through the string // without writing the output, counting the number of wide characters. size_t num_out_chars = 0; memset(&ps, 0, sizeof(ps)); for (size_t i = 0; i < native_mb.size(); ) { const char* src = native_mb.data() + i; size_t res = mbrtowc(NULL, src, native_mb.size() - i, &ps); switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-2): case static_cast<size_t>(-1): return std::wstring(); break; case 0: // We hit an embedded null byte, keep going. i += 1; // Fall through. default: i += res; ++num_out_chars; break; } } if (num_out_chars == 0) return std::wstring(); std::wstring out; out.resize(num_out_chars); memset(&ps, 0, sizeof(ps)); // Clear the shift state. // We walk the input string again, with |i| tracking the index of the // multi-byte input, and |j| tracking the wide output. for (size_t i = 0, j = 0; i < native_mb.size(); ++j) { const char* src = native_mb.data() + i; wchar_t* dst = &out[j]; size_t res = mbrtowc(dst, src, native_mb.size() - i, &ps); switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-2): case static_cast<size_t>(-1): return std::wstring(); break; case 0: i += 1; // Skip null byte. break; default: i += res; break; } } return out; } } // namespace base <commit_msg>Make SysNativeMB converters assume UTF-8 on Chrome OS. <commit_after>// Copyright (c) 2006-2008 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 "base/sys_string_conversions.h" #include <wchar.h> #include "base/string_piece.h" #include "base/utf_string_conversions.h" namespace base { std::string SysWideToUTF8(const std::wstring& wide) { // In theory this should be using the system-provided conversion rather // than our ICU, but this will do for now. return WideToUTF8(wide); } std::wstring SysUTF8ToWide(const StringPiece& utf8) { // In theory this should be using the system-provided conversion rather // than our ICU, but this will do for now. std::wstring out; UTF8ToWide(utf8.data(), utf8.size(), &out); return out; } #if defined(OS_CHROMEOS) // ChromeOS always runs in UTF-8 locale. std::string SysWideToNativeMB(const std::wstring& wide) { return WideToUTF8(wide); } std::wstring SysNativeMBToWide(const StringPiece& native_mb) { return SysUTF8ToWide(native_mb); } #else std::string SysWideToNativeMB(const std::wstring& wide) { mbstate_t ps; // Calculate the number of multi-byte characters. We walk through the string // without writing the output, counting the number of multi-byte characters. size_t num_out_chars = 0; memset(&ps, 0, sizeof(ps)); for (size_t i = 0; i < wide.size(); ++i) { const wchar_t src = wide[i]; // Use a temp buffer since calling wcrtomb with an output of NULL does not // calculate the output length. char buf[16]; // Skip NULLs to avoid wcrtomb's special handling of them. size_t res = src ? wcrtomb(buf, src, &ps) : 0; switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-1): return std::string(); break; case 0: // We hit an embedded null byte, keep going. ++num_out_chars; break; default: num_out_chars += res; break; } } if (num_out_chars == 0) return std::string(); std::string out; out.resize(num_out_chars); // We walk the input string again, with |i| tracking the index of the // wide input, and |j| tracking the multi-byte output. memset(&ps, 0, sizeof(ps)); for (size_t i = 0, j = 0; i < wide.size(); ++i) { const wchar_t src = wide[i]; // We don't want wcrtomb to do it's funkiness for embedded NULLs. size_t res = src ? wcrtomb(&out[j], src, &ps) : 0; switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-1): return std::string(); break; case 0: // We hit an embedded null byte, keep going. ++j; // Output is already zeroed. break; default: j += res; break; } } return out; } std::wstring SysNativeMBToWide(const StringPiece& native_mb) { mbstate_t ps; // Calculate the number of wide characters. We walk through the string // without writing the output, counting the number of wide characters. size_t num_out_chars = 0; memset(&ps, 0, sizeof(ps)); for (size_t i = 0; i < native_mb.size(); ) { const char* src = native_mb.data() + i; size_t res = mbrtowc(NULL, src, native_mb.size() - i, &ps); switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-2): case static_cast<size_t>(-1): return std::wstring(); break; case 0: // We hit an embedded null byte, keep going. i += 1; // Fall through. default: i += res; ++num_out_chars; break; } } if (num_out_chars == 0) return std::wstring(); std::wstring out; out.resize(num_out_chars); memset(&ps, 0, sizeof(ps)); // Clear the shift state. // We walk the input string again, with |i| tracking the index of the // multi-byte input, and |j| tracking the wide output. for (size_t i = 0, j = 0; i < native_mb.size(); ++j) { const char* src = native_mb.data() + i; wchar_t* dst = &out[j]; size_t res = mbrtowc(dst, src, native_mb.size() - i, &ps); switch (res) { // Handle any errors and return an empty string. case static_cast<size_t>(-2): case static_cast<size_t>(-1): return std::wstring(); break; case 0: i += 1; // Skip null byte. break; default: i += res; break; } } return out; } #endif // OS_CHROMEOS } // namespace base <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2007/02/09 14:13:05 iha 1.2.4.13: accept longs also for short values 2006/10/18 17:18:28 bm 1.2.4.12: RESYNC: (1.3-1.4); FILE MERGED 2006/03/07 12:35:47 bm 1.2.4.11: avoid variables starting with underscores. rMutex is a base-class member so use par_rMutex instead 2005/11/24 18:32:22 bm 1.2.4.10: setting a property to default must fire a change event 2005/11/15 15:30:36 bm 1.2.4.9: garbage collection, disposing, reference release issues 2005/11/03 13:38:56 bm 1.2.4.8: do not notify change to parent object in _NoBroadcast method 2005/11/03 11:57:25 bm 1.2.4.7: +firePropertyChangeEvent for notifying property changes 2005/10/07 12:11:23 bm 1.2.4.6: RESYNC: (1.2-1.3); FILE MERGED 2005/09/23 15:24:39 iha 1.2.4.5: #i55000# crash caused by dead reference to mutex 2005/09/02 11:12:50 bm 1.2.4.4: type check in setFastPropertyValue_NoBroadcast in debug mode 2005/08/03 16:36:28 bm 1.2.4.3: algohelper.hxx split up into CommonFunctors.hxx ContainerHelper.hxx CloneHelper.hxx 2005/03/30 16:31:14 bm 1.2.4.2: make model cloneable (+first undo implementation) 2004/02/13 16:51:53 bm 1.2.4.1: join from changes on branch bm_post_chart01<commit_after><|endoftext|>