hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
33f1d1866090d7b523881c4a92cd5f1820dbc088
6,635
cpp
C++
src/images/image.cpp
AKholetsky/blah
fb21ec869d476e525d728e61f2ba689ee02322e5
[ "MIT" ]
null
null
null
src/images/image.cpp
AKholetsky/blah
fb21ec869d476e525d728e61f2ba689ee02322e5
[ "MIT" ]
null
null
null
src/images/image.cpp
AKholetsky/blah
fb21ec869d476e525d728e61f2ba689ee02322e5
[ "MIT" ]
null
null
null
#include <blah/images/image.h> #include <blah/streams/stream.h> #include <blah/streams/filestream.h> #include <blah/core/log.h> using namespace Blah; #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_JPEG #define STBI_ONLY_PNG #define STBI_ONLY_BMP #include "../third_party/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../third_party/stb_image_write.h" namespace { int Blah_STBI_Read(void* user, char* data, int size) { int64_t read = ((Stream*)user)->read(data, size); return (int)read; } void Blah_STBI_Skip(void* user, int n) { ((Stream*)user)->seek(((Stream*)user)->position() + n); } int Blah_STBI_Eof(void* user) { int64_t position = ((Stream*)user)->position(); int64_t length = ((Stream*)user)->length(); if (position >= length) return 1; return 0; } void Blah_STBI_Write(void* context, void* data, int size) { ((Stream*)context)->write((char*)data, size); } } Image::Image() { width = height = 0; pixels = nullptr; m_stbi_ownership = false; } Image::Image(Stream& stream) { width = height = 0; pixels = nullptr; m_stbi_ownership = false; from_stream(stream); } Image::Image(const char* file) { width = height = 0; pixels = nullptr; m_stbi_ownership = false; FileStream fs(file, FileMode::Read); if (fs.is_readable()) from_stream(fs); } Image::Image(int w, int h) { BLAH_ASSERT(w >= 0 && h >= 0, "Image width and height must be larger than 0"); width = w; height = h; pixels = new Color[width * height]; m_stbi_ownership = false; memset(pixels, 0, (size_t)width * (size_t)height * sizeof(Color)); } Image::Image(const Image& src) { width = src.width; height = src.height; m_stbi_ownership = src.m_stbi_ownership; pixels = nullptr; if (src.pixels != nullptr && width > 0 && height > 0) { pixels = new Color[width * height]; memcpy(pixels, src.pixels, sizeof(Color) * width * height); } } Image& Image::operator=(const Image& src) { width = src.width; height = src.height; m_stbi_ownership = src.m_stbi_ownership; pixels = nullptr; if (src.pixels != nullptr && width > 0 && height > 0) { pixels = new Color[width * height]; memcpy(pixels, src.pixels, sizeof(Color) * width * height); } return *this; } Image::Image(Image&& src) noexcept { width = src.width; height = src.height; pixels = src.pixels; m_stbi_ownership = src.m_stbi_ownership; src.width = src.height = 0; src.pixels = nullptr; src.m_stbi_ownership = false; } Image& Image::operator=(Image&& src) noexcept { width = src.width; height = src.height; pixels = src.pixels; m_stbi_ownership = src.m_stbi_ownership; src.width = src.height = 0; src.pixels = nullptr; src.m_stbi_ownership = false; return *this; } Image::~Image() { dispose(); } void Image::from_stream(Stream& stream) { dispose(); if (!stream.is_readable()) { BLAH_ERROR("Unable to load image as the Stream was not readable"); return; } stbi_io_callbacks callbacks; callbacks.eof = Blah_STBI_Eof; callbacks.read = Blah_STBI_Read; callbacks.skip = Blah_STBI_Skip; int x, y, comps; uint8_t* data = stbi_load_from_callbacks(&callbacks, &stream, &x, &y, &comps, 4); if (data == nullptr) { BLAH_ERROR("Unable to load image as the Stream's data was not a valid image"); return; } m_stbi_ownership = true; pixels = (Color*)data; width = x; height = y; } void Image::dispose() { if (m_stbi_ownership) stbi_image_free(pixels); else delete[] pixels; pixels = nullptr; width = height = 0; m_stbi_ownership = false; } void Image::premultiply() { if (pixels != nullptr) { for (int n = 0; n < width * height; n ++) { pixels[n].r = (uint8_t)(pixels[n].r * pixels[n].a / 255); pixels[n].g = (uint8_t)(pixels[n].g * pixels[n].a / 255); pixels[n].b = (uint8_t)(pixels[n].b * pixels[n].a / 255); } } } void Image::set_pixels(const RectI& rect, Color* data) { for (int y = 0; y < rect.h; y++) { int to = rect.x + ((rect.y + y) * width); int from = (y * rect.w); memcpy(pixels + to, data + from, sizeof(Color) * rect.w); } } bool Image::save_png(const char* file) const { FileStream fs(file, FileMode::Write); return save_png(fs); } bool Image::save_png(Stream& stream) const { BLAH_ASSERT(pixels != nullptr, "Image Pixel data cannot be null"); BLAH_ASSERT(width > 0 && height > 0, "Image Width and Height must be larger than 0"); if (stream.is_writable()) { stbi_write_force_png_filter = 0; stbi_write_png_compression_level = 0; if (stbi_write_png_to_func(Blah_STBI_Write, &stream, width, height, 4, pixels, width * 4) != 0) return true; else Log::error("stbi_write_png_to_func failed"); } else { Log::error("Cannot save Image, the Stream is not writable"); } return false; } bool Image::save_jpg(const char* file, int quality) const { FileStream fs(file, FileMode::Write); return save_jpg(fs, quality); } bool Image::save_jpg(Stream& stream, int quality) const { BLAH_ASSERT(pixels != nullptr, "Image Pixel data cannot be null"); BLAH_ASSERT(width > 0 && height > 0, "Image Width and Height must be larger than 0"); if (quality < 1) { Log::warn("jpg quality value should be between 1 and 100; input was %i", quality); quality = 1; } else if (quality > 100) { Log::warn("jpg quality value should be between 1 and 100; input was %i", quality); quality = 100; } if (stream.is_writable()) { if (stbi_write_jpg_to_func(Blah_STBI_Write, &stream, width, height, 4, pixels, quality) != 0) return true; else Log::error("stbi_write_jpg_to_func failed"); } else { Log::error("Cannot save Image, the Stream is not writable"); } return false; } void Image::get_pixels(Color* dest, const Point& destPos, const Point& destSize, RectI sourceRect) { // can't be outside of the source image if (sourceRect.x < 0) sourceRect.x = 0; if (sourceRect.y < 0) sourceRect.y = 0; if (sourceRect.x + sourceRect.w > width) sourceRect.w = width - sourceRect.x; if (sourceRect.y + sourceRect.h > height) sourceRect.h = height - sourceRect.y; // can't be larger than our destination if (sourceRect.w > destSize.x - destPos.x) sourceRect.w = destSize.x - destPos.x; if (sourceRect.h > destSize.y - destPos.y) sourceRect.h = destSize.y - destPos.y; for (int y = 0; y < sourceRect.h; y++) { int to = destPos.x + (destPos.y + y) * destSize.x; int from = sourceRect.x + (sourceRect.y + y) * width; memcpy(dest + to, pixels + from, sizeof(Color) * (int)sourceRect.w); } } Image Image::get_sub_image(const RectI& sourceRect) { Image img(sourceRect.w, sourceRect.h); get_pixels(img.pixels, Point::zero, Point(img.width, img.height), sourceRect); return img; }
21.970199
98
0.674755
AKholetsky
33f216c181bf52fddc6e7c38d14e1a66455a1665
8,705
cpp
C++
ledger-core-tezos/src/tezos/database/TezosLikeTransactionDatabaseHelper.cpp
phaazon/lib-ledger-core
726009203f9b298e70b65c679ca92e99705dfc8c
[ "MIT" ]
null
null
null
ledger-core-tezos/src/tezos/database/TezosLikeTransactionDatabaseHelper.cpp
phaazon/lib-ledger-core
726009203f9b298e70b65c679ca92e99705dfc8c
[ "MIT" ]
null
null
null
ledger-core-tezos/src/tezos/database/TezosLikeTransactionDatabaseHelper.cpp
phaazon/lib-ledger-core
726009203f9b298e70b65c679ca92e99705dfc8c
[ "MIT" ]
null
null
null
/* * * TezosLikeTransactionDatabaseHelper * * Created by El Khalil Bellakrid on 27/04/2019. * * The MIT License (MIT) * * Copyright (c) 2019 Ledger * * 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 <tezos/database/TezosLikeTransactionDatabaseHelper.hpp> #include <tezos/api/enum_from_string.hpp> #include <tezos/api/TezosOperationTag.hpp> #include <core/crypto/SHA256.hpp> #include <core/database/SociOption.hpp> #include <core/database/SociDate.hpp> #include <core/database/SociNumber.hpp> #include <core/utils/Option.hpp> #include <core/wallet/BlockDatabaseHelper.hpp> using namespace soci; namespace ledger { namespace core { bool TezosLikeTransactionDatabaseHelper::getTransactionByHash( soci::session &sql, const std::string &hash, const std::string &operationUid, TezosLikeBlockchainExplorerTransaction &tx ) { rowset<row> rows = (sql.prepare << "SELECT tx.hash, tx.value, tx.time, " " tx.sender, tx.receiver, tx.fees, tx.gas_limit, tx.storage_limit, tx.confirmations, tx.type, tx.public_key, tx.originated_account, tx.status, " "block.height, block.hash, block.time, block.currency_name " "FROM tezos_transactions AS tx " "LEFT JOIN blocks AS block ON tx.block_uid = block.uid " "LEFT JOIN tezos_operations AS xtz_ops ON xtz_ops.transaction_uid = tx.transaction_uid " "WHERE tx.hash = :hash AND xtz_ops.uid = :uid", use(hash), use(operationUid)); for (auto &row : rows) { inflateTransaction(sql, row, tx); return true; } return false; } bool TezosLikeTransactionDatabaseHelper::inflateTransaction(soci::session &sql, const soci::row &row, TezosLikeBlockchainExplorerTransaction &tx) { tx.hash = row.get<std::string>(0); tx.value = BigInt::fromHex(row.get<std::string>(1)); tx.receivedAt = row.get<std::chrono::system_clock::time_point>(2); tx.sender = row.get<std::string>(3); tx.receiver = row.get<std::string>(4); tx.fees = BigInt::fromHex(row.get<std::string>(5)); tx.gas_limit = BigInt::fromHex(row.get<std::string>(6)); tx.storage_limit = BigInt::fromHex(row.get<std::string>(7)); tx.confirmations = get_number<uint64_t>(row, 8); tx.type = api::from_string<api::TezosOperationTag>(row.get<std::string>(9)); auto pubKey = row.get<std::string>(10); if (!pubKey.empty()) { tx.publicKey = pubKey; } auto values = strings::split(row.get<std::string>(11), ":"); if (values.size() == 3) { tx.originatedAccount = TezosLikeBlockchainExplorerOriginatedAccount(values[0], static_cast<bool>(std::stoi(values[1])), static_cast<bool>(std::stoi(values[2]))); } tx.status = get_number<uint64_t>(row, 12); if (row.get_indicator(13) != i_null) { TezosLikeBlockchainExplorer::Block block; block.height = get_number<uint64_t>(row, 13); block.blockHash = row.get<std::string>(14); block.time = row.get<std::chrono::system_clock::time_point>(15); block.currencyName = row.get<std::string>(16); tx.block = block; } return true; } bool TezosLikeTransactionDatabaseHelper::transactionExists(soci::session &sql, const std::string &tezosTxUid) { int32_t count = 0; sql << "SELECT COUNT(*) FROM tezos_transactions WHERE transaction_uid = :tezosTxUid", use(tezosTxUid), into( count); return count == 1; } std::string TezosLikeTransactionDatabaseHelper::createTezosTransactionUid(const std::string &accountUid, const std::string &txHash, api::TezosOperationTag type) { auto result = SHA256::stringToHexHash(fmt::format("uid:{}+{}+{}", accountUid, txHash, api::to_string(type))); return result; } std::string TezosLikeTransactionDatabaseHelper::putTransaction(soci::session &sql, const std::string &accountUid, const TezosLikeBlockchainExplorerTransaction &tx) { auto blockUid = tx.block.map<std::string>([](const TezosLikeBlockchainExplorer::Block &block) { return BlockDatabaseHelper::createBlockUid(block.blockHash, block.currencyName); }); auto tezosTxUid = createTezosTransactionUid(accountUid, tx.hash, tx.type); if (transactionExists(sql, tezosTxUid)) { // UPDATE (we only update block information) if (tx.block.nonEmpty()) { auto type = api::to_string(tx.type); use(blockUid), use(tx.status), use(tx.hash); sql << "UPDATE tezos_transactions SET block_uid = :uid, status = :code WHERE hash = :tx_hash AND type = :type", use(blockUid), use(tx.status), use(tx.hash), use(type); } return tezosTxUid; } else { // Insert if (tx.block.nonEmpty()) { BlockDatabaseHelper::putBlock(sql, tx.block.getValue()); } auto hexValue = tx.value.toHexString(); auto hexFees = tx.fees.toHexString(); auto hexGasLimit = tx.gas_limit.toHexString(); auto hexStorageLimit = tx.storage_limit.toHexString(); auto type = api::to_string(tx.type); auto pubKey = tx.publicKey.getValueOr(""); std::string sOrigAccount; if (tx.originatedAccount.hasValue()) { std::stringstream origAccount; std::vector<std::string> vOrigAccount{tx.originatedAccount.getValue().address, std::to_string(tx.originatedAccount.getValue().spendable), std::to_string(tx.originatedAccount.getValue().delegatable)}; strings::join(vOrigAccount, origAccount, ":"); sOrigAccount = origAccount.str(); } sql << "INSERT INTO tezos_transactions VALUES(:tx_uid, :hash, :value, :block_uid, :time, :sender, :receiver, :fees, :gas_limit, :storage_limit, :confirmations, :type, :public_key, :originated_account, :status)", use(tezosTxUid), use(tx.hash), use(hexValue), use(blockUid), use(tx.receivedAt), use(tx.sender), use(tx.receiver), use(hexFees), use(hexGasLimit), use(hexStorageLimit), use(tx.confirmations), use(type), use(pubKey), use(sOrigAccount), use(tx.status); return tezosTxUid; } } } }
48.904494
227
0.559563
phaazon
33f318206761e0974f2143add8de7c12bcdc3a36
457
hpp
C++
core/Light.hpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
core/Light.hpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
core/Light.hpp
jmppmj/3dgameengine_jillplatts
64f472322423aa4d2c8be5366f36d78dde9f568b
[ "MIT" ]
null
null
null
#pragma once #include "ModelData.hpp" class Light { private: glm::vec3 pos = glm::vec3(0, 0, 0); glm::vec3 color = glm::vec3(1, 1, 1); bool isPointLight = true; public: Light(glm::vec3 pos, glm::vec3 color, bool isPointLight); void Light::setPos(glm::vec3 pos2); bool Light::getIsPointLight(); void Light::setIsPointLight(bool isPointLight); void Light::setColor(glm::vec3 color); glm::vec4 Light::getColor(); glm::vec4 Light::getPos(); };
18.28
58
0.68709
jmppmj
33f3319ba7dee8950a9dd95f73ffc956570be68b
612
cc
C++
kattis/alicedigital.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
kattis/alicedigital.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
kattis/alicedigital.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://open.kattis.com/problems/alicedigital #include <iostream> #include <vector> using namespace std; typedef vector<int> vi; int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; vi a(n + 1, 0); int p = 0; int q = 0; int M = 0; for (int i = 1; i <= n; i++) { cin >> a[i]; if (a[i] < m) { if (q) M = max(M, a[i - 1] - a[p]); p = i; q = 0; } else if (a[i] == m) { if (!q) q = i; else { M = max(M, a[i - 1] - a[p]); p = q; q = i; } } a[i] += a[i - 1]; } if (q) M = max(M, a[n] - a[p]); cout << M << endl; } }
15.692308
48
0.406863
Ashindustry007
33f56b32135cbdb9f7fec298a823d6a3209ba514
106,894
cpp
C++
thorlcr/graph/thgraph.cpp
roscoche/HPCC-Platform
9975e6c5a0996d25ac3c24e3b57dd1389a87f06b
[ "Apache-2.0" ]
null
null
null
thorlcr/graph/thgraph.cpp
roscoche/HPCC-Platform
9975e6c5a0996d25ac3c24e3b57dd1389a87f06b
[ "Apache-2.0" ]
null
null
null
thorlcr/graph/thgraph.cpp
roscoche/HPCC-Platform
9975e6c5a0996d25ac3c24e3b57dd1389a87f06b
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 "thgraph.hpp" #include "jptree.hpp" #include "commonext.hpp" #include "dasess.hpp" #include "jhtree.hpp" #include "thcodectx.hpp" #include "thbuf.hpp" #include "thormisc.hpp" #include "thbufdef.hpp" #include "thmem.hpp" #include "rtlformat.hpp" PointerArray createFuncs; void registerCreateFunc(CreateFunc func) { createFuncs.append((void *)func); } /////////////////////////////////// ////// ///// class CThorGraphResult : implements IThorResult, implements IRowWriter, public CInterface { CActivityBase &activity; rowcount_t rowStreamCount; IOutputMetaData *meta; Owned<IRowWriterMultiReader> rowBuffer; IThorRowInterfaces *rowIf; IEngineRowAllocator *allocator; bool stopped, readers; ThorGraphResultType resultType; void init() { stopped = readers = false; allocator = rowIf->queryRowAllocator(); meta = allocator->queryOutputMeta(); rowStreamCount = 0; } class CStreamWriter : implements IRowWriterMultiReader, public CSimpleInterface { CThorGraphResult &owner; CThorExpandingRowArray rows; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CStreamWriter(CThorGraphResult &_owner, EmptyRowSemantics emptyRowSemantics) : owner(_owner), rows(owner.activity, owner.rowIf, emptyRowSemantics) { } //IRowWriterMultiReader virtual void putRow(const void *row) { rows.append(row); } virtual void flush() { } virtual IRowStream *getReader() { return rows.createRowStream(0, (rowidx_t)-1, false); } }; public: IMPLEMENT_IINTERFACE; CThorGraphResult(CActivityBase &_activity, IThorRowInterfaces *_rowIf, ThorGraphResultType _resultType, unsigned spillPriority) : activity(_activity), rowIf(_rowIf), resultType(_resultType) { init(); EmptyRowSemantics emptyRowSemantics; if (isGrouped()) emptyRowSemantics = ers_eogonly; else if (isSparse()) emptyRowSemantics = ers_allow; else emptyRowSemantics = ers_forbidden; if (SPILL_PRIORITY_DISABLE == spillPriority) rowBuffer.setown(new CStreamWriter(*this, emptyRowSemantics)); else rowBuffer.setown(createOverflowableBuffer(activity, rowIf, emptyRowSemantics, true)); } // IRowWriter virtual void putRow(const void *row) { assertex(!readers); ++rowStreamCount; rowBuffer->putRow(row); } virtual void flush() { } virtual offset_t getPosition() { UNIMPLEMENTED; return 0; } // IThorResult virtual IRowWriter *getWriter() { return LINK(this); } virtual void setResultStream(IRowWriterMultiReader *stream, rowcount_t count) { assertex(!readers); rowBuffer.setown(stream); rowStreamCount = count; } virtual IRowStream *getRowStream() { readers = true; return rowBuffer->getReader(); } virtual IThorRowInterfaces *queryRowInterfaces() { return rowIf; } virtual CActivityBase *queryActivity() { return &activity; } virtual bool isDistributed() const { return resultType & thorgraphresult_distributed; } virtual bool isSparse() const { return resultType & thorgraphresult_sparse; } virtual bool isGrouped() const { return resultType & thorgraphresult_grouped; } virtual void serialize(MemoryBuffer &mb) { Owned<IRowStream> stream = getRowStream(); bool grouped = meta->isGrouped(); if (grouped) { OwnedConstThorRow prev = stream->nextRow(); if (prev) { bool eog; for (;;) { eog = false; OwnedConstThorRow next = stream->nextRow(); if (!next) eog = true; size32_t sz = meta->getRecordSize(prev); mb.append(sz, prev.get()); mb.append(eog); if (!next) { next.setown(stream->nextRow()); if (!next) break; } prev.set(next); } } } else { for (;;) { OwnedConstThorRow row = stream->nextRow(); if (!row) break; size32_t sz = meta->getRecordSize(row); mb.append(sz, row.get()); } } } virtual void getResult(size32_t &len, void * & data) { MemoryBuffer mb; serialize(mb); len = mb.length(); data = mb.detach(); } virtual void getLinkedResult(unsigned &countResult, const byte * * & result) override { assertex(rowStreamCount==((unsigned)rowStreamCount)); // catch, just in case Owned<IRowStream> stream = getRowStream(); countResult = 0; OwnedConstThorRow _rowset = allocator->createRowset((unsigned)rowStreamCount); const void **rowset = (const void **)_rowset.get(); while (countResult < rowStreamCount) { OwnedConstThorRow row = stream->nextRow(); rowset[countResult++] = row.getClear(); } result = (const byte **)_rowset.getClear(); } virtual const void * getLinkedRowResult() { assertex(rowStreamCount==1); // catch, just in case Owned<IRowStream> stream = getRowStream(); return stream->nextRow(); } }; ///// IThorResult *CThorGraphResults::createResult(CActivityBase &activity, unsigned id, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority) { Owned<IThorResult> result = ::createResult(activity, rowIf, resultType, spillPriority); setResult(id, result); return result; } ///// IThorResult *createResult(CActivityBase &activity, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority) { return new CThorGraphResult(activity, rowIf, resultType, spillPriority); } ///// class CThorBoundLoopGraph : implements IThorBoundLoopGraph, public CInterface { CGraphBase *graph; activity_id activityId; Linked<IOutputMetaData> resultMeta; Owned<IOutputMetaData> counterMeta, loopAgainMeta; Owned<IThorRowInterfaces> resultRowIf, countRowIf, loopAgainRowIf; public: IMPLEMENT_IINTERFACE; CThorBoundLoopGraph(CGraphBase *_graph, IOutputMetaData * _resultMeta, unsigned _activityId) : graph(_graph), resultMeta(_resultMeta), activityId(_activityId) { counterMeta.setown(createFixedSizeMetaData(sizeof(thor_loop_counter_t))); loopAgainMeta.setown(createFixedSizeMetaData(sizeof(bool))); } virtual void prepareCounterResult(CActivityBase &activity, IThorGraphResults *results, unsigned loopCounter, unsigned pos) { if (!countRowIf) countRowIf.setown(activity.createRowInterfaces(counterMeta)); RtlDynamicRowBuilder counterRow(countRowIf->queryRowAllocator()); thor_loop_counter_t * res = (thor_loop_counter_t *)counterRow.ensureCapacity(sizeof(thor_loop_counter_t),NULL); *res = loopCounter; OwnedConstThorRow counterRowFinal = counterRow.finalizeRowClear(sizeof(thor_loop_counter_t)); IThorResult *counterResult = results->createResult(activity, pos, countRowIf, thorgraphresult_nul, SPILL_PRIORITY_DISABLE); Owned<IRowWriter> counterResultWriter = counterResult->getWriter(); counterResultWriter->putRow(counterRowFinal.getClear()); graph->setLoopCounter(loopCounter); } virtual void prepareLoopAgainResult(CActivityBase &activity, IThorGraphResults *results, unsigned pos) { if (!loopAgainRowIf) loopAgainRowIf.setown(activity.createRowInterfaces(loopAgainMeta)); activity.queryGraph().createResult(activity, pos, results, loopAgainRowIf, activity.queryGraph().isLocalChild() ? thorgraphresult_nul : thorgraphresult_distributed, SPILL_PRIORITY_DISABLE); } virtual void prepareLoopResults(CActivityBase &activity, IThorGraphResults *results) { if (!resultRowIf) resultRowIf.setown(activity.createRowInterfaces(resultMeta)); ThorGraphResultType resultType = activity.queryGraph().isLocalChild() ? thorgraphresult_nul : thorgraphresult_distributed; IThorResult *loopResult = activity.queryGraph().createResult(activity, 0, results, resultRowIf, resultType); // loop output IThorResult *inputResult = activity.queryGraph().createResult(activity, 1, results, resultRowIf, resultType); // loop input } virtual CGraphBase *queryGraph() { return graph; } }; IThorBoundLoopGraph *createBoundLoopGraph(CGraphBase *graph, IOutputMetaData *resultMeta, unsigned activityId) { return new CThorBoundLoopGraph(graph, resultMeta, activityId); } /////////////////////////////////// bool isDiskInput(ThorActivityKind kind) { switch (kind) { case TAKcsvread: case TAKxmlread: case TAKjsonread: case TAKdiskread: case TAKdisknormalize: case TAKdiskaggregate: case TAKdiskcount: case TAKdiskgroupaggregate: case TAKindexread: case TAKindexcount: case TAKindexnormalize: case TAKindexaggregate: case TAKindexgroupaggregate: case TAKindexgroupexists: case TAKindexgroupcount: case TAKspillread: return true; default: return false; } } void CIOConnection::connect(unsigned which, CActivityBase *destActivity) { destActivity->setInput(which, activity->queryActivity(), index); } /////////////////////////////////// CGraphElementBase *createGraphElement(IPropertyTree &node, CGraphBase &owner, CGraphBase *resultsGraph) { CGraphElementBase *container = NULL; ForEachItemIn(m, createFuncs) { CreateFunc func = (CreateFunc)createFuncs.item(m); container = func(node, owner, resultsGraph); if (container) break; } if (NULL == container) { ThorActivityKind tak = (ThorActivityKind)node.getPropInt("att[@name=\"_kind\"]/@value", TAKnone); throw MakeStringException(TE_UnsupportedActivityKind, "Unsupported activity kind: %s", activityKindStr(tak)); } container->setResultsGraph(resultsGraph); return container; } CGraphElementBase::CGraphElementBase(CGraphBase &_owner, IPropertyTree &_xgmml) : owner(&_owner) { xgmml.setown(createPTreeFromIPT(&_xgmml)); eclText.set(xgmml->queryProp("att[@name=\"ecl\"]/@value")); id = xgmml->getPropInt("@id", 0); kind = (ThorActivityKind)xgmml->getPropInt("att[@name=\"_kind\"]/@value", TAKnone); sink = isActivitySink(kind); bool coLocal = xgmml->getPropBool("att[@name=\"coLocal\"]/@value", false); isLocalData = xgmml->getPropBool("att[@name=\"local\"]/@value", false); // local execute + local data access only isLocal = isLocalData || coLocal; // local execute isGrouped = xgmml->getPropBool("att[@name=\"grouped\"]/@value", false); resultsGraph = NULL; ownerId = xgmml->getPropInt("att[@name=\"_parentActivity\"]/@value", 0); onCreateCalled = prepared = haveCreateCtx = nullAct = false; onlyUpdateIfChanged = xgmml->getPropBool("att[@name=\"_updateIfChanged\"]/@value", false); StringBuffer helperName("fAc"); xgmml->getProp("@id", helperName); helperFactory = (EclHelperFactory) queryJob().queryDllEntry().getEntry(helperName.str()); if (!helperFactory) throw makeOsExceptionV(GetLastError(), "Failed to load helper factory method: %s (dll handle = %p)", helperName.str(), queryJob().queryDllEntry().getInstance()); alreadyUpdated = false; whichBranch = (unsigned)-1; log = true; sentActInitData.setown(createThreadSafeBitSet()); maxCores = queryXGMML().getPropInt("hint[@name=\"max_cores\"]/@value", 0); if (0 == maxCores) maxCores = queryJob().queryMaxDefaultActivityCores(); baseHelper.setown(helperFactory()); } CGraphElementBase::~CGraphElementBase() { activity.clear(); baseHelper.clear(); // clear before dll is unloaded } CJobBase &CGraphElementBase::queryJob() const { return owner->queryJob(); } CJobChannel &CGraphElementBase::queryJobChannel() const { return owner->queryJobChannel(); } IGraphTempHandler *CGraphElementBase::queryTempHandler() const { if (resultsGraph) return resultsGraph->queryTempHandler(); else return queryJob().queryTempHandler(); } void CGraphElementBase::releaseIOs() { loopGraph.clear(); if (activity) activity->releaseIOs(); connectedInputs.kill(); inputs.kill(); outputs.kill(); activity.clear(); } void CGraphElementBase::addDependsOn(CGraphBase *graph, int controlId) { ForEachItemIn(i, dependsOn) { if (dependsOn.item(i).graph == graph) return; } dependsOn.append(*new CGraphDependency(graph, controlId)); } StringBuffer &CGraphElementBase::getOpt(const char *prop, StringBuffer &out) const { VStringBuffer path("hint[@name=\"%s\"]/@value", prop); if (!queryXGMML().getProp(path.toLowerCase().str(), out)) queryJob().getOpt(prop, out); return out; } bool CGraphElementBase::getOptBool(const char *prop, bool defVal) const { bool def = queryJob().getOptBool(prop, defVal); VStringBuffer path("hint[@name=\"%s\"]/@value", prop); return queryXGMML().getPropBool(path.toLowerCase().str(), def); } int CGraphElementBase::getOptInt(const char *prop, int defVal) const { int def = queryJob().getOptInt(prop, defVal); VStringBuffer path("hint[@name=\"%s\"]/@value", prop); return queryXGMML().getPropInt(path.toLowerCase().str(), def); } __int64 CGraphElementBase::getOptInt64(const char *prop, __int64 defVal) const { __int64 def = queryJob().getOptInt64(prop, defVal); VStringBuffer path("hint[@name=\"%s\"]/@value", prop); return queryXGMML().getPropInt64(path.toLowerCase().str(), def); } IThorGraphDependencyIterator *CGraphElementBase::getDependsIterator() const { return new ArrayIIteratorOf<const CGraphDependencyArray, CGraphDependency, IThorGraphDependencyIterator>(dependsOn); } void CGraphElementBase::reset() { alreadyUpdated = false; if (activity) activity->reset(); } void CGraphElementBase::ActPrintLog(const char *format, ...) { va_list args; va_start(args, format); ::ActPrintLogArgs(this, thorlog_null, MCdebugProgress, format, args); va_end(args); } void CGraphElementBase::ActPrintLog(IException *e, const char *format, ...) { va_list args; va_start(args, format); ::ActPrintLogArgs(this, e, thorlog_all, MCexception(e), format, args); va_end(args); } void CGraphElementBase::ActPrintLog(IException *e) { ActPrintLog(e, "%s", ""); } void CGraphElementBase::abort(IException *e) { CActivityBase *activity = queryActivity(); if (activity) activity->abort(); } void CGraphElementBase::doconnect() { ForEachItemIn(i, connectedInputs) { CIOConnection *io = connectedInputs.item(i); if (io) io->connect(i, queryActivity()); } } void CGraphElementBase::clearConnections() { connectedInputs.kill(); connectedOutputs.kill(); if (activity) activity->clearConnections(); } void CGraphElementBase::addInput(unsigned input, CGraphElementBase *inputAct, unsigned inputOutIdx) { while (inputs.ordinality()<=input) inputs.append(NULL); inputs.replace(new COwningSimpleIOConnection(LINK(inputAct), inputOutIdx), input); while (inputAct->outputs.ordinality()<=inputOutIdx) inputAct->outputs.append(NULL); inputAct->outputs.replace(new CIOConnection(this, input), inputOutIdx); } void CGraphElementBase::connectInput(unsigned input, CGraphElementBase *inputAct, unsigned inputOutIdx) { ActPrintLog("CONNECTING (id=%" ACTPF "d, idx=%d) to (id=%" ACTPF "d, idx=%d)", inputAct->queryId(), inputOutIdx, queryId(), input); while (connectedInputs.ordinality()<=input) connectedInputs.append(NULL); connectedInputs.replace(new COwningSimpleIOConnection(LINK(inputAct), inputOutIdx), input); while (inputAct->connectedOutputs.ordinality()<=inputOutIdx) inputAct->connectedOutputs.append(NULL); inputAct->connectedOutputs.replace(new CIOConnection(this, input), inputOutIdx); } void CGraphElementBase::serializeCreateContext(MemoryBuffer &mb) { if (!onCreateCalled) return; DelayedSizeMarker sizeMark(mb); queryHelper()->serializeCreateContext(mb); sizeMark.write(); if (isSink()) mb.append(alreadyUpdated); } void CGraphElementBase::deserializeCreateContext(MemoryBuffer &mb) { size32_t createCtxLen; mb.read(createCtxLen); createCtxMb.clear().append(createCtxLen, mb.readDirect(createCtxLen)); haveCreateCtx = true; if (isSink()) mb.read(alreadyUpdated); } void CGraphElementBase::serializeStartContext(MemoryBuffer &mb) { DelayedSizeMarker sizeMark(mb); queryHelper()->serializeStartContext(mb); sizeMark.write(); } void CGraphElementBase::onCreate() { CriticalBlock b(crit); if (onCreateCalled) return; onCreateCalled = true; if (!nullAct) { CGraphElementBase *ownerActivity = owner->queryOwner() ? owner->queryOwner()->queryElement(ownerId) : NULL; if (ownerActivity) { ownerActivity->onCreate(); // ensure owner created, might not be if this is child query inside another child query. baseHelper->onCreate(queryCodeContext(), ownerActivity->queryHelper(), haveCreateCtx?&createCtxMb:NULL); } else baseHelper->onCreate(queryCodeContext(), NULL, haveCreateCtx?&createCtxMb:NULL); if (isLoopActivity(*this)) { unsigned loopId = queryXGMML().getPropInt("att[@name=\"_loopid\"]/@value"); Owned<CGraphStub> stub = owner->getChildGraph(loopId); Owned<IThorBoundLoopGraph> boundLoopGraph = createBoundLoopGraph(&stub->queryOriginalGraph(), baseHelper->queryOutputMeta(), queryId()); setBoundGraph(boundLoopGraph); } } } void CGraphElementBase::onStart(size32_t parentExtractSz, const byte *parentExtract, MemoryBuffer *startCtx) { if (nullAct) return; CriticalBlock b(crit); baseHelper->onStart(parentExtract, startCtx); } bool CGraphElementBase::executeDependencies(size32_t parentExtractSz, const byte *parentExtract, int controlId, bool async) { Owned<IThorGraphDependencyIterator> deps = getDependsIterator(); ForEach(*deps) { CGraphDependency &dep = deps->query(); if (dep.controlId == controlId) dep.graph->execute(parentExtractSz, parentExtract, true, async); if (owner->queryJob().queryAborted() || owner->queryAborted()) return false; } return true; } bool CGraphElementBase::prepareContext(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies, bool shortCircuit, bool async, bool connectOnly) { try { bool create = true; if (connectOnly) { if (prepared) return true; ForEachItemIn(i, inputs) { if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, false, false, async, true)) return false; } } else { bool _shortCircuit = shortCircuit; Owned<IThorGraphDependencyIterator> deps = getDependsIterator(); bool depsDone = true; ForEach(*deps) { CGraphDependency &dep = deps->query(); if (0 == dep.controlId && NotFound == owner->dependentSubGraphs.find(*dep.graph)) { owner->dependentSubGraphs.append(*dep.graph); if (!dep.graph->isComplete()) depsDone = false; } } if (depsDone) _shortCircuit = false; if (!depsDone && checkDependencies) { if (!executeDependencies(parentExtractSz, parentExtract, 0, async)) return false; } whichBranch = (unsigned)-1; switch (getKind()) { case TAKindexwrite: case TAKdiskwrite: case TAKcsvwrite: case TAKxmlwrite: case TAKjsonwrite: case TAKspillwrite: if (_shortCircuit) return true; onCreate(); alreadyUpdated = checkUpdate(); if (alreadyUpdated) return false; break; case TAKchildif: case TAKif: case TAKifaction: { if (_shortCircuit) return true; onCreate(); onStart(parentExtractSz, parentExtract); IHThorIfArg *helper = (IHThorIfArg *)baseHelper.get(); whichBranch = helper->getCondition() ? 0 : 1; // True argument precedes false... /* NB - The executeDependencies code below is only needed if actionLinkInNewGraph=true, which is no longer the default * It should be removed, once we are positive there are no issues with in-line conditional actions */ if (TAKifaction == getKind()) { if (!executeDependencies(parentExtractSz, parentExtract, whichBranch+1, async)) //NB whenId 1 based return false; create = false; } break; } case TAKchildcase: case TAKcase: { if (_shortCircuit) return true; onCreate(); onStart(parentExtractSz, parentExtract); IHThorCaseArg *helper = (IHThorCaseArg *)baseHelper.get(); whichBranch = helper->getBranch(); if (whichBranch >= inputs.ordinality()) whichBranch = inputs.ordinality()-1; break; } case TAKfilter: case TAKfiltergroup: case TAKfilterproject: { if (_shortCircuit) return true; onCreate(); onStart(parentExtractSz, parentExtract); switch (getKind()) { case TAKfilter: whichBranch = ((IHThorFilterArg *)baseHelper.get())->canMatchAny() ? 0 : 1; break; case TAKfiltergroup: whichBranch = ((IHThorFilterGroupArg *)baseHelper.get())->canMatchAny() ? 0 : 1; break; case TAKfilterproject: whichBranch = ((IHThorFilterProjectArg *)baseHelper.get())->canMatchAny() ? 0 : 1; break; } break; } case TAKsequential: case TAKparallel: { /* NB - The executeDependencies code below is only needed if actionLinkInNewGraph=true, which is no longer the default * It should be removed, once we are positive there are no issues with in-line sequential/parallel activities */ for (unsigned s=1; s<=dependsOn.ordinality(); s++) executeDependencies(parentExtractSz, parentExtract, s, async); create = false; break; } case TAKwhen_dataset: case TAKwhen_action: { if (!executeDependencies(parentExtractSz, parentExtract, WhenBeforeId, async)) return false; if (!executeDependencies(parentExtractSz, parentExtract, WhenParallelId, async)) return false; break; } } if (checkDependencies && ((unsigned)-1 != whichBranch)) { if (inputs.queryItem(whichBranch)) { if (!queryInput(whichBranch)->prepareContext(parentExtractSz, parentExtract, true, false, async, connectOnly)) return false; } ForEachItemIn(i, inputs) { if (i != whichBranch) { if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, false, false, async, true)) return false; } } } else { ForEachItemIn(i, inputs) { if (!queryInput(i)->prepareContext(parentExtractSz, parentExtract, checkDependencies, false, async, connectOnly)) return false; } } } if (create) { if (prepared) // no need to recreate return true; prepared = true; ForEachItemIn(i2, inputs) { CIOConnection *inputIO = inputs.item(i2); connectInput(i2, inputIO->activity, inputIO->index); } createActivity(); } return true; } catch (IException *_e) { IThorException *e = QUERYINTERFACE(_e, IThorException); if (e) { if (!e->queryActivityId()) setExceptionActivityInfo(*this, e); } else { e = MakeActivityException(this, _e); _e->Release(); } throw e; } } void CGraphElementBase::preStart(size32_t parentExtractSz, const byte *parentExtract) { activity->preStart(parentExtractSz, parentExtract); } void CGraphElementBase::createActivity() { CriticalBlock b(crit); if (activity) return; activity.setown(factory()); if (isSink()) owner->addActiveSink(*this); } ICodeContext *CGraphElementBase::queryCodeContext() { return queryOwner().queryCodeContext(); } ///// // JCSMORE loop - probably need better way to check if any act in graph is global(meaning needs some synchronization between slaves in activity execution) bool isGlobalActivity(CGraphElementBase &container) { switch (container.getKind()) { // always global, but only co-ordinate init/done case TAKcsvwrite: case TAKxmlwrite: case TAKjsonwrite: case TAKindexwrite: case TAKkeydiff: case TAKkeypatch: case TAKdictionaryworkunitwrite: return true; case TAKdiskwrite: { Owned<IHThorDiskWriteArg> helper = (IHThorDiskWriteArg *)container.helperFactory(); unsigned flags = helper->getFlags(); return (0 == (TDXtemporary & flags)); // global if not temporary } case TAKspillwrite: case TAKspill: return false; case TAKcsvread: { Owned<IHThorCsvReadArg> helper = (IHThorCsvReadArg *)container.helperFactory(); // if header lines, then [may] need to co-ordinate across slaves if (container.queryOwner().queryOwner() && (!container.queryOwner().isGlobal())) // I am in a child query return false; return helper->queryCsvParameters()->queryHeaderLen() > 0; } // dependent on child acts? case TAKlooprow: case TAKloopcount: case TAKgraphloop: case TAKparallelgraphloop: case TAKloopdataset: case TAKexternalsink: case TAKexternalsource: case TAKexternalprocess: return false; // dependent on local/grouped case TAKkeyeddistribute: case TAKhashdistribute: case TAKhashdistributemerge: case TAKnwaydistribute: case TAKworkunitwrite: case TAKdistribution: case TAKpartition: case TAKdiskaggregate: case TAKdiskcount: case TAKdiskgroupaggregate: case TAKindexaggregate: case TAKindexcount: case TAKindexgroupaggregate: case TAKindexgroupexists: case TAKindexgroupcount: case TAKremoteresult: case TAKcountproject: case TAKcreaterowlimit: case TAKskiplimit: case TAKlimit: case TAKsort: case TAKdedup: case TAKjoin: case TAKselfjoin: case TAKhashjoin: case TAKsmartjoin: case TAKkeyeddenormalize: case TAKhashdenormalize: case TAKdenormalize: case TAKlookupdenormalize: //GH->JCS why are these here, and join not? case TAKalldenormalize: case TAKsmartdenormalize: case TAKdenormalizegroup: case TAKhashdenormalizegroup: case TAKlookupdenormalizegroup: case TAKkeyeddenormalizegroup: case TAKalldenormalizegroup: case TAKsmartdenormalizegroup: case TAKaggregate: case TAKexistsaggregate: case TAKcountaggregate: case TAKhashaggregate: case TAKhashdedup: case TAKrollup: case TAKiterate: case TAKselectn: case TAKfirstn: case TAKenth: case TAKsample: case TAKgroup: case TAKchoosesets: case TAKchoosesetsenth: case TAKchoosesetslast: case TAKtopn: case TAKprocess: case TAKchildcount: case TAKwhen_dataset: case TAKwhen_action: case TAKnonempty: if (!container.queryLocalOrGrouped()) return true; break; case TAKkeyedjoin: case TAKalljoin: case TAKlookupjoin: if (!container.queryLocal()) return true; // always local case TAKfilter: case TAKfilterproject: case TAKfiltergroup: case TAKsplit: case TAKpipewrite: case TAKdegroup: case TAKproject: case TAKprefetchproject: case TAKprefetchcountproject: case TAKnormalize: case TAKnormalizechild: case TAKnormalizelinkedchild: case TAKpipethrough: case TAKif: case TAKchildif: case TAKchildcase: case TAKcase: case TAKparse: case TAKpiperead: case TAKxmlparse: case TAKjoinlight: case TAKselfjoinlight: case TAKdiskread: case TAKdisknormalize: case TAKchildaggregate: case TAKchildgroupaggregate: case TAKchildthroughnormalize: case TAKchildnormalize: case TAKspillread: case TAKindexread: case TAKindexnormalize: case TAKxmlread: case TAKjsonread: case TAKdiskexists: case TAKindexexists: case TAKchildexists: case TAKthroughaggregate: case TAKmerge: case TAKfunnel: case TAKregroup: case TAKcombine: case TAKrollupgroup: case TAKcombinegroup: case TAKsoap_rowdataset: case TAKhttp_rowdataset: case TAKsoap_rowaction: case TAKsoap_datasetdataset: case TAKsoap_datasetaction: case TAKlinkedrawiterator: case TAKchilditerator: case TAKstreamediterator: case TAKworkunitread: case TAKchilddataset: case TAKinlinetable: case TAKnull: case TAKemptyaction: case TAKlocalresultread: case TAKlocalresultwrite: case TAKdictionaryresultwrite: case TAKgraphloopresultread: case TAKgraphloopresultwrite: case TAKnwaygraphloopresultread: case TAKapply: case TAKsideeffect: case TAKsimpleaction: case TAKsorted: case TAKdistributed: case TAKtrace: break; case TAKnwayjoin: case TAKnwaymerge: case TAKnwaymergejoin: case TAKnwayinput: case TAKnwayselect: return false; // JCSMORE - I think and/or have to be for now // undefined case TAKdatasetresult: case TAKrowresult: case TAKremotegraph: case TAKlibrarycall: default: return true; // if in doubt } return false; } bool isLoopActivity(CGraphElementBase &container) { switch (container.getKind()) { case TAKlooprow: case TAKloopcount: case TAKloopdataset: case TAKgraphloop: case TAKparallelgraphloop: return true; } return false; } static void getGlobalDeps(CGraphBase &graph, CICopyArrayOf<CGraphDependency> &deps) { Owned<IThorActivityIterator> iter = graph.getIterator(); ForEach(*iter) { CGraphElementBase &elem = iter->query(); Owned<IThorGraphDependencyIterator> dependIterator = elem.getDependsIterator(); ForEach(*dependIterator) { CGraphDependency &dependency = dependIterator->query(); if (dependency.graph->isGlobal() && NULL==dependency.graph->queryOwner()) deps.append(dependency); getGlobalDeps(*dependency.graph, deps); } } } static void noteDependency(CGraphElementBase *targetActivity, CGraphElementBase *sourceActivity, CGraphBase *targetGraph, CGraphBase *sourceGraph, unsigned controlId) { targetActivity->addDependsOn(sourceGraph, controlId); // NB: record dependency in source graph, serialized to slaves, used to decided if should run dependency sinks or not Owned<IPropertyTree> dependencyFor = createPTree(); dependencyFor->setPropInt("@id", sourceActivity->queryId()); dependencyFor->setPropInt("@graphId", targetGraph->queryGraphId()); if (controlId) dependencyFor->setPropInt("@conditionalId", controlId); sourceGraph->queryXGMML().addPropTree("Dependency", dependencyFor.getClear()); } static void addDependencies(IPropertyTree *xgmml, bool failIfMissing, CGraphTableCopy &graphs) { CGraphArrayCopy dependentchildGraphs; CGraphElementArrayCopy targetActivities, sourceActivities; Owned<IPropertyTreeIterator> iter = xgmml->getElements("edge"); ForEach(*iter) { IPropertyTree &edge = iter->query(); graph_id sourceGid = edge.getPropInt("@source"); graph_id targetGid = edge.getPropInt("@target"); Owned<CGraphBase> source = LINK(graphs.find(sourceGid)); Owned<CGraphBase> target = LINK(graphs.find(targetGid)); if (!source || !target) { if (failIfMissing) throwUnexpected(); else continue; // expected if assigning dependencies in slaves } CGraphElementBase *targetActivity = (CGraphElementBase *)target->queryElement(edge.getPropInt("att[@name=\"_targetActivity\"]/@value")); CGraphElementBase *sourceActivity = (CGraphElementBase *)source->queryElement(edge.getPropInt("att[@name=\"_sourceActivity\"]/@value")); if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value")) { if (TAKlocalresultwrite == sourceActivity->getKind() && (TAKlocalresultread != targetActivity->getKind())) { if (source->isLoopSubGraph()) source->setGlobal(true); } } int controlId = 0; if (edge.getPropBool("att[@name=\"_dependsOn\"]/@value", false)) { if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) // JCSMORE - not sure if necess. roxie seem to do. controlId = edge.getPropInt("att[@name=\"_when\"]/@value", 0); CGraphBase &sourceGraph = sourceActivity->queryOwner(); unsigned sourceGraphContext = sourceGraph.queryParentActivityId(); CGraphBase *targetGraph = NULL; unsigned targetGraphContext = -1; for (;;) { targetGraph = &targetActivity->queryOwner(); targetGraphContext = targetGraph->queryParentActivityId(); if (sourceGraphContext == targetGraphContext) break; targetActivity = targetGraph->queryElement(targetGraphContext); } assertex(targetActivity && sourceActivity); noteDependency(targetActivity, sourceActivity, target, source, controlId); } else if (edge.getPropBool("att[@name=\"_conditionSource\"]/@value", false)) { /* Ignore it */ } else if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) { // NB: any dependencies of the child acts. are dependencies of this act. dependentchildGraphs.append(*source); targetActivities.append(*targetActivity); sourceActivities.append(*sourceActivity); } else { if (!edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) // JCSMORE - not sure if necess. roxie seem to do. controlId = edge.getPropInt("att[@name=\"_when\"]/@value", 0); noteDependency(targetActivity, sourceActivity, target, source, controlId); } } ForEachItemIn(c, dependentchildGraphs) { CGraphBase &childGraph = dependentchildGraphs.item(c); CGraphElementBase &targetActivity = targetActivities.item(c); CGraphElementBase &sourceActivity = sourceActivities.item(c); if (!childGraph.isGlobal()) { CICopyArrayOf<CGraphDependency> globalChildGraphDeps; getGlobalDeps(childGraph, globalChildGraphDeps); ForEachItemIn(gcd, globalChildGraphDeps) { CGraphDependency &globalDep = globalChildGraphDeps.item(gcd); noteDependency(&targetActivity, &sourceActivity, globalDep.graph, &childGraph, globalDep.controlId); } } } SuperHashIteratorOf<CGraphBase> allIter(graphs); ForEach(allIter) { CGraphBase &subGraph = allIter.query(); if (subGraph.queryOwner() && subGraph.queryParentActivityId()) { CGraphElementBase *parentElement = subGraph.queryOwner()->queryElement(subGraph.queryParentActivityId()); if (isLoopActivity(*parentElement)) { if (!parentElement->queryOwner().isLocalChild() && !subGraph.isLocalOnly()) subGraph.setGlobal(true); } } } } void traceMemUsage() { StringBuffer memStatsStr; roxiemem::memstats(memStatsStr); PROGLOG("Roxiemem stats: %s", memStatsStr.str()); memsize_t heapUsage = getMapInfo("heap"); if (heapUsage) // if 0, assumed to be unavailable { memsize_t rmtotal = roxiemem::getTotalMemoryLimit(); PROGLOG("Heap usage (excluding Roxiemem) : %" I64F "d bytes", (unsigned __int64)(heapUsage-rmtotal)); } } ///// CGraphBase::CGraphBase(CJobChannel &_jobChannel) : jobChannel(_jobChannel), job(_jobChannel.queryJob()), progressUpdated(false) { xgmml = NULL; parent = owner = graphResultsContainer = NULL; complete = false; parentActivityId = 0; connected = started = graphDone = aborted = false; startBarrier = waitBarrier = doneBarrier = NULL; mpTag = waitBarrierTag = startBarrierTag = doneBarrierTag = TAG_NULL; executeReplyTag = TAG_NULL; parentExtractSz = 0; counter = 0; // loop/graph counter, will be set by loop/graph activity if needed loopBodySubgraph = false; } CGraphBase::~CGraphBase() { clean(); } CGraphBase *CGraphBase::cloneGraph() { Owned<CGraphBase> subGraph = queryJobChannel().createGraph(); CGraphTableCopy newGraphs; subGraph->createFromXGMML(node, owner, parent, graphResultsContainer, newGraphs); addDependencies(queryJob().queryXGMML(), false, newGraphs); return subGraph.getClear(); } void CGraphBase::init() { bool log = queryJob().queryForceLogging(queryGraphId(), (NULL == queryOwner()) || isGlobal()); setLogging(log); } void CGraphBase::clean() { ::Release(startBarrier); ::Release(waitBarrier); ::Release(doneBarrier); localResults.clear(); graphLoopResults.clear(); childGraphsTable.releaseAll(); disconnectActivities(); containers.releaseAll(); sinks.kill(); activeSinks.kill(); } void CGraphBase::serializeCreateContexts(MemoryBuffer &mb) { DelayedSizeMarker sizeMark(mb); Owned<IThorActivityIterator> iter = getIterator(); ForEach (*iter) { CGraphElementBase &element = iter->query(); if (element.isOnCreated()) { mb.append(element.queryId()); element.serializeCreateContext(mb); } } mb.append((activity_id)0); sizeMark.write(); } void CGraphBase::deserializeCreateContexts(MemoryBuffer &mb) { activity_id id; for (;;) { mb.read(id); if (0 == id) break; CGraphElementBase *element = queryElement(id); assertex(element); element->deserializeCreateContext(mb); } } void CGraphBase::reset() { setCompleteEx(false); clearProgressUpdated(); graphCancelHandler.reset(); if (0 == containers.count()) { Owned<IThorGraphIterator> iter = getChildGraphIterator(); ForEach(*iter) iter->query().reset(); } else { Owned<IThorActivityIterator> iter = getIterator(); ForEach(*iter) { CGraphElementBase &element = iter->query(); element.reset(); } dependentSubGraphs.kill(); } if (!queryOwner()) clearNodeStats(); } void CGraphBase::addChildGraph(CGraphStub *stub) { CriticalBlock b(crit); childGraphsTable.replace(*LINK(stub)); if (sequential) orderedChildGraphs.append(*stub); } IThorGraphStubIterator *CGraphBase::getChildStubIterator() const { CriticalBlock b(crit); class CIter : private SuperHashIteratorOf<CGraphStub>, public CSimpleInterfaceOf<IThorGraphStubIterator> { typedef SuperHashIteratorOf<CGraphStub> PARENT; public: CIter(const CChildGraphTable &table) : PARENT(table) { } // IIterator virtual bool first() { return PARENT::first(); } virtual bool next() { return PARENT::next(); } virtual bool isValid() { return PARENT::isValid(); } virtual CGraphStub &query() { return PARENT::query(); } }; return new CIter(childGraphsTable); } IThorGraphIterator *CGraphBase::getChildGraphIterator() const { CriticalBlock b(crit); class CIter : public CSimpleInterfaceOf<IThorGraphIterator> { Owned<IThorGraphStubIterator> iter; public: CIter(IThorGraphStubIterator *_iter) : iter(_iter) { } // IIterator virtual bool first() { return iter->first(); } virtual bool next() { return iter->next(); } virtual bool isValid() { return iter->isValid(); } virtual CGraphBase &query() { CGraphStub &stub = iter->query(); return stub.queryOriginalGraph(); } }; return new CIter(getChildStubIterator()); } bool CGraphBase::fireException(IException *e) { return queryJobChannel().fireException(e); } bool CGraphBase::preStart(size32_t parentExtractSz, const byte *parentExtract) { Owned<IThorActivityIterator> iter = getConnectedIterator(); ForEach(*iter) { CGraphElementBase &element = iter->query(); element.preStart(parentExtractSz, parentExtract); } return true; } void CGraphBase::executeSubGraph(size32_t parentExtractSz, const byte *parentExtract) { CriticalBlock b(executeCrit); if (job.queryPausing()) return; Owned<IException> exception; try { if (!queryOwner()) { StringBuffer s; toXML(&queryXGMML(), s, 2); GraphPrintLog("Running graph [%s] : %s", isGlobal()?"global":"local", s.str()); } if (localResults) localResults->clear(); doExecute(parentExtractSz, parentExtract, false); } catch (IException *e) { GraphPrintLog(e); exception.setown(e); } if (!queryOwner()) { GraphPrintLog("Graph Done"); StringBuffer memStr; getSystemTraceInfo(memStr, PerfMonStandard | PerfMonExtended); GraphPrintLog("%s", memStr.str()); } if (exception) throw exception.getClear(); } void CGraphBase::onCreate() { Owned<IThorActivityIterator> iter = getConnectedIterator(); ForEach(*iter) { CGraphElementBase &element = iter->query(); element.onCreate(); } } void CGraphBase::execute(size32_t _parentExtractSz, const byte *parentExtract, bool checkDependencies, bool async) { if (isComplete()) return; if (async) queryJobChannel().startGraph(*this, checkDependencies, _parentExtractSz, parentExtract); // may block if enough running else { if (!prepare(_parentExtractSz, parentExtract, checkDependencies, false, false)) { setComplete(); return; } executeSubGraph(_parentExtractSz, parentExtract); } } void CGraphBase::doExecute(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies) { if (isComplete()) return; if (queryAborted()) { if (abortException) throw abortException.getLink(); throw MakeGraphException(this, 0, "subgraph aborted"); } GraphPrintLog("Processing graph"); Owned<IException> exception; try { if (started) reset(); else started = true; ++numExecuted; Owned<IThorActivityIterator> iter = getConnectedIterator(); ForEach(*iter) { CGraphElementBase &element = iter->query(); element.onStart(parentExtractSz, parentExtract); element.initActivity(); } initialized = true; if (!preStart(parentExtractSz, parentExtract)) return; start(); if (!wait(aborted?MEDIUMTIMEOUT:INFINITE)) // can't wait indefinitely, query may have aborted and stall, but prudent to wait a short time for underlying graphs to unwind. GraphPrintLogEx(this, thorlog_null, MCuserWarning, "Graph wait cancelled, aborted=%s", aborted?"true":"false"); else graphDone = true; } catch (IException *e) { GraphPrintLog(e); exception.setown(e); } try { if (!exception && abortException) exception.setown(abortException.getClear()); if (exception) { if (NULL == owner || isGlobal()) waitBarrier->cancel(exception); if (!queryOwner()) { StringBuffer str; Owned<IThorException> e = MakeGraphException(this, exception->errorCode(), "%s", exception->errorMessage(str).str()); e->setAction(tea_abort); fireException(e); } } } catch (IException *e) { GraphPrintLog(e, "during abort()"); e->Release(); } try { done(); if (doneBarrier) doneBarrier->wait(false); } catch (IException *e) { GraphPrintLog(e); if (!exception.get()) exception.setown(e); else e->Release(); } end(); if (exception) throw exception.getClear(); if (!queryAborted()) setComplete(); } bool CGraphBase::prepare(size32_t parentExtractSz, const byte *parentExtract, bool checkDependencies, bool shortCircuit, bool async) { if (isComplete()) return false; bool needToExecute = false; ForEachItemIn(s, sinks) { CGraphElementBase &sink = sinks.item(s); if (sink.prepareContext(parentExtractSz, parentExtract, checkDependencies, shortCircuit, async, false)) needToExecute = true; } onCreate(); return needToExecute; } void CGraphBase::done() { if (aborted) return; // activity done methods only called on success Owned<IThorActivityIterator> iter = getConnectedIterator(); ForEach (*iter) { CGraphElementBase &element = iter->query(); element.queryActivity()->done(); } } unsigned CGraphBase::queryJobChannelNumber() const { return queryJobChannel().queryChannel(); } IMPServer &CGraphBase::queryMPServer() const { return jobChannel.queryMPServer(); } bool CGraphBase::syncInitData() { if (loopBodySubgraph) { CGraphElementBase *parentElement = queryOwner() ? queryOwner()->queryElement(queryParentActivityId()) : nullptr; assertex(parentElement); return parentElement->queryLoopGraph()->queryGraph()->isGlobal(); } else return !isLocalChild(); } void CGraphBase::end() { // always called, any final action clear up Owned<IThorActivityIterator> iter = getIterator(); ForEach(*iter) { CGraphElementBase &element = iter->query(); try { if (element.queryActivity()) element.queryActivity()->kill(); } catch (IException *e) { Owned<IException> e2 = MakeActivityException(element.queryActivity(), e, "Error calling kill()"); GraphPrintLog(e2); e->Release(); } } } class CGraphTraverseIteratorBase : implements IThorActivityIterator, public CInterface { protected: CGraphBase &graph; Linked<CGraphElementBase> cur; CIArrayOf<CGraphElementBase> others; CGraphElementArrayCopy covered; CGraphElementBase *popNext() { if (!others.ordinality()) { cur.clear(); return NULL; } cur.setown(&others.popGet()); return cur; } void setNext(bool branchOnConditional) { if (branchOnConditional && ((unsigned)-1) != cur->whichBranch) { CIOConnection *io = cur->connectedInputs.queryItem(cur->whichBranch); if (io) cur.set(io->activity); else cur.clear(); } else { CIOConnectionArray &inputs = cur->connectedInputs; cur.clear(); unsigned n = inputs.ordinality(); bool first = true; for (unsigned i=0; i<n; i++) { CIOConnection *io = inputs.queryItem(i); if (io) { if (first) { first = false; cur.set(io->activity); } else others.append(*LINK(io->activity)); } } } if (!cur) { if (!popNext()) return; } // check haven't been here before for (;;) { if (cur->getOutputs() < 2) break; else if (NotFound == covered.find(*cur)) { if (!cur->alreadyUpdated) { covered.append(*cur); break; } } if (!popNext()) return; } } public: IMPLEMENT_IINTERFACE; CGraphTraverseIteratorBase(CGraphBase &_graph) : graph(_graph) { } virtual bool first() { covered.kill(); others.kill(); cur.clear(); Owned<IThorActivityIterator> sinkIter = graph.getSinkIterator(); if (!sinkIter->first()) return false; for (;;) { cur.set(& sinkIter->query()); if (!cur->alreadyUpdated) break; if (!sinkIter->next()) return false; } while (sinkIter->next()) others.append(sinkIter->get()); return true; } virtual bool isValid() { return NULL != cur.get(); } virtual CGraphElementBase & query() { return *cur; } CGraphElementBase & get() { return *LINK(cur); } }; class CGraphTraverseConnectedIterator : public CGraphTraverseIteratorBase { bool branchOnConditional; public: CGraphTraverseConnectedIterator(CGraphBase &graph, bool _branchOnConditional) : CGraphTraverseIteratorBase(graph), branchOnConditional(_branchOnConditional) { } virtual bool next() { setNext(branchOnConditional); return NULL!=cur.get(); } }; IThorActivityIterator *CGraphBase::getConnectedIterator(bool branchOnConditional) { return new CGraphTraverseConnectedIterator(*this, branchOnConditional); } bool CGraphBase::wait(unsigned timeout) { CTimeMon tm(timeout); unsigned remaining = timeout; class CWaitException { CGraphBase *graph; Owned<IException> exception; public: CWaitException(CGraphBase *_graph) : graph(_graph) { } IException *get() { return exception; } void set(IException *e) { if (!exception) exception.setown(e); else e->Release(); } void throwException() { if (exception) throw exception.getClear(); throw MakeGraphException(graph, 0, "Timed out waiting for graph to end"); } } waitException(this); Owned<IThorActivityIterator> iter = getConnectedIterator(); ForEach (*iter) { CGraphElementBase &element = iter->query(); CActivityBase *activity = element.queryActivity(); if (INFINITE != timeout && tm.timedout(&remaining)) waitException.throwException(); try { if (!activity->wait(remaining)) waitException.throwException(); } catch (IException *e) { waitException.set(e); // will discard if already set if (timeout == INFINITE) { unsigned e = tm.elapsed(); if (e >= MEDIUMTIMEOUT) waitException.throwException(); timeout = MEDIUMTIMEOUT-e; tm.reset(timeout); } } } if (waitException.get()) waitException.throwException(); // synchronize all slaves to end of graphs if (NULL == owner || isGlobal()) { if (INFINITE != timeout && tm.timedout(&remaining)) waitException.throwException(); if (!waitBarrier->wait(true, remaining)) return false; } return true; } void CGraphBase::abort(IException *e) { if (aborted) return; { CriticalBlock cb(crit); abortException.set(e); aborted = true; graphCancelHandler.cancel(0); if (0 == containers.count()) { Owned<IThorGraphStubIterator> iter = getChildStubIterator(); ForEach(*iter) { CGraphStub &graph = iter->query(); graph.abort(e); } } } if (started && !graphDone) { Owned<IThorActivityIterator> iter = getConnectedIterator(); ForEach (*iter) { iter->query().abort(e); // JCSMORE - could do in parallel, they can take some time to timeout } if (startBarrier) startBarrier->cancel(e); if (waitBarrier) waitBarrier->cancel(e); if (doneBarrier) doneBarrier->cancel(e); } } void CGraphBase::GraphPrintLog(const char *format, ...) { va_list args; va_start(args, format); ::GraphPrintLogArgs(this, thorlog_null, MCdebugProgress, format, args); va_end(args); } void CGraphBase::GraphPrintLog(IException *e, const char *format, ...) { va_list args; va_start(args, format); ::GraphPrintLogArgs(this, e, thorlog_null, MCdebugProgress, format, args); va_end(args); } void CGraphBase::GraphPrintLog(IException *e) { GraphPrintLog(e, "%s", ""); } void CGraphBase::setLogging(bool tf) { Owned<IThorActivityIterator> iter = getIterator(); ForEach(*iter) iter->query().setLogging(tf); } void CGraphBase::createFromXGMML(IPropertyTree *_node, CGraphBase *_owner, CGraphBase *_parent, CGraphBase *resultsGraph, CGraphTableCopy &newGraphs) { class CChildParallelFactory : public CGraphStub { Linked<CGraphBase> originalChildGraph; CriticalSection crit; CIArrayOf<CGraphBase> stack; CIArrayOf<CGraphBase> active; bool originalAvailable = true; CGraphBase *getGraph() { Owned<CGraphBase> childGraph; { CriticalBlock b(crit); if (originalAvailable) { originalAvailable = false; active.append(*originalChildGraph.getLink()); return originalChildGraph.getLink(); } if (stack.length()) childGraph.setown(&stack.popGet()); } if (!childGraph) childGraph.setown(originalChildGraph->cloneGraph()); if (originalChildGraph->queryAborted()) throw MakeGraphException(originalChildGraph, 0, "Job aborted"); { CriticalBlock b(crit); active.append(*childGraph.getLink()); } return childGraph.getClear(); } void pushGraph(CGraphBase *childGraph) { CriticalBlock b(crit); verifyex(active.zap(*childGraph)); if (childGraph == originalChildGraph) originalAvailable = true; else stack.append(*LINK(childGraph)); } public: CChildParallelFactory(CGraphBase *_originalChildGraph) : originalChildGraph(_originalChildGraph) { graphId = originalChildGraph->queryGraphId(); } virtual CGraphBase &queryOriginalGraph() override { return *originalChildGraph; } virtual void abort(IException *e) override { for (;;) { Owned<CGraphBase> activeChildGraph; { CriticalBlock b(crit); activeChildGraph.setown(&active.popGet()); if (!activeChildGraph) break; } activeChildGraph->abort(e); } } virtual bool serializeStats(MemoryBuffer &mb) override { // JCSMORE - need to merge other instances return originalChildGraph->serializeStats(mb); } virtual IEclGraphResults * evaluate(unsigned parentExtractSz, const byte * parentExtract) override { Owned<CGraphBase> childGraph = getGraph(); Owned<IEclGraphResults> results = childGraph->evaluate(parentExtractSz, parentExtract); pushGraph(childGraph); return results.getClear(); } }; owner = _owner; parent = _parent?_parent:owner; node.setown(createPTreeFromIPT(_node)); xgmml = node->queryPropTree("att/graph"); sink = xgmml->getPropBool("att[@name=\"rootGraph\"]/@value", false); sequential = xgmml->getPropBool("@sequential"); graphId = node->getPropInt("@id"); global = false; localOnly = -1; // unset parentActivityId = node->getPropInt("att[@name=\"_parentActivity\"]/@value", 0); graphResultsContainer = resultsGraph; CGraphBase *graphContainer = this; if (resultsGraph) graphContainer = resultsGraph; // JCSMORE is this right? graphCodeContext.setContext(this, graphContainer, (ICodeContextExt *)&jobChannel.queryCodeContext()); unsigned numResults = xgmml->getPropInt("att[@name=\"_numResults\"]/@value", 0); if (numResults) { localResults.setown(createThorGraphResults(numResults)); resultsGraph = this; // JCSMORE - it might more sense if this temp handler was owned by parent act., which may finish(get stopped) earlier than the owning graph tmpHandler.setown(queryJob().createTempHandler(false)); } localChild = false; if (owner && parentActivityId) { CGraphElementBase *parentElement = owner->queryElement(parentActivityId); if (isLoopActivity(*parentElement)) { localChild = parentElement->queryOwner().isLocalChild(); unsigned loopId = parentElement->queryXGMML().getPropInt("att[@name=\"_loopid\"]/@value"); if ((graphId == loopId) || (owner->queryGraphId() == loopId)) loopBodySubgraph = true; else localChild = true; } else localChild = true; } Owned<IPropertyTreeIterator> nodes = xgmml->getElements("node"); ForEach(*nodes) { IPropertyTree &e = nodes->query(); ThorActivityKind kind = (ThorActivityKind) e.getPropInt("att[@name=\"_kind\"]/@value"); if (TAKsubgraph == kind) { Owned<CGraphBase> subGraph = queryJobChannel().createGraph(); subGraph->createFromXGMML(&e, this, parent, resultsGraph, newGraphs); activity_id subGraphParentActivityId = e.getPropInt("att[@name=\"_parentActivity\"]/@value", 0); if (subGraphParentActivityId) // JCS - not sure if ever false { Owned<CGraphStub> stub = new CChildParallelFactory(subGraph); addChildGraph(stub); } else addChildGraph(subGraph); if (!global) global = subGraph->isGlobal(); newGraphs.replace(*subGraph); } else { if (localChild && !e.getPropBool("att[@name=\"coLocal\"]/@value", false)) { IPropertyTree *att = createPTree("att"); att->setProp("@name", "coLocal"); att->setPropBool("@value", true); e.addPropTree("att", att); } CGraphElementBase *act = createGraphElement(e, *this, resultsGraph); addActivity(act); if (!global) global = isGlobalActivity(*act); } } Owned<IPropertyTreeIterator> edges = xgmml->getElements("edge"); ForEach(*edges) { IPropertyTree &edge = edges->query(); //Ignore edges that represent dependencies from parent activities to child activities. if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) continue; unsigned sourceOutput = edge.getPropInt("att[@name=\"_sourceIndex\"]/@value", 0); unsigned targetInput = edge.getPropInt("att[@name=\"_targetIndex\"]/@value", 0); CGraphElementBase *source = queryElement(edge.getPropInt("@source")); CGraphElementBase *target = queryElement(edge.getPropInt("@target")); target->addInput(targetInput, source, sourceOutput); } Owned<IThorActivityIterator> iter = getIterator(); ForEach(*iter) { CGraphElementBase &element = iter->query(); if (0 == element.getOutputs()) { /* JCSMORE - Making some outputs conditional, will require: * a) Pass through information as to which dependent graph causes this graph (and this sink) to execute) * b) Allow the subgraph to re-executed by other dependent subgraphs and avoid re-executing completed sinks * c) Keep common points (splitters) around (preferably in memory), re-execution of graph will need them */ sinks.append(*LINK(&element)); } } init(); } void CGraphBase::executeChildGraphs(size32_t parentExtractSz, const byte *parentExtract) { if (sequential) { // JCSMORE - would need to re-think how this is done if these sibling child queries could be executed in parallel ForEachItemIn(o, orderedChildGraphs) { CGraphBase &graph = orderedChildGraphs.item(o).queryOriginalGraph(); if (graph.isSink()) graph.execute(parentExtractSz, parentExtract, true, false); } } else { Owned<IThorGraphIterator> iter = getChildGraphIterator(); ForEach(*iter) { CGraphBase &graph = iter->query(); if (graph.isSink()) graph.execute(parentExtractSz, parentExtract, true, false); } } } void CGraphBase::doExecuteChild(size32_t parentExtractSz, const byte *parentExtract) { reset(); if (0 == containers.count()) executeChildGraphs(parentExtractSz, parentExtract); else execute(parentExtractSz, parentExtract, false, false); queryTempHandler()->clearTemps(); } void CGraphBase::executeChild(size32_t & retSize, void * &ret, size32_t parentExtractSz, const byte *parentExtract) { reset(); doExecute(parentExtractSz, parentExtract, false); UNIMPLEMENTED; /* ForEachItemIn(idx1, elements) { EclGraphElement & cur = elements.item(idx1); if (cur.isResult) { cur.extractResult(retSize, ret); return; } } */ throwUnexpected(); } void CGraphBase::setResults(IThorGraphResults *results) // used by master only { localResults.set(results); } void CGraphBase::executeChild(size32_t parentExtractSz, const byte *parentExtract, IThorGraphResults *results, IThorGraphResults *_graphLoopResults) { localResults.set(results); graphLoopResults.set(_graphLoopResults); doExecuteChild(parentExtractSz, parentExtract); graphLoopResults.clear(); localResults.clear(); } StringBuffer &getGlobals(CGraphBase &graph, StringBuffer &str) { bool first = true; Owned<IThorActivityIterator> iter = graph.getIterator(); ForEach(*iter) { CGraphElementBase &e = iter->query(); if (isGlobalActivity(e)) { if (first) str.append("Graph(").append(graph.queryGraphId()).append("): ["); else str.append(", "); first = false; ThorActivityKind kind = e.getKind(); str.append(activityKindStr(kind)); str.append("(").append(e.queryId()).append(")"); } } if (!first) str.append("]"); Owned<IThorGraphIterator> childIter = graph.getChildGraphIterator(); ForEach(*childIter) { CGraphBase &childGraph = childIter->query(); getGlobals(childGraph, str); } return str; } void CGraphBase::executeChild(size32_t parentExtractSz, const byte *parentExtract) { assertex(localResults); localResults->clear(); if (isGlobal()) // any slave { StringBuffer str("Global acts = "); getGlobals(*this, str); throw MakeGraphException(this, 0, "Global child graph? : %s", str.str()); } doExecuteChild(parentExtractSz, parentExtract); } IThorResult *CGraphBase::getResult(unsigned id, bool distributed) { return localResults->getResult(id, distributed); } IThorResult *CGraphBase::getGraphLoopResult(unsigned id, bool distributed) { return graphLoopResults->getResult(id, distributed); } IThorResult *CGraphBase::createResult(CActivityBase &activity, unsigned id, IThorGraphResults *results, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority) { return results->createResult(activity, id, rowIf, resultType, spillPriority); } IThorResult *CGraphBase::createResult(CActivityBase &activity, unsigned id, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority) { return localResults->createResult(activity, id, rowIf, resultType, spillPriority); } IThorResult *CGraphBase::createGraphLoopResult(CActivityBase &activity, IThorRowInterfaces *rowIf, ThorGraphResultType resultType, unsigned spillPriority) { return graphLoopResults->createResult(activity, rowIf, resultType, spillPriority); } // IEclGraphResults void CGraphBase::getDictionaryResult(unsigned & count, const byte * * & ret, unsigned id) { Owned<IThorResult> result = getResult(id, true); // will get collated distributed result result->getLinkedResult(count, ret); } void CGraphBase::getLinkedResult(unsigned & count, const byte * * & ret, unsigned id) { Owned<IThorResult> result = getResult(id, true); // will get collated distributed result result->getLinkedResult(count, ret); } const void * CGraphBase::getLinkedRowResult(unsigned id) { Owned<IThorResult> result = getResult(id, true); // will get collated distributed result return result->getLinkedRowResult(); } // IThorChildGraph impl. IEclGraphResults *CGraphBase::evaluate(unsigned _parentExtractSz, const byte *parentExtract) { CriticalBlock block(evaluateCrit); localResults.setown(createThorGraphResults(xgmml->getPropInt("att[@name=\"_numResults\"]/@value", 0))); parentExtractSz = _parentExtractSz; executeChild(parentExtractSz, parentExtract); return localResults.getClear(); } static bool isLocalOnly(const CGraphElementBase &activity); static bool isLocalOnly(const CGraphBase &graph) // checks all dependencies, if something needs to be global, whole body is forced to be execution sync. { if (0 == graph.activityCount()) { Owned<IThorGraphIterator> iter = graph.getChildGraphIterator(); ForEach(*iter) { CGraphBase &childGraph = iter->query(); if (childGraph.isSink()) { if (!isLocalOnly(childGraph)) return false; } } } else { if (graph.isGlobal()) return false; Owned<IThorActivityIterator> sinkIter = graph.getAllSinkIterator(); ForEach(*sinkIter) { CGraphElementBase &sink = sinkIter->query(); if (!isLocalOnly(sink)) return false; } } return true; } static bool isLocalOnly(const CGraphElementBase &activity) { Owned<IThorGraphDependencyIterator> deps = activity.getDependsIterator(); ForEach(*deps) { if (!isLocalOnly(*(deps->query().graph))) return false; } StringBuffer match("edge[@target=\""); match.append(activity.queryId()).append("\"]"); Owned<IPropertyTreeIterator> inputs = activity.queryOwner().queryXGMML().getElements(match.str()); ForEach(*inputs) { IPropertyTree &edge = inputs->query(); //Ignore edges that represent dependencies from parent activities to child activities. if (edge.getPropBool("att[@name=\"_childGraph\"]/@value", false)) continue; CGraphElementBase *sourceAct = activity.queryOwner().queryElement(edge.getPropInt("@source")); if (!isLocalOnly(*sourceAct)) return false; } return true; } bool CGraphBase::isLocalOnly() const // checks all dependencies, if something needs to be global, whole body is forced to be execution sync. { if (-1 == localOnly) localOnly = (int)::isLocalOnly(*this); return 1==localOnly; } IThorGraphResults *CGraphBase::createThorGraphResults(unsigned num) { return new CThorGraphResults(num); } //// void CGraphTempHandler::registerFile(const char *name, graph_id graphId, unsigned usageCount, bool temp, WUFileKind fileKind, StringArray *clusters) { assertex(temp); LOG(MCdebugProgress, thorJob, "registerTmpFile name=%s, usageCount=%d", name, usageCount); CriticalBlock b(crit); if (tmpFiles.find(name)) throw MakeThorException(TE_FileAlreadyUsedAsTempFile, "File already used as temp file (%s)", name); tmpFiles.replace(* new CFileUsageEntry(name, graphId, fileKind, usageCount)); } void CGraphTempHandler::deregisterFile(const char *name, bool kept) { LOG(MCdebugProgress, thorJob, "deregisterTmpFile name=%s", name); CriticalBlock b(crit); CFileUsageEntry *fileUsage = tmpFiles.find(name); if (!fileUsage) { if (errorOnMissing) throw MakeThorException(TE_FileNotFound, "File not found (%s) deregistering tmp file", name); return; } if (0 == fileUsage->queryUsage()) // marked 'not to be deleted' until workunit complete. return; else if (1 == fileUsage->queryUsage()) { tmpFiles.remove(name); try { if (!removeTemp(name)) LOG(MCwarning, unknownJob, "Failed to delete tmp file : %s (not found)", name); } catch (IException *e) { StringBuffer s("Failed to delete tmp file : "); FLLOG(MCwarning, thorJob, e, s.append(name).str()); } } else fileUsage->decUsage(); } void CGraphTempHandler::clearTemps() { CriticalBlock b(crit); Owned<IFileUsageIterator> iter = getIterator(); ForEach(*iter) { CFileUsageEntry &entry = iter->query(); const char *tmpname = entry.queryName(); try { if (!removeTemp(tmpname)) LOG(MCwarning, thorJob, "Failed to delete tmp file : %s (not found)", tmpname); } catch (IException *e) { StringBuffer s("Failed to delete tmp file : "); FLLOG(MCwarning, thorJob, e, s.append(tmpname).str()); } } iter.clear(); tmpFiles.kill(); } ///// class CGraphExecutor; class CGraphExecutorGraphInfo : public CInterface { public: CGraphExecutorGraphInfo(CGraphExecutor &_executor, CGraphBase *_subGraph, IGraphCallback &_callback, const byte *parentExtract, size32_t parentExtractSz) : executor(_executor), subGraph(_subGraph), callback(_callback) { parentExtractMb.append(parentExtractSz, parentExtract); } CGraphExecutor &executor; IGraphCallback &callback; Linked<CGraphBase> subGraph; MemoryBuffer parentExtractMb; }; class CGraphExecutor : implements IGraphExecutor, public CInterface { CJobChannel &jobChannel; CJobBase &job; CIArrayOf<CGraphExecutorGraphInfo> stack, running, toRun; UnsignedArray seen; bool stopped; unsigned limit; unsigned waitOnRunning; CriticalSection crit; Semaphore runningSem; Owned<IThreadPool> graphPool; class CGraphExecutorFactory : implements IThreadFactory, public CInterface { CGraphExecutor &executor; public: IMPLEMENT_IINTERFACE; CGraphExecutorFactory(CGraphExecutor &_executor) : executor(_executor) { } // IThreadFactory virtual IPooledThread *createNew() { class CGraphExecutorThread : implements IPooledThread, public CInterface { Owned<CGraphExecutorGraphInfo> graphInfo; public: IMPLEMENT_IINTERFACE; CGraphExecutorThread() { } virtual void init(void *startInfo) override { graphInfo.setown((CGraphExecutorGraphInfo *)startInfo); } virtual void threadmain() override { for (;;) { Linked<CGraphBase> graph = graphInfo->subGraph; Owned<IException> e; try { PROGLOG("CGraphExecutor: Running graph, graphId=%" GIDPF "d", graph->queryGraphId()); graphInfo->callback.runSubgraph(*graph, graphInfo->parentExtractMb.length(), (const byte *)graphInfo->parentExtractMb.toByteArray()); } catch (IException *_e) { e.setown(_e); } Owned<CGraphExecutorGraphInfo> nextGraphInfo; try { nextGraphInfo.setown(graphInfo->executor.graphDone(*graphInfo, e)); } catch (IException *e) { GraphPrintLog(graph, e, "graphDone"); e->Release(); } graphInfo.clear(); // NB: at this point the graph will be destroyed if (e) throw e.getClear(); if (!nextGraphInfo) return; graphInfo.setown(nextGraphInfo.getClear()); } } virtual bool canReuse() const override { return true; } virtual bool stop() override { return true; } }; return new CGraphExecutorThread(); } } *factory; CGraphExecutorGraphInfo *findRunning(graph_id gid) { ForEachItemIn(r, running) { CGraphExecutorGraphInfo *graphInfo = &running.item(r); if (gid == graphInfo->subGraph->queryGraphId()) return graphInfo; } return NULL; } public: IMPLEMENT_IINTERFACE; CGraphExecutor(CJobChannel &_jobChannel) : jobChannel(_jobChannel), job(_jobChannel.queryJob()) { limit = (unsigned)job.getWorkUnitValueInt("concurrentSubGraphs", globals->getPropInt("@concurrentSubGraphs", 1)); PROGLOG("CGraphExecutor: limit = %d", limit); waitOnRunning = 0; stopped = false; factory = new CGraphExecutorFactory(*this); graphPool.setown(createThreadPool("CGraphExecutor pool", factory, &jobChannel, limit)); } ~CGraphExecutor() { stopped = true; graphPool->joinAll(); factory->Release(); } CGraphExecutorGraphInfo *graphDone(CGraphExecutorGraphInfo &doneGraphInfo, IException *e) { CriticalBlock b(crit); running.zap(doneGraphInfo); if (waitOnRunning) { runningSem.signal(waitOnRunning); waitOnRunning = 0; } if (e || job.queryAborted()) { stopped = true; stack.kill(); return NULL; } if (job.queryPausing()) stack.kill(); else if (stack.ordinality()) { CICopyArrayOf<CGraphExecutorGraphInfo> toMove; ForEachItemIn(s, stack) { bool dependenciesDone = true; CGraphExecutorGraphInfo &graphInfo = stack.item(s); ForEachItemIn (d, graphInfo.subGraph->dependentSubGraphs) { CGraphBase &subGraph = graphInfo.subGraph->dependentSubGraphs.item(d); if (!subGraph.isComplete()) { dependenciesDone = false; break; } } if (dependenciesDone) { graphInfo.subGraph->dependentSubGraphs.kill(); graphInfo.subGraph->prepare(graphInfo.parentExtractMb.length(), (const byte *)graphInfo.parentExtractMb.toByteArray(), true, true, true); // now existing deps done, maybe more to prepare ForEachItemIn (d, graphInfo.subGraph->dependentSubGraphs) { CGraphBase &subGraph = graphInfo.subGraph->dependentSubGraphs.item(d); if (!subGraph.isComplete()) { dependenciesDone = false; break; } } if (dependenciesDone) { graphInfo.subGraph->dependentSubGraphs.kill(); // none to track anymore toMove.append(graphInfo); } } } ForEachItemIn(m, toMove) { Linked<CGraphExecutorGraphInfo> graphInfo = &toMove.item(m); stack.zap(*graphInfo); toRun.add(*graphInfo.getClear(), 0); } } job.markWuDirty(); PROGLOG("CGraphExecutor running=%d, waitingToRun=%d, dependentsWaiting=%d", running.ordinality(), toRun.ordinality(), stack.ordinality()); while (toRun.ordinality()) { if (job.queryPausing()) return NULL; Linked<CGraphExecutorGraphInfo> nextGraphInfo = &toRun.item(0); toRun.remove(0); if (!nextGraphInfo->subGraph->isComplete() && (NULL == findRunning(nextGraphInfo->subGraph->queryGraphId()))) { running.append(*nextGraphInfo.getLink()); return nextGraphInfo.getClear(); } } return NULL; } // IGraphExecutor virtual void add(CGraphBase *subGraph, IGraphCallback &callback, bool checkDependencies, size32_t parentExtractSz, const byte *parentExtract) { bool alreadyRunning; { CriticalBlock b(crit); if (job.queryPausing()) return; if (subGraph->isComplete()) return; alreadyRunning = NULL != findRunning(subGraph->queryGraphId()); if (alreadyRunning) ++waitOnRunning; } if (alreadyRunning) { for (;;) { PROGLOG("Waiting on subgraph %" GIDPF "d", subGraph->queryGraphId()); if (runningSem.wait(MEDIUMTIMEOUT) || job.queryAborted() || job.queryPausing()) break; } return; } else { CriticalBlock b(crit); if (seen.contains(subGraph->queryGraphId())) return; // already queued; seen.append(subGraph->queryGraphId()); } if (!subGraph->prepare(parentExtractSz, parentExtract, checkDependencies, true, true)) { subGraph->setComplete(); return; } if (subGraph->dependentSubGraphs.ordinality()) { bool dependenciesDone = true; ForEachItemIn (d, subGraph->dependentSubGraphs) { CGraphBase &graph = subGraph->dependentSubGraphs.item(d); if (!graph.isComplete()) { dependenciesDone = false; break; } } if (dependenciesDone) subGraph->dependentSubGraphs.kill(); // none to track anymore } Owned<CGraphExecutorGraphInfo> graphInfo = new CGraphExecutorGraphInfo(*this, subGraph, callback, parentExtract, parentExtractSz); CriticalBlock b(crit); if (0 == subGraph->dependentSubGraphs.ordinality()) { if (running.ordinality()<limit) { running.append(*LINK(graphInfo)); PROGLOG("Add: Launching graph thread for graphId=%" GIDPF "d", subGraph->queryGraphId()); graphPool->start(graphInfo.getClear()); } else stack.add(*graphInfo.getClear(), 0); // push to front, no dependency, free to run next. } else stack.append(*graphInfo.getClear()); // as dependencies finish, may move up the list } virtual IThreadPool &queryGraphPool() { return *graphPool; } virtual void wait() { PROGLOG("CGraphExecutor exiting, waiting on graph pool"); graphPool->joinAll(); PROGLOG("CGraphExecutor graphPool finished"); } }; //// // IContextLogger class CThorContextLogger : implements IContextLogger, public CSimpleInterface { CJobBase &job; unsigned traceLevel; StringAttr globalIdHeader; StringAttr callerIdHeader; StringAttr globalId; StringBuffer localId; public: IMPLEMENT_IINTERFACE_USING(CSimpleInterface); CThorContextLogger(CJobBase &_job) : job(_job) { traceLevel = 1; if (globals->hasProp("@httpGlobalIdHeader")) setHttpIdHeaders(globals->queryProp("@httpGlobalIdHeader"), globals->queryProp("@httpCallerIdHeader")); } virtual void CTXLOGva(const char *format, va_list args) const __attribute__((format(printf,2,0))) { StringBuffer ss; ss.valist_appendf(format, args); LOG(MCdebugProgress, thorJob, "%s", ss.str()); } virtual void logOperatorExceptionVA(IException *E, const char *file, unsigned line, const char *format, va_list args) const __attribute__((format(printf,5,0))) { StringBuffer ss; ss.append("ERROR"); if (E) ss.append(": ").append(E->errorCode()); if (file) ss.appendf(": %s(%d) ", file, line); if (E) E->errorMessage(ss.append(": ")); if (format) ss.append(": ").valist_appendf(format, args); LOG(MCoperatorProgress, thorJob, "%s", ss.str()); } virtual void noteStatistic(StatisticKind kind, unsigned __int64 value) const { } virtual void mergeStats(const CRuntimeStatisticCollection &from) const { } virtual unsigned queryTraceLevel() const { return traceLevel; } virtual void setGlobalId(const char *id, SocketEndpoint &ep, unsigned pid) { globalId.set(id); appendLocalId(localId.clear(), ep, pid); } virtual const char *queryGlobalId() const { return globalId.get(); } virtual const char *queryLocalId() const { return localId.str(); } virtual void setHttpIdHeaders(const char *global, const char *caller) { if (global && *global) globalIdHeader.set(global); if (caller && *caller) callerIdHeader.set(caller); } virtual const char *queryGlobalIdHttpHeader() const { return globalIdHeader.str(); } virtual const char *queryCallerIdHttpHeader() const { return callerIdHeader.str(); } }; //// CJobBase::CJobBase(ILoadedDllEntry *_querySo, const char *_graphName) : querySo(_querySo), graphName(_graphName) { maxDiskUsage = diskUsage = 0; dirty = true; aborted = false; globalMemoryMB = globals->getPropInt("@globalMemorySize"); // in MB channelsPerSlave = globals->getPropInt("@channelsPerSlave", 1); numChannels = channelsPerSlave; pluginMap = new SafePluginMap(&pluginCtx, true); // JCSMORE - Will pass down at job creation time... jobGroup.set(&::queryClusterGroup()); slaveGroup.setown(jobGroup->remove(0)); nodeGroup.set(&queryNodeGroup()); myNodeRank = nodeGroup->rank(::queryMyNode()); unsigned channelsPerSlave = globals->getPropInt("@channelsPerSlave", 1); jobChannelSlaveNumbers.allocateN(channelsPerSlave, true); // filled when channels are added. jobSlaveChannelNum.allocateN(querySlaves()); // filled when channels are added. for (unsigned s=0; s<querySlaves(); s++) jobSlaveChannelNum[s] = NotFound; StringBuffer wuXML; if (!getEmbeddedWorkUnitXML(querySo, wuXML)) throw MakeStringException(0, "Failed to locate workunit info in query : %s", querySo->queryName()); Owned<ILocalWorkUnit> localWU = createLocalWorkUnit(wuXML); Owned<IConstWUGraph> graph = localWU->getGraph(graphName); graphXGMML.setown(graph->getXGMMLTree(false)); if (!graphXGMML) throwUnexpected(); } void CJobBase::init() { StringBuffer tmp; tmp.append(wuid); tmp.append(graphName); key.set(tmp.str()); StringBuffer user; extractFromWorkunitDAToken(token.str(), nullptr, &user, nullptr); userDesc = createUserDescriptor(); userDesc->set(user.str(), token.str());//use workunit token as password forceLogGraphIdMin = (graph_id)getWorkUnitValueInt("forceLogGraphIdMin", 0); forceLogGraphIdMax = (graph_id)getWorkUnitValueInt("forceLogGraphIdMax", 0); logctx.setown(new CThorContextLogger(*this)); // global setting default on, can be overridden by #option timeActivities = 0 != getWorkUnitValueInt("timeActivities", globals->getPropBool("@timeActivities", true)); maxActivityCores = (unsigned)getWorkUnitValueInt("maxActivityCores", 0); // NB: 0 means system decides if (0 == maxActivityCores) maxActivityCores = getAffinityCpus(); pausing = false; resumed = false; crcChecking = 0 != getWorkUnitValueInt("THOR_ROWCRC", globals->getPropBool("@THOR_ROWCRC", false)); usePackedAllocator = 0 != getWorkUnitValueInt("THOR_PACKEDALLOCATOR", globals->getPropBool("@THOR_PACKEDALLOCATOR", true)); memorySpillAtPercentage = (unsigned)getWorkUnitValueInt("memorySpillAt", globals->getPropInt("@memorySpillAt", 80)); sharedMemoryLimitPercentage = (unsigned)getWorkUnitValueInt("globalMemoryLimitPC", globals->getPropInt("@sharedMemoryLimit", 90)); sharedMemoryMB = globalMemoryMB*sharedMemoryLimitPercentage/100; failOnLeaks = getOptBool("failOnLeaks"); maxLfnBlockTimeMins = getOptInt(THOROPT_MAXLFN_BLOCKTIME_MINS, DEFAULT_MAXLFN_BLOCKTIME_MINS); PROGLOG("Global memory size = %d MB, shared memory = %d%%, memory spill at = %d%%", globalMemoryMB, sharedMemoryLimitPercentage, memorySpillAtPercentage); StringBuffer tracing("maxActivityCores = "); if (maxActivityCores) tracing.append(maxActivityCores); else tracing.append("[unbound]"); PROGLOG("%s", tracing.str()); } void CJobBase::beforeDispose() { endJob(); } CJobChannel &CJobBase::queryJobChannel(unsigned c) const { return jobChannels.item(c); } CActivityBase &CJobBase::queryChannelActivity(unsigned c, graph_id gid, activity_id id) const { CJobChannel &channel = queryJobChannel(c); Owned<CGraphBase> graph = channel.getGraph(gid); dbgassertex(graph); CGraphElementBase *container = graph->queryElement(id); dbgassertex(container); return *container->queryActivity(); } void CJobBase::startJob() { LOG(MCdebugProgress, thorJob, "New Graph started : %s", graphName.get()); ClearTempDirs(); perfmonhook.setown(createThorMemStatsPerfMonHook(*this, getOptInt(THOROPT_MAX_KERNLOG, 3))); setPerformanceMonitorHook(perfmonhook); PrintMemoryStatusLog(); logDiskSpace(); unsigned keyNodeCacheMB = (unsigned)getWorkUnitValueInt("keyNodeCacheMB", DEFAULT_KEYNODECACHEMB * queryJobChannels()); unsigned keyLeafCacheMB = (unsigned)getWorkUnitValueInt("keyLeafCacheMB", DEFAULT_KEYLEAFCACHEMB * queryJobChannels()); unsigned keyBlobCacheMB = (unsigned)getWorkUnitValueInt("keyBlobCacheMB", DEFAULT_KEYBLOBCACHEMB * queryJobChannels()); setNodeCacheMem(keyNodeCacheMB * 0x100000); setLeafCacheMem(keyLeafCacheMB * 0x100000); setBlobCacheMem(keyBlobCacheMB * 0x100000); PROGLOG("Key node caching setting: node=%u MB, leaf=%u MB, blob=%u MB", keyNodeCacheMB, keyLeafCacheMB, keyBlobCacheMB); unsigned keyFileCacheLimit = (unsigned)getWorkUnitValueInt("keyFileCacheLimit", 0); if (!keyFileCacheLimit) keyFileCacheLimit = (querySlaves()+1)*2; setKeyIndexCacheSize(keyFileCacheLimit); PROGLOG("Key file cache size set to: %d", keyFileCacheLimit); if (getOptBool("dumpStacks")) // mainly as an example of printAllStacks() usage { StringBuffer output; if (getAllStacks(output)) PrintLogDirect(output); else WARNLOG("Failed to capture process stacks: %s", output.str()); } } void CJobBase::endJob() { if (jobEnded) return; jobEnded = true; setPerformanceMonitorHook(nullptr); LOG(MCdebugProgress, thorJob, "Job ended : %s", graphName.get()); clearKeyStoreCache(true); PrintMemoryStatusLog(); Owned<IMultiException> exceptions; ForEachItemIn(c, jobChannels) { try { jobChannels.item(c).clean(); } catch (IException *e) { if (!exceptions) exceptions.setown(makeMultiException()); exceptions->append(*LINK(e)); } } try { jobChannels.kill(); // avoiding circular references. Kill before other CJobBase components are destroyed that channels reference. ::Release(userDesc); ::Release(pluginMap); traceMemUsage(); if (numChannels > 1) // if only 1 - then channel allocator is same as sharedAllocator, leaks will be reported by the single channel checkAndReportLeaks(sharedAllocator->queryRowManager()); } catch (IException *e) { if (!exceptions) exceptions.setown(makeMultiException()); exceptions->append(*LINK(e)); } if (exceptions && exceptions->ordinality()) throw exceptions.getClear(); } void CJobBase::checkAndReportLeaks(roxiemem::IRowManager *rowManager) { if (!failOnLeaks) // NB: leaks reported by row manager destructor anyway return; if (rowManager->allocated()) { rowManager->reportLeaks(); throw MakeThorException(TE_RowLeaksDetected, "Row leaks detected"); } } bool CJobBase::queryForceLogging(graph_id graphId, bool def) const { // JCSMORE, could add comma separated range, e.g. 1-5,10-12 if ((graphId >= forceLogGraphIdMin) && (graphId <= forceLogGraphIdMax)) return true; return def; } void CJobBase::addSubGraph(IPropertyTree &xgmml) { CriticalBlock b(crit); for (unsigned c=0; c<queryJobChannels(); c++) { CJobChannel &jobChannel = queryJobChannel(c); Owned<CGraphBase> subGraph = jobChannel.createGraph(); subGraph->createFromXGMML(&xgmml, NULL, NULL, NULL, jobChannel.queryAllGraphs()); jobChannel.addSubGraph(*subGraph.getClear()); } } void CJobBase::addDependencies(IPropertyTree *xgmml, bool failIfMissing) { for (unsigned c=0; c<queryJobChannels(); c++) { CJobChannel &jobChannel = queryJobChannel(c); jobChannel.addDependencies(xgmml, failIfMissing); } } bool CJobBase::queryUseCheckpoints() const { return globals->getPropBool("@checkPointRecovery") || 0 != getWorkUnitValueInt("checkPointRecovery", 0); } void CJobBase::abort(IException *e) { aborted = true; for (unsigned c=0; c<queryJobChannels(); c++) { CJobChannel &jobChannel = queryJobChannel(c); jobChannel.abort(e); } } void CJobBase::increase(offset_t usage, const char *key) { diskUsage += usage; if (diskUsage > maxDiskUsage) maxDiskUsage = diskUsage; } void CJobBase::decrease(offset_t usage, const char *key) { diskUsage -= usage; } // these getX methods for property in workunit settings, then global setting, defaulting to provided 'dft' if not present StringBuffer &CJobBase::getOpt(const char *opt, StringBuffer &out) { if (!opt || !*opt) return out; // probably error VStringBuffer gOpt("Debug/@%s", opt); getWorkUnitValue(opt, out); if (0 == out.length()) globals->getProp(gOpt, out); return out; } bool CJobBase::getOptBool(const char *opt, bool dft) { if (!opt || !*opt) return dft; // probably error VStringBuffer gOpt("Debug/@%s", opt); return getWorkUnitValueBool(opt, globals->getPropBool(gOpt, dft)); } int CJobBase::getOptInt(const char *opt, int dft) { if (!opt || !*opt) return dft; // probably error VStringBuffer gOpt("Debug/@%s", opt); return (int)getWorkUnitValueInt(opt, globals->getPropInt(gOpt, dft)); } __int64 CJobBase::getOptInt64(const char *opt, __int64 dft) { if (!opt || !*opt) return dft; // probably error VStringBuffer gOpt("Debug/@%s", opt); return getWorkUnitValueInt(opt, globals->getPropInt64(gOpt, dft)); } IThorAllocator *CJobBase::getThorAllocator(unsigned channel) { return sharedAllocator.getLink(); } /// CJobChannel CJobChannel::CJobChannel(CJobBase &_job, IMPServer *_mpServer, unsigned _channel) : job(_job), mpServer(_mpServer), channel(_channel) { aborted = false; thorAllocator.setown(job.getThorAllocator(channel)); jobComm.setown(mpServer->createCommunicator(&job.queryJobGroup())); myrank = job.queryJobGroup().rank(queryMyNode()); graphExecutor.setown(new CGraphExecutor(*this)); } CJobChannel::~CJobChannel() { if (!cleaned) clean(); } INode *CJobChannel::queryMyNode() { return mpServer->queryMyNode(); } void CJobChannel::wait() { if (graphExecutor) graphExecutor->wait(); } ICodeContext &CJobChannel::queryCodeContext() const { return *codeCtx; } ICodeContext &CJobChannel::querySharedMemCodeContext() const { return *sharedMemCodeCtx; } mptag_t CJobChannel::deserializeMPTag(MemoryBuffer &mb) { mptag_t tag; deserializeMPtag(mb, tag); if (TAG_NULL != tag) { PROGLOG("deserializeMPTag: tag = %d", (int)tag); jobComm->flush(tag); } return tag; } IEngineRowAllocator *CJobChannel::getRowAllocator(IOutputMetaData * meta, activity_id activityId, roxiemem::RoxieHeapFlags flags) const { return thorAllocator->getRowAllocator(meta, activityId, flags); } roxiemem::IRowManager *CJobChannel::queryRowManager() const { return thorAllocator->queryRowManager(); } void CJobChannel::addDependencies(IPropertyTree *xgmml, bool failIfMissing) { ::addDependencies(xgmml, failIfMissing, allGraphs); } IThorGraphIterator *CJobChannel::getSubGraphs() { CriticalBlock b(crit); return new CGraphTableIterator(subGraphs); } void CJobChannel::clean() { if (cleaned) return; cleaned = true; wait(); queryRowManager()->reportMemoryUsage(false); PROGLOG("CJobBase resetting memory manager"); if (graphExecutor) { graphExecutor->queryGraphPool().stopAll(); graphExecutor.clear(); } subGraphs.kill(); job.checkAndReportLeaks(thorAllocator->queryRowManager()); thorAllocator.clear(); codeCtx.clear(); } void CJobChannel::startGraph(CGraphBase &graph, bool checkDependencies, size32_t parentExtractSize, const byte *parentExtract) { graphExecutor->add(&graph, *this, checkDependencies, parentExtractSize, parentExtract); } IThorResult *CJobChannel::getOwnedResult(graph_id gid, activity_id ownerId, unsigned resultId) { Owned<CGraphBase> graph = getGraph(gid); if (!graph) { Owned<IThorException> e = MakeThorException(0, "getOwnedResult: graph not found"); e->setGraphInfo(queryJob().queryGraphName(), gid); throw e.getClear(); } Owned<IThorResult> result; if (ownerId) { CGraphElementBase *container = graph->queryElement(ownerId); assertex(container); CActivityBase *activity = container->queryActivity(); IThorGraphResults *results = activity->queryResults(); if (!results) throw MakeGraphException(graph, 0, "GraphGetResult: no results created (requesting: %d)", resultId); result.setown(activity->queryResults()->getResult(resultId)); } else result.setown(graph->getResult(resultId)); if (!result) throw MakeGraphException(graph, 0, "GraphGetResult: result not found: %d", resultId); return result.getClear(); } void CJobChannel::abort(IException *e) { aborted = true; Owned<IThorGraphIterator> iter = getSubGraphs(); ForEach (*iter) { CGraphBase &graph = iter->query(); graph.abort(e); } } // IGraphCallback void CJobChannel::runSubgraph(CGraphBase &graph, size32_t parentExtractSz, const byte *parentExtract) { graph.executeSubGraph(parentExtractSz, parentExtract); } static IThorResource *iThorResource = NULL; void setIThorResource(IThorResource &r) { iThorResource = &r; } IThorResource &queryThor() { return *iThorResource; } // // // // CActivityBase::CActivityBase(CGraphElementBase *_container) : container(*_container), timeActivities(_container->queryJob().queryTimeActivities()) { mpTag = TAG_NULL; abortSoon = receiving = cancelledReceive = initialized = reInit = false; baseHelper.set(container.queryHelper()); parentExtractSz = 0; parentExtract = NULL; } CActivityBase::~CActivityBase() { } void CActivityBase::abort() { if (!abortSoon) ActPrintLog("Abort condition set"); abortSoon = true; } void CActivityBase::kill() { ownedResults.clear(); } bool CActivityBase::appendRowXml(StringBuffer & target, IOutputMetaData & meta, const void * row) const { if (!meta.hasXML()) { target.append("<xml-unavailable/>"); return false; } try { CommonXmlWriter xmlWrite(XWFnoindent); meta.toXML((byte *) row, xmlWrite); target.append(xmlWrite.str()); return true; } catch (IException * e) { e->Release(); target.append("<invalid-row/>"); return false; } } void CActivityBase::logRow(const char * prefix, IOutputMetaData & meta, const void * row) const { bool blindLogging = false; // MORE: should check a workunit/global option if (meta.hasXML() && !blindLogging) { StringBuffer xml; appendRowXml(xml, meta, row); ActPrintLog("%s: %s", prefix, xml.str()); } } void CActivityBase::ActPrintLog(const char *format, ...) const { va_list args; va_start(args, format); ::ActPrintLogArgs(&queryContainer(), thorlog_null, MCdebugProgress, format, args); va_end(args); } void CActivityBase::ActPrintLog(IException *e, const char *format, ...) const { va_list args; va_start(args, format); ::ActPrintLogArgs(&queryContainer(), e, thorlog_all, MCexception(e), format, args); va_end(args); } void CActivityBase::ActPrintLog(IException *e) const { ActPrintLog(e, "%s", ""); } IThorRowInterfaces * CActivityBase::createRowInterfaces(IOutputMetaData * meta, byte seq) { activity_id id = createCompoundActSeqId(queryId(), seq); return createThorRowInterfaces(queryRowManager(), meta, id, queryHeapFlags(), queryCodeContext()); } IThorRowInterfaces * CActivityBase::createRowInterfaces(IOutputMetaData * meta, roxiemem::RoxieHeapFlags heapFlags, byte seq) { activity_id id = createCompoundActSeqId(queryId(), seq); return createThorRowInterfaces(queryRowManager(), meta, id, heapFlags, queryCodeContext()); } bool CActivityBase::fireException(IException *e) { Owned<IThorException> _te; IThorException *te = QUERYINTERFACE(e, IThorException); if (te) { if (!te->queryActivityId()) setExceptionActivityInfo(container, te); } else { te = MakeActivityException(this, e); te->setAudience(e->errorAudience()); _te.setown(te); } return container.queryOwner().fireException(te); } void CActivityBase::processAndThrowOwnedException(IException * _e) { IThorException *e = QUERYINTERFACE(_e, IThorException); if (e) { if (!e->queryActivityId()) setExceptionActivityInfo(container, e); } else { e = MakeActivityException(this, _e); _e->Release(); } throw e; } IEngineRowAllocator * CActivityBase::queryRowAllocator() { if (CABallocatorlock.lock()) { if (!rowAllocator) { roxiemem::RoxieHeapFlags heapFlags = queryHeapFlags(); rowAllocator.setown(getRowAllocator(queryRowMetaData(), heapFlags)); } CABallocatorlock.unlock(); } return rowAllocator; } IOutputRowSerializer * CActivityBase::queryRowSerializer() { if (CABserializerlock.lock()) { if (!rowSerializer) rowSerializer.setown(queryRowMetaData()->createDiskSerializer(queryCodeContext(),queryId())); CABserializerlock.unlock(); } return rowSerializer; } IOutputRowDeserializer * CActivityBase::queryRowDeserializer() { if (CABdeserializerlock.lock()) { if (!rowDeserializer) rowDeserializer.setown(queryRowMetaData()->createDiskDeserializer(queryCodeContext(),queryId())); CABdeserializerlock.unlock(); } return rowDeserializer; } IThorRowInterfaces *CActivityBase::getRowInterfaces() { // create an independent instance, to avoid circular link dependency problems return createThorRowInterfaces(queryRowManager(), queryRowMetaData(), container.queryId(), queryHeapFlags(), queryCodeContext()); } IEngineRowAllocator *CActivityBase::getRowAllocator(IOutputMetaData * meta, roxiemem::RoxieHeapFlags flags, byte seq) const { activity_id actId = createCompoundActSeqId(queryId(), seq); return queryJobChannel().getRowAllocator(meta, actId, flags); } bool CActivityBase::receiveMsg(ICommunicator &comm, CMessageBuffer &mb, const rank_t rank, const mptag_t mpTag, rank_t *sender, unsigned timeout) { BooleanOnOff onOff(receiving); CTimeMon t(timeout); unsigned remaining = timeout; // check 'cancelledReceive' every 10 secs while (!cancelledReceive && ((MP_WAIT_FOREVER==timeout) || !t.timedout(&remaining))) { if (comm.recv(mb, rank, mpTag, sender, remaining>10000?10000:remaining)) return true; } return false; } bool CActivityBase::receiveMsg(CMessageBuffer &mb, const rank_t rank, const mptag_t mpTag, rank_t *sender, unsigned timeout) { return receiveMsg(queryJobChannel().queryJobComm(), mb, rank, mpTag, sender, timeout); } void CActivityBase::cancelReceiveMsg(ICommunicator &comm, const rank_t rank, const mptag_t mpTag) { cancelledReceive = true; if (receiving) comm.cancel(rank, mpTag); } void CActivityBase::cancelReceiveMsg(const rank_t rank, const mptag_t mpTag) { cancelReceiveMsg(queryJobChannel().queryJobComm(), rank, mpTag); }
32.951295
221
0.617172
roscoche
33f61ec978a273caa269dc28db8c99c60ea5b70c
11,267
cpp
C++
src/appleseed/foundation/utility/benchmark/benchmarksuite.cpp
markreidvfx/appleseed
b9805e4d2750fe4c88e2cddc68456dae52679101
[ "MIT" ]
null
null
null
src/appleseed/foundation/utility/benchmark/benchmarksuite.cpp
markreidvfx/appleseed
b9805e4d2750fe4c88e2cddc68456dae52679101
[ "MIT" ]
null
null
null
src/appleseed/foundation/utility/benchmark/benchmarksuite.cpp
markreidvfx/appleseed
b9805e4d2750fe4c88e2cddc68456dae52679101
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "benchmarksuite.h" // appleseed.foundation headers. #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/thread.h" #include "foundation/platform/timers.h" #include "foundation/platform/types.h" #include "foundation/utility/benchmark/benchmarkresult.h" #include "foundation/utility/benchmark/ibenchmarkcase.h" #include "foundation/utility/benchmark/ibenchmarkcasefactory.h" #include "foundation/utility/benchmark/timingresult.h" #include "foundation/utility/filter.h" #include "foundation/utility/gnuplotfile.h" #include "foundation/utility/stopwatch.h" #include "foundation/utility/string.h" // Standard headers. #include <algorithm> #include <cassert> #include <cmath> #include <cstddef> #include <exception> #include <limits> #include <memory> #include <string> #include <vector> namespace foundation { // // BenchmarkSuite class implementation. // #define GENERATE_BENCHMARK_PLOTS namespace { // An empty benchmark case used for measuring the overhead of calling IBenchmarkCase::run(). struct EmptyBenchmarkCase : public IBenchmarkCase { const char* get_name() const override { return "Empty"; } APPLESEED_NO_INLINE void run() override { } }; } struct BenchmarkSuite::Impl { #if APPLESEED_X86 typedef Stopwatch<X86Timer> StopwatchType; #else typedef Stopwatch<DefaultProcessorTimer> StopwatchType; #endif std::string m_name; std::vector<IBenchmarkCaseFactory*> m_factories; static double measure_runtime_seconds( IBenchmarkCase* benchmark, StopwatchType& stopwatch) { stopwatch.start(); benchmark->run(); stopwatch.measure(); return stopwatch.get_seconds(); } static double measure_runtime_ticks( IBenchmarkCase* benchmark, StopwatchType& stopwatch) { stopwatch.start(); benchmark->run(); stopwatch.measure(); return static_cast<double>(stopwatch.get_ticks()); } template <typename MeasurementFunction> static double measure_runtime( IBenchmarkCase* benchmark, StopwatchType& stopwatch, MeasurementFunction& measurement_function, const size_t measurement_count) { double lowest_runtime = std::numeric_limits<double>::max(); for (size_t i = 0; i < measurement_count; ++i) { const double runtime = measurement_function(benchmark, stopwatch); lowest_runtime = std::min(lowest_runtime, runtime); } return lowest_runtime; } static size_t compute_measurement_count( IBenchmarkCase* benchmark, StopwatchType& stopwatch) { // Measure the runtime using a very small number of measurements. Not accurate. const size_t InitialMeasurementCount = 10; const double measurement_time = measure_runtime( benchmark, stopwatch, BenchmarkSuite::Impl::measure_runtime_seconds, InitialMeasurementCount); // Compute the number of measurements to get an accurate runtime measure. const size_t MaxMeasurementCount = 1000000; const double MaxTargetTotalTime = 0.1; // seconds return static_cast<size_t>(std::ceil( std::min(MaxMeasurementCount * measurement_time, MaxTargetTotalTime) / measurement_time)); } // Measure and return the overhead (in ticks) of running an empty benchmark case. static double measure_call_overhead_ticks( StopwatchType& stopwatch, const size_t measurement_count) { std::unique_ptr<IBenchmarkCase> empty_case(new EmptyBenchmarkCase()); return measure_runtime( empty_case.get(), stopwatch, BenchmarkSuite::Impl::measure_runtime_ticks, measurement_count); } }; BenchmarkSuite::BenchmarkSuite(const char* name) : impl(new Impl()) { assert(name); impl->m_name = name; } BenchmarkSuite::~BenchmarkSuite() { delete impl; } const char* BenchmarkSuite::get_name() const { return impl->m_name.c_str(); } void BenchmarkSuite::register_case(IBenchmarkCaseFactory* factory) { assert(factory); impl->m_factories.push_back(factory); } void BenchmarkSuite::run(BenchmarkResult& suite_result) const { PassThroughFilter filter; run(filter, suite_result); } void BenchmarkSuite::run( const IFilter& filter, BenchmarkResult& suite_result) const { BenchmarkingThreadContext benchmarking_context; bool has_begun_suite = false; for (size_t i = 0; i < impl->m_factories.size(); ++i) { IBenchmarkCaseFactory* factory = impl->m_factories[i]; // Skip benchmark cases that aren't let through by the filter. if (!filter.accepts(factory->get_name())) continue; if (!has_begun_suite) { // Tell the listeners that a benchmark suite is about to be executed. suite_result.begin_suite(*this); suite_result.signal_suite_execution(); has_begun_suite = true; } // Instantiate the benchmark case. std::unique_ptr<IBenchmarkCase> benchmark(factory->create()); // Tell the listeners that a benchmark case is about to be executed. suite_result.begin_case(*this, *benchmark.get()); #ifdef NDEBUG try #endif { suite_result.signal_case_execution(); // Recreate the stopwatch (and the underlying timer) for every benchmark // case, since the CPU frequency will fluctuate quite a bit depending on // the CPU load. We need an up-to-date frequency estimation in order to // compute accurate call rates. Impl::StopwatchType stopwatch(100000); // Estimate benchmarking parameters. const size_t measurement_count = Impl::compute_measurement_count(benchmark.get(), stopwatch); // Measure the overhead of calling IBenchmarkCase::run(). const double overhead_ticks = Impl::measure_call_overhead_ticks(stopwatch, measurement_count); // Run the benchmark case. const double runtime_ticks = Impl::measure_runtime( benchmark.get(), stopwatch, BenchmarkSuite::Impl::measure_runtime_ticks, measurement_count); // Gather the timing results. TimingResult timing_result; timing_result.m_iteration_count = 1; timing_result.m_measurement_count = measurement_count; timing_result.m_frequency = static_cast<double>(stopwatch.get_timer().frequency()); timing_result.m_ticks = runtime_ticks > overhead_ticks ? runtime_ticks - overhead_ticks : 0.0; // Post the timing result. suite_result.write( *this, *benchmark.get(), __FILE__, __LINE__, timing_result); #ifdef GENERATE_BENCHMARK_PLOTS std::vector<Vector2d> points; const size_t PointCount = 100; for (size_t j = 0; j < PointCount; ++j) { const double ticks = Impl::measure_runtime( benchmark.get(), stopwatch, BenchmarkSuite::Impl::measure_runtime_ticks, std::max<size_t>(1, measurement_count / PointCount)); points.emplace_back( static_cast<double>(j), ticks > overhead_ticks ? ticks - overhead_ticks : 0.0); } const std::string filepath = format("unit benchmarks/plots/{0}_{1}.gnuplot", get_name(), benchmark->get_name()); GnuplotFile plotfile; plotfile.new_plot().set_points(points); plotfile.write(filepath); #endif } #ifdef NDEBUG catch (const std::exception& e) { if (!is_empty_string(e.what())) { suite_result.write( *this, *benchmark.get(), __FILE__, __LINE__, "an unexpected exception was caught: %s", e.what()); } else { suite_result.write( *this, *benchmark.get(), __FILE__, __LINE__, "an unexpected exception was caught (no details available)."); } suite_result.signal_case_failure(); } catch (...) { suite_result.write( *this, *benchmark.get(), __FILE__, __LINE__, "an unexpected exception was caught (no details available)."); suite_result.signal_case_failure(); } #endif // Tell the listeners that the benchmark case execution has ended. suite_result.end_case(*this, *benchmark.get()); } if (has_begun_suite) { // Report a benchmark suite failure if one or more benchmark cases failed. if (suite_result.get_case_failure_count() > 0) suite_result.signal_suite_failure(); // Tell the listeners that the benchmark suite execution has ended. suite_result.end_suite(*this); } } } // namespace foundation
31.917847
106
0.617911
markreidvfx
33f74ccc3b216a435803e2b9423c0caf6b88825e
56,981
cpp
C++
src/ARIA/ariaUtil.cpp
rzsavilla/Robot_PathPlanning
7ca805b917824ecaf8f12a950b1f77bd76ac5836
[ "MIT" ]
1
2018-10-13T02:50:25.000Z
2018-10-13T02:50:25.000Z
src/ARIA/ariaUtil.cpp
rzsavilla/Robot_PathPlanning
7ca805b917824ecaf8f12a950b1f77bd76ac5836
[ "MIT" ]
null
null
null
src/ARIA/ariaUtil.cpp
rzsavilla/Robot_PathPlanning
7ca805b917824ecaf8f12a950b1f77bd76ac5836
[ "MIT" ]
1
2018-10-13T02:50:26.000Z
2018-10-13T02:50:26.000Z
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. 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 If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ #define _GNU_SOURCE 1 // for isnormal() and other newer (non-ansi) C functions #include "ArExport.h" #include "ariaOSDef.h" #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <string.h> #include <math.h> #include <ctype.h> #ifdef WIN32 #include <windows.h> // for timeGetTime() and mmsystem.h #include <mmsystem.h> // for timeGetTime() #else #include <sys/time.h> #include <stdarg.h> #include <unistd.h> #include <utime.h> #include <sys/types.h> #include <dirent.h> #include <ctype.h> #include <errno.h> #include <fcntl.h> #endif #include "ariaInternal.h" #include "ariaTypedefs.h" #include "ariaUtil.h" #ifndef ARINTERFACE #include "ArSick.h" #include "ArUrg.h" #include "ArLMS1XX.h" #include "ArUrg_2_0.h" #endif // ARINTERFACE #include "ArSerialConnection.h" #include "ArTcpConnection.h" #ifdef WIN32 #include <io.h> AREXPORT const char *ArUtil::COM1 = "COM1"; AREXPORT const char *ArUtil::COM2 = "COM2"; AREXPORT const char *ArUtil::COM3 = "COM3"; AREXPORT const char *ArUtil::COM4 = "COM4"; AREXPORT const char *ArUtil::COM5 = "COM5"; AREXPORT const char *ArUtil::COM6 = "COM6"; AREXPORT const char *ArUtil::COM7 = "COM7"; AREXPORT const char *ArUtil::COM8 = "COM8"; AREXPORT const char *ArUtil::COM9 = "COM9"; AREXPORT const char *ArUtil::COM10 = "COM10"; AREXPORT const char *ArUtil::COM11 = "COM11"; AREXPORT const char *ArUtil::COM12 = "COM12"; AREXPORT const char *ArUtil::COM13 = "COM13"; AREXPORT const char *ArUtil::COM14 = "COM14"; AREXPORT const char *ArUtil::COM15 = "COM15"; AREXPORT const char *ArUtil::COM16 = "COM16"; #else // ifndef WIN32 AREXPORT const char *ArUtil::COM1 = "/dev/ttyS0"; AREXPORT const char *ArUtil::COM2 = "/dev/ttyS1"; AREXPORT const char *ArUtil::COM3 = "/dev/ttyS2"; AREXPORT const char *ArUtil::COM4 = "/dev/ttyS3"; AREXPORT const char *ArUtil::COM5 = "/dev/ttyS4"; AREXPORT const char *ArUtil::COM6 = "/dev/ttyS5"; AREXPORT const char *ArUtil::COM7 = "/dev/ttyS6"; AREXPORT const char *ArUtil::COM8 = "/dev/ttyS7"; AREXPORT const char *ArUtil::COM9 = "/dev/ttyS8"; AREXPORT const char *ArUtil::COM10 = "/dev/ttyS9"; AREXPORT const char *ArUtil::COM11 = "/dev/ttyS10"; AREXPORT const char *ArUtil::COM12 = "/dev/ttyS11"; AREXPORT const char *ArUtil::COM13 = "/dev/ttyS12"; AREXPORT const char *ArUtil::COM14 = "/dev/ttyS13"; AREXPORT const char *ArUtil::COM15 = "/dev/ttyS14"; AREXPORT const char *ArUtil::COM16 = "/dev/ttyS15"; #endif // WIN32 AREXPORT const char *ArUtil::TRUESTRING = "true"; AREXPORT const char *ArUtil::FALSESTRING = "false"; // const double eps = std::numeric_limits<double>::epsilon(); const double ArMath::ourEpsilon = 0.00000001; #ifdef WIN32 // max returned by rand() const long ArMath::ourRandMax = RAND_MAX; #else // max returned by lrand48() const long ArMath::ourRandMax = 2147483648;// 2^31, per lrand48 man page #endif #ifdef WIN32 const char ArUtil::SEPARATOR_CHAR = '\\'; const char *ArUtil::SEPARATOR_STRING = "\\"; const char ArUtil::OTHER_SEPARATOR_CHAR = '/'; #else const char ArUtil::SEPARATOR_CHAR = '/'; const char *ArUtil::SEPARATOR_STRING = "/"; const char ArUtil::OTHER_SEPARATOR_CHAR = '\\'; #endif #ifdef WIN32 ArMutex ArUtil::ourLocaltimeMutex; #endif /** This sleeps for the given number of milliseconds... Note in linux it tries to sleep for 10 ms less than the amount given, which should wind up close to correct... Linux is broken in this regard and sleeps for too long... it sleeps for the ceiling of the current 10 ms range, then for an additional 10 ms... so: 11 to 20 ms sleeps for 30 ms... 21 to 30 ms sleeps for 40 ms... 31 to 40 ms sleeps for 50 ms... this continues on up to the values we care about of.. 81 to 90 ms sleeps for 100 ms... 91 to 100 ms sleeps for 110 ms... so we'll sleep for 10 ms less than we want to, which should put us about right... guh @param ms the number of milliseconds to sleep for */ AREXPORT void ArUtil::sleep(unsigned int ms) { #ifdef WIN32 Sleep(ms); #else // ifndef win32 if (ms > 10) ms -= 10; usleep(ms * 1000); #endif // linux } /** Get the time in milliseconds, counting from some arbitrary point. This time is only valid within this run of the program. @return millisecond time */ AREXPORT unsigned int ArUtil::getTime(void) { // the good unix way #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) struct timespec tp; if (clock_gettime(CLOCK_MONOTONIC, &tp) == 0) return tp.tv_nsec / 1000000 + (tp.tv_sec % 1000000)*1000; // the old unix way as a fallback #endif // if it isn't the good way #if !defined(WIN32) struct timeval tv; if (gettimeofday(&tv,NULL) == 0) return tv.tv_usec/1000 + (tv.tv_sec % 1000000)*1000;//windows else return 0; #elif defined(WIN32) return timeGetTime(); #endif } /* Takes a string and splits it into a list of words. It appends the words to the outList. If there is nothing found, it will not touch the outList. @param inString the input string to split @param outList the list in which to store the words that are found */ /* AREXPORT void ArUtil::splitString(std::string inString, std::list<std::string> &outList) { const char *start, *end; // Strip off leading white space for (end=inString.c_str(); *end && isspace(*end); ++end) ; while (*end) { // Mark start of the word then find end for (start=end; *end && !isspace(*end); ++end) ; // Store the word if (*start && ((*end && isspace(*end)) || !*end)) outList.push_back(std::string(start, (int)(end-start))); for (; *end && isspace(*end); ++end) ; } } */ #ifdef WIN32 /** @return size in bytes. -1 on error. @param fileName name of the file to size */ AREXPORT long ArUtil::sizeFile(std::string fileName) { struct _stat buf; if (_stat(fileName.c_str(), &buf) < 0) return(-1); if (!(buf.st_mode | _S_IFREG)) return(-1); return(buf.st_size); } /** @return size in bytes. -1 on error. @param fileName name of the file to size */ AREXPORT long ArUtil::sizeFile(const char * fileName) { struct _stat buf; if (_stat(fileName, &buf) < 0) return(-1); if (!(buf.st_mode | _S_IFREG)) return(-1); return(buf.st_size); } #else // !WIN32 AREXPORT long ArUtil::sizeFile(std::string fileName) { struct stat buf; if (stat(fileName.c_str(), &buf) < 0) { ArLog::logErrorFromOS(ArLog::Normal, "ArUtil::sizeFile: stat failed"); return(-1); } if (!S_ISREG(buf.st_mode)) return(-1); return(buf.st_size); } /** @return size in bytes. -1 on error. @param fileName name of the file to size */ AREXPORT long ArUtil::sizeFile(const char * fileName) { struct stat buf; if (stat(fileName, &buf) < 0) { ArLog::logErrorFromOS(ArLog::Normal, "ArUtil::sizeFile: stat failed"); return(-1); } if (!S_ISREG(buf.st_mode)) return(-1); return(buf.st_size); } #endif // else !WIN32 /** @return true if file is found @param fileName name of the file to size */ AREXPORT bool ArUtil::findFile(const char *fileName) { FILE *fp; if ((fp=ArUtil::fopen(fileName, "r"))) { fclose(fp); return(true); } else return(false); } /* Works for \ and /. Returns true if something was actualy done. Sets fileOut to be what ever the answer is. @return true if the path contains a file @param fileIn input path/fileName @param fileOut output fileName */ /*AREXPORT bool ArUtil::stripDir(std::string fileIn, std::string &fileOut) { const char *ptr; for (ptr=fileIn.c_str(); *ptr; ++ptr) ; for (--ptr; (ptr > fileIn.c_str()) && (*ptr != '/') && (*ptr != '\\'); --ptr) ; if ((*ptr == '/') || (*ptr == '\\')) { fileOut=ptr+1; return(true); } else { fileOut=fileIn; return(false); } } */ /* Works for \ and /. Returns true if something was actualy done. Sets fileOut to be what ever the answer is. @return true if the file contains a path @param fileIn input path/fileName @param fileOut output path */ /* AREXPORT bool ArUtil::stripFile(std::string fileIn, std::string &fileOut) { const char *start, *end; for (start=end=fileIn.c_str(); *end; ++end) { if ((*end == '/') || (*end == '\\')) { start=end; for (; *end && ((*end == '/') || (*end == '\\')); ++end) ; } } if (start < end) { fileOut.assign(fileIn, 0, start-fileIn.c_str()); return(true); } fileOut=fileIn; return(false); } */ AREXPORT bool ArUtil::stripQuotes(char *dest, const char *src, size_t destLen) { size_t srcLen = strlen(src); if (destLen < srcLen + 1) { ArLog::log(ArLog::Normal, "ArUtil::stripQuotes: destLen isn't long enough to fit copy its %d should be %d", destLen, srcLen + 1); return false; } // if there are no quotes to strip just copy and return if (srcLen < 2 || (src[0] != '"' || src[srcLen - 1] != '"')) { strcpy(dest, src); return true; } // we have quotes so chop of the first and last char strncpy(dest, &src[1], srcLen - 1); dest[srcLen - 2] = '\0'; return true; } /** Append a directory separator character to the given path string, depending on the * platform. On Windows, a backslash ('\\') is added. On other platforms, a * forward slash ('/') is appended. If there is no more allocated space in the * path string, no character will be appended. @param path the path string to append a slash to @param pathLength maximum length allocated for path string */ AREXPORT void ArUtil::appendSlash(char *path, size_t pathLength) { // first check boundary size_t len; len = strlen(path); if (len > pathLength - 2) return; if (len == 0 || (path[len - 1] != '\\' && path[len - 1] != '/')) { #ifdef WIN32 path[len] = '\\'; #else path[len] = '/'; #endif path[len + 1] = '\0'; } } AREXPORT void ArUtil::appendSlash(std::string &path) { // first check boundary size_t len = path.length(); if ((len == 0) || (path[len - 1] != SEPARATOR_CHAR && path[len - 1] != OTHER_SEPARATOR_CHAR)) { path += SEPARATOR_STRING; } } // end method appendSlash /** @param path the path in which to fix the orientation of the slashes @param pathLength the maximum length of path */ AREXPORT void ArUtil::fixSlashes(char *path, size_t pathLength) { #ifdef WIN32 fixSlashesBackward(path, pathLength); #else fixSlashesForward(path, pathLength); #endif } /** @param path the path in which to fix the orientation of the slashes @param pathLength how long that path is at max */ AREXPORT void ArUtil::fixSlashesBackward(char *path, size_t pathLength) { for (size_t i=0; path[i] != '\0' && i < pathLength; i++) { if (path[i] == '/') path[i]='\\'; } } /** @param path the path in which to fix the orientation of the slashes @param pathLength how long that path is at max */ AREXPORT void ArUtil::fixSlashesForward(char *path, size_t pathLength) { for (size_t i=0; path[i] != '\0' && i < pathLength; i++) { if (path[i] == '\\') path[i]='/'; } } /** @param path the path in which to fix the orientation of the slashes */ AREXPORT void ArUtil::fixSlashes(std::string &path) { for (size_t i = 0; i < path.length(); i++) { if (path[i] == OTHER_SEPARATOR_CHAR) path[i]= SEPARATOR_CHAR; } } AREXPORT char ArUtil::getSlash() { return SEPARATOR_CHAR; } /** This function will take the 'baseDir' and put the 'insideDir' after it so that it winds up with 'baseDir/insideDir/'. It will take care of slashes, making sure there is one between them and one at the end, and the slashes will match what the operating system expects. @param dest the place to put the result @param destLength the length of the place to put the results @param baseDir the directory to start with @param insideDir the directory to place after the baseDir **/ AREXPORT void ArUtil::addDirectories(char *dest, size_t destLength, const char *baseDir, const char *insideDir) { // start it off strncpy(dest, baseDir, destLength - 1); // make sure we have a null term dest[destLength - 1] = '\0'; // toss on that slash appendSlash(dest, destLength); // put on the inside dir strncat(dest, insideDir, destLength - strlen(dest) - 1); // now toss on that slash appendSlash(dest, destLength); // and now fix up all the slashes fixSlashes(dest, destLength); } /** This compares two strings, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcmp(std::string str, std::string str2) { return ::strcmp(str.c_str(), str2.c_str()); } /** This compares two strings, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcmp(std::string str, const char *str2) { return ::strcmp(str.c_str(), str2); } /** This compares two strings, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcmp(const char *str, std::string str2) { return ::strcmp(str, str2.c_str()); } /** This compares two strings, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcmp(const char *str, const char *str2) { return ::strcmp(str, str2); } /** This compares two strings ignoring case, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcasecmp(std::string str, std::string str2) { return ::strcasecmp(str.c_str(), str2.c_str()); } /** This compares two strings ignoring case, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcasecmp(std::string str, const char *str2) { return ::strcasecmp(str.c_str(), str2); } /** This compares two strings ignoring case, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcasecmp(const char *str, std::string str2) { return ::strcasecmp(str, str2.c_str()); } /** This compares two strings ignoring case, it returns an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. @param str the string to compare @param str2 the second string to compare @return an integer less than, equal to, or greater than zero if str is found, respectively, to be less than, to match, or be greater than str2. */ AREXPORT int ArUtil::strcasecmp(const char *str, const char *str2) { return ::strcasecmp(str, str2); } AREXPORT int ArUtil::strcasequotecmp(const std::string &str1, const std::string &str2) { int len1 = str1.length(); size_t pos1 = 0; if ((len1 >= 2) && (str1[0] == '\"') && (str1[len1 - 1] == '\"')) { pos1 = 1; } int len2 = str2.length(); size_t pos2 = 0; if ((len2 >= 2) && (str2[0] == '\"') && (str2[len2 - 1] == '\"')) { pos2 = 1; } /* Unfortunately gcc2 does't support the 5 argument version of std::string::compare()... * (Furthermore, note that it's 3-argument compare has the arguments in the wrong order.) */ #if defined(__GNUC__) && (__GNUC__ <= 2) && (__GNUC_MINOR__ <= 96) #warning Using GCC 2.96 or less so must use nonstandard std::string::compare method. int cmp = str1.compare(str2.substr(pos2, len2 - 2 * pos2), pos1, len1 - 2 * pos1); #else int cmp = str1.compare(pos1, len1 - 2 * pos1, str2, pos2, len2 - 2 * pos2); #endif return cmp; } // end method strcasequotecmp /** This copies src into dest but puts a \ before any spaces in src, escaping them... its mostly for use with ArArgumentBuilder... make sure you have at least maxLen spaces in the arrays that you're passing as dest... this allocates no memory **/ AREXPORT void ArUtil::escapeSpaces(char *dest, const char *src, size_t maxLen) { size_t i, adj, len; len = strlen(src); // walk it, when we find one toss in the slash and incr adj so the // next characters go in the right space for (i = 0, adj = 0; i < len && i + adj < maxLen; i++) { if (src[i] == ' ') { dest[i+adj] = '\\'; adj++; } dest[i+adj] = src[i]; } // make sure its null terminated dest[i+adj] = '\0'; } /** This copies src into dest but makes it lower case make sure you have at least maxLen arrays that you're passing as dest... this allocates no memory **/ AREXPORT void ArUtil::lower(char *dest, const char *src, size_t maxLen) { size_t i; size_t len; len = strlen(src); for (i = 0; i < len && i < maxLen; i++) dest[i] = tolower(src[i]); dest[i] = '\0'; } AREXPORT bool ArUtil::isOnlyAlphaNumeric(const char *str) { unsigned int ui; unsigned int len; if (str == NULL) return true; for (ui = 0, len = strlen(str); ui < len; ui++) { if (!isalpha(str[ui]) && !isdigit(str[ui]) && str[ui] != '\0') return false; } return true; } AREXPORT bool ArUtil::isOnlyNumeric(const char *str) { if (str == NULL) return true; for (unsigned i = 0, len = strlen(str); i < len; i++) { if (!isdigit(str[i]) && str[i] != '\0') return false; } return true; } AREXPORT bool ArUtil::isStrEmpty(const char *str) { if (str == NULL) { return true; } if (str[0] == '\0') { return true; } return false; } // end method isStrEmpty AREXPORT bool ArUtil::isStrInList(const char *str, const std::list<std::string> &list, bool isIgnoreCase) { if (str == NULL) { return false; } for (std::list<std::string>::const_iterator aIter = list.begin(); aIter != list.end(); aIter++) { if (!isIgnoreCase) { if (strcmp((*aIter).c_str(), str) == 0) { return true; } } else { // ignore case if (strcasecmp((*aIter).c_str(), str) == 0) { return true; } } // end else ignore case } // end for each string return false; } // end method isStrInList AREXPORT const char *ArUtil::convertBool(int val) { if (val) return TRUESTRING; else return FALSESTRING; } AREXPORT double ArUtil::atof(const char *nptr) { if (strcasecmp(nptr, "inf") == 0) return HUGE_VAL; else if (strcasecmp(nptr, "-inf") == 0) return -HUGE_VAL; else return ::atof(nptr); } AREXPORT void ArUtil::functorPrintf(ArFunctor1<const char *> *functor, char *str, ...) { char buf[10000]; va_list ptr; va_start(ptr, str); //vsprintf(buf, str, ptr); vsnprintf(buf, sizeof(buf) - 1, str, ptr); buf[sizeof(buf) - 1] = '\0'; functor->invoke(buf); va_end(ptr); } AREXPORT void ArUtil::writeToFile(const char *str, FILE *file) { fputs(str, file); } /** This function reads a string from a file. The file can contain spaces or tabs, but a '\\r' or '\\n' will be treated as the end of the string, and the string cannot have more characters than the value given by strLen. This is mostly for internal use with Linux to determine the Aria directory from a file in /etc, but will work with Linux or Windows. @param fileName name of the file in which to look @param str the string to copy the file contents into @param strLen the maximum allocated length of str **/ AREXPORT bool ArUtil::getStringFromFile(const char *fileName, char *str, size_t strLen) { FILE *strFile; unsigned int i; str[0] = '\0'; if ((strFile = ArUtil::fopen(fileName, "r")) != NULL) { fgets(str, strLen, strFile); for (i = 0; i < strLen; i++) { if (str[i] == '\r' || str[i] == '\n' || str[i] == '\0') { str[i] = '\0'; fclose(strFile); break; } } } else { str[0] = '\0'; return false; } return true; } /** * Look up the given value under the given key, within the given registry root * key. @param root the root key to use, one of the REGKEY enum values @param key the name of the key to find @param value the value name in which to find the string @param str where to put the string found, or if it could not be found, an empty (length() == 0) string @param len the length of the allocated memory in str @return true if the string was found, false if it was not found or if there was a problem such as the string not being long enough **/ AREXPORT bool ArUtil::getStringFromRegistry(REGKEY root, const char *key, const char *value, char *str, int len) { #ifndef WIN32 return false; #else // WIN32 HKEY hkey; int err; unsigned long numKeys; unsigned long longestKey; unsigned long numValues; unsigned long longestValue; unsigned long longestDataLength; char *valueName; unsigned long valueLength; unsigned long type; char *data; unsigned long dataLength; HKEY rootKey; switch (root) { case REGKEY_CLASSES_ROOT: rootKey = HKEY_CLASSES_ROOT; break; case REGKEY_CURRENT_CONFIG: rootKey = HKEY_CURRENT_CONFIG; break; case REGKEY_CURRENT_USER: rootKey = HKEY_CURRENT_USER; break; case REGKEY_LOCAL_MACHINE: rootKey = HKEY_LOCAL_MACHINE; break; case REGKEY_USERS: rootKey=HKEY_USERS; break; default: ArLog::log(ArLog::Terse, "ArUtil::getStringFromRegistry: Bad root key given."); return false; } if ((err = RegOpenKeyEx(rootKey, key, 0, KEY_READ, &hkey)) == ERROR_SUCCESS) { //printf("Got a key\n"); if (RegQueryInfoKey(hkey, NULL, NULL, NULL, &numKeys, &longestKey, NULL, &numValues, &longestValue, &longestDataLength, NULL, NULL) == ERROR_SUCCESS) { /* printf("Have %d keys longest is %d, have %d values longest name is %d, longest data is %d\n", numKeys, longestKey, numValues, longestValue, longestDataLength); */ data = new char[longestDataLength+2]; valueName = new char[longestValue+2]; for (unsigned long i = 0; i < numValues; ++i) { dataLength = longestDataLength+1; valueLength = longestValue+1; if ((err = RegEnumValue(hkey, i, valueName, &valueLength, NULL, &type, (unsigned char *)data, &dataLength)) == ERROR_SUCCESS) { //printf("Enumed value %d, name is %s, value is %s\n", i, valueName, data); if (strcmp(value, valueName) == 0) { if (len < dataLength) { ArLog::log(ArLog::Terse,"ArUtil::getStringFromRegistry: str passed in not long enough for data."); delete data; delete valueName; return false; } strncpy(str, data, len); delete data; delete valueName; return true; } } /* else printf("Couldn't enum value %d cause %d\n",i, err); */ } delete data; delete valueName; } /* else printf("QueryInfoKey failed\n"); */ } /* else printf("No key %d\n", err); */ return false; #endif } #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) bool ArTime::ourMonotonicClock = true; #endif AREXPORT void ArTime::setToNow(void) { // if we have the best way of finding time use that #if defined(_POSIX_TIMERS) && defined(_POSIX_MONOTONIC_CLOCK) if (ourMonotonicClock) { struct timespec timeNow; if (clock_gettime(CLOCK_MONOTONIC, &timeNow) == 0) { mySec = timeNow.tv_sec; myMSec = timeNow.tv_nsec / 1000000; return; } else { ourMonotonicClock = false; ArLog::logNoLock(ArLog::Terse, "ArTime::setToNow: invalid return from clock_gettime."); } } #endif // if our good way didn't work use the old ways #ifndef WIN32 struct timeval timeNow; if (gettimeofday(&timeNow, NULL) == 0) { mySec = timeNow.tv_sec; myMSec = timeNow.tv_usec / 1000; } else ArLog::logNoLock(ArLog::Terse, "ArTime::setToNow: invalid return from gettimeofday."); // thats probably not available in windows, so this is the one we've been using #else /* this should be the better way, but it doesn't really work... this would be seconds from 1970, but it is based on the hardware timer or something and so winds up not being updated all the time and winds up being some number of ms < 20 ms off struct _timeb startTime; _ftime(&startTime); mySec = startTime.time; myMSec = startTime.millitm;*/ // so we're going with just their normal function, msec since boot long timeNow; timeNow = timeGetTime(); mySec = timeNow / 1000; myMSec = timeNow % 1000; // but if the good way isn't available use the old way... #endif } AREXPORT ArRunningAverage::ArRunningAverage(size_t numToAverage) { myNumToAverage = numToAverage; myTotal = 0; myNum = 0; myUseRootMeanSquare = false; } AREXPORT ArRunningAverage::~ArRunningAverage() { } AREXPORT double ArRunningAverage::getAverage(void) const { if (myNum == 0) return 0.0; if (myUseRootMeanSquare) return sqrt(myTotal / myNum); else return myTotal / myNum; } AREXPORT void ArRunningAverage::add(double val) { if (myUseRootMeanSquare) myTotal += (val * val); else myTotal += val; myNum++; myVals.push_front(val); if (myVals.size() > myNumToAverage || myNum > myNumToAverage) { if (myUseRootMeanSquare) myTotal -= (myVals.back() * myVals.back()); else myTotal -= myVals.back(); myNum--; myVals.pop_back(); } } AREXPORT void ArRunningAverage::clear(void) { while (myVals.size() > 0) myVals.pop_back(); myNum = 0; myTotal = 0; } AREXPORT size_t ArRunningAverage::getNumToAverage(void) const { return myNumToAverage; } AREXPORT void ArRunningAverage::setNumToAverage(size_t numToAverage) { myNumToAverage = numToAverage; while (myVals.size() > myNumToAverage) { if (myUseRootMeanSquare) myTotal -= (myVals.back() * myVals.back()); else myTotal -= myVals.back(); myNum--; myVals.pop_back(); } } AREXPORT size_t ArRunningAverage::getCurrentNumAveraged(void) { return myNum; } AREXPORT void ArRunningAverage::setUseRootMeanSquare(bool useRootMeanSquare) { if (myUseRootMeanSquare != useRootMeanSquare) { myTotal = 0; std::list<double>::iterator it; for (it = myVals.begin(); it != myVals.end(); it++) { if (useRootMeanSquare) myTotal += ((*it) * (*it)); else myTotal += (*it); } } myUseRootMeanSquare = useRootMeanSquare; } AREXPORT bool ArRunningAverage::getUseRootMeanSquare(void) { return myUseRootMeanSquare; } AREXPORT ArRootMeanSquareCalculator::ArRootMeanSquareCalculator() { clear(); myName = "ArRootMeanSquareCalculator"; } AREXPORT ArRootMeanSquareCalculator::~ArRootMeanSquareCalculator() { } AREXPORT double ArRootMeanSquareCalculator::getRootMeanSquare (void) const { if (myNum == 0) return 0; else return sqrt((double) myTotal / (double)myNum); } AREXPORT void ArRootMeanSquareCalculator::add(int val) { myTotal += val * val; myNum++; if (myTotal < 0) { ArLog::log(ArLog::Normal, "%s: total wrapped, resetting", myName.c_str()); clear(); // this isn't a clean fix, but won't let it infinitely loop on a bad value //add(val); } } AREXPORT void ArRootMeanSquareCalculator::clear(void) { myTotal = 0; myNum = 0; } AREXPORT size_t ArRootMeanSquareCalculator::getCurrentNumAveraged(void) { return myNum; } AREXPORT void ArRootMeanSquareCalculator::setName(const char *name) { if (name != NULL) myName = name; else myName = "ArRootMeanSquareCalculator"; } AREXPORT const char *ArRootMeanSquareCalculator::getName(void) { return myName.c_str(); } #ifndef WIN32 AREXPORT ArDaemonizer::ArDaemonizer(int *argc, char **argv, bool closeStdErrAndStdOut) : myParser(argc, argv), myLogOptionsCB(this, &ArDaemonizer::logOptions) { myIsDaemonized = false; myCloseStdErrAndStdOut = closeStdErrAndStdOut; Aria::addLogOptionsCB(&myLogOptionsCB); } AREXPORT ArDaemonizer::~ArDaemonizer() { } AREXPORT bool ArDaemonizer::daemonize(void) { if (myParser.checkArgument("-daemonize") || myParser.checkArgument("-d")) { return forceDaemonize(); } else return true; } /** This returns true if daemonizing worked, returns false if it didn't... the parent process exits here if forking worked. **/ AREXPORT bool ArDaemonizer::forceDaemonize(void) { switch (fork()) { case 0: // child process just return myIsDaemonized = true; if (myCloseStdErrAndStdOut) { fclose(stdout); fclose(stderr); } return true; case -1: // error.... fail printf("Can't fork"); ArLog::log(ArLog::Terse, "ArDaemonizer: Can't fork"); return false; default: // parent process printf("Daemon started\n"); exit(0); } } AREXPORT void ArDaemonizer::logOptions(void) const { ArLog::log(ArLog::Terse, "Options for Daemonizing:"); ArLog::log(ArLog::Terse, "-daemonize"); ArLog::log(ArLog::Terse, "-d"); ArLog::log(ArLog::Terse, ""); } #endif // WIN32 std::map<ArPriority::Priority, std::string> ArPriority::ourPriorityNames; std::string ArPriority::ourUnknownPriorityName; bool ArPriority::ourStringsInited = false; AREXPORT const char *ArPriority::getPriorityName(Priority priority) { if (!ourStringsInited) { ourPriorityNames[IMPORTANT] = "Basic"; ourPriorityNames[NORMAL] = "Intermediate"; ourPriorityNames[TRIVIAL] = "Advanced"; ourPriorityNames[DETAILED] = "Advanced"; ourPriorityNames[EXPERT] = "Expert"; ourPriorityNames[FACTORY] = "Factory"; ourUnknownPriorityName = "Unknown"; ourStringsInited = true; } std::map<ArPriority::Priority, std::string>::iterator iter = ourPriorityNames.find(priority); if (iter != ourPriorityNames.end()) { return iter->second.c_str(); } else { return ourUnknownPriorityName.c_str(); } } AREXPORT void ArUtil::putCurrentYearInString(char* s, size_t len) { struct tm t; ArUtil::localtime(&t); snprintf(s, len, "%4d", 1900 + t.tm_year); s[len-1] = '\0'; } AREXPORT void ArUtil::putCurrentMonthInString(char* s, size_t len) { struct tm t; ArUtil::localtime(&t); snprintf(s, len, "%02d", t.tm_mon + 1); s[len-1] = '\0'; } AREXPORT void ArUtil::putCurrentDayInString(char* s, size_t len) { struct tm t; ArUtil::localtime(&t); snprintf(s, len, "%02d", t.tm_mday); s[len-1] = '\0'; } AREXPORT void ArUtil::putCurrentHourInString(char* s, size_t len) { struct tm t; ArUtil::localtime(&t); snprintf(s, len, "%02d", t.tm_hour); s[len-1] = '\0'; } AREXPORT void ArUtil::putCurrentMinuteInString(char* s, size_t len) { struct tm t; ArUtil::localtime(&t); snprintf(s, len, "%02d", t.tm_min); s[len-1] = '\0'; } AREXPORT void ArUtil::putCurrentSecondInString(char* s, size_t len) { struct tm t; ArUtil::localtime(&t); snprintf(s, len, "%02d", t.tm_sec); s[len-1] = '\0'; } AREXPORT time_t ArUtil::parseTime(const char *str, bool *ok, bool toToday) { struct tm tmOut; if (toToday) { struct tm now; if (!localtime(&now)) { *ok = false; return 0; } memcpy(&tmOut, &now, sizeof(now)); } else { memset(&tmOut, 0, sizeof(tmOut)); // The day-of-the-month starts at 1 (not 0)... tmOut.tm_mday = 1; // Setting the year to 70 because if it is left at 0 or 1, then // the call to mktime() returns an apparently bogus value. Think // that 70 makes sense since times are generally measured from // 1/1/1970 (but still, it's all a little strange). tmOut.tm_year = 70; tmOut.tm_isdst = -1; // Negative value means unknown } bool isValid = true; int hrs = -1; int min = -1; int sec = 0; ArArgumentBuilder separator(512, ':'); separator.add(str); // if there's the wrong number of args, or any of the args aren't // integers then it's invalid and we won't parse it if ((separator.getArgc() != 2 && separator.getArgc() != 3) || !separator.isArgInt(0) || !separator.isArgInt(1) || (separator.getArgc() == 3 && !separator.isArgInt(2))) { //printf("Invalid... %d\n", separator.getArgc()); //separator.log(); isValid = false; } else { hrs = separator.getArgInt(0); min = separator.getArgInt(1); if (separator.getArgc() == 3) sec = separator.getArgInt(2); //printf("Was %02d:%02d:%02d", hrs, min, sec); } /* char *tempBuf = new char[strlen(str) + 1]; strncpy(tempBuf, str, sizeof(tempBuf)); // Attempted to use strptime, but it doesn't seem to be universally // available. char *pch = strtok(tempBuf, ":"); if (pch != NULL) { hrs = atoi(pch); } pch = strtok(NULL, ":"); if (pch != NULL) { min = atoi(pch); } */ // make sure the actual numbers are valid if (!((hrs >= 0) && (hrs < 24) && (min >= 0) && (min < 60) && (sec >= 0) && (sec < 60))) isValid = false; if (isValid) { tmOut.tm_hour = hrs; tmOut.tm_min = min; tmOut.tm_sec = sec; } time_t newTime = mktime(&tmOut); if (ok != NULL) { *ok = (isValid && (newTime != -1)); } //delete [] tempBuf; return newTime; } // end method parseTime AREXPORT bool ArUtil::localtime(const time_t *timep, struct tm *result) { #ifdef WIN32 ourLocaltimeMutex.lock(); struct tm *r = ::localtime(timep); if(r == NULL) { ourLocaltimeMutex.unlock(); return false; } *result = *r; // copy the 'struct tm' object before unlocking. ourLocaltimeMutex.unlock(); return true; #else return (::localtime_r(timep, result) != NULL); #endif } /** Call ArUtil::localtime() with the current time obtained by calling * time(NULL). * @return false on error (e.g. invalid input), otherwise true. */ AREXPORT bool ArUtil::localtime(struct tm *result) { time_t now = time(NULL); return ArUtil::localtime(&now, result); } AREXPORT ArCallbackList::ArCallbackList( const char *name, ArLog::LogLevel logLevel, bool singleShot) { myName = name; mySingleShot = singleShot; setLogLevel(logLevel); std::string mutexName; mutexName = "ArCallbackList::"; mutexName += name; mutexName += "::myDataMutex"; myDataMutex.setLogName(mutexName.c_str()); } AREXPORT ArCallbackList::~ArCallbackList() { } AREXPORT void ArCallbackList::addCallback( ArFunctor *functor, int position) { myDataMutex.lock(); myList.insert( std::pair<int, ArFunctor *>(-position, functor)); myDataMutex.unlock(); } AREXPORT void ArCallbackList::remCallback(ArFunctor *functor) { myDataMutex.lock(); std::multimap<int, ArFunctor *>::iterator it; for (it = myList.begin(); it != myList.end(); it++) { if ((*it).second == functor) { myList.erase(it); myDataMutex.unlock(); remCallback(functor); return; } } myDataMutex.unlock(); } AREXPORT void ArCallbackList::setName(const char *name) { myDataMutex.lock(); myName = name; myDataMutex.unlock(); } AREXPORT void ArCallbackList::setNameVar(const char *name, ...) { char arg[2048]; va_list ptr; va_start(ptr, name); vsnprintf(arg, sizeof(arg), name, ptr); arg[sizeof(arg) - 1] = '\0'; va_end(ptr); return setName(arg); } AREXPORT void ArCallbackList::setSingleShot(bool singleShot) { myDataMutex.lock(); mySingleShot = singleShot; myDataMutex.unlock(); } AREXPORT void ArCallbackList::setLogLevel(ArLog::LogLevel logLevel) { myDataMutex.lock(); myLogLevel = logLevel; myDataMutex.unlock(); } AREXPORT void ArCallbackList::invoke(void) { myDataMutex.lock(); std::multimap<int, ArFunctor *>::iterator it; ArFunctor *functor; ArLog::log(myLogLevel, "%s: Starting calls", myName.c_str()); for (it = myList.begin(); it != myList.end(); it++) { functor = (*it).second; if (functor == NULL) continue; if (functor->getName() != NULL && functor->getName()[0] != '\0') ArLog::log(myLogLevel, "%s: Calling functor '%s' at %d", myName.c_str(), functor->getName(), -(*it).first); else ArLog::log(myLogLevel, "%s: Calling unnamed functor at %d", myName.c_str(), -(*it).first); functor->invoke(); } ArLog::log(myLogLevel, "%s: Ended calls", myName.c_str()); if (mySingleShot) { ArLog::log(myLogLevel, "%s: Clearing callbacks", myName.c_str()); myList.clear(); } myDataMutex.unlock(); } #ifndef WIN32 /** @param baseDir the base directory to work from @param fileName the fileName to squash the case from @param result where to put the result @param resultLen length of the result @return true if it could find the file, the result is in result, false if it couldn't find the file **/ AREXPORT bool ArUtil::matchCase(const char *baseDir, const char *fileName, char *result, size_t resultLen) { /*** ArLog::log(ArLog::Normal, "ArUtil::matchCase() baseDir = \"%s\" fileName = \"%s\"", baseDir, fileName); ***/ DIR *dir; struct dirent *ent; char separator; #ifndef WIN32 separator = '/'; #else separator = '\\'; #endif result[0] = '\0'; std::list<std::string> split = splitFileName(fileName); std::list<std::string>::iterator it = split.begin(); std::string finding = (*it); /* for (it = split.begin(); it != split.end(); it++) { printf("@@@@@@@@ %s\n", (*it).c_str()); } */ // how this works is we start at the base dir then read through // until we find what the next name we need, if entry is a directory // and we're not at the end of our string list then we change into // that dir and the while loop keeps going, if the entry isn't a // directory and matchs and its the last in our string list we've // found what we want if ((dir = opendir(baseDir)) == NULL) { ArLog::log(ArLog::Normal, "ArUtil: No such directory '%s' for base", baseDir); return false; } if (finding == ".") { it++; if (it != split.end()) { finding = (*it); } else { ArLog::log(ArLog::Normal, "ArUtil: No file or directory given (base = %s file = %s)", baseDir, fileName); closedir(dir); // KMC NEED TO DETERMINE WHICH IS CORRECT. // The following change appears to be necessary for maps, but is still // undergoing testing.... // Just return the given ".". (This is necessary to find maps in the local // directory under some circumstances.) // snprintf(result, resultLen, finding.c_str()); // return true; return false; } } while ((ent = readdir(dir)) != NULL) { // ignore some of these if (ent->d_name[0] == '.') { //printf("Ignoring %s\n", ent->d_name[0]); continue; } //printf("NAME %s finding %s\n", ent->d_name, finding.c_str()); // we've found what we were looking for if (ArUtil::strcasecmp(ent->d_name, finding) == 0) { size_t lenOfResult; lenOfResult = strlen(result); // make sure we can put the filename in if (strlen(ent->d_name) > resultLen - lenOfResult - 2) { ArLog::log(ArLog::Normal, "ArUtil::matchCase: result not long enough"); closedir(dir); return false; } //printf("Before %s", result); if (lenOfResult != 0) { result[lenOfResult] = separator; result[lenOfResult+1] = '\0'; } // put the filename in strcpy(&result[strlen(result)], ent->d_name); //printf("after %s\n", result); // see if we're at the end it++; if (it != split.end()) { //printf("Um.........\n"); finding = (*it); std::string wholeDir; wholeDir = baseDir; wholeDir += result; closedir(dir); //printf("'%s' '%s' '%s'\n", baseDir, result, wholeDir.c_str()); if ((dir = opendir(wholeDir.c_str())) == NULL) { ArLog::log(ArLog::Normal, "ArUtil::matchCase: Error going into %s", result); return false; } } else { //printf("\n########## Got it %s\n", result); closedir(dir); return true; } } } ArLog::log(ArLog::Normal, "ArUtil::matchCase: %s doesn't exist in %s", fileName, baseDir); //printf("!!!!!!!! %s", finding.c_str()); closedir(dir); return false; } #endif // !WIN32 AREXPORT bool ArUtil::getDirectory(const char *fileName, char *result, size_t resultLen) { char separator; #ifndef WIN32 separator = '/'; #else separator = '\\'; #endif if (fileName == NULL || fileName[0] == '\0' || resultLen == 0) { ArLog::log(ArLog::Normal, "ArUtil: getDirectory, bad setup"); return false; } // just play in the result buffer strncpy(result, fileName, resultLen - 1); // make sure its nulled result[resultLen - 1] = '\0'; char *toPos; ArUtil::fixSlashes(result, resultLen); // see where the last directory is toPos = strrchr(result, separator); // if there's no divider it must just be a file name if (toPos == NULL) { result[0] = '\0'; return true; } // otherwise just toss a null into the last separator and we're done else { *toPos = '\0'; return true; } } AREXPORT bool ArUtil::getFileName(const char *fileName, char *result, size_t resultLen) { char separator; #ifndef WIN32 separator = '/'; #else separator = '\\'; #endif if (fileName == NULL || fileName[0] == '\0' || resultLen == 0) { ArLog::log(ArLog::Normal, "ArUtil: getFileName, bad setup"); return false; } char *str; size_t fileNameLen = strlen(fileName); str = new char[fileNameLen + 1]; //printf("0 %s\n", fileName); // just play in the result buffer strncpy(str, fileName, fileNameLen); // make sure its nulled str[fileNameLen] = '\0'; //printf("1 %s\n", str); char *toPos; ArUtil::fixSlashes(str, fileNameLen + 1); //printf("2 %s\n", str); // see where the last directory is toPos = strrchr(str, separator); // if there's no divider it must just be a file name if (toPos == NULL) { // copy the filename in and make sure it has a null strncpy(result, str, resultLen - 1); result[resultLen - 1] = '\0'; //printf("3 %s\n", result); delete[] str; return true; } // otherwise take the section from that separator to the end else { strncpy(result, &str[toPos - str + 1], resultLen - 2); result[resultLen - 1] = '\0'; //printf("4 %s\n", result); delete[] str; return true; } } #ifndef WIN32 /** This function assumes the slashes are all heading the right way already. **/ std::list<std::string> ArUtil::splitFileName(const char *fileName) { std::list<std::string> split; if (fileName == NULL) return split; char separator; #ifndef WIN32 separator = '/'; #else separator = '\\'; #endif size_t len; size_t i; size_t last; bool justSepped; char entry[2048]; for (i = 0, justSepped = false, last = 0, len = strlen(fileName); ; i++) { if ((fileName[i] == separator && !justSepped) || fileName[i] == '\0' || i >= len) { if (i - last > 2047) { ArLog::log(ArLog::Normal, "ArUtil::splitFileName: some directory or file too long"); } if (!justSepped) { strncpy(entry, &fileName[last], i - last); entry[i-last] = '\0'; split.push_back(entry); justSepped = true; } if (fileName[i] == '\0' || i >= len) return split; } else if (fileName[i] == separator && justSepped) { justSepped = true; last = i; } else if (fileName[i] != separator && justSepped) { justSepped = false; last = i; } } ArLog::log(ArLog::Normal, "ArUtil::splitFileName: file str ('%s') happened weird", fileName); return split; } #endif // !WIN32 AREXPORT bool ArUtil::changeFileTimestamp(const char *fileName, time_t timestamp) { if (ArUtil::isStrEmpty(fileName)) { ArLog::log(ArLog::Normal, "Cannot change date on file with empty name"); return false; } #ifdef WIN32 FILETIME fileTime; HANDLE hFile = CreateFile(fileName, GENERIC_READ | GENERIC_WRITE, 0,NULL, OPEN_EXISTING, 0,NULL); if (hFile == NULL) { return false; } // The following is extracted from the MSDN article "Converting a time_t Value // to a File Time". LONGLONG temp = Int32x32To64(timestamp, 10000000) + 116444736000000000; fileTime.dwLowDateTime = (DWORD) temp; fileTime.dwHighDateTime = temp >> 32; SetFileTime(hFile, &fileTime, (LPFILETIME) NULL, // don't change last access time (?) &fileTime); CloseHandle(hFile); #else // unix char timeBuf[500]; strftime(timeBuf, sizeof(timeBuf), "%c", ::localtime(&timestamp)); ArLog::log(ArLog::Normal, "Changing file %s modified time to %s", fileName, timeBuf); // time_t newTime = mktime(&timestamp); struct utimbuf fileTime; fileTime.actime = timestamp; fileTime.modtime = timestamp; utime(fileName, &fileTime); #endif // else unix return true; } // end method changeFileTimestamp AREXPORT void ArUtil::setFileCloseOnExec(int fd, bool closeOnExec) { #ifndef WIN32 if (fd <= 0) return; int flags; if ((flags = fcntl(fd, F_GETFD)) < 0) { ArLog::log(ArLog::Normal, "ArUtil::setFileCloseOnExec: Cannot use F_GETFD in fnctl on fd %d", fd); return; } if (closeOnExec) flags |= FD_CLOEXEC; else flags &= ~FD_CLOEXEC; if (fcntl(fd, F_SETFD, flags) < 0) { ArLog::log(ArLog::Normal, "ArUtil::setFileCloseOnExec: Cannot use F_GETFD in fnctl on fd %d", fd); return; } #endif } AREXPORT void ArUtil::setFileCloseOnExec(FILE *file, bool closeOnExec) { if (file != NULL) setFileCloseOnExec(fileno(file)); } AREXPORT FILE *ArUtil::fopen(const char *path, const char *mode, bool closeOnExec) { FILE *file; file = ::fopen(path, mode); setFileCloseOnExec(file, closeOnExec); return file; } AREXPORT int ArUtil::open(const char *pathname, int flags, bool closeOnExec) { int fd; fd = ::open(pathname, flags); setFileCloseOnExec(fd, closeOnExec); return fd; } AREXPORT int ArUtil::open(const char *pathname, int flags, mode_t mode, bool closeOnExec) { int fd; fd = ::open(pathname, flags, mode); setFileCloseOnExec(fd, closeOnExec); return fd; } AREXPORT int ArUtil::creat(const char *pathname, mode_t mode, bool closeOnExec) { int fd; fd = ::creat(pathname, mode); setFileCloseOnExec(fd, closeOnExec); return fd; } AREXPORT FILE *ArUtil::popen(const char *command, const char *type, bool closeOnExec) { FILE *file; #ifndef WIN32 file = ::popen(command, type); #else file = _popen(command, type); #endif setFileCloseOnExec(file, closeOnExec); return file; } AREXPORT bool ArUtil::floatIsNormal(double f) { #ifdef WIN32 return (!::_isnan(f) && ::_finite(f)); #else return isnormal(f); #endif } AREXPORT long ArMath::randomInRange(long m, long n) { // simple method return m + random() / (ourRandMax / (n - m + 1) + 1); // alternate method is to use drand48, multiply and round (does Windows have // drand48?), or keep trying numbers until we get one in range. } AREXPORT double ArMath::epsilon() { return ourEpsilon; } AREXPORT long ArMath::getRandMax() { return ourRandMax; } #ifndef ARINTERFACE ArGlobalRetFunctor2<ArLaser *, int, const char *> ArLaserCreatorHelper::ourLMS2xxCB(&ArLaserCreatorHelper::createLMS2xx); ArGlobalRetFunctor2<ArLaser *, int, const char *> ArLaserCreatorHelper::ourUrgCB(&ArLaserCreatorHelper::createUrg); ArGlobalRetFunctor2<ArLaser *, int, const char *> ArLaserCreatorHelper::ourLMS1XXCB(&ArLaserCreatorHelper::createLMS1XX); ArGlobalRetFunctor2<ArLaser *, int, const char *> ArLaserCreatorHelper::ourUrg_2_0CB(&ArLaserCreatorHelper::createUrg_2_0); ArLaser *ArLaserCreatorHelper::createLMS2xx(int laserNumber, const char *logPrefix) { return new ArLMS2xx(laserNumber); } ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateLMS2xxCB(void) { return &ourLMS2xxCB; } ArLaser *ArLaserCreatorHelper::createUrg(int laserNumber, const char *logPrefix) { return new ArUrg(laserNumber); } ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateUrgCB(void) { return &ourUrgCB; } ArLaser *ArLaserCreatorHelper::createLMS1XX(int laserNumber, const char *logPrefix) { return new ArLMS1XX(laserNumber); } ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateLMS1XXCB(void) { return &ourLMS1XXCB; } ArLaser *ArLaserCreatorHelper::createUrg_2_0(int laserNumber, const char *logPrefix) { return new ArUrg_2_0(laserNumber); } ArRetFunctor2<ArLaser *, int, const char *> *ArLaserCreatorHelper::getCreateUrg_2_0CB(void) { return &ourUrg_2_0CB; } #endif // ARINTERFACE ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *> ArDeviceConnectionCreatorHelper::ourSerialCB( &ArDeviceConnectionCreatorHelper::createSerialConnection); ArGlobalRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *> ArDeviceConnectionCreatorHelper::ourTcpCB( &ArDeviceConnectionCreatorHelper::createTcpConnection); ArLog::LogLevel ArDeviceConnectionCreatorHelper::ourSuccessLogLevel; ArDeviceConnection *ArDeviceConnectionCreatorHelper::createSerialConnection( const char *port, const char *defaultInfo, const char *logPrefix) { ArDeviceConnection *devConn; devConn = internalCreateSerialConnection(port, defaultInfo, logPrefix); return devConn; } ArDeviceConnection *ArDeviceConnectionCreatorHelper::internalCreateSerialConnection( const char *port, const char *defaultInfo, const char *logPrefix) { ArSerialConnection *serConn = new ArSerialConnection(); std::string serPort; if (strcasecmp(port, "COM1") == 0) serPort = ArUtil::COM1; else if (strcasecmp(port, "COM2") == 0) serPort = ArUtil::COM2; else if (strcasecmp(port, "COM3") == 0) serPort = ArUtil::COM3; else if (strcasecmp(port, "COM4") == 0) serPort = ArUtil::COM4; else if (strcasecmp(port, "COM5") == 0) serPort = ArUtil::COM5; else if (strcasecmp(port, "COM6") == 0) serPort = ArUtil::COM6; else if (strcasecmp(port, "COM7") == 0) serPort = ArUtil::COM7; else if (strcasecmp(port, "COM8") == 0) serPort = ArUtil::COM8; else if (strcasecmp(port, "COM9") == 0) serPort = ArUtil::COM9; else if (strcasecmp(port, "COM10") == 0) serPort = ArUtil::COM10; else if (strcasecmp(port, "COM11") == 0) serPort = ArUtil::COM11; else if (strcasecmp(port, "COM12") == 0) serPort = ArUtil::COM12; else if (strcasecmp(port, "COM13") == 0) serPort = ArUtil::COM13; else if (strcasecmp(port, "COM14") == 0) serPort = ArUtil::COM14; else if (strcasecmp(port, "COM15") == 0) serPort = ArUtil::COM15; else if (strcasecmp(port, "COM16") == 0) serPort = ArUtil::COM16; else if (port != NULL) serPort = port; ArLog::log(ourSuccessLogLevel, "%Set serial port to open %s", logPrefix, serPort.c_str()); serConn->setPort(serPort.c_str()); return serConn; /* This code is commented out because it created problems with demo (or any other program that used ArLaserConnector::connectLasers with addAllLasersToRobot as true) int ret; if ((ret = serConn->open(serPort.c_str())) == 0) { ArLog::log(ourSuccessLogLevel, "%sOpened serial port %s", logPrefix, serPort.c_str()); return serConn; } else { ArLog::log(ArLog::Normal, "%sCould not open serial port %s (from %s), because %s", logPrefix, serPort.c_str(), port, serConn->getOpenMessage(ret)); delete serConn; return NULL; } */ } ArRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *> * ArDeviceConnectionCreatorHelper::getCreateSerialCB(void) { return &ourSerialCB; } ArDeviceConnection *ArDeviceConnectionCreatorHelper::createTcpConnection( const char *port, const char *defaultInfo, const char *logPrefix) { ArTcpConnection *tcpConn = new ArTcpConnection; int ret; tcpConn->setPort(port, atoi(defaultInfo)); ArLog::log(ourSuccessLogLevel, "%sSet tcp connection to open %s (and port %d)", logPrefix, port, atoi(defaultInfo)); return tcpConn; /* This code is commented out because it created problems with demo (or any other program that used ArLaserConnector::connectLasers with addAllLasersToRobot as true) if ((ret = tcpConn->open(port, atoi(defaultInfo))) == 0) { ArLog::log(ourSuccessLogLevel, "%sOpened tcp connection from %s (and port %d)", logPrefix, port, atoi(defaultInfo)); return tcpConn; } else { ArLog::log(ArLog::Normal, "%sCould not open a tcp connection to host '%s' with default port %d (from '%s'), because %s", logPrefix, port, atoi(defaultInfo), defaultInfo, tcpConn->getOpenMessage(ret)); delete tcpConn; return NULL; } */ } ArRetFunctor3<ArDeviceConnection *, const char *, const char *, const char *> * ArDeviceConnectionCreatorHelper::getCreateTcpCB(void) { return &ourTcpCB; } void ArDeviceConnectionCreatorHelper::setSuccessLogLevel( ArLog::LogLevel successLogLevel) { ourSuccessLogLevel = successLogLevel; } ArLog::LogLevel ArDeviceConnectionCreatorHelper::setSuccessLogLevel(void) { return ourSuccessLogLevel; }
25.3587
134
0.647777
rzsavilla
33f7c9daf4599356166825b3a4a5694d2668467c
1,679
cpp
C++
test/deduce_scalar_mv_test.cpp
boostorg/boost-qvm
5791440b346232c391ab8d16f559ca5b2d7ae9b3
[ "BSL-1.0" ]
null
null
null
test/deduce_scalar_mv_test.cpp
boostorg/boost-qvm
5791440b346232c391ab8d16f559ca5b2d7ae9b3
[ "BSL-1.0" ]
null
null
null
test/deduce_scalar_mv_test.cpp
boostorg/boost-qvm
5791440b346232c391ab8d16f559ca5b2d7ae9b3
[ "BSL-1.0" ]
null
null
null
// Copyright 2008-2022 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifdef BOOST_QVM_TEST_SINGLE_HEADER # include BOOST_QVM_TEST_SINGLE_HEADER #else # include <boost/qvm/deduce_scalar.hpp> # include <boost/qvm/mat.hpp> # include <boost/qvm/mat_operations.hpp> # include <boost/qvm/vec.hpp> # include <boost/qvm/vec_mat_operations3.hpp> #endif #include <boost/core/lightweight_test.hpp> template <class T> struct wrap { T t; wrap() { } explicit wrap(T t):t(t) { } }; template <class S, class T> wrap<T> operator*(S s, wrap<T> w) { return wrap<T>(s * w.t); } template <class T> wrap<T> operator+(wrap<T> a, wrap<T> b) { return wrap<T>(a.t + b.t); } namespace boost { namespace qvm { template <class T> struct is_scalar<wrap<T> > { static bool const value=true; }; template <class S, class T> struct deduce_scalar<S, wrap<T> > { typedef wrap<typename deduce_scalar<S, T>::type> type; }; } } int main() { using namespace boost::qvm; mat<double, 3, 3> m = rotz_mat<3>(3.14159); vec<wrap<double>, 3> v; v.a[0] = wrap<double>(1.0); v.a[1] = wrap<double>(0); v.a[2] = wrap<double>(0); vec<wrap<double>, 3> r = m * v; BOOST_TEST_LT(fabs(r.a[0].t+1), 0.0001); BOOST_TEST_LT(fabs(r.a[1].t), 0.0001); BOOST_TEST_LT(fabs(r.a[2].t), 0.0001); return boost::report_errors(); }
22.092105
79
0.585468
boostorg
33f955f4b7b40f59688a1a7f87cf362aee8d0523
468
cpp
C++
src/Subpackets/Tag2Sub28.cpp
mugwort-rc/pyOpenPGP
a1d35a93a69ed5bbec768f3c6347742630d71a15
[ "MIT" ]
null
null
null
src/Subpackets/Tag2Sub28.cpp
mugwort-rc/pyOpenPGP
a1d35a93a69ed5bbec768f3c6347742630d71a15
[ "MIT" ]
null
null
null
src/Subpackets/Tag2Sub28.cpp
mugwort-rc/pyOpenPGP
a1d35a93a69ed5bbec768f3c6347742630d71a15
[ "MIT" ]
null
null
null
#include <boost/python.hpp> #include "OpenPGP/Subpackets/Tag2Sub28.h" void Tag2Sub28_init() { boost::python::class_<Tag2Sub28, boost::python::bases<Tag2Subpacket>>("Tag2Sub28") .def(boost::python::init<std::string &>()) .def("read", &Tag2Sub28::read) .def("show", &Tag2Sub28::show) .def("raw", &Tag2Sub28::raw) .def("get_signer", &Tag2Sub28::get_signer) .def("set_signer", &Tag2Sub28::set_signer) .def("clone", &Tag2Sub28::clone) ; }
27.529412
82
0.65812
mugwort-rc
33f9c11b20cdbf2983f795564136aa8d1fdf4bcf
332
cc
C++
PhysicsTools/JetMCAlgos/src/BasePartonSelector.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
PhysicsTools/JetMCAlgos/src/BasePartonSelector.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
PhysicsTools/JetMCAlgos/src/BasePartonSelector.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "PhysicsTools/JetMCAlgos/interface/BasePartonSelector.h" BasePartonSelector::BasePartonSelector() {} BasePartonSelector::~BasePartonSelector() {} void BasePartonSelector::run(const edm::Handle<reco::GenParticleCollection>& particles, std::unique_ptr<reco::GenParticleRefVector>& partons) {}
36.888889
87
0.740964
ckamtsikis
33facceab40746a6a205d13aaa958b7e1675ca04
1,047
cpp
C++
topic_wise/arrays/CountandSay.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
topic_wise/arrays/CountandSay.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
topic_wise/arrays/CountandSay.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/*The count-and-say sequence is the sequence of integers with the first five terms as following: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. Note: Each term of the sequence of integers will be represented as a string. Example 1: Input: 1 Output: "1" Example 2: Input: 4 Output: "1211"*/ class Solution { public: string countAndSay(int n) { if (n == 1) { return "1"; } else if (n == 2) { return "11"; } else { string s = countAndSay(n - 1); string n{}; int c = 1; for (int i = 0; i < s.size(); i++) { if (i + 1 < s.size() and s[i] == s[i + 1]) { c++; } else { char num = c + '0'; n += string{num} + string{s[i]}; c = 1; } } return n; } } };
19.754717
80
0.494747
archit-1997
33faec5db7f5f4242cdf3e7e164458fa1e7105c6
2,006
cpp
C++
src/iq_neuron.cpp
twetto/iq-neuron
dad804c61001ffcaa5578ec9e7531eeec4952188
[ "MIT" ]
4
2019-10-18T10:01:01.000Z
2020-07-17T03:43:48.000Z
src/iq_neuron.cpp
twetto/iq-neuron
dad804c61001ffcaa5578ec9e7531eeec4952188
[ "MIT" ]
1
2019-10-25T08:35:27.000Z
2019-10-28T05:06:55.000Z
src/iq_neuron.cpp
twetto/iq-neuron
dad804c61001ffcaa5578ec9e7531eeec4952188
[ "MIT" ]
3
2019-07-29T09:21:11.000Z
2021-08-28T14:25:13.000Z
/* IQIF neuron object * Chen-Fu Yeh, 2019/11/09 */ #include "iq_neuron.h" using namespace std; iq_neuron::iq_neuron(int rest, int threshold, int reset, int a, int b, int noise) { x = rest; // initialize with rest potential t_neuron = 0; f_min = (a*rest + b*threshold) / (a+b); // dV/dt and others _a = a; _b = b; _rest = rest; _threshold = threshold; _reset = reset; if(noise == 0) noise++; // set noise strength else if(noise < 0) noise = -noise; _noise = noise; _is_set = true; return; } bool iq_neuron::is_set() { return _is_set; } void iq_neuron::set(int rest, int threshold, int reset, int a, int b, int noise) { x = rest; t_neuron = 0; f_min = (a*rest + b*threshold) / (a+b); _a = a; _b = b; _rest = rest; _threshold = threshold; _reset = reset; if(noise == 0) noise++; else if(noise < 0) noise = -noise; _noise = noise; _is_set = true; return; } void iq_neuron::set_vmax(int vmax) { VMAX = vmax; return; } void iq_neuron::set_vmin(int vmin) { VMIN = vmin; return; } void iq_neuron::iq(int external_current) { int f; /* solving dV/dt */ if(x < f_min) f = _a * (_rest - x); else f = _b * (x - _threshold); x += (f >> 3) + external_current + rand()%_noise - (_noise >> 1); /* fire if exceeding action potential */ _is_firing = false; if(x > VMAX) { _spike_count++; _is_firing = true; x = _reset; } else if(x < VMIN) x = VMIN; t_neuron++; return; } int iq_neuron::potential() { return x; } bool iq_neuron::is_firing() { return _is_firing; } int iq_neuron::spike_count() { int count = _spike_count; _spike_count = 0; return count; } float iq_neuron::spike_rate() { float r = _spike_count / (float) t_neuron; t_neuron = 0; _spike_count = 0; return r; }
18.236364
77
0.547856
twetto
33faf880222e95dd8e9e2bcc92642906a952bb73
23,412
cpp
C++
src/divvy/app/paths/cursor/ReverseLiquidityForAccount.cpp
coinjet/rippled
33963ff958596346ba4c3f8236c99aa54e32b826
[ "BSL-1.0" ]
null
null
null
src/divvy/app/paths/cursor/ReverseLiquidityForAccount.cpp
coinjet/rippled
33963ff958596346ba4c3f8236c99aa54e32b826
[ "BSL-1.0" ]
null
null
null
src/divvy/app/paths/cursor/ReverseLiquidityForAccount.cpp
coinjet/rippled
33963ff958596346ba4c3f8236c99aa54e32b826
[ "BSL-1.0" ]
null
null
null
//------------------------------------------------------------------------------ /* This file is part of divvyd: https://github.com/xdv/divvyd Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <BeastConfig.h> #include <divvy/protocol/Quality.h> #include <divvy/app/paths/Credit.h> #include <divvy/app/paths/cursor/DivvyLiquidity.h> #include <divvy/basics/Log.h> namespace divvy { namespace path { // Calculate saPrvRedeemReq, saPrvIssueReq, saPrvDeliver from saCur, based on // required deliverable, propagate redeem, issue (for accounts) and deliver // requests (for order books) to the previous node. // // Inflate amount requested by required fees. // Reedems are limited based on IOUs previous has on hand. // Issues are limited based on credit limits and amount owed. // // Currency cannot be XDV because we are rippling. // // No permanent account balance adjustments as we don't know how much is going // to actually be pushed through yet - changes are only in the scratch pad // ledger. // // <-- tesSUCCESS or tecPATH_DRY TER PathCursor::reverseLiquidityForAccount () const { TER terResult = tesSUCCESS; auto const lastNodeIndex = nodeSize () - 1; auto const isFinalNode = (nodeIndex_ == lastNodeIndex); // 0 quality means none has yet been determined. std::uint64_t uRateMax = 0 ; // Current is allowed to redeem to next. const bool previousNodeIsAccount = !nodeIndex_ || previousNode().isAccount(); const bool nextNodeIsAccount = isFinalNode || nextNode().isAccount(); AccountID const& previousAccountID = previousNodeIsAccount ? previousNode().account_ : node().account_; AccountID const& nextAccountID = nextNodeIsAccount ? nextNode().account_ : node().account_; // Offers are always issue. // This is the quality from from the previous node to this one. const std::uint32_t uQualityIn = (nodeIndex_ != 0) ? quality_in (ledger(), node().account_, previousAccountID, node().issue_.currency) : QUALITY_ONE; // And this is the quality from the next one to this one. const std::uint32_t uQualityOut = (nodeIndex_ != lastNodeIndex) ? quality_out (ledger(), node().account_, nextAccountID, node().issue_.currency) : QUALITY_ONE; // For previousNodeIsAccount: // Previous account is already owed. const STAmount saPrvOwed = (previousNodeIsAccount && nodeIndex_ != 0) ? creditBalance (ledger(), node().account_, previousAccountID, node().issue_.currency) : STAmount (node().issue_); // The limit amount that the previous account may owe. const STAmount saPrvLimit = (previousNodeIsAccount && nodeIndex_ != 0) ? creditLimit (ledger(), node().account_, previousAccountID, node().issue_.currency) : STAmount (node().issue_); // Next account is owed. const STAmount saNxtOwed = (nextNodeIsAccount && nodeIndex_ != lastNodeIndex) ? creditBalance (ledger(), node().account_, nextAccountID, node().issue_.currency) : STAmount (node().issue_); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount>" << " nodeIndex_=" << nodeIndex_ << "/" << lastNodeIndex << " previousAccountID=" << previousAccountID << " node.account_=" << node().account_ << " nextAccountID=" << nextAccountID << " currency=" << node().issue_.currency << " uQualityIn=" << uQualityIn << " uQualityOut=" << uQualityOut << " saPrvOwed=" << saPrvOwed << " saPrvLimit=" << saPrvLimit; // Requests are computed to be the maximum flow possible. // Previous can redeem the owed IOUs it holds. const STAmount saPrvRedeemReq = (saPrvOwed > zero) ? saPrvOwed : STAmount (saPrvOwed.issue ()); // Previous can issue up to limit minus whatever portion of limit already // used (not including redeemable amount) - another "maximum flow". const STAmount saPrvIssueReq = (saPrvOwed < zero) ? saPrvLimit + saPrvOwed : saPrvLimit; // Precompute these values in case we have an order book. auto deliverCurrency = previousNode().saRevDeliver.getCurrency (); const STAmount saPrvDeliverReq ( {deliverCurrency, previousNode().saRevDeliver.getIssuer ()}, -1); // -1 means unlimited delivery. // Set to zero, because we're trying to hit the previous node. auto saCurRedeemAct = node().saRevRedeem.zeroed(); // Track the amount we actually redeem. auto saCurIssueAct = node().saRevIssue.zeroed(); // For !nextNodeIsAccount auto saCurDeliverAct = node().saRevDeliver.zeroed(); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount:" << " saPrvRedeemReq:" << saPrvRedeemReq << " saPrvIssueReq:" << saPrvIssueReq << " previousNode.saRevDeliver:" << previousNode().saRevDeliver << " saPrvDeliverReq:" << saPrvDeliverReq << " node.saRevRedeem:" << node().saRevRedeem << " node.saRevIssue:" << node().saRevIssue << " saNxtOwed:" << saNxtOwed; // VFALCO-FIXME this generates errors //WriteLog (lsTRACE, DivvyCalc) << pathState_.getJson (); // Current redeem req can't be more than IOUs on hand. assert (!node().saRevRedeem || -saNxtOwed >= node().saRevRedeem); assert (!node().saRevIssue // If not issuing, fine. || saNxtOwed >= zero // saNxtOwed >= 0: Sender not holding next IOUs, saNxtOwed < 0: // Sender holding next IOUs. || -saNxtOwed == node().saRevRedeem); // If issue req, then redeem req must consume all owed. if (nodeIndex_ == 0) { // ^ --> ACCOUNT --> account|offer // Nothing to do, there is no previous to adjust. // // TODO(tom): we could have skipped all that setup and just left // or even just never call this whole routine on nodeIndex_ = 0! } // The next four cases correspond to the table at the bottom of this Wiki // page section: https://xdv.io/wiki/Transit_Fees#Implementation else if (previousNodeIsAccount && nextNodeIsAccount) { if (isFinalNode) { // account --> ACCOUNT --> $ // Overall deliverable. const STAmount saCurWantedReq = std::min ( pathState_.outReq() - pathState_.outAct(), saPrvLimit + saPrvOwed); auto saCurWantedAct = saCurWantedReq.zeroed (); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: account --> " << "ACCOUNT --> $ :" << " saCurWantedReq=" << saCurWantedReq; // Calculate redeem if (saPrvRedeemReq) // Previous has IOUs to redeem. { // Redeem your own IOUs at 1:1 saCurWantedAct = std::min (saPrvRedeemReq, saCurWantedReq); previousNode().saRevRedeem = saCurWantedAct; uRateMax = STAmount::uRateOne; WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: Redeem at 1:1" << " saPrvRedeemReq=" << saPrvRedeemReq << " (available) previousNode.saRevRedeem=" << previousNode().saRevRedeem << " uRateMax=" << amountFromRate (uRateMax).getText (); } else { previousNode().saRevRedeem.clear (saPrvRedeemReq); } // Calculate issuing. previousNode().saRevIssue.clear (saPrvIssueReq); if (saCurWantedReq != saCurWantedAct // Need more. && saPrvIssueReq) // Will accept IOUs from previous. { // Rate: quality in : 1.0 // If we previously redeemed and this has a poorer rate, this // won't be included the current increment. divvyLiquidity ( divvyCalc_, uQualityIn, QUALITY_ONE, saPrvIssueReq, saCurWantedReq, previousNode().saRevIssue, saCurWantedAct, uRateMax); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: Issuing: Rate: " << "quality in : 1.0" << " previousNode.saRevIssue:" << previousNode().saRevIssue << " saCurWantedAct:" << saCurWantedAct; } if (!saCurWantedAct) { // Must have processed something. terResult = tecPATH_DRY; } } else { // Not final node. // account --> ACCOUNT --> account previousNode().saRevRedeem.clear (saPrvRedeemReq); previousNode().saRevIssue.clear (saPrvIssueReq); // redeem (part 1) -> redeem if (node().saRevRedeem // Next wants IOUs redeemed from current account. && saPrvRedeemReq) // Previous has IOUs to redeem to the current account. { // TODO(tom): add English. // Rate : 1.0 : quality out - we must accept our own IOUs // as 1:1. divvyLiquidity ( divvyCalc_, QUALITY_ONE, uQualityOut, saPrvRedeemReq, node().saRevRedeem, previousNode().saRevRedeem, saCurRedeemAct, uRateMax); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "Rate : 1.0 : quality out" << " previousNode.saRevRedeem:" << previousNode().saRevRedeem << " saCurRedeemAct:" << saCurRedeemAct; } // issue (part 1) -> redeem if (node().saRevRedeem != saCurRedeemAct // The current node has more IOUs to redeem. && previousNode().saRevRedeem == saPrvRedeemReq) // The previous node has no IOUs to redeem remaining, so issues. { // Rate: quality in : quality out divvyLiquidity ( divvyCalc_, uQualityIn, uQualityOut, saPrvIssueReq, node().saRevRedeem, previousNode().saRevIssue, saCurRedeemAct, uRateMax); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "Rate: quality in : quality out:" << " previousNode.saRevIssue:" << previousNode().saRevIssue << " saCurRedeemAct:" << saCurRedeemAct; } // redeem (part 2) -> issue. if (node().saRevIssue // Next wants IOUs issued. // TODO(tom): this condition seems redundant. && saCurRedeemAct == node().saRevRedeem // Can only issue if completed redeeming. && previousNode().saRevRedeem != saPrvRedeemReq) // Did not complete redeeming previous IOUs. { // Rate : 1.0 : transfer_rate divvyLiquidity ( divvyCalc_, QUALITY_ONE, divvyTransferRate (ledger(), node().account_), saPrvRedeemReq, node().saRevIssue, previousNode().saRevRedeem, saCurIssueAct, uRateMax); WriteLog (lsDEBUG, DivvyCalc) << "reverseLiquidityForAccount: " << "Rate : 1.0 : transfer_rate:" << " previousNode.saRevRedeem:" << previousNode().saRevRedeem << " saCurIssueAct:" << saCurIssueAct; } // issue (part 2) -> issue if (node().saRevIssue != saCurIssueAct // Need wants more IOUs issued. && saCurRedeemAct == node().saRevRedeem // Can only issue if completed redeeming. && saPrvRedeemReq == previousNode().saRevRedeem // Previously redeemed all owed IOUs. && saPrvIssueReq) // Previous can issue. { // Rate: quality in : 1.0 divvyLiquidity ( divvyCalc_, uQualityIn, QUALITY_ONE, saPrvIssueReq, node().saRevIssue, previousNode().saRevIssue, saCurIssueAct, uRateMax); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "Rate: quality in : 1.0:" << " previousNode.saRevIssue:" << previousNode().saRevIssue << " saCurIssueAct:" << saCurIssueAct; } if (!saCurRedeemAct && !saCurIssueAct) { // Did not make progress. terResult = tecPATH_DRY; } WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "^|account --> ACCOUNT --> account :" << " node.saRevRedeem:" << node().saRevRedeem << " node.saRevIssue:" << node().saRevIssue << " saPrvOwed:" << saPrvOwed << " saCurRedeemAct:" << saCurRedeemAct << " saCurIssueAct:" << saCurIssueAct; } } else if (previousNodeIsAccount && !nextNodeIsAccount) { // account --> ACCOUNT --> offer // Note: deliver is always issue as ACCOUNT is the issuer for the offer // input. WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "account --> ACCOUNT --> offer"; previousNode().saRevRedeem.clear (saPrvRedeemReq); previousNode().saRevIssue.clear (saPrvIssueReq); // We have three cases: the nxt offer can be owned by current account, // previous account or some third party account. // // Also, the current account may or may not have a redeemable balance // with the account for the next offer, so we don't yet know if we're // redeeming or issuing. // // TODO(tom): Make sure deliver was cleared, or check actual is zero. // redeem -> deliver/issue. if (saPrvOwed > zero // Previous has IOUs to redeem. && node().saRevDeliver) // Need some issued. { // Rate : 1.0 : transfer_rate divvyLiquidity ( divvyCalc_, QUALITY_ONE, divvyTransferRate (ledger(), node().account_), saPrvRedeemReq, node().saRevDeliver, previousNode().saRevRedeem, saCurDeliverAct, uRateMax); } // issue -> deliver/issue if (saPrvRedeemReq == previousNode().saRevRedeem // Previously redeemed all owed. && node().saRevDeliver != saCurDeliverAct) // Still need some issued. { // Rate: quality in : 1.0 divvyLiquidity ( divvyCalc_, uQualityIn, QUALITY_ONE, saPrvIssueReq, node().saRevDeliver, previousNode().saRevIssue, saCurDeliverAct, uRateMax); } if (!saCurDeliverAct) { // Must want something. terResult = tecPATH_DRY; } WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << " node.saRevDeliver:" << node().saRevDeliver << " saCurDeliverAct:" << saCurDeliverAct << " saPrvOwed:" << saPrvOwed; } else if (!previousNodeIsAccount && nextNodeIsAccount) { if (isFinalNode) { // offer --> ACCOUNT --> $ // Previous is an offer, no limit: redeem own IOUs. // // This is the final node; we can't look to the right to get values; // we have to go up to get the out value for the entire path state. STAmount const& saCurWantedReq = pathState_.outReq() - pathState_.outAct(); STAmount saCurWantedAct = saCurWantedReq.zeroed(); WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "offer --> ACCOUNT --> $ :" << " saCurWantedReq:" << saCurWantedReq << " saOutAct:" << pathState_.outAct() << " saOutReq:" << pathState_.outReq(); if (saCurWantedReq <= zero) { // TEMPORARY emergency fix // // TODO(tom): why can't saCurWantedReq be -1 if you want to // compute maximum liquidity? This might be unimplemented // functionality. TODO(tom): should the same check appear in // other paths or even be pulled up? WriteLog (lsFATAL, DivvyCalc) << "CurWantReq was not positive"; return tefEXCEPTION; } assert (saCurWantedReq > zero); // FIXME: We got one of these // The previous node is an offer; we are receiving our own currency. // The previous order book's entries might hold our issuances; might // not hold our issuances; might be our own offer. // // Assume the worst case, the case which costs the most to go // through, which is that it is not our own offer or our own // issuances. Later on the forward pass we may be able to do // better. // // TODO: this comment applies generally to this section - move it up // to a document. // Rate: quality in : 1.0 divvyLiquidity ( divvyCalc_, uQualityIn, QUALITY_ONE, saPrvDeliverReq, saCurWantedReq, previousNode().saRevDeliver, saCurWantedAct, uRateMax); if (!saCurWantedAct) { // Must have processed something. terResult = tecPATH_DRY; } WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount:" << " previousNode().saRevDeliver:" << previousNode().saRevDeliver << " saPrvDeliverReq:" << saPrvDeliverReq << " saCurWantedAct:" << saCurWantedAct << " saCurWantedReq:" << saCurWantedReq; } else { // offer --> ACCOUNT --> account // Note: offer is always delivering(redeeming) as account is issuer. WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: " << "offer --> ACCOUNT --> account :" << " node.saRevRedeem:" << node().saRevRedeem << " node.saRevIssue:" << node().saRevIssue; // deliver -> redeem // TODO(tom): now we have more checking in nodeDivvy, these checks // might be redundant. if (node().saRevRedeem) // Next wants us to redeem. { // cur holds IOUs from the account to the right, the nxt // account. If someone is making the current account get rid of // the nxt account's IOUs, then charge the input for quality // out. // // Rate : 1.0 : quality out divvyLiquidity ( divvyCalc_, QUALITY_ONE, uQualityOut, saPrvDeliverReq, node().saRevRedeem, previousNode().saRevDeliver, saCurRedeemAct, uRateMax); } // deliver -> issue. if (node().saRevRedeem == saCurRedeemAct // Can only issue if previously redeemed all. && node().saRevIssue) // Need some issued. { // Rate : 1.0 : transfer_rate divvyLiquidity ( divvyCalc_, QUALITY_ONE, divvyTransferRate (ledger(), node().account_), saPrvDeliverReq, node().saRevIssue, previousNode().saRevDeliver, saCurIssueAct, uRateMax); } WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount:" << " saCurRedeemAct:" << saCurRedeemAct << " node.saRevRedeem:" << node().saRevRedeem << " previousNode.saRevDeliver:" << previousNode().saRevDeliver << " node.saRevIssue:" << node().saRevIssue; if (!previousNode().saRevDeliver) { // Must want something. terResult = tecPATH_DRY; } } } else { // offer --> ACCOUNT --> offer // deliver/redeem -> deliver/issue. WriteLog (lsTRACE, DivvyCalc) << "reverseLiquidityForAccount: offer --> ACCOUNT --> offer"; // Rate : 1.0 : transfer_rate divvyLiquidity ( divvyCalc_, QUALITY_ONE, divvyTransferRate (ledger(), node().account_), saPrvDeliverReq, node().saRevDeliver, previousNode().saRevDeliver, saCurDeliverAct, uRateMax); if (!saCurDeliverAct) { // Must want something. terResult = tecPATH_DRY; } } return terResult; } } // path } // divvy
38.570016
82
0.524475
coinjet
33fbb210810bab91e3e5e5281a19e74822a79a9e
44,258
cpp
C++
src/Widgets/MultiVarTransferFunctionWindow.cpp
FelixBrendel/LineVis
428cf82328ba3d3ac9435f3df765330149d4a921
[ "Apache-2.0" ]
null
null
null
src/Widgets/MultiVarTransferFunctionWindow.cpp
FelixBrendel/LineVis
428cf82328ba3d3ac9435f3df765330149d4a921
[ "Apache-2.0" ]
null
null
null
src/Widgets/MultiVarTransferFunctionWindow.cpp
FelixBrendel/LineVis
428cf82328ba3d3ac9435f3df765330149d4a921
[ "Apache-2.0" ]
null
null
null
/* * BSD 2-Clause License * * Copyright (c) 2020, Christoph Neuhauser * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <cmath> #ifdef __linux__ #include <sys/inotify.h> #include <poll.h> #endif #include <GL/glew.h> #include <glm/glm.hpp> #define IMGUI_DEFINE_MATH_OPERATORS #include <ImGui/imgui.h> #include <ImGui/imgui_internal.h> #include <ImGui/imgui_custom.h> #include <ImGui/imgui_stdlib.h> #include <Utils/AppSettings.hpp> #include <Utils/XML.hpp> #include <Utils/File/Logfile.hpp> #include <Utils/File/FileUtils.hpp> #include <Math/Math.hpp> #include <Graphics/Renderer.hpp> #include <Graphics/Texture/TextureManager.hpp> #ifdef SUPPORT_VULKAN #include <Graphics/Vulkan/Buffers/Buffer.hpp> #endif #include "MultiVarTransferFunctionWindow.hpp" using namespace tinyxml2; const size_t TRANSFER_FUNCTION_TEXTURE_SIZE = 256; GuiVarData::GuiVarData( MultiVarTransferFunctionWindow* window, const std::string& tfPresetFile, sgl::Color16* transferFunctionMap_sRGB, sgl::Color16* transferFunctionMap_linearRGB) { this->window = window; this->transferFunctionMap_sRGB = transferFunctionMap_sRGB; this->transferFunctionMap_linearRGB = transferFunctionMap_linearRGB; std::string tfFileName = window->saveDirectory + tfPresetFile; const std::string stdFileName = window->saveDirectory + "Standard.xml"; if (tfFileName.empty() || !sgl::FileUtils::get()->exists(tfFileName)) { tfFileName = stdFileName; } if (sgl::FileUtils::get()->exists(tfFileName)) { loadTfFromFile(tfFileName); } else { colorPoints = { sgl::ColorPoint_sRGB(sgl::Color(59, 76, 192), 0.0f), sgl::ColorPoint_sRGB(sgl::Color(144, 178, 254), 0.25f), sgl::ColorPoint_sRGB(sgl::Color(220, 220, 220), 0.5f), sgl::ColorPoint_sRGB(sgl::Color(245, 156, 125), 0.75f), sgl::ColorPoint_sRGB(sgl::Color(180, 4, 38), 1.0f) }; opacityPoints = { sgl::OpacityPoint(1.0f, 0.0f), sgl::OpacityPoint(1.0f, 1.0f) }; } } bool GuiVarData::saveTfToFile(const std::string& filename) { FILE* file = fopen(filename.c_str(), "w"); if (file == NULL) { sgl::Logfile::get()->writeError( std::string() + "ERROR: MultiVarTransferFunctionWindow::saveFunctionToFile: Couldn't create file \"" + filename + "\"!"); return false; } XMLPrinter printer(file); printer.OpenElement("TransferFunction"); printer.PushAttribute("colorspace", "sRGB"); // Currently only sRGB supported for points printer.PushAttribute("interpolation_colorspace", sgl::COLOR_SPACE_NAMES[interpolationColorSpace]); printer.OpenElement("OpacityPoints"); // Traverse all opacity points for (size_t i = 0; i < opacityPoints.size(); i++) { printer.OpenElement("OpacityPoint"); printer.PushAttribute("position", opacityPoints.at(i).position); printer.PushAttribute("opacity", opacityPoints.at(i).opacity); printer.CloseElement(); } printer.CloseElement(); printer.OpenElement("ColorPoints"); printer.PushAttribute("color_data", sgl::COLOR_DATA_MODE_NAMES[int(sgl::COLOR_DATA_MODE_UNSIGNED_SHORT)]); // Traverse all color points for (size_t i = 0; i < colorPoints.size(); i++) { printer.OpenElement("ColorPoint"); printer.PushAttribute("position", colorPoints.at(i).position); printer.PushAttribute("r", (int)colorPoints.at(i).color.getR()); printer.PushAttribute("g", (int)colorPoints.at(i).color.getG()); printer.PushAttribute("b", (int)colorPoints.at(i).color.getB()); printer.CloseElement(); } printer.CloseElement(); printer.CloseElement(); fclose(file); return true; } bool GuiVarData::loadTfFromFile(const std::string& filename) { XMLDocument doc; if (doc.LoadFile(filename.c_str()) != 0) { sgl::Logfile::get()->writeError( std::string() + "MultiVarTransferFunctionWindow::loadFunctionFromFile: Couldn't open file \"" + filename + "\"!"); return false; } XMLElement* tfNode = doc.FirstChildElement("TransferFunction"); if (tfNode == nullptr) { sgl::Logfile::get()->writeError( "MultiVarTransferFunctionWindow::loadFunctionFromFile: No \"TransferFunction\" node found!"); return false; } interpolationColorSpace = sgl::COLOR_SPACE_SRGB; // Standard const char* interpolationColorSpaceName = tfNode->Attribute("colorspace_interpolation"); if (interpolationColorSpaceName != nullptr) { for (int i = 0; i < 2; i++) { if (strcmp(interpolationColorSpaceName, sgl::COLOR_SPACE_NAMES[interpolationColorSpace]) == 0) { interpolationColorSpace = (sgl::ColorSpace)i; } } } colorPoints.clear(); opacityPoints.clear(); // Traverse all opacity points auto opacityPointsNode = tfNode->FirstChildElement("OpacityPoints"); if (opacityPointsNode != nullptr) { for (sgl::XMLIterator it(opacityPointsNode, sgl::XMLNameFilter("OpacityPoint")); it.isValid(); ++it) { XMLElement* childElement = *it; float position = childElement->FloatAttribute("position"); float opacity = sgl::clamp(childElement->FloatAttribute("opacity"), 0.0f, 1.0f); opacityPoints.emplace_back(opacity, position); } } // Traverse all color points auto colorPointsNode = tfNode->FirstChildElement("ColorPoints"); if (colorPointsNode != nullptr) { sgl::ColorDataMode colorDataMode = sgl::COLOR_DATA_MODE_UNSIGNED_BYTE; const char* colorDataModeName = colorPointsNode->Attribute("color_data"); if (colorDataModeName != nullptr) { colorDataMode = sgl::parseColorDataModeName(colorDataModeName); } for (sgl::XMLIterator it(colorPointsNode, sgl::XMLNameFilter("ColorPoint")); it.isValid(); ++it) { XMLElement* childElement = *it; sgl::Color16 color; float position = childElement->FloatAttribute("position"); if (colorDataMode == sgl::COLOR_DATA_MODE_UNSIGNED_BYTE) { int red = sgl::clamp(childElement->IntAttribute("r"), 0, 255); int green = sgl::clamp(childElement->IntAttribute("g"), 0, 255); int blue = sgl::clamp(childElement->IntAttribute("b"), 0, 255); color = sgl::Color(red, green, blue); } else if (colorDataMode == sgl::COLOR_DATA_MODE_UNSIGNED_SHORT) { int red = sgl::clamp(childElement->IntAttribute("r"), 0, 65535); int green = sgl::clamp(childElement->IntAttribute("g"), 0, 65535); int blue = sgl::clamp(childElement->IntAttribute("b"), 0, 65535); color = sgl::Color16(red, green, blue); } else if (colorDataMode == sgl::COLOR_DATA_MODE_FLOAT_NORMALIZED) { float red = sgl::clamp(childElement->FloatAttribute("r"), 0.0f, 1.0f); float green = sgl::clamp(childElement->FloatAttribute("g"), 0.0f, 1.0f); float blue = sgl::clamp(childElement->FloatAttribute("b"), 0.0f, 1.0f); color = sgl::Color16(glm::vec3(red, green, blue)); } else if (colorDataMode == sgl::COLOR_DATA_MODE_FLOAT_255) { float red = sgl::clamp(childElement->FloatAttribute("r"), 0.0f, 255.0f) / 255.0f; float green = sgl::clamp(childElement->FloatAttribute("g"), 0.0f, 255.0f) / 255.0f; float blue = sgl::clamp(childElement->FloatAttribute("b"), 0.0f, 255.0f) / 255.0f; color = sgl::Color16(glm::vec3(red, green, blue)); } colorPoints.emplace_back(color, position); } } selectedPointType = sgl::SELECTED_POINT_TYPE_NONE; rebuildTransferFunctionMap(); return true; } void GuiVarData::setAttributeValues(const std::string& name, const std::vector<float>& attributes) { attributeName = name; this->attributes = attributes; float minAttr = std::numeric_limits<float>::max(); float maxAttr = std::numeric_limits<float>::lowest(); #if _OPENMP >= 201107 #pragma omp parallel for reduction(min: minAttr) reduction(max: maxAttr) shared(attributes) default(none) #endif for (size_t i = 0; i < attributes.size(); i++) { float value = attributes.at(i); minAttr = std::min(minAttr, value); maxAttr = std::max(maxAttr, value); } this->dataRange = glm::vec2(minAttr, maxAttr); this->selectedRange = glm::vec2(minAttr, maxAttr); computeHistogram(); } void GuiVarData::computeHistogram() { float histogramsMax = 0; histogram = std::vector<float>(histogramResolution, 0.0f); for (const float& value : attributes) { int32_t index = glm::clamp( static_cast<int>((value - selectedRange.x) / (selectedRange.y - selectedRange.x) * static_cast<float>(histogramResolution)), 0, histogramResolution - 1); histogram.at(index)++; } // Normalize values of histogram. for (const float& binNumber : histogram) { histogramsMax = std::max(histogramsMax, binNumber); } for (float& numBin : histogram) { numBin /= histogramsMax; } } // For OpenGL: Has TRANSFER_FUNCTION_TEXTURE_SIZE entries. // Get mapped color for normalized attribute by accessing entry at "attr*255". void GuiVarData::rebuildTransferFunctionMap() { rebuildTransferFunctionMapLocal(); window->rebuildTransferFunctionMap(); } void GuiVarData::rebuildTransferFunctionMapLocal() { // Create linear RGB color points colorPoints_LinearRGB.clear(); for (sgl::ColorPoint_sRGB& colorPoint : colorPoints) { glm::vec3 linearRGBColor = sgl::TransferFunctionWindow::sRGBToLinearRGB(colorPoint.color.getFloatColorRGB()); colorPoints_LinearRGB.push_back(sgl::ColorPoint_LinearRGB(linearRGBColor, colorPoint.position)); } if (interpolationColorSpace == sgl::COLOR_SPACE_LINEAR_RGB) { rebuildTransferFunctionMap_LinearRGB(); } else { rebuildTransferFunctionMap_sRGB(); } } // For OpenGL: Has 256 entries. Get mapped color for normalized attribute by accessing entry at "attr*255". void GuiVarData::rebuildTransferFunctionMap_LinearRGB() { int colorPointsIdx = 0; int opacityPointsIdx = 0; for (size_t i = 0; i < TRANSFER_FUNCTION_TEXTURE_SIZE; i++) { glm::vec3 linearRGBColorAtIdx; float opacityAtIdx; float currentPosition = static_cast<float>(i) / float(TRANSFER_FUNCTION_TEXTURE_SIZE-1); // colorPoints.at(colorPointsIdx) should be to the right of/equal to currentPosition while (colorPoints_LinearRGB.at(colorPointsIdx).position < currentPosition) { colorPointsIdx++; } while (opacityPoints.at(opacityPointsIdx).position < currentPosition) { opacityPointsIdx++; } // Now compute the color... if (colorPoints_LinearRGB.at(colorPointsIdx).position == currentPosition) { linearRGBColorAtIdx = colorPoints_LinearRGB.at(colorPointsIdx).color; } else { glm::vec3 color0 = colorPoints_LinearRGB.at(colorPointsIdx-1).color; glm::vec3 color1 = colorPoints_LinearRGB.at(colorPointsIdx).color; float pos0 = colorPoints_LinearRGB.at(colorPointsIdx-1).position; float pos1 = colorPoints_LinearRGB.at(colorPointsIdx).position; float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0); linearRGBColorAtIdx = glm::mix(color0, color1, factor); } // ... and the opacity. if (opacityPoints.at(opacityPointsIdx).position == currentPosition) { opacityAtIdx = opacityPoints.at(opacityPointsIdx).opacity; } else { float opacity0 = opacityPoints.at(opacityPointsIdx-1).opacity; float opacity1 = opacityPoints.at(opacityPointsIdx).opacity; float pos0 = opacityPoints.at(opacityPointsIdx-1).position; float pos1 = opacityPoints.at(opacityPointsIdx).position; float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0); opacityAtIdx = sgl::interpolateLinear(opacity0, opacity1, factor); } transferFunctionMap_linearRGB[i] = sgl::Color16(glm::vec4(linearRGBColorAtIdx, opacityAtIdx)); transferFunctionMap_sRGB[i] = sgl::Color16(glm::vec4( sgl::TransferFunctionWindow::linearRGBTosRGB(linearRGBColorAtIdx), opacityAtIdx)); } } // For OpenGL: Has 256 entries. Get mapped color for normalized attribute by accessing entry at "attr*255". void GuiVarData::rebuildTransferFunctionMap_sRGB() { int colorPointsIdx = 0; int opacityPointsIdx = 0; for (size_t i = 0; i < TRANSFER_FUNCTION_TEXTURE_SIZE; i++) { glm::vec3 sRGBColorAtIdx; float opacityAtIdx; float currentPosition = static_cast<float>(i) / float(TRANSFER_FUNCTION_TEXTURE_SIZE-1); // colorPoints.at(colorPointsIdx) should be to the right of/equal to currentPosition while (colorPoints.at(colorPointsIdx).position < currentPosition) { colorPointsIdx++; } while (opacityPoints.at(opacityPointsIdx).position < currentPosition) { opacityPointsIdx++; } // Now compute the color... if (colorPoints.at(colorPointsIdx).position == currentPosition) { sRGBColorAtIdx = colorPoints.at(colorPointsIdx).color.getFloatColorRGB(); } else { glm::vec3 color0 = colorPoints.at(colorPointsIdx-1).color.getFloatColorRGB(); glm::vec3 color1 = colorPoints.at(colorPointsIdx).color.getFloatColorRGB(); float pos0 = colorPoints.at(colorPointsIdx-1).position; float pos1 = colorPoints.at(colorPointsIdx).position; float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0); sRGBColorAtIdx = glm::mix(color0, color1, factor); } // ... and the opacity. if (opacityPoints.at(opacityPointsIdx).position == currentPosition) { opacityAtIdx = opacityPoints.at(opacityPointsIdx).opacity; } else { float opacity0 = opacityPoints.at(opacityPointsIdx-1).opacity; float opacity1 = opacityPoints.at(opacityPointsIdx).opacity; float pos0 = opacityPoints.at(opacityPointsIdx-1).position; float pos1 = opacityPoints.at(opacityPointsIdx).position; float factor = 1.0f - (pos1 - currentPosition) / (pos1 - pos0); opacityAtIdx = sgl::interpolateLinear(opacity0, opacity1, factor); } transferFunctionMap_linearRGB[i] = sgl::Color16(glm::vec4( sgl::TransferFunctionWindow::sRGBToLinearRGB(sRGBColorAtIdx), opacityAtIdx)); transferFunctionMap_sRGB[i] = sgl::Color16(glm::vec4(sRGBColorAtIdx, opacityAtIdx)); } } bool GuiVarData::renderGui() { renderOpacityGraph(); renderColorBar(); if (selectedPointType == sgl::SELECTED_POINT_TYPE_OPACITY) { if (ImGui::DragFloat("Opacity", &opacitySelection, 0.001f, 0.0f, 1.0f)) { opacityPoints.at(currentSelectionIndex).opacity = opacitySelection; rebuildTransferFunctionMap(); reRender = true; } } else if (selectedPointType == sgl::SELECTED_POINT_TYPE_COLOR) { if (ImGui::ColorEdit3("Color", (float*)&colorSelection)) { colorPoints.at(currentSelectionIndex).color = sgl::color16FromFloat( colorSelection.x, colorSelection.y, colorSelection.z, colorSelection.w); rebuildTransferFunctionMap(); reRender = true; } } if (ImGui::Combo( "Color Space", (int*)&interpolationColorSpace, sgl::COLOR_SPACE_NAMES, IM_ARRAYSIZE(sgl::COLOR_SPACE_NAMES))) { rebuildTransferFunctionMap(); reRender = true; } if (ImGui::SliderFloat2("Range", &selectedRange.x, dataRange.x, dataRange.y)) { computeHistogram(); window->rebuildRangeSsbo(); reRender = true; } ImGui::SameLine(); if (ImGui::Button("Reset")) { selectedRange = dataRange; computeHistogram(); window->rebuildRangeSsbo(); reRender = true; } if (ImGui::SliderInt("Histogram Res.", &histogramResolution, 1, 256)) { computeHistogram(); } renderFileDialog(); if (reRender) { reRender = false; return true; } return false; } void GuiVarData::renderFileDialog() { // Load file data if (ImGui::ListBox("##availablefiles", &selectedFileIndex, [this](void* data, int idx, const char** out_text) -> bool { *out_text = window->availableFiles.at(idx).c_str(); return true; }, nullptr, int(window->availableFiles.size()), 4)) { saveFileString = window->availableFiles.at(selectedFileIndex); } ImVec2 cursorPosEnd = ImGui::GetCursorPos(); ImGui::SameLine(); ImVec2 cursorPos = ImGui::GetCursorPos(); ImGui::Text("Available files"); ImGui::SameLine(); ImGui::SetCursorPos(cursorPos + ImVec2(0.0f, 42.0f)); if (ImGui::Button("Load file") && selectedFileIndex >= 0) { loadTfFromFile(window->saveDirectory + window->availableFiles.at(selectedFileIndex)); reRender = true; } ImGui::SetCursorPos(cursorPosEnd); // Save file data ImGui::InputText("##savefilelabel", &saveFileString); ImGui::SameLine(); if (ImGui::Button("Save file")) { saveTfToFile(window->saveDirectory + saveFileString); window->updateAvailableFiles(); } } void GuiVarData::renderOpacityGraph() { ImDrawList* drawList = ImGui::GetWindowDrawList(); float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor(); float regionWidth = ImGui::GetContentRegionAvailWidth(); float graphHeight = 300 * scaleFactor / 1.875f; float border = 2*scaleFactor; float areaWidth = regionWidth - 2.0f*border; float areaHeight = graphHeight - 2.0f*border; opacityGraphBox.min = glm::vec2(ImGui::GetCursorScreenPos().x + border, ImGui::GetCursorScreenPos().y + border); opacityGraphBox.max = opacityGraphBox.min + glm::vec2(areaWidth, areaHeight); sgl::Color& clearColor = window->clearColor; ImColor backgroundColor(clearColor.getFloatR(), clearColor.getFloatG(), clearColor.getFloatB()); ImColor borderColor( 1.0f - clearColor.getFloatR(), 1.0f - clearColor.getFloatG(), 1.0f - clearColor.getFloatB()); // First render the graph box ImVec2 startPos = ImGui::GetCursorScreenPos(); ImVec2 cursorPosHistogram = ImGui::GetCursorPos(); drawList->AddRectFilled( ImVec2(startPos.x, startPos.y), ImVec2(startPos.x + regionWidth, startPos.y + graphHeight), borderColor, ImGui::GetStyle().FrameRounding); drawList->AddRectFilled( ImVec2(startPos.x + border, startPos.y + border), ImVec2(startPos.x + regionWidth - border, startPos.y + graphHeight - border), backgroundColor, ImGui::GetStyle().FrameRounding); if (ImGui::ClickArea("##grapharea", ImVec2(regionWidth, graphHeight + 2), mouseReleased)) { onOpacityGraphClick(); } //ImGui::SetItemAllowOverlap(); ImGui::SetCursorPos(cursorPosHistogram + ImVec2(border, border)); ImVec2 oldPadding = ImGui::GetStyle().FramePadding; ImGui::GetStyle().FramePadding = ImVec2(1, 1); ImGui::PlotHistogram( "##histogram", histogram.data(), int(histogram.size()), 0, nullptr, 0.0f, 1.0f, ImVec2(regionWidth - border * 2, graphHeight - border * 2)); ImGui::GetStyle().FramePadding = oldPadding; // Then render the graph itself for (int i = 0; i < (int)opacityPoints.size()-1; i++) { float positionX0 = opacityPoints.at(i).position * areaWidth + border; float positionX1 = opacityPoints.at(i+1).position * areaWidth + border; float positionY0 = (1.0f - opacityPoints.at(i).opacity) * areaHeight + border; float positionY1 = (1.0f - opacityPoints.at(i+1).opacity) * areaHeight + border; drawList->AddLine( ImVec2(startPos.x + positionX0, startPos.y + positionY0), ImVec2(startPos.x + positionX1, startPos.y + positionY1), borderColor, 1.5f * scaleFactor); } // Finally, render the points for (int i = 0; i < (int)opacityPoints.size(); i++) { ImVec2 centerPt = ImVec2( startPos.x + border + opacityPoints.at(i).position * areaWidth, startPos.y + border + (1.0f - opacityPoints.at(i).opacity) * areaHeight); float radius = 4*scaleFactor; if (selectedPointType == sgl::SELECTED_POINT_TYPE_OPACITY && i == currentSelectionIndex) { radius = 6*scaleFactor; } drawList->AddCircleFilled(centerPt, radius, backgroundColor, 24); drawList->AddCircle(centerPt, radius, borderColor, 24, 1.5f); } } void GuiVarData::renderColorBar() { ImDrawList* drawList = ImGui::GetWindowDrawList(); float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor(); float regionWidth = ImGui::GetContentRegionAvailWidth() - 2.0f; float barHeight = 30 * scaleFactor / 1.875f; colorBarBox.min = glm::vec2(ImGui::GetCursorScreenPos().x + 1, ImGui::GetCursorScreenPos().y + 1); colorBarBox.max = colorBarBox.min + glm::vec2(regionWidth - 2, barHeight - 2); // Draw bar ImVec2 startPos = ImGui::GetCursorScreenPos(); ImVec2 pos = ImVec2(startPos.x + 1, startPos.y + 1); for (size_t i = 0; i < TRANSFER_FUNCTION_TEXTURE_SIZE; i++) { sgl::Color16 color = transferFunctionMap_sRGB[i]; ImU32 colorImgui = ImColor(color.getFloatR(), color.getFloatG(), color.getFloatB()); drawList->AddLine(ImVec2(pos.x, pos.y), ImVec2(pos.x, pos.y + barHeight), colorImgui, 2.0f * regionWidth / 255.0f); pos.x += regionWidth / 255.0f; } // Draw points pos = ImVec2(startPos.x + 2, startPos.y + 2); for (int i = 0; i < (int)colorPoints.size(); i++) { sgl::Color16 color = colorPoints.at(i).color; ImU32 colorImgui = ImColor(color.getFloatR(), color.getFloatG(), color.getFloatB()); ImU32 colorInvertedImgui = ImColor(1.0f - color.getFloatR(), 1.0f - color.getFloatG(), 1.0f - color.getFloatB()); ImVec2 centerPt = ImVec2(pos.x + colorPoints.at(i).position * regionWidth, pos.y + barHeight/2); float radius = 4*scaleFactor; if (selectedPointType == sgl::SELECTED_POINT_TYPE_COLOR && i == currentSelectionIndex) { radius = 6*scaleFactor; } drawList->AddCircleFilled(centerPt, radius, colorImgui, 24); drawList->AddCircle(centerPt, radius, colorInvertedImgui, 24); } if (ImGui::ClickArea("##bararea", ImVec2(regionWidth + 2, barHeight), mouseReleased)) { onColorBarClick(); } } void GuiVarData::onOpacityGraphClick() { glm::vec2 mousePosWidget = glm::vec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y) - opacityGraphBox.min; glm::vec2 normalizedPosition = mousePosWidget / opacityGraphBox.getDimensions(); normalizedPosition.y = 1.0f - normalizedPosition.y; normalizedPosition = glm::clamp(normalizedPosition, glm::vec2(0), glm::vec2(1)); dragging = false; if (selectNearestOpacityPoint(currentSelectionIndex, mousePosWidget)) { // A) Point near to normalized position if (ImGui::GetIO().MouseClicked[0]) { // A.1 Left clicked? Select/drag-and-drop opacitySelection = opacityPoints.at(currentSelectionIndex).opacity; selectedPointType = sgl::SELECTED_POINT_TYPE_OPACITY; dragging = true; } else if (ImGui::GetIO().MouseClicked[1] && currentSelectionIndex != 0 && currentSelectionIndex != int(opacityPoints.size())-1) { // A.2 Middle clicked? Delete point opacityPoints.erase(opacityPoints.begin() + currentSelectionIndex); selectedPointType = sgl::SELECTED_POINT_TYPE_NONE; reRender = true; } } else { // B) If no point near and left clicked: Create new point at position if (ImGui::GetIO().MouseClicked[0]) { // Compute insert position for new point int insertPosition = 0; for (insertPosition = 0; insertPosition < (int)opacityPoints.size(); insertPosition++) { if (normalizedPosition.x < opacityPoints.at(insertPosition).position || insertPosition == int(opacityPoints.size())-1) { break; } } // Add new opacity point glm::vec2 newPosition = normalizedPosition; float newOpacity = newPosition.y; opacityPoints.insert(opacityPoints.begin() + insertPosition, sgl::OpacityPoint(newOpacity, newPosition.x)); currentSelectionIndex = insertPosition; opacitySelection = opacityPoints.at(currentSelectionIndex).opacity; selectedPointType = sgl::SELECTED_POINT_TYPE_OPACITY; dragging = true; reRender = true; } } rebuildTransferFunctionMap(); } void GuiVarData::onColorBarClick() { glm::vec2 mousePosWidget = glm::vec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y) - colorBarBox.min; float normalizedPosition = mousePosWidget.x / colorBarBox.getWidth(); dragging = false; if (selectNearestColorPoint(currentSelectionIndex, mousePosWidget)) { // A) Point near to normalized position if (ImGui::GetIO().MouseClicked[0]) { // A.1 Left clicked? Select/drag-and-drop sgl::Color16& color16 = colorPoints.at(currentSelectionIndex).color; colorSelection = ImColor(color16.getFloatR(), color16.getFloatG(), color16.getFloatB()); selectedPointType = sgl::SELECTED_POINT_TYPE_COLOR; if (currentSelectionIndex != 0 && currentSelectionIndex != int(colorPoints.size())-1) { dragging = true; } } else if (ImGui::GetIO().MouseClicked[1] && currentSelectionIndex != 0 && currentSelectionIndex != int(colorPoints.size())-1) { // A.2 Middle clicked? Delete point colorPoints.erase(colorPoints.begin() + currentSelectionIndex); colorPoints_LinearRGB.erase(colorPoints_LinearRGB.begin() + currentSelectionIndex); selectedPointType = sgl::SELECTED_POINT_TYPE_NONE; reRender = true; } } else { // B) If no point near and left clicked: Create new point at position if (ImGui::GetIO().MouseClicked[0]) { // Compute insert position for new point int insertPosition = 0; for (insertPosition = 0; insertPosition < (int)colorPoints.size(); insertPosition++) { if (normalizedPosition < colorPoints.at(insertPosition).position || insertPosition == int(colorPoints.size())-1) { break; } } // Add new color point float newPosition = normalizedPosition; if (interpolationColorSpace == sgl::COLOR_SPACE_LINEAR_RGB) { // Linear RGB interplation glm::vec3 newColor_linearRGB = glm::mix( colorPoints_LinearRGB.at(insertPosition-1).color, colorPoints_LinearRGB.at(insertPosition).color, 1.0 - (colorPoints_LinearRGB.at(insertPosition).position - newPosition) / (colorPoints_LinearRGB.at(insertPosition).position - colorPoints_LinearRGB.at(insertPosition-1).position)); sgl::Color16 newColorsRGB(sgl::TransferFunctionWindow::linearRGBTosRGB(newColor_linearRGB)); colorPoints_LinearRGB.insert( colorPoints_LinearRGB.begin() + insertPosition, sgl::ColorPoint_LinearRGB(newColor_linearRGB, newPosition)); colorPoints.insert( colorPoints.begin() + insertPosition, sgl::ColorPoint_sRGB(newColorsRGB, newPosition)); } else { // sRGB interpolation sgl::Color16 newColor = sgl::color16Lerp( colorPoints.at(insertPosition-1).color, colorPoints.at(insertPosition).color, 1.0f - (colorPoints.at(insertPosition).position - newPosition) / (colorPoints.at(insertPosition).position - colorPoints.at(insertPosition-1).position)); colorPoints.insert( colorPoints.begin() + insertPosition, sgl::ColorPoint_sRGB(newColor, newPosition)); // colorPoints_LinearRGB computed in @ref rebuildTransferFunctionMap } currentSelectionIndex = insertPosition; sgl::Color16& color16 = colorPoints.at(currentSelectionIndex).color; colorSelection = ImColor(color16.getFloatR(), color16.getFloatG(), color16.getFloatB()); selectedPointType = sgl::SELECTED_POINT_TYPE_COLOR; reRender = true; } } rebuildTransferFunctionMap(); } void GuiVarData::dragPoint() { if (mouseReleased) { dragging = false; } glm::vec2 mousePosWidget = glm::vec2(ImGui::GetMousePos().x, ImGui::GetMousePos().y) - opacityGraphBox.min; if (!dragging || mousePosWidget == oldMousePosWidget) { oldMousePosWidget = mousePosWidget; return; } oldMousePosWidget = mousePosWidget; if (selectedPointType == sgl::SELECTED_POINT_TYPE_OPACITY) { glm::vec2 normalizedPosition = mousePosWidget / opacityGraphBox.getDimensions(); normalizedPosition.y = 1.0f - normalizedPosition.y; normalizedPosition = glm::clamp(normalizedPosition, 0.0f, 1.0f); if (currentSelectionIndex == 0) { normalizedPosition.x = 0.0f; } if (currentSelectionIndex == int(opacityPoints.size())-1) { normalizedPosition.x = 1.0f; } // Clip to neighbors! if (currentSelectionIndex != 0 && normalizedPosition.x < opacityPoints.at(currentSelectionIndex-1).position) { normalizedPosition.x = opacityPoints.at(currentSelectionIndex-1).position; } if (currentSelectionIndex != int(opacityPoints.size())-1 && normalizedPosition.x > opacityPoints.at(currentSelectionIndex+1).position) { normalizedPosition.x = opacityPoints.at(currentSelectionIndex+1).position; } opacityPoints.at(currentSelectionIndex).position = normalizedPosition.x; opacityPoints.at(currentSelectionIndex).opacity = normalizedPosition.y; opacitySelection = opacityPoints.at(currentSelectionIndex).opacity; } if (selectedPointType == sgl::SELECTED_POINT_TYPE_COLOR) { float normalizedPosition = mousePosWidget.x / colorBarBox.getWidth(); normalizedPosition = glm::clamp(normalizedPosition, 0.0f, 1.0f); // Clip to neighbors! if (currentSelectionIndex != 0 && normalizedPosition < colorPoints.at(currentSelectionIndex-1).position) { normalizedPosition = colorPoints.at(currentSelectionIndex-1).position; } if (currentSelectionIndex != int(colorPoints.size())-1 && normalizedPosition > colorPoints.at(currentSelectionIndex+1).position) { normalizedPosition = colorPoints.at(currentSelectionIndex+1).position; } colorPoints.at(currentSelectionIndex).position = normalizedPosition; } rebuildTransferFunctionMap(); reRender = true; } bool GuiVarData::selectNearestOpacityPoint(int& currentSelectionIndex, const glm::vec2& mousePosWidget) { float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor(); for (int i = 0; i < (int)opacityPoints.size(); i++) { glm::vec2 centerPt = glm::vec2( opacityPoints.at(i).position * opacityGraphBox.getWidth(), (1.0f - opacityPoints.at(i).opacity) * opacityGraphBox.getHeight()); if (glm::length(centerPt - mousePosWidget) < scaleFactor * 10.0f) { currentSelectionIndex = i; return true; } } return false; } bool GuiVarData::selectNearestColorPoint(int& currentSelectionIndex, const glm::vec2& mousePosWidget) { float scaleFactor = sgl::ImGuiWrapper::get()->getScaleFactor(); for (int i = 0; i < (int)colorPoints.size(); i++) { ImVec2 centerPt = ImVec2( colorPoints.at(i).position * colorBarBox.getWidth(), colorBarBox.getHeight()/2); if (glm::abs(centerPt.x - mousePosWidget.x) < scaleFactor * 10.0f) { currentSelectionIndex = i; return true; } } return false; } // --------------------------------------------------------------------------------------------------------------------- MultiVarTransferFunctionWindow::MultiVarTransferFunctionWindow( const std::string& saveDirectoryPrefix, const std::vector<std::string>& tfPresetFiles) { parentDirectory = sgl::AppSettings::get()->getDataDirectory(); saveDirectory = sgl::AppSettings::get()->getDataDirectory() + "TransferFunctions/"; if (!saveDirectoryPrefix.empty()) { directoryName = saveDirectoryPrefix; parentDirectory = saveDirectory; saveDirectory = saveDirectory + saveDirectoryPrefix + "/"; } this->tfPresetFiles = tfPresetFiles; directoryContentWatch.setPath(saveDirectory, true); directoryContentWatch.initialize(); #ifdef SUPPORT_OPENGL if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) { tfMapTextureSettings.type = sgl::TEXTURE_1D_ARRAY; tfMapTextureSettings.internalFormat = GL_RGBA16; } #endif #ifdef USE_VULKAN_INTEROP if (sgl::AppSettings::get()->getPrimaryDevice()) { tfMapImageSettingsVulkan.imageType = VK_IMAGE_TYPE_1D; tfMapImageSettingsVulkan.format = VK_FORMAT_R16G16B16A16_UNORM; } #endif updateAvailableFiles(); } MultiVarTransferFunctionWindow::~MultiVarTransferFunctionWindow() { } void MultiVarTransferFunctionWindow::setAttributesValues( const std::vector<std::string>& names, const std::vector<std::vector<float>>& allAttributes) { assert(names.size() == allAttributes.size()); varNames = names; transferFunctionMap_sRGB.resize(TRANSFER_FUNCTION_TEXTURE_SIZE * names.size()); transferFunctionMap_linearRGB.resize(TRANSFER_FUNCTION_TEXTURE_SIZE * names.size()); selectedVarIndex = 0; if (guiVarData.size() != names.size()){ guiVarData.clear(); guiVarData.reserve(names.size()); #ifdef SUPPORT_OPENGL if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) { tfMapTexture = sgl::TextureManager->createEmptyTexture( TRANSFER_FUNCTION_TEXTURE_SIZE, int(names.size()), tfMapTextureSettings); minMaxSsbo = sgl::Renderer->createGeometryBuffer( names.size() * sizeof(glm::vec2), sgl::SHADER_STORAGE_BUFFER); } #endif #ifdef USE_VULKAN_INTEROP if (sgl::AppSettings::get()->getPrimaryDevice()) { tfMapImageSettingsVulkan.width = TRANSFER_FUNCTION_TEXTURE_SIZE; tfMapImageSettingsVulkan.arrayLayers = uint32_t(names.size()); tfMapTextureVulkan = std::make_shared<sgl::vk::Texture>( sgl::AppSettings::get()->getPrimaryDevice(), tfMapImageSettingsVulkan, VK_IMAGE_VIEW_TYPE_1D_ARRAY); minMaxSsboVulkan = std::make_shared<sgl::vk::Buffer>( sgl::AppSettings::get()->getPrimaryDevice(), names.size() * sizeof(glm::vec2), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VMA_MEMORY_USAGE_GPU_ONLY); } #endif minMaxData.clear(); minMaxData.resize(names.size() * 2, 0); for (size_t varIdx = 0; varIdx < names.size(); varIdx++) { guiVarData.push_back(GuiVarData( this, tfPresetFiles.size() > 0 ? tfPresetFiles.at(varIdx % tfPresetFiles.size()) : "", &transferFunctionMap_sRGB.at(TRANSFER_FUNCTION_TEXTURE_SIZE * varIdx), &transferFunctionMap_linearRGB.at(TRANSFER_FUNCTION_TEXTURE_SIZE * varIdx) )); } } for (size_t varIdx = 0; varIdx < names.size(); varIdx++) { GuiVarData& varData = guiVarData.at(varIdx); varData.setAttributeValues(names.at(varIdx), allAttributes.at(varIdx)); } currVarData = &guiVarData.at(selectedVarIndex); updateAvailableFiles(); rebuildTransferFunctionMapComplete(); rebuildRangeSsbo(); } bool MultiVarTransferFunctionWindow::loadFromTfNameList(const std::vector<std::string>& tfNames) { if (tfNames.size() != guiVarData.size()) { sgl::Logfile::get()->writeError( "MultiVarTransferFunctionWindow::loadFromTfNameList: tfNames.size() != guiVarData.size()"); return false; } for (size_t varIdx = 0; varIdx < tfNames.size(); varIdx++) { GuiVarData& varData = guiVarData.at(varIdx); varData.loadTfFromFile(saveDirectory + tfNames.at(varIdx)); } return true; } void MultiVarTransferFunctionWindow::updateAvailableFiles() { sgl::FileUtils::get()->ensureDirectoryExists(saveDirectory); std::vector<std::string> availableFilesAll = sgl::FileUtils::get()->getFilesInDirectoryVector(saveDirectory); availableFiles.clear(); availableFiles.reserve(availableFilesAll.size()); for (const std::string& filename : availableFilesAll) { if (sgl::FileUtils::get()->hasExtension(filename.c_str(), ".xml")) { availableFiles.push_back(filename); } } sgl::FileUtils::get()->sortPathStrings(availableFiles); // Update currently selected filename for (size_t i = 0; i < availableFiles.size(); i++) { availableFiles.at(i) = sgl::FileUtils::get()->getPureFilename(availableFiles.at(i)); for (GuiVarData& varData : guiVarData) { if (availableFiles.at(i) == varData.getSaveFileString()) { varData.selectedFileIndex = (int)i; } } } } void MultiVarTransferFunctionWindow::setClearColor(const sgl::Color& clearColor) { this->clearColor = clearColor; } #ifdef SUPPORT_OPENGL sgl::TexturePtr& MultiVarTransferFunctionWindow::getTransferFunctionMapTexture() { return tfMapTexture; } #endif #ifdef USE_VULKAN_INTEROP sgl::vk::TexturePtr& MultiVarTransferFunctionWindow::getTransferFunctionMapTextureVulkan() { return tfMapTextureVulkan; } #endif bool MultiVarTransferFunctionWindow::getTransferFunctionMapRebuilt() { if (transferFunctionMapRebuilt) { // Reset the flag transferFunctionMapRebuilt = false; return true; } return false; } std::vector<sgl::Color16> MultiVarTransferFunctionWindow::getTransferFunctionMap_sRGB(int varIdx) { return std::vector<sgl::Color16>( transferFunctionMap_sRGB.cbegin() + TRANSFER_FUNCTION_TEXTURE_SIZE * varIdx, transferFunctionMap_sRGB.cbegin() + TRANSFER_FUNCTION_TEXTURE_SIZE * (varIdx + 1)); } void MultiVarTransferFunctionWindow::update(float dt) { directoryContentWatch.update([this] { this->updateAvailableFiles(); }); if (currVarData) { currVarData->dragPoint(); } } void MultiVarTransferFunctionWindow::setUseLinearRGB(bool useLinearRGB) { this->useLinearRGB = useLinearRGB; rebuildTransferFunctionMapComplete(); } void MultiVarTransferFunctionWindow::rebuildTransferFunctionMapComplete() { for (GuiVarData& varData : guiVarData) { varData.rebuildTransferFunctionMapLocal(); } rebuildTransferFunctionMap(); } void MultiVarTransferFunctionWindow::rebuildRangeSsbo() { for (size_t varIdx = 0; varIdx < guiVarData.size(); varIdx++) { GuiVarData& varData = guiVarData.at(varIdx); const glm::vec2& range = varData.getSelectedRange(); minMaxData[varIdx * 2] = range.x; minMaxData[varIdx * 2 + 1] = range.y; } #ifdef SUPPORT_OPENGL if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) { minMaxSsbo->subData(0, minMaxData.size() * sizeof(float), minMaxData.data()); } #endif #ifdef USE_VULKAN_INTEROP if (sgl::AppSettings::get()->getPrimaryDevice()) { minMaxSsboVulkan->uploadData(minMaxData.size() * sizeof(float), minMaxData.data()); } #endif } void MultiVarTransferFunctionWindow::rebuildTransferFunctionMap() { #ifdef SUPPORT_OPENGL if (sgl::AppSettings::get()->getRenderSystem() == sgl::RenderSystem::OPENGL) { sgl::PixelFormat pixelFormat; pixelFormat.pixelType = GL_UNSIGNED_SHORT; if (useLinearRGB) { tfMapTexture->uploadPixelData( TRANSFER_FUNCTION_TEXTURE_SIZE, int(varNames.size()), transferFunctionMap_linearRGB.data(), pixelFormat); } else { tfMapTexture->uploadPixelData( TRANSFER_FUNCTION_TEXTURE_SIZE, int(varNames.size()), transferFunctionMap_sRGB.data(), pixelFormat); } } #endif #ifdef USE_VULKAN_INTEROP if (sgl::AppSettings::get()->getPrimaryDevice()) { if (useLinearRGB) { tfMapTextureVulkan->getImage()->uploadData( TRANSFER_FUNCTION_TEXTURE_SIZE * uint32_t(varNames.size()) * 8, transferFunctionMap_linearRGB.data()); } else { tfMapTextureVulkan->getImage()->uploadData( TRANSFER_FUNCTION_TEXTURE_SIZE * uint32_t(varNames.size()) * 8, transferFunctionMap_sRGB.data()); } } #endif transferFunctionMapRebuilt = true; } bool MultiVarTransferFunctionWindow::renderGui() { sgl::ImGuiWrapper::get()->setNextWindowStandardPosSize(2, 1278, 634, 818); if (showWindow && ImGui::Begin("Multi-Var Transfer Function", &showWindow)) { if (ImGui::BeginCombo("Variable", varNames.at(selectedVarIndex).c_str())) { for (size_t i = 0; i < varNames.size(); ++i) { if (ImGui::Selectable(varNames.at(i).c_str(), selectedVarIndex == i)) { selectedVarIndex = i; currVarData = &guiVarData.at(selectedVarIndex); } } ImGui::EndCombo(); } if (currVarData) { reRender = currVarData->renderGui() || reRender; } ImGui::End(); } if (reRender) { reRender = false; return true; } return false; }
43.390196
123
0.64908
FelixBrendel
33fdf339bf89884ccf4eafbeae7f765a6cd1a109
4,925
cpp
C++
src/IECore/MemoryIndexedIO.cpp
bradleyhenke/cortex
f8245cc6c9464b1de9e6c6e57068248198e63de0
[ "BSD-3-Clause" ]
386
2015-01-02T11:10:43.000Z
2022-03-10T15:12:20.000Z
src/IECore/MemoryIndexedIO.cpp
bradleyhenke/cortex
f8245cc6c9464b1de9e6c6e57068248198e63de0
[ "BSD-3-Clause" ]
484
2015-01-09T18:28:06.000Z
2022-03-31T16:02:04.000Z
src/IECore/MemoryIndexedIO.cpp
bradleyhenke/cortex
f8245cc6c9464b1de9e6c6e57068248198e63de0
[ "BSD-3-Clause" ]
99
2015-01-28T23:18:04.000Z
2022-03-27T00:59:39.000Z
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008-2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/MemoryIndexedIO.h" #include "IECore/FileIndexedIO.h" #include "IECore/VectorTypedData.h" using namespace IECore; IE_CORE_DEFINERUNTIMETYPEDDESCRIPTION( MemoryIndexedIO ) /////////////////////////////////////////////// // // FileIndexedIO::StreamFile (begin) // /////////////////////////////////////////////// class MemoryIndexedIO::StreamFile : public StreamIndexedIO::StreamFile { public: StreamFile( const char *buf, size_t size, IndexedIO::OpenMode mode ); CharVectorDataPtr buffer(); ~StreamFile() override; void flush( size_t endPosition ) override; private: size_t m_endPosition; }; MemoryIndexedIO::StreamFile::StreamFile( const char *buf, size_t size, IndexedIO::OpenMode mode ) : StreamIndexedIO::StreamFile(mode), m_endPosition(0) { if (mode & IndexedIO::Write) { std::stringstream *f = new std::stringstream( std::ios::trunc | std::ios::binary | std::ios::in | std::ios::out ); setInput( f, true, "" ); } else if (mode & IndexedIO::Append) { if ( !buf || !size ) { /// Create new file std::stringstream *f = new std::stringstream( std::ios::trunc | std::ios::binary | std::ios::in | std::ios::out ); setInput( f, true, "" ); } else { /// Read existing file assert( buf ); /// Read existing file std::stringstream *f = new std::stringstream( std::string(buf, size), std::ios::binary | std::ios::in | std::ios::out ); setInput( f, false, "" ); } } else { assert( buf ); assert( mode & IndexedIO::Read ); std::stringstream *f = new std::stringstream( std::string(buf, size), std::ios::binary | std::ios::in | std::ios::out ); setInput( f, false, "" ); } } void MemoryIndexedIO::StreamFile::flush( size_t endPosition ) { m_endPosition = endPosition; } CharVectorDataPtr MemoryIndexedIO::StreamFile::buffer() { std::stringstream *s = static_cast< std::stringstream *>( m_stream ); assert( s ); CharVectorData::ValueType d; const std::string &str = s->str(); d.assign( str.begin(), str.end() ); d.resize( m_endPosition ); assert( d.size() == m_endPosition ); return new CharVectorData( d ); } MemoryIndexedIO::StreamFile::~StreamFile() { } /////////////////////////////////////////////// // // MemoryIndexedIO::StreamFile (end) // /////////////////////////////////////////////// MemoryIndexedIO::MemoryIndexedIO( ConstCharVectorDataPtr buf, const IndexedIO::EntryIDList &root, IndexedIO::OpenMode mode) { const char *bufPtr = nullptr; size_t size = 0; if ( buf ) { bufPtr = &(buf->readable()[0]); size = buf->readable().size(); } open( new StreamFile( bufPtr, size, mode ), root ); } MemoryIndexedIO::MemoryIndexedIO( StreamIndexedIO::Node &rootNode ) : StreamIndexedIO( rootNode ) { } MemoryIndexedIO::~MemoryIndexedIO() { } CharVectorDataPtr MemoryIndexedIO::buffer() { flush(); StreamFile &stream = static_cast<StreamFile&>( streamFile() ); return stream.buffer(); } IndexedIO * MemoryIndexedIO::duplicate(Node &rootNode) const { // duplicate the IO interface changing the current node MemoryIndexedIO *other = new MemoryIndexedIO( rootNode ); return other; }
30.214724
151
0.657056
bradleyhenke
33fdf948cd6d64179e9d82b680ba30593b58de6f
2,509
cpp
C++
src/cimple/tests/type/main.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
4
2015-12-16T06:43:14.000Z
2020-01-24T06:05:47.000Z
src/cimple/tests/type/main.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
src/cimple/tests/type/main.cpp
LegalizeAdulthood/cimple
5ec70784f2ee3e455a2258f82b07c0dacccb4093
[ "MIT" ]
null
null
null
/* **============================================================================== ** ** Copyright (c) 2003, 2004, 2005, 2006, Michael Brasher, Karl Schopmeyer ** ** 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 <cassert> #include <cimple/cimple.h> using namespace cimple; void test(const char* name, Type expected_type) { Type type; int status = type_name_to_type(name, type); assert(status == 0); assert(type == expected_type); } int main(int /* argc */, char** argv) { printf("Test+++ %s\n",argv[0]); test("boolean", BOOLEAN); test("uint8", UINT8); test("sint8", SINT8); test("uint16", UINT16); test("sint16", SINT16); test("uint32", UINT32); test("sint32", SINT32); test("uint64", UINT64); test("sint64", SINT64); test("real32", REAL32); test("real64", REAL64); test("char16", CHAR16); test("string", STRING); test("datetime", DATETIME); test("BOOLEAN", BOOLEAN); test("UINT8", UINT8); test("SINT8", SINT8); test("UINT16", UINT16); test("SINT16", SINT16); test("UINT32", UINT32); test("SINT32", SINT32); test("UINT64", UINT64); test("SINT64", SINT64); test("REAL32", REAL32); test("REAL64", REAL64); test("CHAR16", CHAR16); test("STRING", STRING); test("DATETIME", DATETIME); printf("+++++ passed all tests (%s)\n", argv[0]); return 0; }
32.584416
80
0.62774
LegalizeAdulthood
33ff6e3d328c652ea717362e770c0dae140c6366
1,802
hpp
C++
networkit/cpp/embedding/BiasedRandomWalk.hpp
angriman/network
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
[ "MIT" ]
366
2019-06-27T18:48:18.000Z
2022-03-29T08:36:49.000Z
networkit/cpp/embedding/BiasedRandomWalk.hpp
angriman/network
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
[ "MIT" ]
387
2019-06-24T11:30:39.000Z
2022-03-31T10:37:28.000Z
networkit/cpp/embedding/BiasedRandomWalk.hpp
angriman/network
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
[ "MIT" ]
131
2019-07-04T15:40:13.000Z
2022-03-29T12:34:23.000Z
/* * BiasedRandomWalk.hpp * * Created on: 03.07.2020 * Author: Klaus Ahrens <ahrens@informatik.hu-berlin.de> * * adapted and reimplemented from node2vec * part of snap [https://github.com/snap-stanford/snap] * Copyright (c) 2007-2019, Jure Leskovec (under BSD license) * * see [https://arxiv.org/pdf/1607.00653v1.pdf] * */ #ifndef BIASEDRANDOMWALK_HPP #define BIASEDRANDOMWALK_HPP #include <memory> #include <unordered_map> #include <unordered_set> #include <vector> #include <networkit/graph/Graph.hpp> namespace NetworKit { namespace Embedding { class BiasedRandomWalk { public: using Walk = std::vector<node>; // one walk using AllWalks = std::vector<Walk>; // n walks for all nodes: 2 dimensions in one big chunk /// preprocesses transition probabilities for random walks. Has to be called once before doWalks /// calls void preprocessTransitionProbs(double paramP, double paramQ); /// Simulates walks from every node and writes it into walks vector AllWalks doWalks(count walkLen, count numberOfWalks); BiasedRandomWalk(const Graph *graph); private: const Graph *graph; using NeighborSet = std::unordered_set<node>; using NeighborMap = std::unordered_map<node, AliasSampler>; struct GraphData { // assuming contiguous node numbers 0..n-1, they serve as indices using Data = std::vector<NeighborMap>; Data data; GraphData(size_t nn) : data{nn, NeighborMap()} {} }; std::unique_ptr<GraphData> graphData; std::vector<std::vector<node>> index2node; Walk oneWalk(node start, count walkLen); void preprocessNode(node t, double paramP, double paramQ); }; // class BiasedRandomWalk } // namespace Embedding } // namespace NetworKit #endif // BIASEDRANDOMWALK_HPP
27.30303
100
0.704772
angriman
33ff8198ae66cc42da76d1efc0d75657d14fdb16
2,098
cc
C++
day06/part01/puzzle.cc
ovove/aoc19
7b74552cf376a699fe554afcae980d7de6dd18cd
[ "Unlicense" ]
null
null
null
day06/part01/puzzle.cc
ovove/aoc19
7b74552cf376a699fe554afcae980d7de6dd18cd
[ "Unlicense" ]
null
null
null
day06/part01/puzzle.cc
ovove/aoc19
7b74552cf376a699fe554afcae980d7de6dd18cd
[ "Unlicense" ]
null
null
null
#include <string> #include <string_view> #include <iostream> #include <regex> #include <algorithm> #include <map> // #include <range/v3/all.hpp> namespace { using SatelliteGraph = std::map<std::string, std::vector<std::string>>; SatelliteGraph map2graph(std::istream& map) { SatelliteGraph result; const std::regex regex(R"(([A-Z0-9]+)\)([A-Z0-9]+))"); for (std::string line; std::getline(map, line);) { std::smatch match; if (not std::regex_match(line, match, regex)) continue; const auto& center = match[1]; const auto& satellite = match[2]; result[center].push_back(satellite); static_cast<void>(result[satellite]); } return result; } using SatelliteDistances = std::map<std::string, unsigned>; void checksum_(const SatelliteGraph& graph, const std::string& satellite, SatelliteDistances& satellite_distances, unsigned distance) { satellite_distances[satellite] = distance; for (const auto next_satellite : graph.at(satellite)) { checksum_(graph, next_satellite, satellite_distances, distance + 1); } } unsigned checksum(const SatelliteGraph& graph) { SatelliteDistances satellite_distances; checksum_(graph, "COM", satellite_distances, 0); unsigned tot_dist = 0; for (auto [satellite, distance] : satellite_distances) tot_dist += distance; return tot_dist; } } // namespace #if not defined(DO_UNIT_TEST) #include <filesystem> #include <fstream> int main() { using std::filesystem::path; std::ifstream input(path(BINARY_DIR) / path("..") / path("input")); const auto graph = map2graph(input); const auto chksum = checksum(graph); std::cout << chksum << std::endl; } #else // DO_UNIT_TEST #include <gtest/gtest.h> #include <sstream> TEST(DAY06_PART01, TEST01) { const std::string map = R"( COM)B B)C C)D D)E E)F B)G G)H D)I E)J J)K K)L)"; std::istringstream iss(map); const auto graph = map2graph(iss); const auto chksum = checksum(graph); ASSERT_EQ(chksum, 42); } #endif // DO_UNIT_TEST
23.840909
80
0.659676
ovove
d5018e36c13540c04dfcdf308c8537bae3c2e67d
413
hpp
C++
include/httplib/http/response.hpp
andrusha97/httplib
3f1733ea03c009c22393a99eadc006befd5b4942
[ "MIT" ]
null
null
null
include/httplib/http/response.hpp
andrusha97/httplib
3f1733ea03c009c22393a99eadc006befd5b4942
[ "MIT" ]
null
null
null
include/httplib/http/response.hpp
andrusha97/httplib
3f1733ea03c009c22393a99eadc006befd5b4942
[ "MIT" ]
null
null
null
#pragma once #include <httplib/detail/common.hpp> #include <httplib/http/headers.hpp> #include <httplib/http/version.hpp> #include <string> HTTPLIB_OPEN_NAMESPACE struct http_response_t { unsigned int code = 0; std::string reason; http_version_t version; http_headers_t headers; }; std::ostream &operator<<(std::ostream &stream, const http_response_t &response); HTTPLIB_CLOSE_NAMESPACE
16.52
80
0.748184
andrusha97
d501a76112ee571565b25b56c1e25347067fbe08
19,005
hpp
C++
include/tudocomp/compressors/lfs/LFS2Compressor.hpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-22T11:29:02.000Z
2020-09-22T11:29:02.000Z
include/tudocomp/compressors/lfs/LFS2Compressor.hpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/tudocomp/compressors/lfs/LFS2Compressor.hpp
421408/tudocomp
9634742393995acdde148b0412f083bfdd0fbe9f
[ "ECL-2.0", "Apache-2.0" ]
1
2020-09-29T08:57:13.000Z
2020-09-29T08:57:13.000Z
#pragma once #include <tudocomp/config.h> #ifndef SDSL_FOUND #pragma message "SDSL required, but not available!" #else //std includes: #include <vector> #include <tuple> //general includes: #include <tudocomp/util.hpp> #include <tudocomp/ds/IntVector.hpp> #include <tudocomp/Compressor.hpp> #include <tudocomp/Error.hpp> #include <tudocomp/Tags.hpp> #include <tudocomp_stat/StatPhase.hpp> //sdsl include stree: #include <sdsl/suffix_trees.hpp> //includes encoding: #include <tudocomp/io/BitOStream.hpp> #include <tudocomp/coders/EliasGammaCoder.hpp> #include <tudocomp/coders/HuffmanCoder.hpp> //decompressor: #include <tudocomp/decompressors/LFS2Decompressor.hpp> namespace tdc { namespace lfs { template< typename literal_coder_t = HuffmanCoder, typename len_coder_t = EliasGammaCoder > class LFS2Compressor : public Compressor { private: //Suffix Tree type + st typedef sdsl::cst_sct3< sdsl::csa_bitcompressed<> > cst_t; cst_t stree; using node_type = typename cst_t::node_type; //Stores nts_symbols of first layer IntVector<uint> first_layer_nts; // offset to begin of last nts +1. if ==0 no substitution IntVector<uint> fl_offsets; // stores subs in first layer symbols IntVector<uint> second_layer_nts; // dead pos in first layer BitVector second_layer_dead; //pair contains begin pos, length std::vector<std::pair<uint, uint> > non_terminal_symbols; //stores node_ids of corresponding factor length std::vector<std::vector<uint> > bins; //stores beginning positions corresponding to node_ids std::vector<std::vector<uint> > node_begins; bool exact; uint size; public: inline static Meta meta() { Meta m(Compressor::type_desc(), "lfs2", "lfs2 with simst"); m.param("min_lrf").primitive(5); m.param("exact").primitive(0); m.param("lfs2_lit_coder").strategy<literal_coder_t>( Coder::type_desc(), Meta::Default<HuffmanCoder>()); m.param("lfs2_len_coder").strategy<len_coder_t>( Coder::type_desc(), Meta::Default<EliasGammaCoder>()); m.add_tag(tags::require_sentinel); return m; } using Compressor::Compressor; inline virtual void compress(Input& input, Output& output) override { uint min_lrf = config().param("min_lrf").as_uint(); exact = config().param("exact").as_bool(); auto in = input.as_view(); MissingSentinelError::check(in); //create vectors: first_layer_nts = IntVector<uint>(input.size(), 0); fl_offsets = IntVector<uint>(input.size(), 0); second_layer_nts = IntVector<uint>(input.size(), 0); second_layer_dead = BitVector(input.size(), 0); if(in.size() >= min_lrf){ StatPhase::wrap("Constructing ST", [&]{ size = in.size(); //remove sentinel because sdsl cant handle that while(in[size-1] == 0){ size--; } std::string in_string ((const char*) in.data(), size); sdsl::construct_im(stree, in_string , 1); }); StatPhase::wrap("Computing LRF", [&]{ bins.resize(200); uint node_counter = 0; typedef sdsl::cst_bfs_iterator<cst_t> iterator; iterator begin = iterator(&stree, stree.root()); iterator end = iterator(&stree, stree.root(), true, true); StatPhase::wrap("Iterate over ST", [&]{ DLOG(INFO)<<"iterate st"; for (iterator it = begin; it != end; ++it) { if(!stree.is_leaf(*it)){ if(bins.size() <= stree.depth(*it)) { uint resize = bins.size()*2; while (resize<= stree.depth(*it)) { resize*=2; } bins.resize(resize); } bins[stree.depth(*it)].push_back(stree.id(*it)); node_counter++; } } }); node_begins.resize(node_counter); uint nts_number = 1 ; StatPhase::wrap("Iterate over Node Bins", [&]{ //iterate node bins top down DLOG(INFO)<<"iterate over Node Bins"; for(uint i = bins.size()-1; i>=min_lrf; i--){ //iterate over ids in bin: while(!bins[i].empty()){ uint id = bins[i].back(); bins[i].pop_back(); node_type node = stree.inv_id(id); uint no_leaf_id = id - stree.size(); //get bps of node if(node_begins[no_leaf_id].empty()){ //get leaves or merge child vectors std::vector<uint> offsets; std::vector<uint> leaf_bps; for (auto & child : stree.children(node)) { if(stree.is_leaf(child)){ leaf_bps.push_back(stree.csa[stree.lb(child)]); } else { int child_id = stree.id(child) - stree.size(); if(!node_begins[child_id ].empty()){ //append child list, remember offset offsets.push_back(node_begins[no_leaf_id].size()); node_begins[no_leaf_id].insert(node_begins[no_leaf_id].end(),node_begins[child_id ].begin(), node_begins[child_id].end()); node_begins[child_id] = std::vector<uint>(); } } } std::sort(leaf_bps.begin(), leaf_bps.end()); offsets.push_back(node_begins[no_leaf_id].size()); node_begins[no_leaf_id].insert(node_begins[no_leaf_id].end(),leaf_bps.begin(), leaf_bps.end()); //inplace merge with offset for(uint k = 0; k < offsets.size()-1; k++){ std::inplace_merge(node_begins[no_leaf_id].begin(), node_begins[no_leaf_id].begin()+ offsets[k], node_begins[no_leaf_id].begin()+ offsets[k+1]); } //now inplace merge to end std::inplace_merge(node_begins[no_leaf_id].begin(), node_begins[no_leaf_id].begin()+ offsets.back(), node_begins[no_leaf_id].end()); } //if still empty, because everything is substituted... if(node_begins[no_leaf_id].empty()){ continue; } //check if viable lrf, else sort higher! if((node_begins[no_leaf_id].size()>=2)){ if (( (uint)( node_begins[no_leaf_id].back() - node_begins[no_leaf_id].front() )) >= i ){ //greedily iterate over occurences signed long last = 0 - (long) i; std::vector<uint> first_layer_viable; std::vector<uint> second_layer_viable; for(uint occurence : node_begins[no_leaf_id]){ //check for viability if( (last+i <= (long) occurence)){ if(fl_offsets[occurence] == 0){ if(fl_offsets[occurence + i -1] == 0){ //Position is firs layer viable first_layer_viable.push_back(occurence); last= occurence; } } else { //find nts number of symbol that corresponds to substitued occ uint parent_nts= first_layer_nts[ occurence - (fl_offsets[occurence] -1) ]; auto nts = non_terminal_symbols[parent_nts-1]; //if length of parent nts is greater than current len + offset if(nts.second >=fl_offsets[occurence]-1 + i ){ second_layer_viable.push_back(occurence); } } } } //and substitute //if at least 2 first level layer occs viable: if(first_layer_viable.size() >=1 &&(first_layer_viable.size() + second_layer_viable.size() >= 2) ) { std::pair<uint,uint> nts = std::make_pair(first_layer_viable.front(), i); non_terminal_symbols.push_back(nts); //iterate over vector, make first layer unviable: for(uint occ : first_layer_viable){ first_layer_nts[occ]= nts_number; for(uint nts_length =0; nts_length < i; nts_length++){ fl_offsets[occ + nts_length] = nts_length+1; } } for(uint sl_occ :second_layer_viable){ uint parent_nts= first_layer_nts[ sl_occ - (fl_offsets[sl_occ] -1) ]; auto parent_sym = non_terminal_symbols[parent_nts-1]; uint parent_start= parent_sym.first; uint sl_start = (parent_start + fl_offsets[sl_occ] -1); uint sl_end = sl_start+i-1; if(second_layer_dead[sl_start] == (uint)0 && second_layer_dead[sl_end] == (uint)0){ second_layer_nts[sl_start]=nts_number; for(uint dead = sl_start; dead<=sl_end;dead++){ second_layer_dead[dead]=1; } } } //raise nts number: nts_number++; } } else { if(exact){ //readd node if lrf shorter uint min_shorter = node_begins[no_leaf_id].back() - node_begins[no_leaf_id].front(); //check if parent subs this lrf node_type parent = stree.parent(node); uint depth = stree.depth(parent); if(depth < (min_shorter)){ //just re-add node, if the possible replaceable lrf is longer than dpeth of parent node bins[min_shorter].push_back(stree.id(node)); } } continue; } } } } }); }); DLOG(INFO)<<"Computing symbol depth"; IntVector<uint> nts_depth(non_terminal_symbols.size(), 0); for(uint nts_num =0; nts_num<non_terminal_symbols.size(); nts_num++){ auto symbol = non_terminal_symbols[nts_num]; uint cur_depth = nts_depth[nts_num]; for(uint pos = symbol.first; pos < symbol.second + symbol.first ; pos++){ if(second_layer_nts[pos]>0){ uint symbol_num = second_layer_nts[pos] -1; if(nts_depth[symbol_num]< cur_depth+1){ nts_depth[symbol_num]= cur_depth+1; } } } } DLOG(INFO)<<"Computing done"; std::sort(nts_depth.begin(), nts_depth.end()); if(nts_depth.size()>0){ uint max_depth = nts_depth[nts_depth.size()-1]; DLOG(INFO)<<"Max CFG Depth: "<< max_depth; DLOG(INFO)<<"Number of CFG rules: "<< non_terminal_symbols.size(); if(nts_depth.size()>=4){ uint quarter = nts_depth.size() /4; StatPhase::log("25 \% quantil CFG Depth", nts_depth[quarter -1]); StatPhase::log("50 \% quantil CFG Depth", nts_depth[(2*quarter) -1]); StatPhase::log("75 \% quantil CFG Depth", nts_depth[(3*quarter) -1]); } StatPhase::log("Max CFG Depth", max_depth); } //input size end } StatPhase::log("Number of CFG rules", non_terminal_symbols.size()); std::stringstream literals; for(uint position = 0; position< in.size(); position++){ if(fl_offsets[position]==0){ literals << in[position]; } } for(uint nts_num = 0; nts_num<non_terminal_symbols.size(); nts_num++){ auto symbol = non_terminal_symbols[nts_num]; for(uint pos = symbol.first; pos < symbol.second + symbol.first; pos++){ if(second_layer_nts[pos] == 0 && pos < in.size()){ literals<< in[pos]; } } } StatPhase::wrap("Encoding Comp", [&]{ // encode dictionary: DLOG(INFO) << "encoding dictionary symbol sizes "; std::shared_ptr<BitOStream> bitout = std::make_shared<BitOStream>(output); typename literal_coder_t::Encoder lit_coder( config().sub_config("lfs2_lit_coder"), bitout, ViewLiterals(literals.str()) ); typename len_coder_t::Encoder len_coder( config().sub_config("lfs2_len_coder"), bitout, NoLiterals() ); //encode lengths: DLOG(INFO)<<"number nts: " << non_terminal_symbols.size(); Range intrange (0, UINT_MAX); //encode first length: if(non_terminal_symbols.size()>=1){ auto symbol = non_terminal_symbols[0]; uint last_length=symbol.second; //Range for encoding nts number Range s_length_r (0,last_length); len_coder.encode(last_length,intrange); //encode delta length of following symbols for(uint nts_num = 1; nts_num < non_terminal_symbols.size(); nts_num++){ symbol = non_terminal_symbols[nts_num]; len_coder.encode(last_length-symbol.second,s_length_r); last_length=symbol.second; } //encode last length, to have zero length last len_coder.encode(symbol.second,s_length_r); }else { len_coder.encode(0ULL,intrange); } Range dict_r(0, non_terminal_symbols.size()); long buf_size = bitout->stream().tellp(); StatPhase::log("Bytes Length Encoding", buf_size); DLOG(INFO)<<"Bytes Length Encoding: "<< buf_size; DLOG(INFO) << "encoding dictionary symbols"; uint dict_literals=0; // encode dictionary strings, backwards, to directly decode strings: if(non_terminal_symbols.size()>=1){ std::pair<uint,uint> symbol; for(long nts_num =non_terminal_symbols.size()-1; nts_num >= 0; nts_num--){ symbol = non_terminal_symbols[nts_num]; for(uint pos = symbol.first; pos < symbol.second + symbol.first ; pos++){ if(second_layer_nts[pos] > 0){ lit_coder.encode(1, bit_r); lit_coder.encode(second_layer_nts[pos], dict_r); auto symbol = non_terminal_symbols[second_layer_nts[pos] -1]; pos += symbol.second - 1; } else { lit_coder.encode(0, bit_r); lit_coder.encode(in[pos],literal_r); dict_literals++; } } } } uint literals=0; buf_size = long(bitout->stream().tellp()) - buf_size; StatPhase::log("Bytes Non-Terminal Symbol Encoding", buf_size); DLOG(INFO)<<"Bytes Non-Terminal Symbol Encoding: "<< buf_size; //encode start symbol DLOG(INFO)<<"encode start symbol"; for(uint pos = 0; pos < in.size(); pos++){ if(first_layer_nts[pos]>0){ lit_coder.encode(1, bit_r); lit_coder.encode(first_layer_nts[pos], dict_r); auto symbol = non_terminal_symbols[first_layer_nts[pos] -1]; pos += symbol.second - 1; } else { lit_coder.encode(0, bit_r); lit_coder.encode(in[pos],literal_r); literals++; } } buf_size = long(bitout->stream().tellp()) - buf_size; StatPhase::log("Bytes Start Symbol Encoding", buf_size); DLOG(INFO)<<"Bytes Start Symbol Encoding: "<< buf_size; StatPhase::log("Literals in Dictionary", dict_literals); StatPhase::log("Literals in Start Symbol", literals); StatPhase::log("Literals in Input", in.size()); double literal_percent = ((double)dict_literals + (double)literals)/ (double)in.size(); StatPhase::log("Literals Encoding / Literals Input", literal_percent); DLOG(INFO)<<"encoding done"; }); } inline std::unique_ptr<Decompressor> decompressor() const override { return Algorithm::instance< LFS2Decompressor<literal_coder_t, len_coder_t>>(); } }; //namespaces closing }} #endif
37.858566
176
0.473612
421408
d5046672da82a39afaaa79a713ad8494c3e43f72
11,486
cpp
C++
background-change.cpp
2vin/background-changing
c5f33ac3d87aaad2c94b9c9c3af146c49ca1f24f
[ "MIT" ]
null
null
null
background-change.cpp
2vin/background-changing
c5f33ac3d87aaad2c94b9c9c3af146c49ca1f24f
[ "MIT" ]
1
2018-05-27T18:56:25.000Z
2018-05-27T18:56:25.000Z
background-change.cpp
2vin/background-changing
c5f33ac3d87aaad2c94b9c9c3af146c49ca1f24f
[ "MIT" ]
1
2018-09-05T11:18:06.000Z
2018-09-05T11:18:06.000Z
#include "opencv2/opencv.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> using namespace std; using namespace cv; Mat myMask; Mat myFrame; Mat origFrame; int frameCols = 0, frameRows = 0; Mat refine(Mat frame, Mat mask); static void help() { cout << "\nThis program demonstrates GrabCut segmentation -- select an object in a region\n" "and then grabcut will attempt to segment it out.\n" "Call:\n" "./grabcut <image_name>\n" "\nSelect a rectangular area around the object you want to segment\n" << "\nHot keys: \n" "\tESC - quit the program\n" "\tr - restore the original image\n" "\tn - next iteration\n" "\n" "\tleft mouse button - set rectangle\n" "\n" "\tCTRL+left mouse button - set GC_BGD pixels\n" "\tSHIFT+left mouse button - set GC_FGD pixels\n" "\n" "\tCTRL+right mouse button - set GC_PR_BGD pixels\n" "\tSHIFT+right mouse button - set GC_PR_FGD pixels\n" << endl; } const Scalar RED = Scalar(0,0,255); const Scalar PINK = Scalar(230,130,255); const Scalar BLUE = Scalar(255,0,0); const Scalar LIGHTBLUE = Scalar(255,255,160); const Scalar GREEN = Scalar(0,255,0); const int BGD_KEY = EVENT_FLAG_CTRLKEY; const int FGD_KEY = EVENT_FLAG_SHIFTKEY; static void getBinMask( const Mat& comMask, Mat& binMask ) { if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols ) binMask.create( comMask.size(), CV_8UC1 ); binMask = comMask & 1; } class GCApplication { public: enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 }; static const int radius = 2; static const int thickness = -1; void reset(); void setImageAndWinName( const Mat& _image, const string& _winName ); void showImage() const; void mouseClick( int event, int x, int y, int flags, void* param ); int nextIter(); int getIterCount() const { return iterCount; } private: void setRectInMask(); void setLblsInMask( int flags, Point p, bool isPr ); const string* winName; const Mat* image; Mat mask; Mat bgdModel, fgdModel; uchar rectState, lblsState, prLblsState; bool isInitialized; Rect rect; vector<Point> fgdPxls, bgdPxls, prFgdPxls, prBgdPxls; int iterCount; }; void GCApplication::reset() { if( !mask.empty() ) mask.setTo(Scalar::all(GC_BGD)); bgdPxls.clear(); fgdPxls.clear(); prBgdPxls.clear(); prFgdPxls.clear(); isInitialized = false; rectState = NOT_SET; lblsState = NOT_SET; prLblsState = NOT_SET; iterCount = 0; } void GCApplication::setImageAndWinName( const Mat& _image, const string& _winName ) { if( _image.empty() || _winName.empty() ) return; image = &_image; winName = &_winName; mask.create( image->size(), CV_8UC1); reset(); } void GCApplication::showImage() const { if( image->empty() || winName->empty() ) return; Mat res; Mat binMask; if( !isInitialized ) image->copyTo( res ); else { getBinMask( mask, binMask ); image->copyTo( res, binMask ); } vector<Point>::const_iterator it; for( it = bgdPxls.begin(); it != bgdPxls.end(); ++it ) circle( res, *it, radius, BLUE, thickness ); for( it = fgdPxls.begin(); it != fgdPxls.end(); ++it ) circle( res, *it, radius, RED, thickness ); for( it = prBgdPxls.begin(); it != prBgdPxls.end(); ++it ) circle( res, *it, radius, LIGHTBLUE, thickness ); for( it = prFgdPxls.begin(); it != prFgdPxls.end(); ++it ) circle( res, *it, radius, PINK, thickness ); if( rectState == IN_PROCESS || rectState == SET ) rectangle( res, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2); imshow( *winName, res ); if(!binMask.empty()) { myFrame = res.clone(); normalize(binMask, myMask, 0, 255, NORM_MINMAX, -1, Mat() ); } } void GCApplication::setRectInMask() { CV_Assert( !mask.empty() ); mask.setTo( GC_BGD ); rect.x = max(0, rect.x); rect.y = max(0, rect.y); rect.width = min(rect.width, image->cols-rect.x); rect.height = min(rect.height, image->rows-rect.y); (mask(rect)).setTo( Scalar(GC_PR_FGD) ); } void GCApplication::setLblsInMask( int flags, Point p, bool isPr ) { vector<Point> *bpxls, *fpxls; uchar bvalue, fvalue; if( !isPr ) { bpxls = &bgdPxls; fpxls = &fgdPxls; bvalue = GC_BGD; fvalue = GC_FGD; } else { bpxls = &prBgdPxls; fpxls = &prFgdPxls; bvalue = GC_PR_BGD; fvalue = GC_PR_FGD; } if( flags & BGD_KEY ) { bpxls->push_back(p); circle( mask, p, radius, bvalue, thickness ); } if( flags & FGD_KEY ) { fpxls->push_back(p); circle( mask, p, radius, fvalue, thickness ); } } void GCApplication::mouseClick( int event, int x, int y, int flags, void* ) { if( rectState == NOT_SET ) { rect = Rect( Point(0, 0), Point(frameCols,frameRows) ); rectState = SET; setRectInMask(); CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() ); //showImage(); } // TODO add bad args check switch( event ) { case EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels { bool isb = (flags & BGD_KEY) != 0, isf = (flags & FGD_KEY) != 0; if( rectState == NOT_SET && !isb && !isf ) { rectState = IN_PROCESS; rect = Rect( x, y, 1, 1 ); } if ( (isb || isf) && rectState == SET ) lblsState = IN_PROCESS; } break; case EVENT_RBUTTONDOWN: // set GC_PR_BGD(GC_PR_FGD) labels { bool isb = (flags & BGD_KEY) != 0, isf = (flags & FGD_KEY) != 0; if ( (isb || isf) && rectState == SET ) prLblsState = IN_PROCESS; } break; case EVENT_LBUTTONUP: if( rectState == IN_PROCESS ) { rect = Rect( Point(rect.x, rect.y), Point(x,y) ); rectState = SET; setRectInMask(); CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() ); showImage(); } if( lblsState == IN_PROCESS ) { setLblsInMask(flags, Point(x,y), false); lblsState = SET; showImage(); } break; case EVENT_RBUTTONUP: if( prLblsState == IN_PROCESS ) { setLblsInMask(flags, Point(x,y), true); prLblsState = SET; showImage(); } break; case EVENT_MOUSEMOVE: if( rectState == IN_PROCESS ) { rect = Rect( Point(rect.x, rect.y), Point(x,y) ); CV_Assert( bgdPxls.empty() && fgdPxls.empty() && prBgdPxls.empty() && prFgdPxls.empty() ); showImage(); } else if( lblsState == IN_PROCESS ) { setLblsInMask(flags, Point(x,y), false); showImage(); } else if( prLblsState == IN_PROCESS ) { setLblsInMask(flags, Point(x,y), true); showImage(); } break; } } int GCApplication::nextIter() { if( isInitialized ) grabCut( *image, mask, rect, bgdModel, fgdModel, 1 ); else { if( rectState != SET ) return iterCount; if( lblsState == SET || prLblsState == SET ) grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_MASK ); else grabCut( *image, mask, rect, bgdModel, fgdModel, 1, GC_INIT_WITH_RECT ); isInitialized = true; } iterCount++; bgdPxls.clear(); fgdPxls.clear(); prBgdPxls.clear(); prFgdPxls.clear(); return iterCount; } GCApplication gcapp; static void on_mouse( int event, int x, int y, int flags, void* param ) { gcapp.mouseClick( event, x, y, flags, param ); } int main( int argc, char** argv ) { string filename = argv[1]; if( filename.empty() ) { cout << "\nDurn, empty filename" << endl; return 1; } Mat image = imread( filename, 1 ); origFrame = image.clone(); if(image.cols>1200) { resize(image, image, Size(), 0.3, 0.3); } if( image.empty() ) { cout << "\n Durn, couldn't read image filename " << filename << endl; return 1; } help(); frameCols = image.cols; frameRows = image.rows; const string winName = "image"; namedWindow( winName, WINDOW_AUTOSIZE ); setMouseCallback( winName, on_mouse, 0 ); gcapp.setImageAndWinName( image, winName ); gcapp.showImage(); for(;;) { int c = waitKey(0); switch( (char) c ) { case '\x1b': cout << "Exiting ..." << endl; goto exit_main; case 'r': cout << endl; gcapp.reset(); gcapp.showImage(); break; case 'n': int iterCount = gcapp.getIterCount(); // cout << "<" << iterCount << "... "; int newIterCount = gcapp.nextIter(); if( newIterCount > iterCount ) { gcapp.showImage(); // cout << iterCount << ">" << endl; } else cout << "rect must be determined>" << endl; break; } if(!myMask.empty()) { myFrame = origFrame.clone(); resize(myMask,myMask, origFrame.size()); Mat temp = myFrame.clone(); Mat White = Mat(myFrame.rows, myFrame.cols, CV_8UC3, Scalar(255,255,255)); myMask.convertTo(myMask, CV_8UC1); Mat smooth; Mat dilated; Mat blurBin; Mat myFrame2 = myFrame.clone(); dilate(myMask, dilated, Mat()); for(int i=1; i<myFrame.cols/300; i++) { dilate(dilated, dilated, Mat()); } blur(myFrame, smooth, Size(myFrame.cols/100, myFrame.cols/100)); smooth.copyTo(myFrame, dilated); myFrame2.copyTo(myFrame, myMask); //dilate(myMask, myMask, Mat()); blur(myMask, blurBin, Size(myFrame.cols/200, myFrame.cols/200)); blurBin=blurBin; cvtColor(blurBin, blurBin, CV_GRAY2BGR); // cout<<blurBin.size()<<" "<<blurBin.channels()<<endl; Mat background = imread(argv[2]); double scale = myFrame.rows*1.0/background.rows; resize(background, background, Size(), scale, scale); background = background(Rect(0,0,myFrame.cols, myFrame.rows)); // Background image for(int i=0; i<origFrame.cols; i++) { for(int j=0; j<origFrame.rows; j++) { myFrame.at<Vec3b>(j,i)[0] = ((blurBin.at<Vec3b>(j,i)[0])/255.0)*myFrame.at<Vec3b>(j,i)[0]+((255-blurBin.at<Vec3b>(j,i)[0])/255.0)*background.at<Vec3b>(j,i)[0]; myFrame.at<Vec3b>(j,i)[1] = ((blurBin.at<Vec3b>(j,i)[1])/255.0)*myFrame.at<Vec3b>(j,i)[1]+((255-blurBin.at<Vec3b>(j,i)[0])/255.0)*background.at<Vec3b>(j,i)[1]; myFrame.at<Vec3b>(j,i)[2] = ((blurBin.at<Vec3b>(j,i)[2])/255.0)*myFrame.at<Vec3b>(j,i)[2]+((255-blurBin.at<Vec3b>(j,i)[0])/255.0)*background.at<Vec3b>(j,i)[2]; } } imshow("Result", myFrame); imwrite("Result.jpg", myFrame); } } exit_main: destroyWindow( winName ); return 0; }
27.544365
164
0.560334
2vin
d50497ebfd52764adcdd0be94bd42751cbd3ee60
2,420
cpp
C++
ar_track_alvar/src/FernPoseEstimator.cpp
dasys-lab/cnc-turtlebots
c3749d3905f85c7955a8da8cb3194f7fbe0ba64b
[ "MIT" ]
9
2018-12-08T14:50:18.000Z
2021-02-17T13:45:59.000Z
ar_track_alvar/src/FernPoseEstimator.cpp
dasys-lab/cnc-turtlebots
c3749d3905f85c7955a8da8cb3194f7fbe0ba64b
[ "MIT" ]
null
null
null
ar_track_alvar/src/FernPoseEstimator.cpp
dasys-lab/cnc-turtlebots
c3749d3905f85c7955a8da8cb3194f7fbe0ba64b
[ "MIT" ]
3
2019-12-21T02:50:39.000Z
2022-01-04T02:53:07.000Z
/* * This file is part of ALVAR, A Library for Virtual and Augmented Reality. * * Copyright 2007-2012 VTT Technical Research Centre of Finland * * Contact: VTT Augmented Reality Team <alvar.info@vtt.fi> * <http://www.vtt.fi/multimedia/alvar.html> * * ALVAR 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 ALVAR; if not, see * <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>. */ #include "FernPoseEstimator.h" namespace alvar { FernPoseEstimator::FernPoseEstimator() : mPose() , mCamera() , mCameraEC() { } FernPoseEstimator::~FernPoseEstimator() { } Pose FernPoseEstimator::pose() const { return mPose; } Camera FernPoseEstimator::camera() const { return mCamera; } bool FernPoseEstimator::setCalibration(const std::string &filename, int width, int height) { bool r1 = mCamera.SetCalib(filename.c_str(), width, height); bool r2 = mCameraEC.SetCalib(filename.c_str(), width, height); return r1 && r2; } void FernPoseEstimator::setResolution(int width, int height) { mCamera.SetRes(width, height); mCameraEC.SetRes(width, height); } void FernPoseEstimator::calculateFromPointCorrespondences(FernPoseEstimator::ModelPointVector &mpts, FernPoseEstimator::ImagePointVector &ipts) { mCamera.CalcExteriorOrientation(mpts, ipts, &mPose); // TODO replace camera->cameraec } void FernPoseEstimator::updateFromTrackedPoints(FernPoseEstimator::ExternalContainerMap &container) { mCameraEC.UpdatePose(container, &mPose); } void FernPoseEstimator::extractPlaneCoordinates(FernPoseEstimator::ExternalContainerMap &container) { ExternalContainerMap::iterator iter = container.begin(); ExternalContainerMap::iterator iter_end = container.end(); for(; iter != iter_end; ++iter) { alvar::ExternalContainer &f = iter->second; mCameraEC.Get3dOnPlane(&mPose, f.p2d, f.p3d); f.has_p3d = true; } } } // namespace alvar
28.809524
143
0.746694
dasys-lab
d504cc00313bf908d5c69ac2805bd7c2f0928032
3,192
hpp
C++
include/HaloDataOrganizer.hpp
stu314159/tLBM
1256c5b12fc315d59e08d704c6cef72200e9f01c
[ "MIT" ]
null
null
null
include/HaloDataOrganizer.hpp
stu314159/tLBM
1256c5b12fc315d59e08d704c6cef72200e9f01c
[ "MIT" ]
null
null
null
include/HaloDataOrganizer.hpp
stu314159/tLBM
1256c5b12fc315d59e08d704c6cef72200e9f01c
[ "MIT" ]
null
null
null
/* * HaloDataOrganizer.hpp * * Created on: Jun 13, 2019 * Author: stu */ #ifndef INCLUDE_HALODATAORGANIZER_HPP_ #define INCLUDE_HALODATAORGANIZER_HPP_ #include <map> #include <set> #include <algorithm> //#include "TLBM_definitions.h" #include "HaloDataObject.hpp" template <class T> class HaloDataOrganizer { public: HaloDataOrganizer(); //HaloDataOrganizer(int ngb); ~HaloDataOrganizer(); void add_neighbor(int ngbNum); int get_num_neighbors(); int get_cut_size(); int get_num_halo_nodes(); HaloDataObject<T>& operator[](int k); void print_halo(); std::set<int> get_halo_nodes() const; void allocate_halo_arrays(); void fill_arrays(std::map<int,int> & globalToLocal); static inline unsigned getIDx(int nSpd, int nIdx, int spd){ return nIdx*nSpd + spd; // return spd*nnods + nIdx; // use this if it performs faster. } void extract_halo_data(const T* fOut, const int numSpd); void insert_halo_data(T* fOut, const int numSpd); private: // map keys: neighboring partition rank. // map values: a Halo Data Object that contains a data structure describing the data to be exchanged std::map<int,HaloDataObject<T>> Halo; }; template <class T> HaloDataOrganizer<T>::HaloDataOrganizer() { } template <class T> HaloDataOrganizer<T>::~HaloDataOrganizer() { } template <class T> void HaloDataOrganizer<T>::extract_halo_data(const T* fOut, const int numSpd) { for(auto & ngbIT : Halo) { ngbIT.second.extract_halo_data(fOut,numSpd); } } template <class T> void HaloDataOrganizer<T>::insert_halo_data(T* fOut, const int numSpd) { for(auto & ngbIT: Halo) { ngbIT.second.insert_halo_data(fOut,numSpd); } } template <class T> void HaloDataOrganizer<T>::allocate_halo_arrays() { for(auto & haloIt : Halo) { haloIt.second.allocate_arrays(); } } template <class T> void HaloDataOrganizer<T>::fill_arrays(std::map<int,int> & globalToLocal) { for(auto & haloIt : Halo) { haloIt.second.fill_nums_and_speeds(globalToLocal); } } template <class T> std::set<int> HaloDataOrganizer<T>::get_halo_nodes() const { std::set<int> haloSet; std::set<int> tempSet; for(const auto & haloIt : Halo) { tempSet = haloIt.second.get_halo_nodes(); for (const auto & tIt : tempSet) { haloSet.insert(tIt); } } return haloSet; } template <class T> void HaloDataOrganizer<T>::print_halo() { for(const auto &ngb_it : Halo) { printf("Neighbor Partition %d: \n",ngb_it.first); ngb_it.second.print_halo(); } } template <class T> int HaloDataOrganizer<T>::get_cut_size() { int numCuts = 0; for (const auto & keyIter : Halo) { numCuts += keyIter.second.get_num_items(); } return numCuts; } template <class T> int HaloDataOrganizer<T>::get_num_halo_nodes() { int numHalo = 0; for (const auto & keyIter : Halo) { numHalo += keyIter.second.get_num_nodes(); } return numHalo; } template <class T> HaloDataObject<T> & HaloDataOrganizer<T>::operator[](int k) { return Halo[k]; } template <class T> int HaloDataOrganizer<T>::get_num_neighbors() { return Halo.size(); } template <class T> void HaloDataOrganizer<T>::add_neighbor(int ngbNum) { Halo[ngbNum] = HaloDataObject<T>(); } #endif /* INCLUDE_HALODATAORGANIZER_HPP_ */
18.344828
101
0.713033
stu314159
d506401b50d2e59407dc797d4fd50dff14a4fccc
983
cpp
C++
aws-cpp-sdk-clouddirectory/source/model/UpgradeAppliedSchemaRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-clouddirectory/source/model/UpgradeAppliedSchemaRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-clouddirectory/source/model/UpgradeAppliedSchemaRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/clouddirectory/model/UpgradeAppliedSchemaRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::CloudDirectory::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpgradeAppliedSchemaRequest::UpgradeAppliedSchemaRequest() : m_publishedSchemaArnHasBeenSet(false), m_directoryArnHasBeenSet(false), m_dryRun(false), m_dryRunHasBeenSet(false) { } Aws::String UpgradeAppliedSchemaRequest::SerializePayload() const { JsonValue payload; if(m_publishedSchemaArnHasBeenSet) { payload.WithString("PublishedSchemaArn", m_publishedSchemaArn); } if(m_directoryArnHasBeenSet) { payload.WithString("DirectoryArn", m_directoryArn); } if(m_dryRunHasBeenSet) { payload.WithBool("DryRun", m_dryRun); } return payload.View().WriteReadable(); }
19.27451
69
0.749746
lintonv
d508323b47303f8811d802f301ad5d8444d62e3f
6,227
cpp
C++
External/FEXCore/Source/Interface/Core/ArchHelpers/Arm64Emitter.cpp
phire/FEX
a721257cdd787bd641875ca8e138809aaad17e0c
[ "MIT" ]
628
2020-03-06T14:01:32.000Z
2022-03-31T06:35:14.000Z
External/FEXCore/Source/Interface/Core/ArchHelpers/Arm64Emitter.cpp
phire/FEX
a721257cdd787bd641875ca8e138809aaad17e0c
[ "MIT" ]
576
2020-03-06T08:25:12.000Z
2022-03-30T04:05:29.000Z
External/FEXCore/Source/Interface/Core/ArchHelpers/Arm64Emitter.cpp
phire/FEX
a721257cdd787bd641875ca8e138809aaad17e0c
[ "MIT" ]
38
2020-03-07T06:10:00.000Z
2022-03-29T09:27:36.000Z
#include "Interface/Core/ArchHelpers/Arm64Emitter.h" #include <FEXCore/Utils/LogManager.h> #include <FEXCore/Core/CoreState.h> #include "aarch64/cpu-aarch64.h" #include "cpu-features.h" #include "aarch64/instructions-aarch64.h" #include "utils-vixl.h" #include <tuple> namespace FEXCore::CPU { #define STATE x28 // We want vixl to not allocate a default buffer. Jit and dispatcher will manually create one. Arm64Emitter::Arm64Emitter(size_t size) : vixl::aarch64::Assembler(size, vixl::aarch64::PositionDependentCode) { CPU.SetUp(); auto Features = vixl::CPUFeatures::InferFromOS(); SupportsAtomics = Features.Has(vixl::CPUFeatures::Feature::kAtomics); // RCPC is bugged on Snapdragon 865 // Causes glibc cond16 test to immediately throw assert // __pthread_mutex_cond_lock: Assertion `mutex->__data.__owner == 0' SupportsRCPC = false; //Features.Has(vixl::CPUFeatures::Feature::kRCpc); if (SupportsAtomics) { // Hypervisor can hide this on the c630? Features.Combine(vixl::CPUFeatures::Feature::kLORegions); } SetCPUFeatures(Features); if (!SupportsAtomics) { WARN_ONCE("Host CPU doesn't support atomics. Expect bad performance"); } #ifdef _M_ARM_64 // We need to get the CPU's cache line size // We expect sane targets that have correct cacheline sizes across clusters uint64_t CTR; __asm volatile ("mrs %[ctr], ctr_el0" : [ctr] "=r"(CTR)); DCacheLineSize = 4 << ((CTR >> 16) & 0xF); ICacheLineSize = 4 << (CTR & 0xF); #endif } void Arm64Emitter::LoadConstant(vixl::aarch64::Register Reg, uint64_t Constant) { bool Is64Bit = Reg.IsX(); int Segments = Is64Bit ? 4 : 2; if (Is64Bit && ((~Constant)>> 16) == 0) { movn(Reg, (~Constant) & 0xFFFF); return; } movz(Reg, (Constant) & 0xFFFF, 0); for (int i = 1; i < Segments; ++i) { uint16_t Part = (Constant >> (i * 16)) & 0xFFFF; if (Part) { movk(Reg, Part, i * 16); } } } void Arm64Emitter::PushCalleeSavedRegisters() { // We need to save pairs of registers // We save r19-r30 MemOperand PairOffset(sp, -16, PreIndex); const std::array<std::pair<vixl::aarch64::XRegister, vixl::aarch64::XRegister>, 6> CalleeSaved = {{ {x19, x20}, {x21, x22}, {x23, x24}, {x25, x26}, {x27, x28}, {x29, x30}, }}; for (auto &RegPair : CalleeSaved) { stp(RegPair.first, RegPair.second, PairOffset); } // Additionally we need to store the lower 64bits of v8-v15 // Here's a fun thing, we can use two ST4 instructions to store everything // We just need a single sub to sp before that const std::array< std::tuple<vixl::aarch64::VRegister, vixl::aarch64::VRegister, vixl::aarch64::VRegister, vixl::aarch64::VRegister>, 2> FPRs = {{ {v8, v9, v10, v11}, {v12, v13, v14, v15}, }}; uint32_t VectorSaveSize = sizeof(uint64_t) * 8; sub(sp, sp, VectorSaveSize); // SP supporting move // We just saved x19 so it is safe add(x19, sp, 0); MemOperand QuadOffset(x19, 32, PostIndex); for (auto &RegQuad : FPRs) { st4(std::get<0>(RegQuad).D(), std::get<1>(RegQuad).D(), std::get<2>(RegQuad).D(), std::get<3>(RegQuad).D(), 0, QuadOffset); } } void Arm64Emitter::PopCalleeSavedRegisters() { const std::array< std::tuple<vixl::aarch64::VRegister, vixl::aarch64::VRegister, vixl::aarch64::VRegister, vixl::aarch64::VRegister>, 2> FPRs = {{ {v12, v13, v14, v15}, {v8, v9, v10, v11}, }}; MemOperand QuadOffset(sp, 32, PostIndex); for (auto &RegQuad : FPRs) { ld4(std::get<0>(RegQuad).D(), std::get<1>(RegQuad).D(), std::get<2>(RegQuad).D(), std::get<3>(RegQuad).D(), 0, QuadOffset); } MemOperand PairOffset(sp, 16, PostIndex); const std::array<std::pair<vixl::aarch64::XRegister, vixl::aarch64::XRegister>, 6> CalleeSaved = {{ {x29, x30}, {x27, x28}, {x25, x26}, {x23, x24}, {x21, x22}, {x19, x20}, }}; for (auto &RegPair : CalleeSaved) { ldp(RegPair.first, RegPair.second, PairOffset); } } void Arm64Emitter::SpillStaticRegs() { if (StaticRegisterAllocation()) { for (size_t i = 0; i < SRA64.size(); i+=2) { stp(SRA64[i], SRA64[i+1], MemOperand(STATE, offsetof(FEXCore::Core::CpuStateFrame, State.gregs[i]))); } for (size_t i = 0; i < SRAFPR.size(); i+=2) { stp(SRAFPR[i].Q(), SRAFPR[i+1].Q(), MemOperand(STATE, offsetof(FEXCore::Core::CpuStateFrame, State.xmm[i][0]))); } } } void Arm64Emitter::FillStaticRegs() { if (StaticRegisterAllocation()) { for (size_t i = 0; i < SRA64.size(); i+=2) { ldp(SRA64[i], SRA64[i+1], MemOperand(STATE, offsetof(FEXCore::Core::CpuStateFrame, State.gregs[i]))); } for (size_t i = 0; i < SRAFPR.size(); i+=2) { ldp(SRAFPR[i].Q(), SRAFPR[i+1].Q(), MemOperand(STATE, offsetof(FEXCore::Core::CpuStateFrame, State.xmm[i][0]))); } } } void Arm64Emitter::PushDynamicRegsAndLR() { uint64_t SPOffset = AlignUp((RA64.size() + 1) * 8 + RAFPR.size() * 16, 16); sub(sp, sp, SPOffset); int i = 0; for (auto RA : RAFPR) { str(RA.Q(), MemOperand(sp, i * 8)); i+=2; } #if 0 // All GPRs should be caller saved for (auto RA : RA64) { str(RA, MemOperand(sp, i * 8)); i++; } #endif str(lr, MemOperand(sp, i * 8)); } void Arm64Emitter::PopDynamicRegsAndLR() { uint64_t SPOffset = AlignUp((RA64.size() + 1) * 8 + RAFPR.size() * 16, 16); int i = 0; for (auto RA : RAFPR) { ldr(RA.Q(), MemOperand(sp, i * 8)); i+=2; } #if 0 // All GPRs should be caller saved for (auto RA : RA64) { ldr(RA, MemOperand(sp, i * 8)); i++; } #endif ldr(lr, MemOperand(sp, i * 8)); add(sp, sp, SPOffset); } void Arm64Emitter::ResetStack() { if (SpillSlots == 0) return; if (IsImmAddSub(SpillSlots * 16)) { add(sp, sp, SpillSlots * 16); } else { // Too big to fit in a 12bit immediate LoadConstant(x0, SpillSlots * 16); add(sp, sp, x0); } } void Arm64Emitter::Align16B() { uint64_t CurrentOffset = GetCursorAddress<uint64_t>(); for (uint64_t i = (16 - (CurrentOffset & 0xF)); i != 0; i -= 4) { nop(); } } }
25.838174
118
0.612012
phire
d50a7c441af412f4a480c5d5986a2cba15bf6819
12,139
cpp
C++
chromium/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/modules/fetch/BodyStreamBufferTest.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 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 "modules/fetch/BodyStreamBuffer.h" #include "core/testing/DummyPageHolder.h" #include "modules/fetch/DataConsumerHandleTestUtil.h" #include "platform/testing/UnitTestHelpers.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "wtf/OwnPtr.h" namespace blink { namespace { using ::testing::InSequence; using ::testing::_; using ::testing::SaveArg; using Checkpoint = ::testing::StrictMock<::testing::MockFunction<void(int)>>; using Command = DataConsumerHandleTestUtil::Command; using ReplayingHandle = DataConsumerHandleTestUtil::ReplayingHandle; using MockFetchDataLoaderClient = DataConsumerHandleTestUtil::MockFetchDataLoaderClient; class BodyStreamBufferTest : public ::testing::Test { public: BodyStreamBufferTest() { m_page = DummyPageHolder::create(IntSize(1, 1)); } ~BodyStreamBufferTest() override {} protected: ScriptState* scriptState() { return ScriptState::forMainWorld(m_page->document().frame()); } ExecutionContext* executionContext() { return &m_page->document(); } OwnPtr<DummyPageHolder> m_page; }; TEST_F(BodyStreamBufferTest, ReleaseHandle) { OwnPtr<FetchDataConsumerHandle> handle = createFetchDataConsumerHandleFromWebHandle(createWaitingDataConsumerHandle()); FetchDataConsumerHandle* rawHandle = handle.get(); BodyStreamBuffer* buffer = new BodyStreamBuffer(handle.release()); EXPECT_FALSE(buffer->hasPendingActivity()); EXPECT_FALSE(buffer->stream()->isLocked()); EXPECT_FALSE(buffer->stream()->isDisturbed()); EXPECT_EQ(ReadableStream::Readable, buffer->stream()->stateInternal()); OwnPtr<FetchDataConsumerHandle> handle2 = buffer->releaseHandle(executionContext()); ASSERT_EQ(rawHandle, handle2.get()); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_EQ(ReadableStream::Closed, buffer->stream()->stateInternal()); } TEST_F(BodyStreamBufferTest, LoadBodyStreamBufferAsArrayBuffer) { Checkpoint checkpoint; MockFetchDataLoaderClient* client = MockFetchDataLoaderClient::create(); RefPtr<DOMArrayBuffer> arrayBuffer; InSequence s; EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*client, didFetchDataLoadedArrayBufferMock(_)).WillOnce(SaveArg<0>(&arrayBuffer)); EXPECT_CALL(checkpoint, Call(2)); OwnPtr<ReplayingHandle> handle = ReplayingHandle::create(); handle->add(Command(Command::Data, "hello")); handle->add(Command(Command::Done)); BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(handle.release())); buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsArrayBuffer(), client); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_TRUE(buffer->hasPendingActivity()); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); ASSERT_TRUE(arrayBuffer); EXPECT_EQ("hello", String(static_cast<const char*>(arrayBuffer->data()), arrayBuffer->byteLength())); } TEST_F(BodyStreamBufferTest, LoadBodyStreamBufferAsBlob) { Checkpoint checkpoint; MockFetchDataLoaderClient* client = MockFetchDataLoaderClient::create(); RefPtr<BlobDataHandle> blobDataHandle; InSequence s; EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*client, didFetchDataLoadedBlobHandleMock(_)).WillOnce(SaveArg<0>(&blobDataHandle)); EXPECT_CALL(checkpoint, Call(2)); OwnPtr<ReplayingHandle> handle = ReplayingHandle::create(); handle->add(Command(Command::Data, "hello")); handle->add(Command(Command::Done)); BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(handle.release())); buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsBlobHandle("text/plain"), client); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_TRUE(buffer->hasPendingActivity()); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); EXPECT_EQ(5u, blobDataHandle->size()); } TEST_F(BodyStreamBufferTest, LoadBodyStreamBufferAsString) { Checkpoint checkpoint; MockFetchDataLoaderClient* client = MockFetchDataLoaderClient::create(); InSequence s; EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*client, didFetchDataLoadedString(String("hello"))); EXPECT_CALL(checkpoint, Call(2)); OwnPtr<ReplayingHandle> handle = ReplayingHandle::create(); handle->add(Command(Command::Data, "hello")); handle->add(Command(Command::Done)); BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(handle.release())); buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsString(), client); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_TRUE(buffer->hasPendingActivity()); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); } TEST_F(BodyStreamBufferTest, ReleaseClosedHandle) { BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(createDoneDataConsumerHandle())); EXPECT_EQ(ReadableStream::Readable, buffer->stream()->stateInternal()); testing::runPendingTasks(); EXPECT_EQ(ReadableStream::Closed, buffer->stream()->stateInternal()); EXPECT_FALSE(buffer->stream()->isLocked()); EXPECT_FALSE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); OwnPtr<FetchDataConsumerHandle> handle = buffer->releaseHandle(executionContext()); EXPECT_TRUE(handle); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); } TEST_F(BodyStreamBufferTest, LoadClosedHandle) { Checkpoint checkpoint; MockFetchDataLoaderClient* client = MockFetchDataLoaderClient::create(); InSequence s; EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*client, didFetchDataLoadedString(String(""))); EXPECT_CALL(checkpoint, Call(2)); BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(createDoneDataConsumerHandle())); EXPECT_EQ(ReadableStream::Readable, buffer->stream()->stateInternal()); testing::runPendingTasks(); EXPECT_EQ(ReadableStream::Closed, buffer->stream()->stateInternal()); EXPECT_FALSE(buffer->stream()->isLocked()); EXPECT_FALSE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsString(), client); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_TRUE(buffer->hasPendingActivity()); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); } TEST_F(BodyStreamBufferTest, ReleaseErroredHandle) { BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(createUnexpectedErrorDataConsumerHandle())); EXPECT_EQ(ReadableStream::Readable, buffer->stream()->stateInternal()); testing::runPendingTasks(); EXPECT_EQ(ReadableStream::Errored, buffer->stream()->stateInternal()); EXPECT_FALSE(buffer->stream()->isLocked()); EXPECT_FALSE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); OwnPtr<FetchDataConsumerHandle> handle = buffer->releaseHandle(executionContext()); EXPECT_TRUE(handle); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); } TEST_F(BodyStreamBufferTest, LoadErroredHandle) { Checkpoint checkpoint; MockFetchDataLoaderClient* client = MockFetchDataLoaderClient::create(); InSequence s; EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*client, didFetchDataLoadFailed()); EXPECT_CALL(checkpoint, Call(2)); BodyStreamBuffer* buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(createUnexpectedErrorDataConsumerHandle())); EXPECT_EQ(ReadableStream::Readable, buffer->stream()->stateInternal()); testing::runPendingTasks(); EXPECT_EQ(ReadableStream::Errored, buffer->stream()->stateInternal()); EXPECT_FALSE(buffer->stream()->isLocked()); EXPECT_FALSE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsString(), client); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_TRUE(buffer->hasPendingActivity()); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2); EXPECT_TRUE(buffer->stream()->isLocked()); EXPECT_TRUE(buffer->stream()->isDisturbed()); EXPECT_FALSE(buffer->hasPendingActivity()); } TEST_F(BodyStreamBufferTest, LoaderShouldBeKeptAliveByBodyStreamBuffer) { Checkpoint checkpoint; MockFetchDataLoaderClient* client = MockFetchDataLoaderClient::create(); InSequence s; EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*client, didFetchDataLoadedString(String("hello"))); EXPECT_CALL(checkpoint, Call(2)); OwnPtr<ReplayingHandle> handle = ReplayingHandle::create(); handle->add(Command(Command::Data, "hello")); handle->add(Command(Command::Done)); Persistent<BodyStreamBuffer> buffer = new BodyStreamBuffer(createFetchDataConsumerHandleFromWebHandle(handle.release())); buffer->startLoading(executionContext(), FetchDataLoader::createLoaderAsString(), client); Heap::collectAllGarbage(); checkpoint.Call(1); testing::runPendingTasks(); checkpoint.Call(2); } // TODO(hiroshige): Merge this class into MockFetchDataConsumerHandle. class MockFetchDataConsumerHandleWithMockDestructor : public DataConsumerHandleTestUtil::MockFetchDataConsumerHandle { public: static PassOwnPtr<::testing::StrictMock<MockFetchDataConsumerHandleWithMockDestructor>> create() { return adoptPtr(new ::testing::StrictMock<MockFetchDataConsumerHandleWithMockDestructor>); } ~MockFetchDataConsumerHandleWithMockDestructor() override { destruct(); } MOCK_METHOD0(destruct, void()); }; TEST_F(BodyStreamBufferTest, SourceHandleAndReaderShouldBeDestructedWhenCanceled) { ScriptState::Scope scope(scriptState()); using MockHandle = MockFetchDataConsumerHandleWithMockDestructor; using MockReader = DataConsumerHandleTestUtil::MockFetchDataConsumerReader; OwnPtr<MockHandle> handle = MockHandle::create(); OwnPtr<MockReader> reader = MockReader::create(); Checkpoint checkpoint; InSequence s; EXPECT_CALL(*handle, obtainReaderInternal(_)).WillOnce(::testing::Return(reader.get())); EXPECT_CALL(checkpoint, Call(1)); EXPECT_CALL(*reader, destruct()); EXPECT_CALL(*handle, destruct()); EXPECT_CALL(checkpoint, Call(2)); // |reader| is adopted by |obtainReader|. ASSERT_TRUE(reader.leakPtr()); BodyStreamBuffer* buffer = new BodyStreamBuffer(handle.release()); checkpoint.Call(1); ScriptValue reason(scriptState(), v8String(scriptState()->isolate(), "reason")); buffer->cancelSource(scriptState(), reason); checkpoint.Call(2); } } // namespace } // namespace blink
37.816199
195
0.743142
wedataintelligence
d50a813b21c4a7125a568638f8d335fae4043844
115
cpp
C++
imgui_glfw_binding_source.cpp
CheezLang/imgui
984aa3e5be8d240e19ba6f2395c607320145d32e
[ "MIT" ]
null
null
null
imgui_glfw_binding_source.cpp
CheezLang/imgui
984aa3e5be8d240e19ba6f2395c607320145d32e
[ "MIT" ]
null
null
null
imgui_glfw_binding_source.cpp
CheezLang/imgui
984aa3e5be8d240e19ba6f2395c607320145d32e
[ "MIT" ]
null
null
null
#if !defined(DONT_DEFINE_TYPES) #endif #include "F:/Programming/CppLibs/imgui/imgui/examples/imgui_impl_glfw.h"
16.428571
72
0.791304
CheezLang
d50bb228f8c4f9cb398f2eafa5b7e51afb5899f1
12,432
cc
C++
third_party/webrtc/src/webrtc/video/video_receive_stream.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
8
2016-02-08T11:59:31.000Z
2020-05-31T15:19:54.000Z
third_party/webrtc/src/webrtc/video/video_receive_stream.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
third_party/webrtc/src/webrtc/video/video_receive_stream.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video/video_receive_stream.h" #include <stdlib.h> #include <string> #include "webrtc/base/checks.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/video/receive_statistics_proxy.h" #include "webrtc/video_encoder.h" #include "webrtc/video_receive_stream.h" namespace webrtc { std::string VideoReceiveStream::Decoder::ToString() const { std::stringstream ss; ss << "{decoder: " << (decoder != nullptr ? "(VideoDecoder)" : "nullptr"); ss << ", payload_type: " << payload_type; ss << ", payload_name: " << payload_name; ss << ", is_renderer: " << (is_renderer ? "yes" : "no"); ss << ", expected_delay_ms: " << expected_delay_ms; ss << '}'; return ss.str(); } std::string VideoReceiveStream::Config::ToString() const { std::stringstream ss; ss << "{decoders: ["; for (size_t i = 0; i < decoders.size(); ++i) { ss << decoders[i].ToString(); if (i != decoders.size() - 1) ss << ", "; } ss << ']'; ss << ", rtp: " << rtp.ToString(); ss << ", renderer: " << (renderer != nullptr ? "(renderer)" : "nullptr"); ss << ", render_delay_ms: " << render_delay_ms; if (!sync_group.empty()) ss << ", sync_group: " << sync_group; ss << ", pre_decode_callback: " << (pre_decode_callback != nullptr ? "(EncodedFrameObserver)" : "nullptr"); ss << ", pre_render_callback: " << (pre_render_callback != nullptr ? "(I420FrameCallback)" : "nullptr"); ss << ", target_delay_ms: " << target_delay_ms; ss << '}'; return ss.str(); } std::string VideoReceiveStream::Config::Rtp::ToString() const { std::stringstream ss; ss << "{remote_ssrc: " << remote_ssrc; ss << ", local_ssrc: " << local_ssrc; ss << ", rtcp_mode: " << (rtcp_mode == RtcpMode::kCompound ? "RtcpMode::kCompound" : "RtcpMode::kReducedSize"); ss << ", rtcp_xr: "; ss << "{receiver_reference_time_report: " << (rtcp_xr.receiver_reference_time_report ? "on" : "off"); ss << '}'; ss << ", remb: " << (remb ? "on" : "off"); ss << ", nack: {rtp_history_ms: " << nack.rtp_history_ms << '}'; ss << ", fec: " << fec.ToString(); ss << ", rtx: {"; for (auto& kv : rtx) { ss << kv.first << " -> "; ss << "{ssrc: " << kv.second.ssrc; ss << ", payload_type: " << kv.second.payload_type; ss << '}'; } ss << '}'; ss << ", extensions: ["; for (size_t i = 0; i < extensions.size(); ++i) { ss << extensions[i].ToString(); if (i != extensions.size() - 1) ss << ", "; } ss << ']'; ss << '}'; return ss.str(); } namespace internal { namespace { VideoCodec CreateDecoderVideoCodec(const VideoReceiveStream::Decoder& decoder) { VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.plType = decoder.payload_type; strcpy(codec.plName, decoder.payload_name.c_str()); if (decoder.payload_name == "VP8") { codec.codecType = kVideoCodecVP8; } else if (decoder.payload_name == "VP9") { codec.codecType = kVideoCodecVP9; } else if (decoder.payload_name == "H264") { codec.codecType = kVideoCodecH264; } else { codec.codecType = kVideoCodecGeneric; } if (codec.codecType == kVideoCodecVP8) { codec.codecSpecific.VP8 = VideoEncoder::GetDefaultVp8Settings(); } else if (codec.codecType == kVideoCodecVP9) { codec.codecSpecific.VP9 = VideoEncoder::GetDefaultVp9Settings(); } else if (codec.codecType == kVideoCodecH264) { codec.codecSpecific.H264 = VideoEncoder::GetDefaultH264Settings(); } codec.width = 320; codec.height = 180; codec.startBitrate = codec.minBitrate = codec.maxBitrate = Call::Config::kDefaultStartBitrateBps / 1000; return codec; } } // namespace VideoReceiveStream::VideoReceiveStream(int num_cpu_cores, ChannelGroup* channel_group, int channel_id, const VideoReceiveStream::Config& config, webrtc::VoiceEngine* voice_engine) : transport_adapter_(config.rtcp_send_transport), encoded_frame_proxy_(config.pre_decode_callback), config_(config), clock_(Clock::GetRealTimeClock()), channel_group_(channel_group), channel_id_(channel_id) { RTC_CHECK(channel_group_->CreateReceiveChannel( channel_id_, &transport_adapter_, num_cpu_cores, config)); vie_channel_ = channel_group_->GetChannel(channel_id_); // TODO(pbos): This is not fine grained enough... vie_channel_->SetProtectionMode(config_.rtp.nack.rtp_history_ms > 0, false, -1, -1); vie_channel_->SetKeyFrameRequestMethod(kKeyFrameReqPliRtcp); RTC_DCHECK(config_.rtp.rtcp_mode != RtcpMode::kOff) << "A stream should not be configured with RTCP disabled. This value is " "reserved for internal usage."; vie_channel_->SetRTCPMode(config_.rtp.rtcp_mode); RTC_DCHECK(config_.rtp.remote_ssrc != 0); // TODO(pbos): What's an appropriate local_ssrc for receive-only streams? RTC_DCHECK(config_.rtp.local_ssrc != 0); RTC_DCHECK(config_.rtp.remote_ssrc != config_.rtp.local_ssrc); vie_channel_->SetSSRC(config_.rtp.local_ssrc, kViEStreamTypeNormal, 0); // TODO(pbos): Support multiple RTX, per video payload. Config::Rtp::RtxMap::const_iterator it = config_.rtp.rtx.begin(); for (; it != config_.rtp.rtx.end(); ++it) { RTC_DCHECK(it->second.ssrc != 0); RTC_DCHECK(it->second.payload_type != 0); vie_channel_->SetRemoteSSRCType(kViEStreamTypeRtx, it->second.ssrc); vie_channel_->SetRtxReceivePayloadType(it->second.payload_type, it->first); } // TODO(pbos): Remove channel_group_ usage from VideoReceiveStream. This // should be configured in call.cc. channel_group_->SetChannelRembStatus(false, config_.rtp.remb, vie_channel_); for (size_t i = 0; i < config_.rtp.extensions.size(); ++i) { const std::string& extension = config_.rtp.extensions[i].name; int id = config_.rtp.extensions[i].id; // One-byte-extension local identifiers are in the range 1-14 inclusive. RTC_DCHECK_GE(id, 1); RTC_DCHECK_LE(id, 14); if (extension == RtpExtension::kTOffset) { RTC_CHECK_EQ(0, vie_channel_->SetReceiveTimestampOffsetStatus(true, id)); } else if (extension == RtpExtension::kAbsSendTime) { RTC_CHECK_EQ(0, vie_channel_->SetReceiveAbsoluteSendTimeStatus(true, id)); } else if (extension == RtpExtension::kVideoRotation) { RTC_CHECK_EQ(0, vie_channel_->SetReceiveVideoRotationStatus(true, id)); } else if (extension == RtpExtension::kTransportSequenceNumber) { RTC_CHECK_EQ(0, vie_channel_->SetReceiveTransportSequenceNumber(true, id)); } else { RTC_NOTREACHED() << "Unsupported RTP extension."; } } if (config_.rtp.fec.ulpfec_payload_type != -1) { // ULPFEC without RED doesn't make sense. RTC_DCHECK(config_.rtp.fec.red_payload_type != -1); VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.codecType = kVideoCodecULPFEC; strcpy(codec.plName, "ulpfec"); codec.plType = config_.rtp.fec.ulpfec_payload_type; RTC_CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); } if (config_.rtp.fec.red_payload_type != -1) { VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.codecType = kVideoCodecRED; strcpy(codec.plName, "red"); codec.plType = config_.rtp.fec.red_payload_type; RTC_CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); if (config_.rtp.fec.red_rtx_payload_type != -1) { vie_channel_->SetRtxReceivePayloadType( config_.rtp.fec.red_rtx_payload_type, config_.rtp.fec.red_payload_type); } } if (config.rtp.rtcp_xr.receiver_reference_time_report) vie_channel_->SetRtcpXrRrtrStatus(true); stats_proxy_.reset( new ReceiveStatisticsProxy(config_.rtp.remote_ssrc, clock_)); vie_channel_->RegisterReceiveStatisticsProxy(stats_proxy_.get()); vie_channel_->RegisterReceiveChannelRtcpStatisticsCallback( stats_proxy_.get()); vie_channel_->RegisterReceiveChannelRtpStatisticsCallback(stats_proxy_.get()); vie_channel_->RegisterRtcpPacketTypeCounterObserver(stats_proxy_.get()); RTC_DCHECK(!config_.decoders.empty()); for (size_t i = 0; i < config_.decoders.size(); ++i) { const Decoder& decoder = config_.decoders[i]; RTC_CHECK_EQ(0, vie_channel_->RegisterExternalDecoder( decoder.payload_type, decoder.decoder, decoder.is_renderer, decoder.is_renderer ? decoder.expected_delay_ms : config.render_delay_ms)); VideoCodec codec = CreateDecoderVideoCodec(decoder); RTC_CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); } incoming_video_stream_.reset(new IncomingVideoStream(0)); incoming_video_stream_->SetExpectedRenderDelay(config.render_delay_ms); incoming_video_stream_->SetExternalCallback(this); vie_channel_->SetIncomingVideoStream(incoming_video_stream_.get()); if (config.pre_decode_callback) vie_channel_->RegisterPreDecodeImageCallback(&encoded_frame_proxy_); vie_channel_->RegisterPreRenderCallback(this); } VideoReceiveStream::~VideoReceiveStream() { incoming_video_stream_->Stop(); vie_channel_->RegisterPreRenderCallback(nullptr); vie_channel_->RegisterPreDecodeImageCallback(nullptr); for (size_t i = 0; i < config_.decoders.size(); ++i) vie_channel_->DeRegisterExternalDecoder(config_.decoders[i].payload_type); channel_group_->DeleteChannel(channel_id_); } void VideoReceiveStream::Start() { transport_adapter_.Enable(); incoming_video_stream_->Start(); vie_channel_->StartReceive(); } void VideoReceiveStream::Stop() { incoming_video_stream_->Stop(); vie_channel_->StopReceive(); transport_adapter_.Disable(); } void VideoReceiveStream::SetSyncChannel(VoiceEngine* voice_engine, int audio_channel_id) { if (voice_engine != nullptr && audio_channel_id != -1) { VoEVideoSync* voe_sync_interface = VoEVideoSync::GetInterface(voice_engine); vie_channel_->SetVoiceChannel(audio_channel_id, voe_sync_interface); voe_sync_interface->Release(); } else { vie_channel_->SetVoiceChannel(-1, nullptr); } } VideoReceiveStream::Stats VideoReceiveStream::GetStats() const { return stats_proxy_->GetStats(); } bool VideoReceiveStream::DeliverRtcp(const uint8_t* packet, size_t length) { return vie_channel_->ReceivedRTCPPacket(packet, length) == 0; } bool VideoReceiveStream::DeliverRtp(const uint8_t* packet, size_t length, const PacketTime& packet_time) { return vie_channel_->ReceivedRTPPacket(packet, length, packet_time) == 0; } void VideoReceiveStream::FrameCallback(VideoFrame* video_frame) { stats_proxy_->OnDecodedFrame(); // Post processing is not supported if the frame is backed by a texture. if (video_frame->native_handle() == NULL) { if (config_.pre_render_callback) config_.pre_render_callback->FrameCallback(video_frame); } } int VideoReceiveStream::RenderFrame(const uint32_t /*stream_id*/, const VideoFrame& video_frame) { // TODO(pbos): Wire up config_.render->IsTextureSupported() and convert if not // supported. Or provide methods for converting a texture frame in // VideoFrame. if (config_.renderer != nullptr) config_.renderer->RenderFrame( video_frame, video_frame.render_time_ms() - clock_->TimeInMilliseconds()); stats_proxy_->OnRenderedFrame(video_frame.width(), video_frame.height()); return 0; } void VideoReceiveStream::SignalNetworkState(NetworkState state) { vie_channel_->SetRTCPMode(state == kNetworkUp ? config_.rtp.rtcp_mode : RtcpMode::kOff); } } // namespace internal } // namespace webrtc
36.890208
80
0.677687
bopopescu
d50bc9912659c9fac76afa8c42977160281ba429
1,601
cpp
C++
sources/tests/src/licensetestsuite.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
3
2020-07-30T19:41:00.000Z
2020-10-28T12:52:37.000Z
sources/tests/src/licensetestsuite.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
null
null
null
sources/tests/src/licensetestsuite.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
2
2020-05-11T03:19:00.000Z
2021-07-07T17:40:47.000Z
/** ########################################################################## # If not stated otherwise in this file or this component's LICENSE # file the following copyright and licenses apply: # # Copyright 2019 RDK Management # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## **/ #ifdef HAS_LICENSE #include "licensetestssuite.h" #include "utils/misc/license.h" #define LICENSE_FILE "./License.lic" LicenseTestsSuite::LicenseTestsSuite() : BaseTestsSuite() { } LicenseTestsSuite::~LicenseTestsSuite() { } void LicenseTestsSuite::Run() { License::SetLicenseFile(LICENSE_FILE); License *pLicense = License::GetLicenseInstance(); LICENSE_VALIDATION retval = pLicense->ValidateLicense(); printf("ValidateLicense: %s\n", (pLicense->InterpretValidationCode(retval)).c_str()); TS_ASSERT((retval == VALID) || (retval == FOR_LM_VERIFICATION)); string licContents; TS_ASSERT(pLicense->StringifyLicense(licContents) > 0); License::ResetLicense(); } #endif /* HAS_LICENSE */
32.02
87
0.663335
rdkcmf
d50d608dc4b92b0c6251b547d8b1de3d39119f2a
17,818
cpp
C++
Plugin/Source/PluginProcessor.cpp
b00leant/audiogridder
719ba3b83befa7cb371028c592f4246757dcd31e
[ "MIT" ]
1
2020-05-06T12:52:45.000Z
2020-05-06T12:52:45.000Z
Plugin/Source/PluginProcessor.cpp
b00leant/audiogridder
719ba3b83befa7cb371028c592f4246757dcd31e
[ "MIT" ]
null
null
null
Plugin/Source/PluginProcessor.cpp
b00leant/audiogridder
719ba3b83befa7cb371028c592f4246757dcd31e
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 Andreas Pohl * Licensed under MIT (https://github.com/apohl79/audiogridder/blob/master/COPYING) * * Author: Andreas Pohl */ #include "PluginProcessor.hpp" #include <signal.h> #include "PluginEditor.hpp" #include "json.hpp" using json = nlohmann::json; AudioGridderAudioProcessor::AudioGridderAudioProcessor() #ifndef JucePlugin_PreferredChannelConfigurations : AudioProcessor(BusesProperties() #if !JucePlugin_IsMidiEffect #if !JucePlugin_IsSynth .withInput("Input", AudioChannelSet::stereo(), true) #endif .withOutput("Output", AudioChannelSet::stereo(), true) #endif ), #endif m_client(this) { signal(SIGPIPE, SIG_IGN); File cfg(PLUGIN_CONFIG_FILE); try { if (cfg.exists()) { FileInputStream fis(cfg); json j = json::parse(fis.readEntireStreamAsString().toStdString()); if (j.find("Servers") != j.end()) { for (auto& srv : j["Servers"]) { m_servers.push_back(srv.get<std::string>()); } } if (j.find("Last") != j.end()) { m_activeServer = j["Last"].get<int>(); } if (j.find("NumberOfBuffers") != j.end()) { m_client.NUM_OF_BUFFERS = j["NumberOfBuffers"].get<int>(); } if (j.find("NumberOfAutomationSlots") != j.end()) { m_numberOfAutomationSlots = j["NumberOfAutomationSlots"].get<int>(); } } } catch (json::parse_error& e) { logln_clnt(&m_client, "parsing config failed: " << e.what()); } m_unusedParam.name = "(unassigned)"; m_unusedDummyPlugin.name = "(unused)"; m_unusedDummyPlugin.bypassed = false; m_unusedDummyPlugin.ok = true; m_unusedDummyPlugin.params.add(m_unusedParam); for (int i = 0; i < m_numberOfAutomationSlots; i++) { addParameter(new Parameter(*this, i)); } // load plugins on reconnect m_client.setOnConnectCallback([this] { int idx = 0; for (auto& p : m_loadedPlugins) { p.ok = m_client.addPlugin(p.id, p.presets, p.params, p.settings); logln_clnt(&m_client, "loading " << p.name << " (" << p.id << ")... " << (p.ok ? "ok" : "failed")); if (p.ok) { logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples()); setLatencySamples(m_client.getLatencySamples()); if (p.bypassed) { m_client.bypassPlugin(idx); } for (auto& p : p.params) { if (p.automationSlot > -1) { if (p.automationSlot < m_numberOfAutomationSlots) { enableParamAutomation(idx, p.idx, p.automationSlot); } else { p.automationSlot = -1; } } } } idx++; } MessageManager::callAsync([this] { auto* editor = getActiveEditor(); if (editor != nullptr) { dynamic_cast<AudioGridderAudioProcessorEditor*>(editor)->setConnected(true); } }); }); // handle connection close m_client.setOnCloseCallback([this] { MessageManager::callAsync([this] { auto* editor = getActiveEditor(); if (editor != nullptr) { dynamic_cast<AudioGridderAudioProcessorEditor*>(editor)->setConnected(false); } }); }); if (m_activeServer > -1 && m_activeServer < m_servers.size()) { m_client.setServer(m_servers[m_activeServer]); } } AudioGridderAudioProcessor::~AudioGridderAudioProcessor() { m_client.signalThreadShouldExit(); m_client.close(); } const String AudioGridderAudioProcessor::getName() const { return JucePlugin_Name; } bool AudioGridderAudioProcessor::acceptsMidi() const { #if JucePlugin_WantsMidiInput return true; #else return false; #endif } bool AudioGridderAudioProcessor::producesMidi() const { #if JucePlugin_ProducesMidiOutput return true; #else return false; #endif } bool AudioGridderAudioProcessor::isMidiEffect() const { #if JucePlugin_IsMidiEffect return true; #else return false; #endif } double AudioGridderAudioProcessor::getTailLengthSeconds() const { return 0.0; } bool AudioGridderAudioProcessor::supportsDoublePrecisionProcessing() const { return true; } int AudioGridderAudioProcessor::getNumPrograms() { return 1; } int AudioGridderAudioProcessor::getCurrentProgram() { return 0; } void AudioGridderAudioProcessor::setCurrentProgram(int index) {} const String AudioGridderAudioProcessor::getProgramName(int index) { return {}; } void AudioGridderAudioProcessor::changeProgramName(int index, const String& newName) {} void AudioGridderAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { m_client.init(getTotalNumInputChannels(), sampleRate, samplesPerBlock, isUsingDoublePrecision()); } void AudioGridderAudioProcessor::releaseResources() { // When playback stops, you can use this as an opportunity to free up any // spare memory, etc. } #ifndef JucePlugin_PreferredChannelConfigurations bool AudioGridderAudioProcessor::isBusesLayoutSupported(const BusesLayout& layouts) const { #if JucePlugin_IsMidiEffect ignoreUnused(layouts); return true; #else // This is the place where you check if the layout is supported. // In this template code we only support mono or stereo. if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono() && layouts.getMainOutputChannelSet() != AudioChannelSet::stereo()) { return false; } // This checks if the input layout matches the output layout #if !JucePlugin_IsSynth if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet()) { return false; } #endif return true; #endif } #endif template <typename T> void AudioGridderAudioProcessor::processBlockReal(AudioBuffer<T>& buffer, MidiBuffer& midiMessages) { ScopedNoDenormals noDenormals; auto totalNumInputChannels = getTotalNumInputChannels(); auto totalNumOutputChannels = getTotalNumOutputChannels(); auto* playHead = getPlayHead(); AudioPlayHead::CurrentPositionInfo posInfo; playHead->getCurrentPosition(posInfo); for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i) { buffer.clear(i, 0, buffer.getNumSamples()); } if (!m_client.isReadyLockFree()) { for (auto i = 0; i < buffer.getNumChannels(); ++i) { buffer.clear(i, 0, buffer.getNumSamples()); } } else { if (buffer.getNumChannels() > 0 && buffer.getNumSamples() > 0) { m_client.send(buffer, midiMessages, posInfo); m_client.read(buffer, midiMessages); if (m_client.getLatencySamples() != getLatencySamples()) { logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples()); setLatencySamples(m_client.getLatencySamples()); } } } } bool AudioGridderAudioProcessor::hasEditor() const { return true; } AudioProcessorEditor* AudioGridderAudioProcessor::createEditor() { return new AudioGridderAudioProcessorEditor(*this); } void AudioGridderAudioProcessor::getStateInformation(MemoryBlock& destData) { json j; auto jservers = json::array(); for (auto& srv : m_servers) { jservers.push_back(srv.toStdString()); } j["version"] = 2; j["servers"] = jservers; j["activeServer"] = m_activeServer; auto jplugs = json::array(); for (int i = 0; i < m_loadedPlugins.size(); i++) { auto& plug = m_loadedPlugins[i]; if (m_client.isReadyLockFree()) { auto settings = m_client.getPluginSettings(static_cast<int>(i)); if (settings.getSize() > 0) { plug.settings = settings.toBase64Encoding(); } } auto jpresets = json::array(); for (auto& p : plug.presets) { jpresets.push_back(p.toStdString()); } auto jparams = json::array(); for (auto& p : plug.params) { jparams.push_back(p.toJson()); } jplugs.push_back({plug.id.toStdString(), plug.name.toStdString(), plug.settings.toStdString(), jpresets, jparams, plug.bypassed}); } j["loadedPlugins"] = jplugs; auto dump = j.dump(); destData.append(dump.data(), dump.length()); saveConfig(); } void AudioGridderAudioProcessor::saveConfig(int numOfBuffers) { auto jservers = json::array(); for (auto& srv : m_servers) { jservers.push_back(srv.toStdString()); } if (numOfBuffers < 0) { numOfBuffers = m_client.NUM_OF_BUFFERS; } json jcfg; jcfg["_comment_"] = "PLEASE DO NOT CHANGE THIS FILE WHILE YOUR DAW IS RUNNING AND HAS AUDIOGRIDDER PLUGINS LOADED"; jcfg["Servers"] = jservers; jcfg["Last"] = m_activeServer; jcfg["NumberOfBuffers"] = numOfBuffers; jcfg["NumberOfAutomationSlots"] = m_numberOfAutomationSlots; File cfg(PLUGIN_CONFIG_FILE); cfg.deleteFile(); FileOutputStream fos(cfg); fos.writeText(jcfg.dump(4), false, false, "\n"); } void AudioGridderAudioProcessor::setStateInformation(const void* data, int sizeInBytes) { std::string dump(static_cast<const char*>(data), sizeInBytes); try { json j = json::parse(dump); int version = 0; if (j.find("version") != j.end()) { version = j["version"].get<int>(); } m_servers.clear(); if (j.find("servers") != j.end()) { for (auto& srv : j["servers"]) { m_servers.push_back(srv.get<std::string>()); } } if (j.find("activeServer") != j.end()) { m_activeServer = j["activeServer"].get<int>(); } if (j.find("loadedPlugins") != j.end()) { for (auto& plug : j["loadedPlugins"]) { if (version < 1) { StringArray dummy; Array<e47::Client::Parameter> dummy2; m_loadedPlugins.push_back({plug[0].get<std::string>(), plug[1].get<std::string>(), plug[2].get<std::string>(), dummy, dummy2, false, false}); } else if (version == 1) { StringArray dummy; Array<e47::Client::Parameter> dummy2; m_loadedPlugins.push_back({plug[0].get<std::string>(), plug[1].get<std::string>(), plug[2].get<std::string>(), dummy, dummy2, plug[3].get<bool>(), false}); } else { StringArray presets; for (auto& p : plug[3]) { presets.add(p.get<std::string>()); } Array<e47::Client::Parameter> params; for (auto& p : plug[4]) { params.add(e47::Client::Parameter::fromJson(p)); } m_loadedPlugins.push_back({plug[0].get<std::string>(), plug[1].get<std::string>(), plug[2].get<std::string>(), presets, params, plug[5].get<bool>(), false}); } } } if (m_activeServer > -1 && m_activeServer < m_servers.size()) { m_client.setServer(m_servers[m_activeServer]); m_client.reconnect(); } } catch (json::parse_error& e) { logln_clnt(&m_client, "parsing state info failed: " << e.what()); } } std::vector<ServerPlugin> AudioGridderAudioProcessor::getPlugins(const String& type) const { std::vector<ServerPlugin> ret; for (auto& plugin : getPlugins()) { if (!plugin.getType().compare(type)) { ret.push_back(plugin); } } return ret; } std::set<String> AudioGridderAudioProcessor::getPluginTypes() const { std::set<String> ret; for (auto& plugin : m_client.getPlugins()) { ret.insert(plugin.getType()); } return ret; } bool AudioGridderAudioProcessor::loadPlugin(const String& id, const String& name) { StringArray presets; Array<e47::Client::Parameter> params; logln_clnt(&m_client, "loading " << name << " (" << id << ")... "); suspendProcessing(true); bool success = m_client.addPlugin(id, presets, params); suspendProcessing(false); logln_clnt(&m_client, "..." << (success ? "ok" : "error")); if (success) { logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples()); setLatencySamples(m_client.getLatencySamples()); m_loadedPlugins.push_back({id, name, "", presets, params, false, true}); } return success; } void AudioGridderAudioProcessor::unloadPlugin(int idx) { suspendProcessing(true); m_client.delPlugin(idx); suspendProcessing(false); logln_clnt(&m_client, "updating latency samples to " << m_client.getLatencySamples()); setLatencySamples(m_client.getLatencySamples()); if (idx == m_activePlugin) { hidePlugin(); } else if (idx < m_activePlugin) { m_activePlugin--; } int i = 0; for (auto it = m_loadedPlugins.begin(); it < m_loadedPlugins.end(); it++) { if (i++ == idx) { m_loadedPlugins.erase(it); return; } } } void AudioGridderAudioProcessor::editPlugin(int idx) { m_client.editPlugin(idx); m_activePlugin = idx; } void AudioGridderAudioProcessor::hidePlugin(bool updateServer) { if (updateServer) { m_client.hidePlugin(); } m_activePlugin = -1; } bool AudioGridderAudioProcessor::isBypassed(int idx) { if (idx > -1 && idx < m_loadedPlugins.size()) { return m_loadedPlugins[idx].bypassed; } return false; } void AudioGridderAudioProcessor::bypassPlugin(int idx) { if (idx > -1 && idx < m_loadedPlugins.size()) { m_client.bypassPlugin(idx); m_loadedPlugins[idx].bypassed = true; } } void AudioGridderAudioProcessor::unbypassPlugin(int idx) { if (idx > -1 && idx < m_loadedPlugins.size()) { m_client.unbypassPlugin(idx); m_loadedPlugins[idx].bypassed = false; } } void AudioGridderAudioProcessor::exchangePlugins(int idxA, int idxB) { if (idxA > -1 && idxA < m_loadedPlugins.size() && idxB > -1 && idxB < m_loadedPlugins.size()) { suspendProcessing(true); m_client.exchangePlugins(idxA, idxB); suspendProcessing(false); std::swap(m_loadedPlugins[idxA], m_loadedPlugins[idxB]); if (idxA == m_activePlugin) { m_activePlugin = idxB; } else if (idxB == m_activePlugin) { m_activePlugin = idxA; } for (auto* p : getParameters()) { auto* param = dynamic_cast<Parameter*>(p); if (param->m_idx == idxA) { param->m_idx = idxB; } else if (param->m_idx == idxB) { param->m_idx = idxA; } } } } bool AudioGridderAudioProcessor::enableParamAutomation(int idx, int paramIdx, int slot) { auto& param = m_loadedPlugins[idx].params.getReference(paramIdx); Parameter* pparam = nullptr; if (slot == -1) { for (slot = 0; slot < m_numberOfAutomationSlots; slot++) { pparam = dynamic_cast<Parameter*>(getParameters()[slot]); if (pparam->m_idx == -1) { break; } } } else { pparam = dynamic_cast<Parameter*>(getParameters()[slot]); } if (slot < m_numberOfAutomationSlots) { pparam->m_idx = idx; pparam->m_paramIdx = paramIdx; param.automationSlot = slot; updateHostDisplay(); return true; } return false; } void AudioGridderAudioProcessor::disableParamAutomation(int idx, int paramIdx) { auto& param = m_loadedPlugins[idx].params.getReference(paramIdx); auto* pparam = dynamic_cast<Parameter*>(getParameters()[param.automationSlot]); pparam->reset(); updateHostDisplay(); param.automationSlot = -1; } void AudioGridderAudioProcessor::delServer(int idx) { int i = 0; for (auto it = m_servers.begin(); it < m_servers.end(); it++) { if (i++ == idx) { m_servers.erase(it); return; } } } void AudioGridderAudioProcessor::setActiveServer(int i) { if (i > -1 && i < m_servers.size()) { m_activeServer = i; m_client.setServer(m_servers[i]); } } float AudioGridderAudioProcessor::Parameter::getValue() const { if (m_idx > -1 && m_paramIdx > -1) { return m_processor.getClient().getParameterValue(m_idx, m_paramIdx); } return 0; } void AudioGridderAudioProcessor::Parameter::setValue(float newValue) { if (m_idx > -1 && m_paramIdx > -1) { MessageManager::callAsync( [this, newValue] { m_processor.getClient().setParameterValue(m_idx, m_paramIdx, newValue); }); } } String AudioGridderAudioProcessor::Parameter::getName(int maximumStringLength) const { String name; name << m_slotId << ":" << getPlugin().name << ":" << getParam().name; if (name.length() <= maximumStringLength) { return name; } else { return name.dropLastCharacters(name.length() - maximumStringLength); } } //============================================================================== // This creates new instances of the plugin.. AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new AudioGridderAudioProcessor(); }
34.464217
120
0.599394
b00leant
d50f311baa5bcc6fa2ee3552adff91ceb0cc7f31
169
cpp
C++
Emerald/src/graphics/camera/camera.cpp
jodelahithit/Emerald
880d0e4ec1ab3a14060502eeb01fc124844b909f
[ "Apache-2.0" ]
null
null
null
Emerald/src/graphics/camera/camera.cpp
jodelahithit/Emerald
880d0e4ec1ab3a14060502eeb01fc124844b909f
[ "Apache-2.0" ]
null
null
null
Emerald/src/graphics/camera/camera.cpp
jodelahithit/Emerald
880d0e4ec1ab3a14060502eeb01fc124844b909f
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" void Camera::UpdateProjectionMatrix() { m_projectionMatrix = Matrix4::Perspective(m_FOV, GetApplication()->GetAspect(), m_nearPlane, m_farPlane); }
33.8
106
0.775148
jodelahithit
d5114b098c4fc6702425173f9542b3eca474cb81
12,353
hpp
C++
openstudiocore/src/model/Blind.hpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
1
2015-06-28T09:06:24.000Z
2015-06-28T09:06:24.000Z
openstudiocore/src/model/Blind.hpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
11
2015-05-05T16:16:33.000Z
2017-08-10T08:15:50.000Z
openstudiocore/src/model/Blind.hpp
pepsi7959/OpenstudioThai
fb18afb8b983f71dd5eb171e753dac7d9a4b811b
[ "blessing" ]
1
2017-09-23T12:51:13.000Z
2017-09-23T12:51:13.000Z
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * 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 **********************************************************************/ #ifndef MODEL_BLIND_HPP #define MODEL_BLIND_HPP #include "ModelAPI.hpp" #include "ShadingMaterial.hpp" namespace openstudio { class Quantity; class OSOptionalQuantity; namespace model { namespace detail { class Blind_Impl; } // detail /** Blind is a ShadingMaterial that wraps the OpenStudio IDD object 'OS:WindowMaterial:Blind'. */ class MODEL_API Blind : public ShadingMaterial { public: /** @name Constructors and Destructors */ //@{ explicit Blind(const Model& model, double slatWidth = 0.025, double slatSeparation = 0.01875, double frontSideSlatBeamSolarReflectance = 0.5, double backSideSlatBeamSolarReflectance = 0.5, double frontSideSlatDiffuseSolarReflectance = 0.5, double backSideSlatDiffuseSolarReflectance = 0.5, double slatBeamVisibleTransmittance = 0.0); virtual ~Blind() {} //@} static IddObjectType iddObjectType(); static std::vector<std::string> slatOrientationValues(); /** @name Getters */ //@{ std::string slatOrientation() const; bool isSlatOrientationDefaulted() const; double slatWidth() const; Quantity getSlatWidth(bool returnIP=false) const; double slatSeparation() const; Quantity getSlatSeparation(bool returnIP=false) const; double slatThickness() const; Quantity getSlatThickness(bool returnIP=false) const; bool isSlatThicknessDefaulted() const; double slatAngle() const; Quantity getSlatAngle(bool returnIP=false) const; bool isSlatAngleDefaulted() const; double slatConductivity() const; Quantity getSlatConductivity(bool returnIP=false) const; bool isSlatConductivityDefaulted() const; double slatBeamSolarTransmittance() const; Quantity getSlatBeamSolarTransmittance(bool returnIP=false) const; bool isSlatBeamSolarTransmittanceDefaulted() const; double frontSideSlatBeamSolarReflectance() const; Quantity getFrontSideSlatBeamSolarReflectance(bool returnIP=false) const; double backSideSlatBeamSolarReflectance() const; Quantity getBackSideSlatBeamSolarReflectance(bool returnIP=false) const; double slatDiffuseSolarTransmittance() const; Quantity getSlatDiffuseSolarTransmittance(bool returnIP=false) const; bool isSlatDiffuseSolarTransmittanceDefaulted() const; double frontSideSlatDiffuseSolarReflectance() const; Quantity getFrontSideSlatDiffuseSolarReflectance(bool returnIP=false) const; double backSideSlatDiffuseSolarReflectance() const; Quantity getBackSideSlatDiffuseSolarReflectance(bool returnIP=false) const; double slatBeamVisibleTransmittance() const; Quantity getSlatBeamVisibleTransmittance(bool returnIP=false) const; boost::optional<double> frontSideSlatBeamVisibleReflectance() const; OSOptionalQuantity getFrontSideSlatBeamVisibleReflectance(bool returnIP=false) const; boost::optional<double> backSideSlatBeamVisibleReflectance() const; OSOptionalQuantity getBackSideSlatBeamVisibleReflectance(bool returnIP=false) const; double slatDiffuseVisibleTransmittance() const; Quantity getSlatDiffuseVisibleTransmittance(bool returnIP=false) const; bool isSlatDiffuseVisibleTransmittanceDefaulted() const; boost::optional<double> frontSideSlatDiffuseVisibleReflectance() const; OSOptionalQuantity getFrontSideSlatDiffuseVisibleReflectance(bool returnIP=false) const; boost::optional<double> backSideSlatDiffuseVisibleReflectance() const; OSOptionalQuantity getBackSideSlatDiffuseVisibleReflectance(bool returnIP=false) const; double slatInfraredHemisphericalTransmittance() const; Quantity getSlatInfraredHemisphericalTransmittance(bool returnIP=false) const; bool isSlatInfraredHemisphericalTransmittanceDefaulted() const; double frontSideSlatInfraredHemisphericalEmissivity() const; Quantity getFrontSideSlatInfraredHemisphericalEmissivity(bool returnIP=false) const; bool isFrontSideSlatInfraredHemisphericalEmissivityDefaulted() const; double backSideSlatInfraredHemisphericalEmissivity() const; Quantity getBackSideSlatInfraredHemisphericalEmissivity(bool returnIP=false) const; bool isBackSideSlatInfraredHemisphericalEmissivityDefaulted() const; double blindtoGlassDistance() const; Quantity getBlindtoGlassDistance(bool returnIP=false) const; bool isBlindtoGlassDistanceDefaulted() const; double blindTopOpeningMultiplier() const; Quantity getBlindTopOpeningMultiplier(bool returnIP=false) const; bool isBlindTopOpeningMultiplierDefaulted() const; double blindBottomOpeningMultiplier() const; Quantity getBlindBottomOpeningMultiplier(bool returnIP=false) const; bool isBlindBottomOpeningMultiplierDefaulted() const; double blindLeftSideOpeningMultiplier() const; Quantity getBlindLeftSideOpeningMultiplier(bool returnIP=false) const; bool isBlindLeftSideOpeningMultiplierDefaulted() const; double blindRightSideOpeningMultiplier() const; Quantity getBlindRightSideOpeningMultiplier(bool returnIP=false) const; bool isBlindRightSideOpeningMultiplierDefaulted() const; double minimumSlatAngle() const; Quantity getMinimumSlatAngle(bool returnIP=false) const; bool isMinimumSlatAngleDefaulted() const; double maximumSlatAngle() const; Quantity getMaximumSlatAngle(bool returnIP=false) const; bool isMaximumSlatAngleDefaulted() const; //@} /** @name Setters */ //@{ bool setSlatOrientation(std::string slatOrientation); void resetSlatOrientation(); bool setSlatWidth(double slatWidth); bool setSlatWidth(const Quantity& slatWidth); bool setSlatSeparation(double slatSeparation); bool setSlatSeparation(const Quantity& slatSeparation); bool setSlatThickness(double slatThickness); bool setSlatThickness(const Quantity& slatThickness); void resetSlatThickness(); bool setSlatAngle(double slatAngle); bool setSlatAngle(const Quantity& slatAngle); void resetSlatAngle(); bool setSlatConductivity(double slatConductivity); bool setSlatConductivity(const Quantity& slatConductivity); void resetSlatConductivity(); bool setSlatBeamSolarTransmittance(double slatBeamSolarTransmittance); bool setSlatBeamSolarTransmittance(const Quantity& slatBeamSolarTransmittance); void resetSlatBeamSolarTransmittance(); bool setFrontSideSlatBeamSolarReflectance(double frontSideSlatBeamSolarReflectance); bool setFrontSideSlatBeamSolarReflectance(const Quantity& frontSideSlatBeamSolarReflectance); bool setBackSideSlatBeamSolarReflectance(double backSideSlatBeamSolarReflectance); bool setBackSideSlatBeamSolarReflectance(const Quantity& backSideSlatBeamSolarReflectance); bool setSlatDiffuseSolarTransmittance(double slatDiffuseSolarTransmittance); bool setSlatDiffuseSolarTransmittance(const Quantity& slatDiffuseSolarTransmittance); void resetSlatDiffuseSolarTransmittance(); bool setFrontSideSlatDiffuseSolarReflectance(double frontSideSlatDiffuseSolarReflectance); bool setFrontSideSlatDiffuseSolarReflectance(const Quantity& frontSideSlatDiffuseSolarReflectance); bool setBackSideSlatDiffuseSolarReflectance(double backSideSlatDiffuseSolarReflectance); bool setBackSideSlatDiffuseSolarReflectance(const Quantity& backSideSlatDiffuseSolarReflectance); bool setSlatBeamVisibleTransmittance(double slatBeamVisibleTransmittance); bool setSlatBeamVisibleTransmittance(const Quantity& slatBeamVisibleTransmittance); bool setFrontSideSlatBeamVisibleReflectance(double frontSideSlatBeamVisibleReflectance); bool setFrontSideSlatBeamVisibleReflectance(const Quantity& frontSideSlatBeamVisibleReflectance); void resetFrontSideSlatBeamVisibleReflectance(); bool setBackSideSlatBeamVisibleReflectance(double backSideSlatBeamVisibleReflectance); bool setBackSideSlatBeamVisibleReflectance(const Quantity& backSideSlatBeamVisibleReflectance); void resetBackSideSlatBeamVisibleReflectance(); bool setSlatDiffuseVisibleTransmittance(double slatDiffuseVisibleTransmittance); bool setSlatDiffuseVisibleTransmittance(const Quantity& slatDiffuseVisibleTransmittance); void resetSlatDiffuseVisibleTransmittance(); bool setFrontSideSlatDiffuseVisibleReflectance(double frontSideSlatDiffuseVisibleReflectance); bool setFrontSideSlatDiffuseVisibleReflectance(const Quantity& frontSideSlatDiffuseVisibleReflectance); void resetFrontSideSlatDiffuseVisibleReflectance(); bool setBackSideSlatDiffuseVisibleReflectance(double backSideSlatDiffuseVisibleReflectance); bool setBackSideSlatDiffuseVisibleReflectance(const Quantity& backSideSlatDiffuseVisibleReflectance); void resetBackSideSlatDiffuseVisibleReflectance(); bool setSlatInfraredHemisphericalTransmittance(double slatInfraredHemisphericalTransmittance); bool setSlatInfraredHemisphericalTransmittance(const Quantity& slatInfraredHemisphericalTransmittance); void resetSlatInfraredHemisphericalTransmittance(); bool setFrontSideSlatInfraredHemisphericalEmissivity(double frontSideSlatInfraredHemisphericalEmissivity); bool setFrontSideSlatInfraredHemisphericalEmissivity(const Quantity& frontSideSlatInfraredHemisphericalEmissivity); void resetFrontSideSlatInfraredHemisphericalEmissivity(); bool setBackSideSlatInfraredHemisphericalEmissivity(double backSideSlatInfraredHemisphericalEmissivity); bool setBackSideSlatInfraredHemisphericalEmissivity(const Quantity& backSideSlatInfraredHemisphericalEmissivity); void resetBackSideSlatInfraredHemisphericalEmissivity(); bool setBlindtoGlassDistance(double blindtoGlassDistance); bool setBlindtoGlassDistance(const Quantity& blindtoGlassDistance); void resetBlindtoGlassDistance(); bool setBlindTopOpeningMultiplier(double blindTopOpeningMultiplier); bool setBlindTopOpeningMultiplier(const Quantity& blindTopOpeningMultiplier); void resetBlindTopOpeningMultiplier(); bool setBlindBottomOpeningMultiplier(double blindBottomOpeningMultiplier); bool setBlindBottomOpeningMultiplier(const Quantity& blindBottomOpeningMultiplier); void resetBlindBottomOpeningMultiplier(); bool setBlindLeftSideOpeningMultiplier(double blindLeftSideOpeningMultiplier); bool setBlindLeftSideOpeningMultiplier(const Quantity& blindLeftSideOpeningMultiplier); void resetBlindLeftSideOpeningMultiplier(); bool setBlindRightSideOpeningMultiplier(double blindRightSideOpeningMultiplier); bool setBlindRightSideOpeningMultiplier(const Quantity& blindRightSideOpeningMultiplier); void resetBlindRightSideOpeningMultiplier(); bool setMinimumSlatAngle(double minimumSlatAngle); bool setMinimumSlatAngle(const Quantity& minimumSlatAngle); void resetMinimumSlatAngle(); bool setMaximumSlatAngle(double maximumSlatAngle); bool setMaximumSlatAngle(const Quantity& maximumSlatAngle); void resetMaximumSlatAngle(); //@} /** @name Other */ //@{ //@} protected: /// @cond typedef detail::Blind_Impl ImplType; explicit Blind(std::shared_ptr<detail::Blind_Impl> impl); friend class detail::Blind_Impl; friend class Model; friend class IdfObject; friend class openstudio::detail::IdfObject_Impl; /// @endcond private: REGISTER_LOGGER("openstudio.model.Blind"); }; /** \relates Blind*/ typedef boost::optional<Blind> OptionalBlind; /** \relates Blind*/ typedef std::vector<Blind> BlindVector; } // model } // openstudio #endif // MODEL_BLIND_HPP
31.194444
117
0.80871
pepsi7959
d5115f1dd807baf6f227a32812c871f3bd83d420
28,395
cpp
C++
multiview/multiview_cpp/src/testcases/geometry/euclidean_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/testcases/geometry/euclidean_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/testcases/geometry/euclidean_tc.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#include <algorithm> #include <iterator> #define CATCH_CONFIG_PREFIX_ALL #include "perceive/calibration/aruco-cube.hpp" #include "perceive/contrib/catch.hpp" #include "perceive/geometry.hpp" #include "perceive/geometry/projective/binocular-camera.hpp" namespace perceive { static const string c1001_v6 = R"V0G0N( { "camera-id": "C0001001_v6", "rotation-axis": [-5.289019071995259002605e-01, -8.037447439841696184004e-01, 2.725016680295973547921e-01], "rotation-angle": 4.403040718534967368214e-02, "t": [-9.999691706199903551422e-01, 4.682000672898050178117e-03, -6.303703615144396268932e-03], "baseline": 1.677118998537401595161e-01, "sensor0": { "model": "polynomial<8>", "sensor-id": "STR00017", "format": [2592, 1944], "center": [1.259908344467880397133e+03, 9.543476067019000765868e+02], "scale": 1.733503229994983732207e-03, "calib-region": [82.4137, 125.912, 2499.89, 1843.35], "A": [[4.081363182094257385790e-04, 7.846591271087714758448e-05, 1.117749802370410043550e-03, 2.050148110624722824769e-04, 8.499430114145657211636e-04, 1.202137033918700137480e-04, 2.657899442004324659650e-04, 2.557591866361383359241e-05, 1.478675890686819479475e-04, 3.551415648586637562739e-03, -4.607412044975141632297e-05, 1.061446051619520727916e-02, -4.051013608679160577820e-05, 9.430254182018919795194e-03, -7.433659454589812420888e-05, 2.520923581562218521862e-03, -8.578724808384115968485e-05, -2.794302257206254802568e-03, -1.184080115168654676050e-03, -4.807017326956552344397e-03, -1.889330041735894083477e-03, -1.854248730084105331595e-03, -5.923062148343941069051e-04, -6.226051325912054096312e-04, -7.918204510909552379383e-03, 2.807659980136358035541e-04, -1.386692371503723923698e-02, 3.144186716624482180737e-04, -3.137869973570229370496e-03, 3.464792809319654220968e-04, 7.406920122703386510921e-03, 1.918694069271629750253e-03, 6.451037704162667155150e-03, 8.917384701673108926556e-04, 9.915152431928843379527e-04, 6.928405896704332989078e-02, -1.756316883927931671305e-04, 6.449975726755774463328e-02, -4.511063214778510133129e-04, -2.036354542474170387090e-03, -5.293037764114348620037e-03, -1.087122720821221549814e-03, 5.137947864186872548586e-01, 5.065063338827674541825e-04, 4.882256460082610299844e-02], [2.415619570788307658108e-05, 3.020746602274122869641e-04, 1.374092341015142274691e-04, 6.174744303661985336470e-04, 1.455262958724064248361e-04, 2.937011790217409525072e-04, -3.602390364017271640051e-05, -2.319655276377142745330e-05, -6.724065902904974301180e-05, -1.045114328824338400040e-05, 3.487486800742341502141e-03, -4.192946074774118667139e-05, 9.147459014495772783304e-03, -6.302296973057191879775e-05, 7.339344583677403534294e-03, -3.002658437739483612838e-05, 1.818669534496500199416e-03, -2.348697602473663256784e-04, -1.735129306810551108597e-03, -1.336041998393913817975e-03, -1.639638486985247386313e-03, -1.056904463852648135003e-03, 9.235646859584206898319e-05, -1.235380936145946684235e-05, 6.549325746959058780483e-05, -6.470080080674704345323e-03, 2.144445755465525238481e-04, -4.865152943111726926984e-03, 9.600404768035815383787e-05, 1.985069646551262945167e-03, 7.123550072457365822665e-04, 3.971930067778821002444e-03, 1.223496889110331498074e-03, 1.469815532720685456736e-03, -5.141728148921054231124e-04, -2.007789192047726087309e-04, 6.315384976319464438443e-02, 1.232334347574595700969e-05, 5.335636347570283516406e-02, -7.757682209504875373018e-04, 1.701908258753077364533e-03, -4.529528852638423086496e-03, -4.330224473192770262564e-04, 5.188048489012443420521e-01, -1.066161721393027624061e-02]], "calib-hull": [[82.4137, 994.589], [82.7395, 912.795], [85.3685, 871.576], [92.3784, 775.055], [111.127, 642.099], [138.231, 516.635], [171.755, 400.84], [216.257, 372.164], [271.933, 343.728], [286.076, 336.848], [368.694, 298.754], [446.104, 267.531], [463.093, 261.22], [486.837, 252.871], [557.389, 229.269], [576.681, 223.354], [605.074, 215.252], [687.066, 192.667], [709.383, 187.521], [741.772, 180.559], [805.271, 167.766], [835.322, 161.766], [860.417, 157.08], [896.734, 151.781], [999.599, 138.492], [1026.97, 135.686], [1065.98, 132.822], [1175.51, 126.613], [1203.93, 126.197], [1244.34, 125.912], [1354.78, 128.147], [1383.09, 129.904], [1422.63, 132.578], [1496.12, 139.68], [1529.49, 143.017], [1556.09, 146.504], [1593.15, 152.095], [1661.32, 163.546], [1691.41, 168.604], [1716.05, 173.134], [1749.25, 180.858], [1836.85, 201.752], [1858.53, 207.677], [1887.77, 216.351], [1915.64, 224.752], [1963.5, 239.446], [1982.11, 245.471], [2007.04, 254.468], [2052.54, 271.451], [2072.39, 278.928], [2087.93, 285], [2109.35, 293.832], [2147.74, 310.319], [2177.11, 323.306], [2212.51, 340.414], [2266.29, 367.373], [2282.88, 376.233], [2336.32, 405.799], [2342.31, 409.657], [2426.92, 466.272], [2454.03, 570.463], [2476.27, 680.971], [2491.85, 796.413], [2499.89, 915.432], [2499.46, 1035.58], [2491.39, 1154.54], [2475.95, 1269.77], [2453.58, 1379.92], [2426.41, 1482.96], [2383.01, 1512.72], [2348.33, 1535.02], [2326.94, 1547.95], [2285.49, 1572.44], [2147.68, 1649.75], [2059.28, 1687.99], [2036.64, 1696.75], [1956.44, 1726.57], [1913.45, 1741], [1838.17, 1763.23], [1788.82, 1776.6], [1704.06, 1796.15], [1648.84, 1806.85], [1555.2, 1822.09], [1495.53, 1829.43], [1395.3, 1838.39], [1332.84, 1841.68], [1229.52, 1843.35], [1191.18, 1842.53], [1166.66, 1842], [1064.71, 1836.18], [1027.51, 1832.73], [1003.98, 1830.47], [907.22, 1817.6], [872.222, 1811.98], [850.59, 1808.28], [761.806, 1790.37], [730.341, 1782.97], [710.577, 1778.24], [631.272, 1756.58], [603.563, 1748.4], [586.526, 1743.08], [517.243, 1719.7], [492.838, 1710.75], [478.08, 1705.22], [418.06, 1681.11], [384.471, 1666.8], [332.937, 1643.06], [315.234, 1634.4], [304.34, 1628.77], [245.08, 1598], [235.749, 1592.75], [177.24, 1558.86], [146.527, 1459], [120.765, 1351.49], [100.792, 1237.1], [95.3592, 1189.32], [87.6047, 1117.45], [83.8578, 1052.18], [82.4137, 994.589]] } , "sensor1": { "model": "polynomial<8>", "sensor-id": "STR00018", "format": [2592, 1944], "center": [1.365996599067576426023e+03, 9.619834715588560811739e+02], "scale": 1.736291840401992837839e-03, "calib-region": [78.7126, 124.979, 2550.85, 1835], "A": [[-5.315756199690442607153e-04, 8.046465077178252545131e-05, -1.522758043595403253112e-03, 1.346582592538676792504e-04, -1.498953500720120665668e-03, -6.184453678833223486122e-05, -6.962423581377014808469e-04, -1.119249465862583864384e-04, -1.757216516818263345179e-04, 3.669268064188274322546e-03, 1.766078796994431307499e-04, 1.084797525230436418542e-02, 3.153399946020565142168e-04, 9.496429630240233940586e-03, 1.092412281521589964561e-04, 2.439028130512555393034e-03, 7.932339148422444530251e-06, 5.173378866164785039317e-03, -1.050818808285107486267e-03, 1.001481104868468668956e-02, -1.178458695038332726401e-03, 5.313466479842779421894e-03, -2.664260414071695226568e-06, 8.827648883154804934636e-04, -8.440530738109436326155e-03, -9.967795995024439359433e-04, -1.417627701385058489048e-02, -8.585297867090037338134e-04, -2.727156356488617816591e-03, -4.331716336005569933931e-05, -1.249821847767965121712e-02, 1.441495676987598895114e-03, -1.268309194468521944321e-02, 1.173228543019655401025e-04, -2.004245713858156599518e-03, 7.111781150188134503765e-02, 1.119815287340029941188e-03, 6.509604266012522510998e-02, -1.582743336962632446641e-04, 1.671795931208419627723e-02, -4.906944105397343519614e-03, 2.868963539565123899155e-03, 5.172421081249921614997e-01, -2.643700981644531849968e-03, 4.824947005114835207884e-02], [3.578825528978738738234e-05, -3.932581736850303960606e-04, 1.884504816094725171416e-04, -8.019180890467313485570e-04, 4.201937561761591444220e-04, -1.459995350831010466064e-04, 4.827778197111758790028e-04, 4.487328898503959231925e-04, 1.637110298065916347277e-04, 3.988925765715015635260e-05, 3.533145510380931650363e-03, 2.008976838215881244309e-04, 9.168158870775627855565e-03, 8.693744979788257248865e-05, 6.942543139443178162873e-03, -2.407835536954059871273e-04, 1.457883788077445844783e-03, -3.201801397215240513328e-04, 3.570788063624465158430e-03, -1.674870996303291781349e-03, 4.171110785729122832910e-03, -2.426937210629385999194e-03, -5.498491718434490166389e-04, -9.597464068950289917126e-04, -2.055548056429101766440e-04, -6.403146838894081122051e-03, -5.676372262405880719793e-04, -3.853991144828171344638e-03, 4.452330757886771572807e-04, 3.387757367917261681900e-03, 9.799256737675569178814e-04, -6.438375170346698206369e-03, 2.286510576990127829866e-03, -1.055892257477417106593e-03, 8.581349086410200444064e-04, 6.479658737773563714768e-04, 6.348403960312912208686e-02, 5.361297573553552853198e-04, 5.271980626052616414334e-02, -8.809615456876473960079e-04, 8.757857304262026132413e-03, -4.984164990529466737756e-03, 2.046508215556562884641e-03, 5.230369314085653309476e-01, -1.336270119324906371916e-02]], "calib-hull": [[78.7126, 952.206], [83.8904, 844.077], [95.0449, 738.086], [112.615, 635.416], [135.392, 537.371], [162.807, 483.393], [188.535, 444.362], [237.205, 413.567], [252.003, 404.348], [312.761, 369.838], [313.887, 369.244], [363.366, 343.786], [385.316, 332.68], [386.505, 332.104], [471.656, 293.466], [576.639, 252.499], [659.697, 225.38], [699.404, 212.759], [796.943, 187.599], [843.354, 176.447], [927.762, 160.777], [955.203, 155.725], [1005.17, 147.377], [1131.6, 133.681], [1185.78, 129.132], [1319.61, 125.309], [1375.64, 124.979], [1378.18, 125.104], [1509.81, 131.899], [1566.71, 136.438], [1692.12, 152.882], [1742.75, 161.106], [1744.76, 161.437], [1858.47, 185.055], [1903.32, 195.688], [1905.22, 196.176], [2004.54, 224.377], [2044.8, 236.747], [2163.27, 279.414], [2262.98, 322.01], [2345.37, 362.694], [2384.42, 383.952], [2422.21, 405.414], [2443.01, 417.768], [2456.45, 426.214], [2477.64, 478.807], [2507.54, 589.064], [2526.71, 688.715], [2540.66, 793.045], [2549.13, 899.659], [2550.85, 1007.61], [2546.54, 1114.82], [2536.17, 1219.73], [2520.19, 1320.95], [2499.35, 1417.38], [2475.19, 1507.31], [2440.16, 1546.05], [2405.36, 1566.8], [2360.57, 1591.58], [2335.4, 1604.71], [2301.76, 1621.42], [2282.35, 1630.83], [2252.32, 1645.11], [2212.22, 1662.58], [2189.27, 1672.35], [2153.23, 1687.03], [2106.01, 1704.78], [2078.78, 1714.48], [2036.09, 1729.05], [1981.68, 1746.26], [1948.45, 1755.2], [1898.84, 1768.16], [1835.64, 1783.4], [1797.89, 1790.78], [1741.66, 1801.38], [1670.68, 1812.55], [1629.05, 1817.68], [1567.22, 1824.6], [1489.89, 1830.55], [1446.66, 1832.46], [1373.18, 1835], [1238.91, 1833.7], [1215.23, 1832.66], [1085.14, 1822.4], [1062.44, 1820.04], [940.302, 1802.12], [919.235, 1798.5], [808.059, 1774.77], [670.717, 1736.19], [586.083, 1706.27], [548.654, 1692.41], [496.151, 1670.69], [479.206, 1663.42], [463.843, 1656.66], [461.859, 1655.76], [419.036, 1636.25], [403.82, 1629.17], [388.657, 1621.52], [351.652, 1602.49], [326.098, 1588.83], [294.196, 1570.64], [273.319, 1558.46], [244.333, 1541.17], [200.765, 1513.25], [185.281, 1502.17], [148.646, 1469.08], [123.563, 1373.42], [103.197, 1272.74], [88.8354, 1168.51], [80.5573, 1060.87], [78.7126, 952.206]] } } )V0G0N"; CATCH_TEST_CASE("EuclideanTransform", "[euclidean_transform]") { CATCH_SECTION("TestEuclideanTransform") { const auto aa1 = Vector4{0.1, 1.0, 1.0, to_radians(35.0)}; const auto aa2 = Vector4{0.2, 0.4, 1.0, to_radians(15.0)}; const auto e1 = EuclideanTransform( Vector3(0.1, 0.2, 1.0), axis_angle_to_quaternion(aa1), 6.0); const auto e2 = EuclideanTransform( Vector3{1.0, 1.1, 1.2}, axis_angle_to_quaternion(aa2), 2.0); auto test_it = [](const auto& et, const Vector3& X) { auto Y1 = et.apply(X); Matrix4r M = make_transform_matrix(et); Vector4r Z = M * Vector4r(X(0), X(1), X(2), 1.0); auto Y2 = Vector3(Z(0), Z(1), Z(2)) / Z(3); auto err = (Y2 - Y1).norm(); if(false) { cout << "--------------------" << endl; cout << format("et = {:s}, X = {:s}", str(et), str(X)) << endl; cout << format("|{:s} - {:s}| = {}", str(Y1), str(Y2), err) << endl; cout << endl; } CATCH_REQUIRE(fabs(err) < 1e-9); }; test_it(e1, Vector3{1.0, 0.0, 0.0}); test_it(e1, Vector3{1.0, 1.0, 0.0}); test_it(e1, Vector3{1.0, 1.0, 1.0}); test_it(e2, Vector3{1.0, 0.0, 0.0}); test_it(e2, Vector3{1.0, 1.0, 0.0}); test_it(e2, Vector3{1.0, 1.0, 1.0}); auto test_e12 = [&](const auto& e1, const auto& e2, const Vector3& X) { const auto et = compose(e1, e2); auto Y = e1.apply(X); auto Z = e2.apply(Y); auto W = et.apply(X); Matrix4r M1 = make_transform_matrix(e1); Matrix4r M2 = make_transform_matrix(e2); Matrix4r M = M2 * M1; Vector4r U = M * Vector4r(X(0), X(1), X(2), 1.0); auto V = Vector3(U(0), U(1), U(2)) / U(3); auto err = (W - Z).norm(); auto err1 = (W - V).norm(); auto err2 = (V - Z).norm(); if(false) { cout << "--------------------" << endl; cout << format("X = {:s}", str(X)) << endl; cout << format("e1 = {:s}, Y = {:s}", str(e1), str(Y)) << endl; cout << format("e2 = {:s}, Z = {:s}", str(e2), str(Z)) << endl; cout << format("et = {:s}, W = {:s}", str(et), str(W)) << endl; cout << format("|{:s} - {:s}| = {}", str(W), str(Z), err) << endl; cout << format("|{:s} - {:s}| = {}", str(W), str(V), err1) << endl; cout << format("|{:s} - {:s}| = {}", str(V), str(Z), err2) << endl; cout << endl; } CATCH_REQUIRE(fabs(err) < 1e-9); CATCH_REQUIRE(fabs(err1) < 1e-9); CATCH_REQUIRE(fabs(err2) < 1e-9); }; test_e12(e1, e2, Vector3{1.0, 0.0, 0.0}); test_e12(e1, e2, Vector3{1.0, 1.0, 0.0}); test_e12(e1, e2, Vector3{1.0, 1.0, 1.0}); test_e12(e1, e2, Vector3{1.0, 0.0, 1.0}); auto test_i12 = [&](const auto& e1, const auto& e2, const Vector3& X) { const auto et = compose(e1, e2); const auto ez = et / e2; // ez should be the same as e1 auto Y = e1.apply(X); auto Z = e2.apply(Y); auto V = e2.inverse_apply(Z); // Should be Y auto W = ez.apply(X); // Should be Y auto err1 = (Y - V).norm(); auto err2 = (Y - W).norm(); if(false) { cout << "--------------------" << endl; cout << format("X = {:s}", str(X)) << endl; cout << format("e1 = {:s}, Y = {:s}", str(e1), str(Y)) << endl; cout << format("e2 = {:s}, Z = {:s}", str(e2), str(Z)) << endl; cout << format("et = {:s}, W = {:s}", str(et), str(W)) << endl; cout << format("ez = {:s}, W = {:s}", str(et), str(W)) << endl; cout << format("|{:s} - {:s}| = {}", str(Y), str(V), err1) << endl; cout << format("|{:s} - {:s}| = {}", str(Y), str(W), err2) << endl; cout << endl; } CATCH_REQUIRE(fabs(err1) < 1e-9); CATCH_REQUIRE(fabs(err2) < 1e-9); }; test_i12(e1, e2, Vector3{1.0, 0.0, 0.0}); test_i12(e1, e2, Vector3{1.0, 1.0, 0.0}); test_i12(e1, e2, Vector3{1.0, 1.0, 1.0}); test_i12(e1, e2, Vector3{1.0, 0.0, 1.0}); auto test_inverse = [&](const auto& e1, const Vector3& X) { const auto e_inv = EuclideanTransform{} / e1; auto A = e1.apply(X); auto B = e_inv.inverse_apply(X); auto err = (A - B).norm(); if(false) { cout << "--------------------" << endl; cout << format("X = {:s}", str(X)) << endl; cout << format("e1 = {:s}, Y = {:s}", str(e1), str(A)) << endl; cout << format("ei = {:s}, Z = {:s}", str(e_inv), str(B)) << endl; cout << format("|{:s} - {:s}| = {}", str(A), str(B), err) << endl; cout << endl; } CATCH_REQUIRE(fabs(err) < 1e-9); }; test_inverse(e1, Vector3{1.0, 0.0, 0.0}); test_inverse(e1, Vector3{1.0, 1.0, 0.0}); test_inverse(e1, Vector3{1.0, 1.0, 1.0}); test_inverse(e1, Vector3{1.0, 0.0, 1.0}); test_inverse(e2, Vector3{1.0, 0.0, 0.0}); test_inverse(e2, Vector3{1.0, 1.0, 0.0}); test_inverse(e2, Vector3{1.0, 1.0, 1.0}); test_inverse(e2, Vector3{1.0, 0.0, 1.0}); } CATCH_SECTION("TestKabschAlgorithm") { const vector<Vector3> A{{{1.520167, 2.2585, 0.0641333}, {2.95617, 0.3275, 0.224667}, {1.13917, 0.1735, 0.0391333}, {1.13617, 0.6435, 0.0391333}, {3.11083, 0.5545, 0.0411333}, {2.64083, 0.5595, 0.0411333}}}; const auto N = A.size(); const Quaternion q = Quaternion::between_vectors(Vector3(0, 0, 1), Vector3(0.2, 1.8, 0)); const Vector3 C0 = std::accumulate(cbegin(A), cend(A), Vector3(0, 0, 0)) / real(N); const Vector3 C1 = Vector3(9.1, -2.0, -2.5); vector<Vector3> B(A.size()); std::transform(cbegin(A), cend(A), begin(B), [&](const auto& X) { return q.rotate(X - C0) + C1; }); const auto et = transform_between(A, B); for(auto i = 0u; i < N; ++i) CATCH_REQUIRE((et.apply(A[i]) - B[i]).norm() < 1e-9); } CATCH_SECTION("et-pack-unpack-6df") { std::mt19937 gen; std::uniform_real_distribution<double> distribution{0.0, 1.0}; gen.seed(123456); auto rand = [&](real a, real b) -> real { return (b - a) * distribution(gen) + a; }; auto rand_X = [&]() { return Vector3( rand(-100.0, 100.0), rand(-100.0, 100.0), rand(-100.0, 100.0)); }; auto rand_et = [&]() { EuclideanTransform et; et.scale = rand(0.5, 1.5); et.translation = Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(-1.0, 1.0)); et.rotation = saa_to_quaternion( Vector3(rand(-M_PI, M_PI), rand(-M_PI, M_PI), rand(-M_PI, M_PI))); return et; }; auto test_it = [&](const EuclideanTransform& et0, const EuclideanTransform& et1) { const auto X = rand_X(); const auto Y = et0.apply(X); const auto Z = et1.apply(X); const auto err = (Y - Z).norm(); // INFO(format("|{} - {}| = {}", str(Y), str(Z), err)); // if(std::fabs(err) > 1e-3) FATAL("kAABM!"); CATCH_REQUIRE(true); }; auto test_et = [&](const EuclideanTransform& et0) { array<real, 6> Xs; pack_et_6df(et0, Xs.data()); const auto et1 = unpack_et_6df(Xs.data()); test_it(et0, et1); // should produce the same transformations }; for(auto i = 0; i < 100; ++i) test_et(rand_et()); } CATCH_SECTION("et_with_bcam") { vector<Vector3> Ws{{{3.0920, 3.4870, 0.7400}, {3.0920, 1.1370, 0.7400}, {2.0870, 1.1370, 0.7400}, {2.0870, 3.4870, 0.7400}}}; // C1001_v6 vector<Vector2> Ps{{{1167, 601}, {1907, 1063}, {1603, 1428}, {859, 738}}}; vector<Vector2> Qs{{{1176, 642}, {1893, 1102}, {1555, 1469}, {868, 774}}}; const auto N = Ws.size(); Expects(N == Ps.size()); Expects(N == Qs.size()); // Load bcam_info BinocularCameraInfo bcam; read(bcam, c1001_v6); // Transform for Cam0 EuclideanTransform et0, et1; et0.scale = 1.0; et0.translation = Vector3(1.376556240246096, 1.0544132990288464, 2.2821151846153271); et0.rotation = Quaternion(0.87261013236307849, -0.31804190363459633, 0.1041066722243857, -0.3557565252080937); et1 = bcam.make_et1(et0); const auto C0 = bcam.C0(); const auto C1 = bcam.C1(); // Check the sanity of inputs for(auto i = 0u; i < N; ++i) { const auto& W = Ws[i]; const auto& p = Ps[i]; const auto& q = Qs[i]; const auto E0 = et0.inverse_apply(W); // eye co-ordinate const auto E1 = bcam.q.apply(E0 - C1); const auto E_ = et0.rotation.inverse_rotate(W - et0.translation); const auto Q_ = et1.inverse_apply(W); const auto D0 = bcam.M[0].distort(homgen_P2_to_R2(E0)); const auto D1 = bcam.M[1].distort(homgen_P2_to_R2(E1)); const auto e0 = (D0 - Ps[i]).norm(); const auto e1 = (D1 - Qs[i]).norm(); CATCH_REQUIRE((E0 - E_).norm() < 1e-9); CATCH_REQUIRE((E1 - Q_).norm() < 1e-9); if(false) { cout << string(80, '-') << endl; cout << format("W = {:s}", str(W)) << endl; cout << format("E_ = {:s}", str(E_)) << endl; cout << format("E0 = {:s}", str(E0)) << endl; cout << format("E1 = {:s}", str(E1)) << endl; cout << format("Q_ = {:s}", str(Q_)) << endl; cout << format("D0 = {:s}", str(D0)) << endl; cout << format("D1 = {:s}", str(D1)) << endl; cout << format("e0 = {}", e0) << endl; cout << format("e1 = {}", e1) << endl; cout << endl; } } // CATCH_REQUIRE(true); } CATCH_SECTION("euclidean-transform-plane") { std::mt19937 gen; std::uniform_real_distribution<double> distribution{0.0, 1.0}; gen.seed(123456); auto rand = [&](real a, real b) -> real { return (b - a) * distribution(gen) + a; }; auto test_it = [&]() { // A random transform EuclideanTransform et; et.scale = rand(0.5, 1.5); et.translation = Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(-1.0, 1.0)); et.rotation = saa_to_quaternion( Vector3(rand(-M_PI, M_PI), rand(-M_PI, M_PI), rand(-M_PI, M_PI))); // A random plane Plane p3 = Plane( spherical_to_cartesian(rand(-M_PI, M_PI), rand(-M_PI, M_PI), 1.0), rand(-10.0, 10.0)); // Some points on the plane array<Vector3, 10> Xs; for(auto& X : Xs) X = p3.image(Vector3( rand(-100.0, 100.0), rand(-100.0, 100.0), rand(-100.0, 100.0))); Plane t3 = et.apply_to_plane(p3); // transformed plane // Test plane equation transformation here for(auto i = 0; i < 100; ++i) { // Generate a random point const Vector3 X = p3.image(Vector3( rand(-100.0, 100.0), rand(-100.0, 100.0), rand(-100.0, 100.0))); // The transformed point const Vector3 Y = et.apply(X); // X must be on the random plane CATCH_REQUIRE(std::fabs(p3.side(X)) < 1e-9); // The transformed point (Y) must be on the transformed plane CATCH_REQUIRE(std::fabs(t3.side(Y)) < 1e-9); } }; for(auto i = 0; i < 100; ++i) test_it(); } CATCH_SECTION("euclidean-math-health") { const ArucoCube ac = make_kyle_aruco_cube(); Matrix3r K = Matrix3r::Identity(); const unsigned uh = 1944; const unsigned uw = 2592; const real vfov = 70.0; // vertical field of view K(0, 0) = K(1, 1) = 0.5 * real(uh) / tan(0.5 * to_radians(vfov)); K(0, 2) = uw * 0.5; K(1, 2) = uh * 0.5; const Matrix3r K_inv = K.inverse(); array<real, 7> ets_p0 = { 1.796946, 0.519288, 2.404663, 0.505111, 0.328718, 3.442211, 1.000000}; array<real, 7> ets_p1 = { 1.805852, 0.527716, 2.401060, 0.453412, 0.374650, 3.472033, 1.000000}; array<EuclideanTransform, 2> ets; ets[0].unpack(&ets_p0[0]); ets[1].unpack(&ets_p1[0]); const EuclideanTransform e01 = ets[0].inverse() * ets[1]; BinocularCameraInfo bcam_info; bcam_info.set_from_et(e01.inverse()); const auto C0 = bcam_info.C0(); const auto C1 = bcam_info.C1(); const auto q = bcam_info.q; const auto bt1 = bcam_info.make_et1(ets[0].inverse()).inverse(); CachingUndistortInverse cu0, cu1; cu0.init(K); cu1.init(K); { const auto i = 4; // TOP face const Plane p3 = ac.measures[i].p3; const Plane p3_ = ets[0].apply_to_plane(ac.measures[i].p3); const Plane p31 = ets[1].apply_to_plane(ac.measures[i].p3); for(auto j = 0; j < 4; ++j) { EuclideanTransform et; const auto M = ac.measures[i].Xs[size_t(j)]; const auto X = ets[0].apply(M); const auto Y = ets[1].apply(M); const auto Y_ = bt1.apply(M); const auto Z = e01.apply(X); const auto a = bcam_info.to_ray(0, X); const auto b = bcam_info.to_ray(1, X); const auto A = plane_ray_intersection(p3_, C0, C0 + a); const auto B = plane_ray_intersection(p3_, C1, C1 + q.inverse_apply(b)); const auto x0 = homgen_P2_to_R2(to_vec3(K * Vector3r(a.x, a.y, a.z))); const auto x1 = homgen_P2_to_R2(to_vec3(K * to_vec3r(X))); const auto y0 = homgen_P2_to_R2(to_vec3(K * Vector3r(b.x, b.y, b.z))); const auto y1 = homgen_P2_to_R2(to_vec3(K * to_vec3r(Y))); // Correct const auto zx = transfer_point_between_images( y1, p31, ets[1], ets[0], cu1, cu0); const auto zy = transfer_point_between_images( x1, p3_, ets[0], ets[1], cu0, cu1); auto make_M0 = [&]() { // Take x, and convert to M auto ray = to_vec3(K_inv * Vector3r(x0.x, x0.y, 1.0)).normalised(); return ets[0].inverse_apply( plane_ray_intersection(p3_, C0, C0 + ray)); }; const auto M0 = make_M0(); auto make_M1 = [&]() { // Take x, and convert to M auto ray = to_vec3(K_inv * Vector3r(y1.x, y1.y, 1.0)).normalised(); ray = q.inverse_apply(ray); return ets[0].inverse_apply( plane_ray_intersection(p3_, C1, C1 + ray)); }; const auto M1 = make_M1(); if(false) { cout << format("M = {:s}", str(M)) << endl; cout << format("M0 = {:s}", str(M0)) << endl; cout << format("M1 = {:s}", str(M1)) << endl; cout << format("X = {:s}", str(X)) << endl; cout << format("A = {:s}", str(A)) << endl; cout << format("B = {:s}", str(B)) << endl; cout << format("Y = {:s}", str(Y)) << endl; cout << format("Z = {:s}", str(Z)) << endl; cout << format("x0 = {:s}", str(x0)) << endl; cout << format("x1 = {:s}", str(x0)) << endl; cout << format("zx = {:s}", str(zx)) << endl; cout << format("y0 = {:s}", str(y0)) << endl; cout << format("y1 = {:s}", str(y1)) << endl; cout << format("zy = {:s}", str(zy)) << endl; cout << endl; } CATCH_REQUIRE((M - M0).norm() < 1e-9); CATCH_REQUIRE((M - M1).norm() < 1e-9); CATCH_REQUIRE((Y - Z).norm() < 1e-9); CATCH_REQUIRE((Y - Y_).norm() < 1e-9); CATCH_REQUIRE((A - X).norm() < 1e-9); CATCH_REQUIRE((B - X).norm() < 1e-9); CATCH_REQUIRE((x1 - x0).norm() < 1e-9); CATCH_REQUIRE((y1 - y0).norm() < 1e-9); CATCH_REQUIRE((zx - x0).norm() < 1e-9); CATCH_REQUIRE((zy - y0).norm() < 1e-9); } } } } } // namespace perceive
56.451292
2,374
0.565522
prcvlabs
d511c7c5d6f4685b83a676dc6a2ae6ea6703ec81
7,011
cc
C++
gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-03-13T10:32:53.000Z
2019-03-13T11:05:30.000Z
gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 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 "gpu/ipc/service/gpu_memory_buffer_factory_dxgi.h" #include <vector> #include "base/memory/unsafe_shared_memory_region.h" #include "base/trace_event/trace_event.h" #include "gpu/command_buffer/common/gpu_memory_buffer_support.h" #include "gpu/ipc/common/dxgi_helpers.h" #include "ui/gfx/buffer_format_util.h" #include "ui/gl/gl_angle_util_win.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_image_dxgi.h" namespace gpu { GpuMemoryBufferFactoryDXGI::GpuMemoryBufferFactoryDXGI() { DETACH_FROM_THREAD(thread_checker_); } GpuMemoryBufferFactoryDXGI::~GpuMemoryBufferFactoryDXGI() = default; // TODO(crbug.com/1223490): Avoid the need for a separate D3D device here by // sharing keyed mutex state between DXGI GMBs and D3D shared image backings. Microsoft::WRL::ComPtr<ID3D11Device> GpuMemoryBufferFactoryDXGI::GetOrCreateD3D11Device() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!d3d11_device_) { // Use same adapter as ANGLE device. auto angle_d3d11_device = gl::QueryD3D11DeviceObjectFromANGLE(); if (!angle_d3d11_device) { DLOG(ERROR) << "Failed to get ANGLE D3D11 device"; return nullptr; } Microsoft::WRL::ComPtr<IDXGIDevice> angle_dxgi_device; HRESULT hr = angle_d3d11_device.As(&angle_dxgi_device); CHECK(SUCCEEDED(hr)); Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter = nullptr; hr = FAILED(angle_dxgi_device->GetAdapter(&dxgi_adapter)); if (FAILED(hr)) { DLOG(ERROR) << "GetAdapter failed with error 0x" << std::hex << hr; return nullptr; } // If adapter is not null, driver type must be D3D_DRIVER_TYPE_UNKNOWN // otherwise D3D11CreateDevice will return E_INVALIDARG. // See // https://docs.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-d3d11createdevice#return-value const D3D_DRIVER_TYPE driver_type = dxgi_adapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE; // It's ok to use D3D11_CREATE_DEVICE_SINGLETHREADED because this device is // only ever used on the IO thread (verified by |thread_checker_|). const UINT flags = D3D11_CREATE_DEVICE_SINGLETHREADED; // Using D3D_FEATURE_LEVEL_11_1 is ok since we only support D3D11 when the // platform update containing DXGI 1.2 is present on Win7. const D3D_FEATURE_LEVEL feature_levels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1}; hr = D3D11CreateDevice(dxgi_adapter.Get(), driver_type, /*Software=*/nullptr, flags, feature_levels, base::size(feature_levels), D3D11_SDK_VERSION, &d3d11_device_, /*pFeatureLevel=*/nullptr, /*ppImmediateContext=*/nullptr); if (FAILED(hr)) { DLOG(ERROR) << "D3D11CreateDevice failed with error 0x" << std::hex << hr; return nullptr; } const char* kDebugName = "GPUIPC_GpuMemoryBufferFactoryDXGI"; d3d11_device_->SetPrivateData(WKPDID_D3DDebugObjectName, strlen(kDebugName), kDebugName); } DCHECK(d3d11_device_); return d3d11_device_; } gfx::GpuMemoryBufferHandle GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer( gfx::GpuMemoryBufferId id, const gfx::Size& size, const gfx::Size& framebuffer_size, gfx::BufferFormat format, gfx::BufferUsage usage, int client_id, SurfaceHandle surface_handle) { TRACE_EVENT0("gpu", "GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer"); DCHECK_EQ(framebuffer_size, size); gfx::GpuMemoryBufferHandle handle; auto d3d11_device = GetOrCreateD3D11Device(); if (!d3d11_device) return handle; DXGI_FORMAT dxgi_format; switch (format) { case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::RGBX_8888: dxgi_format = DXGI_FORMAT_R8G8B8A8_UNORM; break; default: NOTREACHED(); return handle; } size_t buffer_size; if (!BufferSizeForBufferFormatChecked(size, format, &buffer_size)) return handle; // We are binding as a shader resource and render target regardless of usage, // so make sure that the usage is one that we support. DCHECK(usage == gfx::BufferUsage::GPU_READ || usage == gfx::BufferUsage::SCANOUT); D3D11_TEXTURE2D_DESC desc = { static_cast<UINT>(size.width()), static_cast<UINT>(size.height()), 1, 1, dxgi_format, {1, 0}, D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, 0, D3D11_RESOURCE_MISC_SHARED_NTHANDLE | D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX}; Microsoft::WRL::ComPtr<ID3D11Texture2D> d3d11_texture; if (FAILED(d3d11_device->CreateTexture2D(&desc, nullptr, &d3d11_texture))) return handle; Microsoft::WRL::ComPtr<IDXGIResource1> dxgi_resource; if (FAILED(d3d11_texture.As(&dxgi_resource))) return handle; HANDLE texture_handle; if (FAILED(dxgi_resource->CreateSharedHandle( nullptr, DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, nullptr, &texture_handle))) return handle; handle.dxgi_handle.Set(texture_handle); handle.type = gfx::DXGI_SHARED_HANDLE; handle.id = id; return handle; } void GpuMemoryBufferFactoryDXGI::DestroyGpuMemoryBuffer( gfx::GpuMemoryBufferId id, int client_id) {} bool GpuMemoryBufferFactoryDXGI::FillSharedMemoryRegionWithBufferContents( gfx::GpuMemoryBufferHandle buffer_handle, base::UnsafeSharedMemoryRegion shared_memory) { DCHECK_EQ(buffer_handle.type, gfx::GpuMemoryBufferType::DXGI_SHARED_HANDLE); auto d3d11_device = GetOrCreateD3D11Device(); if (!d3d11_device) return false; return CopyDXGIBufferToShMem(buffer_handle.dxgi_handle.Get(), std::move(shared_memory), d3d11_device.Get(), &staging_texture_); } ImageFactory* GpuMemoryBufferFactoryDXGI::AsImageFactory() { return this; } scoped_refptr<gl::GLImage> GpuMemoryBufferFactoryDXGI::CreateImageForGpuMemoryBuffer( gfx::GpuMemoryBufferHandle handle, const gfx::Size& size, gfx::BufferFormat format, gfx::BufferPlane plane, int client_id, SurfaceHandle surface_handle) { if (handle.type != gfx::DXGI_SHARED_HANDLE) return nullptr; if (plane != gfx::BufferPlane::DEFAULT) return nullptr; // Transfer ownership of handle to GLImageDXGI. auto image = base::MakeRefCounted<gl::GLImageDXGI>(size, nullptr); if (!image->InitializeHandle(std::move(handle.dxgi_handle), 0, format)) return nullptr; return image; } unsigned GpuMemoryBufferFactoryDXGI::RequiredTextureType() { return GL_TEXTURE_2D; } bool GpuMemoryBufferFactoryDXGI::SupportsFormatRGB() { return true; } } // namespace gpu
34.033981
103
0.72158
Yannic
d514a9e055b489dbe250836cdb055956cc54c5f0
6,890
cpp
C++
Examples/UI/FileDialogs/Sources/app.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
248
2015-01-08T05:21:40.000Z
2022-03-20T02:59:16.000Z
Examples/UI/FileDialogs/Sources/app.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
39
2015-01-14T17:37:07.000Z
2022-03-17T12:59:26.000Z
Examples/UI/FileDialogs/Sources/app.cpp
xctan/ClanLib
1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d
[ "Linux-OpenIB" ]
82
2015-01-11T13:23:49.000Z
2022-02-19T03:17:24.000Z
/* ** ClanLib SDK ** Copyright (c) 1997-2020 The ClanLib Team ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any damages ** arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, ** including commercial applications, and to alter it and redistribute it ** freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not ** claim that you wrote the original software. If you use this software ** in a product, an acknowledgment in the product documentation would be ** appreciated but is not required. ** 2. Altered source versions must be plainly marked as such, and must not be ** misrepresented as being the original software. ** 3. This notice may not be removed or altered from any source distribution. ** ** Note: Some of the libraries ClanLib may link to may have additional ** requirements or restrictions. ** ** File Author(s): ** ** Magnus Norddahl ** Mark Page ** Artem Khomenko */ #include "precomp.h" #include "app.h" #include "../../../ThemeAero/Sources/theme.h" #include <ClanLib/UI/SystemDialogs/folder_browse_dialog.h> #include <ClanLib/UI/SystemDialogs/open_file_dialog.h> #include <ClanLib/UI/SystemDialogs/save_file_dialog.h> using namespace clan; clan::ApplicationInstance<App> clanapp; App::App() { #if defined(WIN32) && !defined(__MINGW32__) clan::D3DTarget::set_current(); #else clan::OpenGLTarget::set_current(); #endif // Create a window: DisplayWindowDescription desc; desc.set_title("UICore: Hello World"); desc.set_allow_resize(true); window = std::make_shared<TopLevelWindow>(desc); auto pRootView = window->root_view(); pRootView->slots.connect(window->root_view()->sig_close(), [&](CloseEvent &e) { RunLoop::exit(); }); pRootView->slots.connect(pRootView->sig_key_press(), [&](clan::KeyEvent &e) { if (e.key() == clan::Key::escape) RunLoop::exit(); } ); // Need for receive a keyboard events. pRootView->set_focus(); // Create a source for our resources FileResourceDocument doc(FileSystem("../../ThemeAero")); ResourceManager resources = FileResourceManager::create(doc); // Mark this thread as the UI thread ui_thread = UIThread(resources); // Style the root view to use rounded corners and a bit of drop shadow pRootView->style()->set("padding: 11px"); pRootView->style()->set("background: #efefef"); pRootView->style()->set("flex-direction: column"); // First (top) panel with button and text // auto panel1 = std::make_shared<View>(); panel1->style()->set("background: white"); panel1->style()->set("padding: 11px"); panel1->style()->set("flex-direction: row"); panel1->style()->set("flex: auto"); pRootView->add_child(panel1); auto button1 = Theme::create_button(); button1->style()->set("height: 40px"); button1->style()->set("width: 120px"); button1->label()->set_text("Folder browse"); button1->style()->set("flex: none"); button1->image_view()->set_image(clan::Image(pRootView->canvas(), "./document_open.png")); button1->func_clicked() = clan::bind_member(this, &App::on_button1_down); panel1->add_child(button1); label1 = std::make_shared<LabelView>(); label1->style()->set("font: 20px/40px 'Ravie'"); label1->style()->set("padding: 0px 10px"); label1->set_text("Press the button for select a folder"); panel1->add_child(label1); // Second panel with button and text // auto panel2 = std::make_shared<View>(); panel2->style()->set("background: white"); panel2->style()->set("padding: 11px"); panel2->style()->set("flex-direction: row"); panel2->style()->set("flex: auto"); pRootView->add_child(panel2); auto button2 = Theme::create_button(); button2->style()->set("height: 40px"); button2->style()->set("width: 120px"); button2->label()->set_text("Open file"); button2->style()->set("flex: none"); button2->func_clicked() = clan::bind_member(this, &App::on_button2_down); panel2->add_child(button2); label2 = std::make_shared<LabelView>(); label2->style()->set("font: 20px/40px 'Ravie'"); label2->style()->set("padding: 0px 10px"); label2->set_text("Press the button for select only existing file"); panel2->add_child(label2); // Third panel with button and text // auto panel3 = std::make_shared<View>(); panel3->style()->set("background: white"); panel3->style()->set("padding: 11px"); panel3->style()->set("flex-direction: row"); panel3->style()->set("flex: auto"); pRootView->add_child(panel3); auto button3 = Theme::create_button(); button3->style()->set("height: 40px"); button3->style()->set("width: 120px"); button3->label()->set_text("Save file"); button3->style()->set("flex: none"); button3->func_clicked() = clan::bind_member(this, &App::on_button3_down); panel3->add_child(button3); label3 = std::make_shared<LabelView>(); label3->style()->set("font: 20px/40px 'Ravie'"); label3->style()->set("padding: 0px 10px"); label3->set_text("Press the button for select existing or new file"); panel3->add_child(label3); // Fourth panel with button and text // auto panel4 = std::make_shared<View>(); panel4->style()->set("background: white"); panel4->style()->set("padding: 11px"); panel4->style()->set("flex-direction: row"); panel4->style()->set("flex: auto"); pRootView->add_child(panel4); button4 = Theme::create_button(); button4->style()->set("height: 40px"); button4->style()->set("width: 120px"); button4->label()->set_text("Sticky button"); button4->style()->set("flex: none"); button4->func_clicked() = clan::bind_member(this, &App::on_button4_down); button4->set_sticky(true); button4->set_pressed(true); panel4->add_child(button4); label4 = std::make_shared<LabelView>(); label4->style()->set("font: 20px/40px 'Ravie'"); label4->style()->set("padding: 0px 10px"); panel4->add_child(label4); on_button4_down(); // Manual setting button's "pressed" property doesn't call user event handler automatically. } void App::on_button1_down() { auto dlg = std::make_shared<BrowseFolderDialog>(window->root_view().get()); label1->set_text(dlg->show() ? dlg->selected_path() : "Canceled"); } void App::on_button2_down() { auto dlg = std::make_shared<OpenFileDialog>(window->root_view().get()); label2->set_text(dlg->show() ? dlg->filename() : "Canceled"); } void App::on_button3_down() { auto dlg = std::make_shared<SaveFileDialog>(window->root_view().get()); label3->set_text(dlg->show() ? dlg->filename() : "Canceled"); } void App::on_button4_down() { label4->set_text(button4->pressed() ? "Sticky button is pressed" : "Sticky button is unpressed"); } bool App::update() { // This needs only if nothing is drawn. Otherwise, use display_window().flip(). window->display_window().request_repaint(); //window->display_window().flip(); return true; }
33.77451
112
0.697823
xctan
d515380d863c775cdc86b6219d718489357a7d02
238
cc
C++
src/abc158/a.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc158/a.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc158/a.cc
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; string solve(string s) { if(s == "AAA" || s == "BBB") return "No"; return "Yes"; } /* int main() { string s; cin >> s; cout << solve(s); } */
14.875
32
0.516807
nryotaro
d5153aabc5ef5950d4034b68c66f9180d9050f96
1,748
cpp
C++
Online Judges/URI/2731/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/2731/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/2731/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <vector> #include <queue> #define INF 10000000 using namespace std; vector<vector<pair<int, int> > > graph; void dijkstra(int start) { vector<int>dist((int)graph.size(), INF); vector<int>path((int)graph.size(), -1); priority_queue<pair<int,int>, vector<pair<int,int> >, greater<pair<int,int> > > pq; dist[start] = 0; pq.push({dist[start], start}); while(!pq.empty()) { int v = pq.top().second; pq.pop(); for (int i = 0; i < (int)graph[v].size(); i++) { int u = graph[v][i].first; int w = graph[v][i].second; if(dist[u] > dist[v] + w) { dist[u] = dist[v] + w; path[u] = v; pq.push({dist[u], u}); } } } int aux = 0; vector<int>trace; while(aux != -1) { trace.push_back(aux); aux = path[aux]; } if(dist[0] > 120) { cout << "It will be " << dist[0] - 120 << " minutes late. "; } else { cout << "Will not be late. "; } cout << "Travel time - " << dist[0] << " - best way - "; for (int i = (int)trace.size() - 1; i >= 0 ; i--) { if(i != (int)trace.size() - 1) cout << " "; cout << trace[i] + 1; } cout << endl; } int main() { int cidades, estradas, v1, v2, time, start; while(cin >> cidades >> estradas && cidades && estradas) { graph.assign(cidades, vector<pair<int,int> >()); while(estradas--) { cin >> v1 >> v2 >> time; v1--; v2--; graph[v1].push_back({v2, time}); graph[v2].push_back({v1, time}); } cin >> start; dijkstra(--start); } return 0; }
25.333333
87
0.463959
AnneLivia
d517a7ae14c50ac5e439a7c29513aa65ab0edf66
3,696
cpp
C++
2018/0414_ARC095/F.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2018/0414_ARC095/F.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2018/0414_ARC095/F.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
/** * File : F.cpp * Author : Kazune Takahashi * Created : 2018-4-14 21:58:25 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int N; vector<int> V[100010]; int visited[100010]; vector<int> path; vector<int> ans; vector<int> ans2; int longest(int v) { fill(visited, visited+100010, -1); queue<int> Q; Q.push(v); visited[v] = 0; while (!Q.empty()) { int now = Q.front(); Q.pop(); for (auto x : V[now]) { if (visited[x] == -1) { visited[x] = visited[now] + 1; Q.push(x); } } } int maxi = 0; int max_t = v; for (auto i = 0; i < N; i++) { assert(visited[i] >= 0); if (visited[i] > maxi) { maxi = visited[i]; max_t = i; } } return max_t; } int main() { cin >> N; for (auto i = 0; i < N-1; i++) { int v, w; cin >> v >> w; v--; w--; V[v].push_back(w); V[w].push_back(v); } int start = longest(0); int goal = longest(start); assert(V[start].size() == 1 && V[goal].size() == 1); longest(start); int dist = visited[goal]; int now = goal; path.push_back(goal); while (dist > 0) { // cerr << "dist = " << dist << ", now = " << now << endl; for (auto x : V[now]) { // cerr << "visited[" << x << "] = " << visited[x] << endl; if (visited[x] == dist - 1) { now = x; path.push_back(now); dist--; break; } } } reverse(path.begin(), path.end()); int S = path.size(); int cnt = 2; for (auto i = 1; i < S - 1; i++) { assert(V[path[i]].size() >= 2); // cerr << "V[" << path[i] << "].size() = " << V[path[i]].size() << endl; cnt += V[path[i]].size() - 1; } if (cnt != N) { // cerr << "N = " << N << ", cnt = " << cnt << endl; assert(cnt < N); cout << -1 << endl; return 0; } ans.push_back(1); int num = 1; for (auto i = 1; i < S - 1; i++) { int subtree = V[path[i]].size() - 1; vector<int> X; for (auto j = 1; j < subtree; j++) { X.push_back(j); } X.push_back(0); for (auto i = 0; i < subtree; i++) { ans.push_back(X[i] + num + 1); } num += subtree; } assert(num + 1 == N); ans.push_back(num + 1); assert((int)ans.size() == N); // reverse(path.begin(), path.end()); ans2.push_back(1); num = 1; for (auto i = 1; i < S - 1; i++) { int subtree = V[path[i]].size() - 1; vector<int> X; for (auto j = 1; j < subtree; j++) { X.push_back(j); } X.push_back(0); for (auto i = 0; i < subtree; i++) { ans2.push_back(X[i] + num + 1); } num += subtree; } ans2.push_back(num + 1); for (auto i = 0; i < N; i++) { if (ans[i] > ans2[i]) { swap(ans, ans2); break; } else if (ans[i] < ans2[i]) { break; } } for (auto i = 0; i < N; i++) { cout << ans[i]; if (i < N-1) { cout << " "; } else { cout << endl; } } }
19.659574
77
0.479708
kazunetakahashi
d51850c216a43599c3d9a9bf589559d88c4e7c1c
13,177
cpp
C++
extsrc/mesa/src/glsl/link_uniforms.cpp
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
28
2015-07-11T17:11:12.000Z
2022-03-26T04:14:16.000Z
extsrc/mesa/src/glsl/link_uniforms.cpp
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
2
2019-05-26T19:02:24.000Z
2021-05-27T14:15:04.000Z
extsrc/mesa/src/glsl/link_uniforms.cpp
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
9
2019-07-04T12:54:29.000Z
2022-02-09T13:04:38.000Z
/* * Copyright © 2011 Intel Corporation * * 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 (including the next * paragraph) 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 "main/core.h" #include "ir.h" #include "linker.h" #include "ir_uniform.h" #include "glsl_symbol_table.h" #include "program/hash_table.h" /** * \file link_uniforms.cpp * Assign locations for GLSL uniforms. * * \author Ian Romanick <ian.d.romanick@intel.com> */ /** * Count the backing storage requirements for a type */ static unsigned values_for_type(const glsl_type *type) { if (type->is_sampler()) { return 1; } else if (type->is_array() && type->fields.array->is_sampler()) { return type->array_size(); } else { return type->component_slots(); } } void uniform_field_visitor::process(ir_variable *var) { const glsl_type *t = var->type; /* Only strdup the name if we actually will need to modify it. */ if (t->is_record() || (t->is_array() && t->fields.array->is_record())) { char *name = ralloc_strdup(NULL, var->name); recursion(var->type, &name, strlen(name)); ralloc_free(name); } else { this->visit_field(t, var->name); } } void uniform_field_visitor::recursion(const glsl_type *t, char **name, unsigned name_length) { /* Records need to have each field processed individually. * * Arrays of records need to have each array element processed * individually, then each field of the resulting array elements processed * individually. */ if (t->is_record()) { for (unsigned i = 0; i < t->length; i++) { const char *field = t->fields.structure[i].name; /* Append '.field' to the current uniform name. */ ralloc_asprintf_rewrite_tail(name, name_length, ".%s", field); recursion(t->fields.structure[i].type, name, name_length + 1 + strlen(field)); } } else if (t->is_array() && t->fields.array->is_record()) { for (unsigned i = 0; i < t->length; i++) { char subscript[13]; /* Append the subscript to the current uniform name */ const unsigned subscript_length = snprintf(subscript, 13, "[%u]", i); ralloc_asprintf_rewrite_tail(name, name_length, "%s", subscript); recursion(t->fields.array, name, name_length + subscript_length); } } else { this->visit_field(t, *name); } } /** * Class to help calculate the storage requirements for a set of uniforms * * As uniforms are added to the active set the number of active uniforms and * the storage requirements for those uniforms are accumulated. The active * uniforms are added the the hash table supplied to the constructor. * * If the same uniform is added multiple times (i.e., once for each shader * target), it will only be accounted once. */ class count_uniform_size : public uniform_field_visitor { public: count_uniform_size(struct string_to_uint_map *map) : num_active_uniforms(0), num_values(0), num_shader_samplers(0), num_shader_uniform_components(0), map(map) { /* empty */ } void start_shader() { this->num_shader_samplers = 0; this->num_shader_uniform_components = 0; } /** * Total number of active uniforms counted */ unsigned num_active_uniforms; /** * Number of data values required to back the storage for the active uniforms */ unsigned num_values; /** * Number of samplers used */ unsigned num_shader_samplers; /** * Number of uniforms used in the current shader */ unsigned num_shader_uniform_components; private: virtual void visit_field(const glsl_type *type, const char *name) { assert(!type->is_record()); assert(!(type->is_array() && type->fields.array->is_record())); /* Count the number of samplers regardless of whether the uniform is * already in the hash table. The hash table prevents adding the same * uniform for multiple shader targets, but in this case we want to * count it for each shader target. */ const unsigned values = values_for_type(type); if (type->contains_sampler()) { this->num_shader_samplers += type->is_array() ? type->array_size() : 1; } else { /* Accumulate the total number of uniform slots used by this shader. * Note that samplers do not count against this limit because they * don't use any storage on current hardware. */ this->num_shader_uniform_components += values; } /* If the uniform is already in the map, there's nothing more to do. */ unsigned id; if (this->map->get(id, name)) return; char *key = strdup(name); this->map->put(this->num_active_uniforms, key); /* Each leaf uniform occupies one entry in the list of active * uniforms. */ this->num_active_uniforms++; this->num_values += values; } struct string_to_uint_map *map; }; /** * Class to help parcel out pieces of backing storage to uniforms * * Each uniform processed has some range of the \c gl_constant_value * structures associated with it. The association is done by finding * the uniform in the \c string_to_uint_map and using the value from * the map to connect that slot in the \c gl_uniform_storage table * with the next available slot in the \c gl_constant_value array. * * \warning * This class assumes that every uniform that will be processed is * already in the \c string_to_uint_map. In addition, it assumes that * the \c gl_uniform_storage and \c gl_constant_value arrays are "big * enough." */ class parcel_out_uniform_storage : public uniform_field_visitor { public: parcel_out_uniform_storage(struct string_to_uint_map *map, struct gl_uniform_storage *uniforms, union gl_constant_value *values) : map(map), uniforms(uniforms), next_sampler(0), values(values) { memset(this->targets, 0, sizeof(this->targets)); } void start_shader() { this->shader_samplers_used = 0; this->shader_shadow_samplers = 0; } private: virtual void visit_field(const glsl_type *type, const char *name) { assert(!type->is_record()); assert(!(type->is_array() && type->fields.array->is_record())); unsigned id; bool found = this->map->get(id, name); assert(found); if (!found) return; /* If there is already storage associated with this uniform, it means * that it was set while processing an earlier shader stage. For * example, we may be processing the uniform in the fragment shader, but * the uniform was already processed in the vertex shader. */ if (this->uniforms[id].storage != NULL) { /* If the uniform already has storage set from another shader stage, * mark the samplers used for this shader stage. */ if (type->contains_sampler()) { const unsigned count = MAX2(1, this->uniforms[id].array_elements); const unsigned shadow = (type->is_array()) ? type->fields.array->sampler_shadow : type->sampler_shadow; for (unsigned i = 0; i < count; i++) { const unsigned s = this->uniforms[id].sampler + i; this->shader_samplers_used |= 1U << s; this->shader_shadow_samplers |= shadow << s; } } return; } const glsl_type *base_type; if (type->is_array()) { this->uniforms[id].array_elements = type->length; base_type = type->fields.array; } else { this->uniforms[id].array_elements = 0; base_type = type; } if (base_type->is_sampler()) { this->uniforms[id].sampler = this->next_sampler; /* Increment the sampler by 1 for non-arrays and by the number of * array elements for arrays. */ this->next_sampler += MAX2(1, this->uniforms[id].array_elements); const gl_texture_index target = base_type->sampler_index(); const unsigned shadow = base_type->sampler_shadow; for (unsigned i = this->uniforms[id].sampler ; i < this->next_sampler ; i++) { this->targets[i] = target; this->shader_samplers_used |= 1U << i; this->shader_shadow_samplers |= shadow << i; } } else { this->uniforms[id].sampler = ~0; } this->uniforms[id].name = ralloc_strdup(this->uniforms, name); this->uniforms[id].type = base_type; this->uniforms[id].initialized = 0; this->uniforms[id].num_driver_storage = 0; this->uniforms[id].driver_storage = NULL; this->uniforms[id].storage = this->values; this->values += values_for_type(type); } struct string_to_uint_map *map; struct gl_uniform_storage *uniforms; unsigned next_sampler; public: union gl_constant_value *values; gl_texture_index targets[MAX_SAMPLERS]; /** * Mask of samplers used by the current shader stage. */ unsigned shader_samplers_used; /** * Mask of samplers used by the current shader stage for shadows. */ unsigned shader_shadow_samplers; }; void link_assign_uniform_locations(struct gl_shader_program *prog) { ralloc_free(prog->UniformStorage); prog->UniformStorage = NULL; prog->NumUserUniformStorage = 0; if (prog->UniformHash != NULL) { prog->UniformHash->clear(); } else { prog->UniformHash = new string_to_uint_map; } for (unsigned i = 0; i < Elements(prog->SamplerUnits); i++) { prog->SamplerUnits[i] = i; } /* First pass: Count the uniform resources used by the user-defined * uniforms. While this happens, each active uniform will have an index * assigned to it. * * Note: this is *NOT* the index that is returned to the application by * glGetUniformLocation. */ count_uniform_size uniform_size(prog->UniformHash); for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) { if (prog->_LinkedShaders[i] == NULL) continue; /* Reset various per-shader target counts. */ uniform_size.start_shader(); foreach_list(node, prog->_LinkedShaders[i]->ir) { ir_variable *const var = ((ir_instruction *) node)->as_variable(); if ((var == NULL) || (var->mode != ir_var_uniform)) continue; /* FINISHME: Update code to process built-in uniforms! */ if (strncmp("gl_", var->name, 3) == 0) continue; uniform_size.process(var); } prog->_LinkedShaders[i]->num_samplers = uniform_size.num_shader_samplers; prog->_LinkedShaders[i]->num_uniform_components = uniform_size.num_shader_uniform_components; } const unsigned num_user_uniforms = uniform_size.num_active_uniforms; const unsigned num_data_slots = uniform_size.num_values; /* On the outside chance that there were no uniforms, bail out. */ if (num_user_uniforms == 0) return; struct gl_uniform_storage *uniforms = rzalloc_array(prog, struct gl_uniform_storage, num_user_uniforms); union gl_constant_value *data = rzalloc_array(uniforms, union gl_constant_value, num_data_slots); #ifndef NDEBUG union gl_constant_value *data_end = &data[num_data_slots]; #endif parcel_out_uniform_storage parcel(prog->UniformHash, uniforms, data); for (unsigned i = 0; i < MESA_SHADER_TYPES; i++) { if (prog->_LinkedShaders[i] == NULL) continue; /* Reset various per-shader target counts. */ parcel.start_shader(); foreach_list(node, prog->_LinkedShaders[i]->ir) { ir_variable *const var = ((ir_instruction *) node)->as_variable(); if ((var == NULL) || (var->mode != ir_var_uniform)) continue; /* FINISHME: Update code to process built-in uniforms! */ if (strncmp("gl_", var->name, 3) == 0) continue; parcel.process(var); } prog->_LinkedShaders[i]->active_samplers = parcel.shader_samplers_used; prog->_LinkedShaders[i]->shadow_samplers = parcel.shader_shadow_samplers; } assert(sizeof(prog->SamplerTargets) == sizeof(parcel.targets)); memcpy(prog->SamplerTargets, parcel.targets, sizeof(prog->SamplerTargets)); #ifndef NDEBUG for (unsigned i = 0; i < num_user_uniforms; i++) { assert(uniforms[i].storage != NULL); } assert(parcel.values == data_end); #endif prog->NumUserUniformStorage = num_user_uniforms; prog->UniformStorage = uniforms; return; }
30.431871
80
0.675951
MauroArgentino
d5187582d079e3d9588b50bbdcdce745ae44c5f0
822
cpp
C++
Recursion/strings_recursion.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
1
2022-02-15T12:53:00.000Z
2022-02-15T12:53:00.000Z
Recursion/strings_recursion.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
Recursion/strings_recursion.cpp
gaurav147-star/DSA-learning
52625953e2b1421fdd550004df893b970aac9308
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class strings_recursion { public: int length(char s[]); void removeX(char s[]); }; int strings_recursion::length(char s[]) { if (s[0] == '\0') { return 0; } int smallStringLength = length(s + 1); return 1 + smallStringLength; } void strings_recursion::removeX(char s[]) { if (s[0] == '\0') { return; } if (s[0] != 'x') { removeX(s + 1); } else { int i = 1; for (; s[i] != '\0'; i++) { s[i - 1] = s[i]; } s[i - 1] = s[i]; removeX(s); } } int main() { strings_recursion l; char str[100]; cin >> str; cout << l.length(str) << endl; l.removeX(str); cout << str << endl; cout << l.length(str) << endl; }
14.945455
42
0.457421
gaurav147-star
d518fb0e32ff30902f083db5a640d07acf40675c
1,814
cpp
C++
Source/Add On - Apple/CCoreGraphics.cpp
StevoGTA/CppToolbox
ff53e4ecf02b283e608afc92769199104ba30bf1
[ "MIT" ]
1
2019-05-02T23:49:03.000Z
2019-05-02T23:49:03.000Z
Source/Add On - Apple/CCoreGraphics.cpp
StevoSM/CppToolbox
11c73e083a4510797d7674e040e096bf5dc7ea2d
[ "MIT" ]
null
null
null
Source/Add On - Apple/CCoreGraphics.cpp
StevoSM/CppToolbox
11c73e083a4510797d7674e040e096bf5dc7ea2d
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------------------------------------------------- // CCoreGraphics.cpp ©2020 Stevo Brock All rights reserved. //---------------------------------------------------------------------------------------------------------------------- #include "CCoreGraphics.h" //---------------------------------------------------------------------------------------------------------------------- // MARK: CCoreGraphics // MARK: Class methods //---------------------------------------------------------------------------------------------------------------------- CGImageRef CCoreGraphics::newImageRef(const CBitmap& bitmap) //---------------------------------------------------------------------------------------------------------------------- { // Setup const S2DSizeS32& size = bitmap.getSize(); const CData& data = bitmap.getPixelData(); CGBitmapInfo bitmapInfo; switch (bitmap.getFormat()) { case CBitmap::kFormatRGB888: bitmapInfo = kCGImageAlphaNone; break; case CBitmap::kFormatRGBA8888: bitmapInfo = kCGImageAlphaPremultipliedLast; break; case CBitmap::kFormatARGB8888: bitmapInfo = kCGImageAlphaPremultipliedFirst; break; default: bitmapInfo = 0; break; } CGColorSpaceRef colorSpaceRef = ::CGColorSpaceCreateDeviceRGB(); CGDataProviderRef dataProviderRef = ::CGDataProviderCreateWithData(nil, data.getBytePtr(), bitmap.getBytesPerRow() * size.mHeight, nil); CGImageRef imageRef = ::CGImageCreate(size.mWidth, size.mHeight, 8, bitmap.getBytesPerPixel() * 8, bitmap.getBytesPerRow(), colorSpaceRef, bitmapInfo, dataProviderRef, nil, 1, kCGRenderingIntentDefault); ::CGDataProviderRelease(dataProviderRef); ::CGColorSpaceRelease(colorSpaceRef); return imageRef; }
43.190476
120
0.495039
StevoGTA
d51985e8238b33ea3f6df0d1d4ca49d9e5c9ab31
504
cc
C++
components/prefs/writeable_pref_store.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/prefs/writeable_pref_store.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/prefs/writeable_pref_store.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 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 "components/prefs/writeable_pref_store.h" void WriteablePrefStore::ReportSubValuesChanged( const std::string& key, std::set<std::vector<std::string>> path_components, uint32_t flags) { // Default implementation. Subclasses may use |path_components| to improve // performance. ReportValueChanged(key, flags); }
33.6
76
0.751984
zealoussnow
d51a6eb192ee41b0b8ce11d5816fe375a6e1b915
106,081
cpp
C++
lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
16
2015-09-08T08:49:11.000Z
2019-07-20T14:46:20.000Z
lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
1
2019-02-10T08:27:48.000Z
2019-02-10T08:27:48.000Z
lib/CodeGen/SelectionDAG/LegalizeVectorTypes.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
7
2016-05-26T17:31:46.000Z
2020-11-04T06:39:23.000Z
//===------- LegalizeVectorTypes.cpp - Legalization of vector types -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file performs vector type splitting and scalarization for LegalizeTypes. // Scalarization is the act of changing a computation in an illegal one-element // vector type to be a computation in its scalar element type. For example, // implementing <1 x f32> arithmetic in a scalar f32 register. This is needed // as a base case when scalarizing vector arithmetic like <4 x f32>, which // eventually decomposes to scalars if the target doesn't support v4f32 or v2f32 // types. // Splitting is the act of changing a computation in an invalid vector type to // be a computation in two vectors of half the size. For example, implementing // <128 x f32> operations in terms of two <64 x f32> operations. // //===----------------------------------------------------------------------===// #include "LegalizeTypes.h" #include "llvm/DataLayout.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Result Vector Scalarization: <1 x ty> -> ty. //===----------------------------------------------------------------------===// void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) { DEBUG(dbgs() << "Scalarize node result " << ResNo << ": "; N->dump(&DAG); dbgs() << "\n"); SDValue R = SDValue(); switch (N->getOpcode()) { default: #ifndef NDEBUG dbgs() << "ScalarizeVectorResult #" << ResNo << ": "; N->dump(&DAG); dbgs() << "\n"; #endif report_fatal_error("Do not know how to scalarize the result of this " "operator!\n"); case ISD::MERGE_VALUES: R = ScalarizeVecRes_MERGE_VALUES(N, ResNo);break; case ISD::BITCAST: R = ScalarizeVecRes_BITCAST(N); break; case ISD::BUILD_VECTOR: R = ScalarizeVecRes_BUILD_VECTOR(N); break; case ISD::CONVERT_RNDSAT: R = ScalarizeVecRes_CONVERT_RNDSAT(N); break; case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break; case ISD::FP_ROUND: R = ScalarizeVecRes_FP_ROUND(N); break; case ISD::FP_ROUND_INREG: R = ScalarizeVecRes_InregOp(N); break; case ISD::FPOWI: R = ScalarizeVecRes_FPOWI(N); break; case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break; case ISD::LOAD: R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break; case ISD::SCALAR_TO_VECTOR: R = ScalarizeVecRes_SCALAR_TO_VECTOR(N); break; case ISD::SIGN_EXTEND_INREG: R = ScalarizeVecRes_InregOp(N); break; case ISD::VSELECT: R = ScalarizeVecRes_VSELECT(N); break; case ISD::SELECT: R = ScalarizeVecRes_SELECT(N); break; case ISD::SELECT_CC: R = ScalarizeVecRes_SELECT_CC(N); break; case ISD::SETCC: R = ScalarizeVecRes_SETCC(N); break; case ISD::UNDEF: R = ScalarizeVecRes_UNDEF(N); break; case ISD::VECTOR_SHUFFLE: R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break; case ISD::ANY_EXTEND: case ISD::CTLZ: case ISD::CTPOP: case ISD::CTTZ: case ISD::FABS: case ISD::FCEIL: case ISD::FCOS: case ISD::FEXP: case ISD::FEXP2: case ISD::FFLOOR: case ISD::FLOG: case ISD::FLOG10: case ISD::FLOG2: case ISD::FNEARBYINT: case ISD::FNEG: case ISD::FP_EXTEND: case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: case ISD::FRINT: case ISD::FSIN: case ISD::FSQRT: case ISD::FTRUNC: case ISD::SIGN_EXTEND: case ISD::SINT_TO_FP: case ISD::TRUNCATE: case ISD::UINT_TO_FP: case ISD::ZERO_EXTEND: R = ScalarizeVecRes_UnaryOp(N); break; case ISD::ADD: case ISD::AND: case ISD::FADD: case ISD::FDIV: case ISD::FMUL: case ISD::FPOW: case ISD::FREM: case ISD::FSUB: case ISD::MUL: case ISD::OR: case ISD::SDIV: case ISD::SREM: case ISD::SUB: case ISD::UDIV: case ISD::UREM: case ISD::XOR: case ISD::SHL: case ISD::SRA: case ISD::SRL: R = ScalarizeVecRes_BinOp(N); break; case ISD::FMA: R = ScalarizeVecRes_TernaryOp(N); break; } // If R is null, the sub-method took care of registering the result. if (R.getNode()) SetScalarizedVector(SDValue(N, ResNo), R); } SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) { SDValue LHS = GetScalarizedVector(N->getOperand(0)); SDValue RHS = GetScalarizedVector(N->getOperand(1)); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), LHS.getValueType(), LHS, RHS); } SDValue DAGTypeLegalizer::ScalarizeVecRes_TernaryOp(SDNode *N) { SDValue Op0 = GetScalarizedVector(N->getOperand(0)); SDValue Op1 = GetScalarizedVector(N->getOperand(1)); SDValue Op2 = GetScalarizedVector(N->getOperand(2)); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), Op0.getValueType(), Op0, Op1, Op2); } SDValue DAGTypeLegalizer::ScalarizeVecRes_MERGE_VALUES(SDNode *N, unsigned ResNo) { SDValue Op = DisintegrateMERGE_VALUES(N, ResNo); return GetScalarizedVector(Op); } SDValue DAGTypeLegalizer::ScalarizeVecRes_BITCAST(SDNode *N) { EVT NewVT = N->getValueType(0).getVectorElementType(); return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NewVT, N->getOperand(0)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_BUILD_VECTOR(SDNode *N) { EVT EltVT = N->getValueType(0).getVectorElementType(); SDValue InOp = N->getOperand(0); // The BUILD_VECTOR operands may be of wider element types and // we may need to truncate them back to the requested return type. if (EltVT.isInteger()) return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, InOp); return InOp; } SDValue DAGTypeLegalizer::ScalarizeVecRes_CONVERT_RNDSAT(SDNode *N) { EVT NewVT = N->getValueType(0).getVectorElementType(); SDValue Op0 = GetScalarizedVector(N->getOperand(0)); return DAG.getConvertRndSat(NewVT, N->getDebugLoc(), Op0, DAG.getValueType(NewVT), DAG.getValueType(Op0.getValueType()), N->getOperand(3), N->getOperand(4), cast<CvtRndSatSDNode>(N)->getCvtCode()); } SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) { return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), N->getValueType(0).getVectorElementType(), N->getOperand(0), N->getOperand(1)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_FP_ROUND(SDNode *N) { EVT NewVT = N->getValueType(0).getVectorElementType(); SDValue Op = GetScalarizedVector(N->getOperand(0)); return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), NewVT, Op, N->getOperand(1)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) { SDValue Op = GetScalarizedVector(N->getOperand(0)); return DAG.getNode(ISD::FPOWI, N->getDebugLoc(), Op.getValueType(), Op, N->getOperand(1)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) { // The value to insert may have a wider type than the vector element type, // so be sure to truncate it to the element type if necessary. SDValue Op = N->getOperand(1); EVT EltVT = N->getValueType(0).getVectorElementType(); if (Op.getValueType() != EltVT) // FIXME: Can this happen for floating point types? Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, Op); return Op; } SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) { assert(N->isUnindexed() && "Indexed vector load?"); SDValue Result = DAG.getLoad(ISD::UNINDEXED, N->getExtensionType(), N->getValueType(0).getVectorElementType(), N->getDebugLoc(), N->getChain(), N->getBasePtr(), DAG.getUNDEF(N->getBasePtr().getValueType()), N->getPointerInfo(), N->getMemoryVT().getVectorElementType(), N->isVolatile(), N->isNonTemporal(), N->isInvariant(), N->getOriginalAlignment()); // Legalized the chain result - switch anything that used the old chain to // use the new one. ReplaceValueWith(SDValue(N, 1), Result.getValue(1)); return Result; } SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) { // Get the dest type - it doesn't always match the input type, e.g. int_to_fp. EVT DestVT = N->getValueType(0).getVectorElementType(); SDValue Op = GetScalarizedVector(N->getOperand(0)); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), DestVT, Op); } SDValue DAGTypeLegalizer::ScalarizeVecRes_InregOp(SDNode *N) { EVT EltVT = N->getValueType(0).getVectorElementType(); EVT ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT().getVectorElementType(); SDValue LHS = GetScalarizedVector(N->getOperand(0)); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), EltVT, LHS, DAG.getValueType(ExtVT)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N) { // If the operand is wider than the vector element type then it is implicitly // truncated. Make that explicit here. EVT EltVT = N->getValueType(0).getVectorElementType(); SDValue InOp = N->getOperand(0); if (InOp.getValueType() != EltVT) return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, InOp); return InOp; } SDValue DAGTypeLegalizer::ScalarizeVecRes_VSELECT(SDNode *N) { SDValue Cond = GetScalarizedVector(N->getOperand(0)); SDValue LHS = GetScalarizedVector(N->getOperand(1)); TargetLowering::BooleanContent ScalarBool = TLI.getBooleanContents(false); TargetLowering::BooleanContent VecBool = TLI.getBooleanContents(true); if (ScalarBool != VecBool) { EVT CondVT = Cond.getValueType(); switch (ScalarBool) { case TargetLowering::UndefinedBooleanContent: break; case TargetLowering::ZeroOrOneBooleanContent: assert(VecBool == TargetLowering::UndefinedBooleanContent || VecBool == TargetLowering::ZeroOrNegativeOneBooleanContent); // Vector read from all ones, scalar expects a single 1 so mask. Cond = DAG.getNode(ISD::AND, N->getDebugLoc(), CondVT, Cond, DAG.getConstant(1, CondVT)); break; case TargetLowering::ZeroOrNegativeOneBooleanContent: assert(VecBool == TargetLowering::UndefinedBooleanContent || VecBool == TargetLowering::ZeroOrOneBooleanContent); // Vector reads from a one, scalar from all ones so sign extend. Cond = DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), CondVT, Cond, DAG.getValueType(MVT::i1)); break; } } return DAG.getNode(ISD::SELECT, N->getDebugLoc(), LHS.getValueType(), Cond, LHS, GetScalarizedVector(N->getOperand(2))); } SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) { SDValue LHS = GetScalarizedVector(N->getOperand(1)); return DAG.getNode(ISD::SELECT, N->getDebugLoc(), LHS.getValueType(), N->getOperand(0), LHS, GetScalarizedVector(N->getOperand(2))); } SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) { SDValue LHS = GetScalarizedVector(N->getOperand(2)); return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), LHS.getValueType(), N->getOperand(0), N->getOperand(1), LHS, GetScalarizedVector(N->getOperand(3)), N->getOperand(4)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_SETCC(SDNode *N) { assert(N->getValueType(0).isVector() == N->getOperand(0).getValueType().isVector() && "Scalar/Vector type mismatch"); if (N->getValueType(0).isVector()) return ScalarizeVecRes_VSETCC(N); SDValue LHS = GetScalarizedVector(N->getOperand(0)); SDValue RHS = GetScalarizedVector(N->getOperand(1)); DebugLoc DL = N->getDebugLoc(); // Turn it into a scalar SETCC. return DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, N->getOperand(2)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) { return DAG.getUNDEF(N->getValueType(0).getVectorElementType()); } SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) { // Figure out if the scalar is the LHS or RHS and return it. SDValue Arg = N->getOperand(2).getOperand(0); if (Arg.getOpcode() == ISD::UNDEF) return DAG.getUNDEF(N->getValueType(0).getVectorElementType()); unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue(); return GetScalarizedVector(N->getOperand(Op)); } SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) { assert(N->getValueType(0).isVector() && N->getOperand(0).getValueType().isVector() && "Operand types must be vectors"); SDValue LHS = GetScalarizedVector(N->getOperand(0)); SDValue RHS = GetScalarizedVector(N->getOperand(1)); EVT NVT = N->getValueType(0).getVectorElementType(); DebugLoc DL = N->getDebugLoc(); // Turn it into a scalar SETCC. SDValue Res = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, N->getOperand(2)); // Vectors may have a different boolean contents to scalars. Promote the // value appropriately. ISD::NodeType ExtendCode = TargetLowering::getExtendForContent(TLI.getBooleanContents(true)); return DAG.getNode(ExtendCode, DL, NVT, Res); } //===----------------------------------------------------------------------===// // Operand Vector Scalarization <1 x ty> -> ty. //===----------------------------------------------------------------------===// bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) { DEBUG(dbgs() << "Scalarize node operand " << OpNo << ": "; N->dump(&DAG); dbgs() << "\n"); SDValue Res = SDValue(); if (Res.getNode() == 0) { switch (N->getOpcode()) { default: #ifndef NDEBUG dbgs() << "ScalarizeVectorOperand Op #" << OpNo << ": "; N->dump(&DAG); dbgs() << "\n"; #endif llvm_unreachable("Do not know how to scalarize this operator's operand!"); case ISD::BITCAST: Res = ScalarizeVecOp_BITCAST(N); break; case ISD::CONCAT_VECTORS: Res = ScalarizeVecOp_CONCAT_VECTORS(N); break; case ISD::EXTRACT_VECTOR_ELT: Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N); break; case ISD::STORE: Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo); break; } } // If the result is null, the sub-method took care of registering results etc. if (!Res.getNode()) return false; // If the result is N, the sub-method updated N in place. Tell the legalizer // core about this. if (Res.getNode() == N) return true; assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 && "Invalid operand expansion"); ReplaceValueWith(SDValue(N, 0), Res); return false; } /// ScalarizeVecOp_BITCAST - If the value to convert is a vector that needs /// to be scalarized, it must be <1 x ty>. Convert the element instead. SDValue DAGTypeLegalizer::ScalarizeVecOp_BITCAST(SDNode *N) { SDValue Elt = GetScalarizedVector(N->getOperand(0)); return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getValueType(0), Elt); } /// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one - /// use a BUILD_VECTOR instead. SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) { SmallVector<SDValue, 8> Ops(N->getNumOperands()); for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i) Ops[i] = GetScalarizedVector(N->getOperand(i)); return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), N->getValueType(0), &Ops[0], Ops.size()); } /// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to /// be scalarized, it must be <1 x ty>, so just return the element, ignoring the /// index. SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) { SDValue Res = GetScalarizedVector(N->getOperand(0)); if (Res.getValueType() != N->getValueType(0)) Res = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), N->getValueType(0), Res); return Res; } /// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be /// scalarized, it must be <1 x ty>. Just store the element. SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){ assert(N->isUnindexed() && "Indexed store of one-element vector?"); assert(OpNo == 1 && "Do not know how to scalarize this operand!"); DebugLoc dl = N->getDebugLoc(); if (N->isTruncatingStore()) return DAG.getTruncStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)), N->getBasePtr(), N->getPointerInfo(), N->getMemoryVT().getVectorElementType(), N->isVolatile(), N->isNonTemporal(), N->getAlignment()); return DAG.getStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)), N->getBasePtr(), N->getPointerInfo(), N->isVolatile(), N->isNonTemporal(), N->getOriginalAlignment()); } //===----------------------------------------------------------------------===// // Result Vector Splitting //===----------------------------------------------------------------------===// /// SplitVectorResult - This method is called when the specified result of the /// specified node is found to need vector splitting. At this point, the node /// may also have invalid operands or may have other results that need /// legalization, we just know that (at least) one result needs vector /// splitting. void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) { DEBUG(dbgs() << "Split node result: "; N->dump(&DAG); dbgs() << "\n"); SDValue Lo, Hi; // See if the target wants to custom expand this node. if (CustomLowerNode(N, N->getValueType(ResNo), true)) return; switch (N->getOpcode()) { default: #ifndef NDEBUG dbgs() << "SplitVectorResult #" << ResNo << ": "; N->dump(&DAG); dbgs() << "\n"; #endif report_fatal_error("Do not know how to split the result of this " "operator!\n"); case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break; case ISD::VSELECT: case ISD::SELECT: SplitRes_SELECT(N, Lo, Hi); break; case ISD::SELECT_CC: SplitRes_SELECT_CC(N, Lo, Hi); break; case ISD::UNDEF: SplitRes_UNDEF(N, Lo, Hi); break; case ISD::BITCAST: SplitVecRes_BITCAST(N, Lo, Hi); break; case ISD::BUILD_VECTOR: SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break; case ISD::CONCAT_VECTORS: SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break; case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break; case ISD::FP_ROUND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break; case ISD::FPOWI: SplitVecRes_FPOWI(N, Lo, Hi); break; case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break; case ISD::SCALAR_TO_VECTOR: SplitVecRes_SCALAR_TO_VECTOR(N, Lo, Hi); break; case ISD::SIGN_EXTEND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break; case ISD::LOAD: SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break; case ISD::SETCC: SplitVecRes_SETCC(N, Lo, Hi); break; case ISD::VECTOR_SHUFFLE: SplitVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N), Lo, Hi); break; case ISD::ANY_EXTEND: case ISD::CONVERT_RNDSAT: case ISD::CTLZ: case ISD::CTTZ: case ISD::CTLZ_ZERO_UNDEF: case ISD::CTTZ_ZERO_UNDEF: case ISD::CTPOP: case ISD::FABS: case ISD::FCEIL: case ISD::FCOS: case ISD::FEXP: case ISD::FEXP2: case ISD::FFLOOR: case ISD::FLOG: case ISD::FLOG10: case ISD::FLOG2: case ISD::FNEARBYINT: case ISD::FNEG: case ISD::FP_EXTEND: case ISD::FP_ROUND: case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: case ISD::FRINT: case ISD::FSIN: case ISD::FSQRT: case ISD::FTRUNC: case ISD::SIGN_EXTEND: case ISD::SINT_TO_FP: case ISD::TRUNCATE: case ISD::UINT_TO_FP: case ISD::ZERO_EXTEND: SplitVecRes_UnaryOp(N, Lo, Hi); break; case ISD::ADD: case ISD::SUB: case ISD::MUL: case ISD::FADD: case ISD::FSUB: case ISD::FMUL: case ISD::SDIV: case ISD::UDIV: case ISD::FDIV: case ISD::FPOW: case ISD::AND: case ISD::OR: case ISD::XOR: case ISD::SHL: case ISD::SRA: case ISD::SRL: case ISD::UREM: case ISD::SREM: case ISD::FREM: SplitVecRes_BinOp(N, Lo, Hi); break; case ISD::FMA: SplitVecRes_TernaryOp(N, Lo, Hi); break; } // If Lo/Hi is null, the sub-method took care of registering results etc. if (Lo.getNode()) SetSplitVector(SDValue(N, ResNo), Lo, Hi); } void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo, SDValue &Hi) { SDValue LHSLo, LHSHi; GetSplitVector(N->getOperand(0), LHSLo, LHSHi); SDValue RHSLo, RHSHi; GetSplitVector(N->getOperand(1), RHSLo, RHSHi); DebugLoc dl = N->getDebugLoc(); Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo, RHSLo); Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi, RHSHi); } void DAGTypeLegalizer::SplitVecRes_TernaryOp(SDNode *N, SDValue &Lo, SDValue &Hi) { SDValue Op0Lo, Op0Hi; GetSplitVector(N->getOperand(0), Op0Lo, Op0Hi); SDValue Op1Lo, Op1Hi; GetSplitVector(N->getOperand(1), Op1Lo, Op1Hi); SDValue Op2Lo, Op2Hi; GetSplitVector(N->getOperand(2), Op2Lo, Op2Hi); DebugLoc dl = N->getDebugLoc(); Lo = DAG.getNode(N->getOpcode(), dl, Op0Lo.getValueType(), Op0Lo, Op1Lo, Op2Lo); Hi = DAG.getNode(N->getOpcode(), dl, Op0Hi.getValueType(), Op0Hi, Op1Hi, Op2Hi); } void DAGTypeLegalizer::SplitVecRes_BITCAST(SDNode *N, SDValue &Lo, SDValue &Hi) { // We know the result is a vector. The input may be either a vector or a // scalar value. EVT LoVT, HiVT; GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); DebugLoc dl = N->getDebugLoc(); SDValue InOp = N->getOperand(0); EVT InVT = InOp.getValueType(); // Handle some special cases efficiently. switch (getTypeAction(InVT)) { case TargetLowering::TypeLegal: case TargetLowering::TypePromoteInteger: case TargetLowering::TypeSoftenFloat: case TargetLowering::TypeScalarizeVector: case TargetLowering::TypeWidenVector: break; case TargetLowering::TypeExpandInteger: case TargetLowering::TypeExpandFloat: // A scalar to vector conversion, where the scalar needs expansion. // If the vector is being split in two then we can just convert the // expanded pieces. if (LoVT == HiVT) { GetExpandedOp(InOp, Lo, Hi); if (TLI.isBigEndian()) std::swap(Lo, Hi); Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo); Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi); return; } break; case TargetLowering::TypeSplitVector: // If the input is a vector that needs to be split, convert each split // piece of the input now. GetSplitVector(InOp, Lo, Hi); Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo); Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi); return; } // In the general case, convert the input to an integer and split it by hand. EVT LoIntVT = EVT::getIntegerVT(*DAG.getContext(), LoVT.getSizeInBits()); EVT HiIntVT = EVT::getIntegerVT(*DAG.getContext(), HiVT.getSizeInBits()); if (TLI.isBigEndian()) std::swap(LoIntVT, HiIntVT); SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi); if (TLI.isBigEndian()) std::swap(Lo, Hi); Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo); Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi); } void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo, SDValue &Hi) { EVT LoVT, HiVT; DebugLoc dl = N->getDebugLoc(); GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); unsigned LoNumElts = LoVT.getVectorNumElements(); SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts); Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, LoVT, &LoOps[0], LoOps.size()); SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end()); Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, HiVT, &HiOps[0], HiOps.size()); } void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo, SDValue &Hi) { assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS"); DebugLoc dl = N->getDebugLoc(); unsigned NumSubvectors = N->getNumOperands() / 2; if (NumSubvectors == 1) { Lo = N->getOperand(0); Hi = N->getOperand(1); return; } EVT LoVT, HiVT; GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors); Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, LoVT, &LoOps[0], LoOps.size()); SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end()); Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HiVT, &HiOps[0], HiOps.size()); } void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo, SDValue &Hi) { SDValue Vec = N->getOperand(0); SDValue Idx = N->getOperand(1); DebugLoc dl = N->getDebugLoc(); EVT LoVT, HiVT; GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, LoVT, Vec, Idx); uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HiVT, Vec, DAG.getIntPtrConstant(IdxVal + LoVT.getVectorNumElements())); } void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo, SDValue &Hi) { DebugLoc dl = N->getDebugLoc(); GetSplitVector(N->getOperand(0), Lo, Hi); Lo = DAG.getNode(ISD::FPOWI, dl, Lo.getValueType(), Lo, N->getOperand(1)); Hi = DAG.getNode(ISD::FPOWI, dl, Hi.getValueType(), Hi, N->getOperand(1)); } void DAGTypeLegalizer::SplitVecRes_InregOp(SDNode *N, SDValue &Lo, SDValue &Hi) { SDValue LHSLo, LHSHi; GetSplitVector(N->getOperand(0), LHSLo, LHSHi); DebugLoc dl = N->getDebugLoc(); EVT LoVT, HiVT; GetSplitDestVTs(cast<VTSDNode>(N->getOperand(1))->getVT(), LoVT, HiVT); Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo, DAG.getValueType(LoVT)); Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi, DAG.getValueType(HiVT)); } void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo, SDValue &Hi) { SDValue Vec = N->getOperand(0); SDValue Elt = N->getOperand(1); SDValue Idx = N->getOperand(2); DebugLoc dl = N->getDebugLoc(); GetSplitVector(Vec, Lo, Hi); if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) { unsigned IdxVal = CIdx->getZExtValue(); unsigned LoNumElts = Lo.getValueType().getVectorNumElements(); if (IdxVal < LoNumElts) Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Lo.getValueType(), Lo, Elt, Idx); else Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Hi.getValueType(), Hi, Elt, DAG.getIntPtrConstant(IdxVal - LoNumElts)); return; } // Spill the vector to the stack. EVT VecVT = Vec.getValueType(); EVT EltVT = VecVT.getVectorElementType(); SDValue StackPtr = DAG.CreateStackTemporary(VecVT); SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, MachinePointerInfo(), false, false, 0); // Store the new element. This may be larger than the vector element type, // so use a truncating store. SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx); Type *VecType = VecVT.getTypeForEVT(*DAG.getContext()); unsigned Alignment = TLI.getDataLayout()->getPrefTypeAlignment(VecType); Store = DAG.getTruncStore(Store, dl, Elt, EltPtr, MachinePointerInfo(), EltVT, false, false, 0); // Load the Lo part from the stack slot. Lo = DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, MachinePointerInfo(), false, false, false, 0); // Increment the pointer to the other part. unsigned IncrementSize = Lo.getValueType().getSizeInBits() / 8; StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr, DAG.getIntPtrConstant(IncrementSize)); // Load the Hi part from the stack slot. Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, MachinePointerInfo(), false, false, false, MinAlign(Alignment, IncrementSize)); } void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo, SDValue &Hi) { EVT LoVT, HiVT; DebugLoc dl = N->getDebugLoc(); GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); Lo = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoVT, N->getOperand(0)); Hi = DAG.getUNDEF(HiVT); } void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo, SDValue &Hi) { assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!"); EVT LoVT, HiVT; DebugLoc dl = LD->getDebugLoc(); GetSplitDestVTs(LD->getValueType(0), LoVT, HiVT); ISD::LoadExtType ExtType = LD->getExtensionType(); SDValue Ch = LD->getChain(); SDValue Ptr = LD->getBasePtr(); SDValue Offset = DAG.getUNDEF(Ptr.getValueType()); EVT MemoryVT = LD->getMemoryVT(); unsigned Alignment = LD->getOriginalAlignment(); bool isVolatile = LD->isVolatile(); bool isNonTemporal = LD->isNonTemporal(); bool isInvariant = LD->isInvariant(); EVT LoMemVT, HiMemVT; GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT); Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, dl, Ch, Ptr, Offset, LD->getPointerInfo(), LoMemVT, isVolatile, isNonTemporal, isInvariant, Alignment); unsigned IncrementSize = LoMemVT.getSizeInBits()/8; Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, DAG.getIntPtrConstant(IncrementSize)); Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, dl, Ch, Ptr, Offset, LD->getPointerInfo().getWithOffset(IncrementSize), HiMemVT, isVolatile, isNonTemporal, isInvariant, Alignment); // Build a factor node to remember that this load is independent of the // other one. Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1), Hi.getValue(1)); // Legalized the chain result - switch anything that used the old chain to // use the new one. ReplaceValueWith(SDValue(LD, 1), Ch); } void DAGTypeLegalizer::SplitVecRes_SETCC(SDNode *N, SDValue &Lo, SDValue &Hi) { assert(N->getValueType(0).isVector() && N->getOperand(0).getValueType().isVector() && "Operand types must be vectors"); EVT LoVT, HiVT; DebugLoc DL = N->getDebugLoc(); GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); // Split the input. EVT InVT = N->getOperand(0).getValueType(); SDValue LL, LH, RL, RH; EVT InNVT = EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElementType(), LoVT.getVectorNumElements()); LL = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(0), DAG.getIntPtrConstant(0)); LH = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(0), DAG.getIntPtrConstant(InNVT.getVectorNumElements())); RL = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(1), DAG.getIntPtrConstant(0)); RH = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, N->getOperand(1), DAG.getIntPtrConstant(InNVT.getVectorNumElements())); Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2)); Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2)); } void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo, SDValue &Hi) { // Get the dest types - they may not match the input types, e.g. int_to_fp. EVT LoVT, HiVT; DebugLoc dl = N->getDebugLoc(); GetSplitDestVTs(N->getValueType(0), LoVT, HiVT); // If the input also splits, handle it directly for a compile time speedup. // Otherwise split it by hand. EVT InVT = N->getOperand(0).getValueType(); if (getTypeAction(InVT) == TargetLowering::TypeSplitVector) { GetSplitVector(N->getOperand(0), Lo, Hi); } else { EVT InNVT = EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElementType(), LoVT.getVectorNumElements()); Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0), DAG.getIntPtrConstant(0)); Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0), DAG.getIntPtrConstant(InNVT.getVectorNumElements())); } if (N->getOpcode() == ISD::FP_ROUND) { Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo, N->getOperand(1)); Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi, N->getOperand(1)); } else if (N->getOpcode() == ISD::CONVERT_RNDSAT) { SDValue DTyOpLo = DAG.getValueType(LoVT); SDValue DTyOpHi = DAG.getValueType(HiVT); SDValue STyOpLo = DAG.getValueType(Lo.getValueType()); SDValue STyOpHi = DAG.getValueType(Hi.getValueType()); SDValue RndOp = N->getOperand(3); SDValue SatOp = N->getOperand(4); ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode(); Lo = DAG.getConvertRndSat(LoVT, dl, Lo, DTyOpLo, STyOpLo, RndOp, SatOp, CvtCode); Hi = DAG.getConvertRndSat(HiVT, dl, Hi, DTyOpHi, STyOpHi, RndOp, SatOp, CvtCode); } else { Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo); Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi); } } void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N, SDValue &Lo, SDValue &Hi) { // The low and high parts of the original input give four input vectors. SDValue Inputs[4]; DebugLoc dl = N->getDebugLoc(); GetSplitVector(N->getOperand(0), Inputs[0], Inputs[1]); GetSplitVector(N->getOperand(1), Inputs[2], Inputs[3]); EVT NewVT = Inputs[0].getValueType(); unsigned NewElts = NewVT.getVectorNumElements(); // If Lo or Hi uses elements from at most two of the four input vectors, then // express it as a vector shuffle of those two inputs. Otherwise extract the // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR. SmallVector<int, 16> Ops; for (unsigned High = 0; High < 2; ++High) { SDValue &Output = High ? Hi : Lo; // Build a shuffle mask for the output, discovering on the fly which // input vectors to use as shuffle operands (recorded in InputUsed). // If building a suitable shuffle vector proves too hard, then bail // out with useBuildVector set. unsigned InputUsed[2] = { -1U, -1U }; // Not yet discovered. unsigned FirstMaskIdx = High * NewElts; bool useBuildVector = false; for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) { // The mask element. This indexes into the input. int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset); // The input vector this mask element indexes into. unsigned Input = (unsigned)Idx / NewElts; if (Input >= array_lengthof(Inputs)) { // The mask element does not index into any input vector. Ops.push_back(-1); continue; } // Turn the index into an offset from the start of the input vector. Idx -= Input * NewElts; // Find or create a shuffle vector operand to hold this input. unsigned OpNo; for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) { if (InputUsed[OpNo] == Input) { // This input vector is already an operand. break; } else if (InputUsed[OpNo] == -1U) { // Create a new operand for this input vector. InputUsed[OpNo] = Input; break; } } if (OpNo >= array_lengthof(InputUsed)) { // More than two input vectors used! Give up on trying to create a // shuffle vector. Insert all elements into a BUILD_VECTOR instead. useBuildVector = true; break; } // Add the mask index for the new shuffle vector. Ops.push_back(Idx + OpNo * NewElts); } if (useBuildVector) { EVT EltVT = NewVT.getVectorElementType(); SmallVector<SDValue, 16> SVOps; // Extract the input elements by hand. for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) { // The mask element. This indexes into the input. int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset); // The input vector this mask element indexes into. unsigned Input = (unsigned)Idx / NewElts; if (Input >= array_lengthof(Inputs)) { // The mask element is "undef" or indexes off the end of the input. SVOps.push_back(DAG.getUNDEF(EltVT)); continue; } // Turn the index into an offset from the start of the input vector. Idx -= Input * NewElts; // Extract the vector element by hand. SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Inputs[Input], DAG.getIntPtrConstant(Idx))); } // Construct the Lo/Hi output using a BUILD_VECTOR. Output = DAG.getNode(ISD::BUILD_VECTOR,dl,NewVT, &SVOps[0], SVOps.size()); } else if (InputUsed[0] == -1U) { // No input vectors were used! The result is undefined. Output = DAG.getUNDEF(NewVT); } else { SDValue Op0 = Inputs[InputUsed[0]]; // If only one input was used, use an undefined vector for the other. SDValue Op1 = InputUsed[1] == -1U ? DAG.getUNDEF(NewVT) : Inputs[InputUsed[1]]; // At least one input vector was used. Create a new shuffle vector. Output = DAG.getVectorShuffle(NewVT, dl, Op0, Op1, &Ops[0]); } Ops.clear(); } } //===----------------------------------------------------------------------===// // Operand Vector Splitting //===----------------------------------------------------------------------===// /// SplitVectorOperand - This method is called when the specified operand of the /// specified node is found to need vector splitting. At this point, all of the /// result types of the node are known to be legal, but other operands of the /// node may need legalization as well as the specified one. bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) { DEBUG(dbgs() << "Split node operand: "; N->dump(&DAG); dbgs() << "\n"); SDValue Res = SDValue(); if (Res.getNode() == 0) { switch (N->getOpcode()) { default: #ifndef NDEBUG dbgs() << "SplitVectorOperand Op #" << OpNo << ": "; N->dump(&DAG); dbgs() << "\n"; #endif report_fatal_error("Do not know how to split this operator's " "operand!\n"); case ISD::SETCC: Res = SplitVecOp_VSETCC(N); break; case ISD::BITCAST: Res = SplitVecOp_BITCAST(N); break; case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break; case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break; case ISD::CONCAT_VECTORS: Res = SplitVecOp_CONCAT_VECTORS(N); break; case ISD::FP_ROUND: Res = SplitVecOp_FP_ROUND(N); break; case ISD::STORE: Res = SplitVecOp_STORE(cast<StoreSDNode>(N), OpNo); break; case ISD::CTTZ: case ISD::CTLZ: case ISD::CTPOP: case ISD::FP_EXTEND: case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: case ISD::SINT_TO_FP: case ISD::UINT_TO_FP: case ISD::FTRUNC: case ISD::TRUNCATE: case ISD::SIGN_EXTEND: case ISD::ZERO_EXTEND: case ISD::ANY_EXTEND: Res = SplitVecOp_UnaryOp(N); break; } } // If the result is null, the sub-method took care of registering results etc. if (!Res.getNode()) return false; // If the result is N, the sub-method updated N in place. Tell the legalizer // core about this. if (Res.getNode() == N) return true; assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 && "Invalid operand expansion"); ReplaceValueWith(SDValue(N, 0), Res); return false; } SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) { // The result has a legal vector type, but the input needs splitting. EVT ResVT = N->getValueType(0); SDValue Lo, Hi; DebugLoc dl = N->getDebugLoc(); GetSplitVector(N->getOperand(0), Lo, Hi); EVT InVT = Lo.getValueType(); EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(), InVT.getVectorNumElements()); Lo = DAG.getNode(N->getOpcode(), dl, OutVT, Lo); Hi = DAG.getNode(N->getOpcode(), dl, OutVT, Hi); return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi); } SDValue DAGTypeLegalizer::SplitVecOp_BITCAST(SDNode *N) { // For example, i64 = BITCAST v4i16 on alpha. Typically the vector will // end up being split all the way down to individual components. Convert the // split pieces into integers and reassemble. SDValue Lo, Hi; GetSplitVector(N->getOperand(0), Lo, Hi); Lo = BitConvertToInteger(Lo); Hi = BitConvertToInteger(Hi); if (TLI.isBigEndian()) std::swap(Lo, Hi); return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), N->getValueType(0), JoinIntegers(Lo, Hi)); } SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) { // We know that the extracted result type is legal. EVT SubVT = N->getValueType(0); SDValue Idx = N->getOperand(1); DebugLoc dl = N->getDebugLoc(); SDValue Lo, Hi; GetSplitVector(N->getOperand(0), Lo, Hi); uint64_t LoElts = Lo.getValueType().getVectorNumElements(); uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); if (IdxVal < LoElts) { assert(IdxVal + SubVT.getVectorNumElements() <= LoElts && "Extracted subvector crosses vector split!"); return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Lo, Idx); } else { return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Hi, DAG.getConstant(IdxVal - LoElts, Idx.getValueType())); } } SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) { SDValue Vec = N->getOperand(0); SDValue Idx = N->getOperand(1); EVT VecVT = Vec.getValueType(); if (isa<ConstantSDNode>(Idx)) { uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!"); SDValue Lo, Hi; GetSplitVector(Vec, Lo, Hi); uint64_t LoElts = Lo.getValueType().getVectorNumElements(); if (IdxVal < LoElts) return SDValue(DAG.UpdateNodeOperands(N, Lo, Idx), 0); return SDValue(DAG.UpdateNodeOperands(N, Hi, DAG.getConstant(IdxVal - LoElts, Idx.getValueType())), 0); } // Store the vector to the stack. EVT EltVT = VecVT.getVectorElementType(); DebugLoc dl = N->getDebugLoc(); SDValue StackPtr = DAG.CreateStackTemporary(VecVT); SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, MachinePointerInfo(), false, false, 0); // Load back the required element. StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx); return DAG.getExtLoad(ISD::EXTLOAD, dl, N->getValueType(0), Store, StackPtr, MachinePointerInfo(), EltVT, false, false, 0); } SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) { assert(N->isUnindexed() && "Indexed store of vector?"); assert(OpNo == 1 && "Can only split the stored value"); DebugLoc DL = N->getDebugLoc(); bool isTruncating = N->isTruncatingStore(); SDValue Ch = N->getChain(); SDValue Ptr = N->getBasePtr(); EVT MemoryVT = N->getMemoryVT(); unsigned Alignment = N->getOriginalAlignment(); bool isVol = N->isVolatile(); bool isNT = N->isNonTemporal(); SDValue Lo, Hi; GetSplitVector(N->getOperand(1), Lo, Hi); EVT LoMemVT, HiMemVT; GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT); unsigned IncrementSize = LoMemVT.getSizeInBits()/8; if (isTruncating) Lo = DAG.getTruncStore(Ch, DL, Lo, Ptr, N->getPointerInfo(), LoMemVT, isVol, isNT, Alignment); else Lo = DAG.getStore(Ch, DL, Lo, Ptr, N->getPointerInfo(), isVol, isNT, Alignment); // Increment the pointer to the other half. Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr, DAG.getIntPtrConstant(IncrementSize)); if (isTruncating) Hi = DAG.getTruncStore(Ch, DL, Hi, Ptr, N->getPointerInfo().getWithOffset(IncrementSize), HiMemVT, isVol, isNT, Alignment); else Hi = DAG.getStore(Ch, DL, Hi, Ptr, N->getPointerInfo().getWithOffset(IncrementSize), isVol, isNT, Alignment); return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi); } SDValue DAGTypeLegalizer::SplitVecOp_CONCAT_VECTORS(SDNode *N) { DebugLoc DL = N->getDebugLoc(); // The input operands all must have the same type, and we know the result the // result type is valid. Convert this to a buildvector which extracts all the // input elements. // TODO: If the input elements are power-two vectors, we could convert this to // a new CONCAT_VECTORS node with elements that are half-wide. SmallVector<SDValue, 32> Elts; EVT EltVT = N->getValueType(0).getVectorElementType(); for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) { SDValue Op = N->getOperand(op); for (unsigned i = 0, e = Op.getValueType().getVectorNumElements(); i != e; ++i) { Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Op, DAG.getIntPtrConstant(i))); } } return DAG.getNode(ISD::BUILD_VECTOR, DL, N->getValueType(0), &Elts[0], Elts.size()); } SDValue DAGTypeLegalizer::SplitVecOp_VSETCC(SDNode *N) { assert(N->getValueType(0).isVector() && N->getOperand(0).getValueType().isVector() && "Operand types must be vectors"); // The result has a legal vector type, but the input needs splitting. SDValue Lo0, Hi0, Lo1, Hi1, LoRes, HiRes; DebugLoc DL = N->getDebugLoc(); GetSplitVector(N->getOperand(0), Lo0, Hi0); GetSplitVector(N->getOperand(1), Lo1, Hi1); unsigned PartElements = Lo0.getValueType().getVectorNumElements(); EVT PartResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, PartElements); EVT WideResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 2*PartElements); LoRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Lo0, Lo1, N->getOperand(2)); HiRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Hi0, Hi1, N->getOperand(2)); SDValue Con = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideResVT, LoRes, HiRes); return PromoteTargetBoolean(Con, N->getValueType(0)); } SDValue DAGTypeLegalizer::SplitVecOp_FP_ROUND(SDNode *N) { // The result has a legal vector type, but the input needs splitting. EVT ResVT = N->getValueType(0); SDValue Lo, Hi; DebugLoc DL = N->getDebugLoc(); GetSplitVector(N->getOperand(0), Lo, Hi); EVT InVT = Lo.getValueType(); EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(), InVT.getVectorNumElements()); Lo = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Lo, N->getOperand(1)); Hi = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Hi, N->getOperand(1)); return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); } //===----------------------------------------------------------------------===// // Result Vector Widening //===----------------------------------------------------------------------===// void DAGTypeLegalizer::WidenVectorResult(SDNode *N, unsigned ResNo) { DEBUG(dbgs() << "Widen node result " << ResNo << ": "; N->dump(&DAG); dbgs() << "\n"); // See if the target wants to custom widen this node. if (CustomWidenLowerNode(N, N->getValueType(ResNo))) return; SDValue Res = SDValue(); switch (N->getOpcode()) { default: #ifndef NDEBUG dbgs() << "WidenVectorResult #" << ResNo << ": "; N->dump(&DAG); dbgs() << "\n"; #endif llvm_unreachable("Do not know how to widen the result of this operator!"); case ISD::MERGE_VALUES: Res = WidenVecRes_MERGE_VALUES(N, ResNo); break; case ISD::BITCAST: Res = WidenVecRes_BITCAST(N); break; case ISD::BUILD_VECTOR: Res = WidenVecRes_BUILD_VECTOR(N); break; case ISD::CONCAT_VECTORS: Res = WidenVecRes_CONCAT_VECTORS(N); break; case ISD::CONVERT_RNDSAT: Res = WidenVecRes_CONVERT_RNDSAT(N); break; case ISD::EXTRACT_SUBVECTOR: Res = WidenVecRes_EXTRACT_SUBVECTOR(N); break; case ISD::FP_ROUND_INREG: Res = WidenVecRes_InregOp(N); break; case ISD::INSERT_VECTOR_ELT: Res = WidenVecRes_INSERT_VECTOR_ELT(N); break; case ISD::LOAD: Res = WidenVecRes_LOAD(N); break; case ISD::SCALAR_TO_VECTOR: Res = WidenVecRes_SCALAR_TO_VECTOR(N); break; case ISD::SIGN_EXTEND_INREG: Res = WidenVecRes_InregOp(N); break; case ISD::VSELECT: case ISD::SELECT: Res = WidenVecRes_SELECT(N); break; case ISD::SELECT_CC: Res = WidenVecRes_SELECT_CC(N); break; case ISD::SETCC: Res = WidenVecRes_SETCC(N); break; case ISD::UNDEF: Res = WidenVecRes_UNDEF(N); break; case ISD::VECTOR_SHUFFLE: Res = WidenVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N)); break; case ISD::ADD: case ISD::AND: case ISD::BSWAP: case ISD::FADD: case ISD::FCOPYSIGN: case ISD::FDIV: case ISD::FMUL: case ISD::FPOW: case ISD::FREM: case ISD::FSUB: case ISD::MUL: case ISD::MULHS: case ISD::MULHU: case ISD::OR: case ISD::SDIV: case ISD::SREM: case ISD::UDIV: case ISD::UREM: case ISD::SUB: case ISD::XOR: Res = WidenVecRes_Binary(N); break; case ISD::FPOWI: Res = WidenVecRes_POWI(N); break; case ISD::SHL: case ISD::SRA: case ISD::SRL: Res = WidenVecRes_Shift(N); break; case ISD::ANY_EXTEND: case ISD::FP_EXTEND: case ISD::FP_ROUND: case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: case ISD::SIGN_EXTEND: case ISD::SINT_TO_FP: case ISD::TRUNCATE: case ISD::UINT_TO_FP: case ISD::ZERO_EXTEND: Res = WidenVecRes_Convert(N); break; case ISD::CTLZ: case ISD::CTPOP: case ISD::CTTZ: case ISD::FABS: case ISD::FCEIL: case ISD::FCOS: case ISD::FEXP: case ISD::FEXP2: case ISD::FFLOOR: case ISD::FLOG: case ISD::FLOG10: case ISD::FLOG2: case ISD::FNEARBYINT: case ISD::FNEG: case ISD::FRINT: case ISD::FSIN: case ISD::FSQRT: case ISD::FTRUNC: Res = WidenVecRes_Unary(N); break; case ISD::FMA: Res = WidenVecRes_Ternary(N); break; } // If Res is null, the sub-method took care of registering the result. if (Res.getNode()) SetWidenedVector(SDValue(N, ResNo), Res); } SDValue DAGTypeLegalizer::WidenVecRes_Ternary(SDNode *N) { // Ternary op widening. DebugLoc dl = N->getDebugLoc(); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); SDValue InOp1 = GetWidenedVector(N->getOperand(0)); SDValue InOp2 = GetWidenedVector(N->getOperand(1)); SDValue InOp3 = GetWidenedVector(N->getOperand(2)); return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, InOp3); } SDValue DAGTypeLegalizer::WidenVecRes_Binary(SDNode *N) { // Binary op widening. unsigned Opcode = N->getOpcode(); DebugLoc dl = N->getDebugLoc(); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); EVT WidenEltVT = WidenVT.getVectorElementType(); EVT VT = WidenVT; unsigned NumElts = VT.getVectorNumElements(); while (!TLI.isTypeLegal(VT) && NumElts != 1) { NumElts = NumElts / 2; VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts); } if (NumElts != 1 && !TLI.canOpTrap(N->getOpcode(), VT)) { // Operation doesn't trap so just widen as normal. SDValue InOp1 = GetWidenedVector(N->getOperand(0)); SDValue InOp2 = GetWidenedVector(N->getOperand(1)); return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2); } // No legal vector version so unroll the vector operation and then widen. if (NumElts == 1) return DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()); // Since the operation can trap, apply operation on the original vector. EVT MaxVT = VT; SDValue InOp1 = GetWidenedVector(N->getOperand(0)); SDValue InOp2 = GetWidenedVector(N->getOperand(1)); unsigned CurNumElts = N->getValueType(0).getVectorNumElements(); SmallVector<SDValue, 16> ConcatOps(CurNumElts); unsigned ConcatEnd = 0; // Current ConcatOps index. int Idx = 0; // Current Idx into input vectors. // NumElts := greatest legal vector size (at most WidenVT) // while (orig. vector has unhandled elements) { // take munches of size NumElts from the beginning and add to ConcatOps // NumElts := next smaller supported vector size or 1 // } while (CurNumElts != 0) { while (CurNumElts >= NumElts) { SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp1, DAG.getIntPtrConstant(Idx)); SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp2, DAG.getIntPtrConstant(Idx)); ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, VT, EOp1, EOp2); Idx += NumElts; CurNumElts -= NumElts; } do { NumElts = NumElts / 2; VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts); } while (!TLI.isTypeLegal(VT) && NumElts != 1); if (NumElts == 1) { for (unsigned i = 0; i != CurNumElts; ++i, ++Idx) { SDValue EOp1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT, InOp1, DAG.getIntPtrConstant(Idx)); SDValue EOp2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT, InOp2, DAG.getIntPtrConstant(Idx)); ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, WidenEltVT, EOp1, EOp2); } CurNumElts = 0; } } // Check to see if we have a single operation with the widen type. if (ConcatEnd == 1) { VT = ConcatOps[0].getValueType(); if (VT == WidenVT) return ConcatOps[0]; } // while (Some element of ConcatOps is not of type MaxVT) { // From the end of ConcatOps, collect elements of the same type and put // them into an op of the next larger supported type // } while (ConcatOps[ConcatEnd-1].getValueType() != MaxVT) { Idx = ConcatEnd - 1; VT = ConcatOps[Idx--].getValueType(); while (Idx >= 0 && ConcatOps[Idx].getValueType() == VT) Idx--; int NextSize = VT.isVector() ? VT.getVectorNumElements() : 1; EVT NextVT; do { NextSize *= 2; NextVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NextSize); } while (!TLI.isTypeLegal(NextVT)); if (!VT.isVector()) { // Scalar type, create an INSERT_VECTOR_ELEMENT of type NextVT SDValue VecOp = DAG.getUNDEF(NextVT); unsigned NumToInsert = ConcatEnd - Idx - 1; for (unsigned i = 0, OpIdx = Idx+1; i < NumToInsert; i++, OpIdx++) { VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NextVT, VecOp, ConcatOps[OpIdx], DAG.getIntPtrConstant(i)); } ConcatOps[Idx+1] = VecOp; ConcatEnd = Idx + 2; } else { // Vector type, create a CONCAT_VECTORS of type NextVT SDValue undefVec = DAG.getUNDEF(VT); unsigned OpsToConcat = NextSize/VT.getVectorNumElements(); SmallVector<SDValue, 16> SubConcatOps(OpsToConcat); unsigned RealVals = ConcatEnd - Idx - 1; unsigned SubConcatEnd = 0; unsigned SubConcatIdx = Idx + 1; while (SubConcatEnd < RealVals) SubConcatOps[SubConcatEnd++] = ConcatOps[++Idx]; while (SubConcatEnd < OpsToConcat) SubConcatOps[SubConcatEnd++] = undefVec; ConcatOps[SubConcatIdx] = DAG.getNode(ISD::CONCAT_VECTORS, dl, NextVT, &SubConcatOps[0], OpsToConcat); ConcatEnd = SubConcatIdx + 1; } } // Check to see if we have a single operation with the widen type. if (ConcatEnd == 1) { VT = ConcatOps[0].getValueType(); if (VT == WidenVT) return ConcatOps[0]; } // add undefs of size MaxVT until ConcatOps grows to length of WidenVT unsigned NumOps = WidenVT.getVectorNumElements()/MaxVT.getVectorNumElements(); if (NumOps != ConcatEnd ) { SDValue UndefVal = DAG.getUNDEF(MaxVT); for (unsigned j = ConcatEnd; j < NumOps; ++j) ConcatOps[j] = UndefVal; } return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0], NumOps); } SDValue DAGTypeLegalizer::WidenVecRes_Convert(SDNode *N) { SDValue InOp = N->getOperand(0); DebugLoc DL = N->getDebugLoc(); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); unsigned WidenNumElts = WidenVT.getVectorNumElements(); EVT InVT = InOp.getValueType(); EVT InEltVT = InVT.getVectorElementType(); EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts); unsigned Opcode = N->getOpcode(); unsigned InVTNumElts = InVT.getVectorNumElements(); if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) { InOp = GetWidenedVector(N->getOperand(0)); InVT = InOp.getValueType(); InVTNumElts = InVT.getVectorNumElements(); if (InVTNumElts == WidenNumElts) { if (N->getNumOperands() == 1) return DAG.getNode(Opcode, DL, WidenVT, InOp); return DAG.getNode(Opcode, DL, WidenVT, InOp, N->getOperand(1)); } } if (TLI.isTypeLegal(InWidenVT)) { // Because the result and the input are different vector types, widening // the result could create a legal type but widening the input might make // it an illegal type that might lead to repeatedly splitting the input // and then widening it. To avoid this, we widen the input only if // it results in a legal type. if (WidenNumElts % InVTNumElts == 0) { // Widen the input and call convert on the widened input vector. unsigned NumConcat = WidenNumElts/InVTNumElts; SmallVector<SDValue, 16> Ops(NumConcat); Ops[0] = InOp; SDValue UndefVal = DAG.getUNDEF(InVT); for (unsigned i = 1; i != NumConcat; ++i) Ops[i] = UndefVal; SDValue InVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InWidenVT, &Ops[0], NumConcat); if (N->getNumOperands() == 1) return DAG.getNode(Opcode, DL, WidenVT, InVec); return DAG.getNode(Opcode, DL, WidenVT, InVec, N->getOperand(1)); } if (InVTNumElts % WidenNumElts == 0) { SDValue InVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InWidenVT, InOp, DAG.getIntPtrConstant(0)); // Extract the input and convert the shorten input vector. if (N->getNumOperands() == 1) return DAG.getNode(Opcode, DL, WidenVT, InVal); return DAG.getNode(Opcode, DL, WidenVT, InVal, N->getOperand(1)); } } // Otherwise unroll into some nasty scalar code and rebuild the vector. SmallVector<SDValue, 16> Ops(WidenNumElts); EVT EltVT = WidenVT.getVectorElementType(); unsigned MinElts = std::min(InVTNumElts, WidenNumElts); unsigned i; for (i=0; i < MinElts; ++i) { SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, InEltVT, InOp, DAG.getIntPtrConstant(i)); if (N->getNumOperands() == 1) Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val); else Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val, N->getOperand(1)); } SDValue UndefVal = DAG.getUNDEF(EltVT); for (; i < WidenNumElts; ++i) Ops[i] = UndefVal; return DAG.getNode(ISD::BUILD_VECTOR, DL, WidenVT, &Ops[0], WidenNumElts); } SDValue DAGTypeLegalizer::WidenVecRes_POWI(SDNode *N) { EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); SDValue InOp = GetWidenedVector(N->getOperand(0)); SDValue ShOp = N->getOperand(1); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp, ShOp); } SDValue DAGTypeLegalizer::WidenVecRes_Shift(SDNode *N) { EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); SDValue InOp = GetWidenedVector(N->getOperand(0)); SDValue ShOp = N->getOperand(1); EVT ShVT = ShOp.getValueType(); if (getTypeAction(ShVT) == TargetLowering::TypeWidenVector) { ShOp = GetWidenedVector(ShOp); ShVT = ShOp.getValueType(); } EVT ShWidenVT = EVT::getVectorVT(*DAG.getContext(), ShVT.getVectorElementType(), WidenVT.getVectorNumElements()); if (ShVT != ShWidenVT) ShOp = ModifyToType(ShOp, ShWidenVT); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp, ShOp); } SDValue DAGTypeLegalizer::WidenVecRes_Unary(SDNode *N) { // Unary op widening. EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); SDValue InOp = GetWidenedVector(N->getOperand(0)); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp); } SDValue DAGTypeLegalizer::WidenVecRes_InregOp(SDNode *N) { EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), cast<VTSDNode>(N->getOperand(1))->getVT() .getVectorElementType(), WidenVT.getVectorNumElements()); SDValue WidenLHS = GetWidenedVector(N->getOperand(0)); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, WidenLHS, DAG.getValueType(ExtVT)); } SDValue DAGTypeLegalizer::WidenVecRes_MERGE_VALUES(SDNode *N, unsigned ResNo) { SDValue WidenVec = DisintegrateMERGE_VALUES(N, ResNo); return GetWidenedVector(WidenVec); } SDValue DAGTypeLegalizer::WidenVecRes_BITCAST(SDNode *N) { SDValue InOp = N->getOperand(0); EVT InVT = InOp.getValueType(); EVT VT = N->getValueType(0); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); DebugLoc dl = N->getDebugLoc(); switch (getTypeAction(InVT)) { case TargetLowering::TypeLegal: break; case TargetLowering::TypePromoteInteger: // If the incoming type is a vector that is being promoted, then // we know that the elements are arranged differently and that we // must perform the conversion using a stack slot. if (InVT.isVector()) break; // If the InOp is promoted to the same size, convert it. Otherwise, // fall out of the switch and widen the promoted input. InOp = GetPromotedInteger(InOp); InVT = InOp.getValueType(); if (WidenVT.bitsEq(InVT)) return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp); break; case TargetLowering::TypeSoftenFloat: case TargetLowering::TypeExpandInteger: case TargetLowering::TypeExpandFloat: case TargetLowering::TypeScalarizeVector: case TargetLowering::TypeSplitVector: break; case TargetLowering::TypeWidenVector: // If the InOp is widened to the same size, convert it. Otherwise, fall // out of the switch and widen the widened input. InOp = GetWidenedVector(InOp); InVT = InOp.getValueType(); if (WidenVT.bitsEq(InVT)) // The input widens to the same size. Convert to the widen value. return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp); break; } unsigned WidenSize = WidenVT.getSizeInBits(); unsigned InSize = InVT.getSizeInBits(); // x86mmx is not an acceptable vector element type, so don't try. if (WidenSize % InSize == 0 && InVT != MVT::x86mmx) { // Determine new input vector type. The new input vector type will use // the same element type (if its a vector) or use the input type as a // vector. It is the same size as the type to widen to. EVT NewInVT; unsigned NewNumElts = WidenSize / InSize; if (InVT.isVector()) { EVT InEltVT = InVT.getVectorElementType(); NewInVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenSize / InEltVT.getSizeInBits()); } else { NewInVT = EVT::getVectorVT(*DAG.getContext(), InVT, NewNumElts); } if (TLI.isTypeLegal(NewInVT)) { // Because the result and the input are different vector types, widening // the result could create a legal type but widening the input might make // it an illegal type that might lead to repeatedly splitting the input // and then widening it. To avoid this, we widen the input only if // it results in a legal type. SmallVector<SDValue, 16> Ops(NewNumElts); SDValue UndefVal = DAG.getUNDEF(InVT); Ops[0] = InOp; for (unsigned i = 1; i < NewNumElts; ++i) Ops[i] = UndefVal; SDValue NewVec; if (InVT.isVector()) NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewInVT, &Ops[0], NewNumElts); else NewVec = DAG.getNode(ISD::BUILD_VECTOR, dl, NewInVT, &Ops[0], NewNumElts); return DAG.getNode(ISD::BITCAST, dl, WidenVT, NewVec); } } return CreateStackStoreLoad(InOp, WidenVT); } SDValue DAGTypeLegalizer::WidenVecRes_BUILD_VECTOR(SDNode *N) { DebugLoc dl = N->getDebugLoc(); // Build a vector with undefined for the new nodes. EVT VT = N->getValueType(0); EVT EltVT = VT.getVectorElementType(); unsigned NumElts = VT.getVectorNumElements(); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); unsigned WidenNumElts = WidenVT.getVectorNumElements(); SmallVector<SDValue, 16> NewOps(N->op_begin(), N->op_end()); NewOps.reserve(WidenNumElts); for (unsigned i = NumElts; i < WidenNumElts; ++i) NewOps.push_back(DAG.getUNDEF(EltVT)); return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &NewOps[0], NewOps.size()); } SDValue DAGTypeLegalizer::WidenVecRes_CONCAT_VECTORS(SDNode *N) { EVT InVT = N->getOperand(0).getValueType(); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); DebugLoc dl = N->getDebugLoc(); unsigned WidenNumElts = WidenVT.getVectorNumElements(); unsigned NumInElts = InVT.getVectorNumElements(); unsigned NumOperands = N->getNumOperands(); bool InputWidened = false; // Indicates we need to widen the input. if (getTypeAction(InVT) != TargetLowering::TypeWidenVector) { if (WidenVT.getVectorNumElements() % InVT.getVectorNumElements() == 0) { // Add undef vectors to widen to correct length. unsigned NumConcat = WidenVT.getVectorNumElements() / InVT.getVectorNumElements(); SDValue UndefVal = DAG.getUNDEF(InVT); SmallVector<SDValue, 16> Ops(NumConcat); for (unsigned i=0; i < NumOperands; ++i) Ops[i] = N->getOperand(i); for (unsigned i = NumOperands; i != NumConcat; ++i) Ops[i] = UndefVal; return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &Ops[0], NumConcat); } } else { InputWidened = true; if (WidenVT == TLI.getTypeToTransformTo(*DAG.getContext(), InVT)) { // The inputs and the result are widen to the same value. unsigned i; for (i=1; i < NumOperands; ++i) if (N->getOperand(i).getOpcode() != ISD::UNDEF) break; if (i == NumOperands) // Everything but the first operand is an UNDEF so just return the // widened first operand. return GetWidenedVector(N->getOperand(0)); if (NumOperands == 2) { // Replace concat of two operands with a shuffle. SmallVector<int, 16> MaskOps(WidenNumElts, -1); for (unsigned i = 0; i < NumInElts; ++i) { MaskOps[i] = i; MaskOps[i + NumInElts] = i + WidenNumElts; } return DAG.getVectorShuffle(WidenVT, dl, GetWidenedVector(N->getOperand(0)), GetWidenedVector(N->getOperand(1)), &MaskOps[0]); } } } // Fall back to use extracts and build vector. EVT EltVT = WidenVT.getVectorElementType(); SmallVector<SDValue, 16> Ops(WidenNumElts); unsigned Idx = 0; for (unsigned i=0; i < NumOperands; ++i) { SDValue InOp = N->getOperand(i); if (InputWidened) InOp = GetWidenedVector(InOp); for (unsigned j=0; j < NumInElts; ++j) Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp, DAG.getIntPtrConstant(j)); } SDValue UndefVal = DAG.getUNDEF(EltVT); for (; Idx < WidenNumElts; ++Idx) Ops[Idx] = UndefVal; return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts); } SDValue DAGTypeLegalizer::WidenVecRes_CONVERT_RNDSAT(SDNode *N) { DebugLoc dl = N->getDebugLoc(); SDValue InOp = N->getOperand(0); SDValue RndOp = N->getOperand(3); SDValue SatOp = N->getOperand(4); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); unsigned WidenNumElts = WidenVT.getVectorNumElements(); EVT InVT = InOp.getValueType(); EVT InEltVT = InVT.getVectorElementType(); EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts); SDValue DTyOp = DAG.getValueType(WidenVT); SDValue STyOp = DAG.getValueType(InWidenVT); ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode(); unsigned InVTNumElts = InVT.getVectorNumElements(); if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) { InOp = GetWidenedVector(InOp); InVT = InOp.getValueType(); InVTNumElts = InVT.getVectorNumElements(); if (InVTNumElts == WidenNumElts) return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp, SatOp, CvtCode); } if (TLI.isTypeLegal(InWidenVT)) { // Because the result and the input are different vector types, widening // the result could create a legal type but widening the input might make // it an illegal type that might lead to repeatedly splitting the input // and then widening it. To avoid this, we widen the input only if // it results in a legal type. if (WidenNumElts % InVTNumElts == 0) { // Widen the input and call convert on the widened input vector. unsigned NumConcat = WidenNumElts/InVTNumElts; SmallVector<SDValue, 16> Ops(NumConcat); Ops[0] = InOp; SDValue UndefVal = DAG.getUNDEF(InVT); for (unsigned i = 1; i != NumConcat; ++i) Ops[i] = UndefVal; InOp = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWidenVT, &Ops[0],NumConcat); return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp, SatOp, CvtCode); } if (InVTNumElts % WidenNumElts == 0) { // Extract the input and convert the shorten input vector. InOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InWidenVT, InOp, DAG.getIntPtrConstant(0)); return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp, SatOp, CvtCode); } } // Otherwise unroll into some nasty scalar code and rebuild the vector. SmallVector<SDValue, 16> Ops(WidenNumElts); EVT EltVT = WidenVT.getVectorElementType(); DTyOp = DAG.getValueType(EltVT); STyOp = DAG.getValueType(InEltVT); unsigned MinElts = std::min(InVTNumElts, WidenNumElts); unsigned i; for (i=0; i < MinElts; ++i) { SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp, DAG.getIntPtrConstant(i)); Ops[i] = DAG.getConvertRndSat(WidenVT, dl, ExtVal, DTyOp, STyOp, RndOp, SatOp, CvtCode); } SDValue UndefVal = DAG.getUNDEF(EltVT); for (; i < WidenNumElts; ++i) Ops[i] = UndefVal; return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts); } SDValue DAGTypeLegalizer::WidenVecRes_EXTRACT_SUBVECTOR(SDNode *N) { EVT VT = N->getValueType(0); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); unsigned WidenNumElts = WidenVT.getVectorNumElements(); SDValue InOp = N->getOperand(0); SDValue Idx = N->getOperand(1); DebugLoc dl = N->getDebugLoc(); if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector) InOp = GetWidenedVector(InOp); EVT InVT = InOp.getValueType(); // Check if we can just return the input vector after widening. uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); if (IdxVal == 0 && InVT == WidenVT) return InOp; // Check if we can extract from the vector. unsigned InNumElts = InVT.getVectorNumElements(); if (IdxVal % WidenNumElts == 0 && IdxVal + WidenNumElts < InNumElts) return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, InOp, Idx); // We could try widening the input to the right length but for now, extract // the original elements, fill the rest with undefs and build a vector. SmallVector<SDValue, 16> Ops(WidenNumElts); EVT EltVT = VT.getVectorElementType(); unsigned NumElts = VT.getVectorNumElements(); unsigned i; for (i=0; i < NumElts; ++i) Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp, DAG.getIntPtrConstant(IdxVal+i)); SDValue UndefVal = DAG.getUNDEF(EltVT); for (; i < WidenNumElts; ++i) Ops[i] = UndefVal; return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts); } SDValue DAGTypeLegalizer::WidenVecRes_INSERT_VECTOR_ELT(SDNode *N) { SDValue InOp = GetWidenedVector(N->getOperand(0)); return DAG.getNode(ISD::INSERT_VECTOR_ELT, N->getDebugLoc(), InOp.getValueType(), InOp, N->getOperand(1), N->getOperand(2)); } SDValue DAGTypeLegalizer::WidenVecRes_LOAD(SDNode *N) { LoadSDNode *LD = cast<LoadSDNode>(N); ISD::LoadExtType ExtType = LD->getExtensionType(); SDValue Result; SmallVector<SDValue, 16> LdChain; // Chain for the series of load if (ExtType != ISD::NON_EXTLOAD) Result = GenWidenVectorExtLoads(LdChain, LD, ExtType); else Result = GenWidenVectorLoads(LdChain, LD); // If we generate a single load, we can use that for the chain. Otherwise, // build a factor node to remember the multiple loads are independent and // chain to that. SDValue NewChain; if (LdChain.size() == 1) NewChain = LdChain[0]; else NewChain = DAG.getNode(ISD::TokenFactor, LD->getDebugLoc(), MVT::Other, &LdChain[0], LdChain.size()); // Modified the chain - switch anything that used the old chain to use // the new one. ReplaceValueWith(SDValue(N, 1), NewChain); return Result; } SDValue DAGTypeLegalizer::WidenVecRes_SCALAR_TO_VECTOR(SDNode *N) { EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); return DAG.getNode(ISD::SCALAR_TO_VECTOR, N->getDebugLoc(), WidenVT, N->getOperand(0)); } SDValue DAGTypeLegalizer::WidenVecRes_SELECT(SDNode *N) { EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); unsigned WidenNumElts = WidenVT.getVectorNumElements(); SDValue Cond1 = N->getOperand(0); EVT CondVT = Cond1.getValueType(); if (CondVT.isVector()) { EVT CondEltVT = CondVT.getVectorElementType(); EVT CondWidenVT = EVT::getVectorVT(*DAG.getContext(), CondEltVT, WidenNumElts); if (getTypeAction(CondVT) == TargetLowering::TypeWidenVector) Cond1 = GetWidenedVector(Cond1); if (Cond1.getValueType() != CondWidenVT) Cond1 = ModifyToType(Cond1, CondWidenVT); } SDValue InOp1 = GetWidenedVector(N->getOperand(1)); SDValue InOp2 = GetWidenedVector(N->getOperand(2)); assert(InOp1.getValueType() == WidenVT && InOp2.getValueType() == WidenVT); return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, Cond1, InOp1, InOp2); } SDValue DAGTypeLegalizer::WidenVecRes_SELECT_CC(SDNode *N) { SDValue InOp1 = GetWidenedVector(N->getOperand(2)); SDValue InOp2 = GetWidenedVector(N->getOperand(3)); return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), InOp1.getValueType(), N->getOperand(0), N->getOperand(1), InOp1, InOp2, N->getOperand(4)); } SDValue DAGTypeLegalizer::WidenVecRes_SETCC(SDNode *N) { assert(N->getValueType(0).isVector() == N->getOperand(0).getValueType().isVector() && "Scalar/Vector type mismatch"); if (N->getValueType(0).isVector()) return WidenVecRes_VSETCC(N); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); SDValue InOp1 = GetWidenedVector(N->getOperand(0)); SDValue InOp2 = GetWidenedVector(N->getOperand(1)); return DAG.getNode(ISD::SETCC, N->getDebugLoc(), WidenVT, InOp1, InOp2, N->getOperand(2)); } SDValue DAGTypeLegalizer::WidenVecRes_UNDEF(SDNode *N) { EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); return DAG.getUNDEF(WidenVT); } SDValue DAGTypeLegalizer::WidenVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N) { EVT VT = N->getValueType(0); DebugLoc dl = N->getDebugLoc(); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); unsigned NumElts = VT.getVectorNumElements(); unsigned WidenNumElts = WidenVT.getVectorNumElements(); SDValue InOp1 = GetWidenedVector(N->getOperand(0)); SDValue InOp2 = GetWidenedVector(N->getOperand(1)); // Adjust mask based on new input vector length. SmallVector<int, 16> NewMask; for (unsigned i = 0; i != NumElts; ++i) { int Idx = N->getMaskElt(i); if (Idx < (int)NumElts) NewMask.push_back(Idx); else NewMask.push_back(Idx - NumElts + WidenNumElts); } for (unsigned i = NumElts; i != WidenNumElts; ++i) NewMask.push_back(-1); return DAG.getVectorShuffle(WidenVT, dl, InOp1, InOp2, &NewMask[0]); } SDValue DAGTypeLegalizer::WidenVecRes_VSETCC(SDNode *N) { assert(N->getValueType(0).isVector() && N->getOperand(0).getValueType().isVector() && "Operands must be vectors"); EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)); unsigned WidenNumElts = WidenVT.getVectorNumElements(); SDValue InOp1 = N->getOperand(0); EVT InVT = InOp1.getValueType(); assert(InVT.isVector() && "can not widen non vector type"); EVT WidenInVT = EVT::getVectorVT(*DAG.getContext(), InVT.getVectorElementType(), WidenNumElts); InOp1 = GetWidenedVector(InOp1); SDValue InOp2 = GetWidenedVector(N->getOperand(1)); // Assume that the input and output will be widen appropriately. If not, // we will have to unroll it at some point. assert(InOp1.getValueType() == WidenInVT && InOp2.getValueType() == WidenInVT && "Input not widened to expected type!"); (void)WidenInVT; return DAG.getNode(ISD::SETCC, N->getDebugLoc(), WidenVT, InOp1, InOp2, N->getOperand(2)); } //===----------------------------------------------------------------------===// // Widen Vector Operand //===----------------------------------------------------------------------===// bool DAGTypeLegalizer::WidenVectorOperand(SDNode *N, unsigned OpNo) { DEBUG(dbgs() << "Widen node operand " << OpNo << ": "; N->dump(&DAG); dbgs() << "\n"); SDValue Res = SDValue(); // See if the target wants to custom widen this node. if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false)) return false; switch (N->getOpcode()) { default: #ifndef NDEBUG dbgs() << "WidenVectorOperand op #" << OpNo << ": "; N->dump(&DAG); dbgs() << "\n"; #endif llvm_unreachable("Do not know how to widen this operator's operand!"); case ISD::BITCAST: Res = WidenVecOp_BITCAST(N); break; case ISD::CONCAT_VECTORS: Res = WidenVecOp_CONCAT_VECTORS(N); break; case ISD::EXTRACT_SUBVECTOR: Res = WidenVecOp_EXTRACT_SUBVECTOR(N); break; case ISD::EXTRACT_VECTOR_ELT: Res = WidenVecOp_EXTRACT_VECTOR_ELT(N); break; case ISD::STORE: Res = WidenVecOp_STORE(N); break; case ISD::SETCC: Res = WidenVecOp_SETCC(N); break; case ISD::FP_EXTEND: case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: case ISD::SINT_TO_FP: case ISD::UINT_TO_FP: case ISD::TRUNCATE: case ISD::SIGN_EXTEND: case ISD::ZERO_EXTEND: case ISD::ANY_EXTEND: Res = WidenVecOp_Convert(N); break; } // If Res is null, the sub-method took care of registering the result. if (!Res.getNode()) return false; // If the result is N, the sub-method updated N in place. Tell the legalizer // core about this. if (Res.getNode() == N) return true; assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 && "Invalid operand expansion"); ReplaceValueWith(SDValue(N, 0), Res); return false; } SDValue DAGTypeLegalizer::WidenVecOp_Convert(SDNode *N) { // Since the result is legal and the input is illegal, it is unlikely // that we can fix the input to a legal type so unroll the convert // into some scalar code and create a nasty build vector. EVT VT = N->getValueType(0); EVT EltVT = VT.getVectorElementType(); DebugLoc dl = N->getDebugLoc(); unsigned NumElts = VT.getVectorNumElements(); SDValue InOp = N->getOperand(0); if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector) InOp = GetWidenedVector(InOp); EVT InVT = InOp.getValueType(); EVT InEltVT = InVT.getVectorElementType(); unsigned Opcode = N->getOpcode(); SmallVector<SDValue, 16> Ops(NumElts); for (unsigned i=0; i < NumElts; ++i) Ops[i] = DAG.getNode(Opcode, dl, EltVT, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp, DAG.getIntPtrConstant(i))); return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts); } SDValue DAGTypeLegalizer::WidenVecOp_BITCAST(SDNode *N) { EVT VT = N->getValueType(0); SDValue InOp = GetWidenedVector(N->getOperand(0)); EVT InWidenVT = InOp.getValueType(); DebugLoc dl = N->getDebugLoc(); // Check if we can convert between two legal vector types and extract. unsigned InWidenSize = InWidenVT.getSizeInBits(); unsigned Size = VT.getSizeInBits(); // x86mmx is not an acceptable vector element type, so don't try. if (InWidenSize % Size == 0 && !VT.isVector() && VT != MVT::x86mmx) { unsigned NewNumElts = InWidenSize / Size; EVT NewVT = EVT::getVectorVT(*DAG.getContext(), VT, NewNumElts); if (TLI.isTypeLegal(NewVT)) { SDValue BitOp = DAG.getNode(ISD::BITCAST, dl, NewVT, InOp); return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, BitOp, DAG.getIntPtrConstant(0)); } } return CreateStackStoreLoad(InOp, VT); } SDValue DAGTypeLegalizer::WidenVecOp_CONCAT_VECTORS(SDNode *N) { // If the input vector is not legal, it is likely that we will not find a // legal vector of the same size. Replace the concatenate vector with a // nasty build vector. EVT VT = N->getValueType(0); EVT EltVT = VT.getVectorElementType(); DebugLoc dl = N->getDebugLoc(); unsigned NumElts = VT.getVectorNumElements(); SmallVector<SDValue, 16> Ops(NumElts); EVT InVT = N->getOperand(0).getValueType(); unsigned NumInElts = InVT.getVectorNumElements(); unsigned Idx = 0; unsigned NumOperands = N->getNumOperands(); for (unsigned i=0; i < NumOperands; ++i) { SDValue InOp = N->getOperand(i); if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector) InOp = GetWidenedVector(InOp); for (unsigned j=0; j < NumInElts; ++j) Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp, DAG.getIntPtrConstant(j)); } return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts); } SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_SUBVECTOR(SDNode *N) { SDValue InOp = GetWidenedVector(N->getOperand(0)); return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), N->getValueType(0), InOp, N->getOperand(1)); } SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N) { SDValue InOp = GetWidenedVector(N->getOperand(0)); return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), N->getValueType(0), InOp, N->getOperand(1)); } SDValue DAGTypeLegalizer::WidenVecOp_STORE(SDNode *N) { // We have to widen the value but we want only to store the original // vector type. StoreSDNode *ST = cast<StoreSDNode>(N); SmallVector<SDValue, 16> StChain; if (ST->isTruncatingStore()) GenWidenVectorTruncStores(StChain, ST); else GenWidenVectorStores(StChain, ST); if (StChain.size() == 1) return StChain[0]; else return DAG.getNode(ISD::TokenFactor, ST->getDebugLoc(), MVT::Other,&StChain[0],StChain.size()); } SDValue DAGTypeLegalizer::WidenVecOp_SETCC(SDNode *N) { SDValue InOp0 = GetWidenedVector(N->getOperand(0)); SDValue InOp1 = GetWidenedVector(N->getOperand(1)); DebugLoc dl = N->getDebugLoc(); // WARNING: In this code we widen the compare instruction with garbage. // This garbage may contain denormal floats which may be slow. Is this a real // concern ? Should we zero the unused lanes if this is a float compare ? // Get a new SETCC node to compare the newly widened operands. // Only some of the compared elements are legal. EVT SVT = TLI.getSetCCResultType(InOp0.getValueType()); SDValue WideSETCC = DAG.getNode(ISD::SETCC, N->getDebugLoc(), SVT, InOp0, InOp1, N->getOperand(2)); // Extract the needed results from the result vector. EVT ResVT = EVT::getVectorVT(*DAG.getContext(), SVT.getVectorElementType(), N->getValueType(0).getVectorNumElements()); SDValue CC = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResVT, WideSETCC, DAG.getIntPtrConstant(0)); return PromoteTargetBoolean(CC, N->getValueType(0)); } //===----------------------------------------------------------------------===// // Vector Widening Utilities //===----------------------------------------------------------------------===// // Utility function to find the type to chop up a widen vector for load/store // TLI: Target lowering used to determine legal types. // Width: Width left need to load/store. // WidenVT: The widen vector type to load to/store from // Align: If 0, don't allow use of a wider type // WidenEx: If Align is not 0, the amount additional we can load/store from. static EVT FindMemType(SelectionDAG& DAG, const TargetLowering &TLI, unsigned Width, EVT WidenVT, unsigned Align = 0, unsigned WidenEx = 0) { EVT WidenEltVT = WidenVT.getVectorElementType(); unsigned WidenWidth = WidenVT.getSizeInBits(); unsigned WidenEltWidth = WidenEltVT.getSizeInBits(); unsigned AlignInBits = Align*8; // If we have one element to load/store, return it. EVT RetVT = WidenEltVT; if (Width == WidenEltWidth) return RetVT; // See if there is larger legal integer than the element type to load/store unsigned VT; for (VT = (unsigned)MVT::LAST_INTEGER_VALUETYPE; VT >= (unsigned)MVT::FIRST_INTEGER_VALUETYPE; --VT) { EVT MemVT((MVT::SimpleValueType) VT); unsigned MemVTWidth = MemVT.getSizeInBits(); if (MemVT.getSizeInBits() <= WidenEltWidth) break; if (TLI.isTypeLegal(MemVT) && (WidenWidth % MemVTWidth) == 0 && isPowerOf2_32(WidenWidth / MemVTWidth) && (MemVTWidth <= Width || (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) { RetVT = MemVT; break; } } // See if there is a larger vector type to load/store that has the same vector // element type and is evenly divisible with the WidenVT. for (VT = (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT >= (unsigned)MVT::FIRST_VECTOR_VALUETYPE; --VT) { EVT MemVT = (MVT::SimpleValueType) VT; unsigned MemVTWidth = MemVT.getSizeInBits(); if (TLI.isTypeLegal(MemVT) && WidenEltVT == MemVT.getVectorElementType() && (WidenWidth % MemVTWidth) == 0 && isPowerOf2_32(WidenWidth / MemVTWidth) && (MemVTWidth <= Width || (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) { if (RetVT.getSizeInBits() < MemVTWidth || MemVT == WidenVT) return MemVT; } } return RetVT; } // Builds a vector type from scalar loads // VecTy: Resulting Vector type // LDOps: Load operators to build a vector type // [Start,End) the list of loads to use. static SDValue BuildVectorFromScalar(SelectionDAG& DAG, EVT VecTy, SmallVector<SDValue, 16>& LdOps, unsigned Start, unsigned End) { DebugLoc dl = LdOps[Start].getDebugLoc(); EVT LdTy = LdOps[Start].getValueType(); unsigned Width = VecTy.getSizeInBits(); unsigned NumElts = Width / LdTy.getSizeInBits(); EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), LdTy, NumElts); unsigned Idx = 1; SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT,LdOps[Start]); for (unsigned i = Start + 1; i != End; ++i) { EVT NewLdTy = LdOps[i].getValueType(); if (NewLdTy != LdTy) { NumElts = Width / NewLdTy.getSizeInBits(); NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewLdTy, NumElts); VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, VecOp); // Readjust position and vector position based on new load type Idx = Idx * LdTy.getSizeInBits() / NewLdTy.getSizeInBits(); LdTy = NewLdTy; } VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVecVT, VecOp, LdOps[i], DAG.getIntPtrConstant(Idx++)); } return DAG.getNode(ISD::BITCAST, dl, VecTy, VecOp); } SDValue DAGTypeLegalizer::GenWidenVectorLoads(SmallVector<SDValue, 16> &LdChain, LoadSDNode *LD) { // The strategy assumes that we can efficiently load powers of two widths. // The routines chops the vector into the largest vector loads with the same // element type or scalar loads and then recombines it to the widen vector // type. EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0)); unsigned WidenWidth = WidenVT.getSizeInBits(); EVT LdVT = LD->getMemoryVT(); DebugLoc dl = LD->getDebugLoc(); assert(LdVT.isVector() && WidenVT.isVector()); assert(LdVT.getVectorElementType() == WidenVT.getVectorElementType()); // Load information SDValue Chain = LD->getChain(); SDValue BasePtr = LD->getBasePtr(); unsigned Align = LD->getAlignment(); bool isVolatile = LD->isVolatile(); bool isNonTemporal = LD->isNonTemporal(); bool isInvariant = LD->isInvariant(); int LdWidth = LdVT.getSizeInBits(); int WidthDiff = WidenWidth - LdWidth; // Difference unsigned LdAlign = (isVolatile) ? 0 : Align; // Allow wider loads // Find the vector type that can load from. EVT NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff); int NewVTWidth = NewVT.getSizeInBits(); SDValue LdOp = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo(), isVolatile, isNonTemporal, isInvariant, Align); LdChain.push_back(LdOp.getValue(1)); // Check if we can load the element with one instruction if (LdWidth <= NewVTWidth) { if (!NewVT.isVector()) { unsigned NumElts = WidenWidth / NewVTWidth; EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts); SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT, LdOp); return DAG.getNode(ISD::BITCAST, dl, WidenVT, VecOp); } if (NewVT == WidenVT) return LdOp; assert(WidenWidth % NewVTWidth == 0); unsigned NumConcat = WidenWidth / NewVTWidth; SmallVector<SDValue, 16> ConcatOps(NumConcat); SDValue UndefVal = DAG.getUNDEF(NewVT); ConcatOps[0] = LdOp; for (unsigned i = 1; i != NumConcat; ++i) ConcatOps[i] = UndefVal; return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0], NumConcat); } // Load vector by using multiple loads from largest vector to scalar SmallVector<SDValue, 16> LdOps; LdOps.push_back(LdOp); LdWidth -= NewVTWidth; unsigned Offset = 0; while (LdWidth > 0) { unsigned Increment = NewVTWidth / 8; Offset += Increment; BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getIntPtrConstant(Increment)); SDValue L; if (LdWidth < NewVTWidth) { // Our current type we are using is too large, find a better size NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff); NewVTWidth = NewVT.getSizeInBits(); L = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo().getWithOffset(Offset), isVolatile, isNonTemporal, isInvariant, MinAlign(Align, Increment)); LdChain.push_back(L.getValue(1)); if (L->getValueType(0).isVector()) { SmallVector<SDValue, 16> Loads; Loads.push_back(L); unsigned size = L->getValueSizeInBits(0); while (size < LdOp->getValueSizeInBits(0)) { Loads.push_back(DAG.getUNDEF(L->getValueType(0))); size += L->getValueSizeInBits(0); } L = DAG.getNode(ISD::CONCAT_VECTORS, dl, LdOp->getValueType(0), &Loads[0], Loads.size()); } } else { L = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo().getWithOffset(Offset), isVolatile, isNonTemporal, isInvariant, MinAlign(Align, Increment)); LdChain.push_back(L.getValue(1)); } LdOps.push_back(L); LdWidth -= NewVTWidth; } // Build the vector from the loads operations unsigned End = LdOps.size(); if (!LdOps[0].getValueType().isVector()) // All the loads are scalar loads. return BuildVectorFromScalar(DAG, WidenVT, LdOps, 0, End); // If the load contains vectors, build the vector using concat vector. // All of the vectors used to loads are power of 2 and the scalars load // can be combined to make a power of 2 vector. SmallVector<SDValue, 16> ConcatOps(End); int i = End - 1; int Idx = End; EVT LdTy = LdOps[i].getValueType(); // First combine the scalar loads to a vector if (!LdTy.isVector()) { for (--i; i >= 0; --i) { LdTy = LdOps[i].getValueType(); if (LdTy.isVector()) break; } ConcatOps[--Idx] = BuildVectorFromScalar(DAG, LdTy, LdOps, i+1, End); } ConcatOps[--Idx] = LdOps[i]; for (--i; i >= 0; --i) { EVT NewLdTy = LdOps[i].getValueType(); if (NewLdTy != LdTy) { // Create a larger vector ConcatOps[End-1] = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewLdTy, &ConcatOps[Idx], End - Idx); Idx = End - 1; LdTy = NewLdTy; } ConcatOps[--Idx] = LdOps[i]; } if (WidenWidth == LdTy.getSizeInBits()*(End - Idx)) return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[Idx], End - Idx); // We need to fill the rest with undefs to build the vector unsigned NumOps = WidenWidth / LdTy.getSizeInBits(); SmallVector<SDValue, 16> WidenOps(NumOps); SDValue UndefVal = DAG.getUNDEF(LdTy); { unsigned i = 0; for (; i != End-Idx; ++i) WidenOps[i] = ConcatOps[Idx+i]; for (; i != NumOps; ++i) WidenOps[i] = UndefVal; } return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &WidenOps[0],NumOps); } SDValue DAGTypeLegalizer::GenWidenVectorExtLoads(SmallVector<SDValue, 16>& LdChain, LoadSDNode * LD, ISD::LoadExtType ExtType) { // For extension loads, it may not be more efficient to chop up the vector // and then extended it. Instead, we unroll the load and build a new vector. EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0)); EVT LdVT = LD->getMemoryVT(); DebugLoc dl = LD->getDebugLoc(); assert(LdVT.isVector() && WidenVT.isVector()); // Load information SDValue Chain = LD->getChain(); SDValue BasePtr = LD->getBasePtr(); unsigned Align = LD->getAlignment(); bool isVolatile = LD->isVolatile(); bool isNonTemporal = LD->isNonTemporal(); EVT EltVT = WidenVT.getVectorElementType(); EVT LdEltVT = LdVT.getVectorElementType(); unsigned NumElts = LdVT.getVectorNumElements(); // Load each element and widen unsigned WidenNumElts = WidenVT.getVectorNumElements(); SmallVector<SDValue, 16> Ops(WidenNumElts); unsigned Increment = LdEltVT.getSizeInBits() / 8; Ops[0] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, BasePtr, LD->getPointerInfo(), LdEltVT, isVolatile, isNonTemporal, Align); LdChain.push_back(Ops[0].getValue(1)); unsigned i = 0, Offset = Increment; for (i=1; i < NumElts; ++i, Offset += Increment) { SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getIntPtrConstant(Offset)); Ops[i] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, NewBasePtr, LD->getPointerInfo().getWithOffset(Offset), LdEltVT, isVolatile, isNonTemporal, Align); LdChain.push_back(Ops[i].getValue(1)); } // Fill the rest with undefs SDValue UndefVal = DAG.getUNDEF(EltVT); for (; i != WidenNumElts; ++i) Ops[i] = UndefVal; return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], Ops.size()); } void DAGTypeLegalizer::GenWidenVectorStores(SmallVector<SDValue, 16>& StChain, StoreSDNode *ST) { // The strategy assumes that we can efficiently store powers of two widths. // The routines chops the vector into the largest vector stores with the same // element type or scalar stores. SDValue Chain = ST->getChain(); SDValue BasePtr = ST->getBasePtr(); unsigned Align = ST->getAlignment(); bool isVolatile = ST->isVolatile(); bool isNonTemporal = ST->isNonTemporal(); SDValue ValOp = GetWidenedVector(ST->getValue()); DebugLoc dl = ST->getDebugLoc(); EVT StVT = ST->getMemoryVT(); unsigned StWidth = StVT.getSizeInBits(); EVT ValVT = ValOp.getValueType(); unsigned ValWidth = ValVT.getSizeInBits(); EVT ValEltVT = ValVT.getVectorElementType(); unsigned ValEltWidth = ValEltVT.getSizeInBits(); assert(StVT.getVectorElementType() == ValEltVT); int Idx = 0; // current index to store unsigned Offset = 0; // offset from base to store while (StWidth != 0) { // Find the largest vector type we can store with EVT NewVT = FindMemType(DAG, TLI, StWidth, ValVT); unsigned NewVTWidth = NewVT.getSizeInBits(); unsigned Increment = NewVTWidth / 8; if (NewVT.isVector()) { unsigned NumVTElts = NewVT.getVectorNumElements(); do { SDValue EOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT, ValOp, DAG.getIntPtrConstant(Idx)); StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr, ST->getPointerInfo().getWithOffset(Offset), isVolatile, isNonTemporal, MinAlign(Align, Offset))); StWidth -= NewVTWidth; Offset += Increment; Idx += NumVTElts; BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getIntPtrConstant(Increment)); } while (StWidth != 0 && StWidth >= NewVTWidth); } else { // Cast the vector to the scalar type we can store unsigned NumElts = ValWidth / NewVTWidth; EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts); SDValue VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, ValOp); // Readjust index position based on new vector type Idx = Idx * ValEltWidth / NewVTWidth; do { SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewVT, VecOp, DAG.getIntPtrConstant(Idx++)); StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr, ST->getPointerInfo().getWithOffset(Offset), isVolatile, isNonTemporal, MinAlign(Align, Offset))); StWidth -= NewVTWidth; Offset += Increment; BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getIntPtrConstant(Increment)); } while (StWidth != 0 && StWidth >= NewVTWidth); // Restore index back to be relative to the original widen element type Idx = Idx * NewVTWidth / ValEltWidth; } } } void DAGTypeLegalizer::GenWidenVectorTruncStores(SmallVector<SDValue, 16>& StChain, StoreSDNode *ST) { // For extension loads, it may not be more efficient to truncate the vector // and then store it. Instead, we extract each element and then store it. SDValue Chain = ST->getChain(); SDValue BasePtr = ST->getBasePtr(); unsigned Align = ST->getAlignment(); bool isVolatile = ST->isVolatile(); bool isNonTemporal = ST->isNonTemporal(); SDValue ValOp = GetWidenedVector(ST->getValue()); DebugLoc dl = ST->getDebugLoc(); EVT StVT = ST->getMemoryVT(); EVT ValVT = ValOp.getValueType(); // It must be true that we the widen vector type is bigger than where // we need to store. assert(StVT.isVector() && ValOp.getValueType().isVector()); assert(StVT.bitsLT(ValOp.getValueType())); // For truncating stores, we can not play the tricks of chopping legal // vector types and bit cast it to the right type. Instead, we unroll // the store. EVT StEltVT = StVT.getVectorElementType(); EVT ValEltVT = ValVT.getVectorElementType(); unsigned Increment = ValEltVT.getSizeInBits() / 8; unsigned NumElts = StVT.getVectorNumElements(); SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp, DAG.getIntPtrConstant(0)); StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, BasePtr, ST->getPointerInfo(), StEltVT, isVolatile, isNonTemporal, Align)); unsigned Offset = Increment; for (unsigned i=1; i < NumElts; ++i, Offset += Increment) { SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getIntPtrConstant(Offset)); SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp, DAG.getIntPtrConstant(0)); StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, NewBasePtr, ST->getPointerInfo().getWithOffset(Offset), StEltVT, isVolatile, isNonTemporal, MinAlign(Align, Offset))); } } /// Modifies a vector input (widen or narrows) to a vector of NVT. The /// input vector must have the same element type as NVT. SDValue DAGTypeLegalizer::ModifyToType(SDValue InOp, EVT NVT) { // Note that InOp might have been widened so it might already have // the right width or it might need be narrowed. EVT InVT = InOp.getValueType(); assert(InVT.getVectorElementType() == NVT.getVectorElementType() && "input and widen element type must match"); DebugLoc dl = InOp.getDebugLoc(); // Check if InOp already has the right width. if (InVT == NVT) return InOp; unsigned InNumElts = InVT.getVectorNumElements(); unsigned WidenNumElts = NVT.getVectorNumElements(); if (WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0) { unsigned NumConcat = WidenNumElts / InNumElts; SmallVector<SDValue, 16> Ops(NumConcat); SDValue UndefVal = DAG.getUNDEF(InVT); Ops[0] = InOp; for (unsigned i = 1; i != NumConcat; ++i) Ops[i] = UndefVal; return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, &Ops[0], NumConcat); } if (WidenNumElts < InNumElts && InNumElts % WidenNumElts) return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, InOp, DAG.getIntPtrConstant(0)); // Fall back to extract and build. SmallVector<SDValue, 16> Ops(WidenNumElts); EVT EltVT = NVT.getVectorElementType(); unsigned MinNumElts = std::min(WidenNumElts, InNumElts); unsigned Idx; for (Idx = 0; Idx < MinNumElts; ++Idx) Ops[Idx] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp, DAG.getIntPtrConstant(Idx)); SDValue UndefVal = DAG.getUNDEF(EltVT); for ( ; Idx < WidenNumElts; ++Idx) Ops[Idx] = UndefVal; return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &Ops[0], WidenNumElts); }
38.971712
81
0.639172
nettrino
d51a8fe0a2f169cda115e9ac3721afcf1e9d24d5
5,873
cc
C++
src/run_crown/deref_expression.cc
Clown-FM/CROWN
7690d59d9459ffa1be7226edd0bede7546412da9
[ "MIT", "BSD-3-Clause" ]
1
2019-09-07T09:58:26.000Z
2019-09-07T09:58:26.000Z
src/run_crown/deref_expression.cc
kunwoo1209/CROWN
7690d59d9459ffa1be7226edd0bede7546412da9
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/run_crown/deref_expression.cc
kunwoo1209/CROWN
7690d59d9459ffa1be7226edd0bede7546412da9
[ "MIT", "BSD-3-Clause" ]
4
2019-09-07T09:53:17.000Z
2021-09-04T16:11:20.000Z
// This file is part of CROWN, which is distributed under the revised // BSD license. A copy of this license can be found in the file LICENSE. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE // for details. /*** * Author: Sudeep juvekar (sjuvekar@eecs.berkeley.edu) * 4/17/09 */ #include <assert.h> #include <cstdlib> #include <cstring> #include <z3.h> #include <iostream> #include "base/basic_functions.h" #include "run_crown/deref_expression.h" #include "run_crown/symbolic_object.h" #include "run_crown/object_tracker.h" #include "run_crown/symbolic_expression_factory.h" namespace crown { DerefExpr::DerefExpr(SymbolicExpr *c, size_t managerIdx, size_t snapshotIdx, size_t s, Value_t v) : SymbolicExpr(s,v), managerIdx_(managerIdx), snapshotIdx_(snapshotIdx), addr_(c) { } DerefExpr::DerefExpr(const DerefExpr& de) : SymbolicExpr(de.size(), de.value()), managerIdx_(de.managerIdx_), snapshotIdx_(de.snapshotIdx_), object_(de.object_), addr_(de.addr_->Clone()) { } DerefExpr::~DerefExpr() { delete addr_; } DerefExpr* DerefExpr::Clone() const { return new DerefExpr(*this); } void DerefExpr::AppendVars(set<var_t>* vars) const { ObjectTracker* tracker = global_tracker_; assert(tracker->snapshotManager().size() > managerIdx_); assert(tracker->snapshotManager()[managerIdx_]->size() > snapshotIdx_); SymbolicObject* object = tracker->snapshotManager()[managerIdx_]->at(snapshotIdx_); addr_->AppendVars(vars); for(size_t i = 0; i < object->writes().size(); i++){ SymbolicExpr *index = object->writes()[i].first; SymbolicExpr *exp = object->writes()[i].second; index->AppendVars(vars); exp->AppendVars(vars); } } bool DerefExpr::DependsOn(const map<var_t,type_t>& vars) const { ObjectTracker* tracker = global_tracker_; assert(tracker->snapshotManager().size() > managerIdx_); assert(tracker->snapshotManager()[managerIdx_]->size() > snapshotIdx_); SymbolicObject* object = tracker->snapshotManager()[managerIdx_]->at(snapshotIdx_); for(size_t i = 0; i < object->writes().size(); i++){ SymbolicExpr *index = object->writes()[i].first; SymbolicExpr *exp = object->writes()[i].second; bool res = index->DependsOn(vars) || exp->DependsOn(vars); if(res == true){ return true; } } return addr_->DependsOn(vars); } void DerefExpr::AppendToString(string *s) const { char buff[92]; s->append("(a!"); sprintf(buff, "%d%d[ ", managerIdx_,snapshotIdx_); s->append(buff); // s->append(", "); addr_->AppendToString(s); s->append(" ])"); } Z3_ast DerefExpr::ConvertToSMT(Z3_context ctx, Z3_solver sol) const { #ifdef DEBUG printf("ConvertToSMT Deref %d %d\n",managerIdx_, snapshotIdx_); #endif global_numOfOperator_++; size_t size_ = size(); Value_t value_ = value(); ObjectTracker* tracker = global_tracker_; assert(tracker->snapshotManager().size() > managerIdx_); assert(tracker->snapshotManager()[managerIdx_]->size() > snapshotIdx_); SymbolicObject* object = tracker->snapshotManager()[managerIdx_]->at(snapshotIdx_); //If the snapshots are not created as a SMT, then create dummy SMT if(tracker->isASTInit == false){ char name[24] = "t0"; Z3_sort ty = Z3_mk_bv_sort(ctx, 32); Z3_ast con = Z3_mk_const(ctx, Z3_mk_string_symbol(ctx, name), ty); for(size_t iter = 0; iter < tracker->snapshotManager().size(); iter++){ size_t objSize = tracker->snapshotManager()[iter]->size(); for(size_t iter2 = 0; iter2 < objSize; iter2++){ tracker->astManager()[iter]->push_back(con); tracker->isCreateAST()[iter]->push_back(false); } } tracker->isASTInit = true; } //size_t mem_length = object->writes().size(); //Naming the uninterpreted function char c[32]; sprintf(c, "a%ld",(unsigned long)this); //Bit-blast the address Z3_ast args_z3_f[1] = {addr_->ConvertToSMT(ctx, sol)}; Z3_sort input_type = Z3_mk_bv_sort(ctx, addr_->size() * 8); Z3_sort output_type; //Output values of a[x] needs to be registered. (e.g. double a[4]) if(value_.type == types::FLOAT){ output_type = Z3_mk_fpa_sort_single(ctx); }else if(value_.type == types::DOUBLE){ output_type = Z3_mk_fpa_sort_double(ctx); }else{ output_type = Z3_mk_bv_sort(ctx, size_*8); } Z3_symbol array_symbol = Z3_mk_string_symbol(ctx, c); Z3_sort array_sort = Z3_mk_array_sort(ctx, input_type, output_type); Z3_ast array = Z3_mk_const(ctx, array_symbol, array_sort); //If the object isn't already created as SMT, then create it. if(tracker->isCreateAST()[managerIdx_]->at(snapshotIdx_) == false){ array = object->ConvertToSMT(ctx, sol, array, output_type); tracker->astManager()[managerIdx_]->at(snapshotIdx_) = array; tracker->isCreateAST()[managerIdx_]->at(snapshotIdx_) = true; }else{ array = tracker->astManager()[managerIdx_]->at(snapshotIdx_); } //Dereference has to be in array (e.g. a[4] -> index can be 0,1,2,3) int sortSizeOfArray = Z3_get_bv_sort_size(ctx, Z3_get_sort(ctx, args_z3_f[0])); Z3_ast startAST = Z3_mk_int64(ctx, object->start(), Z3_mk_bv_sort(ctx, sortSizeOfArray)); Z3_ast endAST = Z3_mk_int64(ctx, object->start()+object->size(), Z3_mk_bv_sort(ctx, sortSizeOfArray)); Z3_ast startAST2 = Z3_mk_bvuge(ctx, args_z3_f[0], startAST); Z3_ast endAST2 = Z3_mk_bvult(ctx, args_z3_f[0], endAST); global_numOfExpr_+=2; //Assert that symbolic address is equal to at one of the values in domain Z3_solver_assert(ctx, sol,startAST2); Z3_solver_assert(ctx, sol,endAST2); //Return the application of the function to addr_ Z3_ast tmp = Z3_mk_select(ctx, array, args_z3_f[0]); return tmp; } bool DerefExpr::Equals(const SymbolicExpr& e) const { const DerefExpr* d = e.CastDerefExpr(); return ((d != NULL) && addr_->Equals(*d->addr_) && object_->Equals(*d->object_)); } } // namespace crown
32.269231
103
0.715307
Clown-FM
d51cb66fc40503d58f07b6731073208bc815fb66
3,975
cpp
C++
src/AssemblerMinHash.cpp
ekg/shasta
e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01
[ "BSD-3-Clause" ]
null
null
null
src/AssemblerMinHash.cpp
ekg/shasta
e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01
[ "BSD-3-Clause" ]
null
null
null
src/AssemblerMinHash.cpp
ekg/shasta
e2fd3c3d79fb4cafe77c62f6af2fef46f7a04b01
[ "BSD-3-Clause" ]
null
null
null
#include "Assembler.hpp" #include "MinHash.hpp" using namespace ChanZuckerberg; using namespace shasta; // Use the minHash algorithm to find alignment candidates. // Use as features sequences of m consecutive special k-mers. void Assembler::findAlignmentCandidatesMinHash( size_t m, // Number of consecutive k-mers that define a feature. size_t minHashIterationCount, // Number of minHash iterations. size_t log2MinHashBucketCount, // Base 2 log of number of buckets for minHash. size_t maxBucketSize, // The maximum size for a bucket to be used. size_t minFrequency, // Minimum number of minHash hits for a pair to become a candidate. size_t threadCount ) { checkKmersAreOpen(); checkMarkersAreOpen(); const ReadId readCount = ReadId(markers.size() / 2); CZI_ASSERT(readCount > 0); // If log2MinHashBucketCount is 0, choose a reasonable value // for the current number of reads. if(log2MinHashBucketCount == 0) { // Compute an approximate base 2 log of the number of reads. static_assert(sizeof(readCount) == 4, "Unexpected readCount size."); const int leadingZeroBitCount = __builtin_clz(readCount); const int log2ReadCount = 32 - leadingZeroBitCount; // Make log2MinHashBucketCount reasonably larger // than the approximate base 2 log of the number of reads. log2MinHashBucketCount = 5 + log2ReadCount; cout << "Set log2MinHashBucketCount to " << log2MinHashBucketCount << endl; } // Check that log2MinHashBucketCount is not unreasonably small. if((1ULL << (log2MinHashBucketCount-3ULL)) < readCount) { throw runtime_error("log2MinHashBucketCount is unreasonably small.\n" "Must at least equal base 2 log of number of reads plus 3."); } // Create the alignment candidates. alignmentCandidates.createNew(largeDataName("AlignmentCandidates"), largeDataPageSize); // Run the MinHash computation to find candidate alignments. MinHash minHash( m, minHashIterationCount, log2MinHashBucketCount, maxBucketSize, minFrequency, threadCount, kmerTable, markers, alignmentCandidates, largeDataFileNamePrefix, largeDataPageSize); } void Assembler::accessAlignmentCandidates() { alignmentCandidates.accessExistingReadOnly(largeDataName("AlignmentCandidates")); } void Assembler::checkAlignmentCandidatesAreOpen() const { if(!alignmentCandidates.isOpen) { throw runtime_error("Alignment candidates are not accessible."); } } // Write the reads that overlap a given read. void Assembler::writeOverlappingReads( ReadId readId0, Strand strand0, const string& fileName) { // Check that we have what we need. checkReadsAreOpen(); checkAlignmentCandidatesAreOpen(); // Open the output file and write the oriented read we were given. ofstream file(fileName); const OrientedReadId orientedReadId0(readId0, strand0); writeOrientedRead(orientedReadId0, file); const uint64_t length0 = reads[orientedReadId0.getReadId()].baseCount; cout << "Reads overlapping " << orientedReadId0 << " length " << length0 << endl; // Loop over all overlaps involving this oriented read. for(const uint64_t i: alignmentTable[orientedReadId0.getValue()]) { const AlignmentData& ad = alignmentData[i]; // Get the other oriented read involved in this overlap. const OrientedReadId orientedReadId1 = ad.getOther(orientedReadId0); // Write it out. const uint64_t length1 = reads[orientedReadId1.getReadId()].baseCount; cout << orientedReadId1 << " length " << length1 << endl; writeOrientedRead(orientedReadId1, file); } cout << "Found " << alignmentTable[orientedReadId0.getValue()].size(); cout << " overlapping oriented reads." << endl; }
32.056452
103
0.693082
ekg
d51d1caa2d631123f846b1530b8e5e05133e36c2
62,133
cpp
C++
WDL/win32_curses/eel_edit.cpp
badi91/iPlug2
e508e85060871cef4ff16c9bc80c503c375e0a14
[ "Zlib" ]
1,305
2018-07-28T08:48:47.000Z
2022-03-31T23:06:59.000Z
WDL/win32_curses/eel_edit.cpp
badi91/iPlug2
e508e85060871cef4ff16c9bc80c503c375e0a14
[ "Zlib" ]
582
2019-01-01T15:37:55.000Z
2022-03-30T22:57:16.000Z
WDL/win32_curses/eel_edit.cpp
badi91/iPlug2
e508e85060871cef4ff16c9bc80c503c375e0a14
[ "Zlib" ]
284
2018-10-17T22:16:26.000Z
2022-03-30T15:38:19.000Z
#ifdef _WIN32 #include <windows.h> #include <windowsx.h> #else #include "../swell/swell.h" #endif #include <stdlib.h> #include <string.h> #ifndef CURSES_INSTANCE #define CURSES_INSTANCE ((win32CursesCtx *)m_cursesCtx) #endif #include "curses.h" #include "eel_edit.h" #include "../wdlutf8.h" #include "../win32_utf8.h" #include "../wdlcstring.h" #include "../eel2/ns-eel-int.h" int g_eel_editor_max_vis_suggestions = 50; EEL_Editor::EEL_Editor(void *cursesCtx) : WDL_CursesEditor(cursesCtx) { m_suggestion_curline_comment_state=0; m_suggestion_x=m_suggestion_y=-1; m_case_sensitive=false; m_comment_str="//"; // todo IsWithinComment() or something? m_function_prefix = "function "; m_suggestion_hwnd=NULL; m_code_func_cache_lines=0; m_code_func_cache_time=0; } EEL_Editor::~EEL_Editor() { if (m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd); m_code_func_cache.Empty(true,free); } #define sh_func_ontoken(x,y) int EEL_Editor::namedTokenHighlight(const char *tokStart, int len, int state) { if (len == 4 && !strnicmp(tokStart,"this",4)) return SYNTAX_KEYWORD; if (len == 7 && !strnicmp(tokStart,"_global",7)) return SYNTAX_KEYWORD; if (len == 5 && !strnicmp(tokStart,"local",5)) return SYNTAX_KEYWORD; if (len == 8 && !strnicmp(tokStart,"function",8)) return SYNTAX_KEYWORD; if (len == 6 && !strnicmp(tokStart,"static",6)) return SYNTAX_KEYWORD; if (len == 8 && !strnicmp(tokStart,"instance",8)) return SYNTAX_KEYWORD; if (len == 6 && !strnicmp(tokStart,"global",6)) return SYNTAX_KEYWORD; if (len == 7 && !strnicmp(tokStart,"globals",7)) return SYNTAX_KEYWORD; if (len == 5 && !strnicmp(tokStart,"while",5)) return SYNTAX_KEYWORD; if (len == 4 && !strnicmp(tokStart,"loop",4)) return SYNTAX_KEYWORD; if (len == 17 && !strnicmp(tokStart,"__denormal_likely",17)) return SYNTAX_FUNC; if (len == 19 && !strnicmp(tokStart,"__denormal_unlikely",19)) return SYNTAX_FUNC; char buf[512]; lstrcpyn_safe(buf,tokStart,wdl_min(sizeof(buf),len+1)); NSEEL_VMCTX vm = peek_want_VM_funcs() ? peek_get_VM() : NULL; if (nseel_getFunctionByName((compileContext*)vm,buf,NULL)) return SYNTAX_FUNC; return A_NORMAL; } int EEL_Editor::parse_format_specifier(const char *fmt_in, int *var_offs, int *var_len) { const char *fmt = fmt_in+1; *var_offs = 0; *var_len = 0; if (fmt_in[0] != '%') return 0; // passed a non-specifier while (*fmt) { const char c = *fmt++; if (c>0 && isalpha(c)) { return (int) (fmt - fmt_in); } if (c == '.' || c == '+' || c == '-' || c == ' ' || (c>='0' && c<='9')) { } else if (c == '{') { if (*var_offs!=0) return 0; // already specified *var_offs = (int)(fmt-fmt_in); if (*fmt == '.' || (*fmt >= '0' && *fmt <= '9')) return 0; // symbol name can't start with 0-9 or . while (*fmt != '}') { if ((*fmt >= 'a' && *fmt <= 'z') || (*fmt >= 'A' && *fmt <= 'Z') || (*fmt >= '0' && *fmt <= '9') || *fmt == '_' || *fmt == '.' || *fmt == '#') { fmt++; } else { return 0; // bad character in variable name } } *var_len = (int)((fmt-fmt_in) - *var_offs); fmt++; } else { break; } } return 0; } void EEL_Editor::draw_string(int *skipcnt, const char *str, int amt, int *attr, int newAttr, int comment_string_state) { if (amt > 0 && comment_string_state=='"') { while (amt > 0 && *str) { const char *str_scan = str; int varpos,varlen,l=0; while (!l && *str_scan) { while (*str_scan && *str_scan != '%' && str_scan < str+amt) str_scan++; if (str_scan >= str+amt) break; l = parse_format_specifier(str_scan,&varpos,&varlen); if (!l && *str_scan) if (*++str_scan == '%') str_scan++; } if (!*str_scan || str_scan >= str+amt) break; // allow default processing to happen if we reached the end of the string if (l > amt) l=amt; if (str_scan > str) { const int sz=wdl_min((int)(str_scan-str),amt); draw_string_urlchk(skipcnt,str,sz,attr,newAttr); str += sz; amt -= sz; } { const int sz=(varlen>0) ? wdl_min(varpos,amt) : wdl_min(l,amt); if (sz>0) { draw_string_internal(skipcnt,str,sz,attr,SYNTAX_HIGHLIGHT2); str += sz; amt -= sz; } } if (varlen>0) { int sz = wdl_min(varlen,amt); if (sz>0) { draw_string_internal(skipcnt,str,sz,attr,*str == '#' ? SYNTAX_STRINGVAR : SYNTAX_HIGHLIGHT1); amt -= sz; str += sz; } sz = wdl_min(l - varpos - varlen, amt); if (sz>0) { draw_string_internal(skipcnt,str,sz,attr,SYNTAX_HIGHLIGHT2); amt-=sz; str+=sz; } } } } draw_string_urlchk(skipcnt,str,amt,attr,newAttr); } void EEL_Editor::draw_string_urlchk(int *skipcnt, const char *str, int amt, int *attr, int newAttr) { if (amt > 0 && (newAttr == SYNTAX_COMMENT || newAttr == SYNTAX_STRING)) { const char *sstr=str; while (amt > 0 && *str) { const char *str_scan = str; int l=0; while (l < 10 && *str_scan) { str_scan += l; l=0; while (*str_scan && (strncmp(str_scan,"http://",7) || (sstr != str_scan && str_scan[-1] > 0 && isalnum(str_scan[-1]))) && str_scan < str+amt) str_scan++; if (!*str_scan || str_scan >= str+amt) break; while (str_scan[l] && str_scan[l] != ')' && str_scan[l] != '\"' && str_scan[l] != ')' && str_scan[l] != ' ' && str_scan[l] != '\t') l++; } if (!*str_scan || str_scan >= str+amt) break; // allow default processing to happen if we reached the end of the string if (l > amt) l=amt; if (str_scan > str) { const int sz=wdl_min((int)(str_scan-str),amt); draw_string_internal(skipcnt,str,sz,attr,newAttr); str += sz; amt -= sz; } const int sz=wdl_min(l,amt); if (sz>0) { draw_string_internal(skipcnt,str,sz,attr,SYNTAX_HIGHLIGHT1); str += sz; amt -= sz; } } } draw_string_internal(skipcnt,str,amt,attr,newAttr); } void EEL_Editor::draw_string_internal(int *skipcnt, const char *str, int amt, int *attr, int newAttr) { // *skipcnt is in characters, amt is in bytes while (*skipcnt > 0 && amt > 0) { const int clen = wdl_utf8_parsechar(str,NULL); str += clen; amt -= clen; *skipcnt -= 1; } if (amt>0) { if (*attr != newAttr) { attrset(newAttr); *attr = newAttr; } addnstr(str,amt); } } WDL_TypedBuf<char> EEL_Editor::s_draw_parentokenstack; bool EEL_Editor::sh_draw_parenttokenstack_pop(char c) { int sz = s_draw_parentokenstack.GetSize(); while (--sz >= 0) { char tc = s_draw_parentokenstack.Get()[sz]; if (tc == c) { s_draw_parentokenstack.Resize(sz,false); return false; } switch (c) { case '?': // any open paren or semicolon is enough to cause error for ?: return true; case '(': if (tc == '[') return true; break; case '[': if (tc == '(') return true; break; } } return true; } bool EEL_Editor::sh_draw_parentokenstack_update(const char *tok, int toklen) { if (toklen == 1) { switch (*tok) { case '(': case '[': case ';': case '?': s_draw_parentokenstack.Add(*tok); break; case ':': return sh_draw_parenttokenstack_pop('?'); case ')': return sh_draw_parenttokenstack_pop('('); case ']': return sh_draw_parenttokenstack_pop('['); } } return false; } void EEL_Editor::draw_line_highlight(int y, const char *p, int *c_comment_state, int line_n) { if (line_n == m_curs_y) m_suggestion_curline_comment_state = *c_comment_state; int last_attr = A_NORMAL; attrset(last_attr); move(y, 0); int rv = do_draw_line(p, c_comment_state, last_attr); attrset(rv< 0 ? SYNTAX_ERROR : A_NORMAL); clrtoeol(); if (rv < 0) attrset(A_NORMAL); } int EEL_Editor::do_draw_line(const char *p, int *c_comment_state, int last_attr) { //skipcnt = m_offs_x if (is_code_start_line(p)) { *c_comment_state=0; s_draw_parentokenstack.Resize(0,false); } int skipcnt = m_offs_x; int ignoreSyntaxState = overrideSyntaxDrawingForLine(&skipcnt, &p, c_comment_state, &last_attr); if (ignoreSyntaxState>0) { int len = (int)strlen(p); draw_string(&skipcnt,p,len,&last_attr,ignoreSyntaxState==100 ? SYNTAX_ERROR : ignoreSyntaxState==2 ? SYNTAX_COMMENT : A_NORMAL); return len-m_offs_x < COLS; } // syntax highlighting const char *endptr = p+strlen(p); const char *tok; const char *lp = p; int toklen=0; int last_comment_state=*c_comment_state; while (NULL != (tok = sh_tokenize(&p,endptr,&toklen,c_comment_state)) || lp < endptr) { if (tok && *tok < 0 && toklen == 1) { while (tok[toklen] < 0) {p++; toklen++; } // utf-8 skip } if (last_comment_state>0) // if in a multi-line string or comment { // draw empty space between lp and p as a string. in this case, tok/toklen includes our string, so we quickly finish after draw_string(&skipcnt,lp,(int)(p-lp),&last_attr, last_comment_state==1 ? SYNTAX_COMMENT:SYNTAX_STRING, last_comment_state); last_comment_state=0; lp = p; continue; } sh_func_ontoken(tok,toklen); // draw empty space between lp and tok/endptr as normal const char *adv_to = tok ? tok : endptr; if (adv_to > lp) draw_string(&skipcnt,lp,(int)(adv_to-lp),&last_attr, A_NORMAL); if (adv_to >= endptr) break; last_comment_state=0; lp = p; if (adv_to == p) continue; // draw token int attr = A_NORMAL; int err_left=0; int err_right=0; int start_of_tok = 0; if (tok[0] == '/' && toklen > 1 && (tok[1] == '*' || tok[1] == '/')) { attr = SYNTAX_COMMENT; } else if (tok[0] > 0 && (isalpha(tok[0]) || tok[0] == '_' || tok[0] == '#')) { int def_attr = A_NORMAL; bool isf=true; if (tok[0] == '#') { def_attr = SYNTAX_STRINGVAR; draw_string(&skipcnt,tok,1,&last_attr,def_attr); tok++; toklen--; } while (toklen > 0) { // divide up by .s, if any int this_len=0; while (this_len < toklen && tok[this_len] != '.') this_len++; if (this_len > 0) { int attr=isf?namedTokenHighlight(tok,this_len,*c_comment_state):def_attr; if (isf && attr == A_NORMAL) { int ntok_len=0, cc = *c_comment_state; const char *pp=lp,*ntok = sh_tokenize(&pp,endptr,&ntok_len,&cc); if (ntok && ntok_len>0 && *ntok == '(') def_attr = attr = SYNTAX_FUNC2; } draw_string(&skipcnt,tok,this_len,&last_attr,attr==A_NORMAL?def_attr:attr); tok += this_len; toklen -= this_len; } if (toklen > 0) { draw_string(&skipcnt,tok,1,&last_attr,SYNTAX_HIGHLIGHT1); tok++; toklen--; } isf=false; } continue; } else if (tok[0] == '.' || (tok[0] >= '0' && tok[0] <= '9') || (toklen > 1 && tok[0] == '$' && (tok[1] == 'x' || tok[1]=='X'))) { attr = SYNTAX_HIGHLIGHT2; int x=1,mode=0; if (tok[0] == '.') mode=1; else if (toklen > 1 && (tok[0] == '$' || tok[0] == '0') && (tok[1] == 'x' || tok[1] == 'X')) { mode=2; x++; } for(;x<toklen;x++) { if (tok[x] == '.' && !mode) mode=1; else if (tok[x] < '0' || tok[x] > '9') { if (mode != 2 || ((tok[x] < 'a' || tok[x] > 'f') && (tok[x] < 'A' || tok[x] > 'F'))) break; } } if (x<toklen) err_right=toklen-x; } else if (tok[0] == '\'' || tok[0] == '\"') { start_of_tok = tok[0]; attr = SYNTAX_STRING; } else if (tok[0] == '$') { attr = SYNTAX_HIGHLIGHT2; if (toklen >= 3 && !strnicmp(tok,"$pi",3)) err_right = toklen - 3; else if (toklen >= 2 && !strnicmp(tok,"$e",2)) err_right = toklen - 2; else if (toklen >= 4 && !strnicmp(tok,"$phi",4)) err_right = toklen - 4; else if (toklen == 4 && tok[1] == '\'' && tok[3] == '\'') { } else if (toklen > 1 && tok[1] == '~') { int x; for(x=2;x<toklen;x++) if (tok[x] < '0' || tok[x] > '9') break; if (x<toklen) err_right=toklen-x; } else err_right = toklen; } else if (ignoreSyntaxState==-1 && (tok[0] == '{' || tok[0] == '}')) { attr = SYNTAX_HIGHLIGHT1; } else { const char *h="()+*-=/,|&%;!<>?:^!~[]"; while (*h && *h != tok[0]) h++; if (*h) { if (*c_comment_state != STATE_BEFORE_CODE && sh_draw_parentokenstack_update(tok,toklen)) attr = SYNTAX_ERROR; else attr = SYNTAX_HIGHLIGHT1; } else { err_left=1; if (tok[0] < 0) while (err_left < toklen && tok[err_left]<0) err_left++; // utf-8 skip } } if (ignoreSyntaxState) err_left = err_right = 0; if (err_left > 0) { if (err_left > toklen) err_left=toklen; draw_string(&skipcnt,tok,err_left,&last_attr,SYNTAX_ERROR); tok+=err_left; toklen -= err_left; } if (err_right > toklen) err_right=toklen; draw_string(&skipcnt, tok, toklen - err_right, &last_attr, attr, start_of_tok); if (err_right > 0) draw_string(&skipcnt,tok+toklen-err_right,err_right,&last_attr,SYNTAX_ERROR); if (ignoreSyntaxState == -1 && tok[0] == '>') { draw_string(&skipcnt,p,strlen(p),&last_attr,ignoreSyntaxState==2 ? SYNTAX_COMMENT : A_NORMAL); break; } } return 1; } int EEL_Editor::GetCommentStateForLineStart(int line) { if (m_write_leading_tabs<=0) m_indent_size=2; const bool uses_code_start_lines = !!is_code_start_line(NULL); int state=0; int x=0; if (uses_code_start_lines) { state=STATE_BEFORE_CODE; for (;;x++) { WDL_FastString *t = m_text.Get(x); if (!t || is_code_start_line(t->Get())) break; const char *p=t->Get(); if (!strnicmp(p,"tabsize:",8)) { int a = atoi(p+8); if (a>0 && a < 32) m_indent_size = a; } } // scan backwards to find line starting with @ for (x=line;x>=0;x--) { WDL_FastString *t = m_text.Get(x); if (!t) break; if (is_code_start_line(t->Get())) { state=0; break; } } x++; } s_draw_parentokenstack.Resize(0,false); for (;x<line;x++) { WDL_FastString *t = m_text.Get(x); const char *p = t?t->Get():""; if (is_code_start_line(p)) { s_draw_parentokenstack.Resize(0,false); state=0; } else if (state != STATE_BEFORE_CODE) { const int ll=t?t->GetLength():0; const char *endp = p+ll; int toklen; const char *tok; while (NULL != (tok=sh_tokenize(&p,endp,&toklen,&state))) // eat all tokens, updating state { sh_func_ontoken(tok,toklen); sh_draw_parentokenstack_update(tok,toklen); } } } return state; } const char *EEL_Editor::sh_tokenize(const char **ptr, const char *endptr, int *lenOut, int *state) { return nseel_simple_tokenizer(ptr, endptr, lenOut, state); } bool EEL_Editor::LineCanAffectOtherLines(const char *txt, int spos, int slen) // if multiline comment etc { const char *special_start = txt + spos; const char *special_end = txt + spos + slen; while (*txt) { if (txt >= special_start-1 && txt < special_end) { const char c = txt[0]; if (c == '*' && txt[1] == '/') return true; if (c == '/' && (txt[1] == '/' || txt[1] == '*')) return true; if (c == '\\' && (txt[1] == '\"' || txt[1] == '\'')) return true; if (txt >= special_start) { if (c == '\"' || c == '\'') return true; if (c == '(' || c == '[' || c == ')' || c == ']' || c == ':' || c == ';' || c == '?') return true; } } txt++; } return false; } struct eel_sh_token { int line, col, end_col; unsigned int data; // packed char for token type, plus 24 bits for linecnt (0=single line, 1=extra line, etc) eel_sh_token(int _line, int _col, int toklen, unsigned char c) { line = _line; col = _col; end_col = col + toklen; data = c; } ~eel_sh_token() { } void add_linecnt(int endcol) { data += 256; end_col = endcol; } int get_linecnt() const { return (data >> 8); } char get_c() const { return (char) (data & 255); } bool is_comment() const { return get_c() == '/' && (get_linecnt() || end_col>col+1); }; }; static int eel_sh_get_token_for_pos(const WDL_TypedBuf<eel_sh_token> *toklist, int line, int col, bool *is_after) { const int sz = toklist->GetSize(); int x; for (x=0; x < sz; x ++) { const eel_sh_token *tok = toklist->Get()+x; const int first_line = tok->line; const int last_line = first_line+tok->get_linecnt(); // last affected line (usually same as first) if (last_line >= line) // if this token doesn't end before the line we care about { // check to see if the token starts after our position if (first_line > line || (first_line == line && tok->col > col)) break; // token started before line/col, see if it ends after line/col if (last_line > line || tok->end_col > col) { // direct hit *is_after = false; return x; } } } *is_after = true; return x-1; } static void eel_sh_generate_token_list(const WDL_PtrList<WDL_FastString> *lines, WDL_TypedBuf<eel_sh_token> *toklist, int start_line, EEL_Editor *editor) { toklist->Resize(0,false); int state=0; int l; int end_line = lines->GetSize(); if (editor->is_code_start_line(NULL)) { for (l = start_line; l < end_line; l ++) { WDL_FastString *s = lines->Get(l); if (s && editor->is_code_start_line(s->Get())) { end_line = l; break; } } for (; start_line >= 0; start_line--) { WDL_FastString *s = lines->Get(start_line); if (s && editor->is_code_start_line(s->Get())) break; } if (start_line < 0) return; // before any code start_line++; } else { start_line = 0; } for (l=start_line;l<end_line;l++) { WDL_FastString *t = lines->Get(l); const int ll = t?t->GetLength():0; const char *start_p = t?t->Get():""; const char *p = start_p; const char *endp = start_p+ll; const char *tok; int last_state=state; int toklen; while (NULL != (tok=editor->sh_tokenize(&p,endp,&toklen,&state))||last_state) { if (last_state == '\'' || last_state == '"' || last_state==1) { const int sz=toklist->GetSize(); // update last token to include this data if (sz) toklist->Get()[sz-1].add_linecnt((int) ((tok ? p:endp) - start_p)); } else { if (tok) switch (tok[0]) { case '{': case '}': case '?': case ':': case ';': case '(': case '[': case ')': case ']': case '\'': case '"': case '/': // comment { eel_sh_token t(l,(int)(tok-start_p),toklen,tok[0]); toklist->Add(t); } break; } } last_state=0; } } } static bool eel_sh_get_matching_pos_for_pos(WDL_PtrList<WDL_FastString> *text, int curx, int cury, int *newx, int *newy, const char **errmsg, EEL_Editor *editor) { static WDL_TypedBuf<eel_sh_token> toklist; eel_sh_generate_token_list(text,&toklist, cury,editor); bool is_after; const int hit_tokidx = eel_sh_get_token_for_pos(&toklist, cury, curx, &is_after); const eel_sh_token *hit_tok = hit_tokidx >= 0 ? toklist.Get() + hit_tokidx : NULL; if (!is_after && hit_tok && (hit_tok->get_c() == '"' || hit_tok->get_c() == '\'' || hit_tok->is_comment())) { eel_sh_token tok = *hit_tok; // save a copy, toklist might get destroyed recursively here hit_tok = &tok; //if (tok.get_c() == '"') { // the user could be editing code in code, tokenize it and see if we can make sense of it WDL_FastString start, end; WDL_PtrList<WDL_FastString> tmplist; WDL_FastString *s = text->Get(tok.line); if (s && s->GetLength() > tok.col+1) { int maxl = tok.get_linecnt()>0 ? 0 : tok.end_col - tok.col - 2; start.Set(s->Get() + tok.col+1, maxl); } tmplist.Add(&start); const int linecnt = tok.get_linecnt(); if (linecnt>0) { for (int a=1; a < linecnt; a ++) { s = text->Get(tok.line + a); if (s) tmplist.Add(s); } s = text->Get(tok.line + linecnt); if (s) { if (tok.end_col>1) end.Set(s->Get(), tok.end_col-1); tmplist.Add(&end); } } int lx = curx, ly = cury - tok.line; if (cury == tok.line) lx -= (tok.col+1); // this will destroy the token if (eel_sh_get_matching_pos_for_pos(&tmplist, lx, ly, newx, newy, errmsg, editor)) { *newy += tok.line; if (cury == tok.line) *newx += tok.col + 1; return true; } } // if within a string or comment, move to start, unless already at start, move to end if (cury == hit_tok->line && curx == hit_tok->col) { *newx=hit_tok->end_col-1; *newy=hit_tok->line + hit_tok->get_linecnt(); } else { *newx=hit_tok->col; *newy=hit_tok->line; } return true; } if (!hit_tok) return false; const int toksz=toklist.GetSize(); int tokpos = hit_tokidx; int pc1=0,pc2=0; // (, [ count int pc3=0; // : or ? count depending on mode int dir=-1, mode=0; // default to scan to previous [( if (!is_after) { switch (hit_tok->get_c()) { case '(': mode=1; dir=1; break; case '[': mode=2; dir=1; break; case ')': mode=3; dir=-1; break; case ']': mode=4; dir=-1; break; case '?': mode=5; dir=1; break; case ':': mode=6; break; case ';': mode=7; break; } // if hit a token, exclude this token from scanning tokpos += dir; } while (tokpos>=0 && tokpos<toksz) { const eel_sh_token *tok = toklist.Get() + tokpos; const char this_c = tok->get_c(); if (!pc1 && !pc2) { bool match=false, want_abort=false; switch (mode) { case 0: match = this_c == '(' || this_c == '['; break; case 1: match = this_c == ')'; break; case 2: match = this_c == ']'; break; case 3: match = this_c == '('; break; case 4: match = this_c == '['; break; case 5: // scan forward to nearest : or ; if (this_c == '?') pc3++; else if (this_c == ':') { if (pc3>0) pc3--; else match=true; } else if (this_c == ';') match=true; else if (this_c == ')' || this_c == ']') { want_abort=true; // if you have "(x<y?z)", don't match for the ? } break; case 6: // scanning back from : to ?, if any case 7: // semicolon searches same as colon, effectively if (this_c == ':') pc3++; else if (this_c == '?') { if (pc3>0) pc3--; else match = true; } else if (this_c == ';' || this_c == '(' || this_c == '[') { want_abort=true; } break; } if (want_abort) break; if (match) { *newx=tok->col; *newy=tok->line; return true; } } switch (this_c) { case '[': pc2++; break; case ']': pc2--; break; case '(': pc1++; break; case ')': pc1--; break; } tokpos+=dir; } if (errmsg) { if (!mode) *errmsg = "Could not find previous [ or ("; else if (mode == 1) *errmsg = "Could not find matching )"; else if (mode == 2) *errmsg = "Could not find matching ]"; else if (mode == 3) *errmsg = "Could not find matching ("; else if (mode == 4) *errmsg = "Could not find matching ["; else if (mode == 5) *errmsg = "Could not find matching : or ; for ?"; else if (mode == 6) *errmsg = "Could not find matching ? for :"; else if (mode == 7) *errmsg = "Could not find matching ? for ;"; } return false; } void EEL_Editor::doParenMatching() { WDL_FastString *curstr; const char *errmsg = ""; if (NULL != (curstr=m_text.Get(m_curs_y))) { int bytex = WDL_utf8_charpos_to_bytepos(curstr->Get(),m_curs_x); if (bytex >= curstr->GetLength()) bytex=curstr->GetLength()-1; if (bytex<0) bytex = 0; int new_x,new_y; if (eel_sh_get_matching_pos_for_pos(&m_text, bytex,m_curs_y,&new_x,&new_y,&errmsg,this)) { curstr = m_text.Get(new_y); if (curstr) new_x = WDL_utf8_bytepos_to_charpos(curstr->Get(),new_x); m_curs_x=new_x; m_curs_y=new_y; m_want_x=-1; draw(); setCursor(1); } else if (errmsg[0]) { draw_message(errmsg); setCursor(0); } } } static int word_len(const char *p) { int l = 0; if (*p >= 'a' && *p <='z') { l++; // lowercase word while (p[l] && p[l] != '_' && p[l] != '.' && !(p[l] >= 'A' && p[l] <='Z')) l++; } else if (*p >= 'A' && *p <= 'Z') { if (!strcmp(p,"MIDI")) return 4; l++; if (p[l] >= 'A' && p[l] <='Z') // UPPERCASE word while (p[l] && p[l] != '_' && p[l] != '.' && !(p[l] >= 'a' && p[l] <='z')) l++; else // Titlecase word while (p[l] && p[l] != '_' && p[l] != '.' && !(p[l] >= 'A' && p[l] <='Z')) l++; } return l; } static int search_str_partial(const char *str, int reflen, const char *word, int wordlen) { // find the longest leading segment of word in str int best_len = 0; for (int y = 0; y < reflen; y ++) { while (y < reflen && !strnicmp(str+y,word,best_len+1)) { if (++best_len >= wordlen) return best_len; reflen--; } } return best_len; } static int fuzzy_match2(const char *codestr, int codelen, const char *refstr, int reflen) { // codestr is user-typed, refstr is the reference function name // our APIs are gfx_blah_blah or TrackBlahBlah so breaking the API up by words // and searching the user-entered code should be effective int lendiff = reflen - codelen; if (lendiff < 0) lendiff = -lendiff; const char *word = refstr; int score = 0; for (;;) { while (*word == '_' || *word == '.') word++; const int wordlen = word_len(word); if (!wordlen) break; char word_buf[128]; lstrcpyn_safe(word_buf,word,wordlen+1); if (WDL_stristr(refstr,word_buf)==word) { int max_match_len = search_str_partial(codestr,codelen,word,wordlen); if (max_match_len < 2 && wordlen == 5 && !strnicmp(word,"Count",5)) { max_match_len = search_str_partial(codestr,codelen,"Num",3); } if (max_match_len > (wordlen <= 2 ? 1 : 2)) score += max_match_len; } word += wordlen; } if (!score) return 0; return score * 1000 + 1000 - wdl_clamp(lendiff*2,0,200); } int EEL_Editor::fuzzy_match(const char *codestr, const char *refstr) { const int codestr_len = (int)strlen(codestr), refstr_len = (int)strlen(refstr); if (refstr_len >= codestr_len && !strnicmp(codestr,refstr,codestr_len)) return 1000000000; int score1 = fuzzy_match2(refstr,refstr_len,codestr,codestr_len); int score2 = fuzzy_match2(codestr,codestr_len,refstr,refstr_len); if (score2 > score1) return score2 | 1; return score1&~1; } static int eeledit_varenumfunc(const char *name, EEL_F *val, void *ctx) { void **parms = (void **)ctx; int score = ((EEL_Editor*)parms[2])->fuzzy_match((const char *)parms[1], name); if (score > 0) ((suggested_matchlist*)parms[0])->add(name,score,suggested_matchlist::MODE_VAR); return 1; } void EEL_Editor::get_suggested_token_names(const char *fname, int chkmask, suggested_matchlist *list) { int x; if (chkmask & (KEYWORD_MASK_BUILTIN_FUNC|KEYWORD_MASK_USER_VAR)) { peek_lock(); NSEEL_VMCTX vm = peek_get_VM(); compileContext *fvm = vm && peek_want_VM_funcs() ? (compileContext*)vm : NULL; if (chkmask&KEYWORD_MASK_BUILTIN_FUNC) for (x=0;;x++) { functionType *p = nseel_enumFunctions(fvm,x); if (!p) break; int score = fuzzy_match(fname,p->name); if (score>0) list->add(p->name,score); } if (vm && (chkmask&KEYWORD_MASK_USER_VAR)) { const void *parms[3] = { list, fname, this }; NSEEL_VM_enumallvars(vm, eeledit_varenumfunc, parms); } peek_unlock(); } if (chkmask & KEYWORD_MASK_USER_FUNC) { ensure_code_func_cache_valid(); for (int x=0;x< m_code_func_cache.GetSize();x++) { const char *k = m_code_func_cache.Get(x) + 4; if (WDL_NORMALLY(k)) { int score = fuzzy_match(fname,k); if (score > 0) list->add(k,score,suggested_matchlist::MODE_USERFUNC); } } } } int EEL_Editor::peek_get_token_info(const char *name, char *sstr, size_t sstr_sz, int chkmask, int ignoreline) { if (chkmask&KEYWORD_MASK_USER_FUNC) { ensure_code_func_cache_valid(); for (int i = 0; i < m_code_func_cache.GetSize(); i ++) { const char *cacheptr = m_code_func_cache.Get(i); const char *nameptr = cacheptr + sizeof(int); if (!(m_case_sensitive ? strcmp(nameptr, name):stricmp(nameptr,name)) && *(int *)cacheptr != ignoreline) { const char *parms = nameptr+strlen(nameptr)+1; const char *trail = parms+strlen(parms)+1; snprintf(sstr,sstr_sz,"%s%s%s%s",nameptr,parms,*trail?" " :"",trail); return 4; } } } if (chkmask & (KEYWORD_MASK_BUILTIN_FUNC|KEYWORD_MASK_USER_VAR)) { int rv = 0; peek_lock(); NSEEL_VMCTX vm = peek_want_VM_funcs() ? peek_get_VM() : NULL; functionType *f = (chkmask&KEYWORD_MASK_BUILTIN_FUNC) ? nseel_getFunctionByName((compileContext*)vm,name,NULL) : NULL; double v; if (f) { snprintf(sstr,sstr_sz,"'%s' is a function that requires %d parameters", f->name,f->nParams&0xff); rv = KEYWORD_MASK_BUILTIN_FUNC; } else if (chkmask & KEYWORD_MASK_USER_VAR) { if (!vm) vm = peek_get_VM(); EEL_F *vptr=NSEEL_VM_getvar(vm,name); if (vptr) { v = *vptr; rv = KEYWORD_MASK_USER_VAR; } } peek_unlock(); if (rv == KEYWORD_MASK_USER_VAR) { int good_len=-1; snprintf(sstr,sstr_sz,"%s=%.14f",name,v); if (v > -1.0 && v < NSEEL_RAM_ITEMSPERBLOCK*NSEEL_RAM_BLOCKS) { const unsigned int w = (unsigned int) (v+NSEEL_CLOSEFACTOR); EEL_F *dv = NSEEL_VM_getramptr_noalloc(vm,w,NULL); if (dv) { snprintf_append(sstr,sstr_sz," [0x%06x]=%.14f",w,*dv); good_len=-2; } else { good_len = strlen(sstr); snprintf_append(sstr,sstr_sz," [0x%06x]=<uninit>",w); } } char buf[512]; buf[0]=0; if (peek_get_numbered_string_value(v,buf,sizeof(buf))) { if (good_len==-2) snprintf_append(sstr,sstr_sz," %.0f(str)=%s",v,buf); else { if (good_len>=0) sstr[good_len]=0; // remove [addr]=<uninit> if a string and no ram snprintf_append(sstr,sstr_sz," (str)=%s",buf); } } } if (rv) return rv; } return 0; } void EEL_Editor::doWatchInfo(int c) { // determine the word we are on, check its value in the effect char sstr[512], buf[512]; lstrcpyn_safe(sstr,"Use this on a valid symbol name", sizeof(sstr)); WDL_FastString *t=m_text.Get(m_curs_y); char curChar=0; if (t) { const char *p=t->Get(); const int bytex = WDL_utf8_charpos_to_bytepos(p,m_curs_x); if (bytex >= 0 && bytex < t->GetLength()) curChar = p[bytex]; if (c != KEY_F1 && (m_selecting || curChar == '(' || curChar == '[' || curChar == ')' || curChar == ']' )) { WDL_FastString code; int miny,maxy,minx,maxx; bool ok = false; if (!m_selecting) { if (eel_sh_get_matching_pos_for_pos(&m_text,minx=m_curs_x,miny=m_curs_y,&maxx, &maxy,NULL,this)) { if (maxy==miny) { if (maxx < minx) { int tmp = minx; minx=maxx; maxx=tmp; } } else if (maxy < miny) { int tmp=maxy; maxy=miny; miny=tmp; tmp = minx; minx=maxx; maxx=tmp; } ok = true; minx++; // skip leading ( } } else { ok=true; getselectregion(minx,miny,maxx,maxy); WDL_FastString *s; s = m_text.Get(miny); if (s) minx = WDL_utf8_charpos_to_bytepos(s->Get(),minx); s = m_text.Get(maxy); if (s) maxx = WDL_utf8_charpos_to_bytepos(s->Get(),maxx); } if (ok) { int x; for (x = miny; x <= maxy; x ++) { WDL_FastString *s=m_text.Get(x); if (s) { const char *str=s->Get(); int sx,ex; if (x == miny) sx=wdl_max(minx,0); else sx=0; int tmp=s->GetLength(); if (sx > tmp) sx=tmp; if (x == maxy) ex=wdl_min(maxx,tmp); else ex=tmp; if (code.GetLength()) code.Append("\r\n"); code.Append(ex-sx?str+sx:"",ex-sx); } } } if (code.Get()[0]) { if (m_selecting && (GetAsyncKeyState(VK_SHIFT)&0x8000)) { peek_lock(); NSEEL_CODEHANDLE ch; NSEEL_VMCTX vm = peek_get_VM(); if (vm && (ch = NSEEL_code_compile_ex(vm,code.Get(),1,0))) { codeHandleType *p = (codeHandleType*)ch; code.Ellipsize(3,20); const char *errstr = "failed writing to"; if (p->code) { buf[0]=0; GetTempPath(sizeof(buf)-64,buf); lstrcatn(buf,"jsfx-out",sizeof(buf)); FILE *fp = fopen(buf,"wb"); if (fp) { errstr="wrote to"; fwrite(p->code,1,p->code_size,fp); fclose(fp); } } snprintf(sstr,sizeof(sstr),"Expression '%s' compiled to %d bytes, %s temp/jsfx-out",code.Get(),p->code_size, errstr); NSEEL_code_free(ch); } else { code.Ellipsize(3,20); snprintf(sstr,sizeof(sstr),"Expression '%s' could not compile",code.Get()); } peek_unlock(); } else { WDL_FastString code2; code2.Set("__debug_watch_value = ((((("); code2.Append(code.Get()); code2.Append(")))));"); peek_lock(); NSEEL_VMCTX vm = peek_get_VM(); EEL_F *vptr=NULL; double v=0.0; const char *err="Invalid context"; if (vm) { NSEEL_CODEHANDLE ch = NSEEL_code_compile_ex(vm,code2.Get(),1,0); if (!ch) err = "Error parsing"; else { NSEEL_code_execute(ch); NSEEL_code_free(ch); vptr = NSEEL_VM_getvar(vm,"__debug_watch_value"); if (vptr) v = *vptr; } } peek_unlock(); { // remove whitespace from code for display int x; bool lb=true; for (x=0;x<code.GetLength();x++) { if (isspace(code.Get()[x])) { if (lb) code.DeleteSub(x--,1); lb=true; } else { lb=false; } } if (lb && code.GetLength()>0) code.SetLen(code.GetLength()-1); } code.Ellipsize(3,20); if (vptr) { snprintf(sstr,sizeof(sstr),"Expression '%s' evaluates to %.14f",code.Get(),v); } else { snprintf(sstr,sizeof(sstr),"Error evaluating '%s': %s",code.Get(),err?err:"Unknown error"); } } } // compile+execute code within () as debug_watch_value = ( code ) // show value (or err msg) } else if (curChar>0 && (isalnum(curChar) || curChar == '_' || curChar == '.' || curChar == '#')) { const int bytex = WDL_utf8_charpos_to_bytepos(p,m_curs_x); const char *lp=p+bytex; const char *rp=lp + WDL_utf8_charpos_to_bytepos(lp,1); while (lp >= p && *lp > 0 && (isalnum(*lp) || *lp == '_' || (*lp == '.' && (lp==p || lp[-1]!='.')))) lp--; if (lp < p || *lp != '#') lp++; while (*rp && *rp > 0 && (isalnum(*rp) || *rp == '_' || (*rp == '.' && rp[1] != '.'))) rp++; if (*lp == '#' && rp > lp+1) { WDL_FastString n; lp++; n.Set(lp,(int)(rp-lp)); int idx; if ((idx=peek_get_named_string_value(n.Get(),buf,sizeof(buf)))>=0) snprintf(sstr,sizeof(sstr),"#%s(%d)=%s",n.Get(),idx,buf); else snprintf(sstr,sizeof(sstr),"#%s not found",n.Get()); } else if (*lp > 0 && (isalpha(*lp) || *lp == '_') && rp > lp) { WDL_FastString n; n.Set(lp,(int)(rp-lp)); if (c==KEY_F1) { if (m_suggestion.GetLength()) goto help_from_sug; on_help(n.Get(),0); return; } int f = peek_get_token_info(n.Get(),sstr,sizeof(sstr),~0,-1); if (!f) snprintf(sstr,sizeof(sstr),"'%s' NOT FOUND",n.Get()); } } } if (c==KEY_F1) { help_from_sug: WDL_FastString t; if (m_suggestion.GetLength()) { const char *p = m_suggestion.Get(); int l; for (l = 0; isalnum(p[l]) || p[l] == '_' || p[l] == '.'; l ++); if (l>0) t.Set(m_suggestion.Get(),l); } on_help(t.GetLength() > 2 ? t.Get() : NULL,(int)curChar); return; } setCursor(); draw_message(sstr); } void EEL_Editor::draw_bottom_line() { #define BOLD(x) { attrset(COLOR_BOTTOMLINE|A_BOLD); addstr(x); attrset(COLOR_BOTTOMLINE&~A_BOLD); } addstr("ma"); BOLD("T"); addstr("ch"); BOLD(" S"); addstr("ave"); if (peek_get_VM()) { addstr(" pee"); BOLD("K"); } if (GetTabCount()>1) { addstr(" | tab: "); BOLD("[], F?"); addstr("=switch "); BOLD("W"); addstr("=close"); } #undef BOLD } #define CTRL_KEY_DOWN (GetAsyncKeyState(VK_CONTROL)&0x8000) #define SHIFT_KEY_DOWN (GetAsyncKeyState(VK_SHIFT)&0x8000) #define ALT_KEY_DOWN (GetAsyncKeyState(VK_MENU)&0x8000) static const char *suggestion_help_text = "(up/down to select, tab to insert)"; static const char *suggestion_help_text2 = "(tab or return to insert)"; static LRESULT WINAPI suggestionProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { EEL_Editor *editor; switch (uMsg) { case WM_DESTROY: editor = (EEL_Editor *)GetWindowLongPtr(hwnd,GWLP_USERDATA); if (editor) editor->m_suggestion_hwnd = NULL; break; case WM_LBUTTONDOWN: case WM_MOUSEMOVE: editor = (EEL_Editor *)GetWindowLongPtr(hwnd,GWLP_USERDATA); if (editor) { win32CursesCtx *ctx = (win32CursesCtx *)editor->m_cursesCtx; if (ctx && ctx->m_font_h) { RECT r; GetClientRect(hwnd,&r); SetForegroundWindow(GetParent(hwnd)); SetFocus(GetParent(hwnd)); const int max_vis = r.bottom / ctx->m_font_h - 1, sel = editor->m_suggestion_hwnd_sel; int hit = GET_Y_LPARAM(lParam) / ctx->m_font_h; if (hit >= max_vis) return 0; if (sel >= max_vis) hit += 1 + sel - max_vis; if (uMsg == WM_LBUTTONDOWN && !SHIFT_KEY_DOWN && !ALT_KEY_DOWN && !CTRL_KEY_DOWN) { editor->m_suggestion_hwnd_sel = hit; editor->onChar('\t'); } else if (sel != hit) { editor->m_suggestion_hwnd_sel = hit; InvalidateRect(hwnd,NULL,FALSE); char sug[512]; sug[0]=0; const char *p = editor->m_suggestion_list.get(hit); if (p && editor->peek_get_token_info(p,sug,sizeof(sug),~0,-1)) { editor->m_suggestion.Set(sug); editor->draw_top_line(); editor->setCursor(); } } } } return 0; case WM_PAINT: editor = (EEL_Editor *)GetWindowLongPtr(hwnd,GWLP_USERDATA); if (editor) { PAINTSTRUCT ps; if (BeginPaint(hwnd,&ps)) { RECT r; GetClientRect(hwnd,&r); win32CursesCtx *ctx = (win32CursesCtx *)editor->m_cursesCtx; HBRUSH br = CreateSolidBrush(ctx->colortab[WDL_CursesEditor::COLOR_TOPLINE][1]); FillRect(ps.hdc,&r,br); DeleteObject(br); suggested_matchlist *ml = &editor->m_suggestion_list; HGDIOBJ oldObj = SelectObject(ps.hdc,ctx->mOurFont); SetBkMode(ps.hdc,TRANSPARENT); const int fonth = wdl_max(ctx->m_font_h,1); const int maxv = r.bottom / fonth - 1; const int selpos = wdl_max(editor->m_suggestion_hwnd_sel,0); int ypos = 0; const bool show_scores = (GetAsyncKeyState(VK_SHIFT)&0x8000) && (GetAsyncKeyState(VK_CONTROL)&0x8000) && (GetAsyncKeyState(VK_MENU)&0x8000); for (int x = (selpos >= maxv ? 1+selpos-maxv : 0); x < ml->get_size() && ypos <= r.bottom-fonth*2; x ++) { int mode, score; const char *p = ml->get(x,&mode,&score); if (WDL_NORMALLY(p)) { const bool sel = x == selpos; SetTextColor(ps.hdc,ctx->colortab[ (mode == suggested_matchlist::MODE_VAR ? WDL_CursesEditor::COLOR_TOPLINE : mode == suggested_matchlist::MODE_USERFUNC ? WDL_CursesEditor::SYNTAX_FUNC2 : mode == suggested_matchlist::MODE_REGVAR ? WDL_CursesEditor::SYNTAX_REGVAR : WDL_CursesEditor::SYNTAX_KEYWORD) | (sel ? A_BOLD:0)][0]); RECT tr = {4, ypos, r.right-4, ypos+fonth }; DrawTextUTF8(ps.hdc,p,-1,&tr,DT_SINGLELINE|DT_NOPREFIX|DT_TOP|DT_LEFT); if (show_scores) { char tmp[128]; snprintf(tmp,sizeof(tmp),"(%d)",score); DrawTextUTF8(ps.hdc,tmp,-1,&tr,DT_SINGLELINE|DT_NOPREFIX|DT_TOP|DT_RIGHT); } } ypos += fonth; } { const COLORREF mix = ((ctx->colortab[WDL_CursesEditor::COLOR_TOPLINE][1]&0xfefefe)>>1) + ((ctx->colortab[WDL_CursesEditor::COLOR_TOPLINE][0]&0xfefefe)>>1); SetTextColor(ps.hdc,mix); RECT tr = {4, r.bottom-fonth, r.right-4, r.bottom }; DrawTextUTF8(ps.hdc, editor->m_suggestion_hwnd_sel >= 0 ? suggestion_help_text2 : suggestion_help_text, -1,&tr,DT_SINGLELINE|DT_NOPREFIX|DT_TOP|DT_CENTER); } SelectObject(ps.hdc,oldObj); EndPaint(hwnd,&ps); } } return 0; } return DefWindowProc(hwnd,uMsg,wParam,lParam); } void EEL_Editor::open_import_line() { WDL_FastString *txtstr=m_text.Get(m_curs_y); const char *txt=txtstr?txtstr->Get():NULL; char fnp[2048]; if (txt && line_has_openable_file(txt,WDL_utf8_charpos_to_bytepos(txt,m_curs_x),fnp,sizeof(fnp))) { WDL_CursesEditor::OpenFileInTab(fnp); } } int EEL_Editor::onChar(int c) { if ((m_ui_state == UI_STATE_NORMAL || m_ui_state == UI_STATE_MESSAGE) && (c == 'K'-'A'+1 || c == 'S'-'A'+1 || c == 'R'-'A'+1 || !SHIFT_KEY_DOWN) && !ALT_KEY_DOWN) switch (c) { case KEY_F1: if (CTRL_KEY_DOWN) break; case 'K'-'A'+1: doWatchInfo(c); return 0; case 'S'-'A'+1: { WDL_DestroyCheck chk(&destroy_check); if(updateFile()) { if (chk.isOK()) draw_message("Error writing file, changes not saved!"); } if (chk.isOK()) setCursor(); } return 0; // case 'I': note stupidly we map Ctrl+I to VK_TAB, bleh case 'R'-'A'+1: if (!SHIFT_KEY_DOWN) break; if (!m_selecting) { open_import_line(); } return 0; case KEY_F4: case 'T'-'A'+1: doParenMatching(); return 0; } int rv = 0; int do_sug = (g_eel_editor_max_vis_suggestions > 0 && m_ui_state == UI_STATE_NORMAL && !m_selecting && m_top_margin > 0 && (c == 'L'-'A'+1 || (!CTRL_KEY_DOWN && !ALT_KEY_DOWN))) ? 1 : 0; bool did_fuzzy = false; char sug[1024]; sug[0]=0; if (do_sug) { if (m_suggestion_hwnd) { // insert if tab or shift+enter or (enter if arrow-navigated) if ((c == '\t' && !SHIFT_KEY_DOWN) || (c == '\r' && (m_suggestion_hwnd_sel>=0 || SHIFT_KEY_DOWN))) { char buf[512]; int sug_mode; const char *ptr = m_suggestion_list.get(wdl_max(m_suggestion_hwnd_sel,0), &sug_mode); lstrcpyn_safe(buf,ptr?ptr:"",sizeof(buf)); DestroyWindow(m_suggestion_hwnd); WDL_FastString *l=m_text.Get(m_curs_y); if (buf[0] && l && WDL_NORMALLY(m_suggestion_tokpos>=0 && m_suggestion_tokpos < l->GetLength()) && WDL_NORMALLY(m_suggestion_toklen>0) && WDL_NORMALLY(m_suggestion_tokpos+m_suggestion_toklen <= l->GetLength())) { preSaveUndoState(); l->DeleteSub(m_suggestion_tokpos,m_suggestion_toklen); l->Insert(buf,m_suggestion_tokpos); int pos = m_suggestion_tokpos + strlen(buf); if (sug_mode == suggested_matchlist::MODE_FUNC || sug_mode == suggested_matchlist::MODE_USERFUNC) { if (pos >= l->GetLength() || l->Get()[pos] != '(') l->Insert("(",pos++); } m_curs_x = WDL_utf8_bytepos_to_charpos(l->Get(),pos); draw(); saveUndoState(); setCursor(); goto run_suggest; } return 0; } if ((c == KEY_UP || c==KEY_DOWN || c == KEY_NPAGE || c == KEY_PPAGE) && !SHIFT_KEY_DOWN) { m_suggestion_hwnd_sel = wdl_max(m_suggestion_hwnd_sel,0) + (c==KEY_UP ? -1 : c==KEY_DOWN ? 1 : c==KEY_NPAGE ? 4 : -4); if (m_suggestion_hwnd_sel >= m_suggestion_list.get_size()) m_suggestion_hwnd_sel = m_suggestion_list.get_size()-1; if (m_suggestion_hwnd_sel < 0) m_suggestion_hwnd_sel=0; InvalidateRect(m_suggestion_hwnd,NULL,FALSE); const char *p = m_suggestion_list.get(m_suggestion_hwnd_sel); if (p) peek_get_token_info(p,sug,sizeof(sug),~0,m_curs_y); goto finish_sug; } } if (c==27 || c=='L'-'A'+1 || c=='\r' || c=='\t' || (c>=KEY_DOWN && c<= KEY_F12 && c!=KEY_DC)) do_sug = 2; // no fuzzy window else if (c=='\b' && !m_suggestion_hwnd) do_sug=2; // backspace will update but won't show suggestions } rv = WDL_CursesEditor::onChar(c); run_suggest: if (do_sug) { WDL_FastString *l=m_text.Get(m_curs_y); if (l) { const int MAX_TOK=512; struct { const char *tok; int toklen; } token_list[MAX_TOK]; const char *cursor = l->Get() + WDL_utf8_charpos_to_bytepos(l->Get(),m_curs_x); int ntok = 0; { const char *p = l->Get(), *endp = p + l->GetLength(); int state = m_suggestion_curline_comment_state, toklen = 0, bcnt = 0, pcnt = 0; const char *tok; // if no parens/brackets are open, use a peekable token that starts at cursor while ((tok=sh_tokenize(&p,endp,&toklen,&state)) && cursor > tok-(!pcnt && !bcnt && (tok[0] < 0 || tok[0] == '_' || isalpha(tok[0])))) { if (!state) { if (WDL_NOT_NORMALLY(ntok >= MAX_TOK)) { memmove(token_list,token_list+1,sizeof(token_list) - sizeof(token_list[0])); ntok--; } switch (*tok) { case '[': bcnt++; break; case ']': bcnt--; break; case '(': pcnt++; break; case ')': pcnt--; break; } token_list[ntok].tok = tok; token_list[ntok].toklen = toklen; ntok++; } } } int t = ntok; int comma_cnt = 0; while (--t >= 0) { const char *tok = token_list[t].tok; int toklen = token_list[t].toklen; const int lc = tok[0], ac = lc==')' ? '(' : lc==']' ? '[' : 0; if (ac) { int cnt=1; while (--t>=0) { const int c = token_list[t].tok[0]; if (c == lc) cnt++; else if (c == ac && !--cnt) break; } if (t > 0) { const int c = token_list[t-1].tok[0]; if (c != ',' && c != ')' && c != ']') t--; continue; } } if (t<0) break; if (tok[0] == ',') comma_cnt++; else if ((tok[0] < 0 || tok[0] == '_' || isalpha(tok[0])) && (cursor <= tok + toklen || (t < ntok-1 && token_list[t+1].tok[0] == '('))) { // if cursor is within or at end of token, or is a function (followed by open-paren) char buf[512]; lstrcpyn_safe(buf,tok,wdl_min(toklen+1, sizeof(buf))); if (peek_get_token_info(buf,sug,sizeof(sug),~0,m_curs_y)) { if (comma_cnt > 0) { // hide previous parameters from sug's parameter fields so we know which parameters // we are (hopefully on) char *pstart = sug; while (*pstart && *pstart != '(') pstart++; if (*pstart == '(') pstart++; int comma_pos = 0; char *p = pstart; while (comma_pos < comma_cnt) { while (*p == ' ') p++; while (*p && *p != ',' && *p != ')') p++; if (*p == ')') break; if (*p) p++; comma_pos++; } if (*p && *p != ')') { *pstart=0; lstrcpyn_safe(buf,p,sizeof(buf)); snprintf_append(sug,sizeof(sug), "... %s",buf); } } break; } // only use token up to cursor for suggestions if (cursor >= tok && cursor <= tok+toklen) { toklen = (int) (cursor-tok); lstrcpyn_safe(buf,tok,wdl_min(toklen+1, sizeof(buf))); } if (c == '\b' && cursor == tok) { } else if (do_sug != 2 && t == ntok-1 && toklen >= 3 && cursor <= tok + toklen) { m_suggestion_list.clear(); get_suggested_token_names(buf,~0,&m_suggestion_list); win32CursesCtx *ctx = (win32CursesCtx *)m_cursesCtx; if (m_suggestion_list.get_size()>0 && WDL_NORMALLY(ctx->m_hwnd) && WDL_NORMALLY(ctx->m_font_w) && WDL_NORMALLY(ctx->m_font_h)) { m_suggestion_toklen = toklen; m_suggestion_tokpos = (int)(tok-l->Get()); m_suggestion_hwnd_sel = -1; if (!m_suggestion_hwnd) { #ifdef _WIN32 static HINSTANCE last_inst; const char *classname = "eel_edit_predicto"; HINSTANCE inst = (HINSTANCE)GetWindowLongPtr(ctx->m_hwnd,GWLP_HINSTANCE); if (inst != last_inst) { last_inst = inst; WNDCLASS wc={CS_DBLCLKS,suggestionProc,}; wc.lpszClassName=classname; wc.hInstance=inst; wc.hCursor=LoadCursor(NULL,IDC_ARROW); RegisterClass(&wc); } m_suggestion_hwnd = CreateWindowEx(0,classname,"", WS_CHILD, 0,0,0,0, ctx->m_hwnd, NULL, inst, NULL); #else m_suggestion_hwnd = CreateDialogParam(NULL,NULL,ctx->m_hwnd, suggestionProc, 0); #endif if (m_suggestion_hwnd) SetWindowLongPtr(m_suggestion_hwnd,GWLP_USERDATA,(LPARAM)this); } if (m_suggestion_hwnd) { const int fontw = ctx->m_font_w, fonth = ctx->m_font_h; int xpos = (WDL_utf8_bytepos_to_charpos(l->Get(),m_suggestion_tokpos) - m_offs_x) * fontw; RECT par_cr; GetClientRect(ctx->m_hwnd,&par_cr); int use_w = (int)strlen(suggestion_help_text); int use_h = (wdl_min(g_eel_editor_max_vis_suggestions,m_suggestion_list.get_size()) + 1)*fonth; for (int x = 0; x < m_suggestion_list.get_size(); x ++) { const char *p = m_suggestion_list.get(x); if (WDL_NORMALLY(p!=NULL)) { const int l = (int) strlen(p); if (l > use_w) use_w=l; } } use_w = 8 + use_w * fontw; if (use_w > par_cr.right - xpos) { xpos = wdl_max(par_cr.right - use_w,0); use_w = par_cr.right - xpos; } const int cursor_line_y = ctx->m_cursor_y * fonth; int ypos = cursor_line_y + fonth; if (ypos + use_h > par_cr.bottom) { if (cursor_line_y-fonth > par_cr.bottom - ypos) { // more room at the top, but enough? ypos = cursor_line_y - use_h; if (ypos<fonth) { ypos = fonth; use_h = cursor_line_y-fonth; } } else use_h = par_cr.bottom - ypos; } SetWindowPos(m_suggestion_hwnd,NULL,xpos,ypos,use_w,use_h, SWP_NOZORDER|SWP_NOACTIVATE); InvalidateRect(m_suggestion_hwnd,NULL,FALSE); ShowWindow(m_suggestion_hwnd,SW_SHOWNA); } did_fuzzy = true; const char *p = m_suggestion_list.get(wdl_max(m_suggestion_hwnd_sel,0)); if (p && peek_get_token_info(p,sug,sizeof(sug),~0,m_curs_y)) break; } } } } } } if (!did_fuzzy && m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd); finish_sug: if (strcmp(sug,m_suggestion.Get()) && m_ui_state == UI_STATE_NORMAL) { m_suggestion.Set(sug); if (sug[0]) { m_suggestion_x=m_curs_x; m_suggestion_y=m_curs_y; draw_top_line(); setCursor(); } } if (!sug[0] && m_suggestion_y>=0 && m_ui_state == UI_STATE_NORMAL) { m_suggestion_x=m_suggestion_y=-1; m_suggestion.Set(""); if (m_top_margin>0) draw_top_line(); else draw(); setCursor(); } return rv; } void EEL_Editor::draw_top_line() { if (m_curs_x >= m_suggestion_x && m_curs_y == m_suggestion_y && m_suggestion.GetLength() && m_ui_state == UI_STATE_NORMAL) { const char *p=m_suggestion.Get(); char str[512]; if (WDL_utf8_get_charlen(m_suggestion.Get()) > COLS) { int l = WDL_utf8_charpos_to_bytepos(m_suggestion.Get(),COLS-4); if (l > sizeof(str)-6) l = sizeof(str)-6; lstrcpyn(str, m_suggestion.Get(), l+1); strcat(str, "..."); p=str; } attrset(COLOR_TOPLINE|A_BOLD); bkgdset(COLOR_TOPLINE); move(0, 0); addstr(p); clrtoeol(); attrset(0); bkgdset(0); } else { m_suggestion_x=m_suggestion_y=-1; if (m_suggestion.GetLength()) m_suggestion.Set(""); WDL_CursesEditor::draw_top_line(); } } void EEL_Editor::onRightClick(HWND hwnd) { WDL_LogicalSortStringKeyedArray<int> flist(m_case_sensitive); int i; if (!(GetAsyncKeyState(VK_CONTROL)&0x8000)) { m_code_func_cache_lines = -1; // invalidate cache ensure_code_func_cache_valid(); for (i = 0; i < m_code_func_cache.GetSize(); i ++) { const char *p = m_code_func_cache.Get(i); const int line = *(int *)p; p += sizeof(int); const char *q = p+strlen(p)+1; char buf[512]; snprintf(buf,sizeof(buf),"%s%s",p,q); flist.AddUnsorted(buf,line); p += 4; } } if (flist.GetSize()) { flist.Resort(); if (m_case_sensitive) flist.Resort(WDL_LogicalSortStringKeyedArray<int>::cmpistr); HMENU hm=CreatePopupMenu(); int pos=0; for (i=0; i < flist.GetSize(); ++i) { const char* fname=NULL; int line=flist.Enumerate(i, &fname); InsertMenu(hm, pos++, MF_STRING|MF_BYPOSITION, line+1, fname); } POINT p; GetCursorPos(&p); int ret=TrackPopupMenu(hm, TPM_NONOTIFY|TPM_RETURNCMD, p.x, p.y, 0, hwnd, NULL); DestroyMenu(hm); if (ret > 0) { GoToLine(ret-1,true); } } else { doWatchInfo(0); } } void EEL_Editor::ensure_code_func_cache_valid() { const char *prefix = m_function_prefix; if (!prefix || !*prefix) return; const DWORD now = GetTickCount(); if (m_text.GetSize()==m_code_func_cache_lines && (now-m_code_func_cache_time)<5000) return; m_code_func_cache_lines = m_text.GetSize(); m_code_func_cache_time = now; m_code_func_cache.Empty(true,free); const int prefix_len = (int) strlen(m_function_prefix); for (int i=0; i < m_text.GetSize(); ++i) { WDL_FastString* s=m_text.Get(i); if (WDL_NORMALLY(s)) { const char *p = s->Get(); while (*p) { if (m_case_sensitive ? !strncmp(p,prefix,prefix_len) : !strnicmp(p,prefix,prefix_len)) { p+=prefix_len; while (*p == ' ') p++; if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || *p == '_') { const char *q = p+1; while ((*q >= '0' && *q <= '9') || (*q >= 'a' && *q <= 'z') || (*q >= 'A' && *q <= 'Z') || *q == ':' || // lua *q == '_' || *q == '.') q++; const char *endp = q; while (*q == ' ') q++; if (*q == '(') { const char *endq = q; while (*endq && *endq != ')') endq++; if (*endq) endq++; const char *r = endq; while (*r == ' ') r++; const int p_len = (int) (endp - p); const int q_len = (int) (endq - q); const int r_len = (int) strlen(r); // add function char *v = (char *)malloc(sizeof(int) + p_len + q_len + r_len + 3), *wr = v; if (WDL_NORMALLY(v)) { *(int *)wr = i; wr += sizeof(int); lstrcpyn_safe(wr,p,p_len+1); wr += p_len+1; lstrcpyn_safe(wr,q,q_len+1); wr += q_len+1; lstrcpyn_safe(wr,r,r_len+1); wr += r_len+1; m_code_func_cache.Add(v); } p = r; // continue parsing after parentheses } } } if (*p) p++; } } } } #ifdef WDL_IS_FAKE_CURSES LRESULT EEL_Editor::onMouseMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_LBUTTONDBLCLK: if (m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd); if (CURSES_INSTANCE && CURSES_INSTANCE->m_font_w && CURSES_INSTANCE->m_font_h) { const int y = ((short)HIWORD(lParam)) / CURSES_INSTANCE->m_font_h - m_top_margin; //const int x = ((short)LOWORD(lParam)) / CURSES_INSTANCE->m_font_w + m_offs_x; WDL_FastString *fs=m_text.Get(y + m_paneoffs_y[m_curpane]); if (fs && y >= 0) { if (!strncmp(fs->Get(),"import",6) && isspace(fs->Get()[6])) { open_import_line(); return 1; } } // ctrl+doubleclicking a function goes to it if (CTRL_KEY_DOWN) { WDL_FastString *l=m_text.Get(m_curs_y); if (l) { const char *p = l->Get(), *endp = p + l->GetLength(), *cursor = p + WDL_utf8_charpos_to_bytepos(p,m_curs_x); int state = 0, toklen = 0; const char *tok; while ((tok=sh_tokenize(&p,endp,&toklen,&state)) && cursor > tok+toklen); if (tok && cursor <= tok+toklen) { ensure_code_func_cache_valid(); while (toklen > 0) { for (int i = 0; i < m_code_func_cache.GetSize(); i ++) { const char *p = m_code_func_cache.Get(i); int line = *(int *)p; p+=sizeof(int); if (line != m_curs_y && strlen(p) == toklen && (m_case_sensitive ? !strncmp(p,tok,toklen) : !strnicmp(p,tok,toklen))) { GoToLine(line,true); return 0; } } // try removing any foo. prefixes while (toklen > 0 && *tok != '.') { tok++; toklen--; } tok++; toklen--; } } } } } break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: if (m_suggestion_hwnd) DestroyWindow(m_suggestion_hwnd); break; } return WDL_CursesEditor::onMouseMessage(hwnd,uMsg,wParam,lParam); } #endif
29.657757
161
0.530362
badi91
d51daa9e1e70d6408cdfb4d7a4b61f0e565ff340
29,952
cc
C++
modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.cc
IsaacZhang123/apollo
174d17df316a0c30fdeb38c87deb9293791e0f5f
[ "Apache-2.0" ]
2
2021-01-19T02:27:59.000Z
2021-08-18T06:56:32.000Z
modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.cc
IsaacZhang123/apollo
174d17df316a0c30fdeb38c87deb9293791e0f5f
[ "Apache-2.0" ]
null
null
null
modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.cc
IsaacZhang123/apollo
174d17df316a0c30fdeb38c87deb9293791e0f5f
[ "Apache-2.0" ]
1
2020-06-22T12:46:39.000Z
2020-06-22T12:46:39.000Z
/* Copyright 2017 The Apollo Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #include "modules/map/hdmap/adapter/xml_parser/lanes_xml_parser.h" #include "modules/map/hdmap/adapter/xml_parser/util_xml_parser.h" namespace { double ToMPS(double speed) { return speed * 1000.0 / 3600.0; } bool IsReferenceLane(int lane_id) { return lane_id == 0; } }; // namespace namespace apollo { namespace hdmap { namespace adapter { Status LanesXmlParser::Parse(const tinyxml2::XMLElement& xml_node, const std::string& road_id, std::vector<RoadSectionInternal>* sections) { CHECK_NOTNULL(sections); const auto lanes_node = xml_node.FirstChildElement("lanes"); CHECK_NOTNULL(lanes_node); const tinyxml2::XMLElement* sub_node = lanes_node->FirstChildElement("laneSection"); CHECK_NOTNULL(sub_node); size_t section_cnt = 0; while (sub_node) { RoadSectionInternal section_internal; std::string section_id = std::to_string(++section_cnt); section_internal.id = section_id; section_internal.section.mutable_id()->set_id(section_id); RETURN_IF_ERROR(ParseLaneSection(*sub_node, &section_internal.lanes)); RETURN_IF_ERROR(ParseSectionBoundary( *sub_node, section_internal.section.mutable_boundary()->mutable_outer_polygon())); sections->push_back(section_internal); sub_node = sub_node->NextSiblingElement("laneSection"); } CHECK_GT(sections->size(), 0); return Status::OK(); } Status LanesXmlParser::ParseSectionBoundary( const tinyxml2::XMLElement& xml_node, PbBoundaryPolygon* boundary) { CHECK_NOTNULL(boundary); auto boundaries_node = xml_node.FirstChildElement("boundaries"); if (boundaries_node == nullptr) { std::string err_msg = "Error parse boundaries"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } auto sub_node = boundaries_node->FirstChildElement("boundary"); while (sub_node) { PbBoundaryEdge* boundary_edge = boundary->add_edge(); RETURN_IF_ERROR( UtilXmlParser::ParseCurve(*sub_node, boundary_edge->mutable_curve())); std::string type; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "type", &type); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse boundary type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbBoundaryEdgeType boundary_type; RETURN_IF_ERROR(ToPbBoundaryType(type, &boundary_type)); boundary_edge->set_type(boundary_type); sub_node = sub_node->NextSiblingElement("boundary"); } return Status::OK(); } Status LanesXmlParser::ToPbBoundaryType(const std::string& type, PbBoundaryEdgeType* boundary_type) { CHECK_NOTNULL(boundary_type); std::string upper_type = UtilXmlParser::ToUpper(type); if (upper_type == "LEFTBOUNDARY") { *boundary_type = hdmap::BoundaryEdge::LEFT_BOUNDARY; } else if (upper_type == "RIGHTBOUNDARY") { *boundary_type = hdmap::BoundaryEdge::RIGHT_BOUNDARY; } else { *boundary_type = hdmap::BoundaryEdge::NORMAL; } return Status::OK(); } Status LanesXmlParser::ParseLaneSection(const tinyxml2::XMLElement& xml_node, std::vector<LaneInternal>* lanes) { CHECK_NOTNULL(lanes); // left const tinyxml2::XMLElement* sub_node = xml_node.FirstChildElement("left"); if (sub_node) { sub_node = sub_node->FirstChildElement("lane"); while (sub_node) { LaneInternal lane_internal; RETURN_IF_ERROR(ParseLane(*sub_node, &lane_internal)); *(lane_internal.lane.mutable_left_boundary()) = lane_internal.lane.right_boundary(); lane_internal.lane.clear_right_boundary(); if (lanes->size() > 0) { PbLane& left_neighbor_lane = lanes->back().lane; *(left_neighbor_lane.mutable_right_boundary()) = lane_internal.lane.left_boundary(); } lanes->push_back(lane_internal); sub_node = sub_node->NextSiblingElement("lane"); } } // center LaneInternal reference_lane_internal; sub_node = xml_node.FirstChildElement("center"); CHECK_NOTNULL(sub_node); sub_node = sub_node->FirstChildElement("lane"); CHECK_NOTNULL(sub_node); RETURN_IF_ERROR(ParseLane(*sub_node, &reference_lane_internal)); *(reference_lane_internal.lane.mutable_left_boundary()) = reference_lane_internal.lane.right_boundary(); if (lanes->size() > 0) { PbLane& left_neighbor_lane = lanes->back().lane; *(left_neighbor_lane.mutable_right_boundary()) = reference_lane_internal.lane.left_boundary(); } // right sub_node = xml_node.FirstChildElement("right"); if (sub_node) { sub_node = sub_node->FirstChildElement("lane"); PbLane* left_neighbor_lane = &reference_lane_internal.lane; while (sub_node) { // PbLane lane LaneInternal lane_internal; RETURN_IF_ERROR(ParseLane(*sub_node, &lane_internal)); *(lane_internal.lane.mutable_left_boundary()) = left_neighbor_lane->right_boundary(); lanes->push_back(lane_internal); left_neighbor_lane = &lanes->back().lane; sub_node = sub_node->NextSiblingElement("lane"); } } return Status::OK(); } Status LanesXmlParser::ParseLane(const tinyxml2::XMLElement& xml_node, LaneInternal* lane_internal) { CHECK_NOTNULL(lane_internal); PbLane* lane = &lane_internal->lane; // lane id int id = 0; int checker = xml_node.QueryIntAttribute("id", &id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane id"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } std::string lane_id; checker = UtilXmlParser::QueryStringAttribute(xml_node, "uid", &lane_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane uid"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane->mutable_id()->set_id(lane_id); // lane type std::string lane_type; checker = UtilXmlParser::QueryStringAttribute(xml_node, "type", &lane_type); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbLaneType pb_lane_type; Status success = ToPbLaneType(lane_type, &pb_lane_type); if (!success.ok()) { std::string err_msg = "Error convert lane type to pb lane type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane->set_type(pb_lane_type); // border const tinyxml2::XMLElement* sub_node = xml_node.FirstChildElement("border"); if (sub_node) { PbLaneBoundary* lane_boundary = lane->mutable_right_boundary(); CHECK(lane_boundary != nullptr); success = UtilXmlParser::ParseCurve(*sub_node, lane_boundary->mutable_curve()); if (!success.ok()) { std::string err_msg = "Error parse lane border"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane_boundary->set_length( UtilXmlParser::CurveLength(*lane_boundary->mutable_curve())); bool is_virtual = false; std::string virtual_border = "FALSE"; checker = UtilXmlParser::QueryStringAttribute(*sub_node, "virtual", &virtual_border); if (checker == tinyxml2::XML_SUCCESS) { if (virtual_border == "TRUE") { is_virtual = true; } } lane_boundary->set_virtual_(is_virtual); } // road mark if (sub_node) { sub_node = sub_node->FirstChildElement("borderType"); } while (sub_node) { PbLaneBoundary* lane_boundary = lane->mutable_right_boundary(); PbLaneBoundaryTypeType boundary_type; success = ParseLaneBorderMark(*sub_node, &boundary_type); if (!success.ok()) { std::string err_msg = "Error parse lane border type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } double s_offset = 0.0; checker = sub_node->QueryDoubleAttribute("sOffset", &s_offset); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane boundary type offset."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } auto lane_boundary_type = lane_boundary->add_boundary_type(); lane_boundary_type->set_s(s_offset); lane_boundary_type->add_types(boundary_type); sub_node = sub_node->NextSiblingElement("borderType"); } // reference line if (IsReferenceLane(id)) { return Status::OK(); } // turn type std::string turn_type; checker = UtilXmlParser::QueryStringAttribute(xml_node, "turnType", &turn_type); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane turn type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbTurnType pb_turn_type; success = ToPbTurnType(turn_type, &pb_turn_type); if (!success.ok()) { std::string err_msg = "Error convert turn type to pb turn type."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane->set_turn(pb_turn_type); // direction RETURN_IF_ERROR(ParseDirection(xml_node, lane)); // link sub_node = xml_node.FirstChildElement("link"); if (sub_node) { ParseLaneLink(*sub_node, lane); } // center curve RETURN_IF_ERROR(ParseCenterCurve(xml_node, lane)); // speed RETURN_IF_ERROR(ParseSpeed(xml_node, lane)); // sample association RETURN_IF_ERROR(ParseSampleAssociates(xml_node, lane)); // road sample association RETURN_IF_ERROR(ParseRoadSampleAssociates(xml_node, lane)); // overlap object ParseObjectOverlapGroup(xml_node, &lane_internal->overlap_objects); // overlap signal ParseSignalOverlapGroup(xml_node, &lane_internal->overlap_signals); // overlap junction ParseJunctionOverlapGroup(xml_node, &lane_internal->overlap_junctions); // overlap lane ParseLaneOverlapGroup(xml_node, &lane_internal->overlap_lanes); return Status::OK(); } Status LanesXmlParser::ParseDirection(const tinyxml2::XMLElement& xml_node, PbLane* lane) { CHECK_NOTNULL(lane); std::string direction; int checker = UtilXmlParser::QueryStringAttribute(xml_node, "direction", &direction); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane direction."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbLaneDirection pb_lane_direction; Status success = ToPbDirection(direction, &pb_lane_direction); if (!success.ok()) { std::string err_msg = "Error convert direction to pb direction"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane->set_direction(pb_lane_direction); return Status::OK(); } Status LanesXmlParser::ParseCenterCurve(const tinyxml2::XMLElement& xml_node, PbLane* lane) { CHECK_NOTNULL(lane); auto sub_node = xml_node.FirstChildElement("centerLine"); if (!sub_node) { std::string err_msg = "Error parse lane center curve"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } PbCurve* center_curve = lane->mutable_central_curve(); Status success = UtilXmlParser::ParseCurve(*sub_node, center_curve); if (!success.ok()) { std::string err_msg = "Error parse lane center curve"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane->set_length(UtilXmlParser::CurveLength(*center_curve)); return Status::OK(); } Status LanesXmlParser::ParseSpeed(const tinyxml2::XMLElement& xml_node, PbLane* lane) { double max_speed = 0.0; auto sub_node = xml_node.FirstChildElement("speed"); if (sub_node) { int checker = sub_node->QueryDoubleAttribute("max", &max_speed); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane speed attribute"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } lane->set_speed_limit(ToMPS(max_speed)); } return Status::OK(); } Status LanesXmlParser::ParseSampleAssociates( const tinyxml2::XMLElement& xml_node, PbLane* lane) { CHECK_NOTNULL(lane); auto sub_node = xml_node.FirstChildElement("sampleAssociates"); if (sub_node == nullptr) { std::string err_msg = "Error parse sample associates"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } sub_node = sub_node->FirstChildElement("sampleAssociate"); if (sub_node == nullptr) { std::string err_msg = "Error parse sample associate"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } while (sub_node) { double left_width = 0.0; double right_width = 0.0; double s = 0.0; int checker = sub_node->QueryDoubleAttribute("sOffset", &s); checker += sub_node->QueryDoubleAttribute("leftWidth", &left_width); checker += sub_node->QueryDoubleAttribute("rightWidth", &right_width); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane sample associate attribute"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } auto left_sample = lane->add_left_sample(); left_sample->set_s(s); left_sample->set_width(left_width); auto right_sample = lane->add_right_sample(); right_sample->set_s(s); right_sample->set_width(right_width); sub_node = sub_node->NextSiblingElement("sampleAssociate"); } return Status::OK(); } Status LanesXmlParser::ParseRoadSampleAssociates( const tinyxml2::XMLElement& xml_node, PbLane* lane) { CHECK_NOTNULL(lane); auto sub_node = xml_node.FirstChildElement("roadSampleAssociations"); if (sub_node == nullptr) { std::string err_msg = "Error parse road sample associations"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } sub_node = sub_node->FirstChildElement("sampleAssociation"); if (sub_node == nullptr) { std::string err_msg = "Error parse road sample association"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } while (sub_node) { double left_width = 0.0; double right_width = 0.0; double s = 0.0; int checker = sub_node->QueryDoubleAttribute("sOffset", &s); checker += sub_node->QueryDoubleAttribute("leftWidth", &left_width); checker += sub_node->QueryDoubleAttribute("rightWidth", &right_width); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse road sample association attribute"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } auto left_road_sample = lane->add_left_road_sample(); left_road_sample->set_s(s); left_road_sample->set_width(left_width); auto right_road_sample = lane->add_right_road_sample(); right_road_sample->set_s(s); right_road_sample->set_width(right_width); sub_node = sub_node->NextSiblingElement("sampleAssociation"); } return Status::OK(); } Status LanesXmlParser::ParseObjectOverlapGroup( const tinyxml2::XMLElement& xml_node, std::vector<OverlapWithLane>* object_overlaps) { CHECK_NOTNULL(object_overlaps); auto object_overlap = xml_node.FirstChildElement("objectOverlapGroup"); if (object_overlap) { auto sub_node = object_overlap->FirstChildElement("objectReference"); while (sub_node) { std::string object_id; double start_s = 0.0; double end_s = 0.0; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &object_id); checker += sub_node->QueryDoubleAttribute("startOffset", &start_s); checker += sub_node->QueryDoubleAttribute("endOffset", &end_s); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane object overlap"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } bool is_merge = false; checker = sub_node->QueryBoolAttribute("isMerge", &is_merge); if (checker != tinyxml2::XML_SUCCESS) { is_merge = false; } OverlapWithLane overlap_with_lane; overlap_with_lane.object_id = object_id; overlap_with_lane.start_s = start_s; overlap_with_lane.end_s = end_s; overlap_with_lane.is_merge = is_merge; RETURN_IF_ERROR( ParseRegionOverlap(*sub_node, &overlap_with_lane.region_overlaps)); if (overlap_with_lane.region_overlaps.size() > 0) { UtilXmlParser::QueryStringAttribute( *sub_node, "regionOverlapId", &overlap_with_lane.region_overlap_id); } object_overlaps->push_back(overlap_with_lane); sub_node = sub_node->NextSiblingElement("objectReference"); } } return Status::OK(); } Status LanesXmlParser::ParseSignalOverlapGroup( const tinyxml2::XMLElement& xml_node, std::vector<OverlapWithLane>* signal_overlaps) { CHECK_NOTNULL(signal_overlaps); auto signal_overlap = xml_node.FirstChildElement("signalOverlapGroup"); if (signal_overlap) { auto sub_node = signal_overlap->FirstChildElement("signalReference"); while (sub_node) { std::string object_id; double start_s = 0.0; double end_s = 0.0; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &object_id); checker += sub_node->QueryDoubleAttribute("startOffset", &start_s); checker += sub_node->QueryDoubleAttribute("endOffset", &end_s); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane signal overlap"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } bool is_merge = false; checker = sub_node->QueryBoolAttribute("isMerge", &is_merge); if (checker != tinyxml2::XML_SUCCESS) { is_merge = false; } OverlapWithLane overlap_with_lane; overlap_with_lane.object_id = object_id; overlap_with_lane.start_s = start_s; overlap_with_lane.end_s = end_s; overlap_with_lane.is_merge = is_merge; signal_overlaps->push_back(overlap_with_lane); sub_node = sub_node->NextSiblingElement("signalReference"); } } return Status::OK(); } Status LanesXmlParser::ParseJunctionOverlapGroup( const tinyxml2::XMLElement& xml_node, std::vector<OverlapWithLane>* junction_overlaps) { CHECK_NOTNULL(junction_overlaps); auto overlap_group = xml_node.FirstChildElement("junctionOverlapGroup"); if (overlap_group) { auto sub_node = overlap_group->FirstChildElement("junctionReference"); while (sub_node) { std::string object_id; double start_s = 0.0; double end_s = 0.0; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &object_id); checker += sub_node->QueryDoubleAttribute("startOffset", &start_s); checker += sub_node->QueryDoubleAttribute("endOffset", &end_s); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane junction overlap"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } bool is_merge = false; checker = sub_node->QueryBoolAttribute("isMerge", &is_merge); if (checker != tinyxml2::XML_SUCCESS) { is_merge = false; } OverlapWithLane overlap_with_lane; overlap_with_lane.object_id = object_id; overlap_with_lane.start_s = start_s; overlap_with_lane.end_s = end_s; overlap_with_lane.is_merge = is_merge; junction_overlaps->push_back(overlap_with_lane); sub_node = sub_node->NextSiblingElement("junctionReference"); } } return Status::OK(); } Status LanesXmlParser::ParseLaneOverlapGroup( const tinyxml2::XMLElement& xml_node, std::vector<OverlapWithLane>* lane_overlaps) { CHECK_NOTNULL(lane_overlaps); auto overlap_node = xml_node.FirstChildElement("laneOverlapGroup"); if (overlap_node) { auto sub_node = overlap_node->FirstChildElement("laneReference"); while (sub_node) { std::string lane_id; double start_s = 0.0; double end_s = 0.0; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id); checker += sub_node->QueryDoubleAttribute("startOffset", &start_s); checker += sub_node->QueryDoubleAttribute("endOffset", &end_s); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error parse lane lane overlap"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } bool is_merge = false; checker = sub_node->QueryBoolAttribute("isMerge", &is_merge); if (checker != tinyxml2::XML_SUCCESS) { is_merge = false; } OverlapWithLane overlap_with_lane; overlap_with_lane.object_id = lane_id; overlap_with_lane.start_s = start_s; overlap_with_lane.end_s = end_s; overlap_with_lane.is_merge = is_merge; lane_overlaps->push_back(overlap_with_lane); sub_node = sub_node->NextSiblingElement("laneReference"); } } return Status::OK(); } Status LanesXmlParser::ToPbLaneType(const std::string& type, PbLaneType* lane_type) { CHECK_NOTNULL(lane_type); std::string upper_str = UtilXmlParser::ToUpper(type); if (upper_str == "NONE") { *lane_type = hdmap::Lane::NONE; } else if (upper_str == "DRIVING") { *lane_type = hdmap::Lane::CITY_DRIVING; } else if (upper_str == "BIKING") { *lane_type = hdmap::Lane::BIKING; } else if (upper_str == "PARKING") { *lane_type = hdmap::Lane::PARKING; } else if (upper_str == "SHOULDER") { *lane_type = hdmap::Lane::SHOULDER; } else if (upper_str == "SIDEWALK") { *lane_type = hdmap::Lane::SIDEWALK; } else { std::string err_msg = "Error or unsupport lane type:" + type; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status LanesXmlParser::ToPbTurnType(const std::string& type, PbTurnType* pb_turn_type) { CHECK_NOTNULL(pb_turn_type); std::string upper_str = UtilXmlParser::ToUpper(type); if (upper_str == "NOTURN") { *pb_turn_type = hdmap::Lane::NO_TURN; } else if (upper_str == "LEFTTURN") { *pb_turn_type = hdmap::Lane::LEFT_TURN; } else if (upper_str == "RIGHTTURN") { *pb_turn_type = hdmap::Lane::RIGHT_TURN; } else if (upper_str == "UTURN") { *pb_turn_type = hdmap::Lane::U_TURN; } else { std::string err_msg = "Error or unsupport turn type:" + type; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status LanesXmlParser::ToPbDirection(const std::string& type, PbLaneDirection* pb_direction) { CHECK_NOTNULL(pb_direction); std::string upper_str = UtilXmlParser::ToUpper(type); if (upper_str == "FORWARD") { *pb_direction = hdmap::Lane::FORWARD; } else if (upper_str == "BACKWARD") { *pb_direction = hdmap::Lane::BACKWARD; } else if (upper_str == "BIDIRECTION") { *pb_direction = hdmap::Lane::BIDIRECTION; } else { std::string err_msg = "Error or unsupport dirction:" + type; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } void LanesXmlParser::ParseLaneLink(const tinyxml2::XMLElement& xml_node, PbLane* lane) { CHECK_NOTNULL(lane); const tinyxml2::XMLElement* sub_node = xml_node.FirstChildElement("predecessor"); while (sub_node) { std::string lane_id; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id); if (checker == tinyxml2::XML_SUCCESS) { PbID* pb_lane_id = lane->add_predecessor_id(); pb_lane_id->set_id(lane_id); } sub_node = sub_node->NextSiblingElement("predecessor"); } sub_node = xml_node.FirstChildElement("successor"); while (sub_node) { std::string lane_id; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id); if (checker == tinyxml2::XML_SUCCESS) { PbID* pb_lane_id = lane->add_successor_id(); pb_lane_id->set_id(lane_id); } sub_node = sub_node->NextSiblingElement("successor"); } sub_node = xml_node.FirstChildElement("neighbor"); while (sub_node) { std::string side; std::string direction; std::string lane_id; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id); checker += UtilXmlParser::QueryStringAttribute(*sub_node, "side", &side); checker += UtilXmlParser::QueryStringAttribute(*sub_node, "direction", &direction); if (checker == tinyxml2::XML_SUCCESS) { if (side == "left") { if (direction == "same") { lane->add_left_neighbor_forward_lane_id()->set_id(lane_id); } else { lane->add_left_neighbor_reverse_lane_id()->set_id(lane_id); } } else if (side == "right") { if (direction == "same") { lane->add_right_neighbor_forward_lane_id()->set_id(lane_id); } else { lane->add_right_neighbor_reverse_lane_id()->set_id(lane_id); } } } sub_node = sub_node->NextSiblingElement("neighbor"); } sub_node = xml_node.FirstChildElement("selfReverse"); while (sub_node) { std::string lane_id; int checker = UtilXmlParser::QueryStringAttribute(*sub_node, "id", &lane_id); if (checker == tinyxml2::XML_SUCCESS) { lane->add_self_reverse_lane_id()->set_id(lane_id); } sub_node = sub_node->NextSiblingElement("selfReverse"); } } Status LanesXmlParser::ParseLaneBorderMark( const tinyxml2::XMLElement& xml_node, PbLaneBoundaryTypeType* boundary_type) { CHECK_NOTNULL(boundary_type); std::string type; std::string color; int checker = UtilXmlParser::QueryStringAttribute(xml_node, "type", &type); checker += UtilXmlParser::QueryStringAttribute(xml_node, "color", &color); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error to parse lane border mark"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } Status success = ToPbLaneMarkType(type, color, boundary_type); if (!success.ok()) { std::string err_msg = "fail to convert to pb lane border mark"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status LanesXmlParser::ToPbLaneMarkType(const std::string& type, const std::string& color, PbLaneBoundaryTypeType* boundary_type) { CHECK_NOTNULL(boundary_type); std::string upper_type = UtilXmlParser::ToUpper(type); std::string upper_color = UtilXmlParser::ToUpper(color); if (upper_type == "CURB") { *boundary_type = hdmap::LaneBoundaryType::CURB; return Status::OK(); } if (upper_type == "NONE") { *boundary_type = hdmap::LaneBoundaryType::UNKNOWN; return Status::OK(); } if (upper_color == "YELLOW") { if (upper_type == "SOLID") { *boundary_type = hdmap::LaneBoundaryType::SOLID_YELLOW; } else if (upper_type == "BROKEN") { *boundary_type = hdmap::LaneBoundaryType::DOTTED_YELLOW; } else { std::string err_msg = "Error or unsupport lane boundary type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } } else if (upper_color == "WHITE") { if (upper_type == "SOLID") { *boundary_type = hdmap::LaneBoundaryType::SOLID_WHITE; } else if (upper_type == "BROKEN") { *boundary_type = hdmap::LaneBoundaryType::DOTTED_WHITE; } else { std::string err_msg = "Error or unsupport lane boundary type"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } } else { std::string err_msg = "Error or unsupport lane boundary color."; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } return Status::OK(); } Status LanesXmlParser::ParseRegionOverlap( const tinyxml2::XMLElement& xml_node, std::vector<PbRegionOverlap>* region_overlaps) { CHECK_NOTNULL(region_overlaps); auto region_overlap_node = xml_node.FirstChildElement("regionOverlap"); while (region_overlap_node != nullptr) { PbRegionOverlap region_overlap; std::string region_overlap_id; int checker = UtilXmlParser::QueryStringAttribute(*region_overlap_node, "id", &region_overlap_id); if (checker != tinyxml2::XML_SUCCESS) { std::string err_msg = "Error to parse region overlap id"; return Status(apollo::common::ErrorCode::HDMAP_DATA_ERROR, err_msg); } region_overlap.mutable_id()->set_id(region_overlap_id); auto outline_node = region_overlap_node->FirstChildElement("outline"); while (outline_node != nullptr) { RETURN_IF_ERROR(UtilXmlParser::ParseOutline( *outline_node, region_overlap.add_polygon())); outline_node = outline_node->NextSiblingElement("outline"); } region_overlap_node = region_overlap_node->NextSiblingElement("regionOverlap"); region_overlaps->emplace_back(region_overlap); } return Status::OK(); } } // namespace adapter } // namespace hdmap } // namespace apollo
35.0726
80
0.685831
IsaacZhang123
d51ec1720ee2162fa6b160278ebe048b09a56fd0
577
cpp
C++
test/src/doctest_main.cpp
karnkaul/veg
a6b54484b162a188f7abae8ae27d2c1f04fda16c
[ "MIT" ]
8
2021-07-16T18:07:15.000Z
2022-01-31T19:17:10.000Z
test/src/doctest_main.cpp
karnkaul/veg
a6b54484b162a188f7abae8ae27d2c1f04fda16c
[ "MIT" ]
1
2022-01-18T23:02:26.000Z
2022-01-18T23:02:30.000Z
test/src/doctest_main.cpp
karnkaul/veg
a6b54484b162a188f7abae8ae27d2c1f04fda16c
[ "MIT" ]
2
2022-01-18T15:45:18.000Z
2022-01-26T09:53:19.000Z
#define DOCTEST_CONFIG_IMPLEMENT #include "doctest.h" #include <cstdio> #include <backward.hpp> namespace veg { int argc = 0; char** argv = nullptr; } // namespace veg auto main(int argc, char** argv) -> int { veg::argc = argc; veg::argv = argv; char argname[] = "--veg-death-assertion-id"; if (argc >= 3 && // (std::strcmp(argv[argc - 2], argname) == 0)) { std::FILE* _{}; _ = std::freopen("/dev/null", "w", stderr); _ = std::freopen("/dev/null", "w", stdout); } else { backward::SignalHandling const sh; } return doctest::Context(argc, argv).run(); }
21.37037
51
0.616984
karnkaul
d52047756e66a3c16b8efa635ce2d1f323bae298
2,910
cpp
C++
src/stc/scope.cpp
antonvw/wex
c4c41c660c9967623093a1b407af034c59a56be8
[ "MIT" ]
3
2020-03-01T06:30:30.000Z
2021-05-01T05:11:48.000Z
src/stc/scope.cpp
antonvw/wex
c4c41c660c9967623093a1b407af034c59a56be8
[ "MIT" ]
96
2020-01-18T18:25:48.000Z
2022-03-26T12:26:50.000Z
src/stc/scope.cpp
antonvw/wex
c4c41c660c9967623093a1b407af034c59a56be8
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Name: scope.cpp // Purpose: Implementation of class wex::scope // Author: Anton van Wezenbeek // Copyright: (c) 2020-2021 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <wex/log.h> #include <wex/stc.h> #include "scope.h" wex::scope::scope(stc* s) : m_stc(s) { } void wex::scope::check_levels(check_t type) { bool changed = false; const auto level(m_stc->get_fold_level()); const auto size(m_filters.size()); if (type[LEVEL_DOWN] && size >= 1 && level < size - 1) { m_filters.erase(m_filters.begin() + level + 1, m_filters.end()); changed = true; log::debug("scope::check_levels erased level") << size - m_filters.size() << "current:" << level << "size:" << m_filters.size(); } if (!changed && type[LEVEL_UP] && level >= size) { map_t m; m[std::string()] = ctags_entry(); m_filters.insert(m_filters.end(), level - size + 1, m); changed = true; log::debug("scope::check_levels inserted level") << m_filters.size() - size << "current:" << level << "size:" << m_filters.size(); } if (changed) { m_it = m_filters[level].end(); } } const std::string wex::scope::class_name(const std::string& name) const { const auto level(m_stc->get_fold_level()); if (m_filters.empty() || level > m_filters.size()) { return std::string(); } log::debug("scope::class_name") << name << level << m_filters[level].size(); if (const auto& it = iterator(name); !end()) { return it->second.class_name(); } else { return std::string(); } } bool wex::scope::end() const { const auto level(m_stc->get_fold_level()); return level >= m_filters.size() || m_it == m_filters[level].end(); } bool wex::scope::find(const std::string& text) { m_it = iterator(text); return !end(); } wex::ctags_entry& wex::scope::get(const std::string& text) { if (m_filters.empty()) { sync(); } const auto level(m_stc->get_fold_level()); return m_filters[level][text]; } void wex::scope::insert(const std::string& text, const ctags_entry& ce) { assert(!text.empty()); const auto level(m_stc->get_fold_level()); m_filters[level].insert({text, ce}); find(text); log::debug("scope::insert") << text << level << ce; } wex::scope::map_t::const_iterator wex::scope::iterator(const std::string& text) const { const auto level(m_stc->get_fold_level()); if (text.empty()) { return m_filters[level].end(); } for (int i = std::min(level, m_filters.size() - 1); i >= 0; i--) { if (const auto& it = m_filters[i].find(text); it != m_filters[i].end()) { return it; } } return m_filters[level].end(); } void wex::scope::sync() { log::debug("scope::sync"); check_levels(); }
21.086957
80
0.576289
antonvw
d520fecc7313fd00060c3bd0391a55885087991f
6,931
hpp
C++
c++/src/objtools/align_format/unit_test/blast_test_util.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/objtools/align_format/unit_test/blast_test_util.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/objtools/align_format/unit_test/blast_test_util.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: blast_test_util.hpp 354597 2012-02-28 16:45:09Z ucko $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Christiam Camacho * */ /** @file blast_test_util.hpp * Utilities to develop and debug unit tests for BLAST */ #ifndef _BLAST_TEST_UTIL_HPP #define _BLAST_TEST_UTIL_HPP #include <string> #include <exception> #include <assert.h> #include <corelib/ncbistd.hpp> #include <serial/serial.hpp> #include <serial/objostr.hpp> #include <util/random_gen.hpp> #include <util/format_guess.hpp> #include <serial/serial.hpp> #include <objtools/data_loaders/blastdb/bdbloader.hpp> #ifndef ASSERT #define ASSERT assert #endif // forward declarations namespace ncbi { namespace objects { class CSeq_id; class CSeq_align_set; class CSeqVector; class CScope; class CObjectManager; } namespace blast { struct SSeqLoc; } } namespace TestUtil { // Random integer generator for use with std::generate #if defined(__ICC) || defined(NCBI_OS_IRIX) || defined(__clang__) template <int lowest_value = 0, int highest_value = INT_MAX> #else template <int lowest_value = 0, int highest_value = ncbi::CRandom::GetMax()> #endif struct CRandomIntGen { CRandomIntGen() : m_Gen(::time(0)) {} int operator()() { return m_Gen.GetRand(lowest_value, highest_value); } private: ncbi::CRandom m_Gen; }; ncbi::objects::CSeq_id* GenerateRandomSeqid_Gi(); template <class T> ncbi::CRef<T> ReadObject(const std::string& filename) { ncbi::CNcbiIfstream in(filename.c_str()); if ( !in ) { throw std::runtime_error("Failed to open " + filename); } ncbi::CRef<T> retval(new T); switch (ncbi::CFormatGuess().Format(in)) { case ncbi::CFormatGuess::eTextASN: in >> ncbi::MSerial_AsnText >> *retval; break; case ncbi::CFormatGuess::eBinaryASN: in >> ncbi::MSerial_AsnBinary >> *retval; break; case ncbi::CFormatGuess::eXml: in >> ncbi::MSerial_Xml >> *retval; break; default: throw std::runtime_error("Unsupported format"); } return retval; } /// Convenience template function to print ASN.1 objects to a new file template <class T> void PrintTextAsn1Object(std::string filename, T* obj) { std::ofstream out(filename.c_str()); if ( !out ) throw std::runtime_error("Could not open " + filename); out << ncbi::MSerial_AsnText << *obj; } /** Converts bl2seq and blast style seq-align-sets to the seq-align-set format * that the new formatter understands (same flat format as C toolkit * seq-aligns) */ ncbi::CRef<ncbi::objects::CSeq_align_set> FlattenSeqAlignSet(const ncbi::objects::CSeq_align_set& sset); /// Assumes that the sas argument is a bl2seq and blast style seq-align-set void PrintFormattedSeqAlign(std::ostream& out, const ncbi::objects::CSeq_align_set* sas, ncbi::objects::CScope& scope); /// Endianness independent hash function. /// /// This function computes a hash value for an array of any primitive /// type. The hash assumes the data is the array is in "host" order /// with respect to endianness and should produce the same value on /// any platform for the same numerical values of the array /// elements.<P> /// /// The algorithm attempts to be robust against changes in values in /// the array, the length of the array, zeroes appended to the array), /// and will not normally be fooled by naturally occurring patterns in /// the buffer. 9However, it is not intended to be secure against /// deliberate attempts to produce a collision).<P> /// /// The size of an element of the array must be uniform and is /// specified as an argument to the function. It must exactly divide /// the byte length of the array. If the size element is specified as /// 1, no swapping will be done. This can be used to hash a string. /// /// @param buffer /// Points to the beginning of the array. /// @param byte_length /// The length of the array in bytes. /// @param swap_size /// The size of one array element (specify 1 to disable swapping). /// @param hash_seed. /// The starting value of the hash. Uint4 EndianIndependentBufferHash(const char * buffer, Uint4 byte_length, Uint4 swap_size = 1, Uint4 hash_seed = 1); /** Class which registers the BLAST database and Genbank data loaders as a * non-default data loaders with the object manager upon construction. * Designed so that the scopes created by this object are configured properly * to obtain the sequences in the expected priorities in the BLAST code. */ class CBlastOM { public: enum ELocation { eRemote, eLocal }; typedef ncbi::CBlastDbDataLoader::EDbType EDbType; CBlastOM(const std::string& dbname, EDbType db_type, ELocation location = eLocal); /// Create a new scope with the default set to the BLAST database data /// loader for the BLAST database specified in the constructor (if found), /// then set to the Genbank data loader ncbi::CRef<ncbi::objects::CScope> NewScope(); /// Removes the BLAST database data loader from the object manager. void RevokeBlastDbDataLoader(); private: ncbi::CRef<ncbi::objects::CObjectManager> m_ObjMgr; std::string m_BlastDbLoaderName; std::string m_GbLoaderName; void x_InitBlastDatabaseDataLoader(const std::string& dbname, EDbType dbtype, ELocation location); void x_InitGenbankDataLoader(); }; } #endif // _BLAST_TEST_UTIL_HPP
33.97549
86
0.665416
OpenHero
d5253eaacce066df546bf71ee56094c0c5c69043
16,440
cpp
C++
attic/p42/SysCore/Keyboard/kybrd.cpp
mooseman/plan_42
0b726f06088c6940aa7050b5cef9f93a3cdcc788
[ "Unlicense" ]
7
2015-02-18T13:45:06.000Z
2019-01-24T21:49:18.000Z
attic/p42/SysCore/Keyboard/kybrd.cpp
mooseman/plan_42
0b726f06088c6940aa7050b5cef9f93a3cdcc788
[ "Unlicense" ]
null
null
null
attic/p42/SysCore/Keyboard/kybrd.cpp
mooseman/plan_42
0b726f06088c6940aa7050b5cef9f93a3cdcc788
[ "Unlicense" ]
2
2017-04-21T09:38:50.000Z
2020-05-26T22:13:58.000Z
//**************************************************************************** //** //** kybrd.cpp //** -Keyboard driver //** //**************************************************************************** //============================================================================ // IMPLEMENTATION HEADERS //============================================================================ #include <string.h> #include <ctype.h> #include <hal.h> #include "kybrd.h" //============================================================================ // IMPLEMENTATION PRIVATE DEFINITIONS / ENUMERATIONS / SIMPLE TYPEDEFS //============================================================================ // keyboard encoder ------------------------------------------ enum KYBRD_ENCODER_IO { KYBRD_ENC_INPUT_BUF = 0x60, KYBRD_ENC_CMD_REG = 0x60 }; enum KYBRD_ENC_CMDS { KYBRD_ENC_CMD_SET_LED = 0xED, KYBRD_ENC_CMD_ECHO = 0xEE, KYBRD_ENC_CMD_SCAN_CODE_SET = 0xF0, KYBRD_ENC_CMD_ID = 0xF2, KYBRD_ENC_CMD_AUTODELAY = 0xF3, KYBRD_ENC_CMD_ENABLE = 0xF4, KYBRD_ENC_CMD_RESETWAIT = 0xF5, KYBRD_ENC_CMD_RESETSCAN = 0xF6, KYBRD_ENC_CMD_ALL_AUTO = 0xF7, KYBRD_ENC_CMD_ALL_MAKEBREAK = 0xF8, KYBRD_ENC_CMD_ALL_MAKEONLY = 0xF9, KYBRD_ENC_CMD_ALL_MAKEBREAK_AUTO = 0xFA, KYBRD_ENC_CMD_SINGLE_AUTOREPEAT = 0xFB, KYBRD_ENC_CMD_SINGLE_MAKEBREAK = 0xFC, KYBRD_ENC_CMD_SINGLE_BREAKONLY = 0xFD, KYBRD_ENC_CMD_RESEND = 0xFE, KYBRD_ENC_CMD_RESET = 0xFF }; // keyboard controller --------------------------------------- enum KYBRD_CTRL_IO { KYBRD_CTRL_STATS_REG= 0x64, KYBRD_CTRL_CMD_REG = 0x64 }; enum KYBRD_CTRL_STATS_MASK { KYBRD_CTRL_STATS_MASK_OUT_BUF = 1, //00000001 KYBRD_CTRL_STATS_MASK_IN_BUF = 2, //00000010 KYBRD_CTRL_STATS_MASK_SYSTEM = 4, //00000100 KYBRD_CTRL_STATS_MASK_CMD_DATA = 8, //00001000 KYBRD_CTRL_STATS_MASK_LOCKED = 0x10, //00010000 KYBRD_CTRL_STATS_MASK_AUX_BUF = 0x20, //00100000 KYBRD_CTRL_STATS_MASK_TIMEOUT = 0x40, //01000000 KYBRD_CTRL_STATS_MASK_PARITY = 0x80 //10000000 }; enum KYBRD_CTRL_CMDS { KYBRD_CTRL_CMD_READ = 0x20, KYBRD_CTRL_CMD_WRITE = 0x60, KYBRD_CTRL_CMD_SELF_TEST = 0xAA, KYBRD_CTRL_CMD_INTERFACE_TEST = 0xAB, KYBRD_CTRL_CMD_DISABLE = 0xAD, KYBRD_CTRL_CMD_ENABLE = 0xAE, KYBRD_CTRL_CMD_READ_IN_PORT = 0xC0, KYBRD_CTRL_CMD_READ_OUT_PORT = 0xD0, KYBRD_CTRL_CMD_WRITE_OUT_PORT = 0xD1, KYBRD_CTRL_CMD_READ_TEST_INPUTS = 0xE0, KYBRD_CTRL_CMD_SYSTEM_RESET = 0xFE, KYBRD_CTRL_CMD_MOUSE_DISABLE = 0xA7, KYBRD_CTRL_CMD_MOUSE_ENABLE = 0xA8, KYBRD_CTRL_CMD_MOUSE_PORT_TEST = 0xA9, KYBRD_CTRL_CMD_MOUSE_WRITE = 0xD4 }; // scan error codes ------------------------------------------ enum KYBRD_ERROR { KYBRD_ERR_BUF_OVERRUN = 0, KYBRD_ERR_ID_RET = 0x83AB, KYBRD_ERR_BAT = 0xAA, //note: can also be L. shift key make code KYBRD_ERR_ECHO_RET = 0xEE, KYBRD_ERR_ACK = 0xFA, KYBRD_ERR_BAT_FAILED = 0xFC, KYBRD_ERR_DIAG_FAILED = 0xFD, KYBRD_ERR_RESEND_CMD = 0xFE, KYBRD_ERR_KEY = 0xFF }; //============================================================================ // IMPLEMENTATION PRIVATE CLASS PROTOTYPES / EXTERNAL CLASS REFERENCES //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE STRUCTURES / UTILITY CLASSES //============================================================================ //============================================================================ // IMPLEMENTATION REQUIRED EXTERNAL REFERENCES (AVOID) //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE DATA //============================================================================ //! current scan code static char _scancode; //! lock keys static bool _numlock, _scrolllock, _capslock; //! shift, alt, and ctrl keys current state static bool _shift, _alt, _ctrl; //! set if keyboard error static int _kkybrd_error = 0; //! set if the Basic Assurance Test (BAT) failed static bool _kkybrd_bat_res = false; //! set if diagnostics failed static bool _kkybrd_diag_res = false; //! set if system should resend last command static bool _kkybrd_resend_res = false; //! set if keyboard is disabled static bool _kkybrd_disable = false; //! original xt scan code set. Array index==make code //! change what keys the scan code corrospond to if your scan code set is different static int _kkybrd_scancode_std [] = { //! key scancode KEY_UNKNOWN, //0 KEY_ESCAPE, //1 KEY_1, //2 KEY_2, //3 KEY_3, //4 KEY_4, //5 KEY_5, //6 KEY_6, //7 KEY_7, //8 KEY_8, //9 KEY_9, //0xa KEY_0, //0xb KEY_MINUS, //0xc KEY_EQUAL, //0xd KEY_BACKSPACE, //0xe KEY_TAB, //0xf KEY_Q, //0x10 KEY_W, //0x11 KEY_E, //0x12 KEY_R, //0x13 KEY_T, //0x14 KEY_Y, //0x15 KEY_U, //0x16 KEY_I, //0x17 KEY_O, //0x18 KEY_P, //0x19 KEY_LEFTBRACKET,//0x1a KEY_RIGHTBRACKET,//0x1b KEY_RETURN, //0x1c KEY_LCTRL, //0x1d KEY_A, //0x1e KEY_S, //0x1f KEY_D, //0x20 KEY_F, //0x21 KEY_G, //0x22 KEY_H, //0x23 KEY_J, //0x24 KEY_K, //0x25 KEY_L, //0x26 KEY_SEMICOLON, //0x27 KEY_QUOTE, //0x28 KEY_GRAVE, //0x29 KEY_LSHIFT, //0x2a KEY_BACKSLASH, //0x2b KEY_Z, //0x2c KEY_X, //0x2d KEY_C, //0x2e KEY_V, //0x2f KEY_B, //0x30 KEY_N, //0x31 KEY_M, //0x32 KEY_COMMA, //0x33 KEY_DOT, //0x34 KEY_SLASH, //0x35 KEY_RSHIFT, //0x36 KEY_KP_ASTERISK,//0x37 KEY_RALT, //0x38 KEY_SPACE, //0x39 KEY_CAPSLOCK, //0x3a KEY_F1, //0x3b KEY_F2, //0x3c KEY_F3, //0x3d KEY_F4, //0x3e KEY_F5, //0x3f KEY_F6, //0x40 KEY_F7, //0x41 KEY_F8, //0x42 KEY_F9, //0x43 KEY_F10, //0x44 KEY_KP_NUMLOCK, //0x45 KEY_SCROLLLOCK, //0x46 KEY_HOME, //0x47 KEY_KP_8, //0x48 //keypad up arrow KEY_PAGEUP, //0x49 KEY_KP_2, //0x50 //keypad down arrow KEY_KP_3, //0x51 //keypad page down KEY_KP_0, //0x52 //keypad insert key KEY_KP_DECIMAL, //0x53 //keypad delete key KEY_UNKNOWN, //0x54 KEY_UNKNOWN, //0x55 KEY_UNKNOWN, //0x56 KEY_F11, //0x57 KEY_F12 //0x58 }; //! invalid scan code. Used to indicate the last scan code is not to be reused const int INVALID_SCANCODE = 0; //============================================================================ // INTERFACE DATA //============================================================================ //============================================================================ // IMPLEMENTATION PRIVATE FUNCTION PROTOTYPES //============================================================================ uint8_t kybrd_ctrl_read_status (); void kybrd_ctrl_send_cmd (uint8_t); uint8_t kybrd_enc_read_buf (); void kybrd_enc_send_cmd (uint8_t); void _cdecl i86_kybrd_irq (); //============================================================================ // IMPLEMENTATION PRIVATE FUNCTIONS //============================================================================ //! read status from keyboard controller uint8_t kybrd_ctrl_read_status () { return inportb (KYBRD_CTRL_STATS_REG); } //! send command byte to keyboard controller void kybrd_ctrl_send_cmd (uint8_t cmd) { //! wait for kkybrd controller input buffer to be clear while (1) if ( (kybrd_ctrl_read_status () & KYBRD_CTRL_STATS_MASK_IN_BUF) == 0) break; outportb (KYBRD_CTRL_CMD_REG, cmd); } //! read keyboard encoder buffer uint8_t kybrd_enc_read_buf () { return inportb (KYBRD_ENC_INPUT_BUF); } //! send command byte to keyboard encoder void kybrd_enc_send_cmd (uint8_t cmd) { //! wait for kkybrd controller input buffer to be clear while (1) if ( (kybrd_ctrl_read_status () & KYBRD_CTRL_STATS_MASK_IN_BUF) == 0) break; //! send command byte to kybrd encoder outportb (KYBRD_ENC_CMD_REG, cmd); } //! keyboard interrupt handler void _cdecl i86_kybrd_irq () { _asm add esp, 12 _asm pushad _asm cli static bool _extended = false; int code = 0; //! read scan code only if the kkybrd controller output buffer is full (scan code is in it) if (kybrd_ctrl_read_status () & KYBRD_CTRL_STATS_MASK_OUT_BUF) { //! read the scan code code = kybrd_enc_read_buf (); //! is this an extended code? If so, set it and return if (code == 0xE0 || code == 0xE1) _extended = true; else { //! either the second byte of an extended scan code or a single byte scan code _extended = false; //! test if this is a break code (Original XT Scan Code Set specific) if (code & 0x80) { //test bit 7 //! covert the break code into its make code equivelant code -= 0x80; //! grab the key int key = _kkybrd_scancode_std [code]; //! test if a special key has been released & set it switch (key) { case KEY_LCTRL: case KEY_RCTRL: _ctrl = false; break; case KEY_LSHIFT: case KEY_RSHIFT: _shift = false; break; case KEY_LALT: case KEY_RALT: _alt = false; break; } } else { //! this is a make code - set the scan code _scancode = code; //! grab the key int key = _kkybrd_scancode_std [code]; //! test if user is holding down any special keys & set it switch (key) { case KEY_LCTRL: case KEY_RCTRL: _ctrl = true; break; case KEY_LSHIFT: case KEY_RSHIFT: _shift = true; break; case KEY_LALT: case KEY_RALT: _alt = true; break; case KEY_CAPSLOCK: _capslock = (_capslock) ? false : true; kkybrd_set_leds (_numlock, _capslock, _scrolllock); break; case KEY_KP_NUMLOCK: _numlock = (_numlock) ? false : true; kkybrd_set_leds (_numlock, _capslock, _scrolllock); break; case KEY_SCROLLLOCK: _scrolllock = (_scrolllock) ? false : true; kkybrd_set_leds (_numlock, _capslock, _scrolllock); break; } } } //! watch for errors switch (code) { case KYBRD_ERR_BAT_FAILED: _kkybrd_bat_res = false; break; case KYBRD_ERR_DIAG_FAILED: _kkybrd_diag_res = false; break; case KYBRD_ERR_RESEND_CMD: _kkybrd_resend_res = true; break; } } //! tell hal we are done interruptdone(0); //! return from interrupt handler _asm sti _asm popad _asm iretd } //============================================================================ // INTERFACE FUNCTIONS //============================================================================ //! returns scroll lock state bool kkybrd_get_scroll_lock () { return _scrolllock; } //! returns num lock state bool kkybrd_get_numlock () { return _numlock; } //! returns caps lock state bool kkybrd_get_capslock () { return _capslock; } //! returns status of control key bool kkybrd_get_ctrl () { return _ctrl; } //! returns status of alt key bool kkybrd_get_alt () { return _alt; } //! returns status of shift key bool kkybrd_get_shift () { return _shift; } //! tells driver to ignore last resend request void kkybrd_ignore_resend () { _kkybrd_resend_res = false; } //! return if system should redo last commands bool kkybrd_check_resend () { return _kkybrd_resend_res; } //! return diagnostics test result bool kkybrd_get_diagnostic_res () { return _kkybrd_diag_res; } //! return BAT test result bool kkybrd_get_bat_res () { return _kkybrd_bat_res; } //! return last scan code uint8_t kkybrd_get_last_scan () { return _scancode; } //! sets leds void kkybrd_set_leds (bool num, bool caps, bool scroll) { uint8_t data = 0; //! set or clear the bit data = (scroll) ? (data | 1) : (data & 1); data = (num) ? (num | 2) : (num & 2); data = (caps) ? (num | 4) : (num & 4); //! send the command -- update keyboard Light Emetting Diods (LEDs) kybrd_enc_send_cmd (KYBRD_ENC_CMD_SET_LED); kybrd_enc_send_cmd (data); } //! get last key stroke KEYCODE kkybrd_get_last_key () { return (_scancode!=INVALID_SCANCODE) ? ((KEYCODE)_kkybrd_scancode_std [_scancode]) : (KEY_UNKNOWN); } //! discards last scan void kkybrd_discard_last_key () { _scancode = INVALID_SCANCODE; } //! convert key to an ascii character char kkybrd_key_to_ascii (KEYCODE code) { uint8_t key = code; //! insure key is an ascii character if (isascii (key)) { //! if shift key is down or caps lock is on, make the key uppercase if (_shift || _capslock) if (key >= 'a' && key <= 'z') key -= 32; if (_shift && !_capslock) if (key >= '0' && key <= '9') switch (key) { case '0': key = KEY_RIGHTPARENTHESIS; break; case '1': key = KEY_EXCLAMATION; break; case '2': key = KEY_AT; break; case '3': key = KEY_EXCLAMATION; break; case '4': key = KEY_HASH; break; case '5': key = KEY_PERCENT; break; case '6': key = KEY_CARRET; break; case '7': key = KEY_AMPERSAND; break; case '8': key = KEY_ASTERISK; break; case '9': key = KEY_LEFTPARENTHESIS; break; } else { switch (key) { case KEY_COMMA: key = KEY_LESS; break; case KEY_DOT: key = KEY_GREATER; break; case KEY_SLASH: key = KEY_QUESTION; break; case KEY_SEMICOLON: key = KEY_COLON; break; case KEY_QUOTE: key = KEY_QUOTEDOUBLE; break; case KEY_LEFTBRACKET : key = KEY_LEFTCURL; break; case KEY_RIGHTBRACKET : key = KEY_RIGHTCURL; break; case KEY_GRAVE: key = KEY_TILDE; break; case KEY_MINUS: key = KEY_UNDERSCORE; break; case KEY_PLUS: key = KEY_EQUAL; break; case KEY_BACKSLASH: key = KEY_BAR; break; } } //! return the key return key; } //! scan code != a valid ascii char so no convertion is possible return 0; } //! disables the keyboard void kkybrd_disable () { kybrd_ctrl_send_cmd (KYBRD_CTRL_CMD_DISABLE); _kkybrd_disable = true; } //! enables the keyboard void kkybrd_enable () { kybrd_ctrl_send_cmd (KYBRD_CTRL_CMD_ENABLE); _kkybrd_disable = false; } //! returns true if keyboard is disabled bool kkybrd_is_disabled () { return _kkybrd_disable; } //! reset the system void kkybrd_reset_system () { //! writes 11111110 to the output port (sets reset system line low) kybrd_ctrl_send_cmd (KYBRD_CTRL_CMD_WRITE_OUT_PORT); kybrd_enc_send_cmd (0xfe); } //! run self test bool kkybrd_self_test () { //! send command kybrd_ctrl_send_cmd (KYBRD_CTRL_CMD_SELF_TEST); //! wait for output buffer to be full while (1) if (kybrd_ctrl_read_status () & KYBRD_CTRL_STATS_MASK_OUT_BUF) break; //! if output buffer == 0x55, test passed return (kybrd_enc_read_buf () == 0x55) ? true : false; } //! prepares driver for use void kkybrd_install (int irq) { //! Install our interrupt handler (irq 1 uses interrupt 33) setvect (irq, i86_kybrd_irq); //! assume BAT test is good. If there is a problem, the IRQ handler where catch the error _kkybrd_bat_res = true; _scancode = 0; //! set lock keys and led lights _numlock = _scrolllock = _capslock = false; kkybrd_set_leds (false, false, false); //! shift, ctrl, and alt keys _shift = _alt = _ctrl = false; } //============================================================================ // INTERFACE CLASS BODIES //============================================================================ //**************************************************************************** //** //** END[kybrd.cpp] //** //****************************************************************************
24.212077
101
0.556873
mooseman
d525f95e42d6522cd7ee92b8811407b917e7369b
42,083
cpp
C++
src/Vendor/gumbo/GumboInterface.cpp
luojilab/CSSParser
1c507c98a0cdd37227f3b3c71f84a2165445a795
[ "MIT" ]
15
2018-08-31T06:54:27.000Z
2022-01-06T07:01:29.000Z
src/Vendor/gumbo/GumboInterface.cpp
getsync/CSSParser
1c507c98a0cdd37227f3b3c71f84a2165445a795
[ "MIT" ]
null
null
null
src/Vendor/gumbo/GumboInterface.cpp
getsync/CSSParser
1c507c98a0cdd37227f3b3c71f84a2165445a795
[ "MIT" ]
6
2018-08-31T06:54:36.000Z
2021-10-09T07:10:36.000Z
#include <string> #include <stdio.h> #include <list> #include <set> #include <algorithm> #include "GumboInterface.h" #include "string_buffer.h" #include "error.h" #include "StringUtil.h" #include "UrlUtil.h" //#include "pcrecpp.h" namespace future { static std::set<std::string> init_set(const char** arr, int lenth) { std::set<std::string> ret; for (int i = 0; i < lenth; i++) { ret.insert(std::string(arr[i])); } return ret; } static const char*arr_nonbreaking[42] = { "a", "abbr", "acronym", "b", "bdo", "big", "br", "button", "cite", "code", "del", "dfn", "em", "font", "i", "image", "img", "input", "ins", "kbd", "label", "map", "nobr", "object", "q", "ruby", "rt", "s", "samp", "select", "small", "span", "strike", "strong", "sub", "sup", "textarea", "tt", "u", "var", "wbr", "mbp:nu" }; static std::set<std::string> nonbreaking_inline = init_set(arr_nonbreaking, 42); static const char*arr_preserve_whitespace[4] = { "pre", "textarea", "script", "style" }; static std::set<std::string> preserve_whitespace = init_set( arr_preserve_whitespace, 4); static const char*arr_special_handling[2] = { "html", "body" }; static std::set<std::string> special_handling = init_set(arr_special_handling, 2); static const char*arr_no_entity_sub[2] = { "script", "style" }; static std::set<std::string> no_entity_sub = init_set(arr_no_entity_sub, 2); static const char*arr_void_tags[29] = { "area", "base", "basefont", "bgsound", "br", "col", "command", "embed", "event-source", "frame", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "spacer", "track", "wbr", "mbp:pagebreak", "mglyph", "mspace", "mprescripts", "none", "maligngroup", "malignmark", "msline" }; static std::set<std::string> void_tags = init_set(arr_void_tags, 29); static const char*arr_structural_tags[24] = { "article", "aside", "blockquote", "body", "canvas", "colgroup", "div", "dl", "figure", "footer", "head", "header", "hr", "html", "ol", "section", "table", "tbody", "tfoot", "thead", "td", "th", "tr", "ul" }; static std::set<std::string> structural_tags = init_set(arr_structural_tags, 24); static const char*arr_other_text_holders[18] = { "address", "caption", "dd", "div", "dt", "h1", "h2", "h3", "h4", "h5", "h6", "legend", "li", "option", "p", "td", "th", "title" }; static std::set<std::string> other_text_holders = init_set( arr_other_text_holders, 18); static const char*arr_manifest_properties[5] = { "math", "nav", "script", "svg", "epub:switch" }; static std::set<std::string> manifest_properties = init_set( arr_manifest_properties, 5); static const char*arr_href_src_tags[17] = { "a", "area", "audio", "base", "embed", "font-face-uri", "frame", "iframe", "image", "img", "input", "link", "object", "script", "source", "track", "video" }; static std::set<std::string> href_src_tags = init_set(arr_href_src_tags, 17); static const char POUND_SIGN = '#'; static const char FORWARD_SLASH = '/'; static const std::string aSRC = std::string("src"); static const std::string aHREF = std::string("href"); static const std::string aPOSTER = std::string("poster"); static const std::string aDATA = std::string("data"); std::map<std::string, std::string> EmptyHash = std::map<std::string, std::string>(); // These need to match the GumboAttributeNamespaceEnum sequence static const char *attribute_nsprefixes[4] = { "", "xlink:", "xml:", "xmlns:" }; // Note: m_output contains the gumbo output tree which // has data structures with pointers into the original source // buffer passed in!!!!!! // This source buffer is provided by the m_utf8src std::string // which should always exist unchanged alongside the output tree // Do NOT change or delete m_utf8src once set until after you // have properly destroyed the gumbo output tree GumboInterface::GumboInterface(const std::string &source, const std::string &version) : m_source(source), m_output(NULL), m_utf8src(""), m_sourceupdates(EmptyHash), m_newcsslinks(""), m_currentdir(""), m_newbody(""), m_hasnbsp(false), m_version(version) { } GumboInterface::GumboInterface(const std::string &source, const std::string &version, const std::map<std::string, std::string> & source_updates) : m_source(source), m_output(NULL), m_utf8src(""), m_sourceupdates(source_updates), m_newcsslinks(""), m_currentdir(""), m_newbody(""), m_hasnbsp(false), m_version(version) { } GumboInterface::~GumboInterface() { if (m_output != NULL) { gumbo_destroy_output(m_output); m_output = NULL; m_utf8src = ""; } } void GumboInterface::parse() { if (!m_source.empty() && (m_output == NULL)) { std::string three("3"); if (!StringUtil::startWith(m_version, three)) { m_hasnbsp = StringUtil::contains(m_source, std::string("&nbsp;")); } m_utf8src = m_source; // remove any xml header line and any trailing whitespace if (m_utf8src.compare(0, 5, "<?xml") == 0) { size_t end = m_utf8src.find_first_of('>', 5); end = m_utf8src.find_first_not_of("\n\r\t\v\f ", end + 1); m_utf8src.erase(0, end); } // In case we ever have to revert to earlier versions, please note the following // additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?) // do not properly initialize myoptions from the static const kGumboDefaultOptions defined // in the gumbo library. Instead whatever was in memory at the time is used causing random // issues later on so if reverting remember to keep these specific changes as the bug // they work around took a long long time to track down GumboOptions myoptions = kGumboDefaultOptions; myoptions.tab_stop = 4; myoptions.use_xhtml_rules = true; myoptions.stop_on_first_error = false; myoptions.max_errors = -1; // GumboInterface::m_mutex.lock(); m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length()); // GumboInterface::m_mutex.unlock(); } } std::string GumboInterface::repair() { std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } std::string utf8out = serialize(m_output->document); rtrim(utf8out); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; } return result; } std::string GumboInterface::getxhtml() { std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } std::string utf8out = serialize(m_output->document); rtrim(utf8out); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; } return result; } std::string GumboInterface::prettyprint(std::string indent_chars) { std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } std::string ind = indent_chars; std::string utf8out = prettyprint(m_output->document, 0, ind); rtrim(utf8out); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; } return result; } std::list<std::string> GumboInterface::get_all_properties() { std::list<std::string> properties; if (!m_source.empty()) { if (m_output == NULL) { parse(); } properties = get_properties(m_output->root); } return properties; } std::string GumboInterface::perform_source_updates( const std::string& my_current_book_relpath) { m_currentdir = my_current_book_relpath; std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } enum UpdateTypes doupdates = SourceUpdates; std::string utf8out = serialize(m_output->document, doupdates); rtrim(utf8out); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; } return result; } std::string GumboInterface::perform_style_updates( const std::string& my_current_book_relpath) { //m_currentdir = QFileInfo(my_current_book_relpath).dir().path(); std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } enum UpdateTypes doupdates = StyleUpdates; std::string utf8out = serialize(m_output->document, doupdates); rtrim(utf8out); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; } return result; } std::string GumboInterface::perform_link_updates(const std::string& newcsslinks) { m_newcsslinks = newcsslinks; std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } enum UpdateTypes doupdates = LinkUpdates; std::string utf8out = serialize(m_output->document, doupdates); rtrim(utf8out); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; } return result; } GumboNode * GumboInterface::get_root_node() { if (!m_source.empty()) { if (m_output == NULL) { parse(); } } return m_output->root; } std::string GumboInterface::get_body_contents() { if (!m_source.empty()) { if (m_output == NULL) { parse(); } } std::list<GumboTag> tags = std::list<GumboTag>(); tags.push_back(GUMBO_TAG_BODY); std::list<GumboNode*> nodes = get_all_nodes_with_tags(tags); if (nodes.size() != 1) { return std::string(); } enum UpdateTypes doupdates = NoUpdates; std::string results = serialize_contents(nodes.front(), doupdates); return results; } std::list<std::string> GumboInterface::get_properties(GumboNode* node) { if (node->type != GUMBO_NODE_ELEMENT) { return std::list<std::string>(); } std::list<std::string> properties; std::string tagname = get_tag_name(node); if (in_set(manifest_properties, tagname)) { properties.push_back(tagname); } GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, "src"); if (attr) { properties.push_back(std::string("remote-resources")); } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { std::list<std::string> ret = get_properties( static_cast<GumboNode*> (children->data[i])); properties.merge(ret); } return properties; } std::string GumboInterface::get_qwebpath_to_node(GumboNode* node) { std::list<std::string> path_pieces; GumboNode* anode = node; while (anode && !((anode->type == GUMBO_NODE_ELEMENT) && (anode->v.element.tag == GUMBO_TAG_HTML))) { GumboNode* myparent = anode->parent; std::string parent_name = get_tag_name(myparent); int index; std::string aname = get_tag_name(anode); if (aname == "#text") { index = anode->index_within_parent; } else { // need to find child num in parent as if only elements exist GumboVector* children = &myparent->v.element.children; int elnum = 0; for (unsigned int i = 0; i < children->length; i++) { GumboNode* child = static_cast<GumboNode*> (children->data[i]); if (i == anode->index_within_parent) { break; } if ((child->type == GUMBO_NODE_ELEMENT) || (child->type == GUMBO_NODE_TEMPLATE)) { elnum++; } } index = elnum; } path_pieces.push_back(parent_name + " " + StringUtil::int2str(index)); anode = myparent; } std::string ret; for (std::list<std::string>::iterator iter = path_pieces.begin(); iter != path_pieces.end(); iter++) { ret.append(*iter); ret.append(","); } return ret; } GumboNode* GumboInterface::get_node_from_qwebpath(std::string webpath) { return NULL; } std::list<unsigned int> GumboInterface::get_path_to_node(GumboNode* node) { std::list<unsigned int> apath = std::list<unsigned int>(); GumboNode* anode = node; while (anode && !((anode->type == GUMBO_NODE_ELEMENT) && (anode->v.element.tag == GUMBO_TAG_HTML))) { apath.push_back(anode->index_within_parent); anode = anode->parent; } return apath; } GumboNode* GumboInterface::get_node_from_path(std::list<unsigned int> &apath) { GumboNode* dest = get_root_node(); unsigned int childnum = 0; for (std::list<unsigned int>::iterator iter = apath.begin(); iter != apath.end(); iter++, childnum++) { if ((dest->type == GUMBO_NODE_ELEMENT) || (dest->type == GUMBO_NODE_TEMPLATE)) { GumboVector* children = &dest->v.element.children; if (childnum < children->length) { dest = static_cast<GumboNode*> (children->data[childnum]); } else { break; } } else { break; } } return dest; } std::string GumboInterface::perform_body_updates(const std::string & new_body) { std::string result = ""; if (!m_source.empty()) { if (m_output == NULL) { parse(); } } std::list<GumboTag> tags = std::list<GumboTag>(); tags.push_back(GUMBO_TAG_BODY); std::list<GumboNode*> nodes = get_all_nodes_with_tags(tags); if (nodes.size() != 1) { return std::string(); } m_newbody = new_body; enum UpdateTypes doupdates = BodyUpdates; std::string utf8out = serialize(m_output->document, doupdates); result = std::string("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n") + utf8out; m_newbody = ""; return result; } std::list<GumboWellFormedError> GumboInterface::error_check() { std::list<GumboWellFormedError> errlist; int line_offset = 0; // In case we ever have to revert to earlier versions, please note the following // additional initialization is needed because Microsoft Visual Studio 2013 (and earlier?) // do not properly initialize myoptions from the static const kGumboDefaultOptions defined // in the gumbo library. Instead whatever was in memory at the time is used causing random // issues later on so if reverting remember to keep these specific changes as the bug // they work around took a long long time to track down GumboOptions myoptions = kGumboDefaultOptions; myoptions.tab_stop = 4; myoptions.use_xhtml_rules = true; myoptions.stop_on_first_error = false; myoptions.max_errors = -1; if (!m_source.empty() && (m_output == NULL)) { m_utf8src = m_source; // remove any xml header line and trailing whitespace if (m_utf8src.compare(0, 5, "<?xml") == 0) { size_t end = m_utf8src.find_first_of('>', 0); end = m_utf8src.find_first_not_of("\n\r\t\v\f ", end + 1); m_utf8src.erase(0, end); line_offset++; } // add in epub version specific doctype if missing if ((m_utf8src.compare(0, 9, "<!DOCTYPE") != 0) && (m_utf8src.compare( 0, 9, "<!doctype") != 0)) { std::string three("3"); if (StringUtil::startWith(m_version, three)) { m_utf8src.insert(0, "<!DOCTYPE html>\n"); } else { m_utf8src.insert( 0, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n"); } line_offset--; } m_output = gumbo_parse_with_options(&myoptions, m_utf8src.data(), m_utf8src.length()); } // qDebug() << QString::fromStdString(m_utf8src); const GumboVector* errors = &m_output->errors; for (unsigned int i = 0; i < errors->length; ++i) { GumboError* er = static_cast<GumboError*> (errors->data[i]); GumboWellFormedError gperror; gperror.line = er->position.line + line_offset; ; gperror.column = er->position.column; // unsigned int typenum = er->type; GumboStringBuffer text; gumbo_string_buffer_init(&text); gumbo_error_to_string(er, &text); std::string errmsg(text.data, text.length); gperror.message = errmsg; // qDebug() << gperror.message; gumbo_string_buffer_destroy(&text); errlist.push_back(gperror); } return errlist; } std::list<GumboNode*> GumboInterface::get_all_nodes_with_attribute( const std::string& attname) { std::list<GumboNode*> nodes; if (!m_source.empty()) { if (m_output == NULL) { parse(); } nodes = get_nodes_with_attribute(m_output->root, attname.c_str()); } return nodes; } std::list<GumboNode*> GumboInterface::get_nodes_with_attribute(GumboNode* node, const char * attname) { if (node->type != GUMBO_NODE_ELEMENT) { return std::list<GumboNode*>(); } std::list<GumboNode*> nodes; GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, attname); if (attr) { nodes.push_back(node); } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { std::list<GumboNode*> ret = get_nodes_with_attribute( static_cast<GumboNode*> (children->data[i]), attname); nodes.merge(ret); } return nodes; } std::list<std::string> GumboInterface::get_all_values_for_attribute( const std::string& attname) { std::list<std::string> attrvals; if (!m_source.empty()) { if (m_output == NULL) { parse(); } attrvals = get_values_for_attr(m_output->root, attname.c_str()); } return attrvals; } std::list<std::string> GumboInterface::get_values_for_attr(GumboNode* node, const char* attr_name) { if (node->type != GUMBO_NODE_ELEMENT) { return std::list<std::string>(); } std::list<std::string> attr_vals; GumboAttribute* attr = gumbo_get_attribute(&node->v.element.attributes, attr_name); if (attr != NULL) { attr_vals.push_back(attr->value); } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { std::list<std::string> ret = get_values_for_attr( static_cast<GumboNode*> (children->data[i]), attr_name); attr_vals.merge(ret); } return attr_vals; } std::map<std::string, std::string> GumboInterface::get_attributes_of_node( GumboNode* node) { std::map<std::string, std::string> node_atts; if (node->type != GUMBO_NODE_ELEMENT) { return node_atts; } const GumboVector * attribs = &node->v.element.attributes; for (unsigned int i = 0; i < attribs->length; ++i) { GumboAttribute* attr = static_cast<GumboAttribute*> (attribs->data[i]); std::string key = get_attribute_name(attr); std::string val = attr->value; node_atts[key] = val; } return node_atts; } std::string GumboInterface::get_local_text_of_node(GumboNode* node) { std::string node_text; if (node->type != GUMBO_NODE_ELEMENT) { return node_text; } // handle br tag as special case element tag with a text value GumboTag tag = node->v.element.tag; if (tag == GUMBO_TAG_BR) { node_text = "\n"; return node_text; } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { GumboNode* child = static_cast<GumboNode*> (children->data[i]); if (child->type == GUMBO_NODE_TEXT) { node_text += child->v.text.text; } else if (child->type == GUMBO_NODE_WHITESPACE) { // keep all whitespace to keep as close to original as possible node_text += child->v.text.text; } else if (child->type == GUMBO_NODE_CDATA) { node_text += child->v.text.text; } else if (child->type == GUMBO_NODE_ELEMENT) { node_text += get_local_text_of_node(child); } } return node_text; } std::string GumboInterface::get_text_of_node(GumboNode* node) { std::string node_text; if (node->type == GUMBO_NODE_TEXT) { node_text = std::string(node->v.text.text); } return node_text; } std::list<GumboNode*> GumboInterface::get_all_nodes_with_tag(GumboTag tag) { std::list<GumboTag> tags; tags.push_back(tag); return get_all_nodes_with_tags(tags); } std::list<GumboNode*> GumboInterface::get_all_nodes_with_tags( const std::list<GumboTag> & tags) { std::list<GumboNode*> nodes; if (!m_source.empty()) { if (m_output == NULL) { parse(); } nodes = get_nodes_with_tags(m_output->root, tags); } return nodes; } std::list<GumboNode*> GumboInterface::get_nodes_with_tags(GumboNode* node, const std::list<GumboTag> & tags) { if (node->type != GUMBO_NODE_ELEMENT) { return std::list<GumboNode*>(); } std::list<GumboNode*> nodes; GumboTag tag = node ->v.element.tag; if (find(tags.begin(), tags.end(), tag) != tags.end()) { nodes.push_back(node); } GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; ++i) { std::list<GumboNode*> ret = get_nodes_with_tags( static_cast<GumboNode*> (children->data[i]), tags); nodes.merge(ret); } return nodes; } std::list<GumboNode*> GumboInterface::get_all_nodes(GumboNode* node) { std::list<GumboNode*> ret; ret.push_back(node); if (node->type == GUMBO_NODE_ELEMENT) { GumboVector* children = &node->v.element.children; for (unsigned int i = 0; i < children->length; i++) { std::list<GumboNode*> childrenNodes = get_all_nodes( static_cast<GumboNode *> (children->data[i])); ret.merge(childrenNodes); } } return ret; } bool GumboInterface::in_set(std::set<std::string> &s, std::string &key) { return s.find(key) != s.end(); } void GumboInterface::rtrim(std::string &s) { s.erase(s.find_last_not_of(" \n\r\t\v\f") + 1); } void GumboInterface::ltrim(std::string &s) { s.erase(0, s.find_first_not_of(" \n\r\t\v\f")); } void GumboInterface::ltrimnewlines(std::string &s) { s.erase(0, s.find_first_not_of("\n\r")); } // delete everything up to and including the newline void GumboInterface::newlinetrim(std::string &s) { size_t pos = s.find("\n"); if (pos != std::string::npos) { s.erase(0, pos + 1); } } void GumboInterface::condense_whitespace(std::string &s) { size_t n = s.length(); std::string val; val.reserve(n); std::string wspace = " \n\r\t\v\f"; char last_c = 'x'; for (size_t i = 0; i < n; i++) { char c = s.at(i); if (wspace.find(c) != std::string::npos) { c = ' '; } if ((c != ' ') || (last_c != ' ')) { val.push_back(c); } last_c = c; } s = val; } void GumboInterface::replace_all(std::string &s, const char * s1, const char * s2) { std::string t1(s1); size_t len = t1.length(); size_t pos = s.find(t1); while (pos != std::string::npos) { s.replace(pos, len, s2); pos = s.find(t1, pos + len); } } std::string GumboInterface::update_attribute_value(const std::string &attvalue) { std::string result = attvalue; std::string attpath = UrlUtil::UrlDecode(attvalue); std::size_t fragpos = attpath.rfind(POUND_SIGN); bool has_fragment = fragpos != std::string::npos; std::string fragment = ""; if (has_fragment) { fragment = attpath.substr(fragpos, attpath.length() - fragpos); attpath = attpath.substr(0, fragpos); } std::string search_key = attpath; std::string new_href; if (m_sourceupdates.find(search_key) != m_sourceupdates.end()) { new_href = m_sourceupdates.at(search_key); } if (!new_href.empty()) { new_href += fragment; result = new_href; } return result; } std::string GumboInterface::update_style_urls(const std::string &source) { std::string result = source; // pcrecpp::RE_Options opt; // opt.set_utf8(true); // opt.set_caseless(true); // opt.set_multiline(true); // const std::string // EXTRACT_STYLE_URL( // "(?:(?:src|background|background-image|list-style|list-style-image|border-image|border-image-source|content)\\s*:|@import)\\s*" // "[^;\\}\\(\"']*" // "(?:" // "url\\([\"']?([^\\(\\)\"']*)[\"']?\\)" // "|" // "[\"']([^\\(\\)\"']*)[\"']" // ")"); // // const std::string // MATCH_STYLE_URL( // "((src|background|background-image|list-style|list-style-image|border-image|border-image-source|content)(\\s*:|@import)(\\s*" // "[^;\\}\\(\"']*" // "url\\([\"']?([^\\(\\)\"']*)[\"']?\\)" // "|" // "[\"']([^\\(\\)\"']*)[\"']" // "))"); // // const std::string REPLACE_URL = ":.*(url\\s*\\([^\\)]+\\))"; // pcrecpp::RE reMatch = pcrecpp::RE(MATCH_STYLE_URL, opt); // pcrecpp::RE reExtract = pcrecpp::RE(EXTRACT_STYLE_URL, opt); // pcrecpp::RE reReplace = pcrecpp::RE(REPLACE_URL, opt); // std::string findStr; // std::string findStrCopy; // std::string findStrExtract; // pcrecpp::StringPiece inSp(source); // pcrecpp::StringPiece inSpExtract(source); // // while(reMatch.FindAndConsume(&inSp, &findStr)){ // findStrCopy = findStr; // reExtract.FindAndConsume(&inSpExtract, &findStrExtract); // std::string new_href; // if (m_sourceupdates.find(findStrExtract) != m_sourceupdates.end()) { // new_href = m_sourceupdates.at(findStrExtract); // reReplace.Replace(std::string(":url(")+ new_href + ")",&findStrCopy); // result.erase(result.size() - inSp.size() - findStr.size(),findStr.size()); // result.insert(result.size() - inSp.size(),findStrCopy.c_str()); // } // } return result; } std::string GumboInterface::substitute_xml_entities_into_text( const std::string &text) { std::string result = text; // replacing & must come first replace_all(result, "&", "&amp;"); replace_all(result, "<", "&lt;"); replace_all(result, ">", "&gt;"); // convert non-breaking spaces to entities to prevent their loss for later editing // See the strange//buggy behaviour of Qt QTextDocument toPlainText() routine if (m_hasnbsp) { replace_all(result, "\xc2\xa0", "&nbsp;"); } else { replace_all(result, "\xc2\xa0", "&#160;"); } return result; } std::string GumboInterface::substitute_xml_entities_into_attributes(char quote, const std::string &text) { std::string result = substitute_xml_entities_into_text(text); if (quote == '"') { replace_all(result, "\"", "&quot;"); } else if (quote == '\'') { replace_all(result, "'", "&apos;"); } return result; } std::string GumboInterface::get_tag_name(GumboNode *node) { std::string tagname; if (node->type == GUMBO_NODE_DOCUMENT) { tagname = "#document"; return tagname; } else if ((node->type == GUMBO_NODE_TEXT) || (node->type == GUMBO_NODE_WHITESPACE)) { tagname = "#text"; return tagname; } else if (node->type == GUMBO_NODE_CDATA) { tagname = "#cdata"; return tagname; } tagname = gumbo_normalized_tagname(node->v.element.tag); if ((tagname.empty()) || (node->v.element.tag_namespace == GUMBO_NAMESPACE_SVG)) { // set up to examine original text of tag. GumboStringPiece gsp = node->v.element.original_tag; gumbo_tag_from_original_text(&gsp); // special handling for some svg tag names. if (node->v.element.tag_namespace == GUMBO_NAMESPACE_SVG) { const char * data = gumbo_normalize_svg_tagname(&gsp); // NOTE: data may not be null-terminated! // since case change only - length must be same as original // if no replacement found returns null, not original tag! if (data != NULL) { return std::string(data, gsp.length); } } if (tagname.empty()) { return std::string(gsp.data, gsp.length); } } return tagname; } // if missing leave it alone // if epub3 docytpe use it otherwise set it to epub2 docytpe std::string GumboInterface::build_doctype(GumboNode *node) { std::string two("2"); std::string three("3"); std::string results = ""; if (StringUtil::startWith(m_version, two)) { results.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"); results.append( " \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n"); return results; } else if (StringUtil::startWith(m_version, three)) { results.append("<!DOCTYPE html>\n\n"); return results; } if (node->v.document.has_doctype) { std::string name(node->v.document.name); std::string pi(node->v.document.public_identifier); std::string si(node->v.document.system_identifier); if ((name == "html") && pi.empty() && si.empty()) { results.append("<!DOCTYPE html>\n\n"); return results; } else { results.append( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"); results.append( " \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n\n"); } } return results; } // deal properly with foreign namespaced attributes std::string GumboInterface::get_attribute_name(GumboAttribute * at) { std::string attr_name = at->name; GumboAttributeNamespaceEnum attr_ns = at->attr_namespace; if ((attr_ns == GUMBO_ATTR_NAMESPACE_NONE) || (attr_name == "xmlns")) { return attr_name; } attr_name = std::string(attribute_nsprefixes[attr_ns]) + attr_name; return attr_name; } std::string GumboInterface::build_attributes(GumboAttribute * at, bool no_entities, bool run_src_updates, bool run_style_updates) { std::string atts = " "; std::string name = get_attribute_name(at); std::string local_name = at->name; atts.append(name); std::string attvalue = at->value; if (run_src_updates && (local_name == aHREF || local_name == aSRC || local_name == aPOSTER || local_name == aDATA)) { attvalue = update_attribute_value(attvalue); } if (run_style_updates && (local_name == "style")) { attvalue = update_style_urls(attvalue); } // we handle empty attribute values like so: alt="" char quote = '"'; std::string qs = "\""; // verify an original value existed since we create our own attributes // and if so determine the original quote character used if any if (at->original_value.data) { if ((!attvalue.empty()) || (at->original_value.data[0] == '"') || (at->original_value.data[0] == '\'')) { quote = at->original_value.data[0]; if (quote == '\'') qs = std::string("'"); if (quote == '"') qs = std::string("\""); } } atts.append("="); atts.append(qs); if (no_entities) { atts.append(attvalue); } else { atts.append(substitute_xml_entities_into_attributes(quote, attvalue)); } atts.append(qs); return atts; } // serialize children of a node // may be invoked recursively std::string GumboInterface::serialize_contents(GumboNode* node, enum UpdateTypes doupdates) { std::string contents = ""; std::string tagname = get_tag_name(node); bool no_entity_substitution = in_set(no_entity_sub, tagname); bool keep_whitespace = in_set(preserve_whitespace, tagname); bool is_inline = in_set(nonbreaking_inline, tagname); bool is_structural = in_set(structural_tags, tagname); // build up result for each child, recursively if need be GumboVector* children = &node->v.element.children; bool inject_newline = false; bool in_head_without_title = (tagname == "head"); for (unsigned int i = 0; i < children->length; ++i) { GumboNode* child = static_cast<GumboNode*> (children->data[i]); if (child->type == GUMBO_NODE_TEXT) { std::string text; if (no_entity_substitution) { text = std::string(child->v.text.text); } else { text = substitute_xml_entities_into_text( std::string(child->v.text.text)); } if (inject_newline && !text.empty() && (text.at(0) == '\n')) text.erase(0, 1); inject_newline = false; contents.append(text); } else if (child->type == GUMBO_NODE_ELEMENT || child->type == GUMBO_NODE_TEMPLATE) { contents.append(serialize(child, doupdates)); inject_newline = false; std::string childname = get_tag_name(child); if (in_head_without_title && (childname == "title")) in_head_without_title = false; if (!is_inline && !keep_whitespace && !in_set(nonbreaking_inline, childname) && is_structural) { contents.append("\n"); inject_newline = true; } } else if (child->type == GUMBO_NODE_WHITESPACE) { // try to keep all whitespace to keep as close to original as possible std::string wspace = std::string(child->v.text.text); if (inject_newline) { newlinetrim(wspace); inject_newline = false; } contents.append(wspace); inject_newline = false; } else if (child->type == GUMBO_NODE_CDATA) { contents.append( "<![CDATA[" + std::string(child->v.text.text) + "]]>"); inject_newline = false; } else if (child->type == GUMBO_NODE_COMMENT) { contents.append("<!--" + std::string(child->v.text.text) + "-->"); } else { fprintf(stderr, "unknown element of type: %d\n", child->type); inject_newline = false; } } if (in_head_without_title) contents.append("<title></title>"); return contents; } // serialize a GumboNode back to html/xhtml // may be invoked recursively std::string GumboInterface::serialize(GumboNode* node, enum UpdateTypes doupdates) { // special case the document node if (node->type == GUMBO_NODE_DOCUMENT) { std::string results = build_doctype(node); results.append(serialize_contents(node, doupdates)); return results; } std::string close = ""; std::string closeTag = ""; std::string atts = ""; std::string tagname = get_tag_name(node); bool need_special_handling = in_set(special_handling, tagname); bool is_void_tag = in_set(void_tags, tagname); bool no_entity_substitution = in_set(no_entity_sub, tagname); bool is_href_src_tag = in_set(href_src_tags, tagname); bool in_xml_ns = node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML; // bool is_inline = in_set(nonbreaking_inline, tagname); // build attr string const GumboVector * attribs = &node->v.element.attributes; for (unsigned int i = 0; i < attribs->length; ++i) { GumboAttribute* at = static_cast<GumboAttribute*> (attribs->data[i]); atts.append( build_attributes(at, no_entity_substitution, ((doupdates & SourceUpdates) && is_href_src_tag), (doupdates & StyleUpdates))); } // Make sure that the xmlns attribute exists as an html tag attribute if (tagname == "html") { if (atts.find("xmlns=") == std::string::npos) { atts.append(" xmlns=\"http://www.w3.org/1999/xhtml\""); } } // determine contents std::string contents; if ((tagname == "body") && (doupdates & BodyUpdates)) { contents = m_newbody; } else { // serialize your contents contents = serialize_contents(node, doupdates); } // determine closing tag type std::string testcontents = contents; ltrim(testcontents); if (is_void_tag || (in_xml_ns && testcontents.empty())) { close = "/"; } else { closeTag = "</" + tagname + ">"; } if ((doupdates & StyleUpdates) && (tagname == "style") && (node->parent->type == GUMBO_NODE_ELEMENT) && (node->parent->v.element.tag == GUMBO_TAG_HEAD)) { contents = update_style_urls(contents); } if (need_special_handling) { ltrimnewlines(contents); rtrim(contents); contents.append("\n"); } // build results std::string results; if ((doupdates & LinkUpdates) && (tagname == "link") && (node->parent->type == GUMBO_NODE_ELEMENT) && (node->parent->v.element.tag == GUMBO_TAG_HEAD)) { return ""; } results.append("<" + tagname + atts + close + ">"); if (need_special_handling) results.append("\n"); results.append(contents); if ((doupdates & LinkUpdates) && (tagname == "head")) { results.append(m_newcsslinks); } results.append(closeTag); if (need_special_handling) results.append("\n"); return results; } std::string GumboInterface::prettyprint_contents(GumboNode* node, int lvl, const std::string indent_chars) { std::string contents = ""; std::string tagname = get_tag_name(node); bool no_entity_substitution = in_set(no_entity_sub, tagname); bool keep_whitespace = in_set(preserve_whitespace, tagname); bool is_inline = in_set(nonbreaking_inline, tagname); bool is_structural = in_set(structural_tags, tagname); char c = indent_chars.at(0); int n = indent_chars.length(); std::string indent_space = std::string((lvl - 1) * n, c); char last_char = 'x'; bool contains_block_tags = false; GumboVector* children = &node->v.element.children; if (is_structural || (tagname == "#document")) last_char = '\n'; bool in_head_without_title = (tagname == "head"); for (unsigned int i = 0; i < children->length; ++i) { GumboNode* child = static_cast<GumboNode*> (children->data[i]); if (child->type == GUMBO_NODE_TEXT) { std::string val; if (no_entity_substitution) { val = std::string(child->v.text.text); } else { val = substitute_xml_entities_into_text( std::string(child->v.text.text)); } // if child of a structual element is text and follows a newline, indent it properly if (is_structural && last_char == '\n') { contents.append(indent_space); ltrim(val); } if (!keep_whitespace && !is_structural) { // okay to condense whitespace condense_whitespace(val); } contents.append(val); } else if (child->type == GUMBO_NODE_ELEMENT || child->type == GUMBO_NODE_TEMPLATE) { std::string val = prettyprint(child, lvl, indent_chars); std::string childname = get_tag_name(child); if (in_head_without_title && (childname == "title")) in_head_without_title = false; if (!in_set(nonbreaking_inline, childname)) { contains_block_tags = true; if (last_char != '\n') { contents.append("\n"); if (tagname != "head" && tagname != "html") contents.append("\n"); last_char = '\n'; } } // if child of a structual element is inline and follows a newline, indent it properly if (is_structural && in_set(nonbreaking_inline, childname) && (last_char == '\n')) { contents.append(indent_space); ltrim(val); } contents.append(val); } else if (child->type == GUMBO_NODE_WHITESPACE) { if (keep_whitespace) { std::string wspace = std::string(child->v.text.text); contents.append(wspace); } else if (is_inline || in_set(other_text_holders, tagname)) { if (std::string(" \t\v\f\r\n").find(last_char) == std::string::npos) { contents.append(std::string(" ")); } } } else if (child->type == GUMBO_NODE_CDATA) { contents.append( "<![CDATA[" + std::string(child->v.text.text) + "]]>"); } else if (child->type == GUMBO_NODE_COMMENT) { contents.append("<!--" + std::string(child->v.text.text) + "-->"); } else { fprintf(stderr, "unknown element of type: %d\n", child->type); } // update last character of current contents if (!contents.empty()) { last_char = contents.at(contents.length() - 1); } } // inject epmpty title into head if one is missing if (in_head_without_title) { if (last_char != '\n') contents.append("\n"); contents.append(indent_space + "<title></title>\n"); last_char = '\n'; } // treat inline tags containing block tags like a block tag if (is_inline && contains_block_tags) { if (last_char != '\n') contents.append("\n\n"); contents.append(indent_space); } return contents; } // prettyprint a GumboNode back to html/xhtml // may be invoked recursively std::string GumboInterface::prettyprint(GumboNode* node, int lvl, const std::string indent_chars) { // special case the document node if (node->type == GUMBO_NODE_DOCUMENT) { std::string results = build_doctype(node); results.append(prettyprint_contents(node, lvl + 1, indent_chars)); return results; } std::string tagname = get_tag_name(node); std::string parentname = get_tag_name(node->parent); bool in_head = (parentname == "head"); bool is_structural = in_set(structural_tags, tagname); bool is_inline = in_set(nonbreaking_inline, tagname); bool in_xml_ns = node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML; // build attr string std::string atts = ""; bool no_entity_substitution = in_set(no_entity_sub, tagname); const GumboVector * attribs = &node->v.element.attributes; for (unsigned int i = 0; i < attribs->length; ++i) { GumboAttribute* at = static_cast<GumboAttribute*> (attribs->data[i]); atts.append(build_attributes(at, no_entity_substitution)); } bool is_void_tag = in_set(void_tags, tagname); // get tag contents std::string contents = ""; if (!is_void_tag) { if (is_structural && tagname != "html") { contents = prettyprint_contents(node, lvl + 1, indent_chars); } else { contents = prettyprint_contents(node, lvl, indent_chars); } } bool keep_whitespace = in_set(preserve_whitespace, tagname); if (!keep_whitespace && !is_inline) { rtrim(contents); } std::string testcontents = contents; ltrim(testcontents); bool single = is_void_tag || (in_xml_ns && testcontents.empty()); char c = indent_chars.at(0); int n = indent_chars.length(); std::string indent_space = std::string((lvl - 1) * n, c); // handle self-closed tags with no contents first if (single) { std::string selfclosetag = "<" + tagname + atts + "/>"; if (is_inline) { // always add newline after br tags when they are children of structural tags if ((tagname == "br") && in_set(structural_tags, parentname)) { selfclosetag.append("\n"); if (!in_head && (tagname != "html")) selfclosetag.append("\n"); } return selfclosetag; } if (!in_head && (tagname != "html")) selfclosetag.append("\n"); return indent_space + selfclosetag + "\n"; } // Handle the general case std::string results; std::string starttag = "<" + tagname + atts + ">"; std::string closetag = "</" + tagname + ">"; if (is_structural) { results = indent_space + starttag; if (!contents.empty()) { results.append("\n" + contents + "\n" + indent_space); } results.append(closetag + "\n"); if (!in_head && (tagname != "html")) results.append("\n"); } else if (is_inline) { results = starttag; results.append(contents); results.append(closetag); } else /** all others */{ results = indent_space + starttag; if (!keep_whitespace) { ltrim(contents); } results.append(contents); results.append(closetag + "\n"); if (!in_head && (tagname != "html")) results.append("\n"); } return results; } }
31.977964
149
0.643348
luojilab
d526727055b3a97048584f86c03f0a79d2af5c06
5,116
cpp
C++
src/libSBML/src/sbml/validator/constraints/CompartmentOutsideCycles.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
5
2015-04-16T14:27:38.000Z
2021-11-30T14:54:39.000Z
src/libSBML/src/sbml/validator/constraints/CompartmentOutsideCycles.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
8
2017-05-30T16:58:39.000Z
2022-02-22T16:51:34.000Z
src/libSBML/src/sbml/validator/constraints/CompartmentOutsideCycles.cpp
copasi/copasi-dependencies
c01dd455c843522375c32c2989aa8675f59bb810
[ "Unlicense" ]
7
2016-05-29T08:12:59.000Z
2019-05-02T13:39:25.000Z
/** * @cond doxygenLibsbmlInternal * * @file CompartmentOutsideCycles.cpp * @brief Ensures no cycles exist via a Compartment's 'outside' attribute. * @author Ben Bornstein * * <!-------------------------------------------------------------------------- * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. * * Copyright (C) 2020 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * 3. University College London, London, UK * * Copyright (C) 2019 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2013-2018 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * 3. University of Heidelberg, Heidelberg, Germany * * Copyright (C) 2009-2013 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK * * Copyright (C) 2006-2008 by the California Institute of Technology, * Pasadena, CA, USA * * Copyright (C) 2002-2005 jointly by the following organizations: * 1. California Institute of Technology, Pasadena, CA, USA * 2. Japan Science and Technology Agency, Japan * * 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. A copy of the license agreement is provided * in the file named "LICENSE.txt" included with this software distribution * and also available online as http://sbml.org/software/libsbml/license.html * ---------------------------------------------------------------------- -->*/ #include <sbml/Model.h> #include <sbml/Compartment.h> #include <sbml/util/IdList.h> #include "CompartmentOutsideCycles.h" /** @cond doxygenIgnored */ using namespace std; /** @endcond */ LIBSBML_CPP_NAMESPACE_BEGIN /* * Creates a new Constraint with the given @p id. */ CompartmentOutsideCycles::CompartmentOutsideCycles ( unsigned int id, Validator& v ) : TConstraint<Model>(id, v) { } /* * Destroys this Constraint. */ CompartmentOutsideCycles::~CompartmentOutsideCycles () { } /* * Checks that no Compartments in Model have a cycle via their 'outside' * attribute. * * Sets mHolds to true if no cycles are found, false otherwise. */ void CompartmentOutsideCycles::check_ (const Model& m, const Model&) { for (unsigned int n = 0; n < m.getNumCompartments(); n++) { checkForCycle(m, m.getCompartment(n)); } mCycles.clear(); } /* * Checks for a cycle by following Compartment c's 'outside' attribute. If * a cycle is found, it is added to the list of found cycles, mCycles. */ void CompartmentOutsideCycles::checkForCycle (const Model& m, const Compartment* c) { IdList visited; while (c != NULL && !isInCycle(c)) { const string& id = c->getId(); if ( visited.contains(id) ) { visited.removeIdsBefore(id); mCycles.push_back(visited); logCycle(c, visited); break; } visited.append(id); c = c->isSetOutside() ? m.getCompartment( c->getOutside() ) : NULL; } } /* * Function Object: Returns true if Compartment c is contained in the given * IdList cycle. */ struct CycleContains { CycleContains (const Compartment* c) : id(c->getId()) { } bool operator() (const IdList& lst) const { return lst.contains(id); } const string& id; }; /* * @return @c true if Compartment c is contained in one of the already found * cycles, false otherwise. */ bool CompartmentOutsideCycles::isInCycle (const Compartment* c) { vector<IdList>::iterator end = mCycles.end(); return find_if(mCycles.begin(), end, CycleContains(c)) != end; } /* * Logs a message about a cycle found starting at Compartment c. */ void CompartmentOutsideCycles::logCycle (const Compartment* c, const IdList& cycle) { //msg = // "A <compartment> may not enclose itself through a chain of references " // "involving the 'outside' field. This means that a compartment cannot " // "have its own identifier as the value of 'outside', nor can it point to " // "another compartment whose 'outside' field points directly or indirectly " // "to the compartment. (References: L2V1 erratum 11; L2V2 Section 4.7.7.) "; msg = "Compartment '" + c->getId() + "' encloses itself"; if (cycle.size() > 1) { IdList::const_iterator iter = cycle.begin(); IdList::const_iterator end = cycle.end(); msg += " via '" + *iter++ + "'"; while (iter != end) msg += " -> '" + *iter++ + "'"; msg += " -> '" + c->getId() + "'"; } msg += '.'; logFailure(*c); } LIBSBML_CPP_NAMESPACE_END /** @endcond */
27.956284
80
0.654222
copasi
d5267776d7ddbb314b5aca590f788392546d2329
884
hpp
C++
Siv3D/include/Siv3D/Physics2D/P2BodyType.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
709
2016-03-19T07:55:58.000Z
2022-03-31T08:02:22.000Z
Siv3D/include/Siv3D/Physics2D/P2BodyType.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
415
2017-05-21T05:05:02.000Z
2022-03-29T16:08:27.000Z
Siv3D/include/Siv3D/Physics2D/P2BodyType.hpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
123
2016-03-19T12:47:08.000Z
2022-03-25T03:47:51.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "../Common.hpp" namespace s3d { /// @brief 物体の種類に関するフラグ enum class P2BodyType : uint8 { /// @brief 物体は常に固定され、力の影響を受けません。地面や壁などに使います。 Static, /// @brief 物体は力の影響を受けませんが、移動することができます。動く床などに使います。 Kinematic, /// @brief 物体は力の影響を受けて動き回ります。 Dynamic }; /// @brief `P2BodyType::Static` の省略表記です。 inline constexpr P2BodyType P2Static = P2BodyType::Static; /// @brief `P2BodyType::Kinematic` の省略表記です。 inline constexpr P2BodyType P2Kinematic = P2BodyType::Kinematic; /// @brief `P2BodyType::Dynamic` の省略表記です。 inline constexpr P2BodyType P2Dynamic = P2BodyType::Dynamic; }
22.666667
65
0.631222
emadurandal
d527fabc2345d9850127221c934ccf808739c9d3
860
cpp
C++
Raspi backup/final/real_real_final/system_management.cpp
radii-dev/rpi3-self-driving-model-shuttle-bus
f3f050f517b33c09f0552d09fc5094d795226c75
[ "MIT" ]
null
null
null
Raspi backup/final/real_real_final/system_management.cpp
radii-dev/rpi3-self-driving-model-shuttle-bus
f3f050f517b33c09f0552d09fc5094d795226c75
[ "MIT" ]
null
null
null
Raspi backup/final/real_real_final/system_management.cpp
radii-dev/rpi3-self-driving-model-shuttle-bus
f3f050f517b33c09f0552d09fc5094d795226c75
[ "MIT" ]
null
null
null
#include "system_management.h" std::ofstream fileout("log"); System_resource::System_resource() { sysinfo(&memInfo); totalVirtualMem = memInfo.totalram; totalVirtualMem += memInfo.totalswap; totalVirtualMem *= memInfo.mem_unit; totalPhysMem = memInfo.totalram; totalPhysMem *= memInfo.mem_unit; } uint64_t System_resource::getTotalVirtualMem() { return totalVirtualMem; } uint64_t System_resource::getVirtualMemUsed() { virtualMemUsed = memInfo.totalram - memInfo.freeram; virtualMemUsed += memInfo.totalswap - memInfo.freeswap; virtualMemUsed *= memInfo.mem_unit; return virtualMemUsed; } uint64_t System_resource::getTotalPhysMem() { return totalPhysMem; } uint64_t System_resource::getPhysMemUsed() { physMemUsed = memInfo.totalram - memInfo.freeram; physMemUsed *= memInfo.mem_unit; return physMemUsed; } System_resource system_resource;
23.243243
56
0.790698
radii-dev
d52981f986e594e9ef98cc4ce1c56ba8027e82f7
1,518
cpp
C++
OpencvBuild/Opencv/Opencv/core/perf/perf_sort.cpp
kevinlq/Opencv-module-build
73ca967ff994e0c86f2537e273040807e7250897
[ "MIT" ]
3
2017-11-02T15:12:14.000Z
2021-06-03T06:10:48.000Z
OpencvBuild/Opencv/Opencv/core/perf/perf_sort.cpp
kevinlq/Opencv-module-build
73ca967ff994e0c86f2537e273040807e7250897
[ "MIT" ]
null
null
null
OpencvBuild/Opencv/Opencv/core/perf/perf_sort.cpp
kevinlq/Opencv-module-build
73ca967ff994e0c86f2537e273040807e7250897
[ "MIT" ]
3
2018-01-03T15:11:21.000Z
2019-05-31T03:21:01.000Z
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::tuple; using std::tr1::make_tuple; using std::tr1::get; #define TYPICAL_MAT_SIZES_SORT TYPICAL_MAT_SIZES #define TYPICAL_MAT_TYPES_SORT CV_8UC1, CV_16UC1, CV_32FC1 #define SORT_TYPES SORT_EVERY_ROW | SORT_ASCENDING, SORT_EVERY_ROW | SORT_DESCENDING #define TYPICAL_MATS_SORT testing::Combine( testing::Values(TYPICAL_MAT_SIZES_SORT), testing::Values(TYPICAL_MAT_TYPES_SORT), testing::Values(SORT_TYPES) ) typedef tuple<Size, MatType, int> sortParams; typedef TestBaseWithParam<sortParams> sortFixture; PERF_TEST_P(sortFixture, sort, TYPICAL_MATS_SORT) { const sortParams params = GetParam(); const Size sz = get<0>(params); const int type = get<1>(params), flags = get<2>(params); cv::Mat a(sz, type), b(sz, type); declare.in(a, WARMUP_RNG).out(b); TEST_CYCLE() cv::sort(a, b, flags); SANITY_CHECK(b); } typedef sortFixture sortIdxFixture; #undef SORT_TYPES #define SORT_TYPES SORT_EVERY_COLUMN | SORT_ASCENDING, SORT_EVERY_COLUMN | SORT_DESCENDING PERF_TEST_P(sortIdxFixture, sorIdx, TYPICAL_MATS_SORT) { const sortParams params = GetParam(); const Size sz = get<0>(params); const int type = get<1>(params), flags = get<2>(params); cv::Mat a(sz, type), b(sz, type); declare.in(a, WARMUP_RNG).out(b); TEST_CYCLE() cv::sortIdx(a, b, flags); SANITY_CHECK_NOTHING(); }
28.641509
162
0.700264
kevinlq
d52a2e3d7bc726d86fdc5b6f25baffcad0df83ff
7,246
cpp
C++
BlackBone/src/BlackBone/LocalHook/LocalHookBase.cpp
wafflehammer/MonoInjector
bc7680a2ec8be606f5fdc8614c0c991a1d074382
[ "MIT" ]
354
2018-08-13T18:19:21.000Z
2022-03-20T10:37:20.000Z
Protection/BlackBone/src/BlackBone/LocalHook/LocalHookBase.cpp
Bia10/ZzukBot_V3
55abfb38fd07ba970d4b4020d8d96b87559509db
[ "Unlicense" ]
6
2017-08-03T03:40:56.000Z
2021-10-18T22:12:58.000Z
Protection/BlackBone/src/BlackBone/LocalHook/LocalHookBase.cpp
Bia10/ZzukBot_V3
55abfb38fd07ba970d4b4020d8d96b87559509db
[ "Unlicense" ]
90
2018-11-15T12:37:51.000Z
2022-02-14T11:12:39.000Z
#include "LocalHookBase.h" namespace blackbone { std::unordered_map<void*, DetourBase*> DetourBase::_breakpoints; void* DetourBase::_vecHandler = nullptr; DetourBase::DetourBase() { } DetourBase::~DetourBase() { VirtualFree( _buf, 0, MEM_RELEASE ); } /// <summary> /// Allocate detour buffer as close to target as possible /// </summary> /// <param name="nearest">Target address</param> /// <returns>true on success</returns> bool DetourBase::AllocateBuffer( uint8_t* nearest ) { if (_buf != nullptr) return true; MEMORY_BASIC_INFORMATION mbi = { 0 }; for (SIZE_T addr = (SIZE_T)nearest; addr > (SIZE_T)nearest - 0x80000000; addr = (SIZE_T)mbi.BaseAddress - 1) { if (!VirtualQuery( (LPCVOID)addr, &mbi, sizeof( mbi ) )) break; if (mbi.State == MEM_FREE) { _buf = (uint8_t*)VirtualAlloc( (uint8_t*)mbi.BaseAddress + mbi.RegionSize - 0x1000, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE ); if (_buf) break; } } // If allocating a memory page failed, allocate first suitable if (_buf == nullptr) _buf = (uint8_t*)VirtualAlloc( nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE ); _origCode = _buf + 0x100; _newCode = _buf + 0x200; return _buf != nullptr; } /// <summary> /// Temporarily disable hook /// </summary> /// <returns>true on success</returns> bool DetourBase::DisableHook() { if (_type == HookType::InternalInline || _type == HookType::Int3) WriteProcessMemory( GetCurrentProcess(), _original, _origCode, _origSize, NULL ); else if (_type == HookType::HWBP) ToggleHBP( _hwbpIdx[GetCurrentThreadId()], false ); return true; } /// <summary> /// Enable disabled hook /// </summary> /// <returns>true on success</returns> bool DetourBase::EnableHook() { if (_type == HookType::InternalInline || _type == HookType::Int3) WriteProcessMemory( GetCurrentProcess(), _original, _newCode, _origSize, NULL ); else if (_type == HookType::HWBP) ToggleHBP( _hwbpIdx[GetCurrentThreadId()], true ); return true; } /// <summary> /// Toggle hardware breakpoint for current thread /// </summary> /// <param name="index">Breakpoint index ( 0-4 )</param> /// <param name="enable">true to enable, false to disable</param> /// <returns>true on success</returns> bool DetourBase::ToggleHBP( int index, bool enable ) { CONTEXT context = { 0 }; context.ContextFlags = CONTEXT_DEBUG_REGISTERS; if (GetThreadContext( GetCurrentThread(), &context ) != TRUE) return FALSE; if (enable) BitTestAndSetT( (LONG_PTR*)&context.Dr7, 2 * index ); else BitTestAndResetT( (LONG_PTR*)&context.Dr7, 2 * index ); return (SetThreadContext( GetCurrentThread(), &context ) != FALSE); } /// <summary> /// Copy original function bytes /// </summary> /// <param name="Ptr">Origianl function address</param> void DetourBase::CopyOldCode( uint8_t* ptr ) { // Store original bytes uint8_t* src = ptr; uint8_t* old = (uint8_t*)_origCode; uint32_t all_len = 0; ldasm_data ld = { 0 }; do { uint32_t len = ldasm( src, &ld, is_x64 ); // Determine code end if (ld.flags & F_INVALID || (len == 1 && (src[ld.opcd_offset] == 0xCC || src[ld.opcd_offset] == 0xC3)) || (len == 3 && src[ld.opcd_offset] == 0xC2) || len + all_len > 128) { break; } // move instruction memcpy( old, src, len ); // if instruction has relative offset, calculate new offset if (ld.flags & F_RELATIVE) { int32_t diff = 0; const uintptr_t ofst = (ld.disp_offset != 0 ? ld.disp_offset : ld.imm_offset); const uintptr_t sz = ld.disp_size != 0 ? ld.disp_size : ld.imm_size; memcpy( &diff, src + ofst, sz ); #ifdef USE64 // exit if jump is greater then 2GB if (_abs64( src + len + diff - old ) > INT_MAX) { break; } else { diff += static_cast<int32_t>(src - old); memcpy( old + ofst, &diff, sz ); } #else diff += src - old; memcpy( old + ofst, &diff, sz ); #endif } src += len; old += len; all_len += len; } while (all_len < _origSize); // Failed to copy old code, use backup plan if (all_len < _origSize) { _type = HookType::InternalInline; memcpy( _origCode, ptr, _origSize ); } else { SET_JUMP( old, src ); _callOriginal = _origCode; } } /// <summary> /// Exception handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::VectoredHandler( PEXCEPTION_POINTERS excpt ) { switch (excpt->ExceptionRecord->ExceptionCode) { case static_cast<DWORD>(EXCEPTION_BREAKPOINT): return Int3Handler( excpt ); case static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION): return AVHandler( excpt ); case static_cast<DWORD>(EXCEPTION_SINGLE_STEP): return StepHandler( excpt ); default: return EXCEPTION_CONTINUE_SEARCH; } } /// <summary> /// Int3 exception handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::Int3Handler( PEXCEPTION_POINTERS excpt ) { if (_breakpoints.count( excpt->ExceptionRecord->ExceptionAddress )) { DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress]; ((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst; excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } /// <summary> /// Access violation handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::AVHandler( PEXCEPTION_POINTERS /*excpt*/ ) { return EXCEPTION_CONTINUE_SEARCH; } /// <summary> /// Single step exception handler /// </summary> /// <param name="excpt">Exception information</param> /// <returns>Exception disposition</returns> LONG NTAPI DetourBase::StepHandler( PEXCEPTION_POINTERS excpt ) { DWORD index = 0; int found = _BitScanForward( &index, static_cast<DWORD>(excpt->ContextRecord->Dr6) ); if (found != 0 && index < 4 && _breakpoints.count( excpt->ExceptionRecord->ExceptionAddress )) { DetourBase* pInst = _breakpoints[excpt->ExceptionRecord->ExceptionAddress]; // Disable breakpoint at current index BitTestAndResetT( (LONG_PTR*)&excpt->ContextRecord->Dr7, 2 * index ); ((_NT_TIB*)NtCurrentTeb())->ArbitraryUserPointer = (void*)pInst; excpt->ContextRecord->NIP = (uintptr_t)pInst->_internalHandler; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } }
28.085271
112
0.616202
wafflehammer
d52a8639b282d5cb9e6c66ba5def09ad823af4b9
3,195
cpp
C++
csr_uint.cpp
LazyShion/ScaleSCAN
af553f88209e2f1ceb7be93dd349d380a4196e43
[ "MIT" ]
null
null
null
csr_uint.cpp
LazyShion/ScaleSCAN
af553f88209e2f1ceb7be93dd349d380a4196e43
[ "MIT" ]
null
null
null
csr_uint.cpp
LazyShion/ScaleSCAN
af553f88209e2f1ceb7be93dd349d380a4196e43
[ "MIT" ]
1
2021-11-22T16:33:50.000Z
2021-11-22T16:33:50.000Z
#include<iostream> #include<fstream> #include<map> #include<vector> #include<cstdlib> #include<algorithm> #include<set> #define CH printf("check!!\n"); using namespace std; int main(int argc,char *argv[]) { ifstream infile1(argv[1]); ofstream outfile(argv[2],ios_base::out | ios_base::binary); string str1,str2; unsigned int node1,node2; map<unsigned int , unsigned int> mp2; unsigned int node_count; node_count = 0; unsigned int index_size = 0; cout << "create_node_number_map" << endl; while(getline(infile1,str1,'\t')){ getline(infile1,str2); node1 = atoi(str1.c_str()); node2 = atoi(str2.c_str()); if(node1 != node2){ if(mp2.find(node1) == mp2.end()){ mp2[node1] = node_count; node_count++; } index_size++; if(mp2.find(node2) == mp2.end()){ mp2[node2] = node_count; node_count++; } } } ifstream infile2(argv[1]); unsigned int *edge_list = new unsigned int[index_size*2]; unsigned int edge_count = 0; cout << "create_edge_list" << endl; while(getline(infile2,str1,'\t')){ getline(infile2,str2); node1 = atoi(str1.c_str()); node2 = atoi(str2.c_str()); if(node1 != node2){ edge_list[edge_count] = mp2[node1]; edge_count++; edge_list[edge_count] = mp2[node2]; edge_count++; } } mp2.clear(); unsigned int c = 0; unsigned int *node = new unsigned int[node_count + 1]; node[0] = 0; ofstream log("logfile.txt",ios_base::out | ios_base::binary); cout << "create_node_array" << endl; while(c < node_count){ map<unsigned int,set<unsigned int>> mp; unsigned int c0 = c; unsigned int c2 = c+100000; if(c2 >= node_count){ c2 = node_count; } for(unsigned int i = 0;i < index_size*2;i+=2){ if(c <= edge_list[i] && edge_list[i] < c2){ mp[edge_list[i]].insert(edge_list[i+1]); } if(c <= edge_list[i+1] && edge_list[i+1] < c2){ mp[edge_list[i+1]].insert(edge_list[i]); } } while(c<c2){ unsigned int index = mp[c].size(); node[c+1] = node[c] + index; c++; } unsigned int edgesize = node[c] - node[c0]; cout << edgesize << endl; unsigned int *edge_log = new unsigned int[edgesize]; unsigned int n = 0; // cout << "aaa" << endl; while(c0 < c2){ for(auto itr = mp[c0].begin();itr != mp[c0].end();++itr){ edge_log[n] = *itr; n++; } c0++; } log.write((const char*)&edge_log[0],sizeof(unsigned int)*edgesize); delete[] edge_log; mp.clear(); } cout << "write_file" << endl; unsigned int node_total = node_count + 1; unsigned int edge_total = node[node_count]; outfile.write((const char*)&node_count,sizeof(int)); outfile.write((const char*)&edge_total,sizeof(int)); outfile.write((const char*)&node[0],sizeof(int)*(node_total)); delete[] node; ifstream infile3("logfile.txt",ios_base::in | ios_base::binary); unsigned int *edge = new unsigned int[edge_total]; infile3.read((char*)&edge[0],sizeof(int)*(edge_total)); outfile.write((const char*)(edge),sizeof(int)*(edge_total)); log.close(); remove("logfile.txt"); }
23.492647
71
0.600939
LazyShion
d52ba182a9c2333b3469ec0a46922d3f0c6a6a4c
250
cpp
C++
test/unit/math/mix/fun/log1m_test.cpp
bayesmix-dev/math
3616f7195adc95ef8e719a2af845d61102bc9272
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
test/unit/math/mix/fun/log1m_test.cpp
bayesmix-dev/math
3616f7195adc95ef8e719a2af845d61102bc9272
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
test/unit/math/mix/fun/log1m_test.cpp
bayesmix-dev/math
3616f7195adc95ef8e719a2af845d61102bc9272
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#include <test/unit/math/test_ad.hpp> TEST(mathMixMatFun, log1m) { auto f = [](const auto& x1) { return stan::math::log1m(x1); }; stan::test::expect_common_unary_vectorized(f); stan::test::expect_unary_vectorized(f, -21.5, -21, -1, 0.9, 3); }
31.25
65
0.672
bayesmix-dev
d52ec5d95e092e53994be0f0e575ee1eb387cb9d
22,717
cpp
C++
src/RayTracer/RayTracer.cpp
yuphin/Lumen
a210b5a923b684ed1fc6f047544b82af4fdfe2db
[ "MIT" ]
1
2022-01-07T21:25:53.000Z
2022-01-07T21:25:53.000Z
src/RayTracer/RayTracer.cpp
yuphin/Lumen
a210b5a923b684ed1fc6f047544b82af4fdfe2db
[ "MIT" ]
null
null
null
src/RayTracer/RayTracer.cpp
yuphin/Lumen
a210b5a923b684ed1fc6f047544b82af4fdfe2db
[ "MIT" ]
null
null
null
#include "LumenPCH.h" #include <regex> #include <stb_image.h> #define TINYEXR_IMPLEMENTATION #include <zlib.h> #include <tinyexr.h> #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYOBJLOADER_IMPLEMENTATION #include "RayTracer.h" RayTracer* RayTracer::instance = nullptr; static void fb_resize_callback(GLFWwindow* window, int width, int height) { auto app = reinterpret_cast<RayTracer*>(glfwGetWindowUserPointer(window)); app->resized = true; } RayTracer::RayTracer(int width, int height, bool debug, int argc, char* argv[]) : LumenInstance(width, height, debug) { this->instance = this; parse_args(argc, argv); } void RayTracer::init(Window* window) { srand((uint32_t)time(NULL)); this->window = window; vkb.ctx.window_ptr = window->get_window_ptr(); glfwSetFramebufferSizeCallback(vkb.ctx.window_ptr, fb_resize_callback); // Init with ray tracing extensions vkb.add_device_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME); vkb.add_device_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME); vkb.add_device_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME); vkb.add_device_extension(VK_KHR_SHADER_NON_SEMANTIC_INFO_EXTENSION_NAME); vkb.add_device_extension(VK_EXT_SHADER_ATOMIC_FLOAT_EXTENSION_NAME); vkb.add_device_extension(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME); vkb.create_instance(); if (vkb.enable_validation_layers) { vkb.setup_debug_messenger(); } vkb.create_surface(); vkb.pick_physical_device(); vkb.create_logical_device(); vkb.create_swapchain(); create_default_render_pass(vkb.ctx); vkb.create_framebuffers(vkb.ctx.default_render_pass); vkb.create_command_pool(); vkb.create_command_buffers(); vkb.create_sync_primitives(); initialized = true; scene.load_scene(scene_name); switch (scene.config.integrator_type) { case IntegratorType::Path : integrator = std::make_unique<Path>(this, &scene); break; case IntegratorType::BDPT: integrator = std::make_unique<BDPT>(this, &scene); break; case IntegratorType::SPPM: integrator = std::make_unique<SPPM>(this, &scene); break; case IntegratorType::VCM: integrator = std::make_unique<VCM>(this, &scene); break; case IntegratorType::PSSMLT: integrator = std::make_unique<PSSMLT>(this, &scene); break; case IntegratorType::SMLT: integrator = std::make_unique<SMLT>(this, &scene); break; case IntegratorType::VCMMLT: integrator = std::make_unique<VCMMLT>(this, &scene); break; case IntegratorType::ReSTIR: integrator = std::make_unique<ReSTIR>(this, &scene); break; case IntegratorType::ReSTIRGI: integrator = std::make_unique<ReSTIRGI>(this, &scene); break; case IntegratorType::DDGI: integrator = std::make_unique<DDGI>(this, &scene); break; default: break; } integrator->init(); init_resources(); create_post_descriptor(); update_post_desc_set(); create_post_pipeline(); create_compute_pipelines(); init_imgui(); VkPhysicalDeviceMemoryProperties2 props = {}; props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2; VkPhysicalDeviceMemoryBudgetPropertiesEXT budget_props = {}; budget_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_BUDGET_PROPERTIES_EXT; props.pNext = &budget_props; vkGetPhysicalDeviceMemoryProperties2(vk_ctx.physical_device, &props); printf("Memory usage %f MB\n", budget_props.heapUsage[0] * 1e-6); } void RayTracer::update() { if (instance->window->is_key_down(KeyInput::KEY_F10)) { write_exr = true; } float frame_time = draw_frame(); cpu_avg_time = (1. - 1./ (cnt)) * cpu_avg_time + frame_time / (float)cnt; cpu_avg_time = 0.95 * cpu_avg_time + 0.05 * frame_time; integrator->update(); } void RayTracer::render(uint32_t i) { // Render image integrator->render(); auto cmdbuf = vkb.ctx.command_buffers[i]; VkCommandBufferBeginInfo begin_info = vk::command_buffer_begin_info( VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); vk::check(vkBeginCommandBuffer(cmdbuf, &begin_info)); if (write_exr) { // Copy to host visible storage buffer { VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageExtent.width = instance->width; region.imageExtent.height = instance->height; region.imageExtent.depth = 1; transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); vkCmdCopyImageToBuffer(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, output_img_buffer_cpu.handle, 1, &region); transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL); } } if (calc_rmse && has_gt) { // Calculate RMSE { VkBufferImageCopy region = {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageExtent.width = instance->width; region.imageExtent.height = instance->height; region.imageExtent.depth = 1; transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); vkCmdCopyImageToBuffer(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, output_img_buffer.handle, 1, &region); auto barrier = buffer_barrier(output_img_buffer.handle, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); vkCmdPipelineBarrier(cmdbuf, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_DEPENDENCY_BY_REGION_BIT, 0, 0, 1, &barrier, 0, 0); // Calculate and reduce { vkCmdBindDescriptorSets( cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, calc_rmse_pipeline->pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdBindDescriptorSets( cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, reduce_rmse_pipeline->pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdBindDescriptorSets( cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, output_rmse_pipeline->pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdPushConstants(cmdbuf, calc_rmse_pipeline->pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PostPC), &post_pc); vkCmdPushConstants(cmdbuf, reduce_rmse_pipeline->pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PostPC), &post_pc); vkCmdPushConstants(cmdbuf, output_rmse_pipeline->pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(PostPC), &post_pc); reduce(cmdbuf, residual_buffer, counter_buffer, *calc_rmse_pipeline, *reduce_rmse_pipeline, instance->width * instance->height); vkCmdBindPipeline(cmdbuf, VK_PIPELINE_BIND_POINT_COMPUTE, output_rmse_pipeline->handle); auto num_wgs = 1; vkCmdDispatch(cmdbuf, num_wgs, 1, 1); transition_image_layout(cmdbuf, integrator->output_tex.img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL); } } } // Apply Post FX and present VkClearValue clear_color = { 0.25f, 0.25f, 0.25f, 1.0f }; VkClearValue clear_depth = { 1.0f, 0 }; VkViewport viewport = vk::viewport((float)width, (float)height, 0.0f, 1.0f); VkClearValue clear_values[] = { clear_color, clear_depth }; VkRenderPassBeginInfo post_rpi{ VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; post_rpi.clearValueCount = 2; post_rpi.pClearValues = clear_values; post_rpi.renderPass = vkb.ctx.default_render_pass; post_rpi.framebuffer = vkb.ctx.swapchain_framebuffers[i]; post_rpi.renderArea = { {0, 0}, vkb.ctx.swapchain_extent }; pc_post_settings.enable_tonemapping = settings.enable_tonemapping; vkCmdBeginRenderPass(cmdbuf, &post_rpi, VK_SUBPASS_CONTENTS_INLINE); vkCmdSetViewport(cmdbuf, 0, 1, &viewport); VkRect2D scissor = vk::rect2D(width, height, 0, 0); vkCmdSetScissor(cmdbuf, 0, 1, &scissor); vkCmdBindPipeline(cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, post_pipeline->handle); vkCmdBindDescriptorSets(cmdbuf, VK_PIPELINE_BIND_POINT_GRAPHICS, post_pipeline_layout, 0, 1, &post_desc_set, 0, nullptr); vkCmdPushConstants(cmdbuf, post_pipeline_layout, VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushConstantPost), &pc_post_settings); vkCmdDraw(cmdbuf, 3, 1, 0, 0); ImGui::Render(); ImGui_ImplVulkan_RenderDrawData(ImGui::GetDrawData(), cmdbuf); vkCmdEndRenderPass(cmdbuf); VkClearColorValue val = { 0,0,0,1 }; VkImageSubresourceRange range; range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; range.baseMipLevel = 0; range.levelCount = 1; range.baseArrayLayer = 0; range.layerCount = 1; vk::check(vkEndCommandBuffer(cmdbuf), "Failed to record command buffer"); } float RayTracer::draw_frame() { if (cnt == 0) { start = clock(); } auto t_begin = glfwGetTime() * 1000; bool updated = false; ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); ImGui::Text("Frame time %f ms ( %f FPS )", cpu_avg_time, 1000 / cpu_avg_time); if (ImGui::Button("Reload shaders")) { integrator->reload(); updated |= true; } bool gui_updated = integrator->gui(); updated |= ImGui::Checkbox("Enable ACES tonemapping", &settings.enable_tonemapping); if (updated || gui_updated) { ImGui::Render(); auto t_end = glfwGetTime() * 1000; auto t_diff = t_end - t_begin; integrator->updated = true; return (float)t_diff; } ImGui::Checkbox("Show camera statistics", &show_cam_stats); if (show_cam_stats) { ImGui::PushItemWidth(170); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[0]), 0.05f); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[1]), 0.05f); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[2]), 0.05f); ImGui::DragFloat4("", glm::value_ptr(integrator->camera->camera[3]), 0.05f); } uint32_t image_idx = vkb.prepare_frame(); if (image_idx == UINT32_MAX) { auto t_end = glfwGetTime() * 1000; auto t_diff = t_end - t_begin; return (float)t_diff; } render(image_idx); vkb.submit_frame(image_idx, resized); auto now = clock(); auto diff = ((float)now - start); if (write_exr) { write_exr = false; save_exr((float*)output_img_buffer_cpu.data, instance->width, instance->height, "out.exr"); } bool time_limit = (abs(diff / CLOCKS_PER_SEC - 5)) < 0.1; //calc_rmse = cnt % 30 == 0 || time_limit; //calc_rmse = time_limit; //bool t2 = (abs(diff / CLOCKS_PER_SEC - 10.0)) < 0.1; //if (t2) { // printf("Go!\n"); // t2 = false; //} //printf("Time %f\n", diff / CLOCKS_PER_SEC); //calc_rmse = true; //write_exr = time_limit; if (calc_rmse && has_gt) { float rmse = *(float*)rmse_val_buffer.data; printf("%RMSE: %f - %f\n", rmse * 1e6, diff); } auto t_end = glfwGetTime() * 1000; auto t_diff = t_end - t_begin; cnt++; return (float)t_diff; } void RayTracer::create_post_descriptor() { constexpr int OUTPUT_COLOR_BINDING = 0; constexpr int POST_DESC_BINDING = 1; std::vector<VkDescriptorPoolSize> pool_sizes = { vk::descriptor_pool_size(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1), vk::descriptor_pool_size(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1), }; auto descriptor_pool_ci = vk::descriptor_pool_CI(pool_sizes.size(), pool_sizes.data(), 1); vk::check(vkCreateDescriptorPool(vkb.ctx.device, &descriptor_pool_ci, nullptr, &post_desc_pool), "Failed to create descriptor pool"); std::vector<VkDescriptorSetLayoutBinding> set_layout_bindings = { vk::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT, OUTPUT_COLOR_BINDING), vk::descriptor_set_layout_binding( VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_COMPUTE_BIT, POST_DESC_BINDING), }; auto set_layout_ci = vk::descriptor_set_layout_CI( set_layout_bindings.data(), set_layout_bindings.size()); vk::check(vkCreateDescriptorSetLayout(vkb.ctx.device, &set_layout_ci, nullptr, &post_desc_layout), "Failed to create descriptor set layout"); auto set_allocate_info = vk::descriptor_set_allocate_info(post_desc_pool, &post_desc_layout, 1); vk::check(vkAllocateDescriptorSets(vkb.ctx.device, &set_allocate_info, &post_desc_set), "Failed to allocate descriptor sets"); } void RayTracer::update_post_desc_set() { std::array<VkWriteDescriptorSet, 2> sets = { vk::write_descriptor_set( post_desc_set, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 0, &integrator->output_tex.descriptor_image_info), vk::write_descriptor_set( post_desc_set, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, &post_desc_buffer.descriptor) }; vkUpdateDescriptorSets(vkb.ctx.device, sets.size(), sets.data(), 0, nullptr); } void RayTracer::create_post_pipeline() { GraphicsPipelineSettings post_settings; VkPipelineLayoutCreateInfo create_info{ VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO }; create_info.setLayoutCount = 1; create_info.pSetLayouts = &post_desc_layout; create_info.pushConstantRangeCount = 1; VkPushConstantRange pc_range = { VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(PushConstantPost) }; create_info.pPushConstantRanges = &pc_range; vkCreatePipelineLayout(vkb.ctx.device, &create_info, nullptr, &post_pipeline_layout); post_settings.pipeline_layout = post_pipeline_layout; post_settings.render_pass = vkb.ctx.default_render_pass; post_settings.shaders = { {"src/shaders/post.vert"}, {"src/shaders/post.frag"} }; for (auto& shader : post_settings.shaders) { if (shader.compile()) { LUMEN_ERROR("Shader compilation failed"); } } post_settings.cull_mode = VK_CULL_MODE_NONE; post_settings.enable_tracking = false; post_settings.dynamic_state_enables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; post_pipeline = std::make_unique<Pipeline>(vkb.ctx.device); post_pipeline->create_gfx_pipeline(post_settings); } void RayTracer::create_compute_pipelines() { calc_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device); reduce_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device); output_rmse_pipeline = std::make_unique<Pipeline>(instance->vkb.ctx.device); std::vector<Shader> shaders = { {"src/shaders/rmse/calc_rmse.comp"}, {"src/shaders/rmse/reduce_rmse.comp"}, {"src/shaders/rmse/output_rmse.comp"} }; for (auto& shader : shaders) { shader.compile(); } ComputePipelineSettings settings; settings.desc_set_layouts = &post_desc_layout; settings.desc_set_layout_cnt = 1; settings.push_const_size = sizeof(PostPC); settings.shader = shaders[0]; calc_rmse_pipeline->create_compute_pipeline(settings); settings.shader = shaders[1]; reduce_rmse_pipeline->create_compute_pipeline(settings); settings.shader = shaders[2]; output_rmse_pipeline->create_compute_pipeline(settings); } void RayTracer::init_imgui() { VkDescriptorPoolSize pool_sizes[] = { {VK_DESCRIPTOR_TYPE_SAMPLER, 1000}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1000}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC, 1000}, {VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1000} }; VkDescriptorPoolCreateInfo pool_info = {}; pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; pool_info.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT; pool_info.maxSets = 1000; pool_info.poolSizeCount = (uint32_t)std::size(pool_sizes); pool_info.pPoolSizes = pool_sizes; vk::check(vkCreateDescriptorPool(vkb.ctx.device, &pool_info, nullptr, &imgui_pool)); IMGUI_CHECKVERSION(); ImGui::CreateContext(); // Setup Platform/Renderer backends ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForVulkan(window->get_window_ptr(), true); ImGui_ImplVulkan_InitInfo init_info = {}; init_info.Instance = vkb.ctx.instance; init_info.PhysicalDevice = vkb.ctx.physical_device; init_info.Device = vkb.ctx.device; init_info.Queue = vkb.ctx.queues[(int)QueueType::GFX]; init_info.DescriptorPool = imgui_pool; init_info.MinImageCount = 2; init_info.ImageCount = 2; init_info.MSAASamples = VK_SAMPLE_COUNT_1_BIT; ImGui_ImplVulkan_Init(&init_info, vkb.ctx.default_render_pass); CommandBuffer cmd(&vkb.ctx, true); ImGui_ImplVulkan_CreateFontsTexture(cmd.handle); cmd.submit(vkb.ctx.queues[(int)QueueType::GFX]); ImGui_ImplVulkan_DestroyFontUploadObjects(); } void RayTracer::init_resources() { PostDesc desc; output_img_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, instance->width * instance->height * 4 * 4 ); output_img_buffer_cpu.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_SHARING_MODE_EXCLUSIVE, instance->width * instance->height * 4 * 4 ); residual_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, instance->width * instance->height * 4 ); counter_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, sizeof(int) ); rmse_val_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_SHARING_MODE_EXCLUSIVE, sizeof(float) ); if (load_exr) { // Load the ground truth image const char* img_name = "out.exr"; float* data; int width; int height; const char* err = nullptr; int ret = LoadEXR(&data, &width, &height, img_name, &err); if (ret != TINYEXR_SUCCESS) { if (err) { fprintf(stderr, "ERR : %s\n", err); FreeEXRErrorMessage(err); // release memory of error message. } } else { std::vector<vec4> pixels; int img_res = width * height; pixels.resize(img_res); for (int i = 0; i < img_res; i++) { pixels[i].x = data[4 * i + 0]; pixels[i].y = data[4 * i + 1]; pixels[i].z = data[4 * i + 2]; pixels[i].w = 1.; } auto gt_size = pixels.size() * 4 * 4; gt_img_buffer.create( &instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, gt_size, pixels.data(), true ); desc.gt_img_addr = gt_img_buffer.get_device_address(); has_gt = true; } if (has_gt) { free(data); } } desc.out_img_addr = output_img_buffer.get_device_address(); desc.residual_addr = residual_buffer.get_device_address(); desc.counter_addr = counter_buffer.get_device_address(); desc.rmse_val_addr = rmse_val_buffer.get_device_address(); post_desc_buffer.create(&instance->vkb.ctx, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_SHARING_MODE_EXCLUSIVE, sizeof(PostDesc), &desc, true); post_pc.size = instance->width * instance->height; } void RayTracer::parse_args(int argc, char* argv[]){ scene_name = "scenes/caustics.json"; std::regex fn("(.*).(.json|.xml)"); for (int i = 0; i < argc; i++) { if (std::regex_match(argv[i], fn)) { scene_name = argv[i]; } } } void RayTracer::save_exr(const float* rgb, int width, int height, const char* outfilename) { EXRHeader header; InitEXRHeader(&header); EXRImage image; InitEXRImage(&image); image.num_channels = 3; std::vector<float> images[3]; images[0].resize(width * height); images[1].resize(width * height); images[2].resize(width * height); // Split RGBRGBRGB... into R, G and B layer for (int i = 0; i < width * height; i++) { images[0][i] = rgb[4 * i + 0]; images[1][i] = rgb[4 * i + 1]; images[2][i] = rgb[4 * i + 2]; } float* image_ptr[3]; image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R image.images = (unsigned char**)image_ptr; image.width = width; image.height = height; header.num_channels = 3; header.channels = (EXRChannelInfo*)malloc(sizeof(EXRChannelInfo) * header.num_channels); // Must be (A)BGR order, since most of EXR viewers expect this channel order. strncpy_s(header.channels[0].name, "B", 255); header.channels[0].name[strlen("B")] = '\0'; strncpy_s(header.channels[1].name, "G", 255); header.channels[1].name[strlen("G")] = '\0'; strncpy_s(header.channels[2].name, "R", 255); header.channels[2].name[strlen("R")] = '\0'; header.pixel_types = (int*)malloc(sizeof(int) * header.num_channels); header.requested_pixel_types = (int*)malloc(sizeof(int) * header.num_channels); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // pixel type of output image to be stored in .EXR } const char* err = NULL; // or nullptr in C++11 or later. int ret = SaveEXRImageToFile(&image, &header, outfilename, &err); if (ret != TINYEXR_SUCCESS) { fprintf(stderr, "Save EXR err: %s\n", err); FreeEXRErrorMessage(err); // free's buffer for an error message } printf("Saved exr file. [ %s ] \n", outfilename); free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); } void RayTracer::cleanup() { const auto device = vkb.ctx.device; vkDeviceWaitIdle(device); if (initialized) { vkDestroyDescriptorSetLayout(device, post_desc_layout, nullptr); vkDestroyDescriptorPool(device, post_desc_pool, nullptr); vkDestroyDescriptorPool(device, imgui_pool, nullptr); vkDestroyPipelineLayout(device, post_pipeline_layout, nullptr); ImGui_ImplVulkan_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); gt_img_buffer.destroy(); output_img_buffer.destroy(); integrator->destroy(); post_pipeline->cleanup(); vkb.cleanup(); } }
34.842025
110
0.74693
yuphin
d52fe3d5cf2a04ed0a8620de3137866eaebdb5dc
19,044
cpp
C++
Source/Diagnostics/Diagnostics.cpp
PhilMiller/WarpX
66b01e54771322eae7a7f0ccd697c599452fbd88
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/Diagnostics/Diagnostics.cpp
PhilMiller/WarpX
66b01e54771322eae7a7f0ccd697c599452fbd88
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/Diagnostics/Diagnostics.cpp
PhilMiller/WarpX
66b01e54771322eae7a7f0ccd697c599452fbd88
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "Diagnostics.H" #include "Diagnostics/ComputeDiagFunctors/ComputeDiagFunctor.H" #include "ComputeDiagFunctors/BackTransformParticleFunctor.H" #include "Diagnostics/FlushFormats/FlushFormat.H" #include "Diagnostics/ParticleDiag/ParticleDiag.H" #include "FlushFormats/FlushFormatAscent.H" #include "FlushFormats/FlushFormatCheckpoint.H" #ifdef WARPX_USE_OPENPMD # include "FlushFormats/FlushFormatOpenPMD.H" #endif #include "FlushFormats/FlushFormatPlotfile.H" #include "FlushFormats/FlushFormatSensei.H" #include "Particles/MultiParticleContainer.H" #include "Parallelization/WarpXCommUtil.H" #include "Utils/TextMsg.H" #include "Utils/WarpXAlgorithmSelection.H" #include "Utils/WarpXProfilerWrapper.H" #include "Utils/WarpXUtil.H" #include "WarpX.H" #include <AMReX.H> #include <AMReX_BLassert.H> #include <AMReX_Config.H> #include <AMReX_Geometry.H> #include <AMReX_MultiFab.H> #include <AMReX_ParallelDescriptor.H> #include <AMReX_ParmParse.H> #include <AMReX_Print.H> #include <AMReX_Vector.H> #include <algorithm> #include <string> using namespace amrex::literals; Diagnostics::Diagnostics (int i, std::string name) : m_diag_name(name), m_diag_index(i) { } Diagnostics::~Diagnostics () { } bool Diagnostics::BaseReadParameters () { auto & warpx = WarpX::GetInstance(); amrex::ParmParse pp_diag_name(m_diag_name); m_file_prefix = "diags/" + m_diag_name; pp_diag_name.query("file_prefix", m_file_prefix); queryWithParser(pp_diag_name, "file_min_digits", m_file_min_digits); pp_diag_name.query("format", m_format); pp_diag_name.query("dump_last_timestep", m_dump_last_timestep); amrex::ParmParse pp_geometry("geometry"); std::string dims; pp_geometry.get("dims", dims); // Query list of grid fields to write to output bool varnames_specified = pp_diag_name.queryarr("fields_to_plot", m_varnames_fields); if (!varnames_specified){ if( dims == "RZ" and m_format == "openpmd" ) { m_varnames_fields = {"Er", "Et", "Ez", "Br", "Bt", "Bz", "jr", "jt", "jz"}; } else { m_varnames_fields = {"Ex", "Ey", "Ez", "Bx", "By", "Bz", "jx", "jy", "jz"}; } } // Sanity check if user requests to plot phi if (WarpXUtilStr::is_in(m_varnames_fields, "phi")){ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.do_electrostatic==ElectrostaticSolverAlgo::LabFrame, "plot phi only works if do_electrostatic = labframe"); } // Sanity check if user requests to plot F if (WarpXUtilStr::is_in(m_varnames_fields, "F")){ WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.do_dive_cleaning, "plot F only works if warpx.do_dive_cleaning = 1"); } // G can be written to file only if WarpX::do_divb_cleaning = 1 if (WarpXUtilStr::is_in(m_varnames_fields, "G")) { WARPX_ALWAYS_ASSERT_WITH_MESSAGE( warpx.do_divb_cleaning, "G can be written to file only if warpx.do_divb_cleaning = 1"); } // If user requests to plot proc_number for a serial run, // delete proc_number from fields_to_plot if (amrex::ParallelDescriptor::NProcs() == 1){ m_varnames_fields.erase( std::remove(m_varnames_fields.begin(), m_varnames_fields.end(), "proc_number"), m_varnames_fields.end()); } // Get names of particle quantities to average at each grid point const bool pfield_varnames_specified = pp_diag_name.queryarr("particle_fields_to_plot", m_pfield_varnames); if (!pfield_varnames_specified){ m_pfield_varnames = {}; } #ifdef WARPX_DIM_RZ if (m_pfield_varnames.size() != 0) { amrex::Abort("Input error: cannot use particle_fields_to_plot not implemented for RZ"); } #endif // Get parser strings for particle fields and generate map of parsers std::string parser_str; std::string filter_parser_str = ""; bool do_parser_filter; amrex::ParmParse pp_diag_pfield(m_diag_name + ".particle_fields"); for (const auto& var : m_pfield_varnames) { Store_parserString(pp_diag_pfield, (var + "(x,y,z,ux,uy,uz)").c_str(), parser_str); if (parser_str != "") { m_pfield_strings.insert({var, parser_str}); } else { amrex::Abort("Input error: cannot find parser string for " + var + "." + m_diag_name + ".particle_fields." + var + " in file"); } // Look for and record filter functions. If one is not found, the empty string will be // stored as the filter string, and will be ignored. do_parser_filter = pp_diag_pfield.query((var + ".filter(x,y,z,ux,uy,uz)").c_str(), filter_parser_str); m_pfield_dofilter.insert({var, do_parser_filter}); m_pfield_filter_strings.insert({var, filter_parser_str}); } // Names of all species in the simulation m_all_species_names = warpx.GetPartContainer().GetSpeciesNames(); // Get names of species to average at each grid point const bool pfield_species_specified = pp_diag_name.queryarr("particle_fields_species", m_pfield_species); if (!pfield_species_specified){ m_pfield_species = m_all_species_names; } // Check that species names specified in m_pfield_species are valid bool p_species_name_is_wrong; // Loop over all species specified above for (const auto& species : m_pfield_species) { // Boolean used to check if species name was misspelled p_species_name_is_wrong = true; // Loop over all species for (int i = 0, n = int(m_all_species_names.size()); i < n; i++) { if (species == m_all_species_names[i]) { // Store species index: will be used in ParticleReductionFunctor to calculate // averages for this species m_pfield_species_index.push_back(i); p_species_name_is_wrong = false; } } // If species name was misspelled, abort with error message if (p_species_name_is_wrong) { amrex::Abort("Input error: string " + species + " in " + m_diag_name + ".particle_fields_species does not match any species"); } } m_varnames = m_varnames_fields; // Generate names of averaged particle fields and append to m_varnames for (int ivar=0; ivar<m_pfield_varnames.size(); ivar++) { for (int ispec=0; ispec < int(m_pfield_species.size()); ispec++) { m_varnames.push_back(m_pfield_varnames[ivar] + '_' + m_pfield_species[ispec]); } } // Read user-defined physical extents for the output and store in m_lo and m_hi. m_lo.resize(AMREX_SPACEDIM); m_hi.resize(AMREX_SPACEDIM); bool lo_specified = queryArrWithParser(pp_diag_name, "diag_lo", m_lo, 0, AMREX_SPACEDIM); if (!lo_specified) { for (int idim=0; idim < AMREX_SPACEDIM; ++idim) { m_lo[idim] = warpx.Geom(0).ProbLo(idim); } } bool hi_specified = queryArrWithParser(pp_diag_name, "diag_hi", m_hi, 0, AMREX_SPACEDIM); if (!hi_specified) { for (int idim =0; idim < AMREX_SPACEDIM; ++idim) { m_hi[idim] = warpx.Geom(0).ProbHi(idim); } } // For a moving window simulation, the user-defined m_lo and m_hi must be converted. if (warpx.do_moving_window) { #if defined(WARPX_DIM_3D) amrex::Vector<int> dim_map {0, 1, 2}; #elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ) amrex::Vector<int> dim_map {0, 2}; #else amrex::Vector<int> dim_map {2}; #endif if (warpx.boost_direction[ dim_map[warpx.moving_window_dir] ] == 1) { // Convert user-defined lo and hi for diagnostics to account for boosted-frame // simulations with moving window amrex::Real convert_factor = 1._rt/(warpx.gamma_boost * (1._rt - warpx.beta_boost) ); // Assuming that the window travels with speed c m_lo[warpx.moving_window_dir] *= convert_factor; m_hi[warpx.moving_window_dir] *= convert_factor; } } // Initialize cr_ratio with default value of 1 for each dimension. amrex::Vector<int> cr_ratio(AMREX_SPACEDIM, 1); // Read user-defined coarsening ratio for the output MultiFab. bool cr_specified = queryArrWithParser(pp_diag_name, "coarsening_ratio", cr_ratio, 0, AMREX_SPACEDIM); if (cr_specified) { for (int idim =0; idim < AMREX_SPACEDIM; ++idim) { m_crse_ratio[idim] = cr_ratio[idim]; } } // Names of species to write to output bool species_specified = pp_diag_name.queryarr("species", m_output_species_names); // Auxiliary variables std::string species; bool species_name_is_wrong; // Loop over all fields stored in m_varnames for (const auto& var : m_varnames) { // Check if m_varnames contains a string of the form rho_<species_name> if (var.rfind("rho_", 0) == 0) { // Extract species name from the string rho_<species_name> species = var.substr(var.find("rho_") + 4); // Boolean used to check if species name was misspelled species_name_is_wrong = true; // Loop over all species for (int i = 0, n = int(m_all_species_names.size()); i < n; i++) { // Check if species name extracted from the string rho_<species_name> // matches any of the species in the simulation if (species == m_all_species_names[i]) { // Store species index: will be used in RhoFunctor to dump // rho for this species m_rho_per_species_index.push_back(i); species_name_is_wrong = false; } } // If species name was misspelled, abort with error message if (species_name_is_wrong) { amrex::Abort("Input error: string " + var + " in " + m_diag_name + ".fields_to_plot does not match any species"); } } } bool checkpoint_compatibility = false; if (m_format == "checkpoint"){ if ( varnames_specified == false && pfield_varnames_specified == false && pfield_species_specified == false && lo_specified == false && hi_specified == false && cr_specified == false && species_specified == false ) checkpoint_compatibility = true; } return checkpoint_compatibility; } void Diagnostics::InitData () { // initialize member variables and arrays in base class::Diagnostics InitBaseData(); // initialize member variables and arrays specific to each derived class // (FullDiagnostics, BTDiagnostics, etc.) DerivedInitData(); amrex::ParmParse pp_geometry("geometry"); std::string dims; pp_geometry.get("dims", dims); for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) { // loop over all levels // This includes full diagnostics and BTD as well as cell-center functors for BTD. // Note that the cell-centered data for BTD is computed for all levels and hence // the corresponding functor is also initialized for all the levels for (int lev = 0; lev < nmax_lev; ++lev) { // allocate and initialize m_all_field_functors depending on diag type if (dims == "RZ" and m_format == "openpmd") { InitializeFieldFunctorsRZopenPMD(lev); } else { InitializeFieldFunctors(lev); } } // loop over the levels selected for output // This includes all the levels for full diagnostics // and only the coarse level (mother grid) for BTD for (int lev = 0; lev < nlev_output; ++lev) { // Initialize buffer data required for particle and/or fields InitializeBufferData(i_buffer, lev); } } amrex::ParmParse pp_diag_name(m_diag_name); // default for writing species output is 1 int write_species = 1; pp_diag_name.query("write_species", write_species); if (write_species == 1) { // When particle buffers, m_particle_boundary_buffer are included, // they will be initialized here InitializeParticleBuffer(); InitializeParticleFunctors(); } if (write_species == 0) { if (m_format == "checkpoint"){ amrex::Abort("For checkpoint format, write_species flag must be 1."); } // if user-defined value for write_species == 0, then clear species vector for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer ) { m_output_species.at(i_buffer).clear(); } m_output_species_names.clear(); } else { amrex::Vector <amrex::Real> dummy_val(AMREX_SPACEDIM); if ( queryArrWithParser(pp_diag_name, "diag_lo", dummy_val, 0, AMREX_SPACEDIM) || queryArrWithParser(pp_diag_name, "diag_hi", dummy_val, 0, AMREX_SPACEDIM) ) { // set geometry filter for particle-diags to true when the diagnostic domain-extent // is specified by the user. // Note that the filter is set for every ith snapshot, and the number of snapshots // for full diagnostics is 1, while for BTD it is user-defined. for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer ) { for (auto& v : m_output_species.at(i_buffer)) { v.m_do_geom_filter = true; } // Disabling particle-io for reduced domain diagnostics by reducing // the particle-diag vector to zero. // This is a temporary fix until particle_buffer is supported in diagnostics. m_output_species.at(i_buffer).clear(); } std::string warnMsg = "For full diagnostics on a reduced domain, particle I/O is not "; warnMsg += "supported, yet! Therefore, particle I/O is disabled for this diagnostics: "; warnMsg += m_diag_name; WarpX::GetInstance().RecordWarning("Diagnostics", warnMsg); } } } void Diagnostics::InitBaseData () { auto & warpx = WarpX::GetInstance(); // Number of levels in the simulation at the current timestep nlev = warpx.finestLevel() + 1; // default number of levels to be output = nlev nlev_output = nlev; // Maximum number of levels that will be allocated in the simulation nmax_lev = warpx.maxLevel() + 1; m_all_field_functors.resize( nmax_lev ); // For restart, move the m_lo and m_hi of the diag consistent with the // current moving_window location if (warpx.do_moving_window) { int moving_dir = warpx.moving_window_dir; int shift_num_base = static_cast<int>((warpx.getmoving_window_x() - m_lo[moving_dir]) / warpx.Geom(0).CellSize(moving_dir) ); m_lo[moving_dir] += shift_num_base * warpx.Geom(0).CellSize(moving_dir); m_hi[moving_dir] += shift_num_base * warpx.Geom(0).CellSize(moving_dir); } // Construct Flush class. if (m_format == "plotfile"){ m_flush_format = std::make_unique<FlushFormatPlotfile>() ; } else if (m_format == "checkpoint"){ // creating checkpoint format m_flush_format = std::make_unique<FlushFormatCheckpoint>() ; } else if (m_format == "ascent"){ m_flush_format = std::make_unique<FlushFormatAscent>(); } else if (m_format == "sensei"){ #ifdef AMREX_USE_SENSEI_INSITU m_flush_format = std::make_unique<FlushFormatSensei>( dynamic_cast<amrex::AmrMesh*>(const_cast<WarpX*>(&warpx)), m_diag_name); #else amrex::Abort("To use SENSEI in situ, compile with USE_SENSEI=TRUE"); #endif } else if (m_format == "openpmd"){ #ifdef WARPX_USE_OPENPMD m_flush_format = std::make_unique<FlushFormatOpenPMD>(m_diag_name); #else amrex::Abort("To use openpmd output format, need to compile with USE_OPENPMD=TRUE"); #endif } else { amrex::Abort("unknown output format"); } // allocate vector of buffers then allocate vector of levels for each buffer m_mf_output.resize( m_num_buffers ); for (int i = 0; i < m_num_buffers; ++i) { m_mf_output[i].resize( nmax_lev ); } // allocate vector of geometry objects corresponding to each output multifab. m_geom_output.resize( m_num_buffers ); for (int i = 0; i < m_num_buffers; ++i) { m_geom_output[i].resize( nmax_lev ); } // allocate vector of particle buffers m_output_species.resize(m_num_buffers); } void Diagnostics::ComputeAndPack () { PrepareBufferData(); // prepare the field-data necessary to compute output data PrepareFieldDataForOutput(); // Prepare the particle data necessary to compute output data // Field-data is called first for BTD, since the z-slice location is used to prepare particle data // to determine if the transform is to be done this step. PrepareParticleDataForOutput(); auto & warpx = WarpX::GetInstance(); // compute the necessary fields and store result in m_mf_output. for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) { for(int lev=0; lev<nlev_output; lev++){ int icomp_dst = 0; const auto n = static_cast<int>(m_all_field_functors[lev].size()); for (int icomp=0; icomp<n; icomp++){ // Call all functors in m_all_field_functors[lev]. Each of them computes // a diagnostics and writes in one or more components of the output // multifab m_mf_output[lev]. m_all_field_functors[lev][icomp]->operator()(m_mf_output[i_buffer][lev], icomp_dst, i_buffer); // update the index of the next component to fill icomp_dst += m_all_field_functors[lev][icomp]->nComp(); } // Check that the proper number of components of mf_avg were updated. AMREX_ALWAYS_ASSERT( icomp_dst == m_varnames.size() ); // needed for contour plots of rho, i.e. ascent/sensei if (m_format == "sensei" || m_format == "ascent") { WarpXCommUtil::FillBoundary(m_mf_output[i_buffer][lev], warpx.Geom(lev).periodicity()); } } // Call Particle functor for (int isp = 0; isp < m_all_particle_functors.size(); ++isp) { m_all_particle_functors[isp]->operator()(*m_particles_buffer[i_buffer][isp], m_totalParticles_in_buffer[i_buffer][isp], i_buffer); } } UpdateBufferData(); } void Diagnostics::FilterComputePackFlush (int step, bool force_flush) { WARPX_PROFILE("Diagnostics::FilterComputePackFlush()"); MovingWindowAndGalileanDomainShift (step); if ( DoComputeAndPack (step, force_flush) ) { ComputeAndPack(); } for (int i_buffer = 0; i_buffer < m_num_buffers; ++i_buffer) { if ( !DoDump (step, i_buffer, force_flush) ) continue; Flush(i_buffer); } }
40.433121
142
0.646765
PhilMiller
d5333c8297dff93bb9e32e00f2dc3310dead2358
5,159
cxx
C++
resip/recon/UserAgentServerAuthManager.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
resip/recon/UserAgentServerAuthManager.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
resip/recon/UserAgentServerAuthManager.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#include <cassert> #include "UserAgent.hxx" #include "UserAgentServerAuthManager.hxx" #include <resip/dum/DialogUsageManager.hxx> #include <resip/dum/ServerAuthManager.hxx> #include <resip/dum/UserAuthInfo.hxx> #include <resip/dum/UserProfile.hxx> #include <rutil/MD5Stream.hxx> #include <rutil/WinLeakCheck.hxx> #define RESIPROCATE_SUBSYSTEM Subsystem::RECON using namespace recon; using namespace resip; UserAgentServerAuthManager::UserAgentServerAuthManager(UserAgent& userAgent) : ServerAuthManager(userAgent.getDialogUsageManager(), userAgent.getDialogUsageManager().dumIncomingTarget()), mUserAgent(userAgent) { } UserAgentServerAuthManager::~UserAgentServerAuthManager() { } bool UserAgentServerAuthManager::useAuthInt() const { return true; } bool UserAgentServerAuthManager::proxyAuthenticationMode() const { return false; // Challenge with 401 } const Data& UserAgentServerAuthManager::getChallengeRealm(const SipMessage& msg) { return mUserAgent.getIncomingConversationProfile(msg)->getDefaultFrom().uri().host(); } bool UserAgentServerAuthManager::isMyRealm(const Data& realm) { return true; // .slg. this means we will try to find credentials for any authorization headers // could improve this by looking through all active conversation profiles to see if realm exists } bool UserAgentServerAuthManager::authorizedForThisIdentity(const resip::Data &user, const resip::Data &realm, resip::Uri &fromUri) { return true; // We don't care who the request came from } ServerAuthManager::AsyncBool UserAgentServerAuthManager::requiresChallenge(const SipMessage& msg) { assert(msg.isRequest()); ConversationProfile* profile = mUserAgent.getIncomingConversationProfile(msg).get(); // We want to challenge OOD Refer requests and Invite Requests with Auto-Answer indications switch(msg.method()) { case REFER: if(profile->challengeOODReferRequests() && !msg.header(h_To).exists(p_tag)) { // Don't challenge OOD Refer requests have a valid TargetDialog header if(!msg.exists(h_TargetDialog) || mUserAgent.getDialogUsageManager().findInviteSession(msg.header(h_TargetDialog)).first == InviteSessionHandle::NotValid()) { return True; } } break; case INVITE: if(profile->challengeAutoAnswerRequests() && profile->shouldAutoAnswer(msg)) { return True; } break; default: break; } // Default to not challenge return False; } void UserAgentServerAuthManager::requestCredential(const Data& user, const Data& realm, const SipMessage& msg, const Auth& auth, const Data& transactionId ) { const UserProfile::DigestCredential& digestCredential = mUserAgent.getIncomingConversationProfile(msg)->getDigestCredential(realm); MD5Stream a1; a1 << digestCredential.user << Symbols::COLON << digestCredential.realm << Symbols::COLON << digestCredential.password; a1.flush(); UserAuthInfo* userAuthInfo = new UserAuthInfo(user,realm,a1.getHex(),transactionId); mUserAgent.getDialogUsageManager().post( userAuthInfo ); } /* ==================================================================== Copyright (c) 2007-2008, Plantronics, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Plantronics 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. ==================================================================== */
34.393333
165
0.686373
dulton
d536b7e2212643e95994d8478766ff5c1aa92af6
20,539
cpp
C++
tests/popsparse/SparseFormatsTest.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
95
2020-07-06T17:11:23.000Z
2022-03-12T14:42:28.000Z
tests/popsparse/SparseFormatsTest.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
tests/popsparse/SparseFormatsTest.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
14
2020-07-15T12:32:57.000Z
2022-01-26T14:58:45.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #define BOOST_TEST_MODULE SparseFormatsTest #include "../lib/popsparse/SparseStorageInternal.hpp" #include <boost/test/unit_test.hpp> // CSR/CSC representation of matrix for element sparsity // 10 20 0 0 0 0 // 0 30 0 40 0 0 // 0 0 50 60 70 0 // 0 0 0 0 0 80 // CSR/CSC representation of matrix for block sparsity with 2x3 blocks // 10 11 12 20 21 22 0 0 0 0 0 0 0 0 0 0 0 0 // 13 14 15 23 24 25 0 0 0 0 0 0 0 0 0 0 0 0 // // 0 0 0 30 31 32 0 0 0 40 41 42 0 0 0 0 0 0 // 0 0 0 33 34 35 0 0 0 43 44 45 0 0 0 0 0 0 // // 0 0 0 0 0 0 50 51 52 60 61 62 70 71 72 0 0 0 // 0 0 0 0 0 0 53 54 55 63 64 65 73 74 75 0 0 0 // // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 80 81 82 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 83 84 85 const std::size_t numRows = 4; const std::size_t numColumns = 6; const std::size_t numRowsInBlock = 2; const std::size_t numColumnsInBlock = 3; static const popsparse::CSRMatrix<double> csrRef({10.0, 20, 30, 40, 50, 60, 70, 80.0}, {0, 1, 1, 3, 2, 3, 4, 5}, {0, 2, 4, 7, 8}); const popsparse::CSRMatrix<double> csrRef2x3( {10.0, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 40, 41, 42, 43, 44, 45, 50, 51, 52, 53, 54, 55, 60, 61, 62, 63, 64, 65, 70, 71, 72, 73, 74, 75, 80.0, 81, 82, 83, 84, 85}, {0, 3, 3, 9, 6, 9, 12, 15}, {0, 12, 24, 42, 48}, {2, 3}); // CSR/CSC/COO representation of matrix for block sparsity with 2x6 blocks // 0 1 2 3 4 5 0 0 0 0 0 0 20 21 22 23 24 25 // 6 7 8 9 10 11 0 0 0 0 0 0 26 27 28 29 30 31 // // 0 0 0 0 0 0 40 41 42 43 44 45 0 0 0 0 0 0 // 0 0 0 0 0 0 46 47 48 49 50 51 0 0 0 0 0 0 // // 50 51 52 53 54 55 70 71 72 73 74 75 80 81 82 83 84 85 // 56 57 58 59 60 61 76 77 78 79 80 81 86 87 88 89 90 91 static const popsparse::CSRMatrix<std::size_t> csrRef2x6( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91}, {0, 12, 6, 0, 6, 12}, {0, 24, 36, 72}, {2, 6}); static const popsparse::COOMatrix<std::size_t> cooRef2x6( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91}, {0, 12, 6, 0, 6, 12}, {0, 0, 2, 4, 4, 4}, {2, 6}); static const popsparse::CSRMatrix<std::size_t> csrRef2x6_1x2( {0, 1, 2, 3, 4, 5, 20, 21, 22, 23, 24, 25, 6, 7, 8, 9, 10, 11, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 70, 71, 72, 73, 74, 75, 80, 81, 82, 83, 84, 85, 56, 57, 58, 59, 60, 61, 76, 77, 78, 79, 80, 81, 86, 87, 88, 89, 90, 91}, {0, 2, 4, 12, 14, 16, 0, 2, 4, 12, 14, 16, 6, 8, 10, 6, 8, 10, 0, 2, 4, 6, 8, 10, 12, 14, 16, 0, 2, 4, 6, 8, 10, 12, 14, 16}, {0, 12, 24, 30, 36, 54, 72}, {1, 2}); static const popsparse::COOMatrix<std::size_t> cooRef2x6_1x2( {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91}, {0, 2, 4, 0, 2, 4, 12, 14, 16, 12, 14, 16, 6, 8, 10, 6, 8, 10, 0, 2, 4, 0, 2, 4, 6, 8, 10, 6, 8, 10, 12, 14, 16, 12, 14, 16}, {0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 4, 4, 4, 5, 5, 5, 4, 4, 4, 5, 5, 5}, {1, 2}); // CSR/CSC with block size of 4x4 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 // 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 static const popsparse::CSRMatrix<std::size_t> csrRef4x4({0, 1, 2, 3, 16, 17, 18, 19, 32, 33, 34, 35, 48, 49, 50, 51, 4, 5, 6, 7, 20, 21, 22, 23, 36, 37, 38, 39, 52, 53, 54, 55, 8, 9, 10, 11, 24, 25, 26, 27, 40, 41, 42, 43, 56, 57, 58, 59, 12, 13, 14, 15, 28, 29, 30, 31, 44, 45, 46, 47, 60, 61, 62, 63}, {0, 4, 8, 12}, {0, 64}, {4, 4}); static const popsparse::CSRMatrix<std::size_t> csrRef4x4_2x2( {0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23, 8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31, 32, 33, 48, 49, 34, 35, 50, 51, 36, 37, 52, 53, 38, 39, 54, 55, 40, 41, 56, 57, 42, 43, 58, 59, 44, 45, 60, 61, 46, 47, 62, 63}, {0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14}, {0, 32, 64}, {2, 2}); static const popsparse::COOMatrix<std::size_t> cooRef4x4({0, 1, 2, 3, 16, 17, 18, 19, 32, 33, 34, 35, 48, 49, 50, 51, 4, 5, 6, 7, 20, 21, 22, 23, 36, 37, 38, 39, 52, 53, 54, 55, 8, 9, 10, 11, 24, 25, 26, 27, 40, 41, 42, 43, 56, 57, 58, 59, 12, 13, 14, 15, 28, 29, 30, 31, 44, 45, 46, 47, 60, 61, 62, 63}, {0, 4, 8, 12}, {0, 0, 0, 0}, {4, 4}); static const popsparse::COOMatrix<std::size_t> cooRef4x4_2x2( {0, 1, 16, 17, 2, 3, 18, 19, 32, 33, 48, 49, 34, 35, 50, 51, 4, 5, 20, 21, 6, 7, 22, 23, 36, 37, 52, 53, 38, 39, 54, 55, 8, 9, 24, 25, 10, 11, 26, 27, 40, 41, 56, 57, 42, 43, 58, 59, 12, 13, 28, 29, 14, 15, 30, 31, 44, 45, 60, 61, 46, 47, 62, 63}, {0, 2, 0, 2, 4, 6, 4, 6, 8, 10, 8, 10, 12, 14, 12, 14}, {0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2}, {2, 2}); static const popsparse::CSRMatrix<std::size_t> csrRefS({10, 20, 30, 40, 50, 60, 70, 80}, {0, 1, 1, 3, 2, 3, 4, 5}, {0, 2, 4, 7, 8}); static const popsparse::CSCMatrix<double> cscRef({10, 20, 30, 50, 40, 60, 70, 80}, {0, 1, 3, 4, 6, 7, 8}, {0, 0, 1, 2, 1, 2, 2, 3}); static const popsparse::CSCMatrix<double> cscRef2x3({10, 13, 11, 14, 12, 15, 20, 23, 21, 24, 22, 25, 30, 33, 31, 34, 32, 35, 50, 53, 51, 54, 52, 55, 40, 43, 41, 44, 42, 45, 60, 63, 61, 64, 62, 65, 70, 73, 71, 74, 72, 75, 80, 83, 81, 84, 82, 85}, {0, 6, 18, 24, 36, 42, 48}, {0, 0, 2, 4, 2, 4, 4, 6}, {2, 3}); static const popsparse::CSRMatrix<double> csrRefUnsorted({10.0, 20, 40, 30, 70, 50, 60, 80.0}, {0, 1, 3, 1, 4, 2, 3, 5}, {0, 2, 4, 7, 8}); static const popsparse::CSRMatrix<double> csrRefUnsorted2x3( {10.0, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 40, 41, 42, 43, 44, 45, 30, 31, 32, 33, 34, 35, 70, 71, 72, 73, 74, 75, 50, 51, 52, 53, 54, 55, 60, 61, 62, 63, 64, 65, 80.0, 81, 82, 83, 84, 85}, {0, 3, 9, 3, 12, 6, 9, 15}, {0, 12, 24, 42, 48}, {2, 3}); static const popsparse::COOMatrix<double> cooUnsorted({80, 70, 60, 50, 40, 30, 20, 10}, {5, 4, 3, 2, 3, 1, 1, 0}, {3, 2, 2, 2, 1, 1, 0, 0}); static const popsparse::COOMatrix<double> cooUnsorted2x3( {80, 81, 82, 83, 84, 85, 70, 71, 72, 73, 74, 75, 60, 61, 62, 63, 64, 65, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45, 30, 31, 32, 33, 34, 35, 20, 21, 22, 23, 24, 25, 10, 11, 12, 13, 14, 15}, {15, 12, 9, 6, 9, 3, 3, 0}, {6, 4, 4, 4, 2, 2, 0, 0}); BOOST_AUTO_TEST_CASE(ValidateCsrToCsc) { auto cscResult = popsparse::csrToCSC(numRows, numColumns, csrRef); BOOST_CHECK_EQUAL_COLLECTIONS(cscRef.nzValues.begin(), cscRef.nzValues.end(), cscResult.nzValues.begin(), cscResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef.rowIndices.begin(), cscRef.rowIndices.end(), cscResult.rowIndices.begin(), cscResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef.columnIndices.begin(), cscRef.columnIndices.end(), cscResult.columnIndices.begin(), cscResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCsrToCscBlock) { auto cscResult = popsparse::csrToCSC( numRows * numRowsInBlock, numColumns * numColumnsInBlock, csrRef2x3); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef2x3.nzValues.begin(), cscRef2x3.nzValues.end(), cscResult.nzValues.begin(), cscResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef2x3.rowIndices.begin(), cscRef2x3.rowIndices.end(), cscResult.rowIndices.begin(), cscResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cscRef2x3.columnIndices.begin(), cscRef2x3.columnIndices.end(), cscResult.columnIndices.begin(), cscResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCscToCsr) { auto csrResult = popsparse::cscToCSR(numRows, numColumns, cscRef); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csrResult.nzValues.begin(), csrResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csrResult.rowIndices.begin(), csrResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csrResult.columnIndices.begin(), csrResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCscToCsrBlock) { auto csrResult = popsparse::cscToCSR( numRows * numRowsInBlock, numColumns * numColumnsInBlock, cscRef2x3); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.nzValues.begin(), csrRef2x3.nzValues.end(), csrResult.nzValues.begin(), csrResult.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.rowIndices.begin(), csrRef2x3.rowIndices.end(), csrResult.rowIndices.begin(), csrResult.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.columnIndices.begin(), csrRef2x3.columnIndices.end(), csrResult.columnIndices.begin(), csrResult.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateTransposeCSR) { auto csrRes1 = popsparse::csrTranspose(numRows, numColumns, csrRef); auto csrRes2 = popsparse::csrTranspose(numColumns, numRows, csrRes1); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csrRes2.nzValues.begin(), csrRes2.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csrRes2.rowIndices.begin(), csrRes2.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csrRes2.columnIndices.begin(), csrRes2.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateTransposeCSRBlock) { auto csrRes1 = popsparse::csrTranspose( numRows * numRowsInBlock, numColumns * numColumnsInBlock, csrRef2x3); auto csrRes2 = popsparse::csrTranspose(numColumns * numColumnsInBlock, numRows * numRowsInBlock, csrRes1); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.nzValues.begin(), csrRef2x3.nzValues.end(), csrRes2.nzValues.begin(), csrRes2.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.rowIndices.begin(), csrRef2x3.rowIndices.end(), csrRes2.rowIndices.begin(), csrRes2.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.columnIndices.begin(), csrRef2x3.columnIndices.end(), csrRes2.columnIndices.begin(), csrRes2.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCSRCanonicalize) { auto csr = csrRefUnsorted; popsparse::canonicalizeCSR(csr); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ValidateCSRCanonicalizeBlock) { auto csr = csrRefUnsorted2x3; popsparse::canonicalizeCSR(csr); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x3.nzValues.begin(), csrRef2x3.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x3.rowIndices.begin(), csrRef2x3.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x3.columnIndices.begin(), csrRef2x3.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(GetRowPositionTest) { const auto tile = popsparse::Tile(poplar::Interval(0, 2), poplar::Interval(0, 4)); const std::size_t blockSizeX = 1, blockSizeY = 1; const auto rowInfo = popsparse::getPositionValuePairsPerRow( csrRefS, blockSizeX, blockSizeY, tile); const std::vector<std::vector<std::pair<double, std::size_t>>> expectedInfo = {{{0, 10}, {1, 20}}, {{1, 30}, {3, 40}}}; BOOST_CHECK_EQUAL(rowInfo.size(), expectedInfo.size()); for (unsigned row = 0; row != expectedInfo.size(); ++row) { BOOST_CHECK_EQUAL(rowInfo[row].positionValues.size(), expectedInfo[row].size()); const auto expt = expectedInfo[row]; const auto real = rowInfo[row].positionValues; for (unsigned column = 0; column != expectedInfo[row].size(); ++column) { BOOST_CHECK_EQUAL(real[column].first, expt[column].first); BOOST_CHECK_EQUAL(real[column].second, expt[column].second); } BOOST_CHECK_EQUAL(rowInfo[row].rowNumber, row); } } BOOST_AUTO_TEST_CASE(ConvertCooToCsr) { auto csr = popsparse::cooToCSR(numRows, numColumns, cooUnsorted); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.nzValues.begin(), csrRef.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef.rowIndices.begin(), csrRef.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef.columnIndices.begin(), csrRef.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCsrBlockSize2x6) { auto csr = popsparse::changeCSRBlockSize(csrRef2x6, {1, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x6_1x2.nzValues.begin(), csrRef2x6_1x2.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef2x6_1x2.rowIndices.begin(), csrRef2x6_1x2.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef2x6_1x2.columnIndices.begin(), csrRef2x6_1x2.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCsrBlockSize4x4) { auto csr = popsparse::changeCSRBlockSize(csrRef4x4, {2, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef4x4_2x2.nzValues.begin(), csrRef4x4_2x2.nzValues.end(), csr.nzValues.begin(), csr.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csrRef4x4_2x2.rowIndices.begin(), csrRef4x4_2x2.rowIndices.end(), csr.rowIndices.begin(), csr.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csrRef4x4_2x2.columnIndices.begin(), csrRef4x4_2x2.columnIndices.end(), csr.columnIndices.begin(), csr.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCscBlockSize4x4) { auto csc4x4 = popsparse::csrToCSC(4, 16, csrRef4x4); auto csc4x4_2x2 = popsparse::csrToCSC(4, 16, csrRef4x4_2x2); auto csc = popsparse::changeCSCBlockSize(csc4x4, {2, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csc4x4_2x2.nzValues.begin(), csc4x4_2x2.nzValues.end(), csc.nzValues.begin(), csc.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csc4x4_2x2.rowIndices.begin(), csc4x4_2x2.rowIndices.end(), csc.rowIndices.begin(), csc.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csc4x4_2x2.columnIndices.begin(), csc4x4_2x2.columnIndices.end(), csc.columnIndices.begin(), csc.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCscBlockSize2x6) { auto csc2x6 = popsparse::csrToCSC(6, 18, csrRef2x6); auto csc2x6_1x2 = popsparse::csrToCSC(6, 18, csrRef2x6_1x2); auto csc = popsparse::changeCSCBlockSize(csc2x6, {1, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(csc2x6_1x2.nzValues.begin(), csc2x6_1x2.nzValues.end(), csc.nzValues.begin(), csc.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(csc2x6_1x2.rowIndices.begin(), csc2x6_1x2.rowIndices.end(), csc.rowIndices.begin(), csc.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( csc2x6_1x2.columnIndices.begin(), csc2x6_1x2.columnIndices.end(), csc.columnIndices.begin(), csc.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize4x4) { auto coo = popsparse::changeCOOBlockSize(cooRef4x4, {2, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef4x4_2x2.nzValues.begin(), cooRef4x4_2x2.nzValues.end(), coo.nzValues.begin(), coo.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef4x4_2x2.rowIndices.begin(), cooRef4x4_2x2.rowIndices.end(), coo.rowIndices.begin(), coo.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4_2x2.columnIndices.begin(), cooRef4x4_2x2.columnIndices.end(), coo.columnIndices.begin(), coo.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize2x6) { auto coo = popsparse::changeCOOBlockSize(cooRef2x6, {1, 2}); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef2x6_1x2.nzValues.begin(), cooRef2x6_1x2.nzValues.end(), coo.nzValues.begin(), coo.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS(cooRef2x6_1x2.rowIndices.begin(), cooRef2x6_1x2.rowIndices.end(), coo.rowIndices.begin(), coo.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6_1x2.columnIndices.begin(), cooRef2x6_1x2.columnIndices.end(), coo.columnIndices.begin(), coo.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize2x6DoubleChange) { auto coo = popsparse::changeCOOBlockSize(cooRef2x6, {1, 2}); auto cooOrig = popsparse::changeCOOBlockSize(coo, {2, 6}); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6.nzValues.begin(), cooRef2x6.nzValues.end(), cooOrig.nzValues.begin(), cooOrig.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6.rowIndices.begin(), cooRef2x6.rowIndices.end(), cooOrig.rowIndices.begin(), cooOrig.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef2x6.columnIndices.begin(), cooRef2x6.columnIndices.end(), cooOrig.columnIndices.begin(), cooOrig.columnIndices.end()); } BOOST_AUTO_TEST_CASE(ChangeCooBlockSize4x4DoubleChange) { auto coo = popsparse::changeCOOBlockSize(cooRef4x4, {2, 2}); auto cooOrig = popsparse::changeCOOBlockSize(coo, {4, 4}); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4.nzValues.begin(), cooRef4x4.nzValues.end(), cooOrig.nzValues.begin(), cooOrig.nzValues.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4.rowIndices.begin(), cooRef4x4.rowIndices.end(), cooOrig.rowIndices.begin(), cooOrig.rowIndices.end()); BOOST_CHECK_EQUAL_COLLECTIONS( cooRef4x4.columnIndices.begin(), cooRef4x4.columnIndices.end(), cooOrig.columnIndices.begin(), cooOrig.columnIndices.end()); }
46.05157
80
0.597887
graphcore
d53733bd8ae0d7c5652718dc3012ca238400ae83
9,224
cpp
C++
tools/converter/source/onnx/onnxOpConverter.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
tools/converter/source/onnx/onnxOpConverter.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
tools/converter/source/onnx/onnxOpConverter.cpp
foreverlms/MNN
8f9d3e3331fb54382bb61ac3a2087637a161fec5
[ "Apache-2.0" ]
null
null
null
// // onnxOpConverter.cpp // MNNConverter // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #include "onnxOpConverter.hpp" #include "OpCount.hpp" using namespace MNN; static int32_t _limit(int64_t i64) { if (i64 > (int64_t)(1 << 30)) { return 1 << 30; } if (i64 < (int64_t)(-(1 << 30))) { return (-(1 << 30)); } return i64; } class DefaultonnxOpConverter : public onnxOpConverter { public: virtual void run(MNN::OpT* dstOp, const onnx::NodeProto* onnxNode, std::vector<const onnx::TensorProto*> initializers) override { auto extra = new ExtraT; dstOp->main.type = OpParameter_Extra; dstOp->main.value = extra; extra->engine = "ONNX"; extra->type = onnxNode->op_type(); for (auto srcAttr : onnxNode->attribute()) { std::unique_ptr<AttributeT> attr(new AttributeT); attr->key = srcAttr.name(); switch (srcAttr.type()) { case onnx::AttributeProto_AttributeType_INTS: attr->list.reset(new ListValueT); attr->list->i.resize(srcAttr.ints_size()); for (int i = 0; i < srcAttr.ints_size(); ++i) { attr->list->i[i] = _limit(srcAttr.ints(i)); } break; case onnx::AttributeProto_AttributeType_FLOATS: attr->list.reset(new ListValueT); attr->list->f.resize(srcAttr.floats_size()); for (int i = 0; i < srcAttr.floats_size(); ++i) { attr->list->f[i] = srcAttr.floats(i); } break; case onnx::AttributeProto_AttributeType_TENSOR: attr->tensor.reset(convertTensorToBlob(&srcAttr.t())); break; default: break; } attr->i = _limit(srcAttr.i()); attr->s = srcAttr.s(); attr->f = srcAttr.f(); extra->attr.emplace_back(std::move(attr)); } } virtual MNN::OpParameter type() override { return OpParameter_Extra; } virtual MNN::OpType opType() override { return OpType_Extra; } }; onnxOpConverterSuit::onnxOpConverterSuit() { } onnxOpConverterSuit::~onnxOpConverterSuit() { for (auto& iter : mConverterContainer) { delete iter.second; } mConverterContainer.clear(); } onnxOpConverterSuit* onnxOpConverterSuit::global = nullptr; onnxOpConverterSuit* onnxOpConverterSuit::get() { if (global == nullptr) { global = new onnxOpConverterSuit; } return global; } void onnxOpConverterSuit::insert(onnxOpConverter* t, const char* name) { MNN::OpCount::get()->insertOp("ONNX", std::string(name)); mConverterContainer.insert(std::make_pair(name, t)); } onnxOpConverter* onnxOpConverterSuit::search(const std::string& name) { auto iter = mConverterContainer.find(name); if (iter == mConverterContainer.end()) { static DefaultonnxOpConverter defaultConverter; return &defaultConverter; } return iter->second; } MNN::DataType onnxOpConverter::convertDataType(::onnx::TensorProto_DataType type) { static std::map<::onnx::TensorProto_DataType, MNN::DataType> dataTypeMap{ {onnx::TensorProto_DataType_FLOAT, MNN::DataType_DT_FLOAT}, {onnx::TensorProto_DataType_INT8, MNN::DataType_DT_INT8}, {onnx::TensorProto_DataType_INT32, MNN::DataType_DT_INT32}, {onnx::TensorProto_DataType_INT64, MNN::DataType_DT_INT32}, // For compability, use int32 instead of int64 {onnx::TensorProto_DataType_DOUBLE, MNN::DataType_DT_FLOAT}, // For compability, use float instead of double {onnx::TensorProto_DataType_UINT8, MNN::DataType_DT_UINT8}, {onnx::TensorProto_DataType_INT8, MNN::DataType_DT_INT8}, {onnx::TensorProto_DataType_BOOL, MNN::DataType_DT_INT32}, // For compability, use int32 instead of bool {onnx::TensorProto_DataType_INT16, MNN::DataType_DT_INT32}, // For compability, use int32 instead of int16 {onnx::TensorProto_DataType_UINT16, MNN::DataType_DT_INT32}, // For compability, use int32 instead of uint16 }; if (dataTypeMap.find(type) != dataTypeMap.end()) { return dataTypeMap[type]; } return MNN::DataType_DT_INVALID; } MNN::BlobT* onnxOpConverter::convertTensorToBlob(const onnx::TensorProto* constantTp) { auto constantParam = new MNN::BlobT; auto dataType = convertDataType(constantTp->data_type()); // printf("origindataType = %d, dataType = %s\n", constantTp->data_type(), MNN::EnumNameDataType(dataType)); constantParam->dataType = dataType; constantParam->dataFormat = MNN::MNN_DATA_FORMAT_NCHW; size_t dimSize = constantTp->dims().size(); constantParam->dims.resize(dimSize); size_t dataSize = 1; for (int i = 0; i < dimSize; ++i) { constantParam->dims[i] = constantTp->dims(i); dataSize = dataSize * constantTp->dims(i); } std::vector<int64_t> alignContent((constantTp->raw_data().size() + sizeof(int64_t) - 1) / sizeof(int64_t)); ::memcpy(alignContent.data(), constantTp->raw_data().data(), constantTp->raw_data().size()); const void* tensor_content = (const void*)alignContent.data(); switch (constantTp->data_type()) { #define CASE_DATA_TYPE(src, dst) \ case src: \ if (constantTp->dst##_data_size() != 0) { \ tensor_content = constantTp->dst##_data().data(); \ } \ break; CASE_DATA_TYPE(onnx::TensorProto_DataType_DOUBLE, double); CASE_DATA_TYPE(onnx::TensorProto_DataType_INT64, int64); CASE_DATA_TYPE(onnx::TensorProto_DataType_INT32, int32); CASE_DATA_TYPE(onnx::TensorProto_DataType_FLOAT, float); default: break; } if (0 == dataSize) { // Empty blob return constantParam; } if (!tensor_content) { DLOG(FATAL) << "Convert no data, " "Please make sure "; } switch (constantTp->data_type()) { case onnx::TensorProto_DataType_DOUBLE: { constantParam->float32s.resize(dataSize); auto source = (double*)tensor_content; for (int i = 0; i < dataSize; ++i) { constantParam->float32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_INT64: { constantParam->int32s.resize(dataSize); auto source = (int64_t*)tensor_content; for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = _limit(source[i]); } break; } case onnx::TensorProto_DataType_INT32: { auto source = (int32_t*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_UINT16: { auto source = (uint16_t*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_INT16: { auto source = (int16_t*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_BOOL: { auto source = (bool*)tensor_content; constantParam->int32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int32s[i] = source[i]; } break; } case onnx::TensorProto_DataType_INT8: { auto source = (int8_t*)tensor_content; constantParam->int8s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->int8s[i] = source[i]; } break; } case onnx::TensorProto_DataType_UINT8: { auto source = (uint8_t*)tensor_content; constantParam->uint8s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->uint8s[i] = source[i]; } break; } case onnx::TensorProto_DataType_FLOAT: { float* tempFloatData = (float*)tensor_content; constantParam->float32s.resize(dataSize); for (int i = 0; i < dataSize; ++i) { constantParam->float32s[i] = tempFloatData[i]; } break; } default: { DLOG(FATAL) << "Don't support " << constantTp->data_type(); break; } } return constantParam; }
37.803279
116
0.568517
foreverlms
d539757ef23d4c01ba4e3355d1ccf2d0a166d96d
20,382
hxx
C++
Modules/IO/ImageBase/include/itkImageFileReader.hxx
bradking/ITK
625d4497512b0fb0108106e680063998b8528e06
[ "Apache-2.0" ]
945
2015-01-09T00:43:52.000Z
2022-03-30T08:23:02.000Z
Modules/IO/ImageBase/include/itkImageFileReader.hxx
bradking/ITK
625d4497512b0fb0108106e680063998b8528e06
[ "Apache-2.0" ]
2,354
2015-02-04T21:54:21.000Z
2022-03-31T20:58:21.000Z
Modules/IO/ImageBase/include/itkImageFileReader.hxx
bradking/ITK
625d4497512b0fb0108106e680063998b8528e06
[ "Apache-2.0" ]
566
2015-01-04T14:26:57.000Z
2022-03-18T20:33:18.000Z
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkImageFileReader_hxx #define itkImageFileReader_hxx #include "itkImageFileReader.h" #include "itkObjectFactory.h" #include "itkImageIOFactory.h" #include "itkConvertPixelBuffer.h" #include "itkPixelTraits.h" #include "itkVectorImage.h" #include "itkMetaDataObject.h" #include "itksys/SystemTools.hxx" #include <memory> // For unique_ptr #include <fstream> namespace itk { template <typename TOutputImage, typename ConvertPixelTraits> ImageFileReader<TOutputImage, ConvertPixelTraits>::ImageFileReader() { m_ImageIO = nullptr; this->SetFileName(""); m_UserSpecifiedImageIO = false; m_UseStreaming = true; } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); itkPrintSelfObjectMacro(ImageIO); os << indent << "UserSpecifiedImageIO flag: " << m_UserSpecifiedImageIO << "\n"; os << indent << "m_UseStreaming: " << m_UseStreaming << "\n"; } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::SetImageIO(ImageIOBase * imageIO) { itkDebugMacro("setting ImageIO to " << imageIO); if (this->m_ImageIO != imageIO) { this->m_ImageIO = imageIO; this->Modified(); } m_UserSpecifiedImageIO = true; } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateOutputInformation() { typename TOutputImage::Pointer output = this->GetOutput(); itkDebugMacro(<< "Reading file for GenerateOutputInformation()" << this->GetFileName()); // Check to see if we can read the file given the name or prefix // if (this->GetFileName().empty()) { throw ImageFileReaderException(__FILE__, __LINE__, "FileName must be specified", ITK_LOCATION); } // Test if the file exists and if it can be opened. // An exception will be thrown otherwise. // We catch the exception because some ImageIO's may not actually // open a file. Still reports file error if no ImageIO is loaded. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch (const itk::ExceptionObject & err) { m_ExceptionMessage = err.GetDescription(); } if (m_UserSpecifiedImageIO == false) // try creating via factory { m_ImageIO = ImageIOFactory::CreateImageIO(this->GetFileName().c_str(), ImageIOFactory::IOFileModeEnum::ReadMode); } if (m_ImageIO.IsNull()) { std::ostringstream msg; msg << " Could not create IO object for reading file " << this->GetFileName().c_str() << std::endl; if (!m_ExceptionMessage.empty()) { msg << m_ExceptionMessage; } else { std::list<LightObject::Pointer> allobjects = ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); if (!allobjects.empty()) { msg << " Tried to create one of the following:" << std::endl; for (auto & allobject : allobjects) { auto * io = dynamic_cast<ImageIOBase *>(allobject.GetPointer()); msg << " " << io->GetNameOfClass() << std::endl; } msg << " You probably failed to set a file suffix, or" << std::endl; msg << " set the suffix to an unsupported type." << std::endl; } else { msg << " There are no registered IO factories." << std::endl; msg << " Please visit https://www.itk.org/Wiki/ITK/FAQ#NoFactoryException to diagnose the problem." << std::endl; } } ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } // Got to allocate space for the image. Determine the characteristics of // the image. // m_ImageIO->SetFileName(this->GetFileName().c_str()); m_ImageIO->ReadImageInformation(); SizeType dimSize; double spacing[TOutputImage::ImageDimension]; double origin[TOutputImage::ImageDimension]; typename TOutputImage::DirectionType direction; std::vector<std::vector<double>> directionIO; const unsigned int numberOfDimensionsIO = m_ImageIO->GetNumberOfDimensions(); if (numberOfDimensionsIO > TOutputImage::ImageDimension) { for (unsigned int k = 0; k < numberOfDimensionsIO; ++k) { directionIO.push_back(m_ImageIO->GetDefaultDirection(k)); } } else { for (unsigned int k = 0; k < numberOfDimensionsIO; ++k) { directionIO.push_back(m_ImageIO->GetDirection(k)); } } std::vector<double> axis; for (unsigned int i = 0; i < TOutputImage::ImageDimension; ++i) { if (i < numberOfDimensionsIO) { dimSize[i] = m_ImageIO->GetDimensions(i); spacing[i] = m_ImageIO->GetSpacing(i); origin[i] = m_ImageIO->GetOrigin(i); // Please note: direction cosines are stored as columns of the // direction matrix axis = directionIO[i]; for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j) { if (j < numberOfDimensionsIO) { direction[j][i] = axis[j]; } else { direction[j][i] = 0.0; } } } else { // Number of dimensions in the output is more than number of dimensions // in the ImageIO object (the file). Use default values for the size, // spacing, origin and direction for the final (degenerate) dimensions. dimSize[i] = 1; spacing[i] = 1.0; origin[i] = 0.0; for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j) { if (i == j) { direction[j][i] = 1.0; } else { direction[j][i] = 0.0; } } } } MetaDataDictionary & thisDic = m_ImageIO->GetMetaDataDictionary(); // Store original directions and spacing EncapsulateMetaData<std::vector<double>>( thisDic, "ITK_original_spacing", std::vector<double>(spacing, spacing + TOutputImage::ImageDimension)); EncapsulateMetaData<typename TOutputImage::DirectionType>(thisDic, "ITK_original_direction", direction); // Spacing is expected to be greater than 0 // If negative, flip image direction along this axis. // and store this information in the metadata for (unsigned int i = 0; i < TOutputImage::ImageDimension; ++i) { if (spacing[i] < 0) { spacing[i] = -spacing[i]; for (unsigned j = 0; j < TOutputImage::ImageDimension; ++j) { direction[j][i] = -direction[j][i]; } } } output->SetSpacing(spacing); // Set the image spacing output->SetOrigin(origin); // Set the image origin output->SetDirection(direction); // Set the image direction cosines // Copy MetaDataDictionary from instantiated reader to output image. output->SetMetaDataDictionary(thisDic); this->SetMetaDataDictionary(thisDic); IndexType start; start.Fill(0); ImageRegionType region; region.SetSize(dimSize); region.SetIndex(start); // If a VectorImage, this requires us to set the // VectorLength before allocate if (strcmp(output->GetNameOfClass(), "VectorImage") == 0) { using AccessorFunctorType = typename TOutputImage::AccessorFunctorType; AccessorFunctorType::SetVectorLength(output, m_ImageIO->GetNumberOfComponents()); } output->SetLargestPossibleRegion(region); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::TestFileExistanceAndReadability() { // Test if the file exists. if (!itksys::SystemTools::FileExists(this->GetFileName().c_str())) { ImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "The file doesn't exist. " << std::endl << "Filename = " << this->GetFileName() << std::endl; e.SetDescription(msg.str().c_str()); throw e; return; } // Test if the file can be open for reading access. std::ifstream readTester; readTester.open(this->GetFileName().c_str()); if (readTester.fail()) { readTester.close(); std::ostringstream msg; msg << "The file couldn't be opened for reading. " << std::endl << "Filename: " << this->GetFileName() << std::endl; ImageFileReaderException e(__FILE__, __LINE__, msg.str().c_str(), ITK_LOCATION); throw e; return; } readTester.close(); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::EnlargeOutputRequestedRegion(DataObject * output) { itkDebugMacro(<< "Starting EnlargeOutputRequestedRegion() "); typename TOutputImage::Pointer out = dynamic_cast<TOutputImage *>(output); typename TOutputImage::RegionType largestRegion = out->GetLargestPossibleRegion(); ImageRegionType streamableRegion; // The following code converts the ImageRegion (templated over dimension) // into an ImageIORegion (not templated over dimension). ImageRegionType imageRequestedRegion = out->GetRequestedRegion(); ImageIORegion ioRequestedRegion(TOutputImage::ImageDimension); using ImageIOAdaptor = ImageIORegionAdaptor<TOutputImage::ImageDimension>; ImageIOAdaptor::Convert(imageRequestedRegion, ioRequestedRegion, largestRegion.GetIndex()); // Tell the IO if we should use streaming while reading m_ImageIO->SetUseStreamedReading(m_UseStreaming); // Delegate to the ImageIO the computation of how the // requested region must be enlarged. m_ActualIORegion = m_ImageIO->GenerateStreamableReadRegionFromRequestedRegion(ioRequestedRegion); // the m_ActualIORegion may be more dimensions then the output // Image, in which case we still need to read this larger region to // support reading the "first slice" of a larger image // see bug 9212 // convert the IORegion to a ImageRegion (which is dimension templated) // if the ImageIO must read a higher dimension region, this will // truncate the last dimensions ImageIOAdaptor::Convert(m_ActualIORegion, streamableRegion, largestRegion.GetIndex()); // Check whether the imageRequestedRegion is fully contained inside the // streamable region. Since, ImageRegion::IsInside regards zero // sized regions, as not being inside any other region, we must // specially check this condition to enable zero sized regions to // pass the region propagation phase of the pipeline. if (!streamableRegion.IsInside(imageRequestedRegion) && imageRequestedRegion.GetNumberOfPixels() != 0) { // we must use a InvalidRequestedRegionError since // DataObject::PropagateRequestedRegion() has an exception // specification std::ostringstream message; message << "ImageIO returns IO region that does not fully contain the requested region" << "Requested region: " << imageRequestedRegion << "StreamableRegion region: " << streamableRegion; InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription(message.str().c_str()); throw e; } itkDebugMacro(<< "RequestedRegion is set to:" << streamableRegion << " while the m_ActualIORegion is: " << m_ActualIORegion); out->SetRequestedRegion(streamableRegion); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::GenerateData() { this->UpdateProgress(0.0f); typename TOutputImage::Pointer output = this->GetOutput(); itkDebugMacro(<< "ImageFileReader::GenerateData() \n" << "Allocating the buffer with the EnlargedRequestedRegion \n" << output->GetRequestedRegion() << "\n"); // allocated the output image to the size of the enlarge requested region this->AllocateOutputs(); // Test if the file exists and if it can be opened. // An exception will be thrown otherwise, since we can't // successfully read the file. We catch the exception because some // ImageIO's may not actually open a file. Still // reports file error if no ImageIO is loaded. try { m_ExceptionMessage = ""; this->TestFileExistanceAndReadability(); } catch (const itk::ExceptionObject & err) { m_ExceptionMessage = err.GetDescription(); } // Tell the ImageIO to read the file m_ImageIO->SetFileName(this->GetFileName().c_str()); itkDebugMacro(<< "Setting imageIO IORegion to: " << m_ActualIORegion); m_ImageIO->SetIORegion(m_ActualIORegion); // the size of the buffer is computed based on the actual number of // pixels to be read and the actual size of the pixels to be read // (as opposed to the sizes of the output) size_t sizeOfActualIORegion = m_ActualIORegion.GetNumberOfPixels() * (m_ImageIO->GetComponentSize() * m_ImageIO->GetNumberOfComponents()); IOComponentEnum ioType = ImageIOBase::MapPixelType<typename ConvertPixelTraits::ComponentType>::CType; if (m_ImageIO->GetComponentType() != ioType || (m_ImageIO->GetNumberOfComponents() != ConvertPixelTraits::GetNumberOfComponents())) { // the pixel types don't match so a type conversion needs to be // performed itkDebugMacro(<< "Buffer conversion required from: " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType()) << " to: " << m_ImageIO->GetComponentTypeAsString(ioType) << " ConvertPixelTraits::NumComponents " << ConvertPixelTraits::GetNumberOfComponents() << " m_ImageIO->NumComponents " << m_ImageIO->GetNumberOfComponents()); const std::unique_ptr<char[]> loadBuffer(new char[sizeOfActualIORegion]); m_ImageIO->Read(static_cast<void *>(loadBuffer.get())); // See note below as to why the buffered region is needed and // not actualIOregion this->DoConvertBuffer(static_cast<void *>(loadBuffer.get()), output->GetBufferedRegion().GetNumberOfPixels()); } else if (m_ActualIORegion.GetNumberOfPixels() != output->GetBufferedRegion().GetNumberOfPixels()) { // NOTE: // for the number of pixels read and the number of pixels // requested to not match, the dimensions of the two regions may // be different, therefore we buffer and copy the pixels itkDebugMacro(<< "Buffer required because file dimension is greater then image dimension"); OutputImagePixelType * outputBuffer = output->GetPixelContainer()->GetBufferPointer(); const std::unique_ptr<char[]> loadBuffer(new char[sizeOfActualIORegion]); m_ImageIO->Read(static_cast<void *>(loadBuffer.get())); // we use std::copy_n here as it should be optimized to memcpy for // plain old data, but still is oop std::copy_n(reinterpret_cast<const OutputImagePixelType *>(loadBuffer.get()), output->GetBufferedRegion().GetNumberOfPixels(), outputBuffer); } else { itkDebugMacro(<< "No buffer conversion required."); OutputImagePixelType * outputBuffer = output->GetPixelContainer()->GetBufferPointer(); m_ImageIO->Read(outputBuffer); } this->UpdateProgress(1.0f); } template <typename TOutputImage, typename ConvertPixelTraits> void ImageFileReader<TOutputImage, ConvertPixelTraits>::DoConvertBuffer(void * inputData, size_t numberOfPixels) { // get the pointer to the destination buffer OutputImagePixelType * outputData = this->GetOutput()->GetPixelContainer()->GetBufferPointer(); bool isVectorImage(strcmp(this->GetOutput()->GetNameOfClass(), "VectorImage") == 0); // TODO: // Pass down the PixelType (RGB, VECTOR, etc.) so that any vector to // scalar conversion be type specific. i.e. RGB to scalar would use // a formula to convert to luminance, VECTOR to scalar would use // vector magnitude. // Create a macro as this code is a bit lengthy and repetitive // if the ImageIO pixel type is typeid(type) then use the ConvertPixelBuffer // class to convert the data block to TOutputImage's pixel type // see DefaultConvertPixelTraits and ConvertPixelBuffer // The first else if block applies only to images of type itk::VectorImage // VectorImage needs to copy out the buffer differently.. The buffer is of // type InternalPixelType, but each pixel is really 'k' consecutive pixels. #define ITK_CONVERT_BUFFER_IF_BLOCK(_CType, type) \ else if (m_ImageIO->GetComponentType() == _CType) \ { \ if (isVectorImage) \ { \ ConvertPixelBuffer<type, OutputImagePixelType, ConvertPixelTraits>::ConvertVectorImage( \ static_cast<type *>(inputData), m_ImageIO->GetNumberOfComponents(), outputData, numberOfPixels); \ } \ else \ { \ ConvertPixelBuffer<type, OutputImagePixelType, ConvertPixelTraits>::Convert( \ static_cast<type *>(inputData), m_ImageIO->GetNumberOfComponents(), outputData, numberOfPixels); \ } \ } if (false) { } ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::UCHAR, unsigned char) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::CHAR, char) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::USHORT, unsigned short) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::SHORT, short) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::UINT, unsigned int) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::INT, int) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::ULONG, unsigned long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::LONG, long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::ULONGLONG, unsigned long long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::LONGLONG, long long) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::FLOAT, float) ITK_CONVERT_BUFFER_IF_BLOCK(IOComponentEnum::DOUBLE, double) else { #define TYPENAME(x) m_ImageIO->GetComponentTypeAsString(ImageIOBase::MapPixelType<x>::CType) ImageFileReaderException e(__FILE__, __LINE__); std::ostringstream msg; msg << "Couldn't convert component type: " << std::endl << " " << m_ImageIO->GetComponentTypeAsString(m_ImageIO->GetComponentType()) << std::endl << "to one of: " << std::endl << " " << TYPENAME(unsigned char) << std::endl << " " << TYPENAME(char) << std::endl << " " << TYPENAME(unsigned short) << std::endl << " " << TYPENAME(short) << std::endl << " " << TYPENAME(unsigned int) << std::endl << " " << TYPENAME(int) << std::endl << " " << TYPENAME(unsigned long) << std::endl << " " << TYPENAME(long) << std::endl << " " << TYPENAME(unsigned long long) << std::endl << " " << TYPENAME(long long) << std::endl << " " << TYPENAME(float) << std::endl << " " << TYPENAME(double) << std::endl; e.SetDescription(msg.str().c_str()); e.SetLocation(ITK_LOCATION); throw e; return; } #undef ITK_CONVERT_BUFFER_IF_BLOCK } } // namespace itk #endif
38.675522
120
0.659356
bradking
d53a87a9e6e27378f7ec05288766cada1296d53f
1,628
cpp
C++
cpp/logger/Logger.cpp
yukonfb/profilo
baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375
[ "Apache-2.0" ]
null
null
null
cpp/logger/Logger.cpp
yukonfb/profilo
baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375
[ "Apache-2.0" ]
null
null
null
cpp/logger/Logger.cpp
yukonfb/profilo
baf0ef6e4c140f5b1cdf110b90698f9e8ca7c375
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2004-present, Facebook, 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 "Logger.h" #include <algorithm> #include <chrono> #include <cstring> #include <stdexcept> #include <util/common.h> namespace facebook { namespace profilo { using namespace entries; Logger::EntryIDCounter& Logger::getGlobalEntryID() { static EntryIDCounter global_instance{kDefaultInitialID}; return global_instance; } Logger::Logger(logger::TraceBufferProvider provider, EntryIDCounter& counter) : entryID_(counter), logger_(provider) {} int32_t Logger::writeBytes( EntryType type, int32_t arg1, const uint8_t* arg2, size_t len) { if (len > kMaxVariableLengthEntry) { throw std::overflow_error("len is bigger than kMaxVariableLengthEntry"); } if (arg2 == nullptr) { throw std::invalid_argument("arg2 is null"); } return write(BytesEntry{ .id = 0, .type = type, .matchid = arg1, .bytes = { .values = const_cast<uint8_t*>(arg2), .size = static_cast<uint16_t>(len)}}); } } // namespace profilo } // namespace facebook
26.258065
77
0.702703
yukonfb
d53ae992b6472b93886c119c8ad83a6aeb8a5983
35,578
cpp
C++
display-caf/sdm/libs/core/fb/hw_device.cpp
rahulsnair/android_device_motorola_athenecaf
52399442131dc51ea35cc6fcae1e49683b2bc60b
[ "FTL" ]
null
null
null
display-caf/sdm/libs/core/fb/hw_device.cpp
rahulsnair/android_device_motorola_athenecaf
52399442131dc51ea35cc6fcae1e49683b2bc60b
[ "FTL" ]
null
null
null
display-caf/sdm/libs/core/fb/hw_device.cpp
rahulsnair/android_device_motorola_athenecaf
52399442131dc51ea35cc6fcae1e49683b2bc60b
[ "FTL" ]
null
null
null
/* * Copyright (c) 2014 - 2015, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * 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. */ #define __STDC_FORMAT_MACROS #include <ctype.h> #include <math.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <inttypes.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <linux/fb.h> #include <utils/constants.h> #include <utils/debug.h> #include "hw_device.h" #define __CLASS__ "HWDevice" namespace sdm { HWDevice::HWDevice(BufferSyncHandler *buffer_sync_handler) : fb_node_index_(-1), fb_path_("/sys/devices/virtual/graphics/fb"), hotplug_enabled_(false), buffer_sync_handler_(buffer_sync_handler), synchronous_commit_(false) { #ifndef SDM_VIRTUAL_DRIVER // Pointer to actual driver interfaces. ioctl_ = ::ioctl; open_ = ::open; close_ = ::close; poll_ = ::poll; pread_ = ::pread; pwrite_ = ::pwrite; fopen_ = ::fopen; fclose_ = ::fclose; getline_ = ::getline; #else // Point to virtual driver interfaces. extern int virtual_ioctl(int fd, int cmd, ...); extern int virtual_open(const char *file_name, int access, ...); extern int virtual_close(int fd); extern int virtual_poll(struct pollfd *fds, nfds_t num, int timeout); extern ssize_t virtual_pread(int fd, void *data, size_t count, off_t offset); extern ssize_t virtual_pwrite(int fd, const void *data, size_t count, off_t offset); extern FILE* virtual_fopen(const char *fname, const char *mode); extern int virtual_fclose(FILE* fileptr); extern ssize_t virtual_getline(char **lineptr, size_t *linelen, FILE *stream); ioctl_ = virtual_ioctl; open_ = virtual_open; close_ = virtual_close; poll_ = virtual_poll; pread_ = virtual_pread; pwrite_ = virtual_pwrite; fopen_ = virtual_fopen; fclose_ = virtual_fclose; getline_ = virtual_getline; #endif } DisplayError HWDevice::Init() { DisplayError error = kErrorNone; // Read the fb node index fb_node_index_ = GetFBNodeIndex(device_type_); if (fb_node_index_ == -1) { DLOGE("%s should be present", device_name_); return kErrorHardware; } // Populate Panel Info (Used for Partial Update) PopulateHWPanelInfo(); // Populate HW Capabilities hw_resource_ = HWResourceInfo(); hw_info_intf_->GetHWResourceInfo(&hw_resource_); return error; } DisplayError HWDevice::Open(HWEventHandler *eventhandler) { DisplayError error = kErrorNone; char device_name[64] = {0}; // Store EventHandlers for two Physical displays, i.e., Primary and HDMI // TODO(user): Need to revisit for HDMI as Primary usecase event_handler_ = eventhandler; snprintf(device_name, sizeof(device_name), "%s%d", "/dev/graphics/fb", fb_node_index_); device_fd_ = open_(device_name, O_RDWR); if (device_fd_ < 0) { DLOGE("open %s failed err = %d errstr = %s", device_name, errno, strerror(errno)); return kErrorResources; } return error; } DisplayError HWDevice::Close() { if (device_fd_ > 0) { close_(device_fd_); } return kErrorNone; } DisplayError HWDevice::GetNumDisplayAttributes(uint32_t *count) { *count = 1; return kErrorNone; } DisplayError HWDevice::GetDisplayAttributes(HWDisplayAttributes *display_attributes, uint32_t index) { return kErrorNone; } DisplayError HWDevice::GetHWPanelInfo(HWPanelInfo *panel_info) { *panel_info = hw_panel_info_; return kErrorNone; } DisplayError HWDevice::SetDisplayAttributes(uint32_t index) { return kErrorNone; } DisplayError HWDevice::GetConfigIndex(uint32_t mode, uint32_t *index) { return kErrorNone; } DisplayError HWDevice::PowerOn() { DTRACE_SCOPED(); if (ioctl_(device_fd_, FBIOBLANK, FB_BLANK_UNBLANK) < 0) { IOCTL_LOGE(FB_BLANK_UNBLANK, device_type_); return kErrorHardware; } // Need to turn on HPD if (!hotplug_enabled_) { hotplug_enabled_ = EnableHotPlugDetection(1); } return kErrorNone; } DisplayError HWDevice::PowerOff() { return kErrorNone; } DisplayError HWDevice::Doze() { return kErrorNone; } DisplayError HWDevice::DozeSuspend() { return kErrorNone; } DisplayError HWDevice::Standby() { return kErrorNone; } DisplayError HWDevice::Validate(HWLayers *hw_layers) { DTRACE_SCOPED(); DisplayError error = kErrorNone; HWLayersInfo &hw_layer_info = hw_layers->info; LayerStack *stack = hw_layer_info.stack; DLOGV_IF(kTagDriverConfig, "************************** %s Validate Input ***********************", device_name_); DLOGV_IF(kTagDriverConfig, "SDE layer count is %d", hw_layer_info.count); mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1; uint32_t &mdp_layer_count = mdp_commit.input_layer_cnt; DLOGI_IF(kTagDriverConfig, "left_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.left_roi.x, mdp_commit.left_roi.y, mdp_commit.left_roi.w, mdp_commit.left_roi.h); DLOGI_IF(kTagDriverConfig, "right_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.right_roi.x, mdp_commit.right_roi.y, mdp_commit.right_roi.w, mdp_commit.right_roi.h); for (uint32_t i = 0; i < hw_layer_info.count; i++) { uint32_t layer_index = hw_layer_info.index[i]; Layer &layer = stack->layers[layer_index]; LayerBuffer *input_buffer = layer.input_buffer; HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe; HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; bool is_rotator_used = (hw_rotator_session->hw_block_count != 0); mdp_input_layer mdp_layer; for (uint32_t count = 0; count < 2; count++) { HWPipeInfo *pipe_info = (count == 0) ? left_pipe : right_pipe; HWRotateInfo *hw_rotate_info = &hw_rotator_session->hw_rotate_info[count]; if (hw_rotate_info->valid) { input_buffer = &hw_rotator_session->output_buffer; } if (pipe_info->valid) { mdp_input_layer &mdp_layer = mdp_in_layers_[mdp_layer_count]; mdp_layer_buffer &mdp_buffer = mdp_layer.buffer; mdp_buffer.width = input_buffer->width; mdp_buffer.height = input_buffer->height; mdp_buffer.comp_ratio.denom = 1000; mdp_buffer.comp_ratio.numer = UINT32(hw_layers->config[i].compression * 1000); error = SetFormat(input_buffer->format, &mdp_buffer.format); if (error != kErrorNone) { return error; } mdp_layer.alpha = layer.plane_alpha; mdp_layer.z_order = UINT16(pipe_info->z_order); mdp_layer.transp_mask = 0xffffffff; SetBlending(layer.blending, &mdp_layer.blend_op); mdp_layer.pipe_ndx = pipe_info->pipe_id; mdp_layer.horz_deci = pipe_info->horizontal_decimation; mdp_layer.vert_deci = pipe_info->vertical_decimation; SetRect(pipe_info->src_roi, &mdp_layer.src_rect); SetRect(pipe_info->dst_roi, &mdp_layer.dst_rect); SetMDPFlags(layer, is_rotator_used, &mdp_layer.flags); SetColorSpace(layer.color_space, &mdp_layer.color_space); if (pipe_info->scale_data.enable_pixel_ext) { if ((mdp_layer.flags & MDP_LAYER_DEINTERLACE) && (layer.transform.rotation == 90.0f)) { mdp_buffer.width = pipe_info->scale_data.src_width; } SetHWScaleData(pipe_info->scale_data, mdp_layer_count); } // Send scale data to MDP driver mdp_layer.scale = GetScaleDataRef(mdp_layer_count); mdp_layer_count++; DLOGV_IF(kTagDriverConfig, "******************* Layer[%d] %s pipe Input ******************", i, count ? "Right" : "Left"); DLOGV_IF(kTagDriverConfig, "in_w %d, in_h %d, in_f %d", mdp_buffer.width, mdp_buffer.height, mdp_buffer.format); DLOGV_IF(kTagDriverConfig, "plane_alpha %d, zorder %d, blending %d, horz_deci %d, " "vert_deci %d, pipe_id = 0x%x, mdp_flags 0x%x", mdp_layer.alpha, mdp_layer.z_order, mdp_layer.blend_op, mdp_layer.horz_deci, mdp_layer.vert_deci, mdp_layer.pipe_ndx, mdp_layer.flags); DLOGV_IF(kTagDriverConfig, "src_rect [%d, %d, %d, %d]", mdp_layer.src_rect.x, mdp_layer.src_rect.y, mdp_layer.src_rect.w, mdp_layer.src_rect.h); DLOGV_IF(kTagDriverConfig, "dst_rect [%d, %d, %d, %d]", mdp_layer.dst_rect.x, mdp_layer.dst_rect.y, mdp_layer.dst_rect.w, mdp_layer.dst_rect.h); for (int j = 0; j < 4; j++) { DLOGV_IF(kTagDriverConfig, "Scale Data[%d]: Phase=[%x %x %x %x] Pixel_Ext=[%d %d %d %d]", j, mdp_layer.scale->init_phase_x[j], mdp_layer.scale->phase_step_x[j], mdp_layer.scale->init_phase_y[j], mdp_layer.scale->phase_step_y[j], mdp_layer.scale->num_ext_pxls_left[j], mdp_layer.scale->num_ext_pxls_top[j], mdp_layer.scale->num_ext_pxls_right[j], mdp_layer.scale->num_ext_pxls_btm[j]); DLOGV_IF(kTagDriverConfig, "Fetch=[%d %d %d %d] Repeat=[%d %d %d %d] roi_width = %d", mdp_layer.scale->left_ftch[j], mdp_layer.scale->top_ftch[j], mdp_layer.scale->right_ftch[j], mdp_layer.scale->btm_ftch[j], mdp_layer.scale->left_rpt[j], mdp_layer.scale->top_rpt[j], mdp_layer.scale->right_rpt[j], mdp_layer.scale->btm_rpt[j], mdp_layer.scale->roi_w[j]); } DLOGV_IF(kTagDriverConfig, "*************************************************************"); } } } if (device_type_ == kDeviceVirtual) { LayerBuffer *output_buffer = hw_layers->info.stack->output_buffer; // TODO(user): Need to assign the writeback id from the resource manager, since the support // has not been added hard coding it to 2 for now. mdp_out_layer_.writeback_ndx = 2; mdp_out_layer_.buffer.width = output_buffer->width; mdp_out_layer_.buffer.height = output_buffer->height; mdp_out_layer_.buffer.comp_ratio.denom = 1000; mdp_out_layer_.buffer.comp_ratio.numer = UINT32(hw_layers->output_compression * 1000); SetFormat(output_buffer->format, &mdp_out_layer_.buffer.format); DLOGI_IF(kTagDriverConfig, "********************* Output buffer Info ************************"); DLOGI_IF(kTagDriverConfig, "out_w %d, out_h %d, out_f %d, wb_id %d", mdp_out_layer_.buffer.width, mdp_out_layer_.buffer.height, mdp_out_layer_.buffer.format, mdp_out_layer_.writeback_ndx); DLOGI_IF(kTagDriverConfig, "*****************************************************************"); } mdp_commit.flags |= MDP_VALIDATE_LAYER; if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) { IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_); DumpLayerCommit(mdp_disp_commit_); return kErrorHardware; } return kErrorNone; } void HWDevice::DumpLayerCommit(const mdp_layer_commit &layer_commit) { const mdp_layer_commit_v1 &mdp_commit = layer_commit.commit_v1; const mdp_input_layer *mdp_layers = mdp_commit.input_layers; DLOGE("mdp_commit: flags = %x, release fence = %x", mdp_commit.flags, mdp_commit.release_fence); DLOGE("left_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.left_roi.x, mdp_commit.left_roi.y, mdp_commit.left_roi.w, mdp_commit.left_roi.h); DLOGE("right_roi: x = %d, y = %d, w = %d, h = %d", mdp_commit.right_roi.x, mdp_commit.right_roi.y, mdp_commit.right_roi.w, mdp_commit.right_roi.h); for (uint32_t i = 0; i < mdp_commit.input_layer_cnt; i++) { DLOGE("mdp_commit: layer_cnt = %d, pipe_ndx = %x, zorder = %d, flags = %x", i, mdp_layers[i].pipe_ndx, mdp_layers[i].z_order, mdp_layers[i].flags); const mdp_rect &src_rect = mdp_layers[i].src_rect; DLOGE("src rect: x = %d, y = %d, w = %d, h = %d", src_rect.x, src_rect.y, src_rect.w, src_rect.h); const mdp_rect &dst_rect = mdp_layers[i].dst_rect; DLOGE("dst rect: x = %d, y = %d, w = %d, h = %d", dst_rect.x, dst_rect.y, dst_rect.w, dst_rect.h); } } DisplayError HWDevice::Commit(HWLayers *hw_layers) { DTRACE_SCOPED(); HWLayersInfo &hw_layer_info = hw_layers->info; LayerStack *stack = hw_layer_info.stack; DLOGV_IF(kTagDriverConfig, "*************************** %s Commit Input ************************", device_name_); DLOGV_IF(kTagDriverConfig, "SDE layer count is %d", hw_layer_info.count); mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1; uint32_t mdp_layer_index = 0; for (uint32_t i = 0; i < hw_layer_info.count; i++) { uint32_t layer_index = hw_layer_info.index[i]; LayerBuffer *input_buffer = stack->layers[layer_index].input_buffer; HWPipeInfo *left_pipe = &hw_layers->config[i].left_pipe; HWPipeInfo *right_pipe = &hw_layers->config[i].right_pipe; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; for (uint32_t count = 0; count < 2; count++) { HWPipeInfo *pipe_info = (count == 0) ? left_pipe : right_pipe; HWRotateInfo *hw_rotate_info = &hw_rotator_session->hw_rotate_info[count]; if (hw_rotate_info->valid) { input_buffer = &hw_rotator_session->output_buffer; } if (pipe_info->valid) { mdp_layer_buffer &mdp_buffer = mdp_in_layers_[mdp_layer_index].buffer; mdp_input_layer &mdp_layer = mdp_in_layers_[mdp_layer_index]; if (input_buffer->planes[0].fd >= 0) { mdp_buffer.plane_count = 1; mdp_buffer.planes[0].fd = input_buffer->planes[0].fd; mdp_buffer.planes[0].offset = input_buffer->planes[0].offset; SetStride(device_type_, input_buffer->format, input_buffer->planes[0].stride, &mdp_buffer.planes[0].stride); } else { DLOGW("Invalid buffer fd, setting plane count to 0"); mdp_buffer.plane_count = 0; } mdp_buffer.fence = input_buffer->acquire_fence_fd; mdp_layer_index++; DLOGV_IF(kTagDriverConfig, "****************** Layer[%d] %s pipe Input *******************", i, count ? "Right" : "Left"); DLOGI_IF(kTagDriverConfig, "in_w %d, in_h %d, in_f %d, horz_deci %d, vert_deci %d", mdp_buffer.width, mdp_buffer.height, mdp_buffer.format, mdp_layer.horz_deci, mdp_layer.vert_deci); DLOGI_IF(kTagDriverConfig, "in_buf_fd %d, in_buf_offset %d, in_buf_stride %d, " \ "in_plane_count %d, in_fence %d, layer count %d", mdp_buffer.planes[0].fd, mdp_buffer.planes[0].offset, mdp_buffer.planes[0].stride, mdp_buffer.plane_count, mdp_buffer.fence, mdp_commit.input_layer_cnt); DLOGV_IF(kTagDriverConfig, "*************************************************************"); } } } if (device_type_ == kDeviceVirtual) { LayerBuffer *output_buffer = hw_layers->info.stack->output_buffer; if (output_buffer->planes[0].fd >= 0) { mdp_out_layer_.buffer.planes[0].fd = output_buffer->planes[0].fd; mdp_out_layer_.buffer.planes[0].offset = output_buffer->planes[0].offset; SetStride(device_type_, output_buffer->format, output_buffer->planes[0].stride, &mdp_out_layer_.buffer.planes[0].stride); mdp_out_layer_.buffer.plane_count = 1; } else { DLOGW("Invalid output buffer fd, setting plane count to 0"); mdp_out_layer_.buffer.plane_count = 0; } mdp_out_layer_.buffer.fence = output_buffer->acquire_fence_fd; DLOGI_IF(kTagDriverConfig, "********************** Output buffer Info ***********************"); DLOGI_IF(kTagDriverConfig, "out_fd %d, out_offset %d, out_stride %d, acquire_fence %d", mdp_out_layer_.buffer.planes[0].fd, mdp_out_layer_.buffer.planes[0].offset, mdp_out_layer_.buffer.planes[0].stride, mdp_out_layer_.buffer.fence); DLOGI_IF(kTagDriverConfig, "*****************************************************************"); } mdp_commit.release_fence = -1; mdp_commit.flags &= ~MDP_VALIDATE_LAYER; if (synchronous_commit_) { mdp_commit.flags |= MDP_COMMIT_WAIT_FOR_FINISH; } if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) { IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_); DumpLayerCommit(mdp_disp_commit_); synchronous_commit_ = false; return kErrorHardware; } stack->retire_fence_fd = mdp_commit.retire_fence; // MDP returns only one release fence for the entire layer stack. Duplicate this fence into all // layers being composed by MDP. for (uint32_t i = 0; i < hw_layer_info.count; i++) { uint32_t layer_index = hw_layer_info.index[i]; LayerBuffer *input_buffer = stack->layers[layer_index].input_buffer; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; if (hw_rotator_session->hw_block_count) { input_buffer = &hw_rotator_session->output_buffer; } input_buffer->release_fence_fd = dup(mdp_commit.release_fence); } DLOGI_IF(kTagDriverConfig, "*************************** %s Commit Input ************************", device_name_); DLOGI_IF(kTagDriverConfig, "retire_fence_fd %d", stack->retire_fence_fd); DLOGI_IF(kTagDriverConfig, "*******************************************************************"); close_(mdp_commit.release_fence); if (synchronous_commit_) { // A synchronous commit can be requested when changing the display mode so we need to update // panel info. PopulateHWPanelInfo(); synchronous_commit_ = false; } return kErrorNone; } DisplayError HWDevice::Flush() { ResetDisplayParams(); mdp_layer_commit_v1 &mdp_commit = mdp_disp_commit_.commit_v1; mdp_commit.input_layer_cnt = 0; mdp_commit.output_layer = NULL; mdp_commit.flags &= ~MDP_VALIDATE_LAYER; if (ioctl_(device_fd_, MSMFB_ATOMIC_COMMIT, &mdp_disp_commit_) < 0) { IOCTL_LOGE(MSMFB_ATOMIC_COMMIT, device_type_); DumpLayerCommit(mdp_disp_commit_); return kErrorHardware; } return kErrorNone; } DisplayError HWDevice::SetFormat(const LayerBufferFormat &source, uint32_t *target) { switch (source) { case kFormatARGB8888: *target = MDP_ARGB_8888; break; case kFormatRGBA8888: *target = MDP_RGBA_8888; break; case kFormatBGRA8888: *target = MDP_BGRA_8888; break; case kFormatRGBX8888: *target = MDP_RGBX_8888; break; case kFormatBGRX8888: *target = MDP_BGRX_8888; break; case kFormatRGBA5551: *target = MDP_RGBA_5551; break; case kFormatRGBA4444: *target = MDP_RGBA_4444; break; case kFormatRGB888: *target = MDP_RGB_888; break; case kFormatBGR888: *target = MDP_BGR_888; break; case kFormatRGB565: *target = MDP_RGB_565; break; case kFormatYCbCr420Planar: *target = MDP_Y_CB_CR_H2V2; break; case kFormatYCrCb420Planar: *target = MDP_Y_CR_CB_H2V2; break; case kFormatYCbCr420SemiPlanar: *target = MDP_Y_CBCR_H2V2; break; case kFormatYCrCb420SemiPlanar: *target = MDP_Y_CRCB_H2V2; break; case kFormatYCbCr422H1V2SemiPlanar: *target = MDP_Y_CBCR_H1V2; break; case kFormatYCrCb422H1V2SemiPlanar: *target = MDP_Y_CRCB_H1V2; break; case kFormatYCbCr422H2V1SemiPlanar: *target = MDP_Y_CBCR_H2V1; break; case kFormatYCrCb422H2V1SemiPlanar: *target = MDP_Y_CRCB_H2V1; break; case kFormatYCbCr422H2V1Packed: *target = MDP_YCBYCR_H2V1; break; case kFormatYCbCr420SemiPlanarVenus: *target = MDP_Y_CBCR_H2V2_VENUS; break; case kFormatRGBA8888Ubwc: *target = MDP_RGBA_8888_UBWC; break; case kFormatRGBX8888Ubwc: *target = MDP_RGBX_8888_UBWC; break; case kFormatRGB565Ubwc: *target = MDP_RGB_565_UBWC; break; case kFormatYCbCr420SPVenusUbwc: *target = MDP_Y_CBCR_H2V2_UBWC; break; default: DLOGE("Unsupported format type %d", source); return kErrorParameters; } return kErrorNone; } DisplayError HWDevice::SetStride(HWDeviceType device_type, LayerBufferFormat format, uint32_t width, uint32_t *target) { // TODO(user): This SetStride function is a workaround to satisfy the driver expectation for // rotator and virtual devices. Eventually this will be taken care in the driver. if (device_type != kDeviceRotator && device_type != kDeviceVirtual) { *target = width; return kErrorNone; } switch (format) { case kFormatARGB8888: case kFormatRGBA8888: case kFormatBGRA8888: case kFormatRGBX8888: case kFormatBGRX8888: case kFormatRGBA8888Ubwc: case kFormatRGBX8888Ubwc: *target = width * 4; break; case kFormatRGB888: case kFormatBGR888: *target = width * 3; break; case kFormatRGB565: case kFormatRGB565Ubwc: *target = width * 2; break; case kFormatYCbCr420SemiPlanarVenus: case kFormatYCbCr420SPVenusUbwc: case kFormatYCbCr420Planar: case kFormatYCrCb420Planar: case kFormatYCbCr420SemiPlanar: case kFormatYCrCb420SemiPlanar: *target = width; break; case kFormatYCbCr422H2V1Packed: case kFormatYCrCb422H2V1SemiPlanar: case kFormatYCrCb422H1V2SemiPlanar: case kFormatYCbCr422H2V1SemiPlanar: case kFormatYCbCr422H1V2SemiPlanar: case kFormatRGBA5551: case kFormatRGBA4444: *target = width * 2; break; default: DLOGE("Unsupported format type %d", format); return kErrorParameters; } return kErrorNone; } void HWDevice::SetBlending(const LayerBlending &source, mdss_mdp_blend_op *target) { switch (source) { case kBlendingPremultiplied: *target = BLEND_OP_PREMULTIPLIED; break; case kBlendingCoverage: *target = BLEND_OP_COVERAGE; break; default: *target = BLEND_OP_NOT_DEFINED; break; } } void HWDevice::SetRect(const LayerRect &source, mdp_rect *target) { target->x = UINT32(source.left); target->y = UINT32(source.top); target->w = UINT32(source.right) - target->x; target->h = UINT32(source.bottom) - target->y; } void HWDevice::SetMDPFlags(const Layer &layer, const bool &is_rotator_used, uint32_t *mdp_flags) { LayerBuffer *input_buffer = layer.input_buffer; // Flips will be taken care by rotator, if layer uses rotator for downscale/rotation. So ignore // flip flags for MDP. if (!is_rotator_used) { if (layer.transform.flip_vertical) { *mdp_flags |= MDP_LAYER_FLIP_UD; } if (layer.transform.flip_horizontal) { *mdp_flags |= MDP_LAYER_FLIP_LR; } } if (input_buffer->flags.interlace) { *mdp_flags |= MDP_LAYER_DEINTERLACE; } if (input_buffer->flags.secure) { *mdp_flags |= MDP_LAYER_SECURE_SESSION; } if (input_buffer->flags.secure_display) { *mdp_flags |= MDP_SECURE_DISPLAY_OVERLAY_SESSION; } } void HWDevice::SyncMerge(const int &fd1, const int &fd2, int *target) { if (fd1 >= 0 && fd2 >= 0) { buffer_sync_handler_->SyncMerge(fd1, fd2, target); } else if (fd1 >= 0) { *target = fd1; } else if (fd2 >= 0) { *target = fd2; } } int HWDevice::GetFBNodeIndex(HWDeviceType device_type) { int fb_node_index = -1; for (int i = 0; i <= kDeviceVirtual; i++) { HWPanelInfo *panel_info = new HWPanelInfo(); GetHWPanelInfoByNode(i, panel_info); switch (device_type) { case kDevicePrimary: if (panel_info->is_primary_panel) { fb_node_index = i; } break; case kDeviceHDMI: if (panel_info->port == kPortDTv) { fb_node_index = i; } break; case kDeviceVirtual: if (panel_info->port == kPortWriteBack) { fb_node_index = i; } break; default: break; } } return fb_node_index; } void HWDevice::PopulateHWPanelInfo() { hw_panel_info_ = HWPanelInfo(); GetHWPanelInfoByNode(fb_node_index_, &hw_panel_info_); DLOGI("Device type = %d, Display Port = %d, Display Mode = %d, Device Node = %d, Is Primary = %d", device_type_, hw_panel_info_.port, hw_panel_info_.mode, fb_node_index_, hw_panel_info_.is_primary_panel); DLOGI("Partial Update = %d, Dynamic FPS = %d", hw_panel_info_.partial_update, hw_panel_info_.dynamic_fps); DLOGI("Align: left = %d, width = %d, top = %d, height = %d", hw_panel_info_.left_align, hw_panel_info_.width_align, hw_panel_info_.top_align, hw_panel_info_.height_align); DLOGI("ROI: min_width = %d, min_height = %d, need_merge = %d", hw_panel_info_.min_roi_width, hw_panel_info_.min_roi_height, hw_panel_info_.needs_roi_merge); DLOGI("FPS: min = %d, max =%d", hw_panel_info_.min_fps, hw_panel_info_.max_fps); DLOGI("Left Split = %d, Right Split = %d", hw_panel_info_.split_info.left_split, hw_panel_info_.split_info.right_split); DLOGI("Source Split Always = %d", hw_panel_info_.split_info.always_src_split); } void HWDevice::GetHWPanelInfoByNode(int device_node, HWPanelInfo *panel_info) { if (!panel_info) { DLOGE("PanelInfo pointer in invalid."); return; } char stringbuffer[kMaxStringLength]; FILE *fileptr = NULL; snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_panel_info", fb_path_, device_node); fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("Failed to open msm_fb_panel_info node device node %d", device_node); return; } size_t len = kMaxStringLength; ssize_t read; char *line = NULL; while ((read = getline(&line, &len, fileptr)) != -1) { uint32_t token_count = 0; const uint32_t max_count = 10; char *tokens[max_count] = { NULL }; if (!ParseLine(line, tokens, max_count, &token_count)) { if (!strncmp(tokens[0], "pu_en", strlen("pu_en"))) { panel_info->partial_update = atoi(tokens[1]); } else if (!strncmp(tokens[0], "xstart", strlen("xstart"))) { panel_info->left_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "walign", strlen("walign"))) { panel_info->width_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "ystart", strlen("ystart"))) { panel_info->top_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "halign", strlen("halign"))) { panel_info->height_align = atoi(tokens[1]); } else if (!strncmp(tokens[0], "min_w", strlen("min_w"))) { panel_info->min_roi_width = atoi(tokens[1]); } else if (!strncmp(tokens[0], "min_h", strlen("min_h"))) { panel_info->min_roi_height = atoi(tokens[1]); } else if (!strncmp(tokens[0], "roi_merge", strlen("roi_merge"))) { panel_info->needs_roi_merge = atoi(tokens[1]); } else if (!strncmp(tokens[0], "dyn_fps_en", strlen("dyn_fps_en"))) { panel_info->dynamic_fps = atoi(tokens[1]); } else if (!strncmp(tokens[0], "min_fps", strlen("min_fps"))) { panel_info->min_fps = atoi(tokens[1]); } else if (!strncmp(tokens[0], "max_fps", strlen("max_fps"))) { panel_info->max_fps = atoi(tokens[1]); } else if (!strncmp(tokens[0], "primary_panel", strlen("primary_panel"))) { panel_info->is_primary_panel = atoi(tokens[1]); } } } fclose(fileptr); free(line); panel_info->port = GetHWDisplayPort(device_node); panel_info->mode = GetHWDisplayMode(device_node); GetSplitInfo(device_node, panel_info); } HWDisplayPort HWDevice::GetHWDisplayPort(int device_node) { char stringbuffer[kMaxStringLength]; DisplayError error = kErrorNone; char *line = NULL; size_t len = kMaxStringLength; ssize_t read; HWDisplayPort port = kPortDefault; snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_type", fb_path_, device_node); FILE *fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return port; } read = getline(&line, &len, fileptr); if (read == -1) { fclose(fileptr); return port; } if ((strncmp(line, "mipi dsi cmd panel", strlen("mipi dsi cmd panel")) == 0)) { port = kPortDSI; } else if ((strncmp(line, "mipi dsi video panel", strlen("mipi dsi video panel")) == 0)) { port = kPortDSI; } else if ((strncmp(line, "lvds panel", strlen("lvds panel")) == 0)) { port = kPortLVDS; } else if ((strncmp(line, "edp panel", strlen("edp panel")) == 0)) { port = kPortEDP; } else if ((strncmp(line, "dtv panel", strlen("dtv panel")) == 0)) { port = kPortDTv; } else if ((strncmp(line, "writeback panel", strlen("writeback panel")) == 0)) { port = kPortWriteBack; } else { port = kPortDefault; } fclose(fileptr); free(line); return port; } HWDisplayMode HWDevice::GetHWDisplayMode(int device_node) { char stringbuffer[kMaxStringLength]; DisplayError error = kErrorNone; char *line = NULL; size_t len = kMaxStringLength; ssize_t read; HWDisplayMode mode = kModeDefault; snprintf(stringbuffer, sizeof(stringbuffer), "%s%d/msm_fb_type", fb_path_, device_node); FILE *fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return mode; } read = getline(&line, &len, fileptr); if (read == -1) { fclose(fileptr); return mode; } if ((strncmp(line, "mipi dsi cmd panel", strlen("mipi dsi cmd panel")) == 0)) { mode = kModeCommand; } else if ((strncmp(line, "mipi dsi video panel", strlen("mipi dsi video panel")) == 0)) { mode = kModeVideo; } else { mode = kModeDefault; } fclose(fileptr); free(line); return mode; } void HWDevice::GetSplitInfo(int device_node, HWPanelInfo *panel_info) { char stringbuffer[kMaxStringLength]; FILE *fileptr = NULL; size_t len = kMaxStringLength; ssize_t read; char *line = NULL; uint32_t token_count = 0; const uint32_t max_count = 10; char *tokens[max_count] = { NULL }; // Split info - for MDSS Version 5 - No need to check version here snprintf(stringbuffer , sizeof(stringbuffer), "%s%d/msm_fb_split", fb_path_, device_node); fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return; } // Format "left right" space as delimiter read = getline(&line, &len, fileptr); if (read != -1) { if (!ParseLine(line, tokens, max_count, &token_count)) { panel_info->split_info.left_split = atoi(tokens[0]); panel_info->split_info.right_split = atoi(tokens[1]); } } fclose(fileptr); // SourceSplit enabled - Get More information snprintf(stringbuffer , sizeof(stringbuffer), "%s%d/msm_fb_src_split_info", fb_path_, device_node); fileptr = fopen(stringbuffer, "r"); if (!fileptr) { DLOGW("File not found %s", stringbuffer); return; } read = getline(&line, &len, fileptr); if (read != -1) { if (!strncmp(line, "src_split_always", strlen("src_split_always"))) { panel_info->split_info.always_src_split = true; } } fclose(fileptr); free(line); } int HWDevice::ParseLine(char *input, char *tokens[], const uint32_t max_token, uint32_t *count) { char *tmp_token = NULL; char *temp_ptr; uint32_t index = 0; const char *delim = ", =\n"; if (!input) { return -1; } tmp_token = strtok_r(input, delim, &temp_ptr); while (tmp_token && index < max_token) { tokens[index++] = tmp_token; tmp_token = strtok_r(NULL, delim, &temp_ptr); } *count = index; return 0; } bool HWDevice::EnableHotPlugDetection(int enable) { bool ret_value = true; char hpdpath[kMaxStringLength]; int hdmi_node_index = GetFBNodeIndex(kDeviceHDMI); snprintf(hpdpath , sizeof(hpdpath), "%s%d/hpd", fb_path_, hdmi_node_index); int hpdfd = open_(hpdpath, O_RDWR, 0); if (hpdfd < 0) { DLOGE("Open failed = %s", hpdpath); return kErrorHardware; } char value = enable ? '1' : '0'; ssize_t length = pwrite_(hpdfd, &value, 1, 0); if (length <= 0) { DLOGE("Write failed 'hpd' = %d", enable); ret_value = false; } close_(hpdfd); return ret_value; } void HWDevice::ResetDisplayParams() { memset(&mdp_disp_commit_, 0, sizeof(mdp_disp_commit_)); memset(&mdp_in_layers_, 0, sizeof(mdp_in_layers_)); memset(&mdp_out_layer_, 0, sizeof(mdp_out_layer_)); memset(&scale_data_, 0, sizeof(scale_data_)); for (uint32_t i = 0; i < kMaxSDELayers * 2; i++) { mdp_in_layers_[i].buffer.fence = -1; } mdp_disp_commit_.version = MDP_COMMIT_VERSION_1_0; mdp_disp_commit_.commit_v1.input_layers = mdp_in_layers_; mdp_disp_commit_.commit_v1.output_layer = &mdp_out_layer_; mdp_disp_commit_.commit_v1.release_fence = -1; mdp_disp_commit_.commit_v1.retire_fence = -1; } void HWDevice::SetHWScaleData(const ScaleData &scale, uint32_t index) { mdp_scale_data *mdp_scale = GetScaleDataRef(index); mdp_scale->enable_pxl_ext = scale.enable_pixel_ext; for (int i = 0; i < 4; i++) { const HWPlane &plane = scale.plane[i]; mdp_scale->init_phase_x[i] = plane.init_phase_x; mdp_scale->phase_step_x[i] = plane.phase_step_x; mdp_scale->init_phase_y[i] = plane.init_phase_y; mdp_scale->phase_step_y[i] = plane.phase_step_y; mdp_scale->num_ext_pxls_left[i] = plane.left.extension; mdp_scale->left_ftch[i] = plane.left.overfetch; mdp_scale->left_rpt[i] = plane.left.repeat; mdp_scale->num_ext_pxls_top[i] = plane.top.extension; mdp_scale->top_ftch[i] = plane.top.overfetch; mdp_scale->top_rpt[i] = plane.top.repeat; mdp_scale->num_ext_pxls_right[i] = plane.right.extension; mdp_scale->right_ftch[i] = plane.right.overfetch; mdp_scale->right_rpt[i] = plane.right.repeat; mdp_scale->num_ext_pxls_btm[i] = plane.bottom.extension; mdp_scale->btm_ftch[i] = plane.bottom.overfetch; mdp_scale->btm_rpt[i] = plane.bottom.repeat; mdp_scale->roi_w[i] = plane.roi_width; } } void HWDevice::SetColorSpace(LayerColorSpace source, mdp_color_space *color_space) { switch (source) { case kLimitedRange601: *color_space = MDP_CSC_ITU_R_601; break; case kFullRange601: *color_space = MDP_CSC_ITU_R_601_FR; break; case kLimitedRange709: *color_space = MDP_CSC_ITU_R_709; break; } } } // namespace sdm
37.728526
100
0.669093
rahulsnair
d53b979723cc0e85ed1a29b0b3ad214062ec0e8a
1,538
hpp
C++
Common/Code/IndexBox.hpp
steamclock/internetmap
13bf01e8e1fde8db64ce8fd417a1c907783100ee
[ "MIT" ]
22
2017-07-11T20:31:16.000Z
2021-04-04T16:00:10.000Z
Common/Code/IndexBox.hpp
steamclock/internetmap
13bf01e8e1fde8db64ce8fd417a1c907783100ee
[ "MIT" ]
197
2017-07-06T16:53:59.000Z
2019-05-31T17:57:51.000Z
Common/Code/IndexBox.hpp
steamclock/internetmap
13bf01e8e1fde8db64ce8fd417a1c907783100ee
[ "MIT" ]
10
2017-12-08T21:58:58.000Z
2021-03-20T07:16:47.000Z
// // IndexBox.h // InternetMap // // Created by Alexander on 11.12.12. // Copyright (c) 2012 Peer1. All rights reserved. // #ifndef InternetMap_IndexBox_hpp #define InternetMap_IndexBox_hpp #include "Types.hpp" #include <set> static const float IndexBoxMinX = -8; static const float IndexBoxMaxX = 8; static const float IndexBoxMinY = -2.1; static const float IndexBoxMaxY = 2.1; static const float IndexBoxMinZ = -2.1; static const float IndexBoxMaxZ = 2.1; static const float lengthX = -IndexBoxMinX + IndexBoxMaxX; static const float lengthY = -IndexBoxMinY + IndexBoxMaxY; static const float lengthZ = -IndexBoxMinZ + IndexBoxMaxZ; static const int numberOfCellsX = 32; static const int numberOfCellsY = 4; static const int numberOfCellsZ = 4; static const float boxSizeXWithoutOverlap = lengthX/numberOfCellsX; static const float boxSizeYWithoutOverlap = lengthY/numberOfCellsY; static const float boxSizeZWithoutOverlap = lengthZ/numberOfCellsZ; class IndexBox { Point3 _parameters[2]; Point3 _center; Point3 _minCorner; Point3 _maxCorner; public: std::set<int> indices; bool isPointInside(const Point3& point); bool doesLineIntersectOptimized(const Vector3& origin, const Vector3& invertedDirection, int* sign); Point3 minCorner(); Point3 maxCorner(); Point3 center(); void setMinCorner(const Point3& minCorner); void setMaxCorner(const Point3& maxCorner); void setCenter(const Point3& center); }; typedef shared_ptr<IndexBox> IndexBoxPointer; #endif
27.464286
104
0.750975
steamclock
d53c45114c8012f5752f54f4512f150a527c151e
13,132
cpp
C++
Modules/Scene/vaCameraControllers.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
110
2018-09-04T20:33:59.000Z
2021-12-17T08:46:11.000Z
Modules/Scene/vaCameraControllers.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
5
2018-09-05T20:57:08.000Z
2021-02-24T09:02:31.000Z
Modules/Scene/vaCameraControllers.cpp
magcius/CMAA2
8ceb0daa2afa6b12804da62631494d2ed4b31b53
[ "Apache-2.0" ]
20
2018-09-05T00:41:13.000Z
2021-08-04T01:31:50.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Intel Corporation // 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. /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Author(s): Filip Strugar (filip.strugar@intel.com) // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "vaCameraControllers.h" #include "vaCameraBase.h" #include "Core/vaInput.h" #include "IntegratedExternals/vaImguiIntegration.h" using namespace VertexAsylum; void vaCameraControllerBase::CameraAttached( const shared_ptr<vaCameraBase> & camera ) { if( camera == nullptr ) { assert( !m_attachedCamera.expired() ); m_attachedCamera.reset(); } else { assert( m_attachedCamera.expired() ); m_attachedCamera = camera; } } vaCameraControllerFreeFlight::vaCameraControllerFreeFlight( ) // orient the camera so that X is forward, Z is up, Y is right : m_baseOrientation( vaMatrix4x4::RotationZ( VA_PIf * 0.5f ) * vaMatrix4x4::RotationY( VA_PIf * 0.5f ) ) { // m_hasFocus = true; // temporary m_accumMouseDeltaX = 0.0f; m_accumMouseDeltaY = 0.0f; m_accumMove = vaVector3( 0.0f, 0.0f, 0.0f ); m_rotationSpeed = 0.5f; m_movementSpeed = 20.0f; m_inputSmoothingLerpK = 200.0f; m_yaw = 0.0f; m_pitch = 0.0f; // look towards x m_roll = 0.0f; // y is right m_movementSpeedAccelerationModifier = 0.0f; m_moveWhileNotCaptured = true; } vaCameraControllerFreeFlight::~vaCameraControllerFreeFlight( ) { } void vaCameraControllerFreeFlight::CameraAttached( const shared_ptr<vaCameraBase> & camera ) { vaCameraControllerBase::CameraAttached( camera ); if( camera != nullptr ) { // extract yaw/pitch from attached camera vaMatrix4x4 debasedOrientation = m_baseOrientation.Inverse() * vaMatrix4x4::FromQuaternion( camera->GetOrientation() ); debasedOrientation.DecomposeRotationYawPitchRoll( m_yaw, m_pitch, m_roll ); m_roll = 0; } } void vaCameraControllerFreeFlight::CameraTick( float deltaTime, vaCameraBase & camera, bool hasFocus ) { if( ( vaInputMouseBase::GetCurrent( ) == NULL ) || ( vaInputKeyboardBase::GetCurrent( ) == NULL ) ) return; vaVector3 objectPos = camera.GetPosition(); vaQuaternion objectOri = camera.GetOrientation(); vaInputMouseBase & mouse = *vaInputMouseBase::GetCurrent(); vaInputKeyboardBase & keyboard = *vaInputKeyboardBase::GetCurrent( ); { float smoothingLerpK = vaMath::TimeIndependentLerpF( deltaTime, m_inputSmoothingLerpK ); float speedBoost = 1.0f; if( hasFocus ) { speedBoost *= (keyboard.IsKeyDown( KK_SHIFT ))?(12.0f):(1.0f); speedBoost *= keyboard.IsKeyDown( KK_CONTROL )?(0.08f):(1.0f); if( keyboard.IsKeyDown( KK_SHIFT ) && keyboard.IsKeyDown( KK_MENU ) ) speedBoost *= 10.0f; } // /////////////////////////////////////////////////////////////////////////// // Update camera range/speed changes if( hasFocus ) { if( keyboard.IsKeyDown( KK_SUBTRACT ) ) m_movementSpeed *= 0.95f; if( keyboard.IsKeyDown( KK_ADD ) ) m_movementSpeed *= 1.05f; m_movementSpeed = vaMath::Clamp( m_movementSpeed, 1.0f, 5000.0f ); //if( vaIsKeyClicked( kcViewRangeDown ) ) m_viewRange *= 0.99f; //if( vaIsKeyClicked( kcViewRangeUp ) ) m_viewRange *= 1.01f; //m_viewRange = vaMath::Clamp( m_viewRange, 1000.0f, 1000000.0f ); // } /////////////////////////////////////////////////////////////////////////// // Update camera rotation vaVector2 cdelta = vaVector2( 0.0f, 0.0f ); if( hasFocus ) cdelta = (vaVector2)mouse.GetCursorDelta( ) * m_rotationSpeed; // // smoothing { m_accumMouseDeltaX += cdelta.x; m_accumMouseDeltaY += cdelta.y; cdelta.x = smoothingLerpK * m_accumMouseDeltaX; cdelta.y = smoothingLerpK * m_accumMouseDeltaY; m_accumMouseDeltaX = (1 - smoothingLerpK) * m_accumMouseDeltaX; m_accumMouseDeltaY = (1 - smoothingLerpK) * m_accumMouseDeltaY; } // // Rotate if( mouse.IsCaptured( ) ) { if( mouse.IsKeyDown( MK_Middle ) ) m_roll -= cdelta.x * 0.005f; else m_yaw += cdelta.x * 0.005f; m_pitch += cdelta.y * 0.003f; m_yaw = vaMath::AngleWrap( m_yaw ); m_pitch = vaMath::Clamp( m_pitch, -(float)VA_PIf/2 + 1e-1f, +(float)VA_PIf/2 - 1e-1f ); m_roll = vaMath::AngleWrap( m_roll ); } #if 1 { // round yaw/pitch/roll slightly to avoid precision errors causing non-determinism when saving/loading cameras; 5 is precise enough for 10x zoom sniping (fov/10) but stepping could potential be seen with 100x int precisionTrimDecimals = 5; float k = vaMath::Pow( 10, (float)precisionTrimDecimals ); m_yaw = vaMath::Round(m_yaw * k)/k; m_pitch = vaMath::Round(m_pitch * k)/k; m_roll = vaMath::Round(m_roll * k)/k; } #endif // vaMatrix4x4 cameraWorld = vaMatrix4x4::FromYawPitchRoll( m_yaw, m_pitch, m_roll ); // // Move if( mouse.IsCaptured() || m_moveWhileNotCaptured ) { /////////////////////////////////////////////////////////////////////////// // Update camera movement bool hasInput = false; if( hasFocus ) { hasInput = keyboard.IsKeyDown( (vaKeyboardKeys)'W' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'S' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'A' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'D' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'Q' ) || keyboard.IsKeyDown( (vaKeyboardKeys)'E' ); } m_movementSpeedAccelerationModifier = (hasInput)?(vaMath::Min(m_movementSpeedAccelerationModifier + deltaTime * 0.5f, 1.0f)):(0.0f); float moveSpeed = m_movementSpeed * deltaTime * ( 0.3f + 0.7f * m_movementSpeedAccelerationModifier ) * speedBoost; vaVector3 forward( cameraWorld.GetAxisX() ); vaVector3 right( cameraWorld.GetAxisY() ); vaVector3 up( cameraWorld.GetAxisZ() ); vaVector3 accumMove = m_accumMove; if( hasFocus ) { if( keyboard.IsKeyDown( (vaKeyboardKeys)'W' ) || keyboard.IsKeyDown( KK_UP ) ) accumMove += forward * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'S' ) || keyboard.IsKeyDown( KK_DOWN ) ) accumMove -= forward * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'D' ) || keyboard.IsKeyDown( KK_RIGHT ) ) accumMove += right * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'A' ) || keyboard.IsKeyDown( KK_LEFT ) ) accumMove -= right * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'Q' ) ) accumMove -= up * moveSpeed; if( keyboard.IsKeyDown( (vaKeyboardKeys)'E' ) ) accumMove += up * moveSpeed; } objectPos += accumMove * smoothingLerpK; m_accumMove = accumMove * (1-smoothingLerpK); } objectOri = vaQuaternion::FromRotationMatrix( m_baseOrientation * cameraWorld ); } camera.SetPosition( objectPos ); camera.SetOrientation( objectOri ); } vaCameraControllerFlythrough::vaCameraControllerFlythrough( ) { m_currentTime = 0.0f; m_totalTime = 0.0f; //m_userParam0 = 0.0f; //m_userParam1 = 0.0f; m_playSpeed = 1.0f; m_enableLoop = true; m_fixedUp = false; m_fixedUpVec = vaVector3( 0.0f, 0.0f, 1.0f ); } vaCameraControllerFlythrough::~vaCameraControllerFlythrough( ) { } void vaCameraControllerFlythrough::CameraAttached( const shared_ptr<vaCameraBase> & camera ) { vaCameraControllerBase::CameraAttached( camera ); } bool vaCameraControllerFlythrough::FindKeys( float time, int & keyIndexFrom, int & keyIndexTo ) { time = vaMath::Clamp( time, 0.0f, m_totalTime ); if( m_keys.size() == 0 ) return false; keyIndexFrom = 0; keyIndexTo = 0; if( m_keys.size() == 1 ) return true; // linear search - find binary in std:: algorithms when more perf needed :) for( keyIndexTo = 1; keyIndexTo < m_keys.size(); keyIndexTo++ ) { if( m_keys[keyIndexTo].Time >= time ) break; } keyIndexFrom = keyIndexTo-1; return true; } void vaCameraControllerFlythrough::CameraTick( float deltaTime, vaCameraBase & camera, bool hasFocus ) { hasFocus; //unreferenced if( m_keys.size( ) == 0 ) return; SetPlayTime( GetPlayTime() + deltaTime * GetPlaySpeed() ); int indexFrom, indexTo; if( !FindKeys( GetPlayTime(), indexFrom, indexTo ) ) return; Keyframe & keyFrom = m_keys[indexFrom]; Keyframe & keyTo = m_keys[indexTo]; float timeBetweenKeys = keyTo.Time - keyFrom.Time; timeBetweenKeys = vaMath::Max( 0.00001f, timeBetweenKeys ); float lerpK = vaMath::Clamp( (m_currentTime-keyFrom.Time) / timeBetweenKeys, 0.0f, 1.0f ); //lerpK = vaMath::Smoothstep( lerpK ); vaVector3 pos = vaVector3::Lerp( keyFrom.Position, keyTo.Position, lerpK ); vaQuaternion rot = vaQuaternion::Slerp( keyFrom.Orientation, keyTo.Orientation, lerpK ); #if 1 int index0 = vaMath::Max( 0, indexFrom-1 ); int index1 = indexFrom; int index2 = indexTo; int index3 = vaMath::Min( (int)m_keys.size()-1, indexTo+1 ); Keyframe & key0 = m_keys[index0]; Keyframe & key1 = m_keys[index1]; Keyframe & key2 = m_keys[index2]; Keyframe & key3 = m_keys[index3]; pos = vaVector3::CatmullRom( key0.Position, key1.Position, key2.Position, key3.Position, lerpK ); //pos = vaVector3::Hermite( key1.Position, (key2.Position - key0.Position).Normalized(), key2.Position, (key3.Position - key1.Position).Normalized(), lerpK ); //rot = vaQuaternion::Squad( key0.Orientation, key1.Orientation, key2.Orientation, key3.Orientation, lerpK ); //rot = vaQuaternion::Slerp( key0.Orientation, key1.Orientation, lerpK ); rot = vaQuaternion::CatmullRom( key0.Orientation, key1.Orientation, key2.Orientation, key3.Orientation, lerpK ); #endif if( m_fixedUp ) { vaVector3 currentUp = rot.GetAxisY(); vaVector3 rotAxis = vaVector3::Cross( currentUp, m_fixedUpVec ); float rotAngle = vaVector3::AngleBetweenVectors( currentUp, m_fixedUpVec ); rot *= vaQuaternion::RotationAxis( rotAxis, rotAngle ); } // float lf = vaMath::TimeIndependentLerpF( deltaTime, 5.0f / (currentKey.ShowTime+2.0f) ); // // pos = vaMath::Lerp( camera.GetPosition(), pos, lf ); // rot = vaQuaternion::Slerp( camera.GetOrientation(), rot, lf ); camera.SetPosition( pos ); camera.SetOrientation( rot ); } void vaCameraControllerFlythrough::AddKey( const Keyframe & newKey ) { vector< Keyframe >::iterator it = std::lower_bound( m_keys.begin( ), m_keys.end( ), newKey, ( [ this ]( const Keyframe & a, const Keyframe & b ) { return a.Time < b.Time; } ) ); m_keys.insert( it, newKey ); // insert before iterator it m_totalTime = m_keys.back().Time; } void vaCameraControllerFlythrough::UIPropertiesItemDraw( ) { #ifdef VA_IMGUI_INTEGRATION_ENABLED //ImGui::Text( "Time: %", m_currentTime ); ImGui::SliderFloat( "Playback position", &m_currentTime, 0.0f, m_totalTime ); m_currentTime = vaMath::Clamp( m_currentTime, 0.0f, m_totalTime ); ImGui::InputFloat( "Playback speed", &m_playSpeed, 0.2f ); m_playSpeed = vaMath::Clamp( m_playSpeed, -10.0f, 10.0f ); #endif }
41.0375
216
0.611407
magcius
d53cbc8233243df4139baac58b76bcfabc65507d
286
cpp
C++
Presto/src/Presto/Components/Electronics/Communication/Channel.cpp
mradrianhh/Presto
a43f87507daa094e887df4046c8664b1e6132187
[ "Apache-2.0" ]
1
2022-02-01T03:51:10.000Z
2022-02-01T03:51:10.000Z
Presto/src/Presto/Components/Electronics/Communication/Channel.cpp
mradrianhh/Presto
a43f87507daa094e887df4046c8664b1e6132187
[ "Apache-2.0" ]
null
null
null
Presto/src/Presto/Components/Electronics/Communication/Channel.cpp
mradrianhh/Presto
a43f87507daa094e887df4046c8664b1e6132187
[ "Apache-2.0" ]
null
null
null
#include "prestopch.h" #include "Channel.h" #include "Presto/Components/Electronics/Communication/Signals/ISignal.h" namespace Presto { void Channel::Send(ISignal* signal) { m_Signal = signal; } ISignal* Channel::Read() { return m_Signal; } }
15.888889
72
0.63986
mradrianhh
d53cf336010d073a46734c47291497b2dc4962d6
2,497
cc
C++
chrome/browser/ui/webui/print_preview_ui_uitest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/ui/webui/print_preview_ui_uitest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/ui/webui/print_preview_ui_uitest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2020-01-12T00:55:53.000Z
2020-11-04T06:36:41.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_command_ids.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { class PrintPreviewUITest : public UITest { public: PrintPreviewUITest() { dom_automation_enabled_ = true; // TODO(thestig): Remove when print preview is enabled by default. launch_arguments_.AppendSwitch(switches::kEnablePrintPreview); } void AssertIsPrintPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_PRINT_PREVIEW_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; // TODO(thestig) Remove this test in the future if loading // chrome::kChromeUIPrintURL directly does not make sense. TEST_F(PrintPreviewUITest, LoadPrintPreviewByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the print preview tab via URL. NavigateToURL(GURL(chrome::kChromeUIPrintURL)); AssertIsPrintPage(tab); } TEST_F(PrintPreviewUITest, PrintCommandDisabled) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); // Go to the about:blank page. NavigateToURL(GURL(chrome::kAboutBlankURL)); // Make sure there is 1 tab and print is enabled. Create print preview tab. int tab_count; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); bool enabled; ASSERT_TRUE(browser->IsMenuCommandEnabled(IDC_PRINT, &enabled)); ASSERT_TRUE(enabled); ASSERT_TRUE(browser->RunCommand(IDC_PRINT)); // Make sure there are 2 tabs and print is disabled. ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsPrintPage(tab); ASSERT_TRUE(browser->IsMenuCommandEnabled(IDC_PRINT, &enabled)); ASSERT_FALSE(enabled); } } // namespace
32.855263
77
0.755707
SlimKatLegacy
d5411a6e6847c2c0491ca39d39d322e459ea5dec
1,055
cpp
C++
library/view/widget/default_theme_provider.cpp
topillar/PuTTY-ng
1f5bf26de0f42e03ef4f100fa879b16216d61abf
[ "MIT" ]
39
2019-06-22T12:25:54.000Z
2022-03-14T05:42:44.000Z
library/view/widget/default_theme_provider.cpp
topillar/PuTTY-ng
1f5bf26de0f42e03ef4f100fa879b16216d61abf
[ "MIT" ]
5
2019-06-29T10:58:43.000Z
2020-09-04T08:44:09.000Z
library/view/widget/default_theme_provider.cpp
topillar/PuTTY-ng
1f5bf26de0f42e03ef4f100fa879b16216d61abf
[ "MIT" ]
10
2019-08-07T06:08:23.000Z
2022-03-14T05:42:47.000Z
#include "default_theme_provider.h" #include "ui_base/resource/resource_bundle.h" #include "view/widget/native_widget_win.h" namespace view { DefaultThemeProvider::DefaultThemeProvider() {} DefaultThemeProvider::~DefaultThemeProvider() {} void DefaultThemeProvider::Init(Profile* profile) {} SkBitmap* DefaultThemeProvider::GetBitmapNamed(int id) const { return ui::ResourceBundle::GetSharedInstance().GetBitmapNamed(id); } SkColor DefaultThemeProvider::GetColor(int id) const { // Return debugging-blue. return 0xff0000ff; } bool DefaultThemeProvider::GetDisplayProperty(int id, int* result) const { return false; } bool DefaultThemeProvider::ShouldUseNativeFrame() const { return NativeWidgetWin::IsAeroGlassEnabled(); } bool DefaultThemeProvider::HasCustomImage(int id) const { return false; } RefCountedMemory* DefaultThemeProvider::GetRawData(int id) const { return NULL; } } //namespace view
21.979167
76
0.685308
topillar
d54233e19b83a05d8b9ce887d61da3a86ba34120
20,804
cpp
C++
TESTS/stepper_motor/base/main.cpp
vznncv/vznncv-stepper-driver
c933152dc421ea7ffa61b4916966ce73734f93fa
[ "MIT" ]
2
2021-07-28T11:51:37.000Z
2022-02-17T20:23:59.000Z
TESTS/stepper_motor/base/main.cpp
vznncv/vznncv-stepper-driver
c933152dc421ea7ffa61b4916966ce73734f93fa
[ "MIT" ]
null
null
null
TESTS/stepper_motor/base/main.cpp
vznncv/vznncv-stepper-driver
c933152dc421ea7ffa61b4916966ce73734f93fa
[ "MIT" ]
null
null
null
#include <cmath> #include "greentea-client/test_env.h" #include "mbed.h" #include "unity.h" #include "utest.h" #include "vznncv_stepper_motor.h" #include "vznncv_stepper_motor_extra.h" using namespace utest::v1; using vznncvsteppermotor::BaseStepperMotor; using vznncvsteppermotor::microseconds_u32; using vznncvsteppermotor::SimpleSequenceWrapper; //-------------------------------- // test setup functions //-------------------------------- static utest::v1::status_t app_test_setup_handler(const size_t number_of_cases) { // common setup code ... return greentea_test_setup_handler(number_of_cases); } static utest::v1::status_t app_case_setup_handler(const Case *const source, const size_t index_of_case) { // test setup code ... return greentea_case_setup_handler(source, index_of_case); } static utest::v1::status_t app_case_teardown_handler(const Case *const source, const size_t passed, const size_t failed, const failure_t failure) { // test tear down code ... return greentea_case_teardown_handler(source, passed, failed, failure); } static void app_test_teardown_handler(const size_t passed, const size_t failed, const failure_t failure) { // common tear down code return greentea_test_teardown_handler(passed, failed, failure); } //-------------------------------- // dummy stepper motor driver to track steps //-------------------------------- class DummyStepperMotor : public BaseStepperMotor { public: DummyStepperMotor() = default; private: MoveDirection _last_direction; int _total_steps_forward; int _total_steps_backward; int _enable_event_count; int _disable_event_count; std::chrono::microseconds _last_step; Timer _t; int _err_step_impl = 0; int _err_set_direction_impl = 0; int _err_set_state_impl = 0; public: MoveDirection dsm_get_last_direction() const { return _last_direction; } int dsm_get_total_steps_forward() const { return _total_steps_forward; } int dsm_get_total_steps_backward() const { return _total_steps_backward; } int dsm_get_total_steps() const { return dsm_get_total_steps_forward() + dsm_get_total_steps_backward(); } float dsm_get_movement_time() const { return _last_step.count() / 1'000'000.0f; } int dsm_get_enable_event_count() const { return _enable_event_count; } int dsm_get_disable_event_count() const { return _disable_event_count; } void dsm_reset_step_timer() { CriticalSectionLock lock; _t.reset(); } void dsm_reset_statistic() { CriticalSectionLock lock; _total_steps_forward = 0; _total_steps_backward = 0; _enable_event_count = 0; _disable_event_count = 0; _last_step = 0ms; _last_direction = DIR_NONE; dsm_reset_step_timer(); } void dsm_err_step_impl(int err) { _err_step_impl = err; } void dsm_err_set_direction_impl(int err) { _err_set_direction_impl = err; } void dsm_err_set_state_impl(int err) { _err_set_state_impl = err; } protected: // BaseStepperMotor interface int init_impl() override { _t.start(); dsm_reset_statistic(); return 0; } int step_impl(const step_description_t &step) override { if (_err_step_impl) { return _err_step_impl; } if (_total_steps_forward == 0 && _total_steps_backward == 0) { _t.reset(); } switch (_last_direction) { case vznncvsteppermotor::BaseStepperMotor::DIR_FORWARD: _total_steps_forward++; break; case vznncvsteppermotor::BaseStepperMotor::DIR_NONE: MBED_ERROR(MBED_MAKE_ERROR(MBED_MODULE_DRIVER, MBED_ERROR_CODE_INVALID_OPERATION), "Step with no direction"); break; case vznncvsteppermotor::BaseStepperMotor::DIR_BACKWARD: _total_steps_backward++; break; default: MBED_ERROR(MBED_ERROR_UNKNOWN, "Unreachable code"); } _last_step = _t.elapsed_time(); return 0; } int set_direction_impl(MoveDirection dir) override { if (_err_set_direction_impl) { return _err_set_direction_impl; } _last_direction = dir; return 0; } int set_state_impl(State state) override { if (_err_set_state_impl) { return _err_set_state_impl; } if (state == STATE_ENABLED) { _enable_event_count++; } else if (state == STATE_DISABLED) { _disable_event_count++; } else { MBED_ERROR(MBED_ERROR_UNKNOWN, "Unknown state code"); } return 0; } }; static constexpr float PI = 3.141592653589793f; //-------------------------------- // test functions //-------------------------------- static void test_simple_forward_movement_with_constant_speed() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(2000)); dsm.dsm_reset_statistic(); dsm.move(100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.01f, 0.05f, dsm.dsm_get_movement_time()); } static void test_simple_backward_movement_with_constant_speed() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(2000)); dsm.dsm_reset_statistic(); dsm.move(-100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.01f, 0.05f, dsm.dsm_get_movement_time()); } static void test_simple_forward_movement_with_constant_acceleration() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(2000, 2000)); dsm.dsm_reset_statistic(); dsm.move(100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.06f, 0.39f, dsm.dsm_get_movement_time()); } static void test_simple_backward_movement_with_constant_acceleration() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(2000, 2000)); dsm.dsm_reset_statistic(); dsm.move(-100); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(100, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.06f, 0.39f, dsm.dsm_get_movement_time()); } struct sine_wave_generator_t { sine_wave_generator_t(float a = 0.0f, float phi = 0.0f, float d_phi = 0.1f * PI, int step_count = 0) : a(a) , phi(phi) , d_phi(d_phi) , step_count(step_count) { } float a; float phi; float d_phi; int step_count; SimpleSequenceWrapper::sample_t next() { SimpleSequenceWrapper::sample_t sample; if (step_count <= 0) { sample.value = 0; sample.flags = SimpleSequenceWrapper::FLAG_STOP; } else { sample.value = a * sinf(phi); phi += d_phi; sample.flags = 0; step_count--; } return sample; } }; static void test_simple_movement_with_custom_step() { const microseconds_u32 interval = 10ms; const float f = 2.0f; const int num_periods = 3; sine_wave_generator_t sine_wave_generator; sine_wave_generator.a = 500.0f; sine_wave_generator.d_phi = 2 * PI * f * interval.count() / 1'000'000.0f; sine_wave_generator.step_count = num_periods * 1'000'000.0f / (f * interval.count()); SimpleSequenceWrapper seq_wrapper(callback(&sine_wave_generator, &sine_wave_generator_t::next), interval); DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_custom_step(seq_wrapper.get_custom_step_callback())); dsm.dsm_reset_statistic(); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); const int expected_one_dir_steps = sine_wave_generator.a * 2 * num_periods; const float expected_move_time = num_periods / f; TEST_ASSERT_EQUAL(0, sine_wave_generator.step_count); TEST_ASSERT_INT_WITHIN(100, expected_one_dir_steps, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_INT_WITHIN(100, expected_one_dir_steps, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.2f, expected_move_time, dsm.dsm_get_movement_time()); } static void test_complex_movement() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(2000, 1000)); dsm.dsm_reset_statistic(); dsm.move(100); ThisThread::sleep_for(500ms); dsm.move_to(-500); ThisThread::sleep_for(500ms); dsm.move(-1000); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(4000, 4000)); ThisThread::sleep_for(500ms); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(4000)); dsm.move(2000); dsm.wait_end_of_movement(); TEST_ASSERT_INT_WITHIN(50, 1160, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_INT_WITHIN(50, 660, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.2f, 1.8f, dsm.dsm_get_movement_time()); } void test_base_enable_disable_functionality() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(1000)); // check default state TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_disable_event_count()); // check disabling TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); // check idempotence TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); // check enabling TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_ENABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(2, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); // check idempotence TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_ENABLED)); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(2, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); } void test_active_base_enable_disable_functionality() { int steps; int dist_to_go; Timer t; DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(1000)); dsm.dsm_reset_statistic(); // move, but stop at the center dsm.move(200); ThisThread::sleep_for(100ms); dsm.set_state(BaseStepperMotor::STATE_DISABLED); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); dist_to_go = dsm.distance_to_go(); steps = dsm.dsm_get_total_steps_forward(); TEST_ASSERT_INT_WITHIN(25, 100, steps); TEST_ASSERT_INT_WITHIN(25, 100, dist_to_go); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); // wait and check that there is no more movement ThisThread::sleep_for(200ms); TEST_ASSERT_EQUAL(steps, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(dist_to_go, dsm.distance_to_go()); // check that resume method doesn't work TEST_ASSERT_EQUAL(0, dsm.resume_movement()); ThisThread::sleep_for(200ms); TEST_ASSERT_EQUAL(steps, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(dist_to_go, dsm.distance_to_go()); // check that ::wait_stopping resum control immediately t.start(); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); t.stop(); // note: time should be small, but any interrupt may increase it (like OS scheduler), so check it with some reserve TEST_ASSERT_INT_WITHIN(100, 0, t.elapsed_time().count()); // resume movement dsm.dsm_reset_step_timer(); TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_ENABLED)); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); // check results TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_enable_event_count()); TEST_ASSERT_EQUAL(1, dsm.dsm_get_disable_event_count()); TEST_ASSERT_EQUAL(200, dsm.dsm_get_total_steps_forward()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps_backward()); TEST_ASSERT_EQUAL(BaseStepperMotor::DIR_NONE, dsm.dsm_get_last_direction()); TEST_ASSERT_FLOAT_WITHIN(0.02f, 0.1f, dsm.dsm_get_movement_time()); } static void test_configuration_methods() { float max_speed; float max_accelration; BaseStepperMotor::CustomStepCallback custom_step_cb; BaseStepperMotor::CustomStepCallback custom_step_cb_impl = [](const BaseStepperMotor::position_t &pos) -> BaseStepperMotor::step_instruction_t { return { BaseStepperMotor::DIR_NONE, 500us }; }; DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); // check constant speed parameters TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_speed(1200.0f)); max_speed = 0.0f; TEST_ASSERT_EQUAL(0, dsm.get_mode_params_constant_speed(max_speed)); TEST_ASSERT_EQUAL(1200.0f, max_speed); TEST_ASSERT_EQUAL(BaseStepperMotor::MODE_CONSTANT_SPEED, dsm.get_mode()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_acceleration(max_speed, max_accelration)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_custom_step(custom_step_cb)); // check constant acceleration parameters TEST_ASSERT_EQUAL(0, dsm.set_mode_constant_acceleration(800.0f, 500.0f)); max_speed = 0.0f; max_accelration = 0.0f; TEST_ASSERT_EQUAL(0, dsm.get_mode_params_constant_acceleration(max_speed, max_accelration)); TEST_ASSERT_EQUAL(800.0f, max_speed); TEST_ASSERT_EQUAL(500.0f, max_accelration); TEST_ASSERT_EQUAL(BaseStepperMotor::MODE_CONSTANT_ACCELERATION, dsm.get_mode()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_speed(max_speed)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_custom_step(custom_step_cb)); // check custom step TEST_ASSERT_EQUAL(0, dsm.set_mode_custom_step(custom_step_cb_impl)); custom_step_cb = 0; TEST_ASSERT_EQUAL(0, dsm.get_mode_params_custom_step(custom_step_cb)); TEST_ASSERT_TRUE(custom_step_cb == custom_step_cb_impl); TEST_ASSERT_EQUAL(BaseStepperMotor::MODE_CUSTOM_STEP, dsm.get_mode()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_speed(max_speed)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_mode_params_constant_acceleration(max_speed, max_accelration)); // check step parameters dsm.set_mode_constant_speed(1000.0f); TEST_ASSERT_EQUAL(0, dsm.get_target_position()); TEST_ASSERT_EQUAL(0, dsm.get_current_position()); TEST_ASSERT_EQUAL(0, dsm.distance_to_go()); dsm.set_target_position(100); dsm.set_current_position(50); TEST_ASSERT_EQUAL(100, dsm.get_target_position()); TEST_ASSERT_EQUAL(50, dsm.get_current_position()); TEST_ASSERT_EQUAL(50, dsm.distance_to_go()); dsm.set_target_position(-20); dsm.set_current_position(80); TEST_ASSERT_EQUAL(-20, dsm.get_target_position()); TEST_ASSERT_EQUAL(80, dsm.get_current_position()); TEST_ASSERT_EQUAL(-100, dsm.distance_to_go()); } void test_impl_errors() { DummyStepperMotor dsm; TEST_ASSERT_EQUAL(0, dsm.init()); dsm.set_mode_constant_speed(1000.0f); TEST_ASSERT_EQUAL(0, dsm.get_error()); auto reset_postions = [](BaseStepperMotor &bsm) { bsm.set_current_position(0); bsm.set_target_position(0); }; // check that we movement doesn't cause errors dsm.move(10); dsm.wait_end_of_movement(); TEST_ASSERT_EQUAL(0, dsm.get_error()); // check that step error prevents movement dsm.dsm_reset_statistic(); reset_postions(dsm); dsm.dsm_err_step_impl(-1); dsm.move(10); TEST_ASSERT_NOT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(10, dsm.distance_to_go()); TEST_ASSERT_EQUAL(0, dsm.get_current_position()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps()); dsm.dsm_err_step_impl(0); dsm.clear_error(); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(0, dsm.distance_to_go()); TEST_ASSERT_EQUAL(10, dsm.get_current_position()); TEST_ASSERT_EQUAL(10, dsm.dsm_get_total_steps()); // check that direction error prevents movement dsm.dsm_reset_statistic(); reset_postions(dsm); dsm.dsm_err_set_direction_impl(-1); dsm.move(5); TEST_ASSERT_NOT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_NOT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(5, dsm.distance_to_go()); TEST_ASSERT_EQUAL(0, dsm.get_current_position()); TEST_ASSERT_EQUAL(0, dsm.dsm_get_total_steps()); dsm.dsm_err_set_direction_impl(0); dsm.clear_error(); TEST_ASSERT_EQUAL(0, dsm.resume_movement()); TEST_ASSERT_EQUAL(0, dsm.wait_end_of_movement()); TEST_ASSERT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(0, dsm.distance_to_go()); TEST_ASSERT_EQUAL(5, dsm.get_current_position()); TEST_ASSERT_EQUAL(5, dsm.dsm_get_total_steps()); // check set state error dsm.dsm_reset_statistic(); reset_postions(dsm); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); dsm.dsm_err_set_state_impl(-1); TEST_ASSERT_NOT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_NOT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_ENABLED, dsm.get_state()); dsm.dsm_err_set_state_impl(0); dsm.clear_error(); TEST_ASSERT_EQUAL(0, dsm.set_state(BaseStepperMotor::STATE_DISABLED)); TEST_ASSERT_EQUAL(0, dsm.get_error()); TEST_ASSERT_EQUAL(BaseStepperMotor::STATE_DISABLED, dsm.get_state()); } // test cases description #define SimpleCase(test_fun) Case(#test_fun, app_case_setup_handler, test_fun, app_case_teardown_handler, greentea_case_failure_continue_handler) static Case cases[] = { // base modes SimpleCase(test_simple_forward_movement_with_constant_acceleration), SimpleCase(test_simple_backward_movement_with_constant_acceleration), SimpleCase(test_simple_forward_movement_with_constant_speed), SimpleCase(test_simple_backward_movement_with_constant_speed), SimpleCase(test_simple_movement_with_custom_step), // combination of modes SimpleCase(test_complex_movement), SimpleCase(test_base_enable_disable_functionality), SimpleCase(test_active_base_enable_disable_functionality), // test configuration methods SimpleCase(test_configuration_methods), SimpleCase(test_impl_errors) }; static Specification specification(app_test_setup_handler, cases, app_test_teardown_handler); // Entry point into the tests int main() { // host handshake // note: should be invoked here or in the test_setup_handler GREENTEA_SETUP(40, "default_auto"); // run tests return !Harness::run(specification); }
34.964706
148
0.721977
vznncv
d5440368d4912236ac2556e9f1b5b13b571bc46e
8,329
hxx
C++
include/semaphore.hxx
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
include/semaphore.hxx
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
include/semaphore.hxx
K-Wu/libcxx.doc
c3c0421b2a9cc003146e847d0b8dd3a37100f39a
[ "Apache-2.0" ]
null
null
null
// -*- C++ -*- //===--------------------------- semaphore --------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_SEMAPHORE #define _LIBCPP_SEMAPHORE /* semaphore synopsis namespace std { template<ptrdiff_t least_max_value = implementation-defined> class counting_semaphore { public: static constexpr ptrdiff_t max() noexcept; constexpr explicit counting_semaphore(ptrdiff_t desired); ~counting_semaphore(); counting_semaphore(const counting_semaphore&) = delete; counting_semaphore& operator=(const counting_semaphore&) = delete; void release(ptrdiff_t update = 1); void acquire(); bool try_acquire() noexcept; template<class Rep, class Period> bool try_acquire_for(const chrono::duration<Rep, Period>& rel_time); template<class Clock, class Duration> bool try_acquire_until(const chrono::time_point<Clock, Duration>& abs_time); private: ptrdiff_t counter; // exposition only }; using binary_semaphore = counting_semaphore<1>; } */ #ifndef __simt__ #include <__config.hxx> #include <__threading_support.hxx> #include <atomic.hxx> #include <cassert.hxx> #endif #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif #ifdef _LIBCPP_HAS_NO_THREADS # error <semaphore> is not supported on this single threaded system #endif #if _LIBCPP_STD_VER < 11 # error <semaphore> is requires C++11 or later #endif _LIBCPP_BEGIN_NAMESPACE_STD template<int _Sco> class __atomic_semaphore_base { __atomic_base<ptrdiff_t, _Sco> __count; #ifndef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE __libcpp_contention_t __contention; #endif public: _LIBCPP_INLINE_VISIBILITY __atomic_semaphore_base(ptrdiff_t __count) : __count(__count) { } ~__atomic_semaphore_base() = default; __atomic_semaphore_base(__atomic_semaphore_base const&) = delete; __atomic_semaphore_base& operator=(__atomic_semaphore_base const&) = delete; _LIBCPP_INLINE_VISIBILITY void release(ptrdiff_t __update = 1) { if(0 < __count.fetch_add(__update, memory_order_release)) ; #ifdef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE else if(__update > 1) __cxx_atomic_notify_all(&__count.__a_); else __cxx_atomic_notify_one(&__count.__a_); #else else if(__update > 1) __cxx_atomic_notify_all(&__count.__a_, &__contention); else __cxx_atomic_notify_one(&__count.__a_, &__contention); #endif } _LIBCPP_INLINE_VISIBILITY void acquire() { ptrdiff_t __old = __count.load(memory_order_relaxed); while (1) { if(__old == 0) { #ifdef _LIBCPP_HAS_NO_THREAD_CONTENTION_STATE __cxx_atomic_wait(&__count.__a_, __old, memory_order_relaxed); #else __cxx_atomic_wait(&__count.__a_, __old, memory_order_relaxed, &__contention); #endif __old = __count.load(memory_order_relaxed); continue; } if(__count.compare_exchange_weak(__old, __old - 1, memory_order_acquire, memory_order_relaxed)) break; } } template <class Rep, class Period> _LIBCPP_INLINE_VISIBILITY bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time) { return __libcpp_thread_poll_with_backoff([=]() { ptrdiff_t __old = __count.load(memory_order_acquire); if (__old == 0) return false; return __count.compare_exchange_weak(__old, __old - 1, memory_order_acquire, memory_order_relaxed); }, __rel_time); } }; #ifndef _LIBCPP_HAS_NO_SEMAPHORES class __sem_semaphore_basic_base { #ifdef __APPLE__ atomic<ptrdiff_t> __balance = {0}; #endif __libcpp_semaphore_t __semaphore; public: _LIBCPP_EXPORTED_FROM_ABI __sem_semaphore_basic_base(ptrdiff_t __count); _LIBCPP_EXPORTED_FROM_ABI ~__sem_semaphore_basic_base(); _LIBCPP_EXPORTED_FROM_ABI void release(ptrdiff_t __update); _LIBCPP_EXPORTED_FROM_ABI void acquire(); _LIBCPP_EXPORTED_FROM_ABI bool try_acquire_for(chrono::nanoseconds __rel_time); }; #ifndef _LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER class __sem_semaphore_back_buffered_base { _LIBCPP_INLINE_VISIBILITY void __backfill(); __sem_semaphore_basic_base __semaphore; atomic<ptrdiff_t> __backbuffer; public: _LIBCPP_EXPORTED_FROM_ABI __sem_semaphore_back_buffered_base(ptrdiff_t __count); _LIBCPP_EXPORTED_FROM_ABI ~__sem_semaphore_back_buffered_base(); _LIBCPP_EXPORTED_FROM_ABI void release(ptrdiff_t __update); _LIBCPP_EXPORTED_FROM_ABI void acquire(); _LIBCPP_EXPORTED_FROM_ABI bool try_acquire_for(chrono::nanoseconds __rel_time); }; #endif //_LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER #ifndef _LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER class __sem_semaphore_front_buffered_base { _LIBCPP_INLINE_VISIBILITY bool __try_acquire_fast(); _LIBCPP_INLINE_VISIBILITY void __try_done(); #ifndef _LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER __sem_semaphore_back_buffered_base __semaphore; #else __sem_semaphore_basic_base __semaphore; #endif atomic<ptrdiff_t> __frontbuffer; public: _LIBCPP_EXPORTED_FROM_ABI __sem_semaphore_front_buffered_base(ptrdiff_t __count); _LIBCPP_EXPORTED_FROM_ABI ~__sem_semaphore_front_buffered_base(); _LIBCPP_EXPORTED_FROM_ABI void release(ptrdiff_t __update); _LIBCPP_EXPORTED_FROM_ABI void acquire(); _LIBCPP_EXPORTED_FROM_ABI bool try_acquire_for(chrono::nanoseconds __rel_time); }; #endif //_LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER #endif //_LIBCPP_HAS_NO_SEMAPHORES #if defined(_LIBCPP_HAS_NO_SEMAPHORES) template<int _Sco, ptrdiff_t> using __semaphore_base = __atomic_semaphore_base<_Sco>; #else # if !defined(_LIBCPP_HAS_NO_SEMAPHORE_FRONT_BUFFER) using __sem_semaphore_base = __sem_semaphore_front_buffered_base; # elif !defined(_LIBCPP_HAS_NO_SEMAPHORE_BACK_BUFFER) using __sem_semaphore_base = __sem_semaphore_back_buffered_base; # else using __sem_semaphore_base = __sem_semaphore_basic_base; # endif template<int _Sco, ptrdiff_t __least_max_value> using __semaphore_base = typename conditional<(__least_max_value > 1 && __least_max_value <= _LIBCPP_SEMAPHORE_MAX), __sem_semaphore_base, __atomic_semaphore_base<_Sco>>::type; #endif template<ptrdiff_t __least_max_value = _LIBCPP_SEMAPHORE_MAX> class counting_semaphore { __semaphore_base<0, __least_max_value> __semaphore; public: static constexpr ptrdiff_t max() noexcept { return __least_max_value; } _LIBCPP_INLINE_VISIBILITY counting_semaphore(ptrdiff_t __count = 0) : __semaphore(__count) { } ~counting_semaphore() = default; counting_semaphore(const counting_semaphore&) = delete; counting_semaphore& operator=(const counting_semaphore&) = delete; _LIBCPP_INLINE_VISIBILITY void release(ptrdiff_t __update = 1) { __semaphore.release(__update); } _LIBCPP_INLINE_VISIBILITY void acquire() { __semaphore.acquire(); } template<class Rep, class Period> _LIBCPP_INLINE_VISIBILITY bool try_acquire_for(chrono::duration<Rep, Period> const& __rel_time) { return __semaphore.try_acquire_for(chrono::duration_cast<chrono::nanoseconds>(__rel_time)); } _LIBCPP_INLINE_VISIBILITY bool try_acquire() { return try_acquire_for(chrono::nanoseconds::zero()); } template <class Clock, class Duration> _LIBCPP_INLINE_VISIBILITY bool try_acquire_until(chrono::time_point<Clock, Duration> const& __abs_time) { auto const current = Clock::now(); if(current >= __abs_time) return try_acquire(); else return try_acquire_for(__abs_time - current); } }; using binary_semaphore = counting_semaphore<1>; _LIBCPP_END_NAMESPACE_STD #endif //_LIBCPP_SEMAPHORE
29.122378
100
0.715452
K-Wu
d5449f863e08673cc00b0f7277f890cb4164ab98
34,521
cpp
C++
Testing/Marlin-2.0.x/Marlin/src/HAL/shared/backtrace/unwarm_thumb.cpp
qisback/Geeetech-i3-B-pro-configs
a2c309923c4e68103addda677fda190238a1abe0
[ "CC-BY-4.0" ]
5
2020-05-17T21:16:41.000Z
2021-06-11T04:46:31.000Z
Testing/Marlin-2.0.x/Marlin/src/HAL/shared/backtrace/unwarm_thumb.cpp
qisback/Geeetech-i3-B-pro-configs
a2c309923c4e68103addda677fda190238a1abe0
[ "CC-BY-4.0" ]
1
2020-09-27T14:53:34.000Z
2020-09-27T14:53:34.000Z
src/HAL/shared/backtrace/unwarm_thumb.cpp
Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3
d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20
[ "MIT" ]
2
2019-07-22T20:31:15.000Z
2021-08-01T00:15:38.000Z
/*************************************************************************** * ARM Stack Unwinder, Michael.McTernan.2001@cs.bris.ac.uk * Updated, adapted and several bug fixes on 2018 by Eduardo José Tagle * * This program is PUBLIC DOMAIN. * This means that there is no copyright and anyone is able to take a copy * for free and use it as they wish, with or without modifications, and in * any context, commercially or otherwise. The only limitation is that I * don't guarantee that the software is fit for any purpose or accept any * liability for it's use or misuse - this software is without warranty. *************************************************************************** * File Description: Abstract interpretation for Thumb mode. **************************************************************************/ #if defined(__arm__) || defined(__thumb__) #define MODULE_NAME "UNWARM_THUMB" #include <stdio.h> #include "unwarm.h" /** Sign extend an 11 bit value. * This function simply inspects bit 11 of the input \a value, and if * set, the top 5 bits are set to give a 2's compliment signed value. * \param value The value to sign extend. * \return The signed-11 bit value stored in a 16bit data type. */ static int32_t signExtend11(const uint16_t value) { return (value & 0x400) ? value | 0xFFFFF800 : value; } UnwResult UnwStartThumb(UnwState * const state) { bool found = false; uint16_t t = UNW_MAX_INSTR_COUNT; uint32_t lastJumpAddr = 0; // Last JUMP address, to try to detect infinite loops bool loopDetected = false; // If a loop was detected do { uint16_t instr; /* Attempt to read the instruction */ if (!state->cb->readH(state->regData[15].v & (~0x1), &instr)) return UNWIND_IREAD_H_FAIL; UnwPrintd4("T %x %x %04x:", state->regData[13].v, state->regData[15].v, instr); /* Check that the PC is still on Thumb alignment */ if (!(state->regData[15].v & 0x1)) { UnwPrintd1("\nError: PC misalignment\n"); return UNWIND_INCONSISTENT; } /* Check that the SP and PC have not been invalidated */ if (!M_IsOriginValid(state->regData[13].o) || !M_IsOriginValid(state->regData[15].o)) { UnwPrintd1("\nError: PC or SP invalidated\n"); return UNWIND_INCONSISTENT; } /* * Detect 32bit thumb instructions */ if ((instr & 0xE000) == 0xE000 && (instr & 0x1800) != 0) { uint16_t instr2; /* Check next address */ state->regData[15].v += 2; /* Attempt to read the 2nd part of the instruction */ if (!state->cb->readH(state->regData[15].v & (~0x1), &instr2)) return UNWIND_IREAD_H_FAIL; UnwPrintd3(" %x %04x:", state->regData[15].v, instr2); /* * Load/Store multiple: Only interpret * PUSH and POP */ if ((instr & 0xFE6F) == 0xE82D) { bool L = !!(instr & 0x10); uint16_t rList = instr2; if (L) { uint8_t r; /* Load from memory: POP */ UnwPrintd1("POP {Rlist}\n"); /* Load registers from stack */ for (r = 0; r < 16; r++) { if (rList & (0x1 << r)) { /* Read the word */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (M_IsOriginValid(state->regData[r].o)) { state->regData[r].o = REG_VAL_FROM_STACK; /* If restoring the PC */ if (r == 15) { /* The bottom bit should have been set to indicate that * the caller was from Thumb. This would allow return * by BX for interworking APCS. */ if ((state->regData[15].v & 0x1) == 0) { UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v); /* Pop into the PC will not switch mode */ return UNWIND_INCONSISTENT; } /* Store the return address */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Now have the return address */ UnwPrintd2(" Return PC=%x\n", state->regData[15].v); /* Compensate for the auto-increment, which isn't needed here */ state->regData[15].v -= 2; } } else { if (r == 15) { /* Return address is not valid */ UnwPrintd1("PC popped with invalid address\n"); return UNWIND_FAILURE; } } state->regData[13].v += 4; UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v); } } } else { int8_t r; /* Store to memory: PUSH */ UnwPrintd1("PUSH {Rlist}"); for (r = 15; r >= 0; r--) { if (rList & (0x1 << r)) { UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o)); state->regData[13].v -= 4; if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DWRITE_W_FAIL; } } } } /* * PUSH register */ else if (instr == 0xF84D && (instr2 & 0x0FFF) == 0x0D04) { uint8_t r = instr2 >> 12; /* Store to memory: PUSH */ UnwPrintd2("PUSH {R%d}\n", r); UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o)); state->regData[13].v -= 4; if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DWRITE_W_FAIL; } /* * POP register */ else if (instr == 0xF85D && (instr2 & 0x0FFF) == 0x0B04) { uint8_t r = instr2 >> 12; /* Load from memory: POP */ UnwPrintd2("POP {R%d}\n", r); /* Read the word */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (M_IsOriginValid(state->regData[r].o)) { state->regData[r].o = REG_VAL_FROM_STACK; /* If restoring the PC */ if (r == 15) { /* The bottom bit should have been set to indicate that * the caller was from Thumb. This would allow return * by BX for interworking APCS. */ if ((state->regData[15].v & 0x1) == 0) { UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v); /* Pop into the PC will not switch mode */ return UNWIND_INCONSISTENT; } /* Store the return address */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Now have the return address */ UnwPrintd2(" Return PC=%x\n", state->regData[15].v); /* Compensate for the auto-increment, which isn't needed here */ state->regData[15].v -= 2; } } else { if (r == 15) { /* Return address is not valid */ UnwPrintd1("PC popped with invalid address\n"); return UNWIND_FAILURE; } } state->regData[13].v += 4; UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v); } /* * TBB / TBH */ else if ((instr & 0xFFF0) == 0xE8D0 && (instr2 & 0xFFE0) == 0xF000) { /* We are only interested in * the forms * TBB [PC, ...] * TBH [PC, ..., LSL #1] * as those are used by the C compiler to implement * the switch clauses */ uint8_t rn = instr & 0xF; bool H = !!(instr2 & 0x10); UnwPrintd5("TB%c [r%d,r%d%s]\n", H ? 'H' : 'B', rn, (instr2 & 0xF), H ? ",LSL #1" : ""); // We are only interested if the RN is the PC. Let's choose the 1st destination if (rn == 15) { if (H) { uint16_t rv; if (!state->cb->readH((state->regData[15].v & (~1)) + 2, &rv)) return UNWIND_DREAD_H_FAIL; state->regData[15].v += rv * 2; } else { uint8_t rv; if (!state->cb->readB((state->regData[15].v & (~1)) + 2, &rv)) return UNWIND_DREAD_B_FAIL; state->regData[15].v += rv * 2; } } } /* * Unconditional branch */ else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x9000) { uint32_t v; uint8_t S = (instr & 0x400) >> 10; uint16_t imm10 = (instr & 0x3FF); uint8_t J1 = (instr2 & 0x2000) >> 13; uint8_t J2 = (instr2 & 0x0800) >> 11; uint16_t imm11 = (instr2 & 0x7FF); uint8_t I1 = J1 ^ S ^ 1; uint8_t I2 = J2 ^ S ^ 1; uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1); if (S) imm32 |= 0xFE000000; UnwPrintd2("B %d \n", imm32); /* Update PC */ state->regData[15].v += imm32; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Compute the jump address */ v = state->regData[15].v + 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", v); /* Did we detect an infinite loop ? */ loopDetected = lastJumpAddr == v; /* Remember the last address we jumped to */ lastJumpAddr = v; } /* * Branch with link */ else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0xD000) { uint8_t S = (instr & 0x400) >> 10; uint16_t imm10 = (instr & 0x3FF); uint8_t J1 = (instr2 & 0x2000) >> 13; uint8_t J2 = (instr2 & 0x0800) >> 11; uint16_t imm11 = (instr2 & 0x7FF); uint8_t I1 = J1 ^ S ^ 1; uint8_t I2 = J2 ^ S ^ 1; uint32_t imm32 = (S << 24) | (I1 << 23) | (I2 << 22) |(imm10 << 12) | (imm11 << 1); if (S) imm32 |= 0xFE000000; UnwPrintd2("BL %d \n", imm32); /* Never taken, as we are unwinding the stack */ if (0) { /* Store return address in LR register */ state->regData[14].v = state->regData[15].v + 2; state->regData[14].o = REG_VAL_FROM_CONST; /* Update PC */ state->regData[15].v += imm32; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Display PC of next instruction */ UnwPrintd2(" Return PC=%x", state->regData[15].v); /* Report the return address, including mode bit */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Determine the new mode */ if (state->regData[15].v & 0x1) { /* Branching to THUMB */ /* Account for the auto-increment which isn't needed */ state->regData[15].v -= 2; } else { /* Branch to ARM */ return UnwStartArm(state); } } } /* * Conditional branches. Usually not taken, unless infinite loop is detected */ else if ((instr & 0xF800) == 0xF000 && (instr2 & 0xD000) == 0x8000) { uint8_t S = (instr & 0x400) >> 10; uint16_t imm6 = (instr & 0x3F); uint8_t J1 = (instr2 & 0x2000) >> 13; uint8_t J2 = (instr2 & 0x0800) >> 11; uint16_t imm11 = (instr2 & 0x7FF); uint8_t I1 = J1 ^ S ^ 1; uint8_t I2 = J2 ^ S ^ 1; uint32_t imm32 = (S << 20) | (I1 << 19) | (I2 << 18) |(imm6 << 12) | (imm11 << 1); if (S) imm32 |= 0xFFE00000; UnwPrintd2("Bcond %d\n", imm32); /* Take the jump only if a loop is detected */ if (loopDetected) { /* Update PC */ state->regData[15].v += imm32; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", state->regData[15].v + 2); } } /* * PC-relative load * LDR Rd,[PC, #+/-imm] */ else if ((instr & 0xFF7F) == 0xF85F) { uint8_t rt = (instr2 & 0xF000) >> 12; uint8_t imm12 = (instr2 & 0x0FFF); bool A = !!(instr & 0x80); uint32_t address; /* Compute load address, adding a word to account for prefetch */ address = (state->regData[15].v & (~0x3)) + 4; if (A) address += imm12; else address -= imm12; UnwPrintd4("LDR r%d,[PC #%c0x%08x]", rt, A?'+':'-', address); if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } /* * LDR immediate. * We are only interested when destination is PC. * LDR Rt,[Rn , #n] */ else if ((instr & 0xFFF0) == 0xF8D0) { uint8_t rn = (instr & 0xF); uint8_t rt = (instr2 & 0xF000) >> 12; uint16_t imm12 = (instr2 & 0xFFF); /* If destination is PC and we don't know the source value, then fail */ if (!M_IsOriginValid(state->regData[rn].o)) { state->regData[rt].o = state->regData[rn].o; } else { uint32_t address = state->regData[rn].v + imm12; if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } } /* * LDR immediate * We are only interested when destination is PC. * LDR Rt,[Rn , #-n] * LDR Rt,[Rn], #+/-n] * LDR Rt,[Rn, #+/-n]! */ else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0800) == 0x0800) { uint8_t rn = (instr & 0xF); uint8_t rt = (instr2 & 0xF000) >> 12; uint16_t imm8 = (instr2 & 0xFF); bool P = !!(instr2 & 0x400); bool U = !!(instr2 & 0x200); bool W = !!(instr2 & 0x100); if (!M_IsOriginValid(state->regData[rn].o)) state->regData[rt].o = state->regData[rn].o; else { uint32_t offaddress = state->regData[rn].v + (U ? imm8 + imm8 : 0), address = P ? offaddress : state->regData[rn].v; if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; if (W) state->regData[rn].v = offaddress; } } /* * LDR (register). * We are interested in the form * ldr Rt, [Rn, Rm, lsl #x] * Where Rt is PC, Rn value is known, Rm is not known or unknown */ else if ((instr & 0xFFF0) == 0xF850 && (instr2 & 0x0FC0) == 0x0000) { const uint8_t rn = (instr & 0xF), rt = (instr2 & 0xF000) >> 12, rm = (instr2 & 0xF), imm2 = (instr2 & 0x30) >> 4; if (!M_IsOriginValid(state->regData[rn].o) || !M_IsOriginValid(state->regData[rm].o)) { /* If Rt is PC, and Rn is known, then do an exception and assume Rm equals 0 => This takes the first case in a switch() */ if (rt == 15 && M_IsOriginValid(state->regData[rn].o)) { uint32_t address = state->regData[rn].v; if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } else /* Propagate unknown value */ state->regData[rt].o = state->regData[rn].o; } else { uint32_t address = state->regData[rn].v + (state->regData[rm].v << imm2); if (!UnwMemReadRegister(state, address, &state->regData[rt])) return UNWIND_DREAD_W_FAIL; } } else { UnwPrintd1("???? (32)"); /* Unknown/undecoded. May alter some register, so invalidate file */ UnwInvalidateRegisterFile(state->regData); } /* End of thumb 32bit code */ } /* Format 1: Move shifted register * LSL Rd, Rs, #Offset5 * LSR Rd, Rs, #Offset5 * ASR Rd, Rs, #Offset5 */ else if ((instr & 0xE000) == 0x0000 && (instr & 0x1800) != 0x1800) { bool signExtend; const uint8_t op = (instr & 0x1800) >> 11, offset5 = (instr & 0x07C0) >> 6, rs = (instr & 0x0038) >> 3, rd = (instr & 0x0007); switch (op) { case 0: /* LSL */ UnwPrintd6("LSL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o)); state->regData[rd].v = state->regData[rs].v << offset5; state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; case 1: /* LSR */ UnwPrintd6("LSR r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o)); state->regData[rd].v = state->regData[rs].v >> offset5; state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; case 2: /* ASR */ UnwPrintd6("ASL r%d, r%d, #%d\t; r%d %s", rd, rs, offset5, rs, M_Origin2Str(state->regData[rs].o)); signExtend = !!(state->regData[rs].v & 0x8000); state->regData[rd].v = state->regData[rs].v >> offset5; if (signExtend) state->regData[rd].v |= 0xFFFFFFFF << (32 - offset5); state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; } } /* Format 2: add/subtract * ADD Rd, Rs, Rn * ADD Rd, Rs, #Offset3 * SUB Rd, Rs, Rn * SUB Rd, Rs, #Offset3 */ else if ((instr & 0xF800) == 0x1800) { bool I = !!(instr & 0x0400); bool op = !!(instr & 0x0200); uint8_t rn = (instr & 0x01C0) >> 6; uint8_t rs = (instr & 0x0038) >> 3; uint8_t rd = (instr & 0x0007); /* Print decoding */ UnwPrintd6("%s r%d, r%d, %c%d\t;",op ? "SUB" : "ADD",rd, rs,I ? '#' : 'r',rn); UnwPrintd5("r%d %s, r%d %s",rd, M_Origin2Str(state->regData[rd].o),rs, M_Origin2Str(state->regData[rs].o)); if (!I) { UnwPrintd3(", r%d %s", rn, M_Origin2Str(state->regData[rn].o)); /* Perform calculation */ state->regData[rd].v = state->regData[rs].v + (op ? -state->regData[rn].v : state->regData[rn].v); /* Propagate the origin */ if (M_IsOriginValid(state->regData[rs].o) && M_IsOriginValid(state->regData[rn].o)) { state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; } else state->regData[rd].o = REG_VAL_INVALID; } else { /* Perform calculation */ state->regData[rd].v = state->regData[rs].v + (op ? -rn : rn); /* Propagate the origin */ state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; } } /* Format 3: move/compare/add/subtract immediate * MOV Rd, #Offset8 * CMP Rd, #Offset8 * ADD Rd, #Offset8 * SUB Rd, #Offset8 */ else if ((instr & 0xE000) == 0x2000) { uint8_t op = (instr & 0x1800) >> 11; uint8_t rd = (instr & 0x0700) >> 8; uint8_t offset8 = (instr & 0x00FF); switch (op) { case 0: /* MOV */ UnwPrintd3("MOV r%d, #0x%x", rd, offset8); state->regData[rd].v = offset8; state->regData[rd].o = REG_VAL_FROM_CONST; break; case 1: /* CMP */ /* Irrelevant to unwinding */ UnwPrintd1("CMP ???"); break; case 2: /* ADD */ UnwPrintd5("ADD r%d, #0x%x\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o)); state->regData[rd].v += offset8; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; case 3: /* SUB */ UnwPrintd5("SUB r%d, #0x%d\t; r%d %s", rd, offset8, rd, M_Origin2Str(state->regData[rd].o)); state->regData[rd].v -= offset8; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; } } /* Format 4: ALU operations * AND Rd, Rs * EOR Rd, Rs * LSL Rd, Rs * LSR Rd, Rs * ASR Rd, Rs * ADC Rd, Rs * SBC Rd, Rs * ROR Rd, Rs * TST Rd, Rs * NEG Rd, Rs * CMP Rd, Rs * CMN Rd, Rs * ORR Rd, Rs * MUL Rd, Rs * BIC Rd, Rs * MVN Rd, Rs */ else if ((instr & 0xFC00) == 0x4000) { uint8_t op = (instr & 0x03C0) >> 6; uint8_t rs = (instr & 0x0038) >> 3; uint8_t rd = (instr & 0x0007); #ifdef UNW_DEBUG static const char * const mnu[16] = { "AND", "EOR", "LSL", "LSR", "ASR", "ADC", "SBC", "ROR", "TST", "NEG", "CMP", "CMN", "ORR", "MUL", "BIC", "MVN" }; #endif /* Print the mnemonic and registers */ switch (op) { case 0: /* AND */ case 1: /* EOR */ case 2: /* LSL */ case 3: /* LSR */ case 4: /* ASR */ case 7: /* ROR */ case 9: /* NEG */ case 12: /* ORR */ case 13: /* MUL */ case 15: /* MVN */ UnwPrintd8("%s r%d ,r%d\t; r%d %s, r%d %s",mnu[op],rd, rs, rd, M_Origin2Str(state->regData[rd].o), rs, M_Origin2Str(state->regData[rs].o)); break; case 5: /* ADC */ case 6: /* SBC */ UnwPrintd4("%s r%d, r%d", mnu[op], rd, rs); break; case 8: /* TST */ case 10: /* CMP */ case 11: /* CMN */ /* Irrelevant to unwinding */ UnwPrintd2("%s ???", mnu[op]); break; case 14: /* BIC */ UnwPrintd5("r%d ,r%d\t; r%d %s", rd, rs, rs, M_Origin2Str(state->regData[rs].o)); break; } /* Perform operation */ switch (op) { case 0: /* AND */ state->regData[rd].v &= state->regData[rs].v; break; case 1: /* EOR */ state->regData[rd].v ^= state->regData[rs].v; break; case 2: /* LSL */ state->regData[rd].v <<= state->regData[rs].v; break; case 3: /* LSR */ state->regData[rd].v >>= state->regData[rs].v; break; case 4: /* ASR */ if (state->regData[rd].v & 0x80000000) { state->regData[rd].v >>= state->regData[rs].v; state->regData[rd].v |= 0xFFFFFFFF << (32 - state->regData[rs].v); } else { state->regData[rd].v >>= state->regData[rs].v; } break; case 5: /* ADC */ case 6: /* SBC */ case 8: /* TST */ case 10: /* CMP */ case 11: /* CMN */ break; case 7: /* ROR */ state->regData[rd].v = (state->regData[rd].v >> state->regData[rs].v) | (state->regData[rd].v << (32 - state->regData[rs].v)); break; case 9: /* NEG */ state->regData[rd].v = -state->regData[rs].v; break; case 12: /* ORR */ state->regData[rd].v |= state->regData[rs].v; break; case 13: /* MUL */ state->regData[rd].v *= state->regData[rs].v; break; case 14: /* BIC */ state->regData[rd].v &= ~state->regData[rs].v; break; case 15: /* MVN */ state->regData[rd].v = ~state->regData[rs].v; break; } /* Propagate data origins */ switch (op) { case 0: /* AND */ case 1: /* EOR */ case 2: /* LSL */ case 3: /* LSR */ case 4: /* ASR */ case 7: /* ROR */ case 12: /* ORR */ case 13: /* MUL */ case 14: /* BIC */ if (M_IsOriginValid(state->regData[rd].o) && M_IsOriginValid(state->regData[rs].o)) { state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; } else state->regData[rd].o = REG_VAL_INVALID; break; case 5: /* ADC */ case 6: /* SBC */ /* C-bit not tracked */ state->regData[rd].o = REG_VAL_INVALID; break; case 8: /* TST */ case 10: /* CMP */ case 11: /* CMN */ /* Nothing propagated */ break; case 9: /* NEG */ case 15: /* MVN */ state->regData[rd].o = state->regData[rs].o; state->regData[rd].o |= REG_VAL_ARITHMETIC; break; } } /* Format 5: Hi register operations/branch exchange * ADD Rd, Hs * CMP Hd, Rs * MOV Hd, Hs */ else if ((instr & 0xFC00) == 0x4400) { uint8_t op = (instr & 0x0300) >> 8; bool h1 = (instr & 0x0080) ? true: false; bool h2 = (instr & 0x0040) ? true: false; uint8_t rhs = (instr & 0x0038) >> 3; uint8_t rhd = (instr & 0x0007); /* Adjust the register numbers */ if (h2) rhs += 8; if (h1) rhd += 8; switch (op) { case 0: /* ADD */ UnwPrintd5("ADD r%d, r%d\t; r%d %s", rhd, rhs, rhs, M_Origin2Str(state->regData[rhs].o)); state->regData[rhd].v += state->regData[rhs].v; state->regData[rhd].o = state->regData[rhs].o; state->regData[rhd].o |= REG_VAL_ARITHMETIC; break; case 1: /* CMP */ /* Irrelevant to unwinding */ UnwPrintd1("CMP ???"); break; case 2: /* MOV */ UnwPrintd5("MOV r%d, r%d\t; r%d %s", rhd, rhs, rhd, M_Origin2Str(state->regData[rhs].o)); state->regData[rhd].v = state->regData[rhs].v; state->regData[rhd].o = state->regData[rhd].o; break; case 3: /* BX */ UnwPrintd4("BX r%d\t; r%d %s\n", rhs, rhs, M_Origin2Str(state->regData[rhs].o)); /* Only follow BX if the data was from the stack or BX LR */ if (rhs == 14 || state->regData[rhs].o == REG_VAL_FROM_STACK) { UnwPrintd2(" Return PC=0x%x\n", state->regData[rhs].v & (~0x1)); /* Report the return address, including mode bit */ if (!UnwReportRetAddr(state, state->regData[rhs].v)) return UNWIND_TRUNCATED; /* Update the PC */ state->regData[15].v = state->regData[rhs].v; /* Determine the new mode */ if (state->regData[rhs].v & 0x1) { /* Branching to THUMB */ /* Account for the auto-increment which isn't needed */ state->regData[15].v -= 2; } else /* Branch to ARM */ return UnwStartArm(state); } else { UnwPrintd4("\nError: BX to invalid register: r%d = 0x%x (%s)\n", rhs, state->regData[rhs].o, M_Origin2Str(state->regData[rhs].o)); return UNWIND_FAILURE; } } } /* Format 9: PC-relative load * LDR Rd,[PC, #imm] */ else if ((instr & 0xF800) == 0x4800) { uint8_t rd = (instr & 0x0700) >> 8; uint8_t word8 = (instr & 0x00FF); uint32_t address; /* Compute load address, adding a word to account for prefetch */ address = (state->regData[15].v & (~0x3)) + 4 + (word8 << 2); UnwPrintd3("LDR r%d, 0x%08x", rd, address); if (!UnwMemReadRegister(state, address, &state->regData[rd])) return UNWIND_DREAD_W_FAIL; } /* Format 13: add offset to Stack Pointer * ADD sp,#+imm * ADD sp,#-imm */ else if ((instr & 0xFF00) == 0xB000) { uint8_t value = (instr & 0x7F) * 4; /* Check the negative bit */ if ((instr & 0x80) != 0) { UnwPrintd2("SUB sp,#0x%x", value); state->regData[13].v -= value; } else { UnwPrintd2("ADD sp,#0x%x", value); state->regData[13].v += value; } } /* Format 14: push/pop registers * PUSH {Rlist} * PUSH {Rlist, LR} * POP {Rlist} * POP {Rlist, PC} */ else if ((instr & 0xF600) == 0xB400) { bool L = !!(instr & 0x0800); bool R = !!(instr & 0x0100); uint8_t rList = (instr & 0x00FF); if (L) { uint8_t r; /* Load from memory: POP */ UnwPrintd2("POP {Rlist%s}\n", R ? ", PC" : ""); for (r = 0; r < 8; r++) { if (rList & (0x1 << r)) { /* Read the word */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (M_IsOriginValid(state->regData[r].o)) state->regData[r].o = REG_VAL_FROM_STACK; state->regData[13].v += 4; UnwPrintd3(" r%d = 0x%08x\n", r, state->regData[r].v); } } /* Check if the PC is to be popped */ if (R) { /* Get the return address */ if (!UnwMemReadRegister(state, state->regData[13].v, &state->regData[15])) return UNWIND_DREAD_W_FAIL; /* Alter the origin to be from the stack if it was valid */ if (!M_IsOriginValid(state->regData[15].o)) { /* Return address is not valid */ UnwPrintd1("PC popped with invalid address\n"); return UNWIND_FAILURE; } else { /* The bottom bit should have been set to indicate that * the caller was from Thumb. This would allow return * by BX for interworking APCS. */ if ((state->regData[15].v & 0x1) == 0) { UnwPrintd2("Warning: Return address not to Thumb: 0x%08x\n", state->regData[15].v); /* Pop into the PC will not switch mode */ return UNWIND_INCONSISTENT; } /* Store the return address */ if (!UnwReportRetAddr(state, state->regData[15].v)) return UNWIND_TRUNCATED; /* Now have the return address */ UnwPrintd2(" Return PC=%x\n", state->regData[15].v); /* Update the pc */ state->regData[13].v += 4; /* Compensate for the auto-increment, which isn't needed here */ state->regData[15].v -= 2; } } } else { int8_t r; /* Store to memory: PUSH */ UnwPrintd2("PUSH {Rlist%s}", R ? ", LR" : ""); /* Check if the LR is to be pushed */ if (R) { UnwPrintd3("\n lr = 0x%08x\t; %s", state->regData[14].v, M_Origin2Str(state->regData[14].o)); state->regData[13].v -= 4; /* Write the register value to memory */ if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[14])) return UNWIND_DWRITE_W_FAIL; } for (r = 7; r >= 0; r--) { if (rList & (0x1 << r)) { UnwPrintd4("\n r%d = 0x%08x\t; %s", r, state->regData[r].v, M_Origin2Str(state->regData[r].o)); state->regData[13].v -= 4; if (!UnwMemWriteRegister(state, state->regData[13].v, &state->regData[r])) return UNWIND_DWRITE_W_FAIL; } } } } /* * Conditional branches * Bcond */ else if ((instr & 0xF000) == 0xD000) { int32_t branchValue = (instr & 0xFF); if (branchValue & 0x80) branchValue |= 0xFFFFFF00; /* Branch distance is twice that specified in the instruction. */ branchValue *= 2; UnwPrintd2("Bcond %d \n", branchValue); /* Only take the branch if a loop was detected */ if (loopDetected) { /* Update PC */ state->regData[15].v += branchValue; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", state->regData[15].v + 2); } } /* Format 18: unconditional branch * B label */ else if ((instr & 0xF800) == 0xE000) { uint32_t v; int32_t branchValue = signExtend11(instr & 0x07FF); /* Branch distance is twice that specified in the instruction. */ branchValue *= 2; UnwPrintd2("B %d \n", branchValue); /* Update PC */ state->regData[15].v += branchValue; /* Need to advance by a word to account for pre-fetch. * Advance by a half word here, allowing the normal address * advance to account for the other half word. */ state->regData[15].v += 2; /* Compute the jump address */ v = state->regData[15].v + 2; /* Display PC of next instruction */ UnwPrintd2(" New PC=%x", v); /* Did we detect an infinite loop ? */ loopDetected = lastJumpAddr == v; /* Remember the last address we jumped to */ lastJumpAddr = v; } else { UnwPrintd1("????"); /* Unknown/undecoded. May alter some register, so invalidate file */ UnwInvalidateRegisterFile(state->regData); } UnwPrintd1("\n"); /* Should never hit the reset vector */ if (state->regData[15].v == 0) return UNWIND_RESET; /* Check next address */ state->regData[15].v += 2; /* Garbage collect the memory hash (used only for the stack) */ UnwMemHashGC(state); if (--t == 0) return UNWIND_EXHAUSTED; } while (!found); return UNWIND_SUCCESS; } #endif // __arm__ || __thumb__
32.323034
149
0.499261
qisback
d54606df4cb1464acde729e0b0d7c31afe675644
2,401
cpp
C++
test/Euclid/Geometry/Test.Axis.cpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
7
2015-10-16T20:49:20.000Z
2019-04-17T09:34:35.000Z
test/Euclid/Geometry/Test.Axis.cpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
null
null
null
test/Euclid/Geometry/Test.Axis.cpp
kurocha/euclid
932e4a01043442becc696eb337e796ae9578a078
[ "Unlicense", "MIT" ]
null
null
null
#include <UnitTest/UnitTest.hpp> #include <Euclid/Geometry/Axis.hpp> namespace Euclid { namespace Geometry { UnitTest::Suite AxisTestSuite { "Euclid::Geometry::Axis", {"Construction", [](UnitTest::Examiner & examiner) { auto a1 = Axis<RealT>{IDENTITY}; examiner << "Identity axis has zero translation." << std::endl; examiner.check(a1.translation().equivalent(0)); examiner << "Identity axis has zero rotation." << std::endl; examiner.check(a1.rotation().angle().equivalent(0_deg)); auto a2 = Axis<RealT>{{1, 2, 3}, rotate<Z>(R90)}; examiner << "Axis has correct translation." << std::endl; examiner.check(a2.translation().equivalent({1, 2, 3})); examiner << "Axis has correct rotation." << std::endl; examiner.check(a2.rotation().equivalent((Quat)rotate<Z>(R90))); // This transform should move any points from axis-space to origin-space auto p1 = a2.to_origin() * Vec3(1, 2, 3); /// This transform should move any points from origin-space to axis-space auto p2 = a2.from_origin() * Vec3(0); examiner << "Point is transformed to origin." << std::endl; examiner.check(p1.equivalent(0)); examiner << "Point is transformed from origin." << std::endl; examiner.check(p2.equivalent({1, 2, 3})); auto p3 = a2.to_origin() * Vec3(2, 2, 3); examiner << "Point is rotated correctly around Z." << std::endl; examiner.check(p3.equivalent({0, 1, 0})); } }, {"Axis-Axis Mating", [](UnitTest::Examiner & examiner) { auto a1 = Axis<RealT>({10, 10, 10}, IDENTITY); auto a2 = Axis<RealT>({-5, -5, -5}, rotate<Z>(R90)); auto m1 = a1.mate_with(a2); auto p1 = m1 * Vec3(10, 10, 10); examiner << "Point is translated." << std::endl; examiner.check(p1.equivalent({-5, -5, -5})); auto p2 = m1 * Vec3(10, 10, 15); examiner << "Point is translated." << std::endl; examiner.check(p2.equivalent({-5, -5, 0})); auto p3 = m1 * Vec3(10, 15, 10); examiner << "Point is translated and rotated." << std::endl; examiner.check(p3.equivalent({-10, -5, -5})); auto m2 = a1.mate_with(a2, translate(Vec3{1, 1, 1})); auto p4 = m2 * Vec3(10, 10, 10); examiner << "Point is transformed with intermediate translation." << std::endl; examiner.check(p4.equivalent({-6, -4, -4})); } }, }; } }
28.927711
84
0.602249
kurocha
d5468bb44c87927ca17b5b9a853ee45a7ca6ab93
8,428
cc
C++
src/devices/testing/mock-ddk/mock-device.cc
lambdaxymox/fuchsia
177f2940747db40d498ad4ef2442cd8f78edb965
[ "BSD-2-Clause" ]
1
2021-12-23T01:55:48.000Z
2021-12-23T01:55:48.000Z
src/devices/testing/mock-ddk/mock-device.cc
lambdaxymox/fuchsia
177f2940747db40d498ad4ef2442cd8f78edb965
[ "BSD-2-Clause" ]
1
2020-01-07T00:50:54.000Z
2020-03-28T03:56:01.000Z
src/devices/testing/mock-ddk/mock-device.cc
lambdaxymox/fuchsia
177f2940747db40d498ad4ef2442cd8f78edb965
[ "BSD-2-Clause" ]
1
2021-12-23T06:22:27.000Z
2021-12-23T06:22:27.000Z
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/devices/testing/mock-ddk/mock-device.h" #include <zircon/syscalls/log.h> MockDevice::MockDevice(device_add_args_t* args, MockDevice* parent) : parent_(parent), ops_(args->ops), ctx_(args->ctx), name_(args->name) { if (args->proto_id && args->proto_ops) { AddProtocol(args->proto_id, args->proto_ops, ctx_); } } // static std::shared_ptr<MockDevice> MockDevice::FakeRootParent() { // Using `new` to access a non-public constructor. return std::shared_ptr<MockDevice>(new MockDevice()); } // Static member function. zx_status_t MockDevice::Create(device_add_args_t* args, MockDevice* parent, MockDevice** out_dev) { // We only check the minimum requirements to make sure the mock does not crash: if (!parent || !args || !args->name) { return ZX_ERR_INVALID_ARGS; } // Using `new` to access a non-public constructor. auto new_device = std::shared_ptr<MockDevice>(new MockDevice(args, parent)); *out_dev = new_device.get(); parent->children_.emplace_back(std::move(new_device)); // PropagateMetadata to last child: for (const auto& [key, value] : parent->metadata_) { parent->children().back()->metadata_[key] = value; } parent->children().back()->PropagateMetadata(); return ZX_OK; } MockDevice* MockDevice::GetLatestChild() { if (child_count()) { return children_.back().get(); } return nullptr; } // Templates that dispatch the protocol operations if they were set. // If they were not set, the second parameter is returned to the caller // (usually ZX_ERR_NOT_SUPPORTED) template <typename RetType, typename... ArgTypes> RetType Dispatch(void* ctx, RetType (*op)(void* ctx, ArgTypes...), RetType fallback, ArgTypes... args) { return op ? (*op)(ctx, args...) : fallback; } template <typename... ArgTypes> void Dispatch(void* ctx, void (*op)(void* ctx, ArgTypes...), ArgTypes... args) { if (op) { (*op)(ctx, args...); } } void MockDevice::InitOp() { Dispatch(ctx_, ops_->init); } zx_status_t MockDevice::OpenOp(zx_device_t** dev_out, uint32_t flags) { return Dispatch(ctx_, ops_->open, ZX_OK, dev_out, flags); } zx_status_t MockDevice::CloseOp(uint32_t flags) { return Dispatch(ctx_, ops_->close, ZX_OK, flags); } void MockDevice::UnbindOp() { Dispatch(ctx_, ops_->unbind); } void MockDevice::ReleaseOp() { Dispatch(ctx_, ops_->release); // Make parent release child now for (auto it = parent_->children_.begin(); it != parent_->children_.end(); ++it) { if (it->get() == this) { parent_->children_.erase(it); return; } } // Print error: we did not find ourselves! } MockDevice::~MockDevice() { while (!children_.empty()) { // This should remove the first child device from children_: children_.front()->ReleaseOp(); } } void MockDevice::SuspendNewOp(uint8_t requested_state, bool enable_wake, uint8_t suspend_reason) { Dispatch(ctx_, ops_->suspend, requested_state, enable_wake, suspend_reason); } zx_status_t MockDevice::SetPerformanceStateOp(uint32_t requested_state, uint32_t* out_state) { return Dispatch(ctx_, ops_->set_performance_state, ZX_ERR_NOT_SUPPORTED, requested_state, out_state); } zx_status_t MockDevice::ConfigureAutoSuspendOp(bool enable, uint8_t requested_state) { return Dispatch(ctx_, ops_->configure_auto_suspend, ZX_ERR_NOT_SUPPORTED, enable, requested_state); } void MockDevice::ResumeNewOp(uint32_t requested_state) { Dispatch(ctx_, ops_->resume, requested_state); } zx_status_t MockDevice::ReadOp(void* buf, size_t count, zx_off_t off, size_t* actual) { return Dispatch(ctx_, ops_->read, ZX_ERR_NOT_SUPPORTED, buf, count, off, actual); } zx_status_t MockDevice::WriteOp(const void* buf, size_t count, zx_off_t off, size_t* actual) { return Dispatch(ctx_, ops_->write, ZX_ERR_NOT_SUPPORTED, buf, count, off, actual); } zx_off_t MockDevice::GetSizeOp() { return Dispatch(ctx_, ops_->get_size, 0lu); } zx_status_t MockDevice::MessageOp(fidl_incoming_msg_t* msg, fidl_txn_t* txn) { return Dispatch(ctx_, ops_->message, ZX_ERR_NOT_SUPPORTED, msg, txn); } void MockDevice::ChildPreReleaseOp(void* child_ctx) { Dispatch(ctx_, ops_->child_pre_release, child_ctx); } void MockDevice::SetMetadata(uint32_t type, const void* data, size_t data_length) { metadata_[type] = std::make_pair(data, data_length); PropagateMetadata(); } zx_status_t MockDevice::GetMetadata(uint32_t type, void* buf, size_t buflen, size_t* actual) { auto itr = metadata_.find(type); if (itr != metadata_.end()) { auto [metadata, size] = itr->second; *actual = size; if (buflen < size) { return ZX_ERR_BUFFER_TOO_SMALL; } memcpy(buf, metadata, size); return ZX_OK; } return ZX_ERR_NOT_FOUND; } zx_status_t MockDevice::GetMetadataSize(uint32_t type, size_t* out_size) { auto itr = metadata_.find(type); if (itr != metadata_.end()) { auto [_, size] = itr->second; *out_size = size; return ZX_OK; } return ZX_ERR_BAD_STATE; } void MockDevice::PropagateMetadata() { for (auto& child : children_) { for (const auto& [key, value] : metadata_) { child->metadata_[key] = value; } child->PropagateMetadata(); } } void MockDevice::AddProtocol(uint32_t id, const void* ops, void* ctx) { protocols_.push_back(mock_ddk::ProtocolEntry{id, {ops, ctx}}); } void MockDevice::AddParentProtocol(uint32_t id, const void* ops, void* ctx) { if (!IsRootParent()) { parent_->AddProtocol(id, ops, ctx); } } void MockDevice::SetFirmware(std::vector<uint8_t> firmware, std::string_view path) { firmware_[path] = std::move(firmware); } void MockDevice::SetFirmware(std::string firmware, std::string_view path) { std::vector<uint8_t> vec(firmware.begin(), firmware.end()); SetFirmware(vec, path); } zx_status_t MockDevice::LoadFirmware(std::string_view path, zx_handle_t* fw, size_t* size) { auto firmware = firmware_.find(path); // If a match is not found to 'path', check if there is a firmware that was loaded with // path == nullptr: if (firmware == firmware_.end()) { firmware = firmware_.find(""); } if (firmware == firmware_.end()) { return ZX_ERR_NOT_FOUND; } zx_status_t status = ZX_OK; zx_handle_t vmo = ZX_HANDLE_INVALID; if ((status = zx_vmo_create(firmware->second.size(), 0, &vmo)) != ZX_OK) { return status; } if ((status = zx_vmo_write(vmo, firmware->second.data(), 0, firmware->second.size())) != ZX_OK) { return status; } *fw = vmo; *size = firmware->second.size(); return ZX_OK; } zx_status_t MockDevice::GetProtocol(uint32_t proto_id, void* protocol) const { auto out = reinterpret_cast<mock_ddk::Protocol*>(protocol); // First we check if the user has added protocols: for (const auto& proto : protocols_) { if (proto_id == proto.id) { out->ops = proto.proto.ops; out->ctx = proto.proto.ctx; return ZX_OK; } } return ZX_ERR_NOT_SUPPORTED; } size_t MockDevice::descendant_count() const { size_t count = child_count(); for (auto& child : children_) { count += child->descendant_count(); } return count; } // helper functions: namespace { zx_status_t ProcessDeviceRemoval(MockDevice* device) { device->UnbindOp(); // deleting children, so use a while loop: while (!device->children().empty()) { auto status = ProcessDeviceRemoval(device->children().back().get()); if (status != ZX_OK) { return status; } } if (device->HasUnbindOp()) { zx_status_t status = device->WaitUntilUnbindReplyCalled(); if (status != ZX_OK) { return status; } } device->ReleaseOp(); return ZX_OK; } } // anonymous namespace zx_status_t mock_ddk::ReleaseFlaggedDevices(MockDevice* device) { if (device->AsyncRemoveCalled()) { return ProcessDeviceRemoval(device); } // Make a vector of the child device pointers, because we might delete the child: std::vector<MockDevice*> children; std::transform(device->children().begin(), device->children().end(), std::back_inserter(children), [](std::shared_ptr<MockDevice> c) -> MockDevice* { return c.get(); }); for (auto child : children) { auto ret = ReleaseFlaggedDevices(child); if (ret != ZX_OK) { return ret; } } return ZX_OK; }
30.871795
100
0.691742
lambdaxymox
d5480991c16607bdb60b2f0c4de714ceb7538ddc
3,136
cpp
C++
game/Controller.cpp
eslingsby/SimpleEngine
60b07c235f57388b7b0c6db44cedb8f21b921bea
[ "MIT" ]
null
null
null
game/Controller.cpp
eslingsby/SimpleEngine
60b07c235f57388b7b0c6db44cedb8f21b921bea
[ "MIT" ]
null
null
null
game/Controller.cpp
eslingsby/SimpleEngine
60b07c235f57388b7b0c6db44cedb8f21b921bea
[ "MIT" ]
null
null
null
#include "Controller.hpp" #include "Transform.hpp" #include "Window.hpp" Controller::Controller(Engine& engine) : _engine(engine), _possessed(engine) { SYSFUNC_ENABLE(SystemInterface, update, 0); SYSFUNC_ENABLE(SystemInterface, cursorPosition, 0); SYSFUNC_ENABLE(SystemInterface, keyInput, 0); SYSFUNC_ENABLE(SystemInterface, cursorEnter, 0); SYSFUNC_ENABLE(SystemInterface, mousePress, 0); SYSFUNC_ENABLE(SystemInterface, windowOpen, 0); SYSFUNC_ENABLE(SystemInterface, scrollWheel, 0); assert(_engine.hasSystem<Window>()); } void Controller::update(double dt) { Transform* transform = nullptr; if (_possessed.valid()) transform = _possessed.get<Transform>(); if (transform && _locked) { transform->globalRotate(glm::quat({ 0.0, 0.0, -_dMousePos.x * dt })); transform->localRotate(glm::quat({ -_dMousePos.y * dt, 0.0, 0.0 })); float moveSpeed = 300.f * dt; if (_boost) moveSpeed = 1000.f * dt; transform->localTranslate(glm::vec3(0.f, 0.f, -_flash * 100.f)); if (_forward) transform->localTranslate(Transform::localForward * (float)moveSpeed); if (_back) transform->localTranslate(Transform::localBack * (float)moveSpeed); if (_left) transform->localTranslate(Transform::localLeft * (float)moveSpeed); if (_right) transform->localTranslate(Transform::localRight * (float)moveSpeed); if (_up) transform->globalTranslate(Transform::globalUp * (float)moveSpeed); if (_down) transform->globalTranslate(Transform::globalDown * (float)moveSpeed); } _flash = 0; _dMousePos = { 0.0, 0.0 }; } void Controller::cursorPosition(glm::dvec2 position){ /* glm::vec2 newMousePos = position; if (_mousePos == glm::vec2(0.0, 0.0)) _mousePos = newMousePos; _dMousePos = newMousePos - _mousePos; _mousePos = newMousePos; */ _dMousePos = position; } void Controller::keyInput(uint32_t key, Action action, uint8_t mods){ if (action == Action::Release && key == Key::Key_Escape) { if (_locked) { _engine.system<Window>().setLockedCursor(false); _locked = false; } else if (!_locked) { _engine.quit(); } return; } if (!_possessed.valid()) return; bool value; if (action == Action::Press) value = true; else if (action == Action::Release) value = false; else return; switch (key) { case Key::Key_W: _forward = value; return; case Key::Key_S: _back = value; return; case Key::Key_A: _left = value; return; case Key::Key_D: _right = value; return; case Key::Key_Space: _up = value; return; case Key::Key_LCtrl: _down = value; return; case Key::Key_LShift: _boost = value; return; } } void Controller::cursorEnter(bool enterered) { _cursorInside = enterered; } void Controller::mousePress(uint32_t button, Action action, uint8_t mods) { if (action == Action::Release && !_locked && _cursorInside) { _engine.system<Window>().setLockedCursor(true); _locked = true; } } void Controller::windowOpen(bool opened){ if (!opened) _engine.quit(); } void Controller::scrollWheel(glm::dvec2 offset){ _flash += (float)offset.y; } void Controller::setPossessed(uint64_t id) { _possessed.set(id); }
22.4
78
0.695791
eslingsby
d54be65c70afd2bb465f85bad04edc0d051e2d39
35,240
cc
C++
ui/gfx/render_text.cc
JoKaWare/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
19
2015-03-30T09:49:58.000Z
2020-01-17T20:05:12.000Z
ui/gfx/render_text.cc
jjzhang166/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
1
2015-12-31T06:08:27.000Z
2015-12-31T06:08:27.000Z
ui/gfx/render_text.cc
jjzhang166/WTL-DUI
89fd6f4ed7e6a4ce85f9af29c40de0d9a85ca8b2
[ "BSD-3-Clause" ]
11
2015-06-01T06:18:03.000Z
2020-05-10T07:18:53.000Z
// 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 "ui/gfx/render_text.h" #include <algorithm> #include "base/debug/trace_event.h" #include "base/i18n/break_iterator.h" #include "base/logging.h" #include "base/stl_util.h" #include "third_party/skia/include/core/SkColorFilter.h" #include "third_party/skia/include/core/SkTypeface.h" #include "third_party/skia/include/effects/SkBlurMaskFilter.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "third_party/skia/include/effects/SkLayerDrawLooper.h" #include "ui/base/text/utf16_indexing.h" #include "ui/gfx/canvas.h" #include "ui/gfx/insets.h" #include "ui/gfx/skia_util.h" #include "ui/gfx/shadow_value.h" namespace { // All chars are replaced by this char when the password style is set. // TODO(benrg): GTK uses the first of U+25CF, U+2022, U+2731, U+273A, '*' // that's available in the font (find_invisible_char() in gtkentry.c). const char16 kPasswordReplacementChar = '*'; // Default color used for the cursor. const SkColor kDefaultCursorColor = SK_ColorBLACK; // Default color used for drawing selection text. const SkColor kDefaultSelectionColor = SK_ColorBLACK; // Default color used for drawing selection background. const SkColor kDefaultSelectionBackgroundColor = SK_ColorGRAY; #ifndef NDEBUG // Check StyleRanges invariant conditions: sorted and non-overlapping ranges. void CheckStyleRanges(const gfx::StyleRanges& style_ranges, size_t length) { if (length == 0) { DCHECK(style_ranges.empty()) << "Style ranges exist for empty text."; return; } for (gfx::StyleRanges::size_type i = 0; i < style_ranges.size() - 1; i++) { const ui::Range& former = style_ranges[i].range; const ui::Range& latter = style_ranges[i + 1].range; DCHECK(!former.is_empty()) << "Empty range at " << i << ":" << former; DCHECK(former.IsValid()) << "Invalid range at " << i << ":" << former; DCHECK(!former.is_reversed()) << "Reversed range at " << i << ":" << former; DCHECK(former.end() == latter.start()) << "Ranges gap/overlap/unsorted." << "former:" << former << ", latter:" << latter; } const gfx::StyleRange& end_style = *style_ranges.rbegin(); DCHECK(!end_style.range.is_empty()) << "Empty range at end."; DCHECK(end_style.range.IsValid()) << "Invalid range at end."; DCHECK(!end_style.range.is_reversed()) << "Reversed range at end."; DCHECK(end_style.range.end() == length) << "Style and text length mismatch."; } #endif void ApplyStyleRangeImpl(gfx::StyleRanges* style_ranges, const gfx::StyleRange& style_range) { const ui::Range& new_range = style_range.range; // Follow StyleRanges invariant conditions: sorted and non-overlapping ranges. gfx::StyleRanges::iterator i; for (i = style_ranges->begin(); i != style_ranges->end();) { if (i->range.end() < new_range.start()) { i++; } else if (i->range.start() == new_range.end()) { break; } else if (new_range.Contains(i->range)) { i = style_ranges->erase(i); if (i == style_ranges->end()) break; } else if (i->range.start() < new_range.start() && i->range.end() > new_range.end()) { // Split the current style into two styles. gfx::StyleRange split_style = gfx::StyleRange(*i); split_style.range.set_end(new_range.start()); i = style_ranges->insert(i, split_style) + 1; i->range.set_start(new_range.end()); break; } else if (i->range.start() < new_range.start()) { i->range.set_end(new_range.start()); i++; } else if (i->range.end() > new_range.end()) { i->range.set_start(new_range.end()); break; } else { NOTREACHED(); } } // Add the new range in its sorted location. style_ranges->insert(i, style_range); } // Converts |gfx::Font::FontStyle| flags to |SkTypeface::Style| flags. SkTypeface::Style ConvertFontStyleToSkiaTypefaceStyle(int font_style) { int skia_style = SkTypeface::kNormal; if (font_style & gfx::Font::BOLD) skia_style |= SkTypeface::kBold; if (font_style & gfx::Font::ITALIC) skia_style |= SkTypeface::kItalic; return static_cast<SkTypeface::Style>(skia_style); } // Given |font| and |display_width|, returns the width of the fade gradient. int CalculateFadeGradientWidth(const gfx::Font& font, int display_width) { // Fade in/out about 2.5 characters of the beginning/end of the string. // The .5 here is helpful if one of the characters is a space. // Use a quarter of the display width if the display width is very short. const int average_character_width = font.GetAverageCharacterWidth(); const double gradient_width = std::min(average_character_width * 2.5, display_width / 4.0); DCHECK_GE(gradient_width, 0.0); return static_cast<int>(floor(gradient_width + 0.5)); } // Appends to |positions| and |colors| values corresponding to the fade over // |fade_rect| from color |c0| to color |c1|. void AddFadeEffect(const gfx::Rect& text_rect, const gfx::Rect& fade_rect, SkColor c0, SkColor c1, std::vector<SkScalar>* positions, std::vector<SkColor>* colors) { const SkScalar left = static_cast<SkScalar>(fade_rect.x() - text_rect.x()); const SkScalar width = static_cast<SkScalar>(fade_rect.width()); const SkScalar p0 = left / text_rect.width(); const SkScalar p1 = (left + width) / text_rect.width(); // Prepend 0.0 to |positions|, as required by Skia. if (positions->empty() && p0 != 0.0) { positions->push_back(0.0); colors->push_back(c0); } positions->push_back(p0); colors->push_back(c0); positions->push_back(p1); colors->push_back(c1); } // Creates a SkShader to fade the text, with |left_part| specifying the left // fade effect, if any, and |right_part| specifying the right fade effect. SkShader* CreateFadeShader(const gfx::Rect& text_rect, const gfx::Rect& left_part, const gfx::Rect& right_part, SkColor color) { // Fade alpha of 51/255 corresponds to a fade of 0.2 of the original color. const SkColor fade_color = SkColorSetA(color, 51); std::vector<SkScalar> positions; std::vector<SkColor> colors; if (!left_part.IsEmpty()) AddFadeEffect(text_rect, left_part, fade_color, color, &positions, &colors); if (!right_part.IsEmpty()) AddFadeEffect(text_rect, right_part, color, fade_color, &positions, &colors); DCHECK(!positions.empty()); // Terminate |positions| with 1.0, as required by Skia. if (positions.back() != 1.0) { positions.push_back(1.0); colors.push_back(colors.back()); } SkPoint points[2]; points[0].iset(text_rect.x(), text_rect.y()); points[1].iset(text_rect.right(), text_rect.y()); return SkGradientShader::CreateLinear(&points[0], &colors[0], &positions[0], colors.size(), SkShader::kClamp_TileMode); } } // namespace namespace gfx { namespace internal { SkiaTextRenderer::SkiaTextRenderer(Canvas* canvas) : canvas_skia_(canvas->sk_canvas()), started_drawing_(false) { DCHECK(canvas_skia_); paint_.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint_.setStyle(SkPaint::kFill_Style); paint_.setAntiAlias(true); paint_.setSubpixelText(true); paint_.setLCDRenderText(true); bounds_.setEmpty(); } SkiaTextRenderer::~SkiaTextRenderer() { // Work-around for http://crbug.com/122743, where non-ClearType text is // rendered with incorrect gamma when using the fade shader. Draw the text // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode. // // TODO(asvitkine): Remove this work-around once the Skia bug is fixed. // http://code.google.com/p/skia/issues/detail?id=590 if (deferred_fade_shader_.get()) { paint_.setShader(deferred_fade_shader_.get()); paint_.setXfermodeMode(SkXfermode::kDstIn_Mode); canvas_skia_->drawRect(bounds_, paint_); canvas_skia_->restore(); } } void SkiaTextRenderer::SetDrawLooper(SkDrawLooper* draw_looper) { paint_.setLooper(draw_looper); } void SkiaTextRenderer::SetFontSmoothingSettings(bool enable_smoothing, bool enable_lcd_text) { paint_.setAntiAlias(enable_smoothing); paint_.setSubpixelText(enable_smoothing); paint_.setLCDRenderText(enable_lcd_text); } void SkiaTextRenderer::SetTypeface(SkTypeface* typeface) { paint_.setTypeface(typeface); } void SkiaTextRenderer::SetTextSize(int size) { paint_.setTextSize(size); } void SkiaTextRenderer::SetFontFamilyWithStyle(const std::string& family, int style) { DCHECK(!family.empty()); SkTypeface::Style skia_style = ConvertFontStyleToSkiaTypefaceStyle(style); SkTypeface* typeface = SkTypeface::CreateFromName(family.c_str(), skia_style); SkAutoUnref auto_unref(typeface); if (typeface) { // |paint_| adds its own ref. So don't |release()| it from the ref ptr here. SetTypeface(typeface); // Enable fake bold text if bold style is needed but new typeface does not // have it. paint_.setFakeBoldText((skia_style & SkTypeface::kBold) && !typeface->isBold()); } } void SkiaTextRenderer::SetForegroundColor(SkColor foreground) { paint_.setColor(foreground); } void SkiaTextRenderer::SetShader(SkShader* shader, const Rect& bounds) { bounds_ = RectToSkRect(bounds); paint_.setShader(shader); } void SkiaTextRenderer::DrawPosText(const SkPoint* pos, const uint16* glyphs, size_t glyph_count) { if (!started_drawing_) { started_drawing_ = true; // Work-around for http://crbug.com/122743, where non-ClearType text is // rendered with incorrect gamma when using the fade shader. Draw the text // to a layer and restore it faded by drawing a rect in kDstIn_Mode mode. // // Skip this when there is a looper which seems not working well with // deferred paint. Currently a looper is only used for text shadows. // // TODO(asvitkine): Remove this work-around once the Skia bug is fixed. // http://code.google.com/p/skia/issues/detail?id=590 if (!paint_.isLCDRenderText() && paint_.getShader() && !paint_.getLooper()) { deferred_fade_shader_ = paint_.getShader(); paint_.setShader(NULL); canvas_skia_->saveLayer(&bounds_, NULL); } } const size_t byte_length = glyph_count * sizeof(glyphs[0]); canvas_skia_->drawPosText(&glyphs[0], byte_length, &pos[0], paint_); } // Draw underline and strike through text decorations. // Based on |SkCanvas::DrawTextDecorations()| and constants from: // third_party/skia/src/core/SkTextFormatParams.h void SkiaTextRenderer::DrawDecorations(int x, int y, int width, const StyleRange& style) { if (!style.underline && !style.strike && !style.diagonal_strike) return; // Fraction of the text size to lower a strike through below the baseline. const SkScalar kStrikeThroughOffset = (-SK_Scalar1 * 6 / 21); // Fraction of the text size to lower an underline below the baseline. const SkScalar kUnderlineOffset = (SK_Scalar1 / 9); // Fraction of the text size to use for a strike through or under-line. const SkScalar kLineThickness = (SK_Scalar1 / 18); // Fraction of the text size to use for a top margin of a diagonal strike. const SkScalar kDiagonalStrikeThroughMarginOffset = (SK_Scalar1 / 4); SkScalar text_size = paint_.getTextSize(); SkScalar height = SkScalarMul(text_size, kLineThickness); SkRect r; r.fLeft = x; r.fRight = x + width; if (style.underline) { SkScalar offset = SkScalarMulAdd(text_size, kUnderlineOffset, y); r.fTop = offset; r.fBottom = offset + height; canvas_skia_->drawRect(r, paint_); } if (style.strike) { SkScalar offset = SkScalarMulAdd(text_size, kStrikeThroughOffset, y); r.fTop = offset; r.fBottom = offset + height; canvas_skia_->drawRect(r, paint_); } if (style.diagonal_strike) { SkScalar offset = SkScalarMul(text_size, kDiagonalStrikeThroughMarginOffset); SkPaint paint(paint_); paint.setAntiAlias(true); paint.setStyle(SkPaint::kFill_Style); paint.setStrokeWidth(height); canvas_skia_->drawLine( SkIntToScalar(x), SkIntToScalar(y) - text_size + offset, SkIntToScalar(x + width), SkIntToScalar(y), paint); } } } // namespace internal StyleRange::StyleRange() : foreground(SK_ColorBLACK), font_style(gfx::Font::NORMAL), strike(false), diagonal_strike(false), underline(false) { } RenderText::~RenderText() { } void RenderText::SetText(const string16& text) { DCHECK(!composition_range_.IsValid()); size_t old_text_length = text_.length(); text_ = text; // Update the style ranges as needed. if (text_.empty()) { style_ranges_.clear(); } else if (style_ranges_.empty()) { ApplyDefaultStyle(); } else if (text_.length() > old_text_length) { style_ranges_.back().range.set_end(text_.length()); } else if (text_.length() < old_text_length) { StyleRanges::iterator i; for (i = style_ranges_.begin(); i != style_ranges_.end(); i++) { if (i->range.start() >= text_.length()) { // Style ranges are sorted and non-overlapping, so all the subsequent // style ranges should be out of text_.length() as well. style_ranges_.erase(i, style_ranges_.end()); break; } } // Since style ranges are sorted and non-overlapping, if there is a style // range ends beyond text_.length, it must be the last one. style_ranges_.back().range.set_end(text_.length()); } #ifndef NDEBUG CheckStyleRanges(style_ranges_, text_.length()); #endif cached_bounds_and_offset_valid_ = false; // Reset selection model. SetText should always followed by SetSelectionModel // or SetCursorPosition in upper layer. SetSelectionModel(SelectionModel()); ResetLayout(); } void RenderText::SetHorizontalAlignment(HorizontalAlignment alignment) { if (horizontal_alignment_ != alignment) { horizontal_alignment_ = alignment; display_offset_ = Point(); cached_bounds_and_offset_valid_ = false; } } void RenderText::SetFontList(const FontList& font_list) { font_list_ = font_list; cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::SetFontSize(int size) { font_list_ = font_list_.DeriveFontListWithSize(size); cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::SetCursorEnabled(bool cursor_enabled) { cursor_enabled_ = cursor_enabled; cached_bounds_and_offset_valid_ = false; } const Font& RenderText::GetFont() const { return font_list_.GetFonts()[0]; } void RenderText::ToggleInsertMode() { insert_mode_ = !insert_mode_; cached_bounds_and_offset_valid_ = false; } void RenderText::SetObscured(bool obscured) { if (obscured != obscured_) { obscured_ = obscured; cached_bounds_and_offset_valid_ = false; ResetLayout(); } } void RenderText::SetDisplayRect(const Rect& r) { if (r.width() != display_rect_.width()) ResetLayout(); display_rect_ = r; cached_bounds_and_offset_valid_ = false; } void RenderText::SetCursorPosition(size_t position) { MoveCursorTo(position, false); } void RenderText::MoveCursor(BreakType break_type, VisualCursorDirection direction, bool select) { SelectionModel position(cursor_position(), selection_model_.caret_affinity()); // Cancelling a selection moves to the edge of the selection. if (break_type != LINE_BREAK && !selection().is_empty() && !select) { SelectionModel selection_start = GetSelectionModelForSelectionStart(); int start_x = GetCursorBounds(selection_start, true).x(); int cursor_x = GetCursorBounds(position, true).x(); // Use the selection start if it is left (when |direction| is CURSOR_LEFT) // or right (when |direction| is CURSOR_RIGHT) of the selection end. if (direction == CURSOR_RIGHT ? start_x > cursor_x : start_x < cursor_x) position = selection_start; // For word breaks, use the nearest word boundary in the appropriate // |direction|. if (break_type == WORD_BREAK) position = GetAdjacentSelectionModel(position, break_type, direction); } else { position = GetAdjacentSelectionModel(position, break_type, direction); } if (select) position.set_selection_start(selection().start()); MoveCursorTo(position); } bool RenderText::MoveCursorTo(const SelectionModel& model) { // Enforce valid selection model components. size_t text_length = text().length(); ui::Range range(std::min(model.selection().start(), text_length), std::min(model.caret_pos(), text_length)); // The current model only supports caret positions at valid character indices. if (!IsCursorablePosition(range.start()) || !IsCursorablePosition(range.end())) return false; SelectionModel sel(range, model.caret_affinity()); bool changed = sel != selection_model_; SetSelectionModel(sel); return changed; } bool RenderText::MoveCursorTo(const Point& point, bool select) { SelectionModel position = FindCursorPosition(point); if (select) position.set_selection_start(selection().start()); return MoveCursorTo(position); } bool RenderText::SelectRange(const ui::Range& range) { ui::Range sel(std::min(range.start(), text().length()), std::min(range.end(), text().length())); if (!IsCursorablePosition(sel.start()) || !IsCursorablePosition(sel.end())) return false; LogicalCursorDirection affinity = (sel.is_reversed() || sel.is_empty()) ? CURSOR_FORWARD : CURSOR_BACKWARD; SetSelectionModel(SelectionModel(sel, affinity)); return true; } bool RenderText::IsPointInSelection(const Point& point) { if (selection().is_empty()) return false; SelectionModel cursor = FindCursorPosition(point); return RangeContainsCaret( selection(), cursor.caret_pos(), cursor.caret_affinity()); } void RenderText::ClearSelection() { SetSelectionModel(SelectionModel(cursor_position(), selection_model_.caret_affinity())); } void RenderText::SelectAll() { SelectionModel all; if (GetTextDirection() == base::i18n::LEFT_TO_RIGHT) all = SelectionModel(ui::Range(0, text().length()), CURSOR_FORWARD); else all = SelectionModel(ui::Range(text().length(), 0), CURSOR_BACKWARD); SetSelectionModel(all); } void RenderText::SelectWord() { if (obscured_) { SelectAll(); return; } size_t cursor_pos = cursor_position(); //base::i18n::BreakIterator iter(text(), base::i18n::BreakIterator::BREAK_WORD); //bool success = iter.Init(); //DCHECK(success); //if (!success) // return; size_t selection_start = cursor_pos; //for (; selection_start != 0; --selection_start) { // if (iter.IsStartOfWord(selection_start) || // iter.IsEndOfWord(selection_start)) // break; //} //if (selection_start == cursor_pos) // ++cursor_pos; //for (; cursor_pos < text().length(); ++cursor_pos) // if (iter.IsEndOfWord(cursor_pos) || iter.IsStartOfWord(cursor_pos)) // break; MoveCursorTo(selection_start, false); MoveCursorTo(cursor_pos, true); } const ui::Range& RenderText::GetCompositionRange() const { return composition_range_; } void RenderText::SetCompositionRange(const ui::Range& composition_range) { CHECK(!composition_range.IsValid() || ui::Range(0, text_.length()).Contains(composition_range)); composition_range_.set_end(composition_range.end()); composition_range_.set_start(composition_range.start()); ResetLayout(); } void RenderText::ApplyStyleRange(const StyleRange& style_range) { const ui::Range& new_range = style_range.range; if (!new_range.IsValid() || new_range.is_empty()) return; CHECK(!new_range.is_reversed()); CHECK(ui::Range(0, text_.length()).Contains(new_range)); ApplyStyleRangeImpl(&style_ranges_, style_range); #ifndef NDEBUG CheckStyleRanges(style_ranges_, text_.length()); #endif // TODO(xji): only invalidate if font or underline changes. cached_bounds_and_offset_valid_ = false; ResetLayout(); } void RenderText::ApplyDefaultStyle() { style_ranges_.clear(); StyleRange style = StyleRange(default_style_); style.range.set_end(text_.length()); style_ranges_.push_back(style); cached_bounds_and_offset_valid_ = false; ResetLayout(); } VisualCursorDirection RenderText::GetVisualDirectionOfLogicalEnd() { return GetTextDirection() == base::i18n::LEFT_TO_RIGHT ? CURSOR_RIGHT : CURSOR_LEFT; } void RenderText::Draw(Canvas* canvas) { TRACE_EVENT0("gfx", "RenderText::Draw"); { TRACE_EVENT0("gfx", "RenderText::EnsureLayout"); EnsureLayout(); } gfx::Rect clip_rect(display_rect()); clip_rect.Inset(ShadowValue::GetMargin(text_shadows_)); canvas->Save(); canvas->ClipRect(clip_rect); if (!text().empty()) DrawSelection(canvas); DrawCursor(canvas); if (!text().empty()) { TRACE_EVENT0("gfx", "RenderText::Draw draw text"); DrawVisualText(canvas); } canvas->Restore(); } Rect RenderText::GetCursorBounds(const SelectionModel& caret, bool insert_mode) { EnsureLayout(); size_t caret_pos = caret.caret_pos(); // In overtype mode, ignore the affinity and always indicate that we will // overtype the next character. LogicalCursorDirection caret_affinity = insert_mode ? caret.caret_affinity() : CURSOR_FORWARD; int x = 0, width = 0, height = 0; if (caret_pos == (caret_affinity == CURSOR_BACKWARD ? 0 : text().length())) { // The caret is attached to the boundary. Always return a zero-width caret, // since there is nothing to overtype. Size size = GetStringSize(); if ((GetTextDirection() == base::i18n::RIGHT_TO_LEFT) == (caret_pos == 0)) x = size.width(); height = size.height(); } else { size_t grapheme_start = (caret_affinity == CURSOR_FORWARD) ? caret_pos : IndexOfAdjacentGrapheme(caret_pos, CURSOR_BACKWARD); ui::Range xspan; GetGlyphBounds(grapheme_start, &xspan, &height); if (insert_mode) { x = (caret_affinity == CURSOR_BACKWARD) ? xspan.end() : xspan.start(); } else { // overtype mode x = xspan.GetMin(); width = xspan.length(); } } height = std::min(height, display_rect().height()); int y = (display_rect().height() - height) / 2; return Rect(ToViewPoint(Point(x, y)), Size(width, height)); } const Rect& RenderText::GetUpdatedCursorBounds() { UpdateCachedBoundsAndOffset(); return cursor_bounds_; } size_t RenderText::IndexOfAdjacentGrapheme(size_t index, LogicalCursorDirection direction) { if (index > text().length()) return text().length(); EnsureLayout(); if (direction == CURSOR_FORWARD) { while (index < text().length()) { index++; if (IsCursorablePosition(index)) return index; } return text().length(); } while (index > 0) { index--; if (IsCursorablePosition(index)) return index; } return 0; } SelectionModel RenderText::GetSelectionModelForSelectionStart() { const ui::Range& sel = selection(); if (sel.is_empty()) return selection_model_; return SelectionModel(sel.start(), sel.is_reversed() ? CURSOR_BACKWARD : CURSOR_FORWARD); } void RenderText::SetTextShadows(const std::vector<ShadowValue>& shadows) { text_shadows_ = shadows; } RenderText::RenderText() : horizontal_alignment_(base::i18n::IsRTL() ? ALIGN_RIGHT : ALIGN_LEFT), cursor_enabled_(true), cursor_visible_(false), insert_mode_(true), cursor_color_(kDefaultCursorColor), selection_color_(kDefaultSelectionColor), selection_background_focused_color_(kDefaultSelectionBackgroundColor), selection_background_unfocused_color_(kDefaultSelectionBackgroundColor), focused_(false), composition_range_(ui::Range::InvalidRange()), obscured_(false), fade_head_(false), fade_tail_(false), background_is_transparent_(false), cached_bounds_and_offset_valid_(false) { } const Point& RenderText::GetUpdatedDisplayOffset() { UpdateCachedBoundsAndOffset(); return display_offset_; } SelectionModel RenderText::GetAdjacentSelectionModel( const SelectionModel& current, BreakType break_type, VisualCursorDirection direction) { EnsureLayout(); if (break_type == LINE_BREAK || text().empty()) return EdgeSelectionModel(direction); if (break_type == CHARACTER_BREAK) return AdjacentCharSelectionModel(current, direction); DCHECK(break_type == WORD_BREAK); return AdjacentWordSelectionModel(current, direction); } SelectionModel RenderText::EdgeSelectionModel( VisualCursorDirection direction) { if (direction == GetVisualDirectionOfLogicalEnd()) return SelectionModel(text().length(), CURSOR_FORWARD); return SelectionModel(0, CURSOR_BACKWARD); } void RenderText::SetSelectionModel(const SelectionModel& model) { DCHECK_LE(model.selection().GetMax(), text().length()); selection_model_ = model; cached_bounds_and_offset_valid_ = false; } string16 RenderText::GetDisplayText() const { if (!obscured_) return text_; size_t obscured_text_length = static_cast<size_t>(ui::UTF16IndexToOffset(text_, 0, text_.length())); return string16(obscured_text_length, kPasswordReplacementChar); } void RenderText::ApplyCompositionAndSelectionStyles( StyleRanges* style_ranges) { // TODO(msw): This pattern ought to be reconsidered; what about composition // and selection overlaps, retain existing local style features? // Apply a composition style override to a copy of the style ranges. if (composition_range_.IsValid() && !composition_range_.is_empty()) { StyleRange composition_style(default_style_); composition_style.underline = true; composition_style.range = composition_range_; ApplyStyleRangeImpl(style_ranges, composition_style); } // Apply a selection style override to a copy of the style ranges. if (!selection().is_empty()) { StyleRange selection_style(default_style_); selection_style.foreground = selection_color_; selection_style.range = ui::Range(selection().GetMin(), selection().GetMax()); ApplyStyleRangeImpl(style_ranges, selection_style); } // Apply replacement-mode style override to a copy of the style ranges. // // TODO(xji): NEED TO FIX FOR WINDOWS ASAP. Windows call this function (to // apply styles) in ItemizeLogicalText(). In order for the cursor's underline // character to be drawn correctly, we will need to re-layout the text. It's // not practical to do layout on every cursor blink. We need to fix Windows // port to apply styles during drawing phase like Linux port does. // http://crbug.com/110109 if (!insert_mode_ && cursor_visible() && focused()) { StyleRange replacement_mode_style(default_style_); replacement_mode_style.foreground = selection_color_; size_t cursor = cursor_position(); replacement_mode_style.range.set_start(cursor); replacement_mode_style.range.set_end( IndexOfAdjacentGrapheme(cursor, CURSOR_FORWARD)); ApplyStyleRangeImpl(style_ranges, replacement_mode_style); } } Point RenderText::GetTextOrigin() { Point origin = display_rect().origin(); origin = origin.Add(GetUpdatedDisplayOffset()); origin = origin.Add(GetAlignmentOffset()); return origin; } Point RenderText::ToTextPoint(const Point& point) { return point.Subtract(GetTextOrigin()); } Point RenderText::ToViewPoint(const Point& point) { return point.Add(GetTextOrigin()); } int RenderText::GetContentWidth() { return GetStringSize().width() + (cursor_enabled_ ? 1 : 0); } Point RenderText::GetAlignmentOffset() { if (horizontal_alignment() != ALIGN_LEFT) { int x_offset = display_rect().width() - GetContentWidth(); if (horizontal_alignment() == ALIGN_CENTER) x_offset /= 2; return Point(x_offset, 0); } return Point(); } Point RenderText::GetOriginForDrawing() { Point origin(GetTextOrigin()); const int height = GetStringSize().height(); DCHECK_LE(height, display_rect().height()); // Center the text vertically in the display area. origin.Offset(0, (display_rect().height() - height) / 2); return origin; } void RenderText::ApplyFadeEffects(internal::SkiaTextRenderer* renderer) { if (!fade_head() && !fade_tail()) return; const int text_width = GetStringSize().width(); const int display_width = display_rect().width(); // If the text fits as-is, no need to fade. if (text_width <= display_width) return; int gradient_width = CalculateFadeGradientWidth(GetFont(), display_width); if (gradient_width == 0) return; bool fade_left = fade_head(); bool fade_right = fade_tail(); // Under RTL, |fade_right| == |fade_head|. if (GetTextDirection() == base::i18n::RIGHT_TO_LEFT) std::swap(fade_left, fade_right); gfx::Rect solid_part = display_rect(); gfx::Rect left_part; gfx::Rect right_part; if (fade_left) { left_part = solid_part; left_part.Inset(0, 0, solid_part.width() - gradient_width, 0); solid_part.Inset(gradient_width, 0, 0, 0); } if (fade_right) { right_part = solid_part; right_part.Inset(solid_part.width() - gradient_width, 0, 0, 0); solid_part.Inset(0, 0, gradient_width, 0); } gfx::Rect text_rect = display_rect(); text_rect.Inset(GetAlignmentOffset().x(), 0, 0, 0); const SkColor color = default_style().foreground; SkShader* shader = CreateFadeShader(text_rect, left_part, right_part, color); SkAutoUnref auto_unref(shader); if (shader) { // |renderer| adds its own ref. So don't |release()| it from the ref ptr. renderer->SetShader(shader, display_rect()); } } void RenderText::ApplyTextShadows(internal::SkiaTextRenderer* renderer) { if (text_shadows_.empty()) { renderer->SetDrawLooper(NULL); return; } SkLayerDrawLooper* looper = new SkLayerDrawLooper; SkAutoUnref auto_unref(looper); looper->addLayer(); // top layer of the original. SkLayerDrawLooper::LayerInfo layer_info; layer_info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; layer_info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit; layer_info.fColorMode = SkXfermode::kSrc_Mode; for (size_t i = 0; i < text_shadows_.size(); ++i) { const ShadowValue& shadow = text_shadows_[i]; layer_info.fOffset.set(SkIntToScalar(shadow.x()), SkIntToScalar(shadow.y())); // SkBlurMaskFilter's blur radius defines the range to extend the blur from // original mask, which is half of blur amount as defined in ShadowValue. SkMaskFilter* blur_mask = SkBlurMaskFilter::Create( SkDoubleToScalar(shadow.blur() / 2), SkBlurMaskFilter::kNormal_BlurStyle, SkBlurMaskFilter::kHighQuality_BlurFlag); SkColorFilter* color_filter = SkColorFilter::CreateModeFilter( shadow.color(), SkXfermode::kSrcIn_Mode); SkPaint* paint = looper->addLayer(layer_info); SkSafeUnref(paint->setMaskFilter(blur_mask)); SkSafeUnref(paint->setColorFilter(color_filter)); } renderer->SetDrawLooper(looper); } // static bool RenderText::RangeContainsCaret(const ui::Range& range, size_t caret_pos, LogicalCursorDirection caret_affinity) { // NB: exploits unsigned wraparound (WG14/N1124 section 6.2.5 paragraph 9). size_t adjacent = (caret_affinity == CURSOR_BACKWARD) ? caret_pos - 1 : caret_pos + 1; return range.Contains(ui::Range(caret_pos, adjacent)); } void RenderText::MoveCursorTo(size_t position, bool select) { size_t cursor = std::min(position, text().length()); if (IsCursorablePosition(cursor)) SetSelectionModel(SelectionModel( ui::Range(select ? selection().start() : cursor, cursor), (cursor == 0) ? CURSOR_FORWARD : CURSOR_BACKWARD)); } void RenderText::UpdateCachedBoundsAndOffset() { if (cached_bounds_and_offset_valid_) return; // First, set the valid flag true to calculate the current cursor bounds using // the stale |display_offset_|. Applying |delta_offset| at the end of this // function will set |cursor_bounds_| and |display_offset_| to correct values. cached_bounds_and_offset_valid_ = true; cursor_bounds_ = GetCursorBounds(selection_model_, insert_mode_); // Update |display_offset_| to ensure the current cursor is visible. const int display_width = display_rect_.width(); const int content_width = GetContentWidth(); int delta_offset = 0; if (content_width <= display_width || !cursor_enabled()) { // Don't pan if the text fits in the display width or when the cursor is // disabled. delta_offset = -display_offset_.x(); } else if (cursor_bounds_.right() >= display_rect_.right()) { // TODO(xji): when the character overflow is a RTL character, currently, if // we pan cursor at the rightmost position, the entered RTL character is not // displayed. Should pan cursor to show the last logical characters. // // Pan to show the cursor when it overflows to the right, delta_offset = display_rect_.right() - cursor_bounds_.right() - 1; } else if (cursor_bounds_.x() < display_rect_.x()) { // TODO(xji): have similar problem as above when overflow character is a // LTR character. // // Pan to show the cursor when it overflows to the left. delta_offset = display_rect_.x() - cursor_bounds_.x(); } else if (display_offset_.x() != 0) { // Reduce the pan offset to show additional overflow text when the display // width increases. const int negate_rtl = horizontal_alignment_ == ALIGN_RIGHT ? -1 : 1; const int offset = negate_rtl * display_offset_.x(); if (display_width > (content_width + offset)) delta_offset = negate_rtl * (display_width - (content_width + offset)); } display_offset_.Offset(delta_offset, 0); cursor_bounds_.Offset(delta_offset, 0); } void RenderText::DrawSelection(Canvas* canvas) { const SkColor color = focused() ? selection_background_focused_color_ : selection_background_unfocused_color_; const std::vector<Rect> sel = GetSubstringBounds(selection()); for (std::vector<Rect>::const_iterator i = sel.begin(); i < sel.end(); ++i) canvas->FillRect(*i, color); } void RenderText::DrawCursor(Canvas* canvas) { // Paint cursor. Replace cursor is drawn as rectangle for now. // TODO(msw): Draw a better cursor with a better indication of association. if (cursor_enabled() && cursor_visible() && focused()) { const Rect& bounds = GetUpdatedCursorBounds(); if (bounds.width() != 0) canvas->FillRect(bounds, cursor_color_); else canvas->DrawRect(bounds, cursor_color_); } } } // namespace gfx
35.346038
82
0.694467
JoKaWare
d54c33c36221627729153743f6beca3a63876318
17,743
cpp
C++
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/SSL/SSL_Asynch_Stream_Test.cpp
549654033/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
2
2020-05-20T05:16:34.000Z
2020-05-20T05:19:19.000Z
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/SSL/SSL_Asynch_Stream_Test.cpp
jimxie2012/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
null
null
null
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/SSL/SSL_Asynch_Stream_Test.cpp
jimxie2012/RDHelp
0f5f9c7d098635c7216713d7137c845c0d999226
[ "MIT" ]
4
2020-05-20T01:50:16.000Z
2021-08-29T13:48:25.000Z
// $Id: SSL_Asynch_Stream_Test.cpp 90163 2010-05-18 21:42:20Z mitza $ // ============================================================================ // // = LIBRARY // tests/SSL // // = FILENAME // SSL_Asynch_Stream_Test.cpp // // = DESCRIPTION // This program is a functionality test of ACE_SSL_Asynch_Stream. // It demonstrates one proper use case of ACE_SSL_Asynch_Stream in the // Proactor framework and validates its basic functionality. // // Usage: SSL_Asynch_Stream_Test [-r <hostname:port#>] // [-t <num threads>] [-d <delay>] // [-i <client conn attempt#>] [-n <client request# per conn>] // // Default value: // <hostname:port#>: ACE_DEFAULT_SERVER_HOST:ACE_DEFAULT_PORT // <num threads>: ACE_MAX_THREADS // <client conn attempt#>: ACE_MAX_ITERATIONS // <client req# per conn>: 20 // <delay>: 0 usec // // = AUTHOR // Steve Huston <shuston@riverace.com> // // ============================================================================ #include "../test_config.h" #include "ace/Default_Constants.h" #include "ace/OS_NS_signal.h" #include "ace/OS_NS_string.h" #include "ace/Event_Handler.h" #include "ace/Get_Opt.h" #include "ace/Proactor.h" #include "ace/Reactor.h" #include "ace/Thread_Manager.h" #include "ace/INET_Addr.h" #include "ace/SSL/SSL_Asynch_Stream.h" #include "ace/SSL/SSL_SOCK_Connector.h" #include "ace/SSL/SSL_SOCK_Acceptor.h" #include "ace/SSL/SSL_SOCK_Stream.h" ACE_RCSID(tests, SSL_Asynch_Stream_Test, "$Id: SSL_Asynch_Stream_Test.cpp 90163 2010-05-18 21:42:20Z mitza $") #if defined (ACE_HAS_THREADS) && ((defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) || (defined (ACE_HAS_AIO_CALLS))) // This only works on Win32 platforms and on Unix platforms // supporting POSIX aio calls. class Client_Handler : public ACE_Handler { public: Client_Handler () : msgs_sent_ (0), stream_ (ACE_SSL_Asynch_Stream::ST_CLIENT), block_ (1024) {} ~Client_Handler (); //FUZZ: disable check_for_lack_ACE_OS int open (ACE_HANDLE); //FUZZ: enable check_for_lack_ACE_OS private: virtual void handle_write_stream (const ACE_Asynch_Write_Stream::Result &result); private: size_t msgs_sent_; ACE_SSL_Asynch_Stream stream_; ACE_Message_Block block_; }; class Server_Handler : public ACE_Handler { public: Server_Handler () : msgs_rcvd_ (0), stream_ (ACE_SSL_Asynch_Stream::ST_SERVER), block_ (1024) {} ~Server_Handler (); //FUZZ: disable check_for_lack_ACE_OS int open (ACE_HANDLE); //FUZZ: enable check_for_lack_ACE_OS private: virtual void handle_read_stream (const ACE_Asynch_Read_Stream::Result &result); private: size_t msgs_rcvd_; ACE_SSL_Asynch_Stream stream_; ACE_Message_Block block_; }; class Server_Acceptor : public ACE_Event_Handler { public: //FUZZ: disable check_for_lack_ACE_OS int open (const ACE_INET_Addr &listen_addr); //FUZZ: enable check_for_lack_ACE_OS // Get the I/O handle. virtual ACE_HANDLE get_handle (void) const; // Called when a new connection is ready to accept. virtual int handle_input (ACE_HANDLE fd = ACE_INVALID_HANDLE); virtual int handle_close (ACE_HANDLE handle, ACE_Reactor_Mask close_mask); private: ACE_SSL_SOCK_Acceptor acceptor_; }; // Accepting end point. This is actually "localhost:10010", but some // platform couldn't resolve the name so we use the IP address // directly here. static const ACE_TCHAR *rendezvous = \ ACE_DEFAULT_SERVER_HOST ACE_TEXT (":") ACE_DEFAULT_SERVER_PORT_STR; // Total number of proactor threads. static size_t num_threads = ACE_MAX_THREADS; #if defined (CHORUS) // Add platforms that can't handle too many // connection simultaneously here. #define ACE_LOAD_FACTOR /2 #else #define ACE_LOAD_FACTOR #endif // Number of client connections to attempt. static size_t cli_conn_no = ACE_MAX_ITERATIONS ACE_LOAD_FACTOR; // Number of requests each client connection sends. static size_t cli_req_no = ACE_MAX_THREADS ACE_LOAD_FACTOR; // Delay before a thread sending the next request (in msec.) static int req_delay = 0; // This is the string sent from client to server. static const char *test_string = "SSL_Asynch_Stream_Test!"; // Function to remove signals from the signal mask. static int disable_signal (int sigmin, int sigmax) { #if !defined (ACE_LACKS_UNIX_SIGNALS) sigset_t signal_set; if (ACE_OS::sigemptyset (&signal_set) == - 1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("Error: (%P|%t):%p\n"), ACE_TEXT ("sigemptyset failed"))); for (int i = sigmin; i <= sigmax; i++) ACE_OS::sigaddset (&signal_set, i); // Put the <signal_set>. # if defined (ACE_LACKS_PTHREAD_THR_SIGSETMASK) // In multi-threaded application this is not POSIX compliant // but let's leave it just in case. if (ACE_OS::sigprocmask (SIG_BLOCK, &signal_set, 0) != 0) # else if (ACE_OS::thr_sigsetmask (SIG_BLOCK, &signal_set, 0) != 0) # endif /* ACE_LACKS_PTHREAD_THR_SIGSETMASK */ ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Error: (%P|%t): %p\n"), ACE_TEXT ("SIG_BLOCK failed")), -1); #else ACE_UNUSED_ARG (sigmin); ACE_UNUSED_ARG (sigmax); #endif /* ACE_LACKS_UNIX_SIGNALS */ return 0; } static void parse_args (int argc, ACE_TCHAR *argv[]) { //FUZZ: disable check_for_lack_ACE_OS ACE_Get_Opt getopt (argc, argv, ACE_TEXT ("r:t:d:i:n:")); int c; while ((c = getopt ()) != -1) { //FUZZ: enable check_for_lack_ACE_OS switch (c) { case 'r': // hostname:port rendezvous = getopt.opt_arg (); break; case 't': num_threads = ACE_OS::atoi (getopt.opt_arg ()); break; case 'd': req_delay = ACE_OS::atoi (getopt.opt_arg ()); break; case 'i': cli_conn_no = ACE_OS::atoi (getopt.opt_arg ()); break; case 'n': cli_req_no = ACE_OS::atoi (getopt.opt_arg ()); break; default: ACE_ERROR ((LM_ERROR, ACE_TEXT ("Usage: %s [-r <hostname:port#>]") ACE_TEXT ("\t[-t <nr threads>] [-d <delay>]") ACE_TEXT ("\t[-i <client conn attempt#>]") ACE_TEXT ("\t[-n <client request# per conn>]\n"), argv[0])); break; } } } Client_Handler::~Client_Handler () { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client %@ handle %d down\n"), this, this->stream_.handle ())); if (this->stream_.handle () != ACE_INVALID_HANDLE) { if (this->msgs_sent_ != cli_req_no) ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Client handle %d sent %d messages; ") ACE_TEXT ("expected %d\n"), this->stream_.handle (), this->msgs_sent_, cli_req_no)); else ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client handle %d sent %d messages; ") ACE_TEXT ("closing connection\n"), this->stream_.handle (), cli_req_no)); } this->stream_.close (); } int Client_Handler::open (ACE_HANDLE handle) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client %@ handle %d up\n"), this, handle)); if (this->stream_.open (*this, handle) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Client_Handler: %p\n"), ACE_TEXT ("open")), -1); this->block_.copy (test_string); if (this->stream_.write (this->block_, this->block_.length ()) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Client_Handler: %p\n"), ACE_TEXT ("initiate write")), -1); return 0; } void Client_Handler::handle_write_stream (const ACE_Asynch_Write_Stream::Result &result) { if (!result.success ()) { errno = result.error (); ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Client handle %d: %p\n"), this->stream_.handle (), ACE_TEXT ("write"))); delete this; return; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client %@ handle %d sent %B of %B bytes\n"), this, this->stream_.handle (), result.bytes_transferred (), result.bytes_to_write ())); ACE_Message_Block &b = result.message_block (); bool send_again = true; if (b.length () == 0) { // All block's data sent; rewind the read pointer and send it again // until we've sent the configured number of times. ++this->msgs_sent_; if (this->msgs_sent_ == cli_req_no) send_again = false; // All done else b.rd_ptr (b.base ()); } if (send_again) { if (this->stream_.write (this->block_, this->block_.length ()) == -1) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Client_Handler: %p\n"), ACE_TEXT ("initiate write"))); delete this; } } else { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Client handle %d done sending\n"), this->stream_.handle ())); delete this; } return; } Server_Handler::~Server_Handler () { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server %@ handle %d down\n"), this, this->stream_.handle ())); if (this->stream_.handle () != ACE_INVALID_HANDLE) { if (this->msgs_rcvd_ != cli_req_no) ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Server handle %d received %d messages; ") ACE_TEXT ("expected %d\n"), this->stream_.handle (), this->msgs_rcvd_, cli_req_no)); else ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server handle %d received %d messages; ") ACE_TEXT ("closing connection\n"), this->stream_.handle (), cli_req_no)); } this->stream_.close (); } int Server_Handler::open (ACE_HANDLE handle) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server %@ handle %d up\n"), this, handle)); if (this->stream_.open (*this, handle) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Server_Handler: %p\n"), ACE_TEXT ("open")), -1); if (this->stream_.read (this->block_, this->block_.space () - 1) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) Server_Handler: %p\n"), ACE_TEXT ("read")), -1); return 0; } void Server_Handler::handle_read_stream (const ACE_Asynch_Read_Stream::Result &result) { if (!result.success ()) { errno = result.error (); ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Server handle %d: %p\n"), this->stream_.handle (), ACE_TEXT ("read"))); delete this; return; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server %@ handle %d recv %B of %B bytes\n"), this, this->stream_.handle (), result.bytes_transferred (), result.bytes_to_read ())); if (result.bytes_transferred () == 0) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Server handle %d closed by peer\n"), this->stream_.handle ())); delete this; return; } // Scan through the received data for the expected string. There may be // multiples and/or partials. Count up how many arrive before the connection // is closed. // Remember that the client side sends the terminating nul; in case the // whole thing didn't arrive, we add a nul to the end of the receive // block so we don't run off the end. When the recv into this buffer was // initiated, we left the last byte empty to facilitate this. ACE_Message_Block &b = result.message_block (); *(b.wr_ptr ()) = '\0'; size_t test_string_len = ACE_OS::strlen (test_string); while (b.length () >= test_string_len) { if (0 != ACE_OS::strncmp (b.rd_ptr (), test_string, test_string_len)) ACE_ERROR_BREAK ((LM_ERROR, ACE_TEXT ("(%t) Read string: %C; expected: %C\n"), b.rd_ptr (), test_string)); b.rd_ptr (test_string_len); // That ran up over the string; can we also consume the nul? if (b.length () > 0) b.rd_ptr (1); ++this->msgs_rcvd_; } b.crunch (); if (this->stream_.read (b, b.space () - 1) == -1) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) Server_Handler: %p\n"), ACE_TEXT ("read"))); delete this; } return; } int Server_Acceptor::open (const ACE_INET_Addr &listen_addr) { if (this->acceptor_.open (listen_addr) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("listen")), -1); return 0; } ACE_HANDLE Server_Acceptor::get_handle (void) const { return this->acceptor_.get_handle (); } int Server_Acceptor::handle_input (ACE_HANDLE) { ACE_SSL_SOCK_Stream new_stream; if (this->acceptor_.accept (new_stream) == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) %p\n"), ACE_TEXT ("accept")), -1); Server_Handler *new_handler = 0; ACE_NEW_RETURN (new_handler, Server_Handler, -1); if (new_handler->open (new_stream.get_handle ()) != 0) delete new_handler; return 0; } int Server_Acceptor::handle_close (ACE_HANDLE, ACE_Reactor_Mask) { this->acceptor_.close (); return 0; } static ACE_THR_FUNC_RETURN proactor_loop (void *) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Start handling events.\n"))); disable_signal (ACE_SIGRTMIN, ACE_SIGRTMAX); disable_signal (SIGPIPE, SIGPIPE); int result = ACE_Proactor::instance ()->proactor_run_event_loop (); if (result == -1) ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("(%t) %p\n"), ACE_TEXT ("Error handling events")), 0); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Done handling events.\n"))); return 0; } static ACE_THR_FUNC_RETURN start_clients (void *) { // Client thread function. ACE_INET_Addr addr (rendezvous); ACE_SSL_SOCK_Connector connect; disable_signal (ACE_SIGRTMIN, ACE_SIGRTMAX); disable_signal (SIGPIPE, SIGPIPE); for (size_t i = 0 ; i < cli_conn_no; i++) { ACE_SSL_SOCK_Stream stream; if (connect.connect (stream, addr) < 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) %p\n"), ACE_TEXT ("connect"))); continue; } Client_Handler *new_handler = 0; ACE_NEW_RETURN (new_handler, Client_Handler, (ACE_THR_FUNC_RETURN)-1); if (new_handler->open (stream.get_handle ()) != 0) { delete new_handler; stream.close (); } } return 0; } int run_main (int argc, ACE_TCHAR *argv[]) { ACE_START_TEST (ACE_TEXT ("SSL_Asynch_Stream_Test")); ACE_SSL_Context *context = ACE_SSL_Context::instance (); // Note - the next two strings are naked on purpose... the arguments to // the ACE_SSL_Context methods are const char *, not ACE_TCHAR *. context->certificate ("dummy.pem", SSL_FILETYPE_PEM); context->private_key ("key.pem", SSL_FILETYPE_PEM); parse_args (argc, argv); disable_signal (ACE_SIGRTMIN, ACE_SIGRTMAX); disable_signal (SIGPIPE, SIGPIPE); Server_Acceptor acceptor; ACE_INET_Addr accept_addr (rendezvous); if (acceptor.open (accept_addr) == -1) return 1; if (-1 == ACE_Reactor::instance ()->register_handler (&acceptor, ACE_Event_Handler::ACCEPT_MASK)) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%t) %p; aborting\n"), ACE_TEXT ("register_handler"))); return 1; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Listening at %s\n"), rendezvous)); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t) Spawning %d proactor threads\n"), num_threads)); ACE_Thread_Manager::instance ()->spawn_n (num_threads, proactor_loop); ACE_Thread_Manager::instance ()->spawn (start_clients); ACE_Time_Value loop_limit (20); ACE_Reactor::instance ()->run_reactor_event_loop (loop_limit); ACE_Thread_Manager::instance ()->wait (); // Check for num connections up/down. ACE_END_TEST; return 0; } #else int run_main (int, ACE_TCHAR *[]) { ACE_START_TEST (ACE_TEXT ("SSL_Asynch_Stream_Test")); ACE_ERROR ((LM_INFO, ACE_TEXT ("This test requires threads and AIO which are not ") ACE_TEXT ("supported on this platform\n"))); ACE_END_TEST; return 0; } #endif /* ACE_HAS_THREADS && (WIN32 || AIO) */
31.182777
118
0.568337
549654033
d54c7144b3f02c753bf5568d57057ac816de1945
20,030
cpp
C++
SteamPlugin/Common/SteamUser.cpp
adambiser/agk-steam-plugin
a2e203789085d1680b96451a3165604eb615b9d6
[ "MIT" ]
10
2017-11-02T05:42:30.000Z
2021-10-01T23:42:23.000Z
SteamPlugin/Common/SteamUser.cpp
adambiser/agk-steam-plugin
a2e203789085d1680b96451a3165604eb615b9d6
[ "MIT" ]
2
2018-12-13T03:00:21.000Z
2019-04-04T01:45:02.000Z
SteamPlugin/Common/SteamUser.cpp
adambiser/agk-steam-plugin
a2e203789085d1680b96451a3165604eb615b9d6
[ "MIT" ]
1
2021-11-02T18:37:25.000Z
2021-11-02T18:37:25.000Z
/* Copyright (c) 2019 Adam Biser <adambiser@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdafx.h" #include "SteamUser.h" CDurationControlCallback DurationControlCallback; /* @page ISteamUser */ //AdvertiseGame - game server stuff //BeginAuthSession - game server stuff /* @desc Checks if the current users looks like they are behind a NAT device. @return 1 if the current user is behind a NAT, otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsBehindNAT */ extern "C" DLL_EXPORT int IsBehindNAT() { CheckInitialized(false); return SteamUser()->BIsBehindNAT(); } /* @desc Checks whether the user's phone number is used to uniquely identify them. @return 1 f the current user's phone uniquely verifies their identity; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsPhoneIdentifying */ extern "C" DLL_EXPORT int IsPhoneIdentifying() { CheckInitialized(false); return SteamUser()->BIsPhoneIdentifying(); } /* @desc Checks whether the current user's phone number is awaiting (re)verification. @return 1 if the it is requiring verification; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsPhoneRequiringVerification */ extern "C" DLL_EXPORT int IsPhoneRequiringVerification() { CheckInitialized(false); return SteamUser()->BIsPhoneRequiringVerification(); } /* @desc Checks whether the current user has verified their phone number. @return 1 if the current user has phone verification enabled; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BIsTwoFactorEnabled */ extern "C" DLL_EXPORT int IsPhoneVerified() { CheckInitialized(false); return SteamUser()->BIsPhoneVerified(); } /* @desc Checks whether the current user has Steam Guard two factor authentication enabled on their account. @return 1 if the current user has two factor authentication enabled; otherwise, 0. @url https://partner.steamgames.com/doc/api/ISteamUser#IsPhoneVerified */ extern "C" DLL_EXPORT int IsTwoFactorEnabled() { CheckInitialized(false); return SteamUser()->BIsTwoFactorEnabled(); } /* @desc Checks to see whether the user is logged on to Steam. @return 1 when the user is logged on; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#BLoggedOn */ extern "C" DLL_EXPORT int LoggedOn() { CheckInitialized(false); return SteamUser()->BLoggedOn(); } //CancelAuthTicket - game server stuff //DecompressVoice - voice stuff //EndAuthSession - game server stuff //GetAuthSessionTicket - game server stuff //GetAvailableVoice - voice stuff class CGetDurationControlCallResult : public CCallResultItem<DurationControl_t> { public: CGetDurationControlCallResult() { m_CallResultName = "GetDurationControl()"; m_hSteamAPICall = SteamUser()->GetDurationControl(); } virtual ~CGetDurationControlCallResult() { } AppId_t GetAppID() { return m_Response.m_appid; } bool GetApplicable() { return m_Response.m_bApplicable; } int32 GetCSecsLast5h() { return m_Response.m_csecsLast5h; } int GetProgress() { return (int)m_Response.m_progress; } int GetNotification() { return (int)m_Response.m_notification; } protected: void OnResponse(DurationControl_t *pCallResult, bool bFailure) { CCallResultItem::OnResponse(pCallResult, bFailure); } }; /* @desc Retrieves anti indulgence / duration control for current user / game combination. @return A [call result handle](Callbacks-and-Call-Results#call-results) on success; otherwise 0. @callback-type callresult @callback-getters GetDurationControlAppID, GetDurationControlApplicable, GetDurationControlSecondsInLastFiveHours, GetDurationControlProgress, GetDurationControlNotification @url https://partner.steamgames.com/doc/api/ISteamUser#GetDurationControl */ extern "C" DLL_EXPORT int GetDurationControl() { CheckInitialized(0); DurationControlCallback.Register(); return CallResults()->Add(new CGetDurationControlCallResult()); } /* @desc Sent for games with enabled anti indulgence / duration control, for enabled users. Lets the game know whether persistent rewards or XP should be granted at normal rate, half rate, or zero rate. This callback is fired asynchronously in response to timers triggering. It is also fired in response to calls to GetDurationControl(). @callback-type list @callback-getters GetDurationControlResult, GetDurationControlAppID, GetDurationControlApplicable, GetDurationControlSecondsInLastFiveHours, GetDurationControlProgress, GetDurationControlNotification @return 1 when the callback has more responses to process; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int HasDurationControlResponse() { return DurationControlCallback.HasResponse(); } /* @desc Returns the result of the current DurationControl_t callback response. @return An EResult value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/steam_api#EResult */ extern "C" DLL_EXPORT int GetDurationControlResult() { return DurationControlCallback.GetCurrent().m_eResult; } /* @desc Returns the appid generating playtime of the current DurationControl_t callback response. @return An app ID. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int GetDurationControlAppID() { return DurationControlCallback.GetCurrent().m_appid; } /* @desc Returns the appid generating playtime for the given call result. @param hCallResult An GetDurationControl call result handle. @return An app ID. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @plugin-name GetDurationControlAppID */ extern "C" DLL_EXPORT int GetDurationControlCallResultAppID(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetAppID); } /* @desc Returns whether the duration control is applicable to user + game combination for the current DurationControl_t callback response. @return 1 when the duration control is applicable to user + game combination; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int GetDurationControlApplicable() { return DurationControlCallback.GetCurrent().m_bApplicable; } /* @desc Returns whether the duration control is applicable to user + game combination for the given call result. @param hCallResult An GetDurationControl call result handle. @return 1 when the duration control is applicable to user + game combination; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @plugin-name GetDurationControlApplicable */ extern "C" DLL_EXPORT int GetDurationControlCallResultApplicable(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetApplicable); } /* @desc Returns playtime in trailing 5 hour window plus current session, in seconds, for the current DurationControl_t callback response. @return An integer. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t */ extern "C" DLL_EXPORT int GetDurationControlSecondsInLastFiveHours() { return DurationControlCallback.GetCurrent().m_csecsLast5h; } /* @desc Returns playtime in trailing 5 hour window plus current session, in seconds, for the given call result. @param hCallResult An GetDurationControl call result handle. @return An integer. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @plugin-name GetDurationControlSecondsInLastFiveHours */ extern "C" DLL_EXPORT int GetDurationControlCallResultSecondsInLastFiveHours(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetCSecsLast5h); } /* @desc Returns the recommended progress for the current DurationControl_t callback response. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlProgress */ extern "C" DLL_EXPORT int GetDurationControlProgress() { return DurationControlCallback.GetCurrent().m_progress; } /* @desc Returns the recommended progress for the given call result. @param hCallResult An GetDurationControl call result handle. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlProgress @plugin-name GetDurationControlProgress */ extern "C" DLL_EXPORT int GetDurationControlCallResultProgress(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetProgress); } /* @desc Returns the notification to show, if any (always k_EDurationControlNotification_None for API calls), for the current DurationControl_t callback response. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlNotification */ extern "C" DLL_EXPORT int GetDurationControlNotification() { return DurationControlCallback.GetCurrent().m_notification; } /* @desc Returns the notification to show, if any (always k_EDurationControlNotification_None for API calls), for the given call result. @param hCallResult An GetDurationControl call result handle. @return An EDurationControlProgress value. @url https://partner.steamgames.com/doc/api/ISteamUser#DurationControl_t @url https://partner.steamgames.com/doc/api/ISteamUser#EDurationControlNotification @plugin-name GetDurationControlNotification */ extern "C" DLL_EXPORT int GetDurationControlCallResultNotification(int hCallResult) { return GetCallResultValue(hCallResult, &CGetDurationControlCallResult::GetNotification); } //GetEncryptedAppTicket - encrypted app ticket stuff /* @desc Gets the level of the users Steam badge for your game. The user can have two different badges for a series; the regular badge (max level 5) and the foil badge (max level 1). @param series If you only have one set of cards, the series will be 1. @param foil Check if they have received the foil badge. @return The user's badge level. @url https://partner.steamgames.com/doc/api/ISteamUser#GetGameBadgeLevel */ extern "C" DLL_EXPORT int GetGameBadgeLevel(int series, int foil) { CheckInitialized(0); return SteamUser()->GetGameBadgeLevel(series, foil != 0); } //GetHSteamUser - internal use template<> void ResponseWrapper<MarketEligibilityResponse_t>::SetResult() { m_eResult = k_EResultOK; } class CGetMarketEligibilityCallResult : public CCallResultItem<MarketEligibilityResponse_t, ResponseWrapper<MarketEligibilityResponse_t>> { public: CGetMarketEligibilityCallResult() { m_CallResultName = "GetMarketEligibility()"; m_hSteamAPICall = SteamUser()->GetMarketEligibility(); } virtual ~CGetMarketEligibilityCallResult() { } bool IsAllowed() { return m_Response.m_bAllowed; } int GetNotAllowedReason() { return (int)m_Response.m_eNotAllowedReason; } int GetAllowedAtTime() { return (int)m_Response.m_rtAllowedAtTime; } int GetSteamGuardRequiredDays() { return m_Response.m_cdaySteamGuardRequiredDays; } int GetNewDeviceCooldown() { return m_Response.m_cdayNewDeviceCooldown; } protected: void OnResponse(MarketEligibilityResponse_t *pCallResult, bool bFailure) { CCallResultItem::OnResponse(pCallResult, bFailure); } }; /* @desc Checks whether or not an account is allowed to use the market. @return A [call result handle](Callbacks-and-Call-Results#call-results) on success; otherwise 0. @callback-type callresult @callback-getters GetDurationControlAppID, GetDurationControlApplicable, GetDurationControlSecondsInLastFiveHours, GetDurationControlProgress, GetDurationControlNotification @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibility() { // Not in API docs, see https://partner.steamgames.com/doc/webapi/IEconMarketService#GetMarketEligibility CheckInitialized(0); return CallResults()->Add(new CGetMarketEligibilityCallResult()); } /* @desc Returns whether or not the user can use the market. @param hCallResult An GetMarketEligibility call result handle. @return 1 if the user can use the market; otherwise 0. @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityIsAllowed(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::IsAllowed); } /* @desc Returns the reasons a user may not use the Community Market. @param hCallResult An GetMarketEligibility call result handle. @return A EMarketNotAllowedReasonFlags value. @return-url https://partner.steamgames.com/doc/api/ISteamUser#EMarketNotAllowedReasonFlags @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityNotAllowedReason(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetNotAllowedReason); } /* @desc Returns when the user is allowed to use the market again. @param hCallResult An GetMarketEligibility call result handle. @return A Unix time. @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityAllowedAtTime(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetAllowedAtTime); } /* @desc Returns the number of days any user is required to have had Steam Guard before they can use the market @param hCallResult An GetMarketEligibility call result handle. @return An integer. @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilitySteamGuardRequiredDays(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetSteamGuardRequiredDays); } /* @desc Returns the number of days after initial device authorization a user must wait before using the market on that device @param hCallResult An GetMarketEligibility call result handle. @return An integer @url https://partner.steamgames.com/doc/api/ISteamUser#MarketEligibilityResponse_t */ extern "C" DLL_EXPORT int GetMarketEligibilityNewDeviceCooldown(int hCallResult) { return GetCallResultValue(hCallResult, &CGetMarketEligibilityCallResult::GetNewDeviceCooldown); } /* @desc Gets the Steam level of the user, as shown on their Steam community profile. @return The level of the current user. @url https://partner.steamgames.com/doc/api/ISteamUser#GetPlayerSteamLevel */ extern "C" DLL_EXPORT int GetPlayerSteamLevel() { CheckInitialized(0); return SteamUser()->GetPlayerSteamLevel(); } /* @desc Gets a handle to the Steam ID of the account currently logged into the Steam client. @return A SteamID handle @url https://partner.steamgames.com/doc/api/ISteamUser#GetSteamID */ extern "C" DLL_EXPORT int GetSteamID() { CheckInitialized(0); return SteamHandles()->GetPluginHandle(SteamUser()->GetSteamID()); } // Not in the API, but grouping this near GetSteamID(). /* @desc Checks to see if a Steam ID handle is valid. @param hSteamID The Steam ID handle to check. @return 1 when the Steam ID handle is valid; otherwise 0. */ extern "C" DLL_EXPORT int IsSteamIDValid(int hSteamID) { CheckInitialized(false); CSteamID steamID = SteamHandles()->GetSteamHandle(hSteamID); return steamID.IsValid(); } // Not in the API, but grouping this near GetSteamID(). /* @desc Gets the the account ID (profile number) for the given Steam ID handle. @param hSteamIDUser A user Steam ID handle. @return The account ID. */ extern "C" DLL_EXPORT int GetAccountID(int hSteamIDUser) { CheckInitialized(0); CSteamID steamID = SteamHandles()->GetSteamHandle(hSteamIDUser); if (steamID != k_steamIDNil) { return steamID.GetAccountID(); } return 0; } // Not in the API, but grouping this near GetSteamID(). /* @desc Gets the the SteamID3 for the given Steam ID handle. @param hSteamIDUser A user Steam ID handle. @return A string containing the SteamID3. @url https://developer.valvesoftware.com/wiki/SteamID#Types_of_Steam_Accounts */ extern "C" DLL_EXPORT char *GetSteamID3(int hSteamIDUser) { CheckInitialized(NULL_STRING); CSteamID steamID = SteamHandles()->GetSteamHandle(hSteamIDUser); if (steamID != k_steamIDNil) { std::string steam3("["); // Source: https://developer.valvesoftware.com/wiki/SteamID#Types_of_Steam_Accounts switch (steamID.GetEAccountType()) { case k_EAccountTypeInvalid: // I case k_EAccountTypeIndividual: // U case k_EAccountTypeMultiseat: // M case k_EAccountTypeGameServer: // G case k_EAccountTypeAnonGameServer: // A case k_EAccountTypePending: // P case k_EAccountTypeContentServer: // C case k_EAccountTypeClan: // g case k_EAccountTypeChat: // T / L / c case k_EAccountTypeAnonUser: // a steam3 += "IUMGAPCgT?a"[steamID.GetEAccountType()]; break; case k_EAccountTypeConsoleUser: // 9 = P2P, but this doesn't look right. Fake anyway, just do the default below. default: steam3 += std::to_string(steamID.GetEAccountType()); break; } steam3 += ":" + std::to_string(steamID.GetEUniverse()) + ":" + std::to_string(steamID.GetAccountID()); switch (steamID.GetEAccountType()) { case k_EAccountTypeAnonGameServer: case k_EAccountTypeAnonUser: steam3 += ":" + std::to_string(steamID.GetUnAccountInstance()); break; default: break; } steam3 += "]"; return utils::CreateString(steam3); } return NULL_STRING; } // Not in the API, but grouping this near GetSteamID(). /* @desc Gets the the SteamID64 (profile number) for the given Steam ID handle. @param hSteamIDUser A user Steam ID handle. @return A string containing the 64-bit SteamID64 in base 10. */ extern "C" DLL_EXPORT char *GetSteamID64(int hSteamIDUser) { CheckInitialized(NULL_STRING); char id64[21]; // Max value is 18,446,744,073,709,551,615 //_i64toa(SteamHandles()->GetSteamHandle(hSteamIDUser), id64, 10); // Windows and Linux snprintf(id64, 21, "%llu", SteamHandles()->GetSteamHandle(hSteamIDUser)); return utils::CreateString(id64); } // Not in the API, but grouping this near GetSteamID(). /* @desc Returns the handle for the given SteamID64 string. @param steamID64 A SteamID64 string. @return A Steam ID handle or 0. */ extern "C" DLL_EXPORT int GetHandleFromSteamID64(const char *steamID64) { CheckInitialized(0); //uint64 id = _atoi64(steamID64); uint64 id = atoll(steamID64); return SteamHandles()->GetPluginHandle(CSteamID(id)); } //GetUserDataFolder - Deprecated //GetVoice - voice stuff //GetVoiceOptimalSampleRate - voice stuff //InitiateGameConnection - old authentication, skip? //RequestEncryptedAppTicket - encrypted app ticket stuff //RequestStoreAuthURL - store stuff //StartVoiceRecording - voice stuff //StopVoiceRecording - voice stuff //TerminateGameConnection - old authentication, skip? //TrackAppUsageEvent - deprecated //UserHasLicenseForApp - game server stuff... validate DLC for auth session //Callbacks
37.092593
199
0.795756
adambiser
d54e82dd6e215f030261db2309d6dc11c530ec92
23,963
cpp
C++
src/ast/symboltable/SymbolTable.cpp
totorigolo/caramel
94c8a05c0a456be6b424d415cef19b7efdc3201b
[ "MIT" ]
null
null
null
src/ast/symboltable/SymbolTable.cpp
totorigolo/caramel
94c8a05c0a456be6b424d415cef19b7efdc3201b
[ "MIT" ]
null
null
null
src/ast/symboltable/SymbolTable.cpp
totorigolo/caramel
94c8a05c0a456be6b424d415cef19b7efdc3201b
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018 insa.4if.hexanome_kalate * * 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 "SymbolTable.h" #include "../../Logger.h" #include "../../utils/Common.h" #include "../context/Context.h" #include "../statements/definition/TypeDefinition.h" #include "../../exceptions/UndefinedSymbolError.h" #include "../../exceptions/SymbolAlreadyDefinedError.h" #include "../../exceptions/SymbolAlreadyDeclaredError.h" #include "../../exceptions/DeclarationMismatchException.h" #include "../../exceptions/FunctionCallArgumentsTypeMismatchException.h" #include "../../exceptions/FunctionDefinitionParameterNameMismatchError.h" #include "../../exceptions/FunctionDefinitionParameterTypeMismatchError.h" #include "../../exceptions/FunctionCallArgumentsNumberMismatchException.h" #include "../../exceptions/FunctionDefinitionNumberOfParametersMismatchError.h" #include "../../exceptions/FunctionNameAlreadyDeclaredError.h" namespace caramel::ast { using namespace utils; using namespace exceptions; SymbolTable::SymbolTable(SymbolTable::Ptr const &parentTable) : mParentTable(parentTable) {} VariableSymbol::Ptr SymbolTable::addVariableDeclaration( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, const Declaration::Ptr &declaration ) { logger.trace() << "SymbolTable::addVariableDeclaration(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), declaration ); } else if (isDeclared(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDeclaredError( name, symbol, antlrContext, symbol->getDeclaration(), declaration ); } else { VariableSymbol::Ptr variableSymbol = std::make_shared<VariableSymbol>(name, primaryType); mSymbolMap[name] = variableSymbol; variableSymbol->addDeclaration(declaration); return variableSymbol; } } VariableSymbol::Ptr SymbolTable::addVariableDefinition( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, const Definition::Ptr &definition ) { logger.trace() << "SymbolTable::addVariableDefinition(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), definition ); } else if (isDeclared(name)) { Symbol::Ptr recordedSymbol = getSymbol(antlrContext, name); if (recordedSymbol->getSymbolType() != SymbolType::VariableSymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::VariableSymbol, mSymbolMap[name] ); } if (!recordedSymbol->getType()->equals(primaryType)) { throw DeclarationMismatchException( antlrContext, name, primaryType, mSymbolMap[name] ); } recordedSymbol->addDefinition(definition); return std::dynamic_pointer_cast<VariableSymbol>(recordedSymbol); } else { VariableSymbol::Ptr variableSymbol = std::make_shared<VariableSymbol>(name, primaryType); mSymbolMap[name] = variableSymbol; variableSymbol->addDefinition(definition); return variableSymbol; } } Symbol::Ptr SymbolTable::addVariableUsage( antlr4::ParserRuleContext *antlrContext, std::string const &name, const Statement::Ptr &statement ) { logger.trace() << "SymbolTable::addVariableUsage(" << name << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::VariableSymbol && symbol->getSymbolType() != SymbolType::ArraySymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::VariableSymbol, mSymbolMap[name] ); } symbol->addUsage(statement); return symbol; } else { SymbolTable::Ptr parent = getParentTable(); if (parent) { return parent->addVariableUsage(antlrContext, name, statement); } else { throw UndefinedSymbolError( name, SymbolType::VariableSymbol, antlrContext ); } } } ArraySymbol::Ptr SymbolTable::addArrayDeclaration( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, bool sized, size_t size, const Declaration::Ptr &declaration ) { logger.trace() << "SymbolTable::addArrayDeclaration(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), declaration ); } else if (isDeclared(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDeclaredError( name, symbol, antlrContext, symbol->getDeclaration(), declaration ); } else { ArraySymbol::Ptr arraySymbol; if (sized) { arraySymbol = std::make_shared<ArraySymbol>(name, primaryType, size); } else { arraySymbol = std::make_shared<ArraySymbol>(name, primaryType); } mSymbolMap[name] = arraySymbol; arraySymbol->addDeclaration(declaration); return arraySymbol; } } ArraySymbol::Ptr SymbolTable::addArrayDefinition( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &primaryType, std::string const &name, std::vector<Expression::Ptr> &&content, const Definition::Ptr &definition ) { logger.trace() << "SymbolTable::addArrayDefinition(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), definition ); } else if (isDeclared(name)) { Symbol::Ptr recordedSymbol = getSymbol(antlrContext, name); if (recordedSymbol->getSymbolType() != SymbolType::ArraySymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::ArraySymbol, mSymbolMap[name] ); } if (!recordedSymbol->getType()->equals(primaryType)) { throw DeclarationMismatchException( antlrContext, name, primaryType, mSymbolMap[name] ); } recordedSymbol->addDefinition(definition); return castTo<ArraySymbol::Ptr>(recordedSymbol); } else { ArraySymbol::Ptr arraySymbol = std::make_shared<ArraySymbol>(name, primaryType, std::move(content)); mSymbolMap[name] = arraySymbol; arraySymbol->addDefinition(definition); return arraySymbol; } } ArraySymbol::Ptr SymbolTable::addArrayAccess( antlr4::ParserRuleContext *antlrContext, std::string const &name, const Statement::Ptr &statement ) { logger.trace() << "SymbolTable::addArrayAccess(" << name << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::ArraySymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::ArraySymbol, mSymbolMap[name] ); } auto const &arraySymbol = castTo<ArraySymbol::Ptr>(symbol); arraySymbol->addUsage(statement); return arraySymbol; } else { SymbolTable::Ptr parent = getParentTable(); if (parent) { return parent->addArrayAccess(antlrContext, name, statement); } else { throw UndefinedSymbolError( name, SymbolType::ArraySymbol, antlrContext ); } } } FunctionSymbol::Ptr SymbolTable::addFunctionDeclaration( antlr4::ParserRuleContext *antlrContext, PrimaryType::Ptr const &returnType, std::string const &name, std::vector<FunctionParameterSignature> parameters, const Declaration::Ptr &declaration, bool variadic ) { logger.trace() << "SymbolTable::addFunctionDeclaration(" << name << ", " << returnType->getIdentifier() << ")"; if (isDeclared(name)) { // or defined // TODO: Duplicated code in addFunctionDefinition() -> move to a helper function auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::FunctionSymbol) { throw FunctionNameAlreadyDeclaredError( antlrContext, name, symbol ); } FunctionSymbol::Ptr const &functionSymbol = castTo<FunctionSymbol::Ptr>(symbol); auto declaredParameters = functionSymbol->getParameters(); if (declaredParameters.size() == parameters.size()) { for (size_t i = 0; i < declaredParameters.size(); i++) { std::string const declaredParameterName = declaredParameters[i].name; std::string const declaredParameterTypeIdentifier = declaredParameters[i].primaryType->getIdentifier(); std::string const parameterName = parameters[i].name; std::string const parameterTypeIdentifier = parameters[i].primaryType->getIdentifier(); if (declaredParameterName != parameterName) { throw FunctionDefinitionParameterNameMismatchError( name, antlrContext, declaredParameterName, parameterName ); } if (declaredParameterTypeIdentifier != parameterTypeIdentifier) { throw FunctionDefinitionParameterTypeMismatchError( antlrContext, name, declaredParameters[i].primaryType, parameters[i].primaryType ); } } } else { throw FunctionDefinitionNumberOfParametersMismatchError( name, antlrContext, declaredParameters.size(), parameters.size() ); } functionSymbol->addDeclaration(declaration); return functionSymbol; } else { FunctionSymbol::Ptr functionSymbol = std::make_shared<FunctionSymbol>(name, returnType, variadic); mSymbolMap[name] = functionSymbol; functionSymbol->setParameters(std::move(parameters)); functionSymbol->addDeclaration(declaration); return functionSymbol; } } FunctionSymbol::Ptr SymbolTable::addFunctionDefinition( antlr4::ParserRuleContext *antlrContext, Context::Ptr functionContext, PrimaryType::Ptr const &returnType, std::string const &name, std::vector<Symbol::Ptr> parameters, const Definition::Ptr &definition, bool variadic ) { logger.trace() << "SymbolTable::addFunctionDefinition(" << name << ", " << returnType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); throw SymbolAlreadyDefinedError( name, symbol, antlrContext, symbol->getDefinition(), definition ); } else if (isDeclared(name)) { auto const &symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::FunctionSymbol) { throw FunctionNameAlreadyDeclaredError( antlrContext, name, symbol ); } FunctionSymbol::Ptr const &functionSymbol = castTo<FunctionSymbol::Ptr>(symbol); if (functionSymbol->getContext()) { logger.fatal() << "The function is only declared, but the function context isn't null:\n" << " - existing declaration: " << *functionSymbol->getContext() << '\n' << " - current definition: " << *functionContext; exit(1); } auto declaredParameters = functionSymbol->getParameters(); if (declaredParameters.size() == parameters.size()) { for (size_t i = 0; i < declaredParameters.size(); i++) { std::string const declaredParameterName = declaredParameters[i].name; std::string const declaredParameterTypeIdentifier = declaredParameters[i].primaryType->getIdentifier(); std::string const parameterName = parameters[i]->getName(); std::string const parameterTypeIdentifier = parameters[i]->getType()->getIdentifier(); if (declaredParameterName != parameterName) { throw FunctionDefinitionParameterNameMismatchError( name, antlrContext, declaredParameterName, parameterName ); } if (declaredParameterTypeIdentifier != parameterTypeIdentifier) { throw FunctionDefinitionParameterTypeMismatchError( antlrContext, name, declaredParameters[i].primaryType, parameters[i]->getType() ); } } } else { throw FunctionDefinitionNumberOfParametersMismatchError( name, antlrContext, declaredParameters.size(), parameters.size() ); } functionSymbol->setContext(functionContext); functionSymbol->addDefinition(definition); return functionSymbol; } else { FunctionSymbol::Ptr functionSymbol = std::make_shared<FunctionSymbol>(name, returnType, variadic); mSymbolMap[name] = functionSymbol; functionSymbol->setContext(functionContext); functionSymbol->setParameters(std::move(parameters)); functionSymbol->addDefinition(definition); return functionSymbol; } } Symbol::Ptr SymbolTable::addFunctionParameter( antlr4::ParserRuleContext *antlrContext, std::string const &name, PrimaryType::Ptr const &primaryType, SymbolType parameterType ) { logger.trace() << "SymbolTable::addFunctionParameter(" << name << ", " << primaryType->getIdentifier() << ")"; if (isDefined(name)) { auto const &symbol = getSymbol(antlrContext, name); // TODO: A proper error throw std::runtime_error("Two different parameters can't have the same name."); } else { // If it's defined, we just shadow it if (parameterType == SymbolType::ArraySymbol) { ArraySymbol::Ptr arraySymbol = std::make_shared<ArraySymbol>(name, primaryType); mSymbolMap[name] = arraySymbol; return castTo<Symbol::Ptr>(arraySymbol); } else if (parameterType == SymbolType::VariableSymbol) { VariableSymbol::Ptr variableSymbol = std::make_shared<VariableSymbol>(name, primaryType); mSymbolMap[name] = variableSymbol; return castTo<Symbol::Ptr>(variableSymbol); } else { throw std::runtime_error("This can't be. And it is. Have a cookie!"); } } } FunctionSymbol::Ptr SymbolTable::addFunctionCall( antlr4::ParserRuleContext *antlrContext, std::string const &name, const FunctionCall::Ptr &functionCall ) { logger.trace() << "SymbolTable::addFunctionCall(" << name << ")"; if (isDeclared(name)) { Symbol::Ptr symbol = getSymbol(antlrContext, name); if (symbol->getSymbolType() != SymbolType::FunctionSymbol) { throw DeclarationMismatchException( antlrContext, name, SymbolType::FunctionSymbol, mSymbolMap[name] ); } auto functionSymbol = castTo<FunctionSymbol::Ptr>(symbol); // Check if the arguments match with the function parameters types, if it's not a variadic function if (!functionSymbol->isVariadic()) { std::vector<PrimaryType::Ptr> const &argumentsTypes = functionCall->getArgumentsPrimaryTypes(); auto const &parameters = functionSymbol->getParameters(); if (argumentsTypes.size() != parameters.size()) { throw FunctionCallArgumentsNumberMismatchException( "The function " + name + " takes " + std::to_string(parameters.size()) + " arguments, " + "but " + std::to_string(argumentsTypes.size()) + " were given." ); } for (size_t i = 0; i < argumentsTypes.size(); ++i) { if (!parameters[i].primaryType->greaterThan(argumentsTypes[i])) { std::stringstream errorMessage; errorMessage << "The function " << name << " " << (i+1) << "-th parameter is of type " << parameters[i].primaryType->getIdentifier() << ", but got a " << argumentsTypes[i]->getIdentifier() << "."; throw FunctionCallArgumentsTypeMismatchException(errorMessage.str()); } } } functionSymbol->addUsage(functionCall); return functionSymbol; } else { throw UndefinedSymbolError( name, SymbolType::FunctionSymbol, antlrContext ); } } void SymbolTable::addPrimaryType( PrimaryType::Ptr const &primaryType, std::string const &name ) { logger.trace() << "SymbolTable::addPrimaryType(" << name << ", " << primaryType->getIdentifier() << ")"; // Not declared and not defined if (isNotDeclared(name) && isNotDefined(name)) { mSymbolMap[name] = std::make_shared<TypeSymbol>(name, primaryType); mSymbolMap.at(name)->addDeclaration(nullptr); mSymbolMap.at(name)->addDefinition(nullptr); } else { logger.fatal() << "Can't add " << name << " as a primary type, because a symbol named " << name << " already exists."; exit(1); } } TypeSymbol::Ptr SymbolTable::addType( antlr4::ParserRuleContext *antlrContext, TypeDefinition::Ptr definition ) { auto definitionSymbol = definition->getSymbol().lock(); logger.trace() << "SymbolTable::addType(" << definitionSymbol->getName() << ", " << definitionSymbol->getType()->getIdentifier() << ")"; std::string typeAlias = definitionSymbol->getName(); PrimaryType::Ptr primaryType = definitionSymbol->getType(); // Not declared and not defined if (isNotDeclared(typeAlias)) { TypeSymbol::Ptr typeSymbol = std::make_shared<TypeSymbol>(typeAlias, primaryType); mSymbolMap[typeAlias] = typeSymbol; typeSymbol->addDefinition(definition); return typeSymbol; } else { throw caramel::exceptions::SymbolAlreadyDeclaredError( "Cannot execute typedef", mSymbolMap[typeAlias], antlrContext, mSymbolMap[typeAlias]->getDeclaration(), std::dynamic_pointer_cast<Declaration>(definition)); } } bool SymbolTable::hasSymbol(std::string const &name) { return thisHasSymbol(name) || parentHasSymbol(name); } bool SymbolTable::thisHasSymbol(std::string const &name) { return mSymbolMap.find(name) != mSymbolMap.end(); } bool SymbolTable::parentHasSymbol(std::string const &name) { return getParentTable() && getParentTable()->hasSymbol(name); } Symbol::Ptr SymbolTable::getSymbol(antlr4::ParserRuleContext *antlrContext, std::string const &name) { logger.trace() << "SymbolTable::getSymbol(): " << grey << name; if (thisHasSymbol(name)) { return mSymbolMap.at(name); } else { SymbolTable::Ptr parent = getParentTable(); if (parent) { return parent->getSymbol(antlrContext, name); } else { throw UndefinedSymbolError(name, antlrContext); } } } SymbolTable::Ptr SymbolTable::getParentTable() { return mParentTable; } size_t SymbolTable::getNumberOfSymbols() const { return mSymbolMap.size(); } std::map<std::string, Symbol::Ptr> const &SymbolTable::getSymbols() const { return mSymbolMap; } void SymbolTable::acceptAstDotVisit() { addNode(thisId(), "SymbolTable: " + std::to_string(mSymbolMap.size()) + " symbols", "cylinder", "darkorange"); visitChildrenAstDot(); } void SymbolTable::visitChildrenAstDot() { for (auto const &symbol : mSymbolMap) { addEdge(thisId(), symbol.second->thisId(), symbol.first); symbol.second->acceptAstDotVisit(); } } bool SymbolTable::isDeclared(const std::string &name) { return (thisHasSymbol(name) && mSymbolMap.at(name)->isDeclared()) || (getParentTable() && getParentTable()->isDeclared(name)); } bool SymbolTable::isDefined(const std::string &name) { return (thisHasSymbol(name) && mSymbolMap.at(name)->isDefined()) || (getParentTable() && getParentTable()->isDefined(name)); } } // namespace caramel::ast
38.096979
116
0.590994
totorigolo
d54ed2bd0cc8105b0a7363378b193d40fdc25943
3,021
hpp
C++
master/core/third/RCF/include/RCF/util/ReadWriteProtect.hpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/third/RCF/include/RCF/util/ReadWriteProtect.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/third/RCF/include/RCF/util/ReadWriteProtect.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
//***************************************************************************** // Copyright (c) 2003. All rights reserved. // Developed by Jarl Lindrud. // Contact: jlindrud@hotmail.com . //***************************************************************************** #ifndef _UTIL_READWRITEPROTECT_HPP_ #define _UTIL_READWRITEPROTECT_HPP_ #include "ThreadLibrary.hpp" namespace util { // Utility for applying the readers/writer synchronization pattern. // Currently no bias for writers over readers. // To give multiple read access and single write access to a class X: // //class X { // void read() // { // ReadLock lock(rwp); // // ... // } // void write() // { // WriteLock lock(rwp); // // ... // } // ReadWriteProtect rwp; //} class ReadWriteProtect { public: typedef Platform::Threads::recursive_mutex Mutex; typedef Platform::Threads::condition Event; ReadWriteProtect() : readerCount(0) {} Mutex &getReadMutex() { return readMutex; } Mutex &getWriteMutex() { return writeMutex; } int &getReaderCount() { return readerCount; } void waitOnReadUnlock() { Mutex::scoped_lock lock( readUnlockMutex ); readUnlockEvent.wait(lock); } void notifyReadUnlock() { readUnlockEvent.notify_all(); } private: Mutex readMutex; Mutex writeMutex; Mutex readUnlockMutex; Event readUnlockEvent; int readerCount; }; class ReadLock { public: ReadLock( ReadWriteProtect &rwp ) : rwp( rwp ) { ReadWriteProtect::Mutex::scoped_lock lock( rwp.getReadMutex() ); rwp.getReaderCount()++; } ~ReadLock() { { ReadWriteProtect::Mutex::scoped_lock lock( rwp.getReadMutex() ); rwp.getReaderCount()--; } rwp.notifyReadUnlock(); } private: ReadWriteProtect &rwp; }; class WriteLock { public: WriteLock( ReadWriteProtect &rwp ) : rwp( rwp ), read_lock( rwp.getWriteMutex(), false ), write_lock( rwp.getWriteMutex(), false ) { read_lock.lock(); while (rwp.getReaderCount() > 0) { read_lock.unlock(); rwp.waitOnReadUnlock(); read_lock.lock(); } write_lock.lock(); } ~WriteLock() { write_lock.unlock(); read_lock.unlock(); } private: ReadWriteProtect &rwp; ReadWriteProtect::Mutex::scoped_lock read_RCF_UNUSED_VARIABLE(lock); ReadWriteProtect::Mutex::scoped_lock write_RCF_UNUSED_VARIABLE(lock); }; } // namespace util #endif // ! _UTIL_READWRITEPROTECT_HPP_
27.216216
108
0.506124
importlib
d54f736eac8ecb28f37d4e51826ad635056c4ea5
425
cc
C++
ssl/server.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
2
2021-01-18T02:36:55.000Z
2022-01-17T06:38:46.000Z
ssl/server.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
null
null
null
ssl/server.cc
ririripley/recipes
04267c68a7424326b4aa8dd14b1a879b59ab887c
[ "BSD-3-Clause" ]
1
2020-11-05T15:27:05.000Z
2020-11-05T15:27:05.000Z
#include "InetAddress.h" #include "TlsAcceptor.h" #include "TlsConfig.h" #include "TlsStream.h" int main(int argc, char* argv[]) { TlsConfig config; // config.setCaFile("ca.pem"); config.setCertFile("server.pem"); config.setKeyFile("server.pem"); InetAddress listenAddr(4433); TlsAcceptor acceptor(&config, listenAddr); TlsStreamPtr stream = acceptor.accept(); if (stream) { LOG_INFO << "OK"; } }
18.478261
44
0.682353
ririripley
d54f794032c0ebf8cba0066e0f27bfec5c6166dc
172
hpp
C++
src/common.hpp
Southclaws/samp-bitmapper
17807d2bd2955eb7747c989ecd7c10dc43231821
[ "MIT" ]
7
2017-12-31T13:16:57.000Z
2020-12-28T12:56:15.000Z
src/common.hpp
Southclaws/samp-bitmapper
17807d2bd2955eb7747c989ecd7c10dc43231821
[ "MIT" ]
2
2017-12-31T11:55:22.000Z
2017-12-31T16:57:00.000Z
src/common.hpp
Southclaws/samp-bitmapper
17807d2bd2955eb7747c989ecd7c10dc43231821
[ "MIT" ]
2
2018-07-07T12:34:04.000Z
2020-11-01T21:58:02.000Z
#pragma warning(default:4005) extern void** ppPluginData; extern void* pAMXFunctions; typedef void (*logprintf_t)(const char* szFormat, ...); extern logprintf_t logprintf;
28.666667
55
0.77907
Southclaws
d551d758a425519a51ad37c0e06a590208172fa9
1,227
hpp
C++
src/data/include/class_data_vec.hpp
sjvs/FastSim
7a17b61c5463112e40b12f1842d03a73c342ef55
[ "Apache-2.0" ]
null
null
null
src/data/include/class_data_vec.hpp
sjvs/FastSim
7a17b61c5463112e40b12f1842d03a73c342ef55
[ "Apache-2.0" ]
22
2017-06-27T07:34:02.000Z
2018-09-17T07:36:21.000Z
src/data/include/class_data_vec.hpp
sjvs/FastSim
7a17b61c5463112e40b12f1842d03a73c342ef55
[ "Apache-2.0" ]
2
2018-11-20T13:15:11.000Z
2019-07-03T12:48:40.000Z
/** * @brief define container Data_Vec * * @file class_data_vec.hpp * @author Michal Vrastil * @date 2018-07-11 */ #pragma once #include "stdafx.h" #include <array> /** * @class: Data_Vec * @brief: class containing data [x, y,...] */ template <typename T, size_t N> class Data_Vec { public: // CONSTRUCTORS Data_Vec() = default; Data_Vec(size_t size) { data.fill(std::vector<T>(size)); } // VARIABLES std::array<std::vector<T>, N> data; // ELEMENT ACCESS std::vector<T>& operator[](size_t i){ return data[i]; } const std::vector<T>& operator[](size_t i) const { return data[i]; } // CAPACITY size_t dim() const noexcept{ return data.size(); } size_t size() const noexcept{ return data[0].size(); } void resize (size_t n){ for (auto &vec : data) vec.resize(n); } void resize (size_t n, T val){ for (auto &vec : data) vec.resize(n, val); } void reserve(size_t n){ for (auto &vec : data) vec.reserve(n); } void erase(size_t index){ for (auto &vec : data) vec.erase(vec.begin() + index); } // MODIFIERS void fill(T val){ for (auto &vec : data) std::fill(vec.begin(), vec.end(), val); } };
24.058824
72
0.586797
sjvs
d5525677ee9f048d3c6f48de9f70c9f385e038f7
4,529
cc
C++
flecsi/execution/legion/runtime_main.cc
scothalverson/flecsi
a7b2c289b99ecadd0c75cabc491f5c66e543345c
[ "Unlicense" ]
null
null
null
flecsi/execution/legion/runtime_main.cc
scothalverson/flecsi
a7b2c289b99ecadd0c75cabc491f5c66e543345c
[ "Unlicense" ]
null
null
null
flecsi/execution/legion/runtime_main.cc
scothalverson/flecsi
a7b2c289b99ecadd0c75cabc491f5c66e543345c
[ "Unlicense" ]
null
null
null
/* @@@@@@@@ @@ @@@@@@ @@@@@@@@ @@ /@@///// /@@ @@////@@ @@////// /@@ /@@ /@@ @@@@@ @@ // /@@ /@@ /@@@@@@@ /@@ @@///@@/@@ /@@@@@@@@@/@@ /@@//// /@@/@@@@@@@/@@ ////////@@/@@ /@@ /@@/@@//// //@@ @@ /@@/@@ /@@ @@@//@@@@@@ //@@@@@@ @@@@@@@@ /@@ // /// ////// ////// //////// // Copyright (c) 2016, Los Alamos National Security, LLC All rights reserved. */ /*! @file */ #include <flecsi-config.h> #if !defined(FLECSI_ENABLE_MPI) #error FLECSI_ENABLE_MPI not defined! This file depends on MPI! #endif #include <mpi.h> #include <flecsi/execution/context.h> // Boost command-line options #if defined(FLECSI_ENABLE_BOOST) #include <boost/program_options.hpp> using namespace boost::program_options; #endif #if defined(ENABLE_CALIPER) #include <caliper/cali-mpi.h> #include <caliper/cali.h> #endif //----------------------------------------------------------------------------// //! FleCSI runtime main function. //----------------------------------------------------------------------------// int main(int argc, char ** argv) { #if defined(FLECSI_ENABLE_MPI) // Get the MPI version int version, subversion; MPI_Get_version(&version, &subversion); #if defined(GASNET_CONDUIT_MPI) if(version == 3 && subversion > 0) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); // If you fail this assertion, then your version of MPI // does not support calls from multiple threads and you // cannot use the GASNet MPI conduit if(provided < MPI_THREAD_MULTIPLE) printf("ERROR: Your implementation of MPI does not support " "MPI_THREAD_MULTIPLE which is required for use of the " "GASNet MPI conduit with the Legion-MPI Interop!\n"); assert(provided == MPI_THREAD_MULTIPLE); } else { // Initialize the MPI runtime int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); if(provided < MPI_THREAD_MULTIPLE) printf("ERROR: Your implementation of MPI does not support " "MPI_THREAD_MULTIPLE which is required for use of the " "GASNet MPI conduit with the Legion-MPI Interop!\n"); assert(provided == MPI_THREAD_MULTIPLE); } // if #else int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); if(provided < MPI_THREAD_MULTIPLE) printf("ERROR: Your implementation of MPI does not support " "MPI_THREAD_MULTIPLE which is required for use of the " "GASNet MPI conduit with the Legion-MPI Interop!\n"); assert(provided == MPI_THREAD_MULTIPLE); #endif //#if defined(ENABLE_CALIPER) // cali_mpi_init(); //#endif // get the rank int rank{0}; MPI_Comm_rank(MPI_COMM_WORLD, &rank); #endif // FLECSI_ENABLE_MPI //--------------------------------------------------------------------------// // INIT CLOG //--------------------------------------------------------------------------// // Initialize tags to output all tag groups from CLOG std::string tags("all"); #if defined(FLECSI_ENABLE_BOOST) options_description desc("Cinch test options"); // Add command-line options desc.add_options()("help,h", "Print this message and exit.")("tags,t", value(&tags)->implicit_value("0"), "Enable the specified output tags, e.g., --tags=tag1,tag2." " Passing --tags by itself will print the available tags."); variables_map vm; parsed_options parsed = command_line_parser(argc, argv).options(desc).allow_unregistered().run(); store(parsed, vm); notify(vm); if(vm.count("help")) { if(rank == 0) { std::cout << desc << std::endl; } // if MPI_Finalize(); return 1; } // if #endif // FLECSI_ENABLE_BOOST int result{0}; if(tags == "0") { // Output the available tags if(rank == 0) { std::cout << "Available tags (CLOG):" << std::endl; for(auto t : clog_tag_map()) { std::cout << " " << t.first << std::endl; } // for } // if } else { // Initialize the cinchlog runtime clog_init(tags); // Execute the flecsi runtime. result = flecsi::execution::context_t::instance().initialize(argc, argv); } // if #if defined(FLECSI_ENABLE_MPI) // Shutdown the MPI runtime #ifndef GASNET_CONDUIT_MPI MPI_Finalize(); #endif #endif // FLECSI_ENABLE_MPI return result; } // main
28.664557
80
0.552661
scothalverson
d552c8da99adc3de9432770ef376b2bdc7450433
1,623
cc
C++
source/blender/depsgraph/intern/eval/deg_eval_runtime_backup_movieclip.cc
rbabari/blender
6daa85f14b2974abfc3d0f654c5547f487bb3b74
[ "Naumen", "Condor-1.1", "MS-PL" ]
39
2020-05-26T15:21:14.000Z
2022-03-24T04:46:31.000Z
source/blender/depsgraph/intern/eval/deg_eval_runtime_backup_movieclip.cc
rbabari/blender
6daa85f14b2974abfc3d0f654c5547f487bb3b74
[ "Naumen", "Condor-1.1", "MS-PL" ]
7
2020-05-11T14:04:54.000Z
2020-06-03T15:00:20.000Z
source/blender/depsgraph/intern/eval/deg_eval_runtime_backup_movieclip.cc
rbabari/blender
6daa85f14b2974abfc3d0f654c5547f487bb3b74
[ "Naumen", "Condor-1.1", "MS-PL" ]
4
2020-04-25T14:38:01.000Z
2021-03-03T08:48:58.000Z
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2019 Blender Foundation. * All rights reserved. */ /** \file * \ingroup depsgraph */ #include "intern/eval/deg_eval_runtime_backup_movieclip.h" #include "DNA_movieclip_types.h" #include "BLI_utildefines.h" namespace DEG { MovieClipBackup::MovieClipBackup(const Depsgraph * /*depsgraph*/) { reset(); } void MovieClipBackup::reset() { anim = nullptr; cache = nullptr; } void MovieClipBackup::init_from_movieclip(MovieClip *movieclip) { anim = movieclip->anim; cache = movieclip->cache; /* Clear pointers stored in the movie clip, so they are not freed when copied-on-written * datablock is freed for re-allocation. */ movieclip->anim = nullptr; movieclip->cache = nullptr; } void MovieClipBackup::restore_to_movieclip(MovieClip *movieclip) { movieclip->anim = anim; movieclip->cache = cache; reset(); } } // namespace DEG
26.177419
90
0.732594
rbabari
d553b3cb02174050a0817248f4f8537bc79ca289
1,284
cpp
C++
sstd/src/matrixContainer_binary/InitByComma.cpp
admiswalker/SubStandardLibrary-SSTD-
d0e7c754f4437fc57e8c4ab56fbbf2aa871b00ff
[ "MIT" ]
null
null
null
sstd/src/matrixContainer_binary/InitByComma.cpp
admiswalker/SubStandardLibrary-SSTD-
d0e7c754f4437fc57e8c4ab56fbbf2aa871b00ff
[ "MIT" ]
null
null
null
sstd/src/matrixContainer_binary/InitByComma.cpp
admiswalker/SubStandardLibrary-SSTD-
d0e7c754f4437fc57e8c4ab56fbbf2aa871b00ff
[ "MIT" ]
null
null
null
#include "bmat.hpp" #include "SwapByTwoIndex.hpp" /* bool SwapByTwoIndex::getVal(class sstd::bmat& bMat, uint& p, uint& q){ // Mat 座標 <- bMat 座標 uint p_Div8 = p / 8; uint q_Div8 = q / 8; // bMat8x8 座標 <- bMat 座標 uint p_Mod8 = p - p_Div8 * 8; // p % 8; uint q_Mod8 = q - q_Div8 * 8; // q % 8; UINT64 mask = 0x8000000000000000; mask = mask>>(8*p_Mod8+q_Mod8); return ((bMat.bMat8x8(p_Div8, q_Div8)&mask) != (UINT64)0); } void SwapByTwoIndex::setVal(class sstd::bmat& bMat, uint& p, uint& q, bool val){ // Mat 座標 <- bMat 座標 uint p_Div8 = p / 8; uint q_Div8 = q / 8; // bMat8x8 座標 <- bMat 座標 uint p_Mod8 = p - p_Div8 * 8; // p % 8; uint q_Mod8 = q - q_Div8 * 8; // q % 8; UINT64 mask = 0x8000000000000000; mask = mask>>(8*p_Mod8+q_Mod8); if(val){ // val != 0, true bMat.bMat8x8(p_Div8, q_Div8) |= mask; }else{ // val == 0, false mask=~mask; bMat.bMat8x8(p_Div8, q_Div8) &= mask; } } class SwapByTwoIndex OpSwapByTwoIndex(sstd::bmat* pthis, uint p, uint q){ class SwapByTwoIndex SBTI; SBTI.pBMxs = pthis; SBTI.SwapRowNum = p; SBTI.SwapColNum = q; return SBTI; }; */
22.928571
81
0.535826
admiswalker
d553f7526b1e3b55b887e22c97422f60792033fb
7,117
hpp
C++
structures/linkedlist.hpp
Dannnno/DataStructures
898e16acc4d05e7c387972f1aef252b298fc4f81
[ "MIT" ]
null
null
null
structures/linkedlist.hpp
Dannnno/DataStructures
898e16acc4d05e7c387972f1aef252b298fc4f81
[ "MIT" ]
null
null
null
structures/linkedlist.hpp
Dannnno/DataStructures
898e16acc4d05e7c387972f1aef252b298fc4f81
[ "MIT" ]
null
null
null
/** * \file linkedlist.hpp * \author Dan Obermiller * \brief Implementation of a singly-linked list. */ #ifndef LINKEDLIST_HPP #define LINKEDLIST_HPP 1 #include <cstddef> #include <iterator> #include "list.hpp" #include "../exceptions.hpp" /** * \brief A paramaterized singly-linked list */ template <typename T> class LinkedList : public List<T> { private: /** * \brief Iterator for a linkedlist. */ class Iterator; /** * \brief Constant iterator for a linkedlist. */ class ConstIterator; /** * \brief Node of a linkedlist */ struct ListNode; public: /** * \brief A default constructor for a linked list. */ LinkedList(); /** * \brief A constructor from an array. */ LinkedList(T* arr, std::size_t length); /** * \brief Copy constructor. */ LinkedList(const LinkedList<T>& orig); /** * \brief Move constructor. */ LinkedList(LinkedList<T>&& other); /** * \brief Assignment to a list; */ LinkedList<T>& operator=(LinkedList<T> rhs); /** * \brief The destructor for a linked list. */ ~LinkedList(); /** * \brief Non-member function version of swap. */ template <class P> friend void swap(LinkedList<P>& lhs, LinkedList<P>& rhs); /** * \brief The head (first item) of the list. */ T& getHead(); /** * \brief Constant version of getHead() */ const T& getHead() const; /** * \brief The tail (last item) of the list. */ T& getTail(); /** * \brief Constant version of getTail() */ const T& getTail() const; /** * \brief Returns the size of the list */ std::size_t size() const; /** * \brief Returns whether or not the list is empty. */ bool isEmpty() const; /** * \brief Adds a node to the end of the list. * \post All nodes have the appropriate "next_" and the list has * the appropriate size. */ void append(T value); /** * \brief Removes the first item in the list. */ void remove(); /** * \brief Removes the nth item in the list. */ void remove(std::size_t n); /** * \brief Removes and returns a copy of the value of the first item * in the list. */ T pop(); /** * \brief Removes and returns a copy of the value of the nth item * in the list. */ T pop(std::size_t n); /** * \brief inserts an item at the indicated index. */ void insert(std::size_t index, T value); /** * \brief Determines the index of an element. */ std::size_t index_of(T const& value) const; /** * \brief Determines whether or not the value is present. */ bool contains(T const& value) const; /** * \brief Overloads the addition operator. * \details Adds two lists together and returns the result. */ template <typename P> friend LinkedList<P> operator+(LinkedList<P> lhs, LinkedList<P> rhs); /** * \brief Overloads the multiplication operator. * \details Allows us to make the list repeat n times. */ template <typename P> friend LinkedList<P> operator*(LinkedList<P> lhs, std::size_t n); /** * \brief Overloads the mutable subscript operator. */ T& operator[](std::size_t index); /** * \brief Overloads the immutable subscript operator. */ const T& operator[](std::size_t index) const; /** * \brief Overloads the equivalence operator. */ bool operator==(const LinkedList<T>& rhs) const; /** * \brief Overloads the inequivalence operator. */ bool operator!=(const LinkedList<T>& rhs) const; /** * \brief Returns an array of the values within the list. * \details This is a dynamically allocated array and needs to be * explicitly deleted. */ T* asArray() const; /** * \brief Overloads the << operator. */ template <class P> friend std::ostream& operator<<( std::ostream& str, const LinkedList<P>& list); typedef Iterator iterator; typedef ConstIterator const_iterator; /** * \brief Returns the start of the ListIterator. */ iterator begin(); /** * \brief Returns the end of the ListIterator. */ iterator end(); /** * \brief Returns a costant version of the ListIterator (from the start) */ const_iterator begin() const; /** * \brief Returns a constant version of the ListIterator (at the end). */ const_iterator end() const; /** * \brief Sorts the current list. */ void sort(); /** * \brief Returns a copy of the list in sorted order. * \post The original list is unchanged. */ LinkedList<T> sorted() const; /** * \brief Reverses the order of the list. */ void reverse(); /** * \brief Returns a copy of the list, reversed. * \post The original list is unchanged. */ LinkedList<T> reversed() const; /** * \brief Returns an array of the items in the list. */ T* toArray() const; private: class Iterator : public std::iterator<std::forward_iterator_tag, T> { public: /** * \brief Prefix increment operator overloading. */ Iterator& operator++(); /** * \brief Postfix increment operator overloading. */ Iterator operator++(int) const; /** * \brief Dereferencing operator overloading. */ const T& operator*() const; /** * \brief Member access operator overriding. */ const T* operator->() const; /** * \brief Equality operator overriding. */ bool operator==(const Iterator& rhs) const; /** * \brief Inequality operator overriding. */ bool operator!=(const Iterator& rhs) const; private: friend class LinkedList; /** * \brief The default constructor. */ Iterator() = delete; /** * \brief All iterators should have a current node. */ Iterator(ListNode* node) : current_{node} { } ListNode* current_; }; class ConstIterator : public std::iterator<std::forward_iterator_tag, T> { public: /** * \brief Prefix increment operator overloading. */ ConstIterator& operator++(); /** * \brief Postfix increment operator overloading. */ ConstIterator operator++(int) const; /** * \brief Dereferencing operator overloading. */ const T& operator*() const; /** * \brief Member access operator overriding. */ const T* operator->() const; /** * \brief Equality operator overriding. */ bool operator==(const ConstIterator& rhs) const; /** * \brief Inequality operator overriding. */ bool operator!=(const ConstIterator& rhs) const; private: friend class LinkedList; /** * \brief The default constructor. */ ConstIterator() = delete; /** * \brief All iterators should have a current node. */ ConstIterator(ListNode* node) : current_{node} { } ListNode* current_; }; /** * \brief Node of a linkedlist */ struct ListNode { T value_; ListNode* next_; }; /** * \brief Gets a list node at the given index */ LinkedList<T>::ListNode* getListNode(std::size_t index) const; std::size_t numElements_; ListNode* head_; ListNode* tail_; }; #include "_linkedlist.hpp" #endif
19.287263
76
0.620627
Dannnno
d554bd45d843cb76d265f6338a1d1a4f5b3618ea
10,916
cpp
C++
components/cpp_utils/TFTP.cpp
klaus-liebler/esp32
f6ad2b92153f64d2467f0256c6d2fe776d9d7145
[ "MIT" ]
null
null
null
components/cpp_utils/TFTP.cpp
klaus-liebler/esp32
f6ad2b92153f64d2467f0256c6d2fe776d9d7145
[ "MIT" ]
null
null
null
components/cpp_utils/TFTP.cpp
klaus-liebler/esp32
f6ad2b92153f64d2467f0256c6d2fe776d9d7145
[ "MIT" ]
null
null
null
/* * TFTP.cpp * * See also: * * https://tools.ietf.org/html/rfc1350 * Created on: May 21, 2017 * Author: kolban */ #include "TFTP.h" #include <esp_log.h> #include <FreeRTOS.h> #include <GeneralUtils.h> #include <string> #include <stdio.h> #include <errno.h> #include <string.h> #include <Socket.h> #include "sdkconfig.h" extern "C" { extern uint16_t lwip_ntohs(uint16_t); extern uint32_t lwip_ntohl(uint32_t); extern uint16_t lwip_htons(uint16_t); extern uint32_t lwip_htonl(uint32_t); } static const char* LOG_TAG = "TFTP"; enum opcode { TFTP_OPCODE_RRQ = 1, // Read request TFTP_OPCODE_WRQ = 2, // Write request TFTP_OPCODE_DATA = 3, // Data TFTP_OPCODE_ACK = 4, // Acknowledgement TFTP_OPCODE_ERROR = 5 // Error }; enum ERRORCODE { ERROR_CODE_NOTDEFINED = 0, ERROR_CODE_FILE_NOT_FOUND = 1, ERROR_CODE_ACCESS_VIOLATION = 2, ERROR_CODE_NO_SPACE = 3, ERROR_CODE_ILLEGAL_OPERATION = 4, ERROR_CODE_UNKNOWN_ID = 5, ERROR_CODE_FILE_EXISTS = 6, ERROR_CODE_UNKNOWN_USER = 7 }; /** * Size of the TFTP data payload. */ const int TFTP_DATA_SIZE = 512; struct data_packet { uint16_t blockNumber; std::string data; }; TFTP::TFTP() { m_baseDir = ""; } TFTP::~TFTP() { } /** * @brief Start a TFTP transaction. * @return N/A. */ TFTP::TFTP_Transaction::TFTP_Transaction() { m_baseDir = ""; m_filename = ""; m_mode = ""; m_opCode = -1; } // TFTP_Transaction /** * @brief Process a client read request. * @return N/A. */ void TFTP::TFTP_Transaction::processRRQ() { /* * 2 bytes 2 bytes n bytes * ---------------------------------- * | Opcode | Block # | Data | * ---------------------------------- * */ FILE* file; bool finished = false; ESP_LOGD(LOG_TAG, "Reading TFTP data from file: %s", m_filename.c_str()); std::string tmpName = m_baseDir + "/" + m_filename; /* struct stat buf; if (stat(tmpName.c_str(), &buf) != 0) { ESP_LOGE(LOG_TAG, "Stat file: %s: %s", tmpName.c_str(), strerror(errno)); return; } int length = buf.st_size; */ int blockNumber = 1; file = fopen(tmpName.c_str(), "r"); if (file == nullptr) { ESP_LOGE(LOG_TAG, "Failed to open file for reading: %s: %s", tmpName.c_str(), strerror(errno)); sendError(ERROR_CODE_FILE_NOT_FOUND, tmpName); return; } struct { uint16_t opCode; uint16_t blockNumber; uint8_t buf[TFTP_DATA_SIZE]; } record; record.opCode = htons(TFTP_OPCODE_DATA); // Set the op code to be DATA. while (!finished) { record.blockNumber = htons(blockNumber); int sizeRead = fread(record.buf, 1, TFTP_DATA_SIZE, file); ESP_LOGD(LOG_TAG, "Sending data to %s, blockNumber=%d, size=%d", Socket::addressToString(&m_partnerAddress).c_str(), blockNumber, sizeRead); m_partnerSocket.sendTo((uint8_t*) &record, sizeRead + 4, &m_partnerAddress); if (sizeRead < TFTP_DATA_SIZE) { finished = true; } else { waitForAck(blockNumber); } blockNumber++; // Increment the block number. } ESP_LOGD(LOG_TAG, "File sent"); } // processRRQ /** * @brief Process a client write request. * @return N/A. */ void TFTP::TFTP_Transaction::processWRQ() { /* * 2 bytes 2 bytes n bytes * --------------------------------- * DATA | 03 | Block # | Data | * --------------------------------- * The opcode for data is 0x03 - TFTP_OPCODE_DATA */ struct recv_data { uint16_t opCode; uint16_t blockNumber; uint8_t data; } *pRecv_data; struct sockaddr recvAddr; uint8_t dataBuffer[TFTP_DATA_SIZE + 2 + 2]; bool finished = false; FILE* file; ESP_LOGD(LOG_TAG, "Writing TFTP data to file: %s", m_filename.c_str()); std::string tmpName = m_baseDir + "/" + m_filename; file = fopen(tmpName.c_str(), "w"); if (file == nullptr) { ESP_LOGE(LOG_TAG, "Failed to open file for writing: %s: %s", tmpName.c_str(), strerror(errno)); return; } while(!finished) { pRecv_data = (struct recv_data*) dataBuffer; int receivedSize = m_partnerSocket.receiveFrom(dataBuffer, sizeof(dataBuffer), &recvAddr); if (receivedSize == -1) { ESP_LOGE(LOG_TAG, "rc == -1 from receive_from"); } struct data_packet dp; dp.blockNumber = ntohs(pRecv_data->blockNumber); dp.data = std::string((char*) &pRecv_data->data, receivedSize - 4); fwrite(dp.data.data(), dp.data.length(), 1, file); sendAck(dp.blockNumber); ESP_LOGD(LOG_TAG, "Block size: %d", dp.data.length()); if (dp.data.length() < TFTP_DATA_SIZE) { finished = true; } } // Finished fclose(file); m_partnerSocket.close(); } // process /** * @brief Send an acknowledgment back to the partner. * A TFTP acknowledgment packet contains an opcode (4) and a block number. * * @param [in] blockNumber The block number to send. * @return N/A. */ void TFTP::TFTP_Transaction::sendAck(uint16_t blockNumber) { struct { uint16_t opCode; uint16_t blockNumber; } ackData; ackData.opCode = htons(TFTP_OPCODE_ACK); ackData.blockNumber = htons(blockNumber); ESP_LOGD(LOG_TAG, "Sending ack to %s, blockNumber=%d", Socket::addressToString(&m_partnerAddress).c_str(), blockNumber); m_partnerSocket.sendTo((uint8_t*) &ackData, sizeof(ackData), &m_partnerAddress); } // sendAck /** * @brief Start being a TFTP server. * * This function does not return. * * @param [in] port The port number on which to listen. The default is 69. * @return N/A. */ void TFTP::start(uint16_t port) { /* * Loop forever. At the start of the loop we block waiting for an incoming client request. * The requests that we are expecting are either a request to read a file from the server * or write a file to the server. Once we have received a request we then call the appropriate * handler to handle that type of request. When the request has been completed, we start again. */ ESP_LOGD(LOG_TAG, "Starting TFTP::start() on port %d", port); Socket serverSocket; serverSocket.listen(port, true); // Create a listening socket that is a datagram. while (true) { // This would be a good place to start a transaction in the background. TFTP_Transaction* pTFTPTransaction = new TFTP_Transaction(); pTFTPTransaction->setBaseDir(m_baseDir); uint16_t receivedOpCode = pTFTPTransaction->waitForRequest(&serverSocket); switch (receivedOpCode) { // Handle the write request (client file upload) case opcode::TFTP_OPCODE_WRQ: { pTFTPTransaction->processWRQ(); break; } // Handle the read request (server file download) case opcode::TFTP_OPCODE_RRQ: { pTFTPTransaction->processRRQ(); break; } default: ESP_LOGE(LOG_TAG, "Unknown opcode: %d", receivedOpCode); break; } delete pTFTPTransaction; } // End while loop } // run /** * @brief Set the base dir for file access. * If we are asked to put a file to the file system, this is the base relative directory. * @param baseDir Base directory for file access. * @return N/A. */ void TFTP::TFTP_Transaction::setBaseDir(std::string baseDir) { m_baseDir = baseDir; } // setBaseDir /** * @brief Set the base dir for file access. * If we are asked to put a file to the file system, this is the base relative directory. * @param baseDir Base directory for file access. * @return N/A. */ void TFTP::setBaseDir(std::string baseDir) { m_baseDir = baseDir; } // setBaseDir /** * @brief Wait for an acknowledgment from the client. * After having sent data to the client, we expect an acknowledment back from the client. * This function causes us to wait for an incoming acknowledgment. */ void TFTP::TFTP_Transaction::waitForAck(uint16_t blockNumber) { struct { uint16_t opCode; uint16_t blockNumber; } ackData; ESP_LOGD(LOG_TAG, "TFTP: Waiting for an acknowledgment request"); int sizeRead = m_partnerSocket.receiveFrom((uint8_t*) &ackData, sizeof(ackData), &m_partnerAddress); ESP_LOGD(LOG_TAG, "TFTP: Received some data."); if (sizeRead != sizeof(ackData)) { ESP_LOGE(LOG_TAG, "waitForAck: Received %d but expected %d", sizeRead, sizeof(ackData)); sendError(ERROR_CODE_NOTDEFINED, "Ack not correct size"); return; } ackData.opCode = ntohs(ackData.opCode); ackData.blockNumber = ntohs(ackData.blockNumber); if (ackData.opCode != opcode::TFTP_OPCODE_ACK) { ESP_LOGE(LOG_TAG, "waitForAck: Received opcode %d but expected %d", ackData.opCode, opcode::TFTP_OPCODE_ACK); return; } if (ackData.blockNumber != blockNumber) { ESP_LOGE(LOG_TAG, "waitForAck: Blocknumber received %d but expected %d", ackData.blockNumber, blockNumber); return; } } // waitForAck /** * @brief Wait for a client request. * A %TFTP server waits for requests to send or receive files. A request can be * either WRQ (write request) which is a request from the client to write a new local * file or it can be a RRQ (read request) which is a request from the client to * read a local file. * @param pServerSocket The server socket on which to listen for client requests. * @return The op code received. */ /* * 2 bytes string 1 byte string 1 byte * ----------------------------------------------- * RRQ/ | 01/02 | Filename | 0 | Mode | 0 | * WRQ ----------------------------------------------- */ uint16_t TFTP::TFTP_Transaction::waitForRequest(Socket* pServerSocket) { union { uint8_t buf[TFTP_DATA_SIZE]; uint16_t opCode; } record; size_t length = 100; ESP_LOGD(LOG_TAG, "TFTP: Waiting for a request"); pServerSocket->receiveFrom(record.buf, length, &m_partnerAddress); // Save the filename, mode and op code. m_filename = std::string((char*) (record.buf + 2)); m_mode = std::string((char*) (record.buf + 3 + m_filename.length())); m_opCode = ntohs(record.opCode); switch (m_opCode) { // Handle the Write Request command. case TFTP_OPCODE_WRQ: { m_partnerSocket.createSocket(true); m_partnerSocket.bind(0, INADDR_ANY); sendAck(0); break; } // Handle the Read request command. case TFTP_OPCODE_RRQ: { m_partnerSocket.createSocket(true); m_partnerSocket.bind(0, INADDR_ANY); break; } default: { ESP_LOGD(LOG_TAG, "Un-handled opcode: %d", m_opCode); break; } } return m_opCode; } // waitForRequest /** * @brief Send an error indication to the client. * @param [in] code Error code to send to the client. * @param [in] message Explanation message. * @return N/A. */ void TFTP::TFTP_Transaction::sendError(uint16_t code, std::string message) { /* * 2 bytes 2 bytes string 1 byte * ----------------------------------------- * | Opcode | ErrorCode | ErrMsg | 0 | * ----------------------------------------- */ int size = 2 + 2 + message.length() + 1; uint8_t* buf = (uint8_t*) malloc(size); *(uint16_t*) (&buf[0]) = htons(opcode::TFTP_OPCODE_ERROR); *(uint16_t*) (&buf[2]) = htons(code); strcpy((char*) (&buf[4]), message.c_str()); m_partnerSocket.sendTo(buf, size, &m_partnerAddress); free(buf); } // sendError
27.496222
121
0.661964
klaus-liebler
d55625faab4a967a87ef961045f4929c16c50e77
6,462
cpp
C++
DrvApp/HookEngine/distorm/textdefs.cpp
jackqk/mystudy
84313c1eaed7351d37b609288d1d32bf3b808859
[ "Apache-2.0" ]
15
2017-05-27T16:02:51.000Z
2018-11-30T07:02:22.000Z
DrvApp/HookEngine/distorm/textdefs.cpp
jackqk/mystudy
84313c1eaed7351d37b609288d1d32bf3b808859
[ "Apache-2.0" ]
null
null
null
DrvApp/HookEngine/distorm/textdefs.cpp
jackqk/mystudy
84313c1eaed7351d37b609288d1d32bf3b808859
[ "Apache-2.0" ]
11
2017-11-10T01:28:59.000Z
2018-11-15T11:59:33.000Z
/* textdefs.c diStorm3 - Powerful disassembler for X86/AMD64 http://ragestorm.net/distorm/ distorm at gmail dot com Copyright (C) 2003-2016 Gil Dabah This library is licensed under the BSD license. See the file COPYING. */ #include <stdafx.h> #include "textdefs.h" #ifndef DISTORM_LIGHT static uint8_t Nibble2ChrTable[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; #define NIBBLE_TO_CHR Nibble2ChrTable[t] void _FASTCALL_ str_hex_b(_WString* s, unsigned int x) { /* * def prebuilt(): * s = "" * for i in xrange(256): * if ((i % 0x10) == 0): * s += "\r\n" * s += "\"%02x\", " % (i) * return s */ static int8_t TextBTable[256][3] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff" }; /* * Fixed length of 3 including null terminate character. */ memcpy(&s->p[s->length], TextBTable[x & 255], 3); s->length += 2; } void _FASTCALL_ str_code_hb(_WString* s, unsigned int x) { static int8_t TextHBTable[256][5] = { /* * def prebuilt(): * s = "" * for i in xrange(256): * if ((i % 0x10) == 0): * s += "\r\n" * s += "\"0x%x\", " % (i) * return s */ "0x0", "0x1", "0x2", "0x3", "0x4", "0x5", "0x6", "0x7", "0x8", "0x9", "0xa", "0xb", "0xc", "0xd", "0xe", "0xf", "0x10", "0x11", "0x12", "0x13", "0x14", "0x15", "0x16", "0x17", "0x18", "0x19", "0x1a", "0x1b", "0x1c", "0x1d", "0x1e", "0x1f", "0x20", "0x21", "0x22", "0x23", "0x24", "0x25", "0x26", "0x27", "0x28", "0x29", "0x2a", "0x2b", "0x2c", "0x2d", "0x2e", "0x2f", "0x30", "0x31", "0x32", "0x33", "0x34", "0x35", "0x36", "0x37", "0x38", "0x39", "0x3a", "0x3b", "0x3c", "0x3d", "0x3e", "0x3f", "0x40", "0x41", "0x42", "0x43", "0x44", "0x45", "0x46", "0x47", "0x48", "0x49", "0x4a", "0x4b", "0x4c", "0x4d", "0x4e", "0x4f", "0x50", "0x51", "0x52", "0x53", "0x54", "0x55", "0x56", "0x57", "0x58", "0x59", "0x5a", "0x5b", "0x5c", "0x5d", "0x5e", "0x5f", "0x60", "0x61", "0x62", "0x63", "0x64", "0x65", "0x66", "0x67", "0x68", "0x69", "0x6a", "0x6b", "0x6c", "0x6d", "0x6e", "0x6f", "0x70", "0x71", "0x72", "0x73", "0x74", "0x75", "0x76", "0x77", "0x78", "0x79", "0x7a", "0x7b", "0x7c", "0x7d", "0x7e", "0x7f", "0x80", "0x81", "0x82", "0x83", "0x84", "0x85", "0x86", "0x87", "0x88", "0x89", "0x8a", "0x8b", "0x8c", "0x8d", "0x8e", "0x8f", "0x90", "0x91", "0x92", "0x93", "0x94", "0x95", "0x96", "0x97", "0x98", "0x99", "0x9a", "0x9b", "0x9c", "0x9d", "0x9e", "0x9f", "0xa0", "0xa1", "0xa2", "0xa3", "0xa4", "0xa5", "0xa6", "0xa7", "0xa8", "0xa9", "0xaa", "0xab", "0xac", "0xad", "0xae", "0xaf", "0xb0", "0xb1", "0xb2", "0xb3", "0xb4", "0xb5", "0xb6", "0xb7", "0xb8", "0xb9", "0xba", "0xbb", "0xbc", "0xbd", "0xbe", "0xbf", "0xc0", "0xc1", "0xc2", "0xc3", "0xc4", "0xc5", "0xc6", "0xc7", "0xc8", "0xc9", "0xca", "0xcb", "0xcc", "0xcd", "0xce", "0xcf", "0xd0", "0xd1", "0xd2", "0xd3", "0xd4", "0xd5", "0xd6", "0xd7", "0xd8", "0xd9", "0xda", "0xdb", "0xdc", "0xdd", "0xde", "0xdf", "0xe0", "0xe1", "0xe2", "0xe3", "0xe4", "0xe5", "0xe6", "0xe7", "0xe8", "0xe9", "0xea", "0xeb", "0xec", "0xed", "0xee", "0xef", "0xf0", "0xf1", "0xf2", "0xf3", "0xf4", "0xf5", "0xf6", "0xf7", "0xf8", "0xf9", "0xfa", "0xfb", "0xfc", "0xfd", "0xfe", "0xff" }; if (x < 0x10) { /* < 0x10 has a fixed length of 4 including null terminate. */ memcpy(&s->p[s->length], TextHBTable[x & 255], 4); s->length += 3; } else { /* >= 0x10 has a fixed length of 5 including null terminate. */ memcpy(&s->p[s->length], TextHBTable[x & 255], 5); s->length += 4; } } void _FASTCALL_ str_code_hdw(_WString* s, uint32_t x) { int8_t* buf; int i = 0, shift = 0; unsigned int t = 0; buf = (int8_t*)&s->p[s->length]; buf[0] = '0'; buf[1] = 'x'; buf += 2; for (shift = 28; shift != 0; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } t = x & 0xf; buf[i++] = NIBBLE_TO_CHR; s->length += i + 2; buf[i] = '\0'; } void _FASTCALL_ str_code_hqw(_WString* s, uint8_t src[8]) { int8_t* buf; int i = 0, shift = 0; uint32_t x = RULONG(&src[sizeof(int32_t)]); int t; buf = (int8_t*)&s->p[s->length]; buf[0] = '0'; buf[1] = 'x'; buf += 2; for (shift = 28; shift != -4; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } x = RULONG(src); for (shift = 28; shift != 0; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } t = x & 0xf; buf[i++] = NIBBLE_TO_CHR; s->length += i + 2; buf[i] = '\0'; } #ifdef SUPPORT_64BIT_OFFSET void _FASTCALL_ str_off64(_WString* s, OFFSET_INTEGER x) { int8_t* buf; int i = 0, shift = 0; OFFSET_INTEGER t = 0; buf = (int8_t*)&s->p[s->length]; buf[0] = '0'; buf[1] = 'x'; buf += 2; for (shift = 60; shift != 0; shift -= 4) { t = (x >> shift) & 0xf; if (i | t) buf[i++] = NIBBLE_TO_CHR; } t = x & 0xf; buf[i++] = NIBBLE_TO_CHR; s->length += i + 2; buf[i] = '\0'; } #endif /* SUPPORT_64BIT_OFFSET */ #endif /* DISTORM_LIGHT */
37.352601
129
0.476787
jackqk
d556755ab874ea2f78040cb781cfb7a03579ce09
898
cpp
C++
lib/plog/samples/UtcTime/Main.cpp
hsbsw/hAIR
d7fa988dd639ced63acae3b1e980d39ee3c8412e
[ "MIT" ]
null
null
null
lib/plog/samples/UtcTime/Main.cpp
hsbsw/hAIR
d7fa988dd639ced63acae3b1e980d39ee3c8412e
[ "MIT" ]
null
null
null
lib/plog/samples/UtcTime/Main.cpp
hsbsw/hAIR
d7fa988dd639ced63acae3b1e980d39ee3c8412e
[ "MIT" ]
null
null
null
// // UtcTime - shows how to use UTC time in logs. // #include <plog/Log.h> #include <plog/Init.h> #include <plog/Formatters/CsvFormatter.h> #include <plog/Formatters/TxtFormatter.h> #include <plog/Appenders/ColorConsoleAppender.h> #include <plog/Appenders/RollingFileAppender.h> int main() { static plog::ColorConsoleAppender<plog::TxtFormatterUtcTime> consoleAppender; // TxtFormatter in UTC static plog::RollingFileAppender<plog::CsvFormatterUtcTime> fileAppender("UtcTime.csv", 10000, 2); // CsvFormatter in UTC plog::init(plog::verbose, &consoleAppender).addAppender(&fileAppender); PLOG_VERBOSE << "This is a VERBOSE message"; PLOG_DEBUG << "This is a DEBUG message"; PLOG_INFO << "This is an INFO message"; PLOG_WARNING << "This is a WARNING message"; PLOG_ERROR << "This is an ERROR message"; PLOG_FATAL << "This is a FATAL message"; return 0; }
33.259259
125
0.721604
hsbsw
d55a3c2c148ef28a162c3886742247fd169362ee
12,690
cpp
C++
Lyfe_Game/Source/Lyfe_Game/Private/CompoundStorageComponent_Cell.cpp
GameAboutThings/Lyfe
320a8e27586c327707f36e9a268c84d6d77c6da4
[ "Unlicense" ]
2
2018-04-30T09:58:48.000Z
2018-05-14T10:13:42.000Z
Lyfe_Game/Source/Lyfe_Game/Private/CompoundStorageComponent_Cell.cpp
GameAboutThings/Lyfe
320a8e27586c327707f36e9a268c84d6d77c6da4
[ "Unlicense" ]
null
null
null
Lyfe_Game/Source/Lyfe_Game/Private/CompoundStorageComponent_Cell.cpp
GameAboutThings/Lyfe
320a8e27586c327707f36e9a268c84d6d77c6da4
[ "Unlicense" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "CompoundStorageComponent_Cell.h" #include "Character_SingleCelled.h" #include "Logging.h" #include "Runtime/Engine/Classes/Kismet/GameplayStatics.h" #include "Meta_CellStage.h" // Sets default values for this component's properties UCompoundStorageComponent_Cell::UCompoundStorageComponent_Cell() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // ... } // Called when the game starts void UCompoundStorageComponent_Cell::BeginPlay() { Super::BeginPlay(); SetCompounds(); StartLowCompoundCycle(); lowCompound = "Carbon"; _protein.maximum = 100; _protein.current = 25; } // Called every frame void UCompoundStorageComponent_Cell::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); // ... } /*---------------------------------------------------------------------------------------------------------------------------------------------------------------*/ ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// PRIVATE //////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void UCompoundStorageComponent_Cell::EnforceCompoundBalance() { AddCompound(_playerCompounds._CO2.balance, ECompound::ECO2); AddCompound(_playerCompounds._O2.balance, ECompound::EO2); AddCompound(_playerCompounds._AminoAcid.balance, ECompound::EAminoAcid); AddCompound(_playerCompounds._Glucose.balance, ECompound::EGlucose); AddCompound(_playerCompounds._Lipid.balance, ECompound::ELipid); //First of all set the volume back on the player ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(this->GetOwner()); if (controller != nullptr) { controller->GetWorldTimerManager().SetTimer(consumptionTimer, this, &UCompoundStorageComponent_Cell::EnforceCompoundBalance, SURROUNDINGS_DELTA_TIME, false); } } FString UCompoundStorageComponent_Cell::GetCompoundName(ECompound compound) { return FString(); } void UCompoundStorageComponent_Cell::UpdateLowCompound() { ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0)); if (controller != nullptr) { TArray<bool> isLow = { false, //CO2 false, //oxygen false, //amino acid false, //glucose false //lipid }; //cycle through all compounds and see if the are <= than 10% of their maximum //if they are set, their value in the array to true //after this is done: //check if maybe there are no compounds that are low // in that case set lowCompound to "" //most likely that won't be the case so: //check what currently is in lowCompound //start at that value in the array and go to the next one that is low and set it // current amount / maximum <= 0.1f isLow[0] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::ECO2, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::ECO2, true)) <= 0.1f; isLow[1] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EO2, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EO2, true)) <= 0.1f; isLow[2] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EAminoAcid, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EAminoAcid, true)) <= 0.1f; isLow[3] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::EGlucose, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::EGlucose, true)) <= 0.1f; isLow[4] = ((float)controller->GetCompoundStorage()->GetCompound(ECompound::ELipid, false) / (float)controller->GetCompoundStorage()->GetCompound(ECompound::ELipid, true)) <= 0.1f; if (!isLow[0] && !isLow[1] && !isLow[2] && !isLow[3] && !isLow[4]) { lowCompound = ""; _eLowCompound = ECompound::ENothing; } else { int start = 0; if (_eLowCompound == ECompound::ENothing) { start = 0; } else if (_eLowCompound == ECompound::ECO2) { start = 1; } else if (_eLowCompound == ECompound::EO2) { start = 2; } else if (_eLowCompound == ECompound::EAminoAcid) { start = 3; } else if (_eLowCompound == ECompound::EGlucose) { start = 4; } else if (_eLowCompound == ECompound::ELipid) { start = 0; } //6 so it can return to the starting position if there are not other compounds int position = 0; for (position; position < 6; position++) { if (isLow[(start + position) % 5]) { break; } } switch ((start + position) % 5) { case 0: lowCompound = "CO2"; _eLowCompound = ECompound::ECO2; break; case 1: lowCompound = "Oxygen"; _eLowCompound = ECompound::EO2; break; case 2: lowCompound = "Amino Acids"; _eLowCompound = ECompound::EAminoAcid; break; case 3: lowCompound = "Glucose"; _eLowCompound = ECompound::EGlucose; break; case 4: lowCompound = "Lipids"; _eLowCompound = ECompound::ELipid; break; default: _eLowCompound = ECompound::ENothing; lowCompound = "ERROR"; break; } } controller->GetWorldTimerManager().SetTimer(lowCompoundRefreshTimer, this, &UCompoundStorageComponent_Cell::UpdateLowCompound, 2.f, false); } } ////////////////////////////////////////////////////////////////////////////// //////////////////////////////// PROTECTED /////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void UCompoundStorageComponent_Cell::StartLowCompoundCycle() { //ACharacter_SingleCelled* controller = Cast<ACharacter_SingleCelled>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0)); //if (controller != nullptr) //{ // controller->GetWorldTimerManager().SetTimer(lowCompoundRefreshTimer, this, &AGameMode_Cell::UpdateLowCompound, 2.f, false); //} UpdateLowCompound(); } ////////////////////////////////////////////////////////////////////////////// ///////////////////////////////// PUBLIC ///////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// void UCompoundStorageComponent_Cell::SetCompounds() { //CO2 _playerCompounds._CO2.maximum = 10000.f; _playerCompounds._CO2.current = 1000.f; _playerCompounds._CO2.balance = -1; //Oxygen _playerCompounds._O2.maximum = 10000.f; _playerCompounds._O2.current = 1000.f; _playerCompounds._O2.balance = -1; //Amino Acid _playerCompounds._AminoAcid.maximum = 10000.f; _playerCompounds._AminoAcid.current = 1000.f; _playerCompounds._AminoAcid.balance = -1; //Glucose _playerCompounds._Glucose.maximum = 10000.f; _playerCompounds._Glucose.current = 1000.f; _playerCompounds._Glucose.balance = -1; //Lipid _playerCompounds._Lipid.maximum = 10000.f; _playerCompounds._Lipid.current = 1000.f; _playerCompounds._Lipid.balance = -1; } void UCompoundStorageComponent_Cell::AddCompound(int amount, ECompound compound) { //find the right compound to add the amount if (compound == ECompound::ECO2) { Logging::Log(_playerCompounds._CO2.current); Logging::Log(amount); //add the amount _playerCompounds._CO2.current = _playerCompounds._CO2.current + amount; //check if it's greater than the maximum or smaller than 0 and correct that if (_playerCompounds._CO2.current > _playerCompounds._CO2.maximum) { _playerCompounds._CO2.current = _playerCompounds._CO2.maximum; } else if (_playerCompounds._CO2.current < 0) { _playerCompounds._CO2.current = 0; } } else if (compound == ECompound::EO2) { Logging::Log(_playerCompounds._O2.current); Logging::Log(amount); _playerCompounds._O2.current = _playerCompounds._O2.current + amount; if (_playerCompounds._O2.current > _playerCompounds._O2.maximum) { _playerCompounds._O2.current = _playerCompounds._O2.maximum; } else if (_playerCompounds._O2.current < 0) { _playerCompounds._O2.current = 0; } } else if (compound == ECompound::EAminoAcid) { Logging::Log(_playerCompounds._AminoAcid.current); Logging::Log(amount); _playerCompounds._AminoAcid.current = _playerCompounds._AminoAcid.current + amount; if (_playerCompounds._AminoAcid.current > _playerCompounds._AminoAcid.maximum) { _playerCompounds._AminoAcid.current = _playerCompounds._AminoAcid.maximum; } else if (_playerCompounds._AminoAcid.current < 0) { _playerCompounds._AminoAcid.current = 0; } } else if (compound == ECompound::EGlucose) { Logging::Log(_playerCompounds._Glucose.current); Logging::Log(amount); _playerCompounds._Glucose.current = _playerCompounds._Glucose.current + amount; if (_playerCompounds._Glucose.current > _playerCompounds._Glucose.maximum) { _playerCompounds._Glucose.current = _playerCompounds._Glucose.maximum; } else if (_playerCompounds._Glucose.current < 0) { _playerCompounds._Glucose.current = 0; } } else if (compound == ECompound::ELipid) { Logging::Log(_playerCompounds._Lipid.current); Logging::Log(amount); _playerCompounds._Lipid.current = _playerCompounds._Lipid.current + amount; if (_playerCompounds._Lipid.current > _playerCompounds._Lipid.maximum) { _playerCompounds._Lipid.current = _playerCompounds._Lipid.maximum; } else if (_playerCompounds._Lipid.current < 0) { _playerCompounds._Lipid.current = 0; } } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at AddCompound()"), *GetCompoundName(compound)); } } int UCompoundStorageComponent_Cell::GetCompound(ECompound compound, bool bMax) { if (bMax) { if (compound == ECompound::ECO2) { return _playerCompounds._CO2.maximum; } else if (compound == ECompound::EO2) { return _playerCompounds._O2.maximum; } else if (compound == ECompound::EAminoAcid) { return _playerCompounds._AminoAcid.maximum; } else if (compound == ECompound::EGlucose) { return _playerCompounds._Glucose.maximum; } else if (compound == ECompound::ELipid) { return _playerCompounds._Lipid.maximum; } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompound()"), *GetCompoundName(compound)); return 0; } } else { if (compound == ECompound::ECO2) { return _playerCompounds._CO2.current; } else if (compound == ECompound::EO2) { return _playerCompounds._O2.current; } else if (compound == ECompound::EAminoAcid) { return _playerCompounds._AminoAcid.current; } else if (compound == ECompound::EGlucose) { return _playerCompounds._Glucose.current; } else if (compound == ECompound::ELipid) { return _playerCompounds._Lipid.current; } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompound()"), *GetCompoundName(compound)); return 0; } } } int UCompoundStorageComponent_Cell::GetCompoundBalance(ECompound compound) { if (compound == ECompound::ECO2) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._CO2.balance; } } else if (compound == ECompound::EO2) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._O2.balance; } } else if (compound == ECompound::EAminoAcid) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._AminoAcid.balance; } } else if (compound == ECompound::EGlucose) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._Glucose.balance; } } else if (compound == ECompound::ELipid) { if (GetCompound(compound, false) == 0) { return 0; } else { return _playerCompounds._Lipid.balance; } } else { UE_LOG(LogTemp, Warning, TEXT("Input compound <<%s>> not found at GetCompoundBalance()"), *GetCompoundName(compound)); return 0; } } void UCompoundStorageComponent_Cell::AddProtein(int amount) { _protein.current += amount; if (_protein.current > _protein.maximum) { _protein.current = _protein.maximum; } else if (_protein.current < 0) { _protein.current = 0; } } int UCompoundStorageComponent_Cell::GetProtein(bool bMax) { if (bMax) { return _protein.maximum; } else { return _protein.current; } } FString UCompoundStorageComponent_Cell::GetLowCompound() { return lowCompound; }
27.467532
190
0.665406
GameAboutThings
f65b7c949823aa91c278a5e0314eea978e693527
4,202
cpp
C++
inference-engine/src/vpu/myriad_plugin/myriad_metrics.cpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
1
2022-01-19T15:36:45.000Z
2022-01-19T15:36:45.000Z
inference-engine/src/vpu/myriad_plugin/myriad_metrics.cpp
Andruxin52rus/openvino
d824e371fe7dffb90e6d3d58e4e34adecfce4606
[ "Apache-2.0" ]
22
2021-02-03T12:41:51.000Z
2022-02-21T13:04:48.000Z
inference-engine/src/vpu/myriad_plugin/myriad_metrics.cpp
mmakridi/openvino
769bb7709597c14debdaa356dd60c5a78bdfa97e
[ "Apache-2.0" ]
1
2021-07-28T17:30:46.000Z
2021-07-28T17:30:46.000Z
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "myriad_metrics.h" #include <algorithm> #include <vpu/utils/error.hpp> using namespace vpu::MyriadPlugin; using namespace InferenceEngine; using namespace VPUConfigParams; using namespace PluginConfigParams; //------------------------------------------------------------------------------ // Implementation of methods of class MyriadMetrics //------------------------------------------------------------------------------ MyriadMetrics::MyriadMetrics() { _supportedMetrics = { METRIC_KEY(AVAILABLE_DEVICES), METRIC_KEY(FULL_DEVICE_NAME), METRIC_KEY(SUPPORTED_METRICS), METRIC_KEY(SUPPORTED_CONFIG_KEYS), METRIC_KEY(OPTIMIZATION_CAPABILITIES), METRIC_KEY(RANGE_FOR_ASYNC_INFER_REQUESTS), METRIC_KEY(DEVICE_THERMAL), }; IE_SUPPRESS_DEPRECATED_START _supportedConfigKeys = { MYRIAD_ENABLE_HW_ACCELERATION, MYRIAD_ENABLE_RECEIVING_TENSOR_TIME, MYRIAD_CUSTOM_LAYERS, MYRIAD_ENABLE_FORCE_RESET, MYRIAD_THROUGHPUT_STREAMS, // deprecated KEY_VPU_HW_STAGES_OPTIMIZATION, KEY_VPU_PRINT_RECEIVE_TENSOR_TIME, KEY_VPU_CUSTOM_LAYERS, KEY_VPU_MYRIAD_FORCE_RESET, KEY_VPU_MYRIAD_PLATFORM, CONFIG_KEY(LOG_LEVEL), CONFIG_KEY(EXCLUSIVE_ASYNC_REQUESTS), CONFIG_KEY(PERF_COUNT), CONFIG_KEY(CONFIG_FILE), CONFIG_KEY(DEVICE_ID) }; IE_SUPPRESS_DEPRECATED_END _optimizationCapabilities = { METRIC_VALUE(FP16) }; _rangeForAsyncInferRequests = RangeType(3, 6, 1); _idToDeviceFullNameMap = { {"5", "Intel Movidius Myriad 2 VPU"}, {"8", "Intel Movidius Myriad X VPU"}, }; } std::vector<std::string> MyriadMetrics::AvailableDevicesNames( const std::shared_ptr<IMvnc> &mvnc, const std::vector<DevicePtr> &devicePool) const { std::vector<std::string> availableDevices; auto unbootedDevices = mvnc->AvailableDevicesNames(); availableDevices.insert(availableDevices.begin(), unbootedDevices.begin(), unbootedDevices.end()); for (auto & device : devicePool) { availableDevices.push_back(device->_name); } std::sort(availableDevices.begin(), availableDevices.end()); return availableDevices; } std::string MyriadMetrics::FullName(std::string deviceName) const { std::string nameDelimiter("-ma"); unsigned int indexLenght = 4; unsigned int placeOfTypeId = 2; auto indexStr = deviceName; indexStr.erase(0, indexStr.find(nameDelimiter) + nameDelimiter.length()); if (indexLenght != indexStr.length()) { return deviceName; } else { auto myriadId = std::string(1, indexStr[placeOfTypeId]); if (_idToDeviceFullNameMap.count(myriadId)) { return _idToDeviceFullNameMap.at(myriadId); } } return deviceName; } float MyriadMetrics::DevicesThermal(const DevicePtr& device) const { VPU_THROW_UNLESS(device != nullptr, "No device specified to get its thermal"); return MyriadExecutor::GetThermal(device); } const std::unordered_set<std::string>& MyriadMetrics::SupportedMetrics() const { return _supportedMetrics; } const std::unordered_set<std::string>& MyriadMetrics::SupportedConfigKeys() const { return _supportedConfigKeys; } const std::unordered_set<std::string>& MyriadMetrics::OptimizationCapabilities() const { return _optimizationCapabilities; } RangeType MyriadMetrics::RangeForAsyncInferRequests( const std::map<std::string, std::string>& config) const { auto throughput_streams_str = config.find(ie::MYRIAD_THROUGHPUT_STREAMS); if (throughput_streams_str != config.end()) { try { int throughput_streams = std::stoi(throughput_streams_str->second); if (throughput_streams > 0) { return RangeType(throughput_streams+1, throughput_streams*3, 1); } } catch(...) { THROW_IE_EXCEPTION << "Invalid config value for MYRIAD_THROUGHPUT_STREAMS, can't cast to int"; } } return _rangeForAsyncInferRequests; }
31.125926
106
0.669681
Andruxin52rus
f65c6a13cd9a587638b413bd044a30d92a398b53
1,230
cpp
C++
local_remote_attestation/host/enclave_b.cpp
VictorDebray/azure-tee-attestation-samples
38964c6023586dcc5014bd088daba0fa336c5a46
[ "MIT" ]
6
2020-03-28T16:46:47.000Z
2021-11-23T16:27:47.000Z
local_remote_attestation/host/enclave_b.cpp
VictorDebray/azure-tee-attestation-samples
38964c6023586dcc5014bd088daba0fa336c5a46
[ "MIT" ]
1
2021-02-10T13:48:52.000Z
2021-02-10T13:49:32.000Z
local_remote_attestation/host/enclave_b.cpp
VictorDebray/azure-tee-attestation-samples
38964c6023586dcc5014bd088daba0fa336c5a46
[ "MIT" ]
5
2020-07-31T10:38:44.000Z
2021-11-10T08:24:20.000Z
#include "enclave.h" int enclave_b_flow(oe_enclave_t* enclave, const char* input_file) { int ret = 0; const char* encrypted_file = "./out.encrypted"; const char* decrypted_file = "./out.decrypted"; // encrypt a file std::cout << "Host: decrypting file:" << decrypted_file << std::endl; ret = encrypt_file(enclave, DECRYPT_OPERATION, encrypted_file, decrypted_file); if (ret != 0) { std::cerr << "Host: processFile(DECRYPT_OPERATION) failed with " << ret << std::endl; return 1; } // Make sure the decryption is successfull. Input and decrypted files // are equal std::cout << "Host: compared file:" << decrypted_file << " to file:" << input_file << std::endl; ret = compare_2_files(input_file, decrypted_file); if (ret != 0) { std::cerr << "Host: checking failed! " << decrypted_file << "'s contents are supposed to be same as " << input_file << std::endl; return 1; } std::cout << "Host: " << decrypted_file << " is equal to " << input_file << " as expected" << std::endl; std::cout << "Host: decryption was done successfully" << std::endl; return ret; }
35.142857
79
0.590244
VictorDebray
f65ce637d77ce183f83b70dce6da8d0b4b8b8e71
16,444
cpp
C++
src/master/main.cpp
j143/mesos
a85a22baa32f66ecaa13c4602a195d57f6abf9be
[ "Apache-2.0" ]
null
null
null
src/master/main.cpp
j143/mesos
a85a22baa32f66ecaa13c4602a195d57f6abf9be
[ "Apache-2.0" ]
null
null
null
src/master/main.cpp
j143/mesos
a85a22baa32f66ecaa13c4602a195d57f6abf9be
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // 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 <stdint.h> #include <memory> #include <set> #include <string> #include <utility> #include <vector> #include <mesos/mesos.hpp> #include <mesos/authorizer/authorizer.hpp> #include <mesos/allocator/allocator.hpp> #include <mesos/master/contender.hpp> #include <mesos/master/detector.hpp> #include <mesos/module/anonymous.hpp> #include <mesos/module/authorizer.hpp> #include <mesos/state/in_memory.hpp> #ifndef __WINDOWS__ #include <mesos/state/log.hpp> #endif // __WINDOWS__ #include <mesos/state/state.hpp> #include <mesos/state/storage.hpp> #include <mesos/zookeeper/detector.hpp> #include <process/limiter.hpp> #include <process/owned.hpp> #include <process/pid.hpp> #include <stout/check.hpp> #include <stout/duration.hpp> #include <stout/exit.hpp> #include <stout/flags.hpp> #include <stout/nothing.hpp> #include <stout/option.hpp> #include <stout/os.hpp> #include <stout/path.hpp> #include <stout/stringify.hpp> #include <stout/strings.hpp> #include <stout/try.hpp> #include <stout/version.hpp> #include "common/build.hpp" #include "common/http.hpp" #include "common/protobuf_utils.hpp" #include "hook/manager.hpp" #include "logging/flags.hpp" #include "logging/logging.hpp" #include "master/master.hpp" #include "master/registrar.hpp" #include "master/allocator/mesos/hierarchical.hpp" #include "master/detector/standalone.hpp" #include "module/manager.hpp" #include "version/version.hpp" using namespace mesos::internal; #ifndef __WINDOWS__ using namespace mesos::internal::log; #endif // __WINDOWS__ using namespace mesos::internal::master; using namespace zookeeper; using mesos::Authorizer; using mesos::MasterInfo; using mesos::Parameter; using mesos::Parameters; #ifndef __WINDOWS__ using mesos::log::Log; #endif // __WINDOWS__ using mesos::allocator::Allocator; using mesos::master::contender::MasterContender; using mesos::master::detector::MasterDetector; using mesos::master::detector::StandaloneMasterDetector; using mesos::modules::Anonymous; using mesos::modules::ModuleManager; using mesos::state::InMemoryStorage; #ifndef __WINDOWS__ using mesos::state::LogStorage; #endif // __WINDOWS__ using mesos::state::Storage; using process::Owned; using process::RateLimiter; using process::UPID; using process::firewall::DisabledEndpointsFirewallRule; using process::firewall::FirewallRule; using std::cerr; using std::cout; using std::endl; using std::move; using std::ostringstream; using std::set; using std::shared_ptr; using std::string; using std::vector; int main(int argc, char** argv) { // The order of initialization of various master components is as follows: // * Validate flags. // * Logging. // * Log build information. // * Libprocess. // * Version process. // * Firewall rules: should be initialized before initializing HTTP endpoints. // * Modules: Load module libraries and manifests before they // can be instantiated. // * Anonymous modules: Later components such as Allocators, and master // contender/detector might depend upon anonymous modules. // * Hooks. // * Allocator. // * Registry storage. // * State. // * Master contender. // * Master detector. // * Authorizer. // * Slave removal rate limiter. // * `Master` process. // // TODO(avinash): Add more comments discussing the rationale behind for this // particular component ordering. GOOGLE_PROTOBUF_VERIFY_VERSION; master::Flags flags; Try<flags::Warnings> load = flags.load("MESOS_", argc, argv); if (flags.help) { cout << flags.usage() << endl; return EXIT_SUCCESS; } if (flags.version) { cout << "mesos" << " " << MESOS_VERSION << endl; return EXIT_SUCCESS; } if (load.isError()) { cerr << flags.usage(load.error()) << endl; return EXIT_FAILURE; } logging::initialize(argv[0], true, flags); // Catch signals. // Log any flag warnings (after logging is initialized). foreach (const flags::Warning& warning, load->warnings) { LOG(WARNING) << warning.message; } // Check that master's version has the expected format (SemVer). { Try<Version> version = Version::parse(MESOS_VERSION); if (version.isError()) { EXIT(EXIT_FAILURE) << "Failed to parse Mesos version '" << MESOS_VERSION << "': " << version.error(); } } if (flags.ip_discovery_command.isSome() && flags.ip.isSome()) { EXIT(EXIT_FAILURE) << flags.usage( "Only one of `--ip` or `--ip_discovery_command` should be specified"); } if (flags.ip_discovery_command.isSome()) { Try<string> ipAddress = os::shell(flags.ip_discovery_command.get()); if (ipAddress.isError()) { EXIT(EXIT_FAILURE) << ipAddress.error(); } os::setenv("LIBPROCESS_IP", strings::trim(ipAddress.get())); } else if (flags.ip.isSome()) { os::setenv("LIBPROCESS_IP", flags.ip.get()); } os::setenv("LIBPROCESS_PORT", stringify(flags.port)); if (flags.advertise_ip.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_IP", flags.advertise_ip.get()); } if (flags.advertise_port.isSome()) { os::setenv("LIBPROCESS_ADVERTISE_PORT", flags.advertise_port.get()); } if (flags.zk.isNone()) { if (flags.master_contender.isSome() ^ flags.master_detector.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Both --master_contender and --master_detector should " "be specified or omitted."); } } else { if (flags.master_contender.isSome() || flags.master_detector.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --zk or the " "--master_contender/--master_detector " "pair should be specified."); } } // Log build information. LOG(INFO) << "Build: " << build::DATE << " by " << build::USER; LOG(INFO) << "Version: " << MESOS_VERSION; if (build::GIT_TAG.isSome()) { LOG(INFO) << "Git tag: " << build::GIT_TAG.get(); } if (build::GIT_SHA.isSome()) { LOG(INFO) << "Git SHA: " << build::GIT_SHA.get(); } // This should be the first invocation of `process::initialize`. If it returns // `false`, then it has already been called, which means that the // authentication realm for libprocess-level HTTP endpoints was not set to the // correct value for the master. if (!process::initialize( "master", READWRITE_HTTP_AUTHENTICATION_REALM, READONLY_HTTP_AUTHENTICATION_REALM)) { EXIT(EXIT_FAILURE) << "The call to `process::initialize()` in the master's " << "`main()` was not the function's first invocation"; } spawn(new VersionProcess(), true); // Initialize firewall rules. if (flags.firewall_rules.isSome()) { vector<Owned<FirewallRule>> rules; const Firewall firewall = flags.firewall_rules.get(); if (firewall.has_disabled_endpoints()) { hashset<string> paths; foreach (const string& path, firewall.disabled_endpoints().paths()) { paths.insert(path); } rules.emplace_back(new DisabledEndpointsFirewallRule(paths)); } process::firewall::install(move(rules)); } // Initialize modules. if (flags.modules.isSome() && flags.modulesDir.isSome()) { EXIT(EXIT_FAILURE) << flags.usage("Only one of --modules or --modules_dir should be specified"); } if (flags.modulesDir.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modulesDir.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } if (flags.modules.isSome()) { Try<Nothing> result = ModuleManager::load(flags.modules.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error loading modules: " << result.error(); } } // Create anonymous modules. foreach (const string& name, ModuleManager::find<Anonymous>()) { Try<Anonymous*> create = ModuleManager::create<Anonymous>(name); if (create.isError()) { EXIT(EXIT_FAILURE) << "Failed to create anonymous module named '" << name << "'"; } // We don't bother keeping around the pointer to this anonymous // module, when we exit that will effectively free its memory. // // TODO(benh): We might want to add explicit finalization (and // maybe explicit initialization too) in order to let the module // do any housekeeping necessary when the master is cleanly // terminating. } // Initialize hooks. if (flags.hooks.isSome()) { Try<Nothing> result = HookManager::initialize(flags.hooks.get()); if (result.isError()) { EXIT(EXIT_FAILURE) << "Error installing hooks: " << result.error(); } } // Create an instance of allocator. const string allocatorName = flags.allocator; Try<Allocator*> allocator = Allocator::create(allocatorName); if (allocator.isError()) { EXIT(EXIT_FAILURE) << "Failed to create '" << allocatorName << "' allocator: " << allocator.error(); } CHECK_NOTNULL(allocator.get()); LOG(INFO) << "Using '" << allocatorName << "' allocator"; Storage* storage = nullptr; #ifndef __WINDOWS__ Log* log = nullptr; #endif // __WINDOWS__ if (flags.registry == "in_memory") { storage = new InMemoryStorage(); #ifndef __WINDOWS__ } else if (flags.registry == "replicated_log" || flags.registry == "log_storage") { // TODO(bmahler): "log_storage" is present for backwards // compatibility, can be removed before 0.19.0. if (flags.work_dir.isNone()) { EXIT(EXIT_FAILURE) << "--work_dir needed for replicated log based registry"; } Try<Nothing> mkdir = os::mkdir(flags.work_dir.get()); if (mkdir.isError()) { EXIT(EXIT_FAILURE) << "Failed to create work directory '" << flags.work_dir.get() << "': " << mkdir.error(); } if (flags.zk.isSome()) { // Use replicated log with ZooKeeper. if (flags.quorum.isNone()) { EXIT(EXIT_FAILURE) << "Need to specify --quorum for replicated log based" << " registry when using ZooKeeper"; } Try<zookeeper::URL> url = zookeeper::URL::parse(flags.zk.get()); if (url.isError()) { EXIT(EXIT_FAILURE) << "Error parsing ZooKeeper URL: " << url.error(); } log = new Log( flags.quorum.get(), path::join(flags.work_dir.get(), "replicated_log"), url.get().servers, flags.zk_session_timeout, path::join(url.get().path, "log_replicas"), url.get().authentication, flags.log_auto_initialize, "registrar/"); } else { // Use replicated log without ZooKeeper. log = new Log( 1, path::join(flags.work_dir.get(), "replicated_log"), set<UPID>(), flags.log_auto_initialize, "registrar/"); } storage = new LogStorage(log); #endif // __WINDOWS__ } else { EXIT(EXIT_FAILURE) << "'" << flags.registry << "' is not a supported" << " option for registry persistence"; } CHECK_NOTNULL(storage); mesos::state::State* state = new mesos::state::State(storage); Registrar* registrar = new Registrar(flags, state, READONLY_HTTP_AUTHENTICATION_REALM); MasterContender* contender; MasterDetector* detector; Try<MasterContender*> contender_ = MasterContender::create( flags.zk, flags.master_contender, flags.zk_session_timeout); if (contender_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master contender: " << contender_.error(); } contender = contender_.get(); Try<MasterDetector*> detector_ = MasterDetector::create( flags.zk, flags.master_detector, flags.zk_session_timeout); if (detector_.isError()) { EXIT(EXIT_FAILURE) << "Failed to create a master detector: " << detector_.error(); } detector = detector_.get(); Option<Authorizer*> authorizer_ = None(); auto authorizerNames = strings::split(flags.authorizers, ","); if (authorizerNames.empty()) { EXIT(EXIT_FAILURE) << "No authorizer specified"; } if (authorizerNames.size() > 1) { EXIT(EXIT_FAILURE) << "Multiple authorizers not supported"; } string authorizerName = authorizerNames[0]; // NOTE: The flag --authorizers overrides the flag --acls, i.e. if // a non default authorizer is requested, it will be used and // the contents of --acls will be ignored. // TODO(arojas): Consider adding support for multiple authorizers. Result<Authorizer*> authorizer((None())); if (authorizerName != master::DEFAULT_AUTHORIZER) { LOG(INFO) << "Creating '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(authorizerName); } else { // `authorizerName` is `DEFAULT_AUTHORIZER` at this point. if (flags.acls.isSome()) { LOG(INFO) << "Creating default '" << authorizerName << "' authorizer"; authorizer = Authorizer::create(flags.acls.get()); } } if (authorizer.isError()) { EXIT(EXIT_FAILURE) << "Could not create '" << authorizerName << "' authorizer: " << authorizer.error(); } else if (authorizer.isSome()) { authorizer_ = authorizer.get(); // Set the authorization callbacks for libprocess HTTP endpoints. // Note that these callbacks capture `authorizer_.get()`, but the master // creates a copy of the authorizer during construction. Thus, if in the // future it becomes possible to dynamically set the authorizer, this would // break. process::http::authorization::setCallbacks( createAuthorizationCallbacks(authorizer_.get())); } Files files(READONLY_HTTP_AUTHENTICATION_REALM, authorizer_); Option<shared_ptr<RateLimiter>> slaveRemovalLimiter = None(); if (flags.agent_removal_rate_limit.isSome()) { // Parse the flag value. // TODO(vinod): Move this parsing logic to flags once we have a // 'Rate' abstraction in stout. vector<string> tokens = strings::tokenize(flags.agent_removal_rate_limit.get(), "/"); if (tokens.size() != 2) { EXIT(EXIT_FAILURE) << "Invalid agent_removal_rate_limit: " << flags.agent_removal_rate_limit.get() << ". Format is <Number of agents>/<Duration>"; } Try<int> permits = numify<int>(tokens[0]); if (permits.isError()) { EXIT(EXIT_FAILURE) << "Invalid agent_removal_rate_limit: " << flags.agent_removal_rate_limit.get() << ". Format is <Number of agents>/<Duration>" << ": " << permits.error(); } Try<Duration> duration = Duration::parse(tokens[1]); if (duration.isError()) { EXIT(EXIT_FAILURE) << "Invalid agent_removal_rate_limit: " << flags.agent_removal_rate_limit.get() << ". Format is <Number of agents>/<Duration>" << ": " << duration.error(); } slaveRemovalLimiter = new RateLimiter(permits.get(), duration.get()); } Master* master = new Master( allocator.get(), registrar, &files, contender, detector, authorizer_, slaveRemovalLimiter, flags); if (flags.zk.isNone() && flags.master_detector.isNone()) { // It means we are using the standalone detector so we need to // appoint this Master as the leader. dynamic_cast<StandaloneMasterDetector*>(detector)->appoint(master->info()); } process::spawn(master); process::wait(master->self()); delete master; delete allocator.get(); delete registrar; delete state; delete storage; #ifndef __WINDOWS__ delete log; #endif // __WINDOWS__ delete contender; delete detector; if (authorizer_.isSome()) { delete authorizer_.get(); } return EXIT_SUCCESS; }
29.68231
80
0.662977
j143
f65d48910d200e8e0757ad791c65309974977b88
1,913
hpp
C++
ios/Pods/boost-for-react-native/boost/fiber/detail/config.hpp
malsadi87/zstr-react
63297d67be58393cb1efc57791acdd144643aeb4
[ "MIT" ]
156
2016-12-14T07:54:55.000Z
2021-08-06T10:16:27.000Z
ios/Pods/boost-for-react-native/boost/fiber/detail/config.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
28
2016-10-16T19:42:37.000Z
2018-09-14T21:29:48.000Z
ios/Pods/boost-for-react-native/boost/fiber/detail/config.hpp
c7yrus/alyson-v3
5ad95a8f782f5f5d2fd543d44ca6a8b093395965
[ "Apache-2.0" ]
35
2016-11-25T14:39:33.000Z
2020-05-15T11:06:57.000Z
// Copyright Oliver Kowalke 2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_FIBERS_DETAIL_CONFIG_H #define BOOST_FIBERS_DETAIL_CONFIG_H #include <cstddef> #include <boost/config.hpp> #include <boost/predef.h> #include <boost/detail/workaround.hpp> #ifdef BOOST_FIBERS_DECL # undef BOOST_FIBERS_DECL #endif #if (defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBERS_DYN_LINK) ) && ! defined(BOOST_FIBERS_STATIC_LINK) # if defined(BOOST_FIBERS_SOURCE) # define BOOST_FIBERS_DECL BOOST_SYMBOL_EXPORT # define BOOST_FIBERS_BUILD_DLL # else # define BOOST_FIBERS_DECL BOOST_SYMBOL_IMPORT # endif #endif #if ! defined(BOOST_FIBERS_DECL) # define BOOST_FIBERS_DECL #endif #if ! defined(BOOST_FIBERS_SOURCE) && ! defined(BOOST_ALL_NO_LIB) && ! defined(BOOST_FIBERS_NO_LIB) # define BOOST_LIB_NAME boost_fiber # if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBERS_DYN_LINK) # define BOOST_DYN_LINK # endif # include <boost/config/auto_link.hpp> #endif #if BOOST_OS_LINUX || BOOST_OS_WINDOWS # define BOOST_FIBERS_HAS_FUTEX #endif #if (!defined(BOOST_FIBERS_HAS_FUTEX) && \ (defined(BOOST_FIBERS_SPINLOCK_TTAS_FUTEX) || defined(BOOST_FIBERS_SPINLOCK_TTAS_ADAPTIVE_FUTEX))) # error "futex not supported on this platform" #endif #if !defined(BOOST_FIBERS_SPIN_MAX_COLLISIONS) # define BOOST_FIBERS_SPIN_MAX_COLLISIONS 16 #endif #if !defined(BOOST_FIBERS_SPIN_MAX_TESTS) # define BOOST_FIBERS_SPIN_MAX_TESTS 100 #endif // modern architectures have cachelines with 64byte length // ARM Cortex-A15 32/64byte, Cortex-A9 16/32/64bytes // MIPS 74K: 32byte, 4KEc: 16byte // ist shoudl be safe to use 64byte for all static constexpr std::size_t cache_alignment{ 64 }; static constexpr std::size_t cacheline_length{ 64 }; #endif // BOOST_FIBERS_DETAIL_CONFIG_H
28.984848
107
0.788813
malsadi87
f65d6152e235a9ae5307a87b311c2a1d31670c6d
98
cpp
C++
examples/basic.cpp
sthagen/cpp-fmt-proxy
18783c1019abd8ce2d25f347dce933bb65762323
[ "MIT" ]
1
2021-09-12T11:00:41.000Z
2021-09-12T11:00:41.000Z
examples/basic.cpp
sthagen/cpp-fmt-proxy
18783c1019abd8ce2d25f347dce933bb65762323
[ "MIT" ]
null
null
null
examples/basic.cpp
sthagen/cpp-fmt-proxy
18783c1019abd8ce2d25f347dce933bb65762323
[ "MIT" ]
null
null
null
#define FMT_HEADER_ONLY #include <fmt/format.h> int main() { fmt::print("Hello, {}!\n", 42); }
14
33
0.622449
sthagen
f65e1081d2a574e654796d99e4dae40e79bc1848
1,743
cpp
C++
src/MapGenerator/Math/LineEquation.cpp
USCcorpuscallosum/spiky
38b2d73ae8def2180e9e84f5c9b6ba814468abc9
[ "MIT" ]
2
2018-11-10T20:56:22.000Z
2019-02-10T13:14:05.000Z
src/MapGenerator/Math/LineEquation.cpp
FutureVR/ResponsiveTerrain
f5e631539e886dffb0b4b3f398803730db31f8d7
[ "MIT" ]
null
null
null
src/MapGenerator/Math/LineEquation.cpp
FutureVR/ResponsiveTerrain
f5e631539e886dffb0b4b3f398803730db31f8d7
[ "MIT" ]
null
null
null
// MapGenerator // from https://github.com/Rellikiox/MapGenerator /* * LineEquation.cc * * Created on: Mar 5, 2012 * Author: rellik */ #include "LineEquation.h" equ::equ(Vec2 p1, Vec2 p2) { // Calculamos la pendiente if (p1.x != p2.x) { vertical = false; m = (p2.y - p1.y) / (p2.x - p1.x); b = p1.y - p1.y * m; } else { vertical = true; m = 0; b = p1.x; } } equ::equ(Vec2 p, double m_){ m = m_; if(m != 0){ vertical = false; b = p.y - p.x * m; }else{ vertical = true; b = p.x; } } equ::equ(const equ& e) { m = e.m; b = e.b; vertical = e.vertical; } equ & equ::operator=(const equ &e) { if (this != &e) { m = e.m; b = e.b; vertical = e.vertical; } return *this; } equ::~equ() { m = 0; b = 0; vertical = false; } double equ::operator()(const double x) { return (x * m + b); } void equ::Move(const Vec2 vec) { Vec2 p0, p1; if (vertical) { p0 = Vec2(b, 0); p1 = Vec2(b, 1); } else { p0 = Vec2(0, b); p1 = Vec2(1, m + b); } p0 += Vec2(vec.x, vec.y); p1 += Vec2(vec.x, vec.y); *this = equ(p0, p1); } Vec2 equ::Intersection(equ &e) const { double x; double y; if (this->m != e.m) { if (this->vertical) { x = this->b; y = e(x); } else if (e.vertical) { x = e.b; y = x * this->m + this->b; } else { x = (e.b - this->b) / (this->m - e.m); y = e(x); } } else { if (this->vertical == e.vertical) { x = 0; y = 0; } else { if (this->vertical) { // this es vertical, e es horizontal x = this->b; y = e.b; } else { // this es horizontal, e es vertical x = e.b; y = this->b; } } } return Vec2(x, y); } bool equ::Vertical(){ return vertical; } bool equ::Horizontal(){ return !vertical && m == 0; }
14.056452
61
0.507745
USCcorpuscallosum