text
stringlengths
54
60.6k
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compressor.h" #include "hash.h" #include "pubkey.h" #include "script/standard.h" bool CScriptCompressor::IsToKeyID(CKeyID& hash) const { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { memcpy(&hash, &script[3], 20); return true; } return false; } bool CScriptCompressor::IsToScriptID(CScriptID& hash) const { if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20 && script[22] == OP_EQUAL) { memcpy(&hash, &script[2], 20); return true; } return false; } bool CScriptCompressor::IsToPubKey(CPubKey& pubkey) const { if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG && (script[1] == 0x02 || script[1] == 0x03)) { pubkey.Set(&script[1], &script[34]); return true; } if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG && script[1] == 0x04) { pubkey.Set(&script[1], &script[66]); return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible } return false; } bool CScriptCompressor::Compress(std::vector<unsigned char>& out) const { CKeyID keyID; if (IsToKeyID(keyID)) { out.resize(21); out[0] = 0x00; memcpy(&out[1], &keyID, 20); return true; } CScriptID scriptID; if (IsToScriptID(scriptID)) { out.resize(21); out[0] = 0x01; memcpy(&out[1], &scriptID, 20); return true; } CPubKey pubkey; if (IsToPubKey(pubkey)) { out.resize(33); memcpy(&out[1], &pubkey[1], 32); if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { out[0] = pubkey[0]; return true; } else if (pubkey[0] == 0x04) { out[0] = 0x04 | (pubkey[64] & 0x01); return true; } } return false; } unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const { if (nSize == 0 || nSize == 1) return 20; if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5) return 32; return 0; } bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char>& in) { switch (nSize) { case 0x00: script.resize(25); script[0] = OP_DUP; script[1] = OP_HASH160; script[2] = 20; memcpy(&script[3], &in[0], 20); script[23] = OP_EQUALVERIFY; script[24] = OP_CHECKSIG; return true; case 0x01: script.resize(23); script[0] = OP_HASH160; script[1] = 20; memcpy(&script[2], &in[0], 20); script[22] = OP_EQUAL; return true; case 0x02: case 0x03: script.resize(35); script[0] = 33; script[1] = nSize; memcpy(&script[2], &in[0], 32); script[34] = OP_CHECKSIG; return true; case 0x04: case 0x05: unsigned char vch[33] = {}; vch[0] = nSize - 2; memcpy(&vch[1], &in[0], 32); CPubKey pubkey(&vch[0], &vch[33]); if (!pubkey.Decompress()) return false; assert(pubkey.size() == 65); script.resize(67); script[0] = 65; memcpy(&script[1], pubkey.begin(), 65); script[66] = OP_CHECKSIG; return true; } return false; } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n * 9 + d - 1) * 10 + e; } else { return 1 + (n - 1) * 10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x * 10 + d; } else { n = x + 1; } while (e) { n *= 10; e--; } return n; } <commit_msg>Fix subscript[0] in compressor.cpp<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017-2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compressor.h" #include "hash.h" #include "pubkey.h" #include "script/standard.h" bool CScriptCompressor::IsToKeyID(CKeyID& hash) const { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { memcpy(&hash, &script[3], 20); return true; } return false; } bool CScriptCompressor::IsToScriptID(CScriptID& hash) const { if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20 && script[22] == OP_EQUAL) { memcpy(&hash, &script[2], 20); return true; } return false; } bool CScriptCompressor::IsToPubKey(CPubKey& pubkey) const { if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG && (script[1] == 0x02 || script[1] == 0x03)) { pubkey.Set(&script[1], &script[34]); return true; } if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG && script[1] == 0x04) { pubkey.Set(&script[1], &script[66]); return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible } return false; } bool CScriptCompressor::Compress(std::vector<unsigned char>& out) const { CKeyID keyID; if (IsToKeyID(keyID)) { out.resize(21); out[0] = 0x00; memcpy(&out[1], &keyID, 20); return true; } CScriptID scriptID; if (IsToScriptID(scriptID)) { out.resize(21); out[0] = 0x01; memcpy(&out[1], &scriptID, 20); return true; } CPubKey pubkey; if (IsToPubKey(pubkey)) { out.resize(33); memcpy(&out[1], &pubkey[1], 32); if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { out[0] = pubkey[0]; return true; } else if (pubkey[0] == 0x04) { out[0] = 0x04 | (pubkey[64] & 0x01); return true; } } return false; } unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const { if (nSize == 0 || nSize == 1) return 20; if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5) return 32; return 0; } bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char>& in) { switch (nSize) { case 0x00: script.resize(25); script[0] = OP_DUP; script[1] = OP_HASH160; script[2] = 20; memcpy(&script[3], in.data(), 20); script[23] = OP_EQUALVERIFY; script[24] = OP_CHECKSIG; return true; case 0x01: script.resize(23); script[0] = OP_HASH160; script[1] = 20; memcpy(&script[2], in.data(), 20); script[22] = OP_EQUAL; return true; case 0x02: case 0x03: script.resize(35); script[0] = 33; script[1] = nSize; memcpy(&script[2], in.data(), 32); script[34] = OP_CHECKSIG; return true; case 0x04: case 0x05: unsigned char vch[33] = {}; vch[0] = nSize - 2; memcpy(&vch[1], in.data(), 32); CPubKey pubkey(&vch[0], &vch[33]); if (!pubkey.Decompress()) return false; assert(pubkey.size() == 65); script.resize(67); script[0] = 65; memcpy(&script[1], pubkey.begin(), 65); script[66] = OP_CHECKSIG; return true; } return false; } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n * 9 + d - 1) * 10 + e; } else { return 1 + (n - 1) * 10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x * 10 + d; } else { n = x + 1; } while (e) { n *= 10; e--; } return n; } <|endoftext|>
<commit_before>#include <rohc/compressor.h> #include <rohc/lock.h> #include <rohc/log.h> #include "network.h" #include <rohc/rohc.h> #include "cprofile.h" #include <functional> #include <algorithm> #include <cstring> using namespace std; namespace { struct ContextFinder : public unary_function<const ROHC::CProfile*, bool> { ContextFinder(unsigned int profileID, const ROHC::iphdr* ip) : profileID(profileID), ip(ip) {} bool operator()(const ROHC::CProfile* profile) { return profile && profile->Matches(profileID, ip); } unsigned int profileID; const ROHC::iphdr* ip; }; struct OldestContextFinder : public binary_function<const ROHC::CProfile*, const ROHC::CProfile, bool> { bool operator()(const ROHC::CProfile* a, const ROHC::CProfile* b) { return a->LastUsed() < b->LastUsed(); } }; } // anon ns namespace ROHC { Compressor::Compressor(size_t maxCID, Reordering_t reorder_ratio, IPIDBehaviour_t ip_id_behaviour) : maxCID(maxCID) , contexts(0) , feedbackData(0) , feedbackMutex(allocMutex()) , reorder_ratio(reorder_ratio) , ip_id_behaviour(ip_id_behaviour) , numberOfPacketsSent(0) , dataSizeUncompressed(0) , dataSizeCompressed(0) { /** statistics */ numberOfPacketsSent = 0; dataSizeUncompressed = 0; dataSizeCompressed = 0; memset(statistics, 0, sizeof(statistics)); } Compressor::~Compressor() { for (contexts_t::iterator i = contexts.begin(); contexts.end() != i; ++i) { delete *i; } freeMutex(feedbackMutex); } void Compressor::compress(const uint8_t* data, size_t size, data_t& output) { data_t d(data, data + size); compress(d, output); } void Compressor::compress(const data_t& data, data_t& output) { output.reserve(data.size()); // Take care of received feedback HandleReceivedFeedback(); size_t outputInSize = output.size(); size_t feedbackSize = feedbackData.size(); if (feedbackSize) { ScopedLock lock(feedbackMutex); // Add feedback data (if exists) output.insert(output.end(), feedbackData.begin(), feedbackData.end()); feedbackData.clear(); } if (data.size() < sizeof(iphdr)) { error("Not enough data for an IP header\n"); return; } vector<uint8_t>::const_iterator curPos = data.begin(); const iphdr* ip = reinterpret_cast<const iphdr*>(&curPos[0]); unsigned int profileId = CProfile::ProfileIDForProtocol(ip, distance(curPos, data.end()), rtpDestinations); CProfile* profile = 0; // Do we have this connection already? contexts_t::iterator ctx = find_if(contexts.begin(), contexts.end(), ContextFinder(profileId, ip)); if (contexts.end() == ctx) { // TODO find first null context for (ctx = contexts.begin(); contexts.end() != ctx; ++ctx) { if (!*ctx) break; } uint16_t cid = 0; if (ctx != contexts.end()) { cid = static_cast<uint16_t>(distance(contexts.begin(), ctx)); } else { if (contexts.size() <= maxCID) { cid = static_cast<uint16_t>(contexts.size()); contexts.push_back(0); } else { /** * We have to remove an old profile if we get here */ OldestContextFinder finder; ctx = min_element(contexts.begin(), contexts.end(), finder); cid = (*ctx)->CID(); delete *ctx; } } profile = CProfile::Create(this, cid, profileId, ip); contexts[cid] = profile; } else { profile = *ctx; } profile->SetLastUsed(millisSinceEpoch()); profile->Compress(data, output); ++numberOfPacketsSent; dataSizeUncompressed += data.size(); dataSizeCompressed += output.size() - outputInSize; } void Compressor::SendFeedback(const_data_iterator begin, const_data_iterator end) { ScopedLock lock(feedbackMutex); feedbackData.insert(feedbackData.end(), begin, end); } void Compressor::AppendFeedback(data_t& data) { ScopedLock lock(feedbackMutex); data.insert(data.end(), feedbackData.begin(), feedbackData.end()); feedbackData.clear(); } void Compressor::ReceivedFeedback1(uint16_t cid, uint8_t lsbMSN) { ScopedLock lock(feedbackMutex); receivedFeedback1.push_back(Feedback1(cid, lsbMSN)); } void Compressor::ReceivedFeedback2(uint16_t cid, uint16_t msn, ROHC::FBAckType_t ackType, const_data_iterator begin, const_data_iterator end) { ScopedLock lock(feedbackMutex); receivedFeedback2.push_back(Feedback2(cid, msn, ackType, begin, end)); } void Compressor::HandleReceivedFeedback() { ScopedLock lock(feedbackMutex); while(!receivedFeedback1.empty()) { const Feedback1& fb(receivedFeedback1.front()); if (fb.cid < contexts.size()) { CProfile* profile = contexts[fb.cid]; if (profile) { profile->AckLsbMsn(fb.lsbMSN); } } receivedFeedback1.pop_front(); } while(!receivedFeedback2.empty()) { const Feedback2& fb(receivedFeedback2.front()); if (fb.cid < contexts.size()) { CProfile* profile = contexts[fb.cid]; if (profile) { if (FB_ACK == fb.type) { profile->AckFBMsn(fb.msn14bit); } else if (FB_NACK == fb.type) { profile->NackMsn(fb.msn14bit); } else if (FB_STATIC_NACK == fb.type) { profile->StaticNackMsn(fb.msn14bit); } } } receivedFeedback2.pop_front(); } } void Compressor::addRTPDestinationPort(/*uint32_t daddr,*/ uint16_t dport) { rtpDestinations.push_back(RTPDestination(0, rohc_htons(dport))); } } // ns ROHC <commit_msg>fixed int to ptr cast<commit_after>#include <rohc/compressor.h> #include <rohc/lock.h> #include <rohc/log.h> #include "network.h" #include <rohc/rohc.h> #include "cprofile.h" #include <functional> #include <algorithm> #include <cstring> using namespace std; namespace { struct ContextFinder : public unary_function<const ROHC::CProfile*, bool> { ContextFinder(unsigned int profileID, const ROHC::iphdr* ip) : profileID(profileID), ip(ip) {} bool operator()(const ROHC::CProfile* profile) { return profile && profile->Matches(profileID, ip); } unsigned int profileID; const ROHC::iphdr* ip; }; struct OldestContextFinder : public binary_function<const ROHC::CProfile*, const ROHC::CProfile, bool> { bool operator()(const ROHC::CProfile* a, const ROHC::CProfile* b) { return a->LastUsed() < b->LastUsed(); } }; } // anon ns namespace ROHC { Compressor::Compressor(size_t maxCID, Reordering_t reorder_ratio, IPIDBehaviour_t ip_id_behaviour) : maxCID(maxCID) , contexts(0) , feedbackData(0) , feedbackMutex(allocMutex()) , reorder_ratio(reorder_ratio) , ip_id_behaviour(ip_id_behaviour) , numberOfPacketsSent(0) , dataSizeUncompressed(0) , dataSizeCompressed(0) { /** statistics */ numberOfPacketsSent = 0; dataSizeUncompressed = 0; dataSizeCompressed = 0; memset(statistics, 0, sizeof(statistics)); } Compressor::~Compressor() { for (contexts_t::iterator i = contexts.begin(); contexts.end() != i; ++i) { delete *i; } freeMutex(feedbackMutex); } void Compressor::compress(const uint8_t* data, size_t size, data_t& output) { data_t d(data, data + size); compress(d, output); } void Compressor::compress(const data_t& data, data_t& output) { output.reserve(data.size()); // Take care of received feedback HandleReceivedFeedback(); size_t outputInSize = output.size(); size_t feedbackSize = feedbackData.size(); if (feedbackSize) { ScopedLock lock(feedbackMutex); // Add feedback data (if exists) output.insert(output.end(), feedbackData.begin(), feedbackData.end()); feedbackData.clear(); } if (data.size() < sizeof(iphdr)) { error("Not enough data for an IP header\n"); return; } vector<uint8_t>::const_iterator curPos = data.begin(); const iphdr* ip = reinterpret_cast<const iphdr*>(&curPos[0]); unsigned int profileId = CProfile::ProfileIDForProtocol(ip, distance(curPos, data.end()), rtpDestinations); CProfile* profile = 0; // Do we have this connection already? contexts_t::iterator ctx = find_if(contexts.begin(), contexts.end(), ContextFinder(profileId, ip)); if (contexts.end() == ctx) { // TODO find first null context for (ctx = contexts.begin(); contexts.end() != ctx; ++ctx) { if (!*ctx) break; } uint16_t cid = 0; if (ctx != contexts.end()) { cid = static_cast<uint16_t>(distance(contexts.begin(), ctx)); } else { if (contexts.size() <= maxCID) { cid = static_cast<uint16_t>(contexts.size()); contexts.push_back(static_cast<CProfile*>(0)); } else { /** * We have to remove an old profile if we get here */ OldestContextFinder finder; ctx = min_element(contexts.begin(), contexts.end(), finder); cid = (*ctx)->CID(); delete *ctx; } } profile = CProfile::Create(this, cid, profileId, ip); contexts[cid] = profile; } else { profile = *ctx; } profile->SetLastUsed(millisSinceEpoch()); profile->Compress(data, output); ++numberOfPacketsSent; dataSizeUncompressed += data.size(); dataSizeCompressed += output.size() - outputInSize; } void Compressor::SendFeedback(const_data_iterator begin, const_data_iterator end) { ScopedLock lock(feedbackMutex); feedbackData.insert(feedbackData.end(), begin, end); } void Compressor::AppendFeedback(data_t& data) { ScopedLock lock(feedbackMutex); data.insert(data.end(), feedbackData.begin(), feedbackData.end()); feedbackData.clear(); } void Compressor::ReceivedFeedback1(uint16_t cid, uint8_t lsbMSN) { ScopedLock lock(feedbackMutex); receivedFeedback1.push_back(Feedback1(cid, lsbMSN)); } void Compressor::ReceivedFeedback2(uint16_t cid, uint16_t msn, ROHC::FBAckType_t ackType, const_data_iterator begin, const_data_iterator end) { ScopedLock lock(feedbackMutex); receivedFeedback2.push_back(Feedback2(cid, msn, ackType, begin, end)); } void Compressor::HandleReceivedFeedback() { ScopedLock lock(feedbackMutex); while(!receivedFeedback1.empty()) { const Feedback1& fb(receivedFeedback1.front()); if (fb.cid < contexts.size()) { CProfile* profile = contexts[fb.cid]; if (profile) { profile->AckLsbMsn(fb.lsbMSN); } } receivedFeedback1.pop_front(); } while(!receivedFeedback2.empty()) { const Feedback2& fb(receivedFeedback2.front()); if (fb.cid < contexts.size()) { CProfile* profile = contexts[fb.cid]; if (profile) { if (FB_ACK == fb.type) { profile->AckFBMsn(fb.msn14bit); } else if (FB_NACK == fb.type) { profile->NackMsn(fb.msn14bit); } else if (FB_STATIC_NACK == fb.type) { profile->StaticNackMsn(fb.msn14bit); } } } receivedFeedback2.pop_front(); } } void Compressor::addRTPDestinationPort(/*uint32_t daddr,*/ uint16_t dport) { rtpDestinations.push_back(RTPDestination(0, rohc_htons(dport))); } } // ns ROHC <|endoftext|>
<commit_before> #include "connection.hpp" Connection::Connection() : mode(SERVER) { socket.bind(GAME_PORT); socket.setBlocking(false); } Connection::Connection(Mode mode) : mode(mode) { socket.bind(GAME_PORT); socket.setBlocking(false); } Connection::~Connection() { } void Connection::update(sf::Time dt) { if(mode == SERVER) { // check if clients have timed out std::list<sf::Uint32> disconnectQueue; for(auto iter = elapsedTimeMap.begin(); iter != elapsedTimeMap.end(); ++iter) { if(iter->second.getElapsedTime().asMilliseconds() >= CONNECTION_TIMEOUT_MILLISECONDS) { disconnectQueue.push_front(iter->first); } } for(auto iter = disconnectQueue.begin(); iter != disconnectQueue.end(); ++iter) { #ifndef NDEBUG std::cout << "Disconnected " << sf::IpAddress(*iter).toString() << '\n'; #endif unregisterConnection(*iter); } // heartbeat packet for(auto tIter = heartbeatTimeMap.begin(); tIter != heartbeatTimeMap.end(); ++tIter) { tIter->second += dt; if(tIter->second.asMilliseconds() >= HEARTBEAT_MILLISECONDS) { tIter->second = sf::milliseconds(0); heartbeat(tIter->first); } } // send packet if(!sendPacketQueue.empty()) { auto pInfo = sendPacketQueue.back(); sendPacketQueue.pop_back(); heartbeatTimeMap[pInfo.address] = sf::milliseconds(0); sentPackets[pInfo.address].push_front(PacketInfo(pInfo.packet, pInfo.ID)); socket.send(pInfo.packet, sf::IpAddress(pInfo.address), GAME_PORT); checkSentPacketsSize(pInfo.address); } //TODO flow control // receive packet sf::Packet packet; sf::IpAddress address; unsigned short remotePort; sf::Socket::Status status = socket.receive(packet, address, remotePort); if(status == sf::Socket::Done) { sf::Uint32 protocolID; if(!(packet >> protocolID)) return; // check protocol ID if(protocolID != GAME_PROTOCOL_ID) return; sf::Uint32 ID; sf::Uint32 sequence; sf::Uint32 ack; sf::Uint32 ackBitfield; if(!(packet >> ID) || !(packet >> sequence) || !(packet >> ack) || !(packet >> ackBitfield)) return; if(ID == network::CONNECT) { if(IDMap.find(address.toInteger()) == IDMap.end()) { // Establish connection registerConnection(address.toInteger()); sf::Packet newPacket; sf::Uint32 sequenceID; preparePacket(newPacket, sequenceID, address); sendPacket(newPacket, sequenceID, address); } return; } else if(IDMap.find(address.toInteger()) == IDMap.end()) { // Unknown client not attemping to connect, ignoring return; } else if(ID != IDMap[address.toInteger()]) { // ID and address doesn't match, ignoring return; } // packet is valid #ifndef NDEBUG std::cout << "Valid packet received from " << address.toString() << '\n'; #endif sf::Uint32 clientAddress = address.toInteger(); lookupRtt(clientAddress, ack); elapsedTimeMap[clientAddress].restart(); checkSentPackets(ack, ackBitfield, clientAddress); sf::Uint32 diff = 0; if(sequence > rSequenceMap[clientAddress]) { diff = sequence - rSequenceMap[clientAddress]; if(diff <= 0x7FFFFFFF) { // sequence is more recent rSequenceMap[clientAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[clientAddress]) + 1; if((ackBitfieldMap[clientAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[clientAddress] |= (0x100000000 >> diff); } } else if(rSequenceMap[clientAddress] > sequence) { diff = rSequenceMap[clientAddress] - sequence; if(diff > 0x7FFFFFFF) { // sequence is more recent, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[clientAddress]) + 1; rSequenceMap[clientAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id if((ackBitfieldMap[clientAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[clientAddress] |= (0x100000000 >> diff); } } else { // duplicate packet, ignoring return; } receivedPacket(packet); } } // if(mode == SERVER) else if(mode == CLIENT) { // connection established if(IDMap.size() > 0) { sf::Uint32 serverAddress = clientSentAddress.toInteger(); // check if timed out sf::Time elapsedTime = elapsedTimeMap[serverAddress].getElapsedTime(); if(elapsedTime.asMilliseconds() > CONNECTION_TIMEOUT_MILLISECONDS) { unregisterConnection(serverAddress); return; } // heartbeat heartbeatTimeMap[serverAddress] += dt; if(heartbeatTimeMap[serverAddress].asMilliseconds() >= HEARTBEAT_MILLISECONDS) { heartbeatTimeMap[serverAddress] = sf::milliseconds(0); heartbeat(serverAddress); } // send if(!sendPacketQueue.empty()) { PacketInfo pInfo = sendPacketQueue.back(); sendPacketQueue.pop_back(); sentPackets[serverAddress].push_front(PacketInfo(pInfo.packet, pInfo.ID)); socket.send(pInfo.packet, sf::IpAddress(pInfo.address), GAME_PORT); checkSentPacketsSize(serverAddress); } //TODO flow control // receive sf::Packet packet; sf::IpAddress address; unsigned short port; sf::Socket::Status status; status = socket.receive(packet, address, port); if(status == sf::Socket::Done && address == clientSentAddress) { sf::Uint32 protocolID; if(!(packet >> protocolID)) return; if(protocolID != GAME_PROTOCOL_ID) return; sf::Uint32 ID; sf::Uint32 sequence; sf::Uint32 ack; sf::Uint32 bitfield; if(!(packet >> ID) || !(packet >> sequence) || !(packet >> ack) || !(packet >> bitfield)) return; if(ID != IDMap[serverAddress]) return; // packet is valid #ifndef NDEBUG std::cout << "Valid packet received from " << address.toString() << '\n'; #endif lookupRtt(serverAddress, ack); elapsedTimeMap[serverAddress].restart(); checkSentPackets(ack, bitfield, serverAddress); sf::Uint32 diff = 0; if(sequence > rSequenceMap[serverAddress]) { diff = sequence - rSequenceMap[serverAddress]; if(diff <= 0x7FFFFFFF) { // sequence is more recent rSequenceMap[serverAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[serverAddress]) + 1; if((ackBitfieldMap[serverAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[serverAddress] |= (0x100000000 >> diff); } } else if(rSequenceMap[serverAddress] > sequence) { diff = rSequenceMap[serverAddress] - sequence; if(diff > 0x7FFFFFFF) { // sequence is more recent, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[serverAddress]) + 1; rSequenceMap[serverAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id if((ackBitfieldMap[serverAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[serverAddress] |= (0x100000000 >> diff); } } else { // duplicate packet, ignoring return; } receivedPacket(packet); } } // connection not yet established else { // receive sf::Packet packet; sf::IpAddress address; unsigned short port; sf::Socket::Status status; status = socket.receive(packet, address, port); if(status == sf::Socket::Done && address == clientSentAddress) { sf::Uint32 protocolID; if(!(packet >> protocolID)) return; if(protocolID != GAME_PROTOCOL_ID) return; sf::Uint32 ID; sf::Uint32 sequence; sf::Uint32 ack; sf::Uint32 bitfield; if(!(packet >> ID) || !(packet >> sequence) || !(packet >> ack) || !(packet >> bitfield)) return; registerConnection(address.toInteger(), ID); } } } // elif(mode == CLIENT) } void Connection::connectToServer(sf::IpAddress address) { sf::Packet packet; packet << (sf::Uint32) GAME_PROTOCOL_ID << (sf::Uint32) network::CONNECT << (sf::Uint32) 0 << (sf::Uint32) 0 << (sf::Uint32) 0xFFFFFFFF; socket.send(packet, address, GAME_PORT); clientSentAddress = address; } void Connection::preparePacket(sf::Packet& packet, sf::Uint32& sequenceID, sf::IpAddress address) { sf::Uint32 intAddress = address.toInteger(); auto iter = IDMap.find(intAddress); assert(iter == IDMap.end()); sf::Uint32 ID = iter->second; sequenceID = lSequenceMap[intAddress]++; sf::Uint32 ack = rSequenceMap[intAddress]; sf::Uint32 ackBitfield = ackBitfieldMap[intAddress]; packet << (sf::Uint32) GAME_PROTOCOL_ID << ID << sequenceID << ack << ackBitfield; } void Connection::sendPacket(sf::Packet& packet, sf::Uint32 sequenceID, sf::IpAddress address) { sendPacketQueue.push_front(PacketInfo(packet, sequenceID, address.toInteger())); } void Connection::receivedPacket(sf::Packet packet) {} void Connection::registerConnection(sf::Uint32 address, sf::Uint32 ID) { heartbeatTimeMap.insert(std::make_pair(address, sf::Time())); elapsedTimeMap.insert(std::make_pair(address, sf::Clock())); if(mode == SERVER) { IDMap.insert(std::make_pair(address, generateID())); lSequenceMap.insert(std::make_pair(address, (sf::Uint32) 0)); } else if(mode == CLIENT) { IDMap.insert(std::make_pair(address, ID)); lSequenceMap.insert(std::make_pair(address, (sf::Uint32) 1)); } rSequenceMap.insert(std::make_pair(address, (sf::Uint32) 0)); ackBitfieldMap.insert(std::make_pair(address, (sf::Uint32) 0xFFFFFFFF)); sentPackets.insert(std::make_pair(address, std::list<PacketInfo>())); rttMap.insert(std::make_pair(address, sf::Time())); } void Connection::unregisterConnection(sf::Uint32 address) { heartbeatTimeMap.erase(address); elapsedTimeMap.erase(address); IDMap.erase(address); lSequenceMap.erase(address); rSequenceMap.erase(address); ackBitfieldMap.erase(address); sentPackets.erase(address); rttMap.erase(address); } void Connection::shiftBitfield(sf::IpAddress address, sf::Uint32 diff) { ackBitfieldMap[address.toInteger()] = (ackBitfieldMap[address.toInteger()] >> diff) | (0x100000000 >> diff); } void Connection::checkSentPackets(sf::Uint32 ack, sf::Uint32 bitfield, sf::Uint32 address) { --ack; for(; bitfield != 0x0; bitfield = bitfield << 1) { // if received, don't bother checking if((0x80000000 & bitfield) != 0x0) { --ack; continue; } // not received by client yet, checking if packet timed out for(auto iter = sentPackets[address].begin(); iter != sentPackets[address].end(); ++iter) { if(iter->ID == ack) { // timed out, adding to send queue if(iter->sentTime.getElapsedTime() >= sf::milliseconds(PACKET_LOST_TIMEOUT_MILLISECONDS)) { sf::Packet packetCopy = iter->packet; sf::Uint32 sequenceID; packetCopy >> sequenceID; // protocol ID packetCopy >> sequenceID; // ID of client packetCopy >> sequenceID; // sequence ID sendPacket(iter->packet, sequenceID, sf::IpAddress(address)); } break; } } --ack; } } void Connection::heartbeat(sf::Uint32 addressInteger) { sf::IpAddress address(addressInteger); sf::Packet packet; sf::Uint32 sequenceID; preparePacket(packet, sequenceID, address); sendPacket(packet, sequenceID, address); } void Connection::lookupRtt(sf::Uint32 address, sf::Uint32 ack) { for(auto iter = sentPackets[address].begin(); iter != sentPackets[address].end(); ++iter) { if(iter->ID == ack) { sf::Time time = iter->sentTime.getElapsedTime(); if(time > rttMap[address]) { rttMap[address] += (time - rttMap[address]) * 0.1f; } else { rttMap[address] += (rttMap[address] - time) * 0.1f; } #ifndef NDEBUG std::cout << "RTT of " << sf::IpAddress(address).toString() << " = " << rttMap[address].asMilliseconds() << '\n'; #endif break; } } } void Connection::checkSentPacketsSize(sf::Uint32 address) { while(sentPackets[address].size() > SENT_PACKET_LIST_MAX_SIZE) { sentPackets[address].pop_back(); } } sf::Uint32 Connection::generateID() { sf::Uint32 id; do { id = dist(rd); } while (network::isSpecialID(id)); return id; } <commit_msg>Added some debug logs.<commit_after> #include "connection.hpp" Connection::Connection() : mode(SERVER) { socket.bind(GAME_PORT); socket.setBlocking(false); } Connection::Connection(Mode mode) : mode(mode) { socket.bind(GAME_PORT); socket.setBlocking(false); } Connection::~Connection() { } void Connection::update(sf::Time dt) { if(mode == SERVER) { // check if clients have timed out std::list<sf::Uint32> disconnectQueue; for(auto iter = elapsedTimeMap.begin(); iter != elapsedTimeMap.end(); ++iter) { if(iter->second.getElapsedTime().asMilliseconds() >= CONNECTION_TIMEOUT_MILLISECONDS) { disconnectQueue.push_front(iter->first); } } for(auto iter = disconnectQueue.begin(); iter != disconnectQueue.end(); ++iter) { #ifndef NDEBUG std::cout << "Disconnected " << sf::IpAddress(*iter).toString() << '\n'; #endif unregisterConnection(*iter); } // heartbeat packet for(auto tIter = heartbeatTimeMap.begin(); tIter != heartbeatTimeMap.end(); ++tIter) { tIter->second += dt; if(tIter->second.asMilliseconds() >= HEARTBEAT_MILLISECONDS) { tIter->second = sf::milliseconds(0); heartbeat(tIter->first); } } // send packet if(!sendPacketQueue.empty()) { auto pInfo = sendPacketQueue.back(); sendPacketQueue.pop_back(); heartbeatTimeMap[pInfo.address] = sf::milliseconds(0); sentPackets[pInfo.address].push_front(PacketInfo(pInfo.packet, pInfo.ID)); socket.send(pInfo.packet, sf::IpAddress(pInfo.address), GAME_PORT); checkSentPacketsSize(pInfo.address); } //TODO flow control // receive packet sf::Packet packet; sf::IpAddress address; unsigned short remotePort; sf::Socket::Status status = socket.receive(packet, address, remotePort); if(status == sf::Socket::Done) { sf::Uint32 protocolID; if(!(packet >> protocolID)) return; // check protocol ID if(protocolID != GAME_PROTOCOL_ID) return; sf::Uint32 ID; sf::Uint32 sequence; sf::Uint32 ack; sf::Uint32 ackBitfield; if(!(packet >> ID) || !(packet >> sequence) || !(packet >> ack) || !(packet >> ackBitfield)) return; if(ID == network::CONNECT) { if(IDMap.find(address.toInteger()) == IDMap.end()) { #ifndef NDEBUG std::cout << "SERVER: Establishing new connection with " << address.toString() << '\n'; #endif // Establish connection registerConnection(address.toInteger()); sf::Packet newPacket; sf::Uint32 sequenceID; preparePacket(newPacket, sequenceID, address); sendPacket(newPacket, sequenceID, address); } return; } else if(IDMap.find(address.toInteger()) == IDMap.end()) { // Unknown client not attemping to connect, ignoring return; } else if(ID != IDMap[address.toInteger()]) { // ID and address doesn't match, ignoring return; } // packet is valid #ifndef NDEBUG std::cout << "Valid packet received from " << address.toString() << '\n'; #endif sf::Uint32 clientAddress = address.toInteger(); lookupRtt(clientAddress, ack); elapsedTimeMap[clientAddress].restart(); checkSentPackets(ack, ackBitfield, clientAddress); sf::Uint32 diff = 0; if(sequence > rSequenceMap[clientAddress]) { diff = sequence - rSequenceMap[clientAddress]; if(diff <= 0x7FFFFFFF) { // sequence is more recent rSequenceMap[clientAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[clientAddress]) + 1; if((ackBitfieldMap[clientAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[clientAddress] |= (0x100000000 >> diff); } } else if(rSequenceMap[clientAddress] > sequence) { diff = rSequenceMap[clientAddress] - sequence; if(diff > 0x7FFFFFFF) { // sequence is more recent, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[clientAddress]) + 1; rSequenceMap[clientAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id if((ackBitfieldMap[clientAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[clientAddress] |= (0x100000000 >> diff); } } else { // duplicate packet, ignoring return; } receivedPacket(packet); } } // if(mode == SERVER) else if(mode == CLIENT) { // connection established if(IDMap.size() > 0) { sf::Uint32 serverAddress = clientSentAddress.toInteger(); // check if timed out sf::Time elapsedTime = elapsedTimeMap[serverAddress].getElapsedTime(); if(elapsedTime.asMilliseconds() > CONNECTION_TIMEOUT_MILLISECONDS) { unregisterConnection(serverAddress); return; } // heartbeat heartbeatTimeMap[serverAddress] += dt; if(heartbeatTimeMap[serverAddress].asMilliseconds() >= HEARTBEAT_MILLISECONDS) { heartbeatTimeMap[serverAddress] = sf::milliseconds(0); heartbeat(serverAddress); } // send if(!sendPacketQueue.empty()) { PacketInfo pInfo = sendPacketQueue.back(); sendPacketQueue.pop_back(); sentPackets[serverAddress].push_front(PacketInfo(pInfo.packet, pInfo.ID)); socket.send(pInfo.packet, sf::IpAddress(pInfo.address), GAME_PORT); checkSentPacketsSize(serverAddress); } //TODO flow control // receive sf::Packet packet; sf::IpAddress address; unsigned short port; sf::Socket::Status status; status = socket.receive(packet, address, port); if(status == sf::Socket::Done && address == clientSentAddress) { sf::Uint32 protocolID; if(!(packet >> protocolID)) return; if(protocolID != GAME_PROTOCOL_ID) return; sf::Uint32 ID; sf::Uint32 sequence; sf::Uint32 ack; sf::Uint32 bitfield; if(!(packet >> ID) || !(packet >> sequence) || !(packet >> ack) || !(packet >> bitfield)) return; if(ID != IDMap[serverAddress]) return; // packet is valid #ifndef NDEBUG std::cout << "Valid packet received from " << address.toString() << '\n'; #endif lookupRtt(serverAddress, ack); elapsedTimeMap[serverAddress].restart(); checkSentPackets(ack, bitfield, serverAddress); sf::Uint32 diff = 0; if(sequence > rSequenceMap[serverAddress]) { diff = sequence - rSequenceMap[serverAddress]; if(diff <= 0x7FFFFFFF) { // sequence is more recent rSequenceMap[serverAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[serverAddress]) + 1; if((ackBitfieldMap[serverAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[serverAddress] |= (0x100000000 >> diff); } } else if(rSequenceMap[serverAddress] > sequence) { diff = rSequenceMap[serverAddress] - sequence; if(diff > 0x7FFFFFFF) { // sequence is more recent, diff requires recalc diff = sequence + (0xFFFFFFFF - rSequenceMap[serverAddress]) + 1; rSequenceMap[serverAddress] = sequence; shiftBitfield(address, diff); } else { // sequence is older packet id if((ackBitfieldMap[serverAddress] & (0x100000000 >> diff)) != 0x0) { // already received packet return; } ackBitfieldMap[serverAddress] |= (0x100000000 >> diff); } } else { // duplicate packet, ignoring return; } receivedPacket(packet); } } // connection not yet established else { // receive sf::Packet packet; sf::IpAddress address; unsigned short port; sf::Socket::Status status; status = socket.receive(packet, address, port); if(status == sf::Socket::Done && address == clientSentAddress) { sf::Uint32 protocolID; if(!(packet >> protocolID)) return; if(protocolID != GAME_PROTOCOL_ID) return; sf::Uint32 ID; sf::Uint32 sequence; sf::Uint32 ack; sf::Uint32 bitfield; if(!(packet >> ID) || !(packet >> sequence) || !(packet >> ack) || !(packet >> bitfield)) return; registerConnection(address.toInteger(), ID); } } } // elif(mode == CLIENT) } void Connection::connectToServer(sf::IpAddress address) { #ifndef NDEBUG std::cout << "CLIENT: sending connection request to server at " << address.toString() << '\n'; #endif sf::Packet packet; packet << (sf::Uint32) GAME_PROTOCOL_ID << (sf::Uint32) network::CONNECT << (sf::Uint32) 0 << (sf::Uint32) 0 << (sf::Uint32) 0xFFFFFFFF; socket.send(packet, address, GAME_PORT); clientSentAddress = address; } void Connection::preparePacket(sf::Packet& packet, sf::Uint32& sequenceID, sf::IpAddress address) { sf::Uint32 intAddress = address.toInteger(); auto iter = IDMap.find(intAddress); assert(iter == IDMap.end()); sf::Uint32 ID = iter->second; sequenceID = lSequenceMap[intAddress]++; sf::Uint32 ack = rSequenceMap[intAddress]; sf::Uint32 ackBitfield = ackBitfieldMap[intAddress]; packet << (sf::Uint32) GAME_PROTOCOL_ID << ID << sequenceID << ack << ackBitfield; } void Connection::sendPacket(sf::Packet& packet, sf::Uint32 sequenceID, sf::IpAddress address) { sendPacketQueue.push_front(PacketInfo(packet, sequenceID, address.toInteger())); } void Connection::receivedPacket(sf::Packet packet) {} void Connection::registerConnection(sf::Uint32 address, sf::Uint32 ID) { heartbeatTimeMap.insert(std::make_pair(address, sf::Time())); elapsedTimeMap.insert(std::make_pair(address, sf::Clock())); if(mode == SERVER) { IDMap.insert(std::make_pair(address, generateID())); lSequenceMap.insert(std::make_pair(address, (sf::Uint32) 0)); } else if(mode == CLIENT) { IDMap.insert(std::make_pair(address, ID)); lSequenceMap.insert(std::make_pair(address, (sf::Uint32) 1)); } rSequenceMap.insert(std::make_pair(address, (sf::Uint32) 0)); ackBitfieldMap.insert(std::make_pair(address, (sf::Uint32) 0xFFFFFFFF)); sentPackets.insert(std::make_pair(address, std::list<PacketInfo>())); rttMap.insert(std::make_pair(address, sf::Time())); } void Connection::unregisterConnection(sf::Uint32 address) { heartbeatTimeMap.erase(address); elapsedTimeMap.erase(address); IDMap.erase(address); lSequenceMap.erase(address); rSequenceMap.erase(address); ackBitfieldMap.erase(address); sentPackets.erase(address); rttMap.erase(address); } void Connection::shiftBitfield(sf::IpAddress address, sf::Uint32 diff) { ackBitfieldMap[address.toInteger()] = (ackBitfieldMap[address.toInteger()] >> diff) | (0x100000000 >> diff); } void Connection::checkSentPackets(sf::Uint32 ack, sf::Uint32 bitfield, sf::Uint32 address) { --ack; for(; bitfield != 0x0; bitfield = bitfield << 1) { // if received, don't bother checking if((0x80000000 & bitfield) != 0x0) { --ack; continue; } // not received by client yet, checking if packet timed out for(auto iter = sentPackets[address].begin(); iter != sentPackets[address].end(); ++iter) { if(iter->ID == ack) { // timed out, adding to send queue if(iter->sentTime.getElapsedTime() >= sf::milliseconds(PACKET_LOST_TIMEOUT_MILLISECONDS)) { sf::Packet packetCopy = iter->packet; sf::Uint32 sequenceID; packetCopy >> sequenceID; // protocol ID packetCopy >> sequenceID; // ID of client packetCopy >> sequenceID; // sequence ID sendPacket(iter->packet, sequenceID, sf::IpAddress(address)); } break; } } --ack; } } void Connection::heartbeat(sf::Uint32 addressInteger) { sf::IpAddress address(addressInteger); sf::Packet packet; sf::Uint32 sequenceID; preparePacket(packet, sequenceID, address); sendPacket(packet, sequenceID, address); } void Connection::lookupRtt(sf::Uint32 address, sf::Uint32 ack) { for(auto iter = sentPackets[address].begin(); iter != sentPackets[address].end(); ++iter) { if(iter->ID == ack) { sf::Time time = iter->sentTime.getElapsedTime(); if(time > rttMap[address]) { rttMap[address] += (time - rttMap[address]) * 0.1f; } else { rttMap[address] += (rttMap[address] - time) * 0.1f; } #ifndef NDEBUG std::cout << "RTT of " << sf::IpAddress(address).toString() << " = " << rttMap[address].asMilliseconds() << '\n'; #endif break; } } } void Connection::checkSentPacketsSize(sf::Uint32 address) { while(sentPackets[address].size() > SENT_PACKET_LIST_MAX_SIZE) { sentPackets[address].pop_back(); } } sf::Uint32 Connection::generateID() { sf::Uint32 id; do { id = dist(rd); } while (network::isSpecialID(id)); return id; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright © 2003 Jason Kivlighn <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "rezkonvimporter.h" #include <kapplication.h> #include <klocale.h> #include <kdebug.h> #include <QFile> #include <QRegExp> #include <QTextStream> #include "datablocks/mixednumber.h" RezkonvImporter::RezkonvImporter() : BaseImporter() {} RezkonvImporter::~RezkonvImporter() {} void RezkonvImporter::parseFile( const QString &filename ) { QFile input( filename ); if ( input.open( QIODevice::ReadOnly ) ) { QTextStream stream( &input ); stream.skipWhiteSpace(); QString line; while ( !stream.atEnd() ) { line = stream.readLine(); if ( line.contains( QRegExp( "^=====.*REZKONV.*", Qt::CaseInsensitive ) ) ) { QStringList raw_recipe; while ( !( line = stream.readLine() ).contains( QRegExp( "^=====\\s*$" ) ) && !stream.atEnd() ) raw_recipe << line; readRecipe( raw_recipe ); } } if ( fileRecipeCount() == 0 ) setErrorMsg( i18n( "No recipes found in this file." ) ); } else setErrorMsg( i18n( "Unable to open file." ) ); } void RezkonvImporter::readRecipe( const QStringList &raw_recipe ) { kapp->processEvents(); //don't want the user to think its frozen... especially for files with thousands of recipes Recipe recipe; QStringList::const_iterator text_it = raw_recipe.begin(); m_end_it = raw_recipe.end(); //title (Titel) text_it++; recipe.title = ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).trimmed(); kDebug() << "Found title: " << recipe.title ; //categories (Kategorien): text_it++; QStringList categories; if ( ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).isEmpty() ) categories = QStringList(); else categories = ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).split( ',', QString::SkipEmptyParts ); for ( QStringList::const_iterator it = categories.constBegin(); it != categories.constEnd(); ++it ) { Element new_cat; new_cat.name = QString( *it ).trimmed(); kDebug() << "Found category: " << new_cat.name ; recipe.categoryList.append( new_cat ); } //yield (Menge) text_it++; //get the number between the ":" and the next space after it QString yield_str = ( *text_it ).trimmed(); yield_str.remove( QRegExp( "^Menge:\\s*" ) ); int sep_index = yield_str.indexOf( ' ' ); if ( sep_index != -1 ) recipe.yield.type = yield_str.mid( sep_index+1 ); readRange( yield_str.mid( 0, sep_index ), recipe.yield.amount, recipe.yield.amount_offset ); kDebug() << "Found yield: " << recipe.yield.amount ; bool is_sub = false; bool last_line_empty = false; text_it++; while ( text_it != raw_recipe.end() ) { if ( ( *text_it ).isEmpty() ) { last_line_empty = true; text_it++; continue; } if ( ( *text_it ).contains( QRegExp( "^=====.*=$" ) ) ) //is a header { if ( ( *text_it ).contains( "quelle", Qt::CaseInsensitive ) ) { loadReferences( text_it, recipe ); break; //reference lines are the last before the instructions } else loadIngredientHeader( *text_it, recipe ); } //if it has no more than two spaces followed by a non-digit //then we'll assume it is a direction line else if ( last_line_empty && ( *text_it ).contains( QRegExp( "^\\s{0,2}[^\\d\\s=]" ) ) ) break; else loadIngredient( *text_it, recipe, is_sub ); last_line_empty = false; text_it++; } loadInstructions( text_it, recipe ); add ( recipe ); current_header = QString(); } void RezkonvImporter::loadIngredient( const QString &string, Recipe &recipe, bool &is_sub ) { Ingredient new_ingredient; new_ingredient.amount = 0; //amount not required, so give default of 0 QRegExp cont_test( "^-{1,2}" ); if ( string.trimmed().contains( cont_test ) ) { QString name = string.trimmed(); name.remove( cont_test ); kDebug() << "Appending to last ingredient: " << name ; if ( !recipe.ingList.isEmpty() ) //so it doesn't crash when the first ingredient appears to be a continuation of another recipe.ingList.last().name += ' ' + name; return ; } //amount if ( !string.mid( 0, 7 ).trimmed().isEmpty() ) readRange( string.mid( 0, 7 ), new_ingredient.amount, new_ingredient.amount_offset ); //unit QString unit_str = string.mid( 8, 9 ).trimmed(); new_ingredient.units = Unit( unit_str, new_ingredient.amount ); //name and preparation method new_ingredient.name = string.mid( 18, string.length() - 18 ).trimmed(); //separate out the preparation method QString name_and_prep = new_ingredient.name; int separator_index = name_and_prep.indexOf( "," ); if ( separator_index != -1 ) { new_ingredient.name = name_and_prep.mid( 0, separator_index ).trimmed(); new_ingredient.prepMethodList = ElementList::split(",",name_and_prep.mid( separator_index + 1, name_and_prep.length() ).trimmed() ); } //header (if present) new_ingredient.group = current_header; bool last_is_sub = is_sub; if ( !new_ingredient.prepMethodList.isEmpty() && new_ingredient.prepMethodList.last().name == "or" ) { new_ingredient.prepMethodList.pop_back(); is_sub = true; } else is_sub = false; if ( last_is_sub ) recipe.ingList.last().substitutes.append(new_ingredient); else recipe.ingList.append( new_ingredient ); } void RezkonvImporter::loadIngredientHeader( const QString &string, Recipe &/*recipe*/ ) { QString header = string; header.remove( QRegExp( "^=*" ) ).remove( QRegExp( "=*$" ) ); header = header.trimmed(); kDebug() << "found ingredient header: " << header ; current_header = header; } void RezkonvImporter::loadInstructions( QStringList::const_iterator &text_it, Recipe &recipe ) { QString instr; QRegExp rx_title( "^:{0,1}\\s*O-Titel\\s*:" ); QString line; text_it++; while ( text_it != m_end_it ) { line = *text_it; //titles longer than the line width are rewritten here if ( line.contains( rx_title ) ) { line.remove( rx_title ); recipe.title = line.trimmed(); QRegExp rx_line_cont( ":\\s*>{0,1}\\s*:" ); while ( ( line = *text_it ).contains( rx_line_cont ) ) { line.remove( rx_line_cont ); recipe.title += line; text_it++; } kDebug() << "Found long title: " << recipe.title ; } else { if ( line.trimmed().isEmpty() && ( (text_it+1) != m_end_it ) ) instr += "\n\n"; instr += line.trimmed(); } text_it++; } recipe.instructions = instr; } void RezkonvImporter::loadReferences( QStringList::const_iterator &text_it, Recipe &recipe ) { kDebug() << "Found source header" ; text_it++; while ( text_it != m_end_it && !text_it->trimmed().isEmpty() ) { QRegExp rx_line_begin( "^\\s*-{0,2}\\s*" ); QRegExp rx_creation_date = QRegExp( "^\\s*-{0,2}\\s*Erfasst \\*RK\\*", Qt::CaseInsensitive ); if ( ( *text_it ).contains( rx_creation_date ) ) // date followed by typist { QString date = *text_it; date.remove( rx_creation_date ).remove( QRegExp( " von\\s*$" ) ); // Date is given as DD.MM.YY QString s = date.section( '.', 0, 0 ); int day = s.toInt(); s = date.section( '.', 1, 1 ); int month = s.toInt(); s = date.section( '.', 2, 2 ); int year = s.toInt(); year += 1900; if ( year < 1970 ) year += 100; //we'll assume nothing has been created before 1970 (y2k issues :p) recipe.ctime = QDateTime(QDate(year,month,day)); #if 0 //typist text_it++; QString typist = = *text_it; typist.remove( rx_line_begin ); #endif } else //everything else is an author { if ( ( *text_it ).contains( rx_line_begin ) ) { QString author = *text_it; author.remove( rx_line_begin ); recipe.authorList.append( Element( author ) ); } else break; } text_it++; } } void RezkonvImporter::readRange( const QString &range_str, double &amount, double &amount_offset ) { QString from = range_str.section( '-', 0, 0 ); QString to = range_str.section( '-', 1, 1 ); amount = MixedNumber::fromString( from ).toDouble(); if ( !to.trimmed().isEmpty() ) amount_offset = MixedNumber::fromString( to ).toDouble() - amount; } <commit_msg>Fix Krazy warnings: nullstrassign - src/widgets/rezkonvimporter.cpp<commit_after>/*************************************************************************** * Copyright © 2003 Jason Kivlighn <[email protected]> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * ***************************************************************************/ #include "rezkonvimporter.h" #include <kapplication.h> #include <klocale.h> #include <kdebug.h> #include <QFile> #include <QRegExp> #include <QTextStream> #include "datablocks/mixednumber.h" RezkonvImporter::RezkonvImporter() : BaseImporter() {} RezkonvImporter::~RezkonvImporter() {} void RezkonvImporter::parseFile( const QString &filename ) { QFile input( filename ); if ( input.open( QIODevice::ReadOnly ) ) { QTextStream stream( &input ); stream.skipWhiteSpace(); QString line; while ( !stream.atEnd() ) { line = stream.readLine(); if ( line.contains( QRegExp( "^=====.*REZKONV.*", Qt::CaseInsensitive ) ) ) { QStringList raw_recipe; while ( !( line = stream.readLine() ).contains( QRegExp( "^=====\\s*$" ) ) && !stream.atEnd() ) raw_recipe << line; readRecipe( raw_recipe ); } } if ( fileRecipeCount() == 0 ) setErrorMsg( i18n( "No recipes found in this file." ) ); } else setErrorMsg( i18n( "Unable to open file." ) ); } void RezkonvImporter::readRecipe( const QStringList &raw_recipe ) { kapp->processEvents(); //don't want the user to think its frozen... especially for files with thousands of recipes Recipe recipe; QStringList::const_iterator text_it = raw_recipe.begin(); m_end_it = raw_recipe.end(); //title (Titel) text_it++; recipe.title = ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).trimmed(); kDebug() << "Found title: " << recipe.title ; //categories (Kategorien): text_it++; QStringList categories; if ( ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).isEmpty() ) categories = QStringList(); else categories = ( *text_it ).mid( ( *text_it ).indexOf( ":" ) + 1, ( *text_it ).length() ).split( ',', QString::SkipEmptyParts ); for ( QStringList::const_iterator it = categories.constBegin(); it != categories.constEnd(); ++it ) { Element new_cat; new_cat.name = QString( *it ).trimmed(); kDebug() << "Found category: " << new_cat.name ; recipe.categoryList.append( new_cat ); } //yield (Menge) text_it++; //get the number between the ":" and the next space after it QString yield_str = ( *text_it ).trimmed(); yield_str.remove( QRegExp( "^Menge:\\s*" ) ); int sep_index = yield_str.indexOf( ' ' ); if ( sep_index != -1 ) recipe.yield.type = yield_str.mid( sep_index+1 ); readRange( yield_str.mid( 0, sep_index ), recipe.yield.amount, recipe.yield.amount_offset ); kDebug() << "Found yield: " << recipe.yield.amount ; bool is_sub = false; bool last_line_empty = false; text_it++; while ( text_it != raw_recipe.end() ) { if ( ( *text_it ).isEmpty() ) { last_line_empty = true; text_it++; continue; } if ( ( *text_it ).contains( QRegExp( "^=====.*=$" ) ) ) //is a header { if ( ( *text_it ).contains( "quelle", Qt::CaseInsensitive ) ) { loadReferences( text_it, recipe ); break; //reference lines are the last before the instructions } else loadIngredientHeader( *text_it, recipe ); } //if it has no more than two spaces followed by a non-digit //then we'll assume it is a direction line else if ( last_line_empty && ( *text_it ).contains( QRegExp( "^\\s{0,2}[^\\d\\s=]" ) ) ) break; else loadIngredient( *text_it, recipe, is_sub ); last_line_empty = false; text_it++; } loadInstructions( text_it, recipe ); add ( recipe ); current_header.clear(); } void RezkonvImporter::loadIngredient( const QString &string, Recipe &recipe, bool &is_sub ) { Ingredient new_ingredient; new_ingredient.amount = 0; //amount not required, so give default of 0 QRegExp cont_test( "^-{1,2}" ); if ( string.trimmed().contains( cont_test ) ) { QString name = string.trimmed(); name.remove( cont_test ); kDebug() << "Appending to last ingredient: " << name ; if ( !recipe.ingList.isEmpty() ) //so it doesn't crash when the first ingredient appears to be a continuation of another recipe.ingList.last().name += ' ' + name; return ; } //amount if ( !string.mid( 0, 7 ).trimmed().isEmpty() ) readRange( string.mid( 0, 7 ), new_ingredient.amount, new_ingredient.amount_offset ); //unit QString unit_str = string.mid( 8, 9 ).trimmed(); new_ingredient.units = Unit( unit_str, new_ingredient.amount ); //name and preparation method new_ingredient.name = string.mid( 18, string.length() - 18 ).trimmed(); //separate out the preparation method QString name_and_prep = new_ingredient.name; int separator_index = name_and_prep.indexOf( "," ); if ( separator_index != -1 ) { new_ingredient.name = name_and_prep.mid( 0, separator_index ).trimmed(); new_ingredient.prepMethodList = ElementList::split(",",name_and_prep.mid( separator_index + 1, name_and_prep.length() ).trimmed() ); } //header (if present) new_ingredient.group = current_header; bool last_is_sub = is_sub; if ( !new_ingredient.prepMethodList.isEmpty() && new_ingredient.prepMethodList.last().name == "or" ) { new_ingredient.prepMethodList.pop_back(); is_sub = true; } else is_sub = false; if ( last_is_sub ) recipe.ingList.last().substitutes.append(new_ingredient); else recipe.ingList.append( new_ingredient ); } void RezkonvImporter::loadIngredientHeader( const QString &string, Recipe &/*recipe*/ ) { QString header = string; header.remove( QRegExp( "^=*" ) ).remove( QRegExp( "=*$" ) ); header = header.trimmed(); kDebug() << "found ingredient header: " << header ; current_header = header; } void RezkonvImporter::loadInstructions( QStringList::const_iterator &text_it, Recipe &recipe ) { QString instr; QRegExp rx_title( "^:{0,1}\\s*O-Titel\\s*:" ); QString line; text_it++; while ( text_it != m_end_it ) { line = *text_it; //titles longer than the line width are rewritten here if ( line.contains( rx_title ) ) { line.remove( rx_title ); recipe.title = line.trimmed(); QRegExp rx_line_cont( ":\\s*>{0,1}\\s*:" ); while ( ( line = *text_it ).contains( rx_line_cont ) ) { line.remove( rx_line_cont ); recipe.title += line; text_it++; } kDebug() << "Found long title: " << recipe.title ; } else { if ( line.trimmed().isEmpty() && ( (text_it+1) != m_end_it ) ) instr += "\n\n"; instr += line.trimmed(); } text_it++; } recipe.instructions = instr; } void RezkonvImporter::loadReferences( QStringList::const_iterator &text_it, Recipe &recipe ) { kDebug() << "Found source header" ; text_it++; while ( text_it != m_end_it && !text_it->trimmed().isEmpty() ) { QRegExp rx_line_begin( "^\\s*-{0,2}\\s*" ); QRegExp rx_creation_date = QRegExp( "^\\s*-{0,2}\\s*Erfasst \\*RK\\*", Qt::CaseInsensitive ); if ( ( *text_it ).contains( rx_creation_date ) ) // date followed by typist { QString date = *text_it; date.remove( rx_creation_date ).remove( QRegExp( " von\\s*$" ) ); // Date is given as DD.MM.YY QString s = date.section( '.', 0, 0 ); int day = s.toInt(); s = date.section( '.', 1, 1 ); int month = s.toInt(); s = date.section( '.', 2, 2 ); int year = s.toInt(); year += 1900; if ( year < 1970 ) year += 100; //we'll assume nothing has been created before 1970 (y2k issues :p) recipe.ctime = QDateTime(QDate(year,month,day)); #if 0 //typist text_it++; QString typist = = *text_it; typist.remove( rx_line_begin ); #endif } else //everything else is an author { if ( ( *text_it ).contains( rx_line_begin ) ) { QString author = *text_it; author.remove( rx_line_begin ); recipe.authorList.append( Element( author ) ); } else break; } text_it++; } } void RezkonvImporter::readRange( const QString &range_str, double &amount, double &amount_offset ) { QString from = range_str.section( '-', 0, 0 ); QString to = range_str.section( '-', 1, 1 ); amount = MixedNumber::fromString( from ).toDouble(); if ( !to.trimmed().isEmpty() ) amount_offset = MixedNumber::fromString( to ).toDouble() - amount; } <|endoftext|>
<commit_before>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of hpp-corbaserver. // hpp-corbaserver is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-corbaserver 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-corbaserver. If not, see <http://www.gnu.org/licenses/>. #include <hpp/corbaserver/conversions.hh> #include <boost/mpl/for_each.hpp> #include <pinocchio/spatial/se3.hpp> #include <hpp/corbaserver/config.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/configuration.hh> #include <hpp/constraints/comparison-types.hh> namespace hpp { namespace corbaServer { using CORBA::ULong; void toTransform3f (const Transform_ in, Transform3f& out) { Transform3f::Quaternion Q (in [6], in [3], in [4], in [5]); const value_type eps = 1e-8; if (std::fabs (Q.squaredNorm()-1) > eps) throw Error ("Quaternion is not normalized."); out.translation() << in [0], in [1], in [2]; out.rotation() = Q.matrix(); } Transform3f toTransform3f (const Transform_ in) { Transform3f out; toTransform3f (in, out); return out; } std::vector<Transform3f> toTransform3f (const TransformSeq in) { std::vector<Transform3f> out (in.length()); for (std::size_t i = 0; i < out.size(); ++i) toTransform3f (in[(ULong)i], out[i]); return out; } void toHppTransform (const Transform3f& in, Transform_ out) { Transform3f::Quaternion q (in.rotation()); out[3] = q.x(); out[4] = q.y(); out[5] = q.z(); out[6] = q.w(); for(int i=0; i<3; i++) out[i] = in.translation() [i]; } Transform__slice* toHppTransform (const Transform3f& in) { Transform__slice* out = Transform__alloc(); toHppTransform (in, out); return out; } floatSeq* vectorToFloatSeq (core::vectorIn_t input) { floatSeq* q_ptr = new floatSeq (); vectorToFloatSeq (input, *q_ptr); return q_ptr; } void vectorToFloatSeq (core::vectorIn_t input, floatSeq& output) { ULong size = (ULong) input.size (); output.length (size); for (std::size_t i=0; i<size; ++i) { output [(ULong)i] = input [i]; } } floatSeqSeq* matrixToFloatSeqSeq (core::matrixIn_t input) { floatSeqSeq* res = new floatSeqSeq; res->length ((ULong) input.rows ()); for (size_type i=0; i<input.rows (); ++i) { floatSeq row; row.length ((ULong) input.cols ()); for (size_type j=0; j<input.cols (); ++j) { row [(ULong) j] = input (i, j); } (*res) [(ULong) i] = row; } return res; } intSeqSeq* matrixToIntSeqSeq (Eigen::Ref<const IntMatrix_t > input) { intSeqSeq* res = new intSeqSeq; res->length ((ULong) input.rows ()); for (size_type i=0; i<input.rows (); ++i) { intSeq row; row.length ((ULong) input.cols ()); for (size_type j=0; j<input.cols (); ++j) { row [(ULong) j] = input (i, j); } (*res) [(ULong) i] = row; } return res; } vector3_t floatSeqToVector3 (const floatSeq& dofArray) { if (dofArray.length() != 3) { HPP_THROW (Error, "Expecting vector of size 3, got vector of size " << dofArray.length() << "."); } // Fill dof vector with dof array. vector3_t result; for (unsigned int iDof=0; iDof < 3; ++iDof) { result [iDof] = dofArray [iDof]; } return result; } vector_t floatSeqToVector (const floatSeq& dofArray, const size_type expectedSize) { size_type inputDim = (size_type)dofArray.length(); if (expectedSize >=0 && inputDim != expectedSize) { HPP_THROW (std::runtime_error, "size of input array (" << inputDim << ") is different from the expected size (" << expectedSize << ")"); } // Fill dof vector with dof array. vector_t result (inputDim); for (size_type iDof=0; iDof < inputDim; ++iDof) { result [iDof] = dofArray [(CORBA::ULong)iDof]; } return result; } Configuration_t floatSeqToConfig (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized) { Configuration_t q (floatSeqToVector (dofArray, robot->configSize())); if (throwIfNotNormalized) { const value_type eps = 1e-8; if (!pinocchio::isNormalized(robot, q, eps)) throw Error ("Configuration is not normalized (wrong quaternion or complex norm)."); } return q; } ConfigurationPtr_t floatSeqToConfigPtr (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized) { return ConfigurationPtr_t (new Configuration_t( floatSeqToConfig(robot, dofArray, throwIfNotNormalized) )); } core::matrix_t floatSeqSeqToMatrix (const floatSeqSeq& input, const size_type expectedRows, const size_type expectedCols) { size_type rows = (size_type)input.length(); if (expectedRows >= 0 && rows != expectedRows) { HPP_THROW (std::runtime_error, "number of rows of input floatSeqSeq (" << rows << ") is different from the expected number of rows (" << expectedRows << ")"); } if (rows == 0) return matrix_t (rows, std::max(size_type(0), expectedCols)); size_type cols = (size_type)input[0].length(); if (expectedCols >= 0 && cols != expectedCols) { HPP_THROW (std::runtime_error, "number of cols of input floatSeqSeq (" << cols << ") is different from the expected number of cols (" << expectedCols << ")"); } matrix_t out (rows, cols); for (size_type r = 0; r < rows; ++r) { const floatSeq& row = input[(CORBA::ULong)r]; for (size_type c = 0; c < cols; ++c) out(r,c) = row[(CORBA::ULong)c]; } return out; } IntMatrix_t intSeqSeqToMatrix (const intSeqSeq& input, const size_type expectedRows, const size_type expectedCols) { size_type rows = (size_type)input.length(); if (expectedRows >= 0 && rows != expectedRows) { HPP_THROW (std::runtime_error, "number of rows of input floatSeqSeq (" << rows << ") is different from the expected number of rows (" << expectedRows << ")"); } if (rows == 0) return IntMatrix_t (rows, std::max(size_type(0), expectedCols)); size_type cols = (size_type)input[0].length(); if (expectedCols >= 0 && cols != expectedCols) { HPP_THROW (std::runtime_error, "number of cols of input floatSeqSeq (" << cols << ") is different from the expected number of cols (" << expectedCols << ")"); } IntMatrix_t out (rows, cols); for (size_type r = 0; r < rows; ++r) { const intSeq& row = input[(CORBA::ULong)r]; for (size_type c = 0; c < cols; ++c) out(r,c) = row[(CORBA::ULong)c]; } return out; } std::vector<bool> boolSeqToVector (const hpp::boolSeq& mask, unsigned int length) { if (mask.length () != length) { std::stringstream ss; ss << "Mask must be of length " << length; throw hpp::Error (ss.str().c_str()); } std::vector<bool> m (length); for (size_t i=0; i<length; i++) m[i] = mask[(CORBA::ULong)i]; return m; } constraints::ComparisonTypes_t convertComparison (hpp::ComparisonTypes_t comp) { constraints::ComparisonTypes_t res(comp.length()); for (std::size_t i=0; i<comp.length(); ++i){ switch (comp[(CORBA::ULong)i]){ case Equality: res[i] = constraints::Equality; break; case EqualToZero: res[i] = constraints::EqualToZero; break; case Superior: res[i] = constraints::Superior; break; case Inferior: res[i] = constraints::Inferior; break; default: abort(); } } return res; } hpp::ComparisonTypes_t* convertComparison (constraints::ComparisonTypes_t comp) { hpp::ComparisonTypes_t* res_ptr = new hpp::ComparisonTypes_t(); hpp::ComparisonTypes_t& res (*res_ptr); res.length((CORBA::ULong)comp.size()); for (std::size_t i=0; i<comp.size(); ++i){ switch (comp[i]){ case constraints::Equality: res[(CORBA::ULong)i] = Equality; break; case constraints::EqualToZero: res[(CORBA::ULong)i] = EqualToZero; break; case constraints::Superior: res[(CORBA::ULong)i] = Superior; break; case constraints::Inferior: res[(CORBA::ULong)i] = Inferior; break; default: throw Error("Unknown comparison type"); } } return res_ptr; } using core::Parameter; Parameter toParameter (const CORBA::Any& any); CORBA::Any toCorbaAny (const Parameter& parameter); struct Parameter_CorbaAny { private: template <typename first, typename second> static inline second as (const first& f) { return second (f); } struct convertToParam { const CORBA::Any& corbaAny; Parameter& param; bool& done; void operator()(std::pair<vector_t, floatSeq>) { if (done) return; floatSeq* d = new floatSeq(); if (corbaAny >>= d) { param = Parameter (floatSeqToVector (*d)); done = true; } else delete d; } void operator()(std::pair<matrix_t, floatSeqSeq>) { if (done) return; floatSeqSeq* d = new floatSeqSeq(); if (corbaAny >>= d) { param = Parameter (floatSeqSeqToMatrix (*d)); done = true; } else delete d; } template <typename T> void operator()(T) { if (done) return; typename T::second_type d; if (corbaAny >>= d) { param = Parameter (as<typename T::second_type, typename T::first_type>(d)); done = true; } } convertToParam (const CORBA::Any& a, Parameter& p, bool& d) : corbaAny(a), param(p), done(d) {} }; /// TODO: This list of CORBA types is not complete. typedef boost::mpl::vector< // There is no operator<<= (CORBA::Any, CORBA::Boolean) std::pair<bool , CORBA::Boolean>, std::pair<size_type , CORBA::LongLong>, std::pair<size_type , CORBA::Long>, std::pair<size_type , CORBA::Short>, std::pair<size_type , CORBA::ULongLong>, std::pair<size_type , CORBA::ULong>, std::pair<size_type , CORBA::UShort>, std::pair<value_type , CORBA::Float>, std::pair<value_type , CORBA::Double>, std::pair<std::string, const char*> // This two do not work because omniidl must be given the option -Wba in order to generate // a DynSK.cc file containing the conversion to/from Any type. , std::pair<matrix_t , floatSeqSeq> , std::pair<vector_t , floatSeq> > Parameter_AnyPairs_t; public: static Parameter toParameter (const CORBA::Any& an) { Parameter out; bool done = false; convertToParam ret(an, out, done); boost::mpl::for_each<Parameter_AnyPairs_t> (ret); if (!done) throw hpp::Error ("Could not convert to Parameter"); return out; } static CORBA::Any toCorbaAny (const Parameter& p) { CORBA::Any out; switch (p.type()) { case Parameter::BOOL: out <<= p.boolValue(); break; case Parameter::INT: out <<= (CORBA::Long)p.intValue(); break; case Parameter::FLOAT: out <<= p.floatValue(); break; case Parameter::STRING: out <<= p.stringValue().c_str(); break; case Parameter::VECTOR: out <<= vectorToFloatSeq(p.vectorValue()); break; case Parameter::MATRIX: out <<= matrixToFloatSeqSeq(p.matrixValue()); break; default: throw hpp::Error ("Could not convert to CORBA::Any"); break; } return out; } }; template <> inline vector_t Parameter_CorbaAny::as<floatSeq, vector_t> (const floatSeq& in) { return floatSeqToVector(in); } template <> inline matrix_t Parameter_CorbaAny::as<floatSeqSeq, matrix_t> (const floatSeqSeq& in) { return floatSeqSeqToMatrix(in); } Parameter toParameter (const CORBA::Any& any) { return Parameter_CorbaAny::toParameter(any); } CORBA::Any toCorbaAny (const Parameter& parameter) { return Parameter_CorbaAny::toCorbaAny(parameter); } } // namespace corbaServer } // namespace hpp <commit_msg>add missing include<commit_after>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of hpp-corbaserver. // hpp-corbaserver is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-corbaserver 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-corbaserver. If not, see <http://www.gnu.org/licenses/>. #include <hpp/corbaserver/conversions.hh> #include <boost/mpl/for_each.hpp> #include <boost/mpl/vector.hpp> #include <pinocchio/spatial/se3.hpp> #include <hpp/corbaserver/config.hh> #include <hpp/pinocchio/device.hh> #include <hpp/pinocchio/configuration.hh> #include <hpp/constraints/comparison-types.hh> namespace hpp { namespace corbaServer { using CORBA::ULong; void toTransform3f (const Transform_ in, Transform3f& out) { Transform3f::Quaternion Q (in [6], in [3], in [4], in [5]); const value_type eps = 1e-8; if (std::fabs (Q.squaredNorm()-1) > eps) throw Error ("Quaternion is not normalized."); out.translation() << in [0], in [1], in [2]; out.rotation() = Q.matrix(); } Transform3f toTransform3f (const Transform_ in) { Transform3f out; toTransform3f (in, out); return out; } std::vector<Transform3f> toTransform3f (const TransformSeq in) { std::vector<Transform3f> out (in.length()); for (std::size_t i = 0; i < out.size(); ++i) toTransform3f (in[(ULong)i], out[i]); return out; } void toHppTransform (const Transform3f& in, Transform_ out) { Transform3f::Quaternion q (in.rotation()); out[3] = q.x(); out[4] = q.y(); out[5] = q.z(); out[6] = q.w(); for(int i=0; i<3; i++) out[i] = in.translation() [i]; } Transform__slice* toHppTransform (const Transform3f& in) { Transform__slice* out = Transform__alloc(); toHppTransform (in, out); return out; } floatSeq* vectorToFloatSeq (core::vectorIn_t input) { floatSeq* q_ptr = new floatSeq (); vectorToFloatSeq (input, *q_ptr); return q_ptr; } void vectorToFloatSeq (core::vectorIn_t input, floatSeq& output) { ULong size = (ULong) input.size (); output.length (size); for (std::size_t i=0; i<size; ++i) { output [(ULong)i] = input [i]; } } floatSeqSeq* matrixToFloatSeqSeq (core::matrixIn_t input) { floatSeqSeq* res = new floatSeqSeq; res->length ((ULong) input.rows ()); for (size_type i=0; i<input.rows (); ++i) { floatSeq row; row.length ((ULong) input.cols ()); for (size_type j=0; j<input.cols (); ++j) { row [(ULong) j] = input (i, j); } (*res) [(ULong) i] = row; } return res; } intSeqSeq* matrixToIntSeqSeq (Eigen::Ref<const IntMatrix_t > input) { intSeqSeq* res = new intSeqSeq; res->length ((ULong) input.rows ()); for (size_type i=0; i<input.rows (); ++i) { intSeq row; row.length ((ULong) input.cols ()); for (size_type j=0; j<input.cols (); ++j) { row [(ULong) j] = input (i, j); } (*res) [(ULong) i] = row; } return res; } vector3_t floatSeqToVector3 (const floatSeq& dofArray) { if (dofArray.length() != 3) { HPP_THROW (Error, "Expecting vector of size 3, got vector of size " << dofArray.length() << "."); } // Fill dof vector with dof array. vector3_t result; for (unsigned int iDof=0; iDof < 3; ++iDof) { result [iDof] = dofArray [iDof]; } return result; } vector_t floatSeqToVector (const floatSeq& dofArray, const size_type expectedSize) { size_type inputDim = (size_type)dofArray.length(); if (expectedSize >=0 && inputDim != expectedSize) { HPP_THROW (std::runtime_error, "size of input array (" << inputDim << ") is different from the expected size (" << expectedSize << ")"); } // Fill dof vector with dof array. vector_t result (inputDim); for (size_type iDof=0; iDof < inputDim; ++iDof) { result [iDof] = dofArray [(CORBA::ULong)iDof]; } return result; } Configuration_t floatSeqToConfig (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized) { Configuration_t q (floatSeqToVector (dofArray, robot->configSize())); if (throwIfNotNormalized) { const value_type eps = 1e-8; if (!pinocchio::isNormalized(robot, q, eps)) throw Error ("Configuration is not normalized (wrong quaternion or complex norm)."); } return q; } ConfigurationPtr_t floatSeqToConfigPtr (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized) { return ConfigurationPtr_t (new Configuration_t( floatSeqToConfig(robot, dofArray, throwIfNotNormalized) )); } core::matrix_t floatSeqSeqToMatrix (const floatSeqSeq& input, const size_type expectedRows, const size_type expectedCols) { size_type rows = (size_type)input.length(); if (expectedRows >= 0 && rows != expectedRows) { HPP_THROW (std::runtime_error, "number of rows of input floatSeqSeq (" << rows << ") is different from the expected number of rows (" << expectedRows << ")"); } if (rows == 0) return matrix_t (rows, std::max(size_type(0), expectedCols)); size_type cols = (size_type)input[0].length(); if (expectedCols >= 0 && cols != expectedCols) { HPP_THROW (std::runtime_error, "number of cols of input floatSeqSeq (" << cols << ") is different from the expected number of cols (" << expectedCols << ")"); } matrix_t out (rows, cols); for (size_type r = 0; r < rows; ++r) { const floatSeq& row = input[(CORBA::ULong)r]; for (size_type c = 0; c < cols; ++c) out(r,c) = row[(CORBA::ULong)c]; } return out; } IntMatrix_t intSeqSeqToMatrix (const intSeqSeq& input, const size_type expectedRows, const size_type expectedCols) { size_type rows = (size_type)input.length(); if (expectedRows >= 0 && rows != expectedRows) { HPP_THROW (std::runtime_error, "number of rows of input floatSeqSeq (" << rows << ") is different from the expected number of rows (" << expectedRows << ")"); } if (rows == 0) return IntMatrix_t (rows, std::max(size_type(0), expectedCols)); size_type cols = (size_type)input[0].length(); if (expectedCols >= 0 && cols != expectedCols) { HPP_THROW (std::runtime_error, "number of cols of input floatSeqSeq (" << cols << ") is different from the expected number of cols (" << expectedCols << ")"); } IntMatrix_t out (rows, cols); for (size_type r = 0; r < rows; ++r) { const intSeq& row = input[(CORBA::ULong)r]; for (size_type c = 0; c < cols; ++c) out(r,c) = row[(CORBA::ULong)c]; } return out; } std::vector<bool> boolSeqToVector (const hpp::boolSeq& mask, unsigned int length) { if (mask.length () != length) { std::stringstream ss; ss << "Mask must be of length " << length; throw hpp::Error (ss.str().c_str()); } std::vector<bool> m (length); for (size_t i=0; i<length; i++) m[i] = mask[(CORBA::ULong)i]; return m; } constraints::ComparisonTypes_t convertComparison (hpp::ComparisonTypes_t comp) { constraints::ComparisonTypes_t res(comp.length()); for (std::size_t i=0; i<comp.length(); ++i){ switch (comp[(CORBA::ULong)i]){ case Equality: res[i] = constraints::Equality; break; case EqualToZero: res[i] = constraints::EqualToZero; break; case Superior: res[i] = constraints::Superior; break; case Inferior: res[i] = constraints::Inferior; break; default: abort(); } } return res; } hpp::ComparisonTypes_t* convertComparison (constraints::ComparisonTypes_t comp) { hpp::ComparisonTypes_t* res_ptr = new hpp::ComparisonTypes_t(); hpp::ComparisonTypes_t& res (*res_ptr); res.length((CORBA::ULong)comp.size()); for (std::size_t i=0; i<comp.size(); ++i){ switch (comp[i]){ case constraints::Equality: res[(CORBA::ULong)i] = Equality; break; case constraints::EqualToZero: res[(CORBA::ULong)i] = EqualToZero; break; case constraints::Superior: res[(CORBA::ULong)i] = Superior; break; case constraints::Inferior: res[(CORBA::ULong)i] = Inferior; break; default: throw Error("Unknown comparison type"); } } return res_ptr; } using core::Parameter; Parameter toParameter (const CORBA::Any& any); CORBA::Any toCorbaAny (const Parameter& parameter); struct Parameter_CorbaAny { private: template <typename first, typename second> static inline second as (const first& f) { return second (f); } struct convertToParam { const CORBA::Any& corbaAny; Parameter& param; bool& done; void operator()(std::pair<vector_t, floatSeq>) { if (done) return; floatSeq* d = new floatSeq(); if (corbaAny >>= d) { param = Parameter (floatSeqToVector (*d)); done = true; } else delete d; } void operator()(std::pair<matrix_t, floatSeqSeq>) { if (done) return; floatSeqSeq* d = new floatSeqSeq(); if (corbaAny >>= d) { param = Parameter (floatSeqSeqToMatrix (*d)); done = true; } else delete d; } template <typename T> void operator()(T) { if (done) return; typename T::second_type d; if (corbaAny >>= d) { param = Parameter (as<typename T::second_type, typename T::first_type>(d)); done = true; } } convertToParam (const CORBA::Any& a, Parameter& p, bool& d) : corbaAny(a), param(p), done(d) {} }; /// TODO: This list of CORBA types is not complete. typedef boost::mpl::vector< // There is no operator<<= (CORBA::Any, CORBA::Boolean) std::pair<bool , CORBA::Boolean>, std::pair<size_type , CORBA::LongLong>, std::pair<size_type , CORBA::Long>, std::pair<size_type , CORBA::Short>, std::pair<size_type , CORBA::ULongLong>, std::pair<size_type , CORBA::ULong>, std::pair<size_type , CORBA::UShort>, std::pair<value_type , CORBA::Float>, std::pair<value_type , CORBA::Double>, std::pair<std::string, const char*> // This two do not work because omniidl must be given the option -Wba in order to generate // a DynSK.cc file containing the conversion to/from Any type. , std::pair<matrix_t , floatSeqSeq> , std::pair<vector_t , floatSeq> > Parameter_AnyPairs_t; public: static Parameter toParameter (const CORBA::Any& an) { Parameter out; bool done = false; convertToParam ret(an, out, done); boost::mpl::for_each<Parameter_AnyPairs_t> (ret); if (!done) throw hpp::Error ("Could not convert to Parameter"); return out; } static CORBA::Any toCorbaAny (const Parameter& p) { CORBA::Any out; switch (p.type()) { case Parameter::BOOL: out <<= p.boolValue(); break; case Parameter::INT: out <<= (CORBA::Long)p.intValue(); break; case Parameter::FLOAT: out <<= p.floatValue(); break; case Parameter::STRING: out <<= p.stringValue().c_str(); break; case Parameter::VECTOR: out <<= vectorToFloatSeq(p.vectorValue()); break; case Parameter::MATRIX: out <<= matrixToFloatSeqSeq(p.matrixValue()); break; default: throw hpp::Error ("Could not convert to CORBA::Any"); break; } return out; } }; template <> inline vector_t Parameter_CorbaAny::as<floatSeq, vector_t> (const floatSeq& in) { return floatSeqToVector(in); } template <> inline matrix_t Parameter_CorbaAny::as<floatSeqSeq, matrix_t> (const floatSeqSeq& in) { return floatSeqSeqToMatrix(in); } Parameter toParameter (const CORBA::Any& any) { return Parameter_CorbaAny::toParameter(any); } CORBA::Any toCorbaAny (const Parameter& parameter) { return Parameter_CorbaAny::toCorbaAny(parameter); } } // namespace corbaServer } // namespace hpp <|endoftext|>
<commit_before>#include "GasMeter.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "Ext.h" #include "RuntimeManager.h" namespace dev { namespace eth { namespace jit { namespace // Helper functions { int64_t const c_stepGas[] = {0, 2, 3, 5, 8, 10, 20}; int64_t const c_expByteGas = 10; int64_t const c_sha3Gas = 30; int64_t const c_sha3WordGas = 6; int64_t const c_sloadGas = 50; int64_t const c_sstoreSetGas = 20000; int64_t const c_sstoreResetGas = 5000; int64_t const c_jumpdestGas = 1; int64_t const c_logGas = 375; int64_t const c_logTopicGas = 375; int64_t const c_logDataGas = 8; int64_t const c_callGas = 40; int64_t const c_createGas = 32000; int64_t const c_memoryGas = 3; int64_t const c_copyGas = 3; int64_t getStepCost(Instruction inst) { switch (inst) { // Tier 0 case Instruction::STOP: case Instruction::RETURN: case Instruction::SUICIDE: case Instruction::SSTORE: // Handle cost of SSTORE separately in GasMeter::countSStore() return c_stepGas[0]; // Tier 1 case Instruction::ADDRESS: case Instruction::ORIGIN: case Instruction::CALLER: case Instruction::CALLVALUE: case Instruction::CALLDATASIZE: case Instruction::CODESIZE: case Instruction::GASPRICE: case Instruction::COINBASE: case Instruction::TIMESTAMP: case Instruction::NUMBER: case Instruction::DIFFICULTY: case Instruction::GASLIMIT: case Instruction::POP: case Instruction::PC: case Instruction::MSIZE: case Instruction::GAS: return c_stepGas[1]; // Tier 2 case Instruction::ADD: case Instruction::SUB: case Instruction::LT: case Instruction::GT: case Instruction::SLT: case Instruction::SGT: case Instruction::EQ: case Instruction::ISZERO: case Instruction::AND: case Instruction::OR: case Instruction::XOR: case Instruction::NOT: case Instruction::BYTE: case Instruction::CALLDATALOAD: case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::MLOAD: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::ANY_PUSH: case Instruction::ANY_DUP: case Instruction::ANY_SWAP: return c_stepGas[2]; // Tier 3 case Instruction::MUL: case Instruction::DIV: case Instruction::SDIV: case Instruction::MOD: case Instruction::SMOD: case Instruction::SIGNEXTEND: return c_stepGas[3]; // Tier 4 case Instruction::ADDMOD: case Instruction::MULMOD: case Instruction::JUMP: return c_stepGas[4]; // Tier 5 case Instruction::EXP: case Instruction::JUMPI: return c_stepGas[5]; // Tier 6 case Instruction::BALANCE: case Instruction::EXTCODESIZE: case Instruction::EXTCODECOPY: case Instruction::BLOCKHASH: return c_stepGas[6]; case Instruction::SHA3: return c_sha3Gas; case Instruction::SLOAD: return c_sloadGas; case Instruction::JUMPDEST: return c_jumpdestGas; case Instruction::LOG0: case Instruction::LOG1: case Instruction::LOG2: case Instruction::LOG3: case Instruction::LOG4: { auto numTopics = static_cast<int64_t>(inst) - static_cast<int64_t>(Instruction::LOG0); return c_logGas + numTopics * c_logTopicGas; } case Instruction::CALL: case Instruction::CALLCODE: return c_callGas; case Instruction::CREATE: return c_createGas; } return 0; // TODO: Add UNREACHABLE macro } } GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) : CompilerHelper(_builder), m_runtimeManager(_runtimeManager) { llvm::Type* gasCheckArgs[] = {Type::Gas->getPointerTo(), Type::Gas, Type::BytePtr}; m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, "gas.check", getModule()); m_gasCheckFunc->setDoesNotThrow(); m_gasCheckFunc->setDoesNotCapture(1); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc); auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc); auto gasPtr = &m_gasCheckFunc->getArgumentList().front(); gasPtr->setName("gasPtr"); auto cost = gasPtr->getNextNode(); cost->setName("cost"); auto jmpBuf = cost->getNextNode(); jmpBuf->setName("jmpBuf"); InsertPointGuard guard(m_builder); m_builder.SetInsertPoint(checkBB); auto gas = m_builder.CreateLoad(gasPtr, "gas"); auto gasUpdated = m_builder.CreateNSWSub(gas, cost, "gasUpdated"); auto gasOk = m_builder.CreateICmpSGE(gasUpdated, m_builder.getInt64(0), "gasOk"); // gas >= 0, with gas == 0 we can still do 0 cost instructions m_builder.CreateCondBr(gasOk, updateBB, outOfGasBB, Type::expectTrue); m_builder.SetInsertPoint(updateBB); m_builder.CreateStore(gasUpdated, gasPtr); m_builder.CreateRetVoid(); m_builder.SetInsertPoint(outOfGasBB); m_runtimeManager.abort(jmpBuf); m_builder.CreateUnreachable(); } void GasMeter::count(Instruction _inst) { if (!m_checkCall) { // Create gas check call with mocked block cost at begining of current cost-block m_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getGasPtr(), llvm::UndefValue::get(Type::Gas), m_runtimeManager.getJmpBuf()}); } m_blockCost += getStepCost(_inst); } void GasMeter::count(llvm::Value* _cost, llvm::Value* _jmpBuf, llvm::Value* _gasPtr) { if (_cost->getType() == Type::Word) { auto gasMax256 = m_builder.CreateZExt(Constant::gasMax, Type::Word); auto tooHigh = m_builder.CreateICmpUGT(_cost, gasMax256, "costTooHigh"); auto cost64 = m_builder.CreateTrunc(_cost, Type::Gas); _cost = m_builder.CreateSelect(tooHigh, Constant::gasMax, cost64, "cost"); } assert(_cost->getType() == Type::Gas); createCall(m_gasCheckFunc, {_gasPtr ? _gasPtr : m_runtimeManager.getGasPtr(), _cost, _jmpBuf ? _jmpBuf : m_runtimeManager.getJmpBuf()}); } void GasMeter::countExp(llvm::Value* _exponent) { // Additional cost is 1 per significant byte of exponent // lz - leading zeros // cost = ((256 - lz) + 7) / 8 // OPT: Can gas update be done in exp algorithm? auto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word); auto lz256 = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false)); auto lz = m_builder.CreateTrunc(lz256, Type::Gas, "lz"); auto sigBits = m_builder.CreateSub(m_builder.getInt64(256), lz, "sigBits"); auto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, m_builder.getInt64(7)), m_builder.getInt64(8)); count(m_builder.CreateNUWMul(sigBytes, m_builder.getInt64(c_expByteGas))); } void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue) { auto oldValue = _ext.sload(_index); auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero"); auto newValueIsZero = m_builder.CreateICmpEQ(_newValue, Constant::get(0), "newValueIsZero"); auto oldValueIsntZero = m_builder.CreateICmpNE(oldValue, Constant::get(0), "oldValueIsntZero"); auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero"); auto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isInsert"); auto isDelete = m_builder.CreateAnd(oldValueIsntZero, newValueIsZero, "isDelete"); auto cost = m_builder.CreateSelect(isInsert, m_builder.getInt64(c_sstoreSetGas), m_builder.getInt64(c_sstoreResetGas), "cost"); cost = m_builder.CreateSelect(isDelete, m_builder.getInt64(0), cost, "cost"); count(cost); } void GasMeter::countLogData(llvm::Value* _dataLength) { assert(m_checkCall); assert(m_blockCost > 0); // LOGn instruction is already counted static_assert(c_logDataGas != 1, "Log data gas cost has changed. Update GasMeter."); count(m_builder.CreateNUWMul(_dataLength, Constant::get(c_logDataGas))); // TODO: Use i64 } void GasMeter::countSha3Data(llvm::Value* _dataLength) { assert(m_checkCall); assert(m_blockCost > 0); // SHA3 instruction is already counted // TODO: This round ups to 32 happens in many places static_assert(c_sha3WordGas != 1, "SHA3 data cost has changed. Update GasMeter"); auto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::Gas); auto words64 = m_builder.CreateUDiv(m_builder.CreateNUWAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32)); auto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64); count(cost64); } void GasMeter::giveBack(llvm::Value* _gas) { assert(_gas->getType() == Type::Gas); m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas)); } void GasMeter::commitCostBlock() { // If any uncommited block if (m_checkCall) { if (m_blockCost == 0) // Do not check 0 { m_checkCall->eraseFromParent(); // Remove the gas check call m_checkCall = nullptr; return; } m_checkCall->setArgOperand(1, m_builder.getInt64(m_blockCost)); // Update block cost in gas check call m_checkCall = nullptr; // End cost-block m_blockCost = 0; } assert(m_blockCost == 0); } void GasMeter::countMemory(llvm::Value* _additionalMemoryInWords, llvm::Value* _jmpBuf, llvm::Value* _gasPtr) { static_assert(c_memoryGas != 1, "Memory gas cost has changed. Update GasMeter."); count(_additionalMemoryInWords, _jmpBuf, _gasPtr); } void GasMeter::countCopy(llvm::Value* _copyWords) { static_assert(c_copyGas != 1, "Copy gas cost has changed. Update GasMeter."); count(m_builder.CreateNUWMul(_copyWords, m_builder.getInt64(c_copyGas))); } } } } <commit_msg>Update gas costs for PoC-9: set nonzero storage clear cost<commit_after>#include "GasMeter.h" #include "preprocessor/llvm_includes_start.h" #include <llvm/IR/IntrinsicInst.h> #include "preprocessor/llvm_includes_end.h" #include "Ext.h" #include "RuntimeManager.h" namespace dev { namespace eth { namespace jit { namespace // Helper functions { int64_t const c_stepGas[] = {0, 2, 3, 5, 8, 10, 20}; int64_t const c_expByteGas = 10; int64_t const c_sha3Gas = 30; int64_t const c_sha3WordGas = 6; int64_t const c_sloadGas = 50; int64_t const c_sstoreSetGas = 20000; int64_t const c_sstoreResetGas = 5000; int64_t const c_sstoreClearGas = 5000; int64_t const c_jumpdestGas = 1; int64_t const c_logGas = 375; int64_t const c_logTopicGas = 375; int64_t const c_logDataGas = 8; int64_t const c_callGas = 40; int64_t const c_createGas = 32000; int64_t const c_memoryGas = 3; int64_t const c_copyGas = 3; int64_t getStepCost(Instruction inst) { switch (inst) { // Tier 0 case Instruction::STOP: case Instruction::RETURN: case Instruction::SUICIDE: case Instruction::SSTORE: // Handle cost of SSTORE separately in GasMeter::countSStore() return c_stepGas[0]; // Tier 1 case Instruction::ADDRESS: case Instruction::ORIGIN: case Instruction::CALLER: case Instruction::CALLVALUE: case Instruction::CALLDATASIZE: case Instruction::CODESIZE: case Instruction::GASPRICE: case Instruction::COINBASE: case Instruction::TIMESTAMP: case Instruction::NUMBER: case Instruction::DIFFICULTY: case Instruction::GASLIMIT: case Instruction::POP: case Instruction::PC: case Instruction::MSIZE: case Instruction::GAS: return c_stepGas[1]; // Tier 2 case Instruction::ADD: case Instruction::SUB: case Instruction::LT: case Instruction::GT: case Instruction::SLT: case Instruction::SGT: case Instruction::EQ: case Instruction::ISZERO: case Instruction::AND: case Instruction::OR: case Instruction::XOR: case Instruction::NOT: case Instruction::BYTE: case Instruction::CALLDATALOAD: case Instruction::CALLDATACOPY: case Instruction::CODECOPY: case Instruction::MLOAD: case Instruction::MSTORE: case Instruction::MSTORE8: case Instruction::ANY_PUSH: case Instruction::ANY_DUP: case Instruction::ANY_SWAP: return c_stepGas[2]; // Tier 3 case Instruction::MUL: case Instruction::DIV: case Instruction::SDIV: case Instruction::MOD: case Instruction::SMOD: case Instruction::SIGNEXTEND: return c_stepGas[3]; // Tier 4 case Instruction::ADDMOD: case Instruction::MULMOD: case Instruction::JUMP: return c_stepGas[4]; // Tier 5 case Instruction::EXP: case Instruction::JUMPI: return c_stepGas[5]; // Tier 6 case Instruction::BALANCE: case Instruction::EXTCODESIZE: case Instruction::EXTCODECOPY: case Instruction::BLOCKHASH: return c_stepGas[6]; case Instruction::SHA3: return c_sha3Gas; case Instruction::SLOAD: return c_sloadGas; case Instruction::JUMPDEST: return c_jumpdestGas; case Instruction::LOG0: case Instruction::LOG1: case Instruction::LOG2: case Instruction::LOG3: case Instruction::LOG4: { auto numTopics = static_cast<int64_t>(inst) - static_cast<int64_t>(Instruction::LOG0); return c_logGas + numTopics * c_logTopicGas; } case Instruction::CALL: case Instruction::CALLCODE: return c_callGas; case Instruction::CREATE: return c_createGas; } return 0; // TODO: Add UNREACHABLE macro } } GasMeter::GasMeter(llvm::IRBuilder<>& _builder, RuntimeManager& _runtimeManager) : CompilerHelper(_builder), m_runtimeManager(_runtimeManager) { llvm::Type* gasCheckArgs[] = {Type::Gas->getPointerTo(), Type::Gas, Type::BytePtr}; m_gasCheckFunc = llvm::Function::Create(llvm::FunctionType::get(Type::Void, gasCheckArgs, false), llvm::Function::PrivateLinkage, "gas.check", getModule()); m_gasCheckFunc->setDoesNotThrow(); m_gasCheckFunc->setDoesNotCapture(1); auto checkBB = llvm::BasicBlock::Create(_builder.getContext(), "Check", m_gasCheckFunc); auto updateBB = llvm::BasicBlock::Create(_builder.getContext(), "Update", m_gasCheckFunc); auto outOfGasBB = llvm::BasicBlock::Create(_builder.getContext(), "OutOfGas", m_gasCheckFunc); auto gasPtr = &m_gasCheckFunc->getArgumentList().front(); gasPtr->setName("gasPtr"); auto cost = gasPtr->getNextNode(); cost->setName("cost"); auto jmpBuf = cost->getNextNode(); jmpBuf->setName("jmpBuf"); InsertPointGuard guard(m_builder); m_builder.SetInsertPoint(checkBB); auto gas = m_builder.CreateLoad(gasPtr, "gas"); auto gasUpdated = m_builder.CreateNSWSub(gas, cost, "gasUpdated"); auto gasOk = m_builder.CreateICmpSGE(gasUpdated, m_builder.getInt64(0), "gasOk"); // gas >= 0, with gas == 0 we can still do 0 cost instructions m_builder.CreateCondBr(gasOk, updateBB, outOfGasBB, Type::expectTrue); m_builder.SetInsertPoint(updateBB); m_builder.CreateStore(gasUpdated, gasPtr); m_builder.CreateRetVoid(); m_builder.SetInsertPoint(outOfGasBB); m_runtimeManager.abort(jmpBuf); m_builder.CreateUnreachable(); } void GasMeter::count(Instruction _inst) { if (!m_checkCall) { // Create gas check call with mocked block cost at begining of current cost-block m_checkCall = createCall(m_gasCheckFunc, {m_runtimeManager.getGasPtr(), llvm::UndefValue::get(Type::Gas), m_runtimeManager.getJmpBuf()}); } m_blockCost += getStepCost(_inst); } void GasMeter::count(llvm::Value* _cost, llvm::Value* _jmpBuf, llvm::Value* _gasPtr) { if (_cost->getType() == Type::Word) { auto gasMax256 = m_builder.CreateZExt(Constant::gasMax, Type::Word); auto tooHigh = m_builder.CreateICmpUGT(_cost, gasMax256, "costTooHigh"); auto cost64 = m_builder.CreateTrunc(_cost, Type::Gas); _cost = m_builder.CreateSelect(tooHigh, Constant::gasMax, cost64, "cost"); } assert(_cost->getType() == Type::Gas); createCall(m_gasCheckFunc, {_gasPtr ? _gasPtr : m_runtimeManager.getGasPtr(), _cost, _jmpBuf ? _jmpBuf : m_runtimeManager.getJmpBuf()}); } void GasMeter::countExp(llvm::Value* _exponent) { // Additional cost is 1 per significant byte of exponent // lz - leading zeros // cost = ((256 - lz) + 7) / 8 // OPT: Can gas update be done in exp algorithm? auto ctlz = llvm::Intrinsic::getDeclaration(getModule(), llvm::Intrinsic::ctlz, Type::Word); auto lz256 = m_builder.CreateCall2(ctlz, _exponent, m_builder.getInt1(false)); auto lz = m_builder.CreateTrunc(lz256, Type::Gas, "lz"); auto sigBits = m_builder.CreateSub(m_builder.getInt64(256), lz, "sigBits"); auto sigBytes = m_builder.CreateUDiv(m_builder.CreateAdd(sigBits, m_builder.getInt64(7)), m_builder.getInt64(8)); count(m_builder.CreateNUWMul(sigBytes, m_builder.getInt64(c_expByteGas))); } void GasMeter::countSStore(Ext& _ext, llvm::Value* _index, llvm::Value* _newValue) { auto oldValue = _ext.sload(_index); auto oldValueIsZero = m_builder.CreateICmpEQ(oldValue, Constant::get(0), "oldValueIsZero"); auto newValueIsntZero = m_builder.CreateICmpNE(_newValue, Constant::get(0), "newValueIsntZero"); auto isInsert = m_builder.CreateAnd(oldValueIsZero, newValueIsntZero, "isInsert"); static_assert(c_sstoreResetGas == c_sstoreClearGas, "Update SSTORE gas cost"); auto cost = m_builder.CreateSelect(isInsert, m_builder.getInt64(c_sstoreSetGas), m_builder.getInt64(c_sstoreResetGas), "cost"); count(cost); } void GasMeter::countLogData(llvm::Value* _dataLength) { assert(m_checkCall); assert(m_blockCost > 0); // LOGn instruction is already counted static_assert(c_logDataGas != 1, "Log data gas cost has changed. Update GasMeter."); count(m_builder.CreateNUWMul(_dataLength, Constant::get(c_logDataGas))); // TODO: Use i64 } void GasMeter::countSha3Data(llvm::Value* _dataLength) { assert(m_checkCall); assert(m_blockCost > 0); // SHA3 instruction is already counted // TODO: This round ups to 32 happens in many places static_assert(c_sha3WordGas != 1, "SHA3 data cost has changed. Update GasMeter"); auto dataLength64 = getBuilder().CreateTrunc(_dataLength, Type::Gas); auto words64 = m_builder.CreateUDiv(m_builder.CreateNUWAdd(dataLength64, getBuilder().getInt64(31)), getBuilder().getInt64(32)); auto cost64 = m_builder.CreateNUWMul(getBuilder().getInt64(c_sha3WordGas), words64); count(cost64); } void GasMeter::giveBack(llvm::Value* _gas) { assert(_gas->getType() == Type::Gas); m_runtimeManager.setGas(m_builder.CreateAdd(m_runtimeManager.getGas(), _gas)); } void GasMeter::commitCostBlock() { // If any uncommited block if (m_checkCall) { if (m_blockCost == 0) // Do not check 0 { m_checkCall->eraseFromParent(); // Remove the gas check call m_checkCall = nullptr; return; } m_checkCall->setArgOperand(1, m_builder.getInt64(m_blockCost)); // Update block cost in gas check call m_checkCall = nullptr; // End cost-block m_blockCost = 0; } assert(m_blockCost == 0); } void GasMeter::countMemory(llvm::Value* _additionalMemoryInWords, llvm::Value* _jmpBuf, llvm::Value* _gasPtr) { static_assert(c_memoryGas != 1, "Memory gas cost has changed. Update GasMeter."); count(_additionalMemoryInWords, _jmpBuf, _gasPtr); } void GasMeter::countCopy(llvm::Value* _copyWords) { static_assert(c_copyGas != 1, "Copy gas cost has changed. Update GasMeter."); count(m_builder.CreateNUWMul(_copyWords, m_builder.getInt64(c_copyGas))); } } } } <|endoftext|>
<commit_before>/* * Container for cookies received from other HTTP servers. * * author: Max Kellermann <[email protected]> */ #ifndef BENG_PROXY_COOKIE_JAR_HXX #define BENG_PROXY_COOKIE_JAR_HXX #include "util/StringView.hxx" #include <inline/compiler.h> #include <boost/intrusive/list.hpp> #include <new> #include <sys/types.h> struct pool; struct dpool; struct CookieJar; struct Cookie : boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { StringView name; StringView value; const char *domain = nullptr, *path = nullptr; time_t expires = 0; struct Disposer { struct dpool &pool; explicit Disposer(struct dpool &_pool):pool(_pool) {} void operator()(Cookie *cookie) const { cookie->Free(pool); } }; Cookie(struct dpool &pool, StringView _name, StringView _value); Cookie(struct dpool &pool, const Cookie &src); Cookie(const Cookie &) = delete; Cookie &operator=(const Cookie &) = delete; void Free(struct dpool &pool); }; struct CookieJar { struct dpool &pool; typedef boost::intrusive::list<Cookie, boost::intrusive::constant_time_size<false>> List; List cookies; CookieJar(struct dpool &_pool) :pool(_pool) { } CookieJar(const CookieJar &) = delete; CookieJar &operator=(const CookieJar &) = delete; gcc_malloc CookieJar *Dup(struct dpool &new_pool) const; void Free(); void Add(Cookie &cookie) { cookies.push_front(cookie); } void EraseAndDispose(Cookie &cookie); }; CookieJar * cookie_jar_new(struct dpool &pool) throw(std::bad_alloc); #endif <commit_msg>cookie_jar: make constructor explicit<commit_after>/* * Container for cookies received from other HTTP servers. * * author: Max Kellermann <[email protected]> */ #ifndef BENG_PROXY_COOKIE_JAR_HXX #define BENG_PROXY_COOKIE_JAR_HXX #include "util/StringView.hxx" #include <inline/compiler.h> #include <boost/intrusive/list.hpp> #include <new> #include <sys/types.h> struct pool; struct dpool; struct CookieJar; struct Cookie : boost::intrusive::list_base_hook<boost::intrusive::link_mode<boost::intrusive::normal_link>> { StringView name; StringView value; const char *domain = nullptr, *path = nullptr; time_t expires = 0; struct Disposer { struct dpool &pool; explicit Disposer(struct dpool &_pool):pool(_pool) {} void operator()(Cookie *cookie) const { cookie->Free(pool); } }; Cookie(struct dpool &pool, StringView _name, StringView _value); Cookie(struct dpool &pool, const Cookie &src); Cookie(const Cookie &) = delete; Cookie &operator=(const Cookie &) = delete; void Free(struct dpool &pool); }; struct CookieJar { struct dpool &pool; typedef boost::intrusive::list<Cookie, boost::intrusive::constant_time_size<false>> List; List cookies; explicit CookieJar(struct dpool &_pool) :pool(_pool) { } CookieJar(const CookieJar &) = delete; CookieJar &operator=(const CookieJar &) = delete; gcc_malloc CookieJar *Dup(struct dpool &new_pool) const; void Free(); void Add(Cookie &cookie) { cookies.push_front(cookie); } void EraseAndDispose(Cookie &cookie); }; CookieJar * cookie_jar_new(struct dpool &pool) throw(std::bad_alloc); #endif <|endoftext|>
<commit_before>/* This file is part of the CVD Library. Copyright (C) 2005 The Authors This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cvd/image_io.h" #include "cvd/internal/load_and_save.h" #include "cvd/config.h" #include <sstream> #include <fstream> #include <cstring> using namespace std; namespace CVD{ Exceptions::Image_IO::ImageSizeMismatch::ImageSizeMismatch(const ImageRef& src, const ImageRef& dest) { ostringstream o; o << "Image load: Size mismatch when loading an image (size " << src << ") in to a non\ resizable image (size " << dest << ")."; what = o.str(); } Exceptions::Image_IO::OpenError::OpenError(const string& name, const string& why, int error) { what = "Opening file: " + name+ " (" + why + "): " + strerror(error); } Exceptions::Image_IO::MalformedImage::MalformedImage(const string& why) { what = "Image input: " + why; } Exceptions::Image_IO::UnsupportedImageType::UnsupportedImageType() { what = "Image input: Unsuppported image type."; } Exceptions::Image_IO::IfstreamNotOpen::IfstreamNotOpen() { what = "Image input: File stream has not been opened succesfully."; } Exceptions::Image_IO::EofBeforeImage::EofBeforeImage() { what = "Image input: End of file occured before image."; } Exceptions::Image_IO::WriteError::WriteError(const string& s) { what = "Error writing " + s; } Exceptions::Image_IO::WriteTypeMismatch::WriteTypeMismatch(const string& avail, const string& req) { what = "Image output (CVD internal error): Attempting to write " + req + " data to a file containing " + avail; } Exceptions::Image_IO::ReadTypeMismatch::ReadTypeMismatch(const string& avail, const string& req) { what = "Image input (CVD internal error): Attempting to read " + req + " data from a file containing " + avail; } Exceptions::Image_IO::ReadTypeMismatch::ReadTypeMismatch(const bool read8) { what = string("Image input (CVD internal error): Attempting to read ") + (read8?"8":"16") + "bit data from " + (read8?"16":"8") + "bit file (probably an internal error)."; } Exceptions::Image_IO::UnseekableIstream::UnseekableIstream(const string& s) { what = "Image input: Loading " + s + " images requires seekable istream."; } Exceptions::Image_IO::UnsupportedImageSubType::UnsupportedImageSubType(const string& i, const string& why) { what = "Image input: Unsupported subtype of " + i+ " image: " + why; } Exceptions::Image_IO::InternalLibraryError::InternalLibraryError(const std::string& l, const std::string e) { what = "Internal error in " + l + " library: " + e; } ImageType::ImageType string_to_image_type(const std::string& name) { size_t dot = name.rfind('.'); if (dot == std::string::npos) return ImageType::PNM; std::string suffix = name.substr(dot+1,name.length()-dot-1); for (size_t i=0; i<suffix.length(); i++) suffix[i] = tolower(suffix[i]); if (suffix == "ps") return ImageType::PS; #ifdef CVD_HAVE_JPEG else if (suffix == "jpg" || suffix == "jpeg") return ImageType::JPEG; #endif #ifdef CVD_HAVE_PNG else if (suffix == "png") return ImageType::PNG; #endif #ifdef CVD_HAVE_TIFF else if (suffix == "tif" || suffix == "tiff") return ImageType::TIFF; #endif else if (suffix == "eps") return ImageType::EPS; else if (suffix == "bmp") return ImageType::BMP; else if (suffix == "pnm" || suffix == "ppm" || suffix == "pgm" || suffix == "pbm") return ImageType::PNM; else if (suffix == "txt") return ImageType::TXT; else return ImageType::Unknown; } Internal::ImagePromise<Internal::ImageLoaderIstream> img_load(std::istream& i) { return Internal::ImagePromise<Internal::ImageLoaderIstream>(i); } Internal::ImagePromise<Internal::ImageLoaderString> img_load(const std::string &s) { return Internal::ImagePromise<Internal::ImageLoaderString>(s); } } <commit_msg>FITS file extensions.<commit_after>/* This file is part of the CVD Library. Copyright (C) 2005 The Authors This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "cvd/image_io.h" #include "cvd/internal/load_and_save.h" #include "cvd/config.h" #include <sstream> #include <fstream> #include <cstring> using namespace std; namespace CVD{ Exceptions::Image_IO::ImageSizeMismatch::ImageSizeMismatch(const ImageRef& src, const ImageRef& dest) { ostringstream o; o << "Image load: Size mismatch when loading an image (size " << src << ") in to a non\ resizable image (size " << dest << ")."; what = o.str(); } Exceptions::Image_IO::OpenError::OpenError(const string& name, const string& why, int error) { what = "Opening file: " + name+ " (" + why + "): " + strerror(error); } Exceptions::Image_IO::MalformedImage::MalformedImage(const string& why) { what = "Image input: " + why; } Exceptions::Image_IO::UnsupportedImageType::UnsupportedImageType() { what = "Image input: Unsuppported image type."; } Exceptions::Image_IO::IfstreamNotOpen::IfstreamNotOpen() { what = "Image input: File stream has not been opened succesfully."; } Exceptions::Image_IO::EofBeforeImage::EofBeforeImage() { what = "Image input: End of file occured before image."; } Exceptions::Image_IO::WriteError::WriteError(const string& s) { what = "Error writing " + s; } Exceptions::Image_IO::WriteTypeMismatch::WriteTypeMismatch(const string& avail, const string& req) { what = "Image output (CVD internal error): Attempting to write " + req + " data to a file containing " + avail; } Exceptions::Image_IO::ReadTypeMismatch::ReadTypeMismatch(const string& avail, const string& req) { what = "Image input (CVD internal error): Attempting to read " + req + " data from a file containing " + avail; } Exceptions::Image_IO::ReadTypeMismatch::ReadTypeMismatch(const bool read8) { what = string("Image input (CVD internal error): Attempting to read ") + (read8?"8":"16") + "bit data from " + (read8?"16":"8") + "bit file (probably an internal error)."; } Exceptions::Image_IO::UnseekableIstream::UnseekableIstream(const string& s) { what = "Image input: Loading " + s + " images requires seekable istream."; } Exceptions::Image_IO::UnsupportedImageSubType::UnsupportedImageSubType(const string& i, const string& why) { what = "Image input: Unsupported subtype of " + i+ " image: " + why; } Exceptions::Image_IO::InternalLibraryError::InternalLibraryError(const std::string& l, const std::string e) { what = "Internal error in " + l + " library: " + e; } ImageType::ImageType string_to_image_type(const std::string& name) { size_t dot = name.rfind('.'); if (dot == std::string::npos) return ImageType::PNM; std::string suffix = name.substr(dot+1,name.length()-dot-1); for (size_t i=0; i<suffix.length(); i++) suffix[i] = tolower(suffix[i]); if (suffix == "ps") return ImageType::PS; #ifdef CVD_HAVE_JPEG else if (suffix == "jpg" || suffix == "jpeg") return ImageType::JPEG; #endif #ifdef CVD_HAVE_PNG else if (suffix == "png") return ImageType::PNG; #endif #ifdef CVD_HAVE_TIFF else if (suffix == "tif" || suffix == "tiff") return ImageType::TIFF; #endif else if (suffix == "eps") return ImageType::EPS; else if (suffix == "bmp") return ImageType::BMP; else if (suffix == "pnm" || suffix == "ppm" || suffix == "pgm" || suffix == "pbm") return ImageType::PNM; else if (suffix == "txt") return ImageType::TXT; else if (suffix == "fits" || suffix == "fts") return ImageType::FITS; else return ImageType::Unknown; } Internal::ImagePromise<Internal::ImageLoaderIstream> img_load(std::istream& i) { return Internal::ImagePromise<Internal::ImageLoaderIstream>(i); } Internal::ImagePromise<Internal::ImageLoaderString> img_load(const std::string &s) { return Internal::ImagePromise<Internal::ImageLoaderString>(s); } } <|endoftext|>
<commit_before>#include <string> #include <utility> #include <vector> #include <stdexcept> #include <algorithm> /* TODO: * Normalization and Comparison * http://tools.ietf.org/html/rfc3986#section-6 */ struct uri { std::string scheme; std::string userinfo; std::string host; std::string path; std::string query; std::string fragment; unsigned int port; uri() : port(0) {} uri(const std::string &uri_str) { const char *error_at = NULL; if (!parse(uri_str.c_str(), uri_str.size(), &error_at)) { if (error_at) { throw std::runtime_error(error_at); } else { throw std::runtime_error("uri parser error"); } } } int parse(const char *buf, size_t len, const char **error_at = NULL); void clear() { scheme.clear(); userinfo.clear(); host.clear(); path.clear(); query.clear(); fragment.clear(); port = 0; } void normalize(); std::string compose(bool path_only=false); void transform(uri &base, uri &relative); static std::string encode(const std::string& src); static std::string decode(const std::string& src); template <typename T> struct query_match { query_match(const T &k_) : k(k_) {} const T &k; bool operator()(const std::pair<T, T> &i) { return i.first == k; } }; typedef std::vector<std::pair<std::string, std::string> > query_params; static query_params::iterator find_param(query_params &p, const std::string &k) { return std::find_if(p.begin(), p.end(), query_match<std::string>(k)); } query_params parse_query(); }; <commit_msg>function to remove query param and convert back to string<commit_after>#include <string> #include <utility> #include <vector> #include <stdexcept> #include <algorithm> #include <sstream> /* TODO: * Normalization and Comparison * http://tools.ietf.org/html/rfc3986#section-6 */ struct uri { std::string scheme; std::string userinfo; std::string host; std::string path; std::string query; std::string fragment; unsigned int port; uri() : port(0) {} uri(const std::string &uri_str) { const char *error_at = NULL; if (!parse(uri_str.c_str(), uri_str.size(), &error_at)) { if (error_at) { throw std::runtime_error(error_at); } else { throw std::runtime_error("uri parser error"); } } } int parse(const char *buf, size_t len, const char **error_at = NULL); void clear() { scheme.clear(); userinfo.clear(); host.clear(); path.clear(); query.clear(); fragment.clear(); port = 0; } void normalize(); std::string compose(bool path_only=false); void transform(uri &base, uri &relative); static std::string encode(const std::string& src); static std::string decode(const std::string& src); template <typename T> struct query_match { query_match(const T &k_) : k(k_) {} const T &k; bool operator()(const std::pair<T, T> &i) { return i.first == k; } }; typedef std::vector<std::pair<std::string, std::string> > query_params; query_params parse_query(); static query_params::iterator find_param(query_params &p, const std::string &k) { return std::find_if(p.begin(), p.end(), query_match<std::string>(k)); } static void remove_param(query_params &p, const std::string &k) { query_params::iterator nend = std::remove_if(p.begin(), p.end(), query_match<std::string>(k)); p.erase(nend, p.end()); } static std::string params_to_query(const query_params &pms) { if (pms.empty()) return ""; std::stringstream ss; ss << "?"; query_params::const_iterator it = pms.begin(); while (it!=pms.end()) { ss << it->first << "=" << it->second; ++it; if (it != pms.end()) { ss << "&"; } } return ss.str(); } }; <|endoftext|>
<commit_before>#include "precompiled.h" // // Copyright (c) 2012 The ANGLE 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. // // RenderTarget11.cpp: Implements a DX11-specific wrapper for ID3D11View pointers // retained by Renderbuffers. #include "libGLESv2/renderer/d3d11/RenderTarget11.h" #include "libGLESv2/renderer/d3d11/Renderer11.h" #include "libGLESv2/renderer/d3d11/renderer11_utils.h" #include "libGLESv2/renderer/d3d11/formatutils11.h" #include "libGLESv2/main.h" namespace rx { static bool getTextureProperties(ID3D11Resource *resource, unsigned int *mipLevels, unsigned int *samples) { ID3D11Texture1D *texture1D = d3d11::DynamicCastComObject<ID3D11Texture1D>(resource); if (texture1D) { D3D11_TEXTURE1D_DESC texDesc; texture1D->GetDesc(&texDesc); SafeRelease(texture1D); *mipLevels = texDesc.MipLevels; *samples = 0; return true; } ID3D11Texture2D *texture2D = d3d11::DynamicCastComObject<ID3D11Texture2D>(resource); if (texture2D) { D3D11_TEXTURE2D_DESC texDesc; texture2D->GetDesc(&texDesc); SafeRelease(texture2D); *mipLevels = texDesc.MipLevels; *samples = texDesc.SampleDesc.Count > 1 ? texDesc.SampleDesc.Count : 0; return true; } ID3D11Texture3D *texture3D = d3d11::DynamicCastComObject<ID3D11Texture3D>(resource); if (texture3D) { D3D11_TEXTURE3D_DESC texDesc; texture3D->GetDesc(&texDesc); SafeRelease(texture3D); *mipLevels = texDesc.MipLevels; *samples = 0; return true; } return false; } static unsigned int getRTVSubresourceIndex(ID3D11Resource *resource, ID3D11RenderTargetView *view) { D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; view->GetDesc(&rtvDesc); unsigned int mipSlice = 0; unsigned int arraySlice = 0; switch (rtvDesc.ViewDimension) { case D3D11_RTV_DIMENSION_TEXTURE1D: mipSlice = rtvDesc.Texture1D.MipSlice; arraySlice = 0; break; case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: mipSlice = rtvDesc.Texture1DArray.MipSlice; arraySlice = rtvDesc.Texture1DArray.FirstArraySlice; break; case D3D11_RTV_DIMENSION_TEXTURE2D: mipSlice = rtvDesc.Texture2D.MipSlice; arraySlice = 0; break; case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: mipSlice = rtvDesc.Texture2DArray.MipSlice; arraySlice = rtvDesc.Texture2DArray.FirstArraySlice; break; case D3D11_RTV_DIMENSION_TEXTURE2DMS: mipSlice = 0; arraySlice = 0; break; case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: mipSlice = 0; arraySlice = rtvDesc.Texture2DMSArray.FirstArraySlice; break; case D3D11_RTV_DIMENSION_TEXTURE3D: mipSlice = rtvDesc.Texture3D.MipSlice; arraySlice = 0; break; case D3D11_RTV_DIMENSION_UNKNOWN: case D3D11_RTV_DIMENSION_BUFFER: UNIMPLEMENTED(); break; default: UNREACHABLE(); break; } unsigned int mipLevels, samples; getTextureProperties(resource, &mipLevels, &samples); return D3D11CalcSubresource(mipSlice, arraySlice, mipLevels); } static unsigned int getDSVSubresourceIndex(ID3D11Resource *resource, ID3D11DepthStencilView *view) { D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; view->GetDesc(&dsvDesc); unsigned int mipSlice = 0; unsigned int arraySlice = 0; switch (dsvDesc.ViewDimension) { case D3D11_DSV_DIMENSION_TEXTURE1D: mipSlice = dsvDesc.Texture1D.MipSlice; arraySlice = 0; break; case D3D11_DSV_DIMENSION_TEXTURE1DARRAY: mipSlice = dsvDesc.Texture1DArray.MipSlice; arraySlice = dsvDesc.Texture1DArray.FirstArraySlice; break; case D3D11_DSV_DIMENSION_TEXTURE2D: mipSlice = dsvDesc.Texture2D.MipSlice; arraySlice = 0; break; case D3D11_DSV_DIMENSION_TEXTURE2DARRAY: mipSlice = dsvDesc.Texture2DArray.MipSlice; arraySlice = dsvDesc.Texture2DArray.FirstArraySlice; break; case D3D11_DSV_DIMENSION_TEXTURE2DMS: mipSlice = 0; arraySlice = 0; break; case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY: mipSlice = 0; arraySlice = dsvDesc.Texture2DMSArray.FirstArraySlice; break; case D3D11_DSV_DIMENSION_UNKNOWN: UNIMPLEMENTED(); break; default: UNREACHABLE(); break; } unsigned int mipLevels, samples; getTextureProperties(resource, &mipLevels, &samples); return D3D11CalcSubresource(mipSlice, arraySlice, mipLevels); } RenderTarget11::RenderTarget11(Renderer *renderer, ID3D11RenderTargetView *rtv, ID3D11Resource *resource, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height, GLsizei depth) { mRenderer = Renderer11::makeRenderer11(renderer); mTexture = resource; if (mTexture) { mTexture->AddRef(); } mRenderTarget = rtv; if (mRenderTarget) { mRenderTarget->AddRef(); } mDepthStencil = NULL; mShaderResource = srv; if (mShaderResource) { mShaderResource->AddRef(); } mSubresourceIndex = 0; if (mRenderTarget && mTexture) { D3D11_RENDER_TARGET_VIEW_DESC desc; mRenderTarget->GetDesc(&desc); unsigned int mipLevels, samples; getTextureProperties(mTexture, &mipLevels, &samples); mSubresourceIndex = getRTVSubresourceIndex(mTexture, mRenderTarget); mWidth = width; mHeight = height; mDepth = depth; mSamples = samples; mInternalFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); mActualFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); } } RenderTarget11::RenderTarget11(Renderer *renderer, ID3D11DepthStencilView *dsv, ID3D11Resource *resource, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height, GLsizei depth) { mRenderer = Renderer11::makeRenderer11(renderer); mTexture = resource; if (mTexture) { mTexture->AddRef(); } mRenderTarget = NULL; mDepthStencil = dsv; if (mDepthStencil) { mDepthStencil->AddRef(); } mShaderResource = srv; if (mShaderResource) { mShaderResource->AddRef(); } mSubresourceIndex = 0; if (mDepthStencil && mTexture) { D3D11_DEPTH_STENCIL_VIEW_DESC desc; mDepthStencil->GetDesc(&desc); unsigned int mipLevels, samples; getTextureProperties(mTexture, &mipLevels, &samples); mSubresourceIndex = getDSVSubresourceIndex(mTexture, mDepthStencil); mWidth = width; mHeight = height; mDepth = depth; mSamples = samples; mInternalFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); mActualFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); } } RenderTarget11::RenderTarget11(Renderer *renderer, GLsizei width, GLsizei height, GLenum internalFormat, GLsizei samples) { mRenderer = Renderer11::makeRenderer11(renderer); mTexture = NULL; mRenderTarget = NULL; mDepthStencil = NULL; mShaderResource = NULL; GLuint clientVersion = mRenderer->getCurrentClientVersion(); DXGI_FORMAT texFormat = gl_d3d11::GetTexFormat(internalFormat, clientVersion); DXGI_FORMAT srvFormat = gl_d3d11::GetSRVFormat(internalFormat, clientVersion); DXGI_FORMAT rtvFormat = gl_d3d11::GetRTVFormat(internalFormat, clientVersion); DXGI_FORMAT dsvFormat = gl_d3d11::GetDSVFormat(internalFormat, clientVersion); DXGI_FORMAT multisampleFormat = (dsvFormat != DXGI_FORMAT_UNKNOWN ? dsvFormat : rtvFormat); int supportedSamples = mRenderer->getNearestSupportedSamples(multisampleFormat, samples); if (supportedSamples < 0) { gl::error(GL_OUT_OF_MEMORY); return; } if (width > 0 && height > 0) { // Create texture resource D3D11_TEXTURE2D_DESC desc; desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = texFormat; desc.SampleDesc.Count = (supportedSamples == 0) ? 1 : supportedSamples; desc.SampleDesc.Quality = 0; desc.Usage = D3D11_USAGE_DEFAULT; desc.CPUAccessFlags = 0; desc.MiscFlags = 0; desc.BindFlags = ((srvFormat != DXGI_FORMAT_UNKNOWN) ? D3D11_BIND_SHADER_RESOURCE : 0) | ((dsvFormat != DXGI_FORMAT_UNKNOWN) ? D3D11_BIND_DEPTH_STENCIL : 0) | ((rtvFormat != DXGI_FORMAT_UNKNOWN) ? D3D11_BIND_RENDER_TARGET : 0); ID3D11Device *device = mRenderer->getDevice(); ID3D11Texture2D *texture = NULL; HRESULT result = device->CreateTexture2D(&desc, NULL, &texture); mTexture = texture; if (result == E_OUTOFMEMORY) { gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); if (srvFormat != DXGI_FORMAT_UNKNOWN) { D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_SRV_DIMENSION_TEXTURE2D : D3D11_SRV_DIMENSION_TEXTURE2DMS; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; result = device->CreateShaderResourceView(mTexture, &srvDesc, &mShaderResource); if (result == E_OUTOFMEMORY) { SafeRelease(mTexture); gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); } if (dsvFormat != DXGI_FORMAT_UNKNOWN) { D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_DSV_DIMENSION_TEXTURE2D : D3D11_DSV_DIMENSION_TEXTURE2DMS; dsvDesc.Texture2D.MipSlice = 0; dsvDesc.Flags = 0; result = device->CreateDepthStencilView(mTexture, &dsvDesc, &mDepthStencil); if (result == E_OUTOFMEMORY) { SafeRelease(mTexture); SafeRelease(mShaderResource); gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); } if (rtvFormat != DXGI_FORMAT_UNKNOWN) { D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_RTV_DIMENSION_TEXTURE2D : D3D11_RTV_DIMENSION_TEXTURE2DMS; rtvDesc.Texture2D.MipSlice = 0; result = device->CreateRenderTargetView(mTexture, &rtvDesc, &mRenderTarget); if (result == E_OUTOFMEMORY) { SafeRelease(mTexture); SafeRelease(mShaderResource); SafeRelease(mDepthStencil); gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); if (gl_d3d11::RequiresTextureDataInitialization(internalFormat)) { ID3D11DeviceContext *context = mRenderer->getDeviceContext(); const float clearValues[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; context->ClearRenderTargetView(mRenderTarget, clearValues); } } } mWidth = width; mHeight = height; mDepth = 1; mInternalFormat = internalFormat; mSamples = supportedSamples; mActualFormat = d3d11_gl::GetInternalFormat(texFormat, renderer->getCurrentClientVersion()); mSubresourceIndex = D3D11CalcSubresource(0, 0, 1); } RenderTarget11::~RenderTarget11() { SafeRelease(mTexture); SafeRelease(mRenderTarget); SafeRelease(mDepthStencil); SafeRelease(mShaderResource); } RenderTarget11 *RenderTarget11::makeRenderTarget11(RenderTarget *target) { ASSERT(HAS_DYNAMIC_TYPE(rx::RenderTarget11*, target)); return static_cast<rx::RenderTarget11*>(target); } void RenderTarget11::invalidate(GLint x, GLint y, GLsizei width, GLsizei height) { // Currently a no-op } ID3D11Resource *RenderTarget11::getTexture() const { return mTexture; } ID3D11RenderTargetView *RenderTarget11::getRenderTargetView() const { return mRenderTarget; } ID3D11DepthStencilView *RenderTarget11::getDepthStencilView() const { return mDepthStencil; } ID3D11ShaderResourceView *RenderTarget11::getShaderResourceView() const { return mShaderResource; } unsigned int RenderTarget11::getSubresourceIndex() const { return mSubresourceIndex; } } <commit_msg>Prevents multisample depthstencil from being bound as an SRV<commit_after>#include "precompiled.h" // // Copyright (c) 2012 The ANGLE 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. // // RenderTarget11.cpp: Implements a DX11-specific wrapper for ID3D11View pointers // retained by Renderbuffers. #include "libGLESv2/renderer/d3d11/RenderTarget11.h" #include "libGLESv2/renderer/d3d11/Renderer11.h" #include "libGLESv2/renderer/d3d11/renderer11_utils.h" #include "libGLESv2/renderer/d3d11/formatutils11.h" #include "libGLESv2/main.h" namespace rx { static bool getTextureProperties(ID3D11Resource *resource, unsigned int *mipLevels, unsigned int *samples) { ID3D11Texture1D *texture1D = d3d11::DynamicCastComObject<ID3D11Texture1D>(resource); if (texture1D) { D3D11_TEXTURE1D_DESC texDesc; texture1D->GetDesc(&texDesc); SafeRelease(texture1D); *mipLevels = texDesc.MipLevels; *samples = 0; return true; } ID3D11Texture2D *texture2D = d3d11::DynamicCastComObject<ID3D11Texture2D>(resource); if (texture2D) { D3D11_TEXTURE2D_DESC texDesc; texture2D->GetDesc(&texDesc); SafeRelease(texture2D); *mipLevels = texDesc.MipLevels; *samples = texDesc.SampleDesc.Count > 1 ? texDesc.SampleDesc.Count : 0; return true; } ID3D11Texture3D *texture3D = d3d11::DynamicCastComObject<ID3D11Texture3D>(resource); if (texture3D) { D3D11_TEXTURE3D_DESC texDesc; texture3D->GetDesc(&texDesc); SafeRelease(texture3D); *mipLevels = texDesc.MipLevels; *samples = 0; return true; } return false; } static unsigned int getRTVSubresourceIndex(ID3D11Resource *resource, ID3D11RenderTargetView *view) { D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; view->GetDesc(&rtvDesc); unsigned int mipSlice = 0; unsigned int arraySlice = 0; switch (rtvDesc.ViewDimension) { case D3D11_RTV_DIMENSION_TEXTURE1D: mipSlice = rtvDesc.Texture1D.MipSlice; arraySlice = 0; break; case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: mipSlice = rtvDesc.Texture1DArray.MipSlice; arraySlice = rtvDesc.Texture1DArray.FirstArraySlice; break; case D3D11_RTV_DIMENSION_TEXTURE2D: mipSlice = rtvDesc.Texture2D.MipSlice; arraySlice = 0; break; case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: mipSlice = rtvDesc.Texture2DArray.MipSlice; arraySlice = rtvDesc.Texture2DArray.FirstArraySlice; break; case D3D11_RTV_DIMENSION_TEXTURE2DMS: mipSlice = 0; arraySlice = 0; break; case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: mipSlice = 0; arraySlice = rtvDesc.Texture2DMSArray.FirstArraySlice; break; case D3D11_RTV_DIMENSION_TEXTURE3D: mipSlice = rtvDesc.Texture3D.MipSlice; arraySlice = 0; break; case D3D11_RTV_DIMENSION_UNKNOWN: case D3D11_RTV_DIMENSION_BUFFER: UNIMPLEMENTED(); break; default: UNREACHABLE(); break; } unsigned int mipLevels, samples; getTextureProperties(resource, &mipLevels, &samples); return D3D11CalcSubresource(mipSlice, arraySlice, mipLevels); } static unsigned int getDSVSubresourceIndex(ID3D11Resource *resource, ID3D11DepthStencilView *view) { D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; view->GetDesc(&dsvDesc); unsigned int mipSlice = 0; unsigned int arraySlice = 0; switch (dsvDesc.ViewDimension) { case D3D11_DSV_DIMENSION_TEXTURE1D: mipSlice = dsvDesc.Texture1D.MipSlice; arraySlice = 0; break; case D3D11_DSV_DIMENSION_TEXTURE1DARRAY: mipSlice = dsvDesc.Texture1DArray.MipSlice; arraySlice = dsvDesc.Texture1DArray.FirstArraySlice; break; case D3D11_DSV_DIMENSION_TEXTURE2D: mipSlice = dsvDesc.Texture2D.MipSlice; arraySlice = 0; break; case D3D11_DSV_DIMENSION_TEXTURE2DARRAY: mipSlice = dsvDesc.Texture2DArray.MipSlice; arraySlice = dsvDesc.Texture2DArray.FirstArraySlice; break; case D3D11_DSV_DIMENSION_TEXTURE2DMS: mipSlice = 0; arraySlice = 0; break; case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY: mipSlice = 0; arraySlice = dsvDesc.Texture2DMSArray.FirstArraySlice; break; case D3D11_DSV_DIMENSION_UNKNOWN: UNIMPLEMENTED(); break; default: UNREACHABLE(); break; } unsigned int mipLevels, samples; getTextureProperties(resource, &mipLevels, &samples); return D3D11CalcSubresource(mipSlice, arraySlice, mipLevels); } RenderTarget11::RenderTarget11(Renderer *renderer, ID3D11RenderTargetView *rtv, ID3D11Resource *resource, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height, GLsizei depth) { mRenderer = Renderer11::makeRenderer11(renderer); mTexture = resource; if (mTexture) { mTexture->AddRef(); } mRenderTarget = rtv; if (mRenderTarget) { mRenderTarget->AddRef(); } mDepthStencil = NULL; mShaderResource = srv; if (mShaderResource) { mShaderResource->AddRef(); } mSubresourceIndex = 0; if (mRenderTarget && mTexture) { D3D11_RENDER_TARGET_VIEW_DESC desc; mRenderTarget->GetDesc(&desc); unsigned int mipLevels, samples; getTextureProperties(mTexture, &mipLevels, &samples); mSubresourceIndex = getRTVSubresourceIndex(mTexture, mRenderTarget); mWidth = width; mHeight = height; mDepth = depth; mSamples = samples; mInternalFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); mActualFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); } } RenderTarget11::RenderTarget11(Renderer *renderer, ID3D11DepthStencilView *dsv, ID3D11Resource *resource, ID3D11ShaderResourceView *srv, GLsizei width, GLsizei height, GLsizei depth) { mRenderer = Renderer11::makeRenderer11(renderer); mTexture = resource; if (mTexture) { mTexture->AddRef(); } mRenderTarget = NULL; mDepthStencil = dsv; if (mDepthStencil) { mDepthStencil->AddRef(); } mShaderResource = srv; if (mShaderResource) { mShaderResource->AddRef(); } mSubresourceIndex = 0; if (mDepthStencil && mTexture) { D3D11_DEPTH_STENCIL_VIEW_DESC desc; mDepthStencil->GetDesc(&desc); unsigned int mipLevels, samples; getTextureProperties(mTexture, &mipLevels, &samples); mSubresourceIndex = getDSVSubresourceIndex(mTexture, mDepthStencil); mWidth = width; mHeight = height; mDepth = depth; mSamples = samples; mInternalFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); mActualFormat = d3d11_gl::GetInternalFormat(desc.Format, renderer->getCurrentClientVersion()); } } RenderTarget11::RenderTarget11(Renderer *renderer, GLsizei width, GLsizei height, GLenum internalFormat, GLsizei samples) { mRenderer = Renderer11::makeRenderer11(renderer); mTexture = NULL; mRenderTarget = NULL; mDepthStencil = NULL; mShaderResource = NULL; GLuint clientVersion = mRenderer->getCurrentClientVersion(); DXGI_FORMAT texFormat = gl_d3d11::GetTexFormat(internalFormat, clientVersion); DXGI_FORMAT srvFormat = gl_d3d11::GetSRVFormat(internalFormat, clientVersion); DXGI_FORMAT rtvFormat = gl_d3d11::GetRTVFormat(internalFormat, clientVersion); DXGI_FORMAT dsvFormat = gl_d3d11::GetDSVFormat(internalFormat, clientVersion); DXGI_FORMAT multisampleFormat = (dsvFormat != DXGI_FORMAT_UNKNOWN ? dsvFormat : rtvFormat); int supportedSamples = mRenderer->getNearestSupportedSamples(multisampleFormat, samples); if (supportedSamples < 0) { gl::error(GL_OUT_OF_MEMORY); return; } if (width > 0 && height > 0) { // Create texture resource D3D11_TEXTURE2D_DESC desc; desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = texFormat; desc.SampleDesc.Count = (supportedSamples == 0) ? 1 : supportedSamples; desc.SampleDesc.Quality = 0; desc.Usage = D3D11_USAGE_DEFAULT; desc.CPUAccessFlags = 0; desc.MiscFlags = 0; // If a rendertarget or depthstencil format exists for this texture format, // we'll flag it to allow binding that way. Shader resource views are a little // more complicated. bool bindRTV = false, bindDSV = false, bindSRV = false; bindRTV = (rtvFormat != DXGI_FORMAT_UNKNOWN); bindDSV = (dsvFormat != DXGI_FORMAT_UNKNOWN); if (srvFormat != DXGI_FORMAT_UNKNOWN) { // Multisample targets flagged for binding as depth stencil cannot also be // flagged for binding as SRV, so make certain not to add the SRV flag for // these targets. bindSRV = !(dsvFormat != DXGI_FORMAT_UNKNOWN && desc.SampleDesc.Count > 1); } desc.BindFlags = (bindRTV ? D3D11_BIND_RENDER_TARGET : 0) | (bindDSV ? D3D11_BIND_DEPTH_STENCIL : 0) | (bindSRV ? D3D11_BIND_SHADER_RESOURCE : 0); ID3D11Device *device = mRenderer->getDevice(); ID3D11Texture2D *texture = NULL; HRESULT result = device->CreateTexture2D(&desc, NULL, &texture); mTexture = texture; if (result == E_OUTOFMEMORY) { gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); if (bindSRV) { D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; srvDesc.Format = srvFormat; srvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_SRV_DIMENSION_TEXTURE2D : D3D11_SRV_DIMENSION_TEXTURE2DMS; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.MipLevels = 1; result = device->CreateShaderResourceView(mTexture, &srvDesc, &mShaderResource); if (result == E_OUTOFMEMORY) { SafeRelease(mTexture); gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); } if (bindDSV) { D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; dsvDesc.Format = dsvFormat; dsvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_DSV_DIMENSION_TEXTURE2D : D3D11_DSV_DIMENSION_TEXTURE2DMS; dsvDesc.Texture2D.MipSlice = 0; dsvDesc.Flags = 0; result = device->CreateDepthStencilView(mTexture, &dsvDesc, &mDepthStencil); if (result == E_OUTOFMEMORY) { SafeRelease(mTexture); SafeRelease(mShaderResource); gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); } if (bindRTV) { D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; rtvDesc.Format = rtvFormat; rtvDesc.ViewDimension = (supportedSamples == 0) ? D3D11_RTV_DIMENSION_TEXTURE2D : D3D11_RTV_DIMENSION_TEXTURE2DMS; rtvDesc.Texture2D.MipSlice = 0; result = device->CreateRenderTargetView(mTexture, &rtvDesc, &mRenderTarget); if (result == E_OUTOFMEMORY) { SafeRelease(mTexture); SafeRelease(mShaderResource); SafeRelease(mDepthStencil); gl::error(GL_OUT_OF_MEMORY); return; } ASSERT(SUCCEEDED(result)); if (gl_d3d11::RequiresTextureDataInitialization(internalFormat)) { ID3D11DeviceContext *context = mRenderer->getDeviceContext(); const float clearValues[4] = { 0.0f, 0.0f, 0.0f, 1.0f }; context->ClearRenderTargetView(mRenderTarget, clearValues); } } } mWidth = width; mHeight = height; mDepth = 1; mInternalFormat = internalFormat; mSamples = supportedSamples; mActualFormat = d3d11_gl::GetInternalFormat(texFormat, renderer->getCurrentClientVersion()); mSubresourceIndex = D3D11CalcSubresource(0, 0, 1); } RenderTarget11::~RenderTarget11() { SafeRelease(mTexture); SafeRelease(mRenderTarget); SafeRelease(mDepthStencil); SafeRelease(mShaderResource); } RenderTarget11 *RenderTarget11::makeRenderTarget11(RenderTarget *target) { ASSERT(HAS_DYNAMIC_TYPE(rx::RenderTarget11*, target)); return static_cast<rx::RenderTarget11*>(target); } void RenderTarget11::invalidate(GLint x, GLint y, GLsizei width, GLsizei height) { // Currently a no-op } ID3D11Resource *RenderTarget11::getTexture() const { return mTexture; } ID3D11RenderTargetView *RenderTarget11::getRenderTargetView() const { return mRenderTarget; } ID3D11DepthStencilView *RenderTarget11::getDepthStencilView() const { return mDepthStencil; } ID3D11ShaderResourceView *RenderTarget11::getShaderResourceView() const { return mShaderResource; } unsigned int RenderTarget11::getSubresourceIndex() const { return mSubresourceIndex; } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2017-2018 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "core_io.h" #include "base58.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" #include "streams.h" #include <univalue.h> #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" std::string FormatScript(const CScript& script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = { {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")}, {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")}, {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")}, {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, }; /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format * of a signature. Only pass true for scripts you believe could contain signatures. For example, * pass false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // checks in CheckSignatureEncoding. if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode. } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); for(const CTxDestination& addr : addresses) a.push_back(CGuldenAddress(addr).ToString()); out.pushKV("addresses", a); } void StandardKeyHashToUniv(const CTxOut& txout, UniValue& out, bool fIncludeHex) { if (fIncludeHex) out.pushKV("hex", txout.output.GetHex()); out.pushKV("address", CGuldenAddress(txout.output.standardKeyHash.keyID).ToString()); } void PoW2WitnessToUniv(const CTxOut& txout, UniValue& out, bool fIncludeHex) { if (fIncludeHex) out.pushKV("hex", txout.output.GetHex()); out.pushKV("lock_from_block", txout.output.witnessDetails.lockFromBlock); out.pushKV("lock_until_block", txout.output.witnessDetails.lockUntilBlock); out.pushKV("fail_count", txout.output.witnessDetails.failCount); out.pushKV("action_nonce", txout.output.witnessDetails.actionNonce); out.pushKV("pubkey_spend", txout.output.witnessDetails.spendingKeyID.ToString()); out.pushKV("pubkey_witness", txout.output.witnessDetails.witnessKeyID.ToString()); out.pushKV("address", CGuldenAddress(CPoW2WitnessDestination(txout.output.witnessDetails.spendingKeyID, txout.output.witnessDetails.witnessKeyID)).ToString()); } void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry) { entry.pushKV("txid", tx.GetHash().GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)); entry.pushKV("vsize", GetTransactionWeight(tx)); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn& txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase() && !tx.IsPoW2WitnessCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { if ( tx.IsPoW2WitnessCoinBase() ) { in.pushKV("pow2_coinbase", ""); } if (txin.prevout.isHash) { in.pushKV("prevout_type", "hash"); in.pushKV("txid", txin.prevout.getHash().GetHex()); in.pushKV("tx_height", ""); in.pushKV("tx_index", ""); } else { in.pushKV("prevout_type", "index"); in.pushKV("txid", ""); in.pushKV("tx_height", txin.prevout.prevBlock.blockNumber); in.pushKV("tx_index", txin.prevout.prevBlock.transactionIndex); } in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); if (!tx.vin[i].segregatedSignatureData.IsNull()) { UniValue txinSigData(UniValue::VARR); for (const auto& item : tx.vin[i].segregatedSignatureData.stack) { txinSigData.push_back(HexStr(item.begin(), item.end())); } in.pushKV("txin_sig_data", txinSigData); } } if (IsOldTransactionVersion(tx.nVersion) || txin.FlagIsSet(CTxInFlags::HasRelativeLock)) in.pushKV("sequence", (int64_t)txin.GetSequence(tx.nVersion)); if (txin.FlagIsSet(CTxInFlags::OptInRBF)) in.pushKV("rbf", true); else in.pushKV("rbf", false); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue)); out.pushKV("value", outValue); out.pushKV("n", (int64_t)i); if (txout.GetType() <= CTxOutType::ScriptLegacyOutput) { UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.output.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } else if (txout.GetType() == CTxOutType::PoW2WitnessOutput) { UniValue o(UniValue::VOBJ); PoW2WitnessToUniv(txout, o, true); out.pushKV("PoW²-witness", o); vout.push_back(out); } else if (txout.GetType() == CTxOutType::StandardKeyHashOutput) { UniValue o(UniValue::VOBJ); StandardKeyHashToUniv(txout, o, true); out.pushKV("standard-key-hash", o); vout.push_back(out); } else { assert(0); } } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". } <commit_msg>MISC: Minor build fix.<commit_after>// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2017-2018 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING #include "core_io.h" #include "base58.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" #include "streams.h" #include <univalue.h> #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" std::string FormatScript(const CScript& script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = { {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")}, {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")}, {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")}, {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, }; /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format * of a signature. Only pass true for scripts you believe could contain signatures. For example, * pass false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // checks in CheckSignatureEncoding. if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode. } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); for(const CTxDestination& addr : addresses) a.push_back(CGuldenAddress(addr).ToString()); out.pushKV("addresses", a); } void StandardKeyHashToUniv(const CTxOut& txout, UniValue& out, bool fIncludeHex) { if (fIncludeHex) out.pushKV("hex", txout.output.GetHex()); out.pushKV("address", CGuldenAddress(txout.output.standardKeyHash.keyID).ToString()); } void PoW2WitnessToUniv(const CTxOut& txout, UniValue& out, bool fIncludeHex) { if (fIncludeHex) out.pushKV("hex", txout.output.GetHex()); out.pushKV("lock_from_block", txout.output.witnessDetails.lockFromBlock); out.pushKV("lock_until_block", txout.output.witnessDetails.lockUntilBlock); out.pushKV("fail_count", txout.output.witnessDetails.failCount); out.pushKV("action_nonce", txout.output.witnessDetails.actionNonce); out.pushKV("pubkey_spend", txout.output.witnessDetails.spendingKeyID.ToString()); out.pushKV("pubkey_witness", txout.output.witnessDetails.witnessKeyID.ToString()); out.pushKV("address", CGuldenAddress(CPoW2WitnessDestination(txout.output.witnessDetails.spendingKeyID, txout.output.witnessDetails.witnessKeyID)).ToString()); } void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry) { entry.pushKV("txid", tx.GetHash().GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)); entry.pushKV("vsize", GetTransactionWeight(tx)); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn& txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase() && !tx.IsPoW2WitnessCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { if ( tx.IsPoW2WitnessCoinBase() ) { in.pushKV("pow2_coinbase", ""); } if (txin.prevout.isHash) { in.pushKV("prevout_type", "hash"); in.pushKV("txid", txin.prevout.getHash().GetHex()); in.pushKV("tx_height", ""); in.pushKV("tx_index", ""); } else { in.pushKV("prevout_type", "index"); in.pushKV("txid", ""); in.pushKV("tx_height", txin.prevout.getTransactionBlockNumber()); in.pushKV("tx_index", txin.prevout.getTransactionIndex()); } in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); if (!tx.vin[i].segregatedSignatureData.IsNull()) { UniValue txinSigData(UniValue::VARR); for (const auto& item : tx.vin[i].segregatedSignatureData.stack) { txinSigData.push_back(HexStr(item.begin(), item.end())); } in.pushKV("txin_sig_data", txinSigData); } } if (IsOldTransactionVersion(tx.nVersion) || txin.FlagIsSet(CTxInFlags::HasRelativeLock)) in.pushKV("sequence", (int64_t)txin.GetSequence(tx.nVersion)); if (txin.FlagIsSet(CTxInFlags::OptInRBF)) in.pushKV("rbf", true); else in.pushKV("rbf", false); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue)); out.pushKV("value", outValue); out.pushKV("n", (int64_t)i); if (txout.GetType() <= CTxOutType::ScriptLegacyOutput) { UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.output.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } else if (txout.GetType() == CTxOutType::PoW2WitnessOutput) { UniValue o(UniValue::VOBJ); PoW2WitnessToUniv(txout, o, true); out.pushKV("PoW²-witness", o); vout.push_back(out); } else if (txout.GetType() == CTxOutType::StandardKeyHashOutput) { UniValue o(UniValue::VOBJ); StandardKeyHashToUniv(txout, o, true); out.pushKV("standard-key-hash", o); vout.push_back(out); } else { assert(0); } } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". } <|endoftext|>
<commit_before>// Copyright 2011 Google Inc. 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 "msvc_helper.h" #include <fcntl.h> #include <io.h> #include <stdio.h> #include <windows.h> #include "util.h" #include "getopt.h" namespace { void Usage() { printf( "usage: ninja -t msvc [options] -- cl.exe /showIncludes /otherArgs\n" "options:\n" " -e ENVFILE load environment block from ENVFILE as environment\n" " -o FILE write output dependency information to FILE.d\n" ); } void PushPathIntoEnvironment(const string& env_block) { const char* as_str = env_block.c_str(); while (as_str[0]) { if (_strnicmp(as_str, "path=", 5) == 0) { _putenv(as_str); return; } else { as_str = &as_str[strlen(as_str) + 1]; } } } void WriteDepFileOrDie(const char* object_path, const CLParser& parse) { string depfile_path = string(object_path) + ".d"; FILE* depfile = fopen(depfile_path.c_str(), "w"); if (!depfile) { unlink(object_path); Fatal("opening %s: %s", depfile_path.c_str(), GetLastErrorString().c_str()); } if (fprintf(depfile, "%s: ", object_path) < 0) { unlink(object_path); fclose(depfile); unlink(depfile_path.c_str()); Fatal("writing %s", depfile_path.c_str()); } const set<string>& headers = parse.includes_; for (set<string>::const_iterator i = headers.begin(); i != headers.end(); ++i) { if (fprintf(depfile, "%s\n", EscapeForDepfile(*i).c_str()) < 0) { unlink(object_path); fclose(depfile); unlink(depfile_path.c_str()); Fatal("writing %s", depfile_path.c_str()); } } fclose(depfile); } } // anonymous namespace int MSVCHelperMain(int argc, char** argv) { const char* output_filename = NULL; const char* envfile = NULL; const option kLongOptions[] = { { "help", no_argument, NULL, 'h' }, { NULL, 0, NULL, 0 } }; int opt; while ((opt = getopt_long(argc, argv, "e:o:h", kLongOptions, NULL)) != -1) { switch (opt) { case 'e': envfile = optarg; break; case 'o': output_filename = optarg; break; case 'h': default: Usage(); return 0; } } string env; if (envfile) { string err; if (ReadFile(envfile, &env, &err) != 0) Fatal("couldn't open %s: %s", envfile, err.c_str()); PushPathIntoEnvironment(env); } char* command = GetCommandLine(); command = strstr(command, " -- "); if (!command) { Fatal("expected command line to end with \" -- command args\""); } command += 4; CLWrapper cl; if (!env.empty()) cl.SetEnvBlock((void*)env.data()); string output; int exit_code = cl.Run(command, &output); if (output_filename) { CLParser parser; output = parser.Parse(output); WriteDepFileOrDie(output_filename, parser); } // CLWrapper's output already as \r\n line endings, make sure the C runtime // doesn't expand this to \r\r\n. _setmode(_fileno(stdout), _O_BINARY); printf("%s", output.c_str()); return exit_code; } <commit_msg>Use fwrite in the msvc tool instead of printf<commit_after>// Copyright 2011 Google Inc. 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 "msvc_helper.h" #include <fcntl.h> #include <io.h> #include <stdio.h> #include <windows.h> #include "util.h" #include "getopt.h" namespace { void Usage() { printf( "usage: ninja -t msvc [options] -- cl.exe /showIncludes /otherArgs\n" "options:\n" " -e ENVFILE load environment block from ENVFILE as environment\n" " -o FILE write output dependency information to FILE.d\n" ); } void PushPathIntoEnvironment(const string& env_block) { const char* as_str = env_block.c_str(); while (as_str[0]) { if (_strnicmp(as_str, "path=", 5) == 0) { _putenv(as_str); return; } else { as_str = &as_str[strlen(as_str) + 1]; } } } void WriteDepFileOrDie(const char* object_path, const CLParser& parse) { string depfile_path = string(object_path) + ".d"; FILE* depfile = fopen(depfile_path.c_str(), "w"); if (!depfile) { unlink(object_path); Fatal("opening %s: %s", depfile_path.c_str(), GetLastErrorString().c_str()); } if (fprintf(depfile, "%s: ", object_path) < 0) { unlink(object_path); fclose(depfile); unlink(depfile_path.c_str()); Fatal("writing %s", depfile_path.c_str()); } const set<string>& headers = parse.includes_; for (set<string>::const_iterator i = headers.begin(); i != headers.end(); ++i) { if (fprintf(depfile, "%s\n", EscapeForDepfile(*i).c_str()) < 0) { unlink(object_path); fclose(depfile); unlink(depfile_path.c_str()); Fatal("writing %s", depfile_path.c_str()); } } fclose(depfile); } } // anonymous namespace int MSVCHelperMain(int argc, char** argv) { const char* output_filename = NULL; const char* envfile = NULL; const option kLongOptions[] = { { "help", no_argument, NULL, 'h' }, { NULL, 0, NULL, 0 } }; int opt; while ((opt = getopt_long(argc, argv, "e:o:h", kLongOptions, NULL)) != -1) { switch (opt) { case 'e': envfile = optarg; break; case 'o': output_filename = optarg; break; case 'h': default: Usage(); return 0; } } string env; if (envfile) { string err; if (ReadFile(envfile, &env, &err) != 0) Fatal("couldn't open %s: %s", envfile, err.c_str()); PushPathIntoEnvironment(env); } char* command = GetCommandLine(); command = strstr(command, " -- "); if (!command) { Fatal("expected command line to end with \" -- command args\""); } command += 4; CLWrapper cl; if (!env.empty()) cl.SetEnvBlock((void*)env.data()); string output; int exit_code = cl.Run(command, &output); if (output_filename) { CLParser parser; output = parser.Parse(output); WriteDepFileOrDie(output_filename, parser); } // CLWrapper's output already as \r\n line endings, make sure the C runtime // doesn't expand this to \r\r\n. _setmode(_fileno(stdout), _O_BINARY); // Avoid printf and C strings, since the actual output might contain null // bytes like UTF-16 does (yuck). fwrite(&output[0], sizeof(char), output.size(), stdout); return exit_code; } <|endoftext|>
<commit_before>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ /** * @file DatasetInputLayer.cpp * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com) */ #include <vector> #include <array> #include <random> #include <algorithm> #include <cstring> #include "NetGraph.h" #include "DatasetInputLayer.h" namespace Conv { DatasetInputLayer::DatasetInputLayer (Dataset& dataset, const unsigned int batch_size, const datum loss_sampling_p, const unsigned int seed) : dataset_ (dataset), batch_size_ (batch_size), loss_sampling_p_ (loss_sampling_p), seed_ (seed), generator_ (seed), dist_ (0.0, 1.0) { LOGDEBUG << "Instance created."; label_maps_ = dataset_.GetLabelMaps(); input_maps_ = dataset_.GetInputMaps(); if (seed == 0) { LOGWARN << "Random seed is zero"; } if(dataset_.GetMethod() == FCN) LOGDEBUG << "Using loss sampling probability: " << loss_sampling_p_; elements_training_ = dataset_.GetTrainingSamples(); elements_testing_ = dataset_.GetTestingSamples(); elements_total_ = elements_training_ + elements_testing_; LOGDEBUG << "Total samples: " << elements_total_; // Generate random permutation of the samples // First, we need an array of ascending numbers for (unsigned int i = 0; i < elements_training_; i++) { perm_.push_back (i); } RedoPermutation(); } bool DatasetInputLayer::CreateOutputs (const std::vector< CombinedTensor* >& inputs, std::vector< CombinedTensor* >& outputs) { if (inputs.size() != 0) { LOGERROR << "Inputs specified but not supported"; return false; } if (dataset_.GetMethod() == FCN) { CombinedTensor* data_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), input_maps_); CombinedTensor* label_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), label_maps_); CombinedTensor* helper_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), 2); CombinedTensor* localized_error_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), 1); outputs.push_back (data_output); outputs.push_back (label_output); outputs.push_back (helper_output); outputs.push_back (localized_error_output); } else if (dataset_.GetMethod() == PATCH) { CombinedTensor* data_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), input_maps_); CombinedTensor* label_output = new CombinedTensor (batch_size_, 1, 1, label_maps_); CombinedTensor* helper_output = new CombinedTensor (batch_size_, 1, 1, 2); CombinedTensor* localized_error_output = new CombinedTensor (batch_size_, 1, 1, 1); outputs.push_back (data_output); outputs.push_back (label_output); outputs.push_back (helper_output); outputs.push_back (localized_error_output); } return true; } bool DatasetInputLayer::Connect (const std::vector< CombinedTensor* >& inputs, const std::vector< CombinedTensor* >& outputs, const NetStatus* net) { // TODO validate CombinedTensor* data_output = outputs[0]; CombinedTensor* label_output = outputs[1]; CombinedTensor* helper_output = outputs[2]; CombinedTensor* localized_error_output = outputs[3]; if (data_output == nullptr || label_output == nullptr || localized_error_output == nullptr) return false; bool valid = inputs.size() == 0 && outputs.size() == 4; if (valid) { data_output_ = data_output; label_output_ = label_output; helper_output_ = helper_output; localized_error_output_ = localized_error_output; } return valid; } void DatasetInputLayer::FeedForward() { #ifdef BUILD_OPENCL data_output_->data.MoveToCPU (true); label_output_->data.MoveToCPU (true); localized_error_output_->data.MoveToCPU (true); #endif for (std::size_t sample = 0; sample < batch_size_; sample++) { unsigned int selected_element = 0; bool force_no_weight = false; if (testing_) { // The testing samples are not randomized selected_element = current_element_testing_; current_element_testing_++; if (current_element_testing_ >= elements_testing_) { force_no_weight = true; selected_element = 0; } } else { // Select samples until one from the right subset is hit // Select a sample from the permutation selected_element = perm_[current_element_]; // Select next element current_element_++; // If this is is out of bounds, start at the beginning and randomize // again. if (current_element_ >= perm_.size()) { current_element_ = 0; RedoPermutation(); } } // Copy image and label bool success; if (testing_) success = dataset_.GetTestingSample (data_output_->data, label_output_->data, helper_output_->data, localized_error_output_->data, sample, selected_element); else success = dataset_.GetTrainingSample (data_output_->data, label_output_->data, helper_output_->data, localized_error_output_->data, sample, selected_element); if (!success) { FATAL ("Cannot load samples from Dataset!"); } if (!testing_ && !force_no_weight && dataset_.GetMethod() == FCN) { // Perform loss sampling #ifdef BUILD_OPENCL localized_error_output_->data.MoveToGPU(); #endif const unsigned int block_size = 12; for (unsigned int y = 0; y < localized_error_output_->data.height(); y += block_size) { for (unsigned int x = 0; x < localized_error_output_->data.width(); x += block_size) { if (dist_ (generator_) > loss_sampling_p_) { for (unsigned int iy = y; iy < y + block_size && iy < localized_error_output_->data.height(); iy++) { for (unsigned int ix = x; ix < x + block_size && ix < localized_error_output_->data.width(); ix++) { *localized_error_output_->data.data_ptr (ix, iy, 0, sample) = 0; } } } } } } // Copy localized error if (force_no_weight) localized_error_output_->data.Clear (0.0, sample); } } void DatasetInputLayer::BackPropagate() { // No inputs, no backprop. } unsigned int DatasetInputLayer::GetBatchSize() { return batch_size_; } unsigned int DatasetInputLayer::GetLabelWidth() { return (dataset_.GetMethod() == PATCH) ? 1 : dataset_.GetWidth(); } unsigned int DatasetInputLayer::GetLabelHeight() { return (dataset_.GetMethod() == PATCH) ? 1 : dataset_.GetHeight(); } unsigned int DatasetInputLayer::GetSamplesInTestingSet() { return dataset_.GetTestingSamples(); } unsigned int DatasetInputLayer::GetSamplesInTrainingSet() { return dataset_.GetTrainingSamples(); } void DatasetInputLayer::RedoPermutation() { // Shuffle the array std::shuffle (perm_.begin(), perm_.end(), generator_); } void DatasetInputLayer::SetTestingMode (bool testing) { if (testing != testing_) { if (testing) { LOGDEBUG << "Enabled testing mode."; // Always test the same elements for consistency current_element_testing_ = 0; } else { LOGDEBUG << "Enabled training mode."; } } testing_ = testing; } void DatasetInputLayer::CreateBufferDescriptors(std::vector<NetGraphBuffer>& buffers) { NetGraphBuffer data_buffer; NetGraphBuffer label_buffer; NetGraphBuffer helper_buffer; NetGraphBuffer weight_buffer; data_buffer.description = "Data Output"; label_buffer.description = "Label"; helper_buffer.description = "Helper"; weight_buffer.description = "Weight"; buffers.push_back(data_buffer); buffers.push_back(label_buffer); buffers.push_back(helper_buffer); buffers.push_back(weight_buffer); } bool DatasetInputLayer::IsOpenCLAware() { #ifdef BUILD_OPENCL return true; #else return false; #endif } } <commit_msg>DatasetInputLayer: Fixed bug skipping first test sample<commit_after>/* * This file is part of the CN24 semantic segmentation software, * copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com). * * For licensing information, see the LICENSE file included with this project. */ /** * @file DatasetInputLayer.cpp * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com) */ #include <vector> #include <array> #include <random> #include <algorithm> #include <cstring> #include "NetGraph.h" #include "DatasetInputLayer.h" namespace Conv { DatasetInputLayer::DatasetInputLayer (Dataset& dataset, const unsigned int batch_size, const datum loss_sampling_p, const unsigned int seed) : dataset_ (dataset), batch_size_ (batch_size), loss_sampling_p_ (loss_sampling_p), seed_ (seed), generator_ (seed), dist_ (0.0, 1.0) { LOGDEBUG << "Instance created."; label_maps_ = dataset_.GetLabelMaps(); input_maps_ = dataset_.GetInputMaps(); if (seed == 0) { LOGWARN << "Random seed is zero"; } if(dataset_.GetMethod() == FCN) LOGDEBUG << "Using loss sampling probability: " << loss_sampling_p_; elements_training_ = dataset_.GetTrainingSamples(); elements_testing_ = dataset_.GetTestingSamples(); elements_total_ = elements_training_ + elements_testing_; LOGDEBUG << "Total samples: " << elements_total_; // Generate random permutation of the samples // First, we need an array of ascending numbers for (unsigned int i = 0; i < elements_training_; i++) { perm_.push_back (i); } RedoPermutation(); } bool DatasetInputLayer::CreateOutputs (const std::vector< CombinedTensor* >& inputs, std::vector< CombinedTensor* >& outputs) { if (inputs.size() != 0) { LOGERROR << "Inputs specified but not supported"; return false; } if (dataset_.GetMethod() == FCN) { CombinedTensor* data_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), input_maps_); CombinedTensor* label_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), label_maps_); CombinedTensor* helper_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), 2); CombinedTensor* localized_error_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), 1); outputs.push_back (data_output); outputs.push_back (label_output); outputs.push_back (helper_output); outputs.push_back (localized_error_output); } else if (dataset_.GetMethod() == PATCH) { CombinedTensor* data_output = new CombinedTensor (batch_size_, dataset_.GetWidth(), dataset_.GetHeight(), input_maps_); CombinedTensor* label_output = new CombinedTensor (batch_size_, 1, 1, label_maps_); CombinedTensor* helper_output = new CombinedTensor (batch_size_, 1, 1, 2); CombinedTensor* localized_error_output = new CombinedTensor (batch_size_, 1, 1, 1); outputs.push_back (data_output); outputs.push_back (label_output); outputs.push_back (helper_output); outputs.push_back (localized_error_output); } return true; } bool DatasetInputLayer::Connect (const std::vector< CombinedTensor* >& inputs, const std::vector< CombinedTensor* >& outputs, const NetStatus* net) { // TODO validate CombinedTensor* data_output = outputs[0]; CombinedTensor* label_output = outputs[1]; CombinedTensor* helper_output = outputs[2]; CombinedTensor* localized_error_output = outputs[3]; if (data_output == nullptr || label_output == nullptr || localized_error_output == nullptr) return false; bool valid = inputs.size() == 0 && outputs.size() == 4; if (valid) { data_output_ = data_output; label_output_ = label_output; helper_output_ = helper_output; localized_error_output_ = localized_error_output; } return valid; } void DatasetInputLayer::FeedForward() { #ifdef BUILD_OPENCL data_output_->data.MoveToCPU (true); label_output_->data.MoveToCPU (true); localized_error_output_->data.MoveToCPU (true); #endif for (std::size_t sample = 0; sample < batch_size_; sample++) { unsigned int selected_element = 0; bool force_no_weight = false; if (testing_) { // The testing samples are not randomized if (current_element_testing_ >= elements_testing_) { force_no_weight = true; selected_element = 0; } else { selected_element = current_element_testing_++; } } else { // Select samples until one from the right subset is hit // Select a sample from the permutation selected_element = perm_[current_element_]; // Select next element current_element_++; // If this is is out of bounds, start at the beginning and randomize // again. if (current_element_ >= perm_.size()) { current_element_ = 0; RedoPermutation(); } } // Copy image and label bool success; if (testing_) success = dataset_.GetTestingSample (data_output_->data, label_output_->data, helper_output_->data, localized_error_output_->data, sample, selected_element); else success = dataset_.GetTrainingSample (data_output_->data, label_output_->data, helper_output_->data, localized_error_output_->data, sample, selected_element); if (!success) { FATAL ("Cannot load samples from Dataset!"); } if (!testing_ && !force_no_weight && dataset_.GetMethod() == FCN) { // Perform loss sampling #ifdef BUILD_OPENCL localized_error_output_->data.MoveToGPU(); #endif const unsigned int block_size = 12; for (unsigned int y = 0; y < localized_error_output_->data.height(); y += block_size) { for (unsigned int x = 0; x < localized_error_output_->data.width(); x += block_size) { if (dist_ (generator_) > loss_sampling_p_) { for (unsigned int iy = y; iy < y + block_size && iy < localized_error_output_->data.height(); iy++) { for (unsigned int ix = x; ix < x + block_size && ix < localized_error_output_->data.width(); ix++) { *localized_error_output_->data.data_ptr (ix, iy, 0, sample) = 0; } } } } } } // Copy localized error if (force_no_weight) localized_error_output_->data.Clear (0.0, sample); } } void DatasetInputLayer::BackPropagate() { // No inputs, no backprop. } unsigned int DatasetInputLayer::GetBatchSize() { return batch_size_; } unsigned int DatasetInputLayer::GetLabelWidth() { return (dataset_.GetMethod() == PATCH) ? 1 : dataset_.GetWidth(); } unsigned int DatasetInputLayer::GetLabelHeight() { return (dataset_.GetMethod() == PATCH) ? 1 : dataset_.GetHeight(); } unsigned int DatasetInputLayer::GetSamplesInTestingSet() { return dataset_.GetTestingSamples(); } unsigned int DatasetInputLayer::GetSamplesInTrainingSet() { return dataset_.GetTrainingSamples(); } void DatasetInputLayer::RedoPermutation() { // Shuffle the array std::shuffle (perm_.begin(), perm_.end(), generator_); } void DatasetInputLayer::SetTestingMode (bool testing) { if (testing != testing_) { if (testing) { LOGDEBUG << "Enabled testing mode."; // Always test the same elements for consistency current_element_testing_ = 0; } else { LOGDEBUG << "Enabled training mode."; } } testing_ = testing; } void DatasetInputLayer::CreateBufferDescriptors(std::vector<NetGraphBuffer>& buffers) { NetGraphBuffer data_buffer; NetGraphBuffer label_buffer; NetGraphBuffer helper_buffer; NetGraphBuffer weight_buffer; data_buffer.description = "Data Output"; label_buffer.description = "Label"; helper_buffer.description = "Helper"; weight_buffer.description = "Weight"; buffers.push_back(data_buffer); buffers.push_back(label_buffer); buffers.push_back(helper_buffer); buffers.push_back(weight_buffer); } bool DatasetInputLayer::IsOpenCLAware() { #ifdef BUILD_OPENCL return true; #else return false; #endif } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "command.h" #include "commandlineoption.h" #include "commandlineoptionpool.h" #include <logging/translator.h> #include <tools/error.h> #include <tools/hostosinfo.h> #include <QSet> namespace qbs { using namespace Internal; Command::~Command() { } void Command::parse(QStringList &input) { parseOptions(input); parseMore(input); if (!input.isEmpty()) { throw Error(Tr::tr("Invalid use of command '%1': Extraneous input '%2'.\nUsage: %3") .arg(representation(), input.join(QLatin1String(" ")), longDescription())); } } void Command::addAllToAdditionalArguments(QStringList &input) { while (!input.isEmpty()) addOneToAdditionalArguments(input.takeFirst()); } // TODO: Stricter checking for build variants and properties. void Command::addOneToAdditionalArguments(const QString &argument) { if (argument.startsWith(QLatin1Char('-'))) { throw Error(Tr::tr("Invalid use of command '%1': Encountered option '%2'', expected a " "build variant or property.\nUsage: %3") .arg(representation(), argument, longDescription())); } m_additionalArguments << argument; } QList<CommandLineOption::Type> Command::actualSupportedOptions() const { QList<CommandLineOption::Type> options = supportedOptions(); if (!HostOsInfo::isAnyUnixHost()) options.removeOne(CommandLineOption::ShowProgressOptionType); return options; } void Command::parseOptions(QStringList &input) { QSet<CommandLineOption *> usedOptions; while (!input.isEmpty()) { const QString optionString = input.first(); if (!optionString.startsWith(QLatin1Char('-'))) break; input.removeFirst(); if (optionString.count() == 1) { throw Error(Tr::tr("Invalid use of command '%1': Empty options are not allowed.\n" "Usage: %2").arg(representation(), longDescription())); } // Split up grouped short options. if (optionString.at(1) != QLatin1Char('-') && optionString.count() > 2) { for (int i = optionString.count(); --i > 0;) input.prepend(QLatin1Char('-') + optionString.at(i)); continue; } bool matchFound = false; foreach (const CommandLineOption::Type optionType, actualSupportedOptions()) { CommandLineOption * const option = optionPool().getOption(optionType); if (option->shortRepresentation() != optionString && option->longRepresentation() != optionString) { continue; } if (usedOptions.contains(option) && !option->canAppearMoreThanOnce()) { throw Error(Tr::tr("Invalid use of command '%1': Option '%2' cannot appear " "more than once.\nUsage: %3") .arg(representation(), optionString, longDescription())); } option->parse(type(), optionString, input); usedOptions << option; matchFound = true; break; } if (!matchFound) { throw Error(Tr::tr("Invalid use of command '%1': Unknown option '%2'.\nUsage: %3") .arg(representation(), optionString, longDescription())); } } } QString Command::supportedOptionsDescription() const { QString s = Tr::tr("The possible options are:\n"); foreach (const CommandLineOption::Type opType, actualSupportedOptions()) { const CommandLineOption * const option = optionPool().getOption(opType); s += option->description(type()); } return s; } void Command::parseMore(QStringList &input) { addAllToAdditionalArguments(input); } QString BuildCommand::shortDescription() const { return Tr::tr("Build (parts of) a number of projects. This is the default command."); } QString BuildCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [[variant] [property:value] ...]\n") .arg(representation()); description += Tr::tr("Builds a project in one or more configuration(s).\n"); return description += supportedOptionsDescription(); } static QString buildCommandRepresentation() { return QLatin1String("build"); } QString BuildCommand::representation() const { return buildCommandRepresentation(); } QList<CommandLineOption::Type> BuildCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::JobsOptionType << CommandLineOption::KeepGoingOptionType << CommandLineOption::DryRunOptionType << CommandLineOption::ProductsOptionType << CommandLineOption::ChangedFilesOptionType; } QString CleanCommand::shortDescription() const { return Tr::tr("Remove the files generated during a build."); } QString CleanCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [[variant] [property:value] ...] ...\n"); description += Tr::tr("Removes build artifacts for the given project and configuration(s).\n"); return description += supportedOptionsDescription(); } QString CleanCommand::representation() const { return QLatin1String("clean"); } QList<CommandLineOption::Type> CleanCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::KeepGoingOptionType << CommandLineOption::DryRunOptionType << CommandLineOption::ProductsOptionType; } QString RunCommand::shortDescription() const { return QLatin1String("Run an executable generated by building a project."); } QString RunCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ... " "-- <target> <args>\n").arg(representation()); description += Tr::tr("Runs the specified target with the specified arguments.\n"); description += Tr::tr("The project will be built if it is not up to date; " "see the '%2' command.\n").arg(buildCommandRepresentation()); return description += supportedOptionsDescription(); } QString RunCommand::representation() const { return QLatin1String("run"); } QList<CommandLineOption::Type> RunCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::JobsOptionType << CommandLineOption::KeepGoingOptionType << CommandLineOption::DryRunOptionType << CommandLineOption::ProductsOptionType << CommandLineOption::ChangedFilesOptionType; } void RunCommand::parseMore(QStringList &input) { // Build variants and properties while (!input.isEmpty()) { const QString arg = input.takeFirst(); if (arg == QLatin1String("--")) break; addOneToAdditionalArguments(arg); } if (input.isEmpty()) { throw Error(Tr::tr("Invalid use of command '%1': Needs an executable to run.\nUsage: %2") .arg(representation(), longDescription())); } m_targetName = input.takeFirst(); m_targetParameters = input; input.clear(); } QString ShellCommand::shortDescription() const { return Tr::tr("Open a shell with a product's environment."); } QString ShellCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ...\n") .arg(representation()); description += Tr::tr("Opens a shell in the same environment that a build with the given " "parameters would use.\n"); const ProductsOption * const option = optionPool().productsOption(); description += Tr::tr("The '%1' option may be omitted if and only if the project has " "exactly one product.").arg(option->longRepresentation()); return description += supportedOptionsDescription(); } QString ShellCommand::representation() const { return QLatin1String("shell"); } QList<CommandLineOption::Type> ShellCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::ProductsOptionType; } QString PropertiesCommand::shortDescription() const { return Tr::tr("Show the project properties for a configuration."); } QString PropertiesCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ...\n") .arg(representation()); description += Tr::tr("Shows all properties of the project in the given configuration.\n"); return description += supportedOptionsDescription(); } QString PropertiesCommand::representation() const { return QLatin1String("properties"); } QList<CommandLineOption::Type> PropertiesCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::ProductsOptionType; } QString StatusCommand::shortDescription() const { return Tr::tr("Show the status of files in the project directory."); } QString StatusCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ...\n") .arg(representation()); description += Tr::tr("Lists all the files in the project directory and shows whether " "they are known to qbs in the respective configuration.\n"); return description += supportedOptionsDescription(); } QString StatusCommand::representation() const { return QLatin1String("status"); } QList<CommandLineOption::Type> StatusCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType; } QString HelpCommand::shortDescription() const { return Tr::tr("Show general or command-specific help."); } QString HelpCommand::longDescription() const { QString description = Tr::tr("qbs %1 [<command>]\n").arg(representation()); return description += Tr::tr("Shows either the general help or a description of " "the given command.\n"); } QString HelpCommand::representation() const { return QLatin1String("help"); } QList<CommandLineOption::Type> HelpCommand::supportedOptions() const { return QList<CommandLineOption::Type>(); } void HelpCommand::parseMore(QStringList &input) { if (input.isEmpty()) return; if (input.count() > 1) { throw Error(Tr::tr("Invalid use of command '%1': Cannot describe more than one command.\n" "Usage: %2").arg(representation(), longDescription())); } m_command = input.takeFirst(); Q_ASSERT(input.isEmpty()); } } // namespace qbs <commit_msg>Remove editor artifact.<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "command.h" #include "commandlineoption.h" #include "commandlineoptionpool.h" #include <logging/translator.h> #include <tools/error.h> #include <tools/hostosinfo.h> #include <QSet> namespace qbs { using namespace Internal; Command::~Command() { } void Command::parse(QStringList &input) { parseOptions(input); parseMore(input); if (!input.isEmpty()) { throw Error(Tr::tr("Invalid use of command '%1': Extraneous input '%2'.\nUsage: %3") .arg(representation(), input.join(QLatin1String(" ")), longDescription())); } } void Command::addAllToAdditionalArguments(QStringList &input) { while (!input.isEmpty()) addOneToAdditionalArguments(input.takeFirst()); } // TODO: Stricter checking for build variants and properties. void Command::addOneToAdditionalArguments(const QString &argument) { if (argument.startsWith(QLatin1Char('-'))) { throw Error(Tr::tr("Invalid use of command '%1': Encountered option '%2', expected a " "build variant or property.\nUsage: %3") .arg(representation(), argument, longDescription())); } m_additionalArguments << argument; } QList<CommandLineOption::Type> Command::actualSupportedOptions() const { QList<CommandLineOption::Type> options = supportedOptions(); if (!HostOsInfo::isAnyUnixHost()) options.removeOne(CommandLineOption::ShowProgressOptionType); return options; } void Command::parseOptions(QStringList &input) { QSet<CommandLineOption *> usedOptions; while (!input.isEmpty()) { const QString optionString = input.first(); if (!optionString.startsWith(QLatin1Char('-'))) break; input.removeFirst(); if (optionString.count() == 1) { throw Error(Tr::tr("Invalid use of command '%1': Empty options are not allowed.\n" "Usage: %2").arg(representation(), longDescription())); } // Split up grouped short options. if (optionString.at(1) != QLatin1Char('-') && optionString.count() > 2) { for (int i = optionString.count(); --i > 0;) input.prepend(QLatin1Char('-') + optionString.at(i)); continue; } bool matchFound = false; foreach (const CommandLineOption::Type optionType, actualSupportedOptions()) { CommandLineOption * const option = optionPool().getOption(optionType); if (option->shortRepresentation() != optionString && option->longRepresentation() != optionString) { continue; } if (usedOptions.contains(option) && !option->canAppearMoreThanOnce()) { throw Error(Tr::tr("Invalid use of command '%1': Option '%2' cannot appear " "more than once.\nUsage: %3") .arg(representation(), optionString, longDescription())); } option->parse(type(), optionString, input); usedOptions << option; matchFound = true; break; } if (!matchFound) { throw Error(Tr::tr("Invalid use of command '%1': Unknown option '%2'.\nUsage: %3") .arg(representation(), optionString, longDescription())); } } } QString Command::supportedOptionsDescription() const { QString s = Tr::tr("The possible options are:\n"); foreach (const CommandLineOption::Type opType, actualSupportedOptions()) { const CommandLineOption * const option = optionPool().getOption(opType); s += option->description(type()); } return s; } void Command::parseMore(QStringList &input) { addAllToAdditionalArguments(input); } QString BuildCommand::shortDescription() const { return Tr::tr("Build (parts of) a number of projects. This is the default command."); } QString BuildCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [[variant] [property:value] ...]\n") .arg(representation()); description += Tr::tr("Builds a project in one or more configuration(s).\n"); return description += supportedOptionsDescription(); } static QString buildCommandRepresentation() { return QLatin1String("build"); } QString BuildCommand::representation() const { return buildCommandRepresentation(); } QList<CommandLineOption::Type> BuildCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::JobsOptionType << CommandLineOption::KeepGoingOptionType << CommandLineOption::DryRunOptionType << CommandLineOption::ProductsOptionType << CommandLineOption::ChangedFilesOptionType; } QString CleanCommand::shortDescription() const { return Tr::tr("Remove the files generated during a build."); } QString CleanCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [[variant] [property:value] ...] ...\n"); description += Tr::tr("Removes build artifacts for the given project and configuration(s).\n"); return description += supportedOptionsDescription(); } QString CleanCommand::representation() const { return QLatin1String("clean"); } QList<CommandLineOption::Type> CleanCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::KeepGoingOptionType << CommandLineOption::DryRunOptionType << CommandLineOption::ProductsOptionType; } QString RunCommand::shortDescription() const { return QLatin1String("Run an executable generated by building a project."); } QString RunCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ... " "-- <target> <args>\n").arg(representation()); description += Tr::tr("Runs the specified target with the specified arguments.\n"); description += Tr::tr("The project will be built if it is not up to date; " "see the '%2' command.\n").arg(buildCommandRepresentation()); return description += supportedOptionsDescription(); } QString RunCommand::representation() const { return QLatin1String("run"); } QList<CommandLineOption::Type> RunCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::JobsOptionType << CommandLineOption::KeepGoingOptionType << CommandLineOption::DryRunOptionType << CommandLineOption::ProductsOptionType << CommandLineOption::ChangedFilesOptionType; } void RunCommand::parseMore(QStringList &input) { // Build variants and properties while (!input.isEmpty()) { const QString arg = input.takeFirst(); if (arg == QLatin1String("--")) break; addOneToAdditionalArguments(arg); } if (input.isEmpty()) { throw Error(Tr::tr("Invalid use of command '%1': Needs an executable to run.\nUsage: %2") .arg(representation(), longDescription())); } m_targetName = input.takeFirst(); m_targetParameters = input; input.clear(); } QString ShellCommand::shortDescription() const { return Tr::tr("Open a shell with a product's environment."); } QString ShellCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ...\n") .arg(representation()); description += Tr::tr("Opens a shell in the same environment that a build with the given " "parameters would use.\n"); const ProductsOption * const option = optionPool().productsOption(); description += Tr::tr("The '%1' option may be omitted if and only if the project has " "exactly one product.").arg(option->longRepresentation()); return description += supportedOptionsDescription(); } QString ShellCommand::representation() const { return QLatin1String("shell"); } QList<CommandLineOption::Type> ShellCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::ProductsOptionType; } QString PropertiesCommand::shortDescription() const { return Tr::tr("Show the project properties for a configuration."); } QString PropertiesCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ...\n") .arg(representation()); description += Tr::tr("Shows all properties of the project in the given configuration.\n"); return description += supportedOptionsDescription(); } QString PropertiesCommand::representation() const { return QLatin1String("properties"); } QList<CommandLineOption::Type> PropertiesCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType << CommandLineOption::ProductsOptionType; } QString StatusCommand::shortDescription() const { return Tr::tr("Show the status of files in the project directory."); } QString StatusCommand::longDescription() const { QString description = Tr::tr("qbs %1 [options] [variant] [property:value] ...\n") .arg(representation()); description += Tr::tr("Lists all the files in the project directory and shows whether " "they are known to qbs in the respective configuration.\n"); return description += supportedOptionsDescription(); } QString StatusCommand::representation() const { return QLatin1String("status"); } QList<CommandLineOption::Type> StatusCommand::supportedOptions() const { return QList<CommandLineOption::Type>() << CommandLineOption::FileOptionType << CommandLineOption::LogLevelOptionType << CommandLineOption::VerboseOptionType << CommandLineOption::QuietOptionType << CommandLineOption::ShowProgressOptionType; } QString HelpCommand::shortDescription() const { return Tr::tr("Show general or command-specific help."); } QString HelpCommand::longDescription() const { QString description = Tr::tr("qbs %1 [<command>]\n").arg(representation()); return description += Tr::tr("Shows either the general help or a description of " "the given command.\n"); } QString HelpCommand::representation() const { return QLatin1String("help"); } QList<CommandLineOption::Type> HelpCommand::supportedOptions() const { return QList<CommandLineOption::Type>(); } void HelpCommand::parseMore(QStringList &input) { if (input.isEmpty()) return; if (input.count() > 1) { throw Error(Tr::tr("Invalid use of command '%1': Cannot describe more than one command.\n" "Usage: %2").arg(representation(), longDescription())); } m_command = input.takeFirst(); Q_ASSERT(input.isEmpty()); } } // namespace qbs <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; /** * Specifiy a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { { "setmocktime", 0, "timestamp" }, { "generate", 0, "nblocks" }, { "generate", 1, "maxtries" }, { "generatetoaddress", 0, "nblocks" }, { "generatetoaddress", 2, "maxtries" }, { "getnetworkhashps", 0, "nblocks" }, { "getnetworkhashps", 1, "height" }, { "sendtoaddress", 1, "amount" }, { "sendtoaddress", 4, "subtractfeefromamount" }, { "settxfee", 0, "amount" }, { "getreceivedbyaddress", 1, "minconf" }, { "getreceivedbyaccount", 1, "minconf" }, { "listreceivedbyaddress", 0, "minconf" }, { "listreceivedbyaddress", 1, "include_empty" }, { "listreceivedbyaddress", 2, "include_watchonly" }, { "listreceivedbyaccount", 0, "minconf" }, { "listreceivedbyaccount", 1, "include_empty" }, { "listreceivedbyaccount", 2, "include_watchonly" }, { "getbalance", 1, "minconf" }, { "getbalance", 2, "include_watchonly" }, { "getblockhash", 0, "height" }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, { "waitfornewblock", 0, "timeout" }, { "move", 2, "amount" }, { "move", 3, "minconf" }, { "sendfrom", 2, "amount" }, { "sendfrom", 3, "minconf" }, { "listtransactions", 1, "count" }, { "listtransactions", 2, "skip" }, { "listtransactions", 3, "include_watchonly" }, { "listaccounts", 0, "minconf" }, { "listaccounts", 1, "include_watchonly" }, { "walletpassphrase", 1, "timeout" }, { "getblocktemplate", 0, "template_request" }, { "listsinceblock", 1, "target_confirmations" }, { "listsinceblock", 2, "include_watchonly" }, { "sendmany", 1, "amounts" }, { "sendmany", 2, "minconf" }, { "sendmany", 4, "subtractfeefrom" }, { "addmultisigaddress", 0, "nrequired" }, { "addmultisigaddress", 1, "keys" }, { "createmultisig", 0, "nrequired" }, { "createmultisig", 1, "keys" }, { "listunspent", 0, "minconf" }, { "listunspent", 1, "maxconf" }, { "listunspent", 2, "addresses" }, { "listunspent", 4, "query_options" }, { "getblock", 1, "verbose" }, { "getblockheader", 1, "verbose" }, { "gettransaction", 1, "include_watchonly" }, { "getrawtransaction", 1, "verbose" }, { "createrawtransaction", 0, "inputs" }, { "createrawtransaction", 1, "outputs" }, { "createrawtransaction", 2, "locktime" }, { "signrawtransaction", 1, "prevtxs" }, { "signrawtransaction", 2, "privkeys" }, { "sendrawtransaction", 1, "allowhighfees" }, { "fundrawtransaction", 1, "options" }, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, { "lockunspent", 0, "unlock" }, { "lockunspent", 1, "transactions" }, { "importprivkey", 2, "rescan" }, { "importaddress", 2, "rescan" }, { "importaddress", 3, "p2sh" }, { "importpubkey", 2, "rescan" }, { "importmulti", 0, "requests" }, { "importmulti", 1, "options" }, { "verifychain", 0, "checklevel" }, { "verifychain", 1, "nblocks" }, { "pruneblockchain", 0, "height" }, { "keypoolrefill", 0, "newsize" }, { "getrawmempool", 0, "verbose" }, { "estimatefee", 0, "nblocks" }, { "estimatepriority", 0, "nblocks" }, { "estimatesmartfee", 0, "nblocks" }, { "estimatesmartpriority", 0, "nblocks" }, { "prioritisetransaction", 1, "priority_delta" }, { "prioritisetransaction", 2, "fee_delta" }, { "setban", 2, "bantime" }, { "setban", 3, "absolute" }, { "setnetworkactive", 0, "state" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "bumpfee", 1, "options" }, // Echo with conversion (For testing only) { "echojson", 0, "arg0" }, { "echojson", 1, "arg1" }, { "echojson", 2, "arg2" }, { "echojson", 3, "arg3" }, { "echojson", 4, "arg4" }, { "echojson", 5, "arg5" }, { "echojson", 6, "arg6" }, { "echojson", 7, "arg7" }, { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string& method, const std::string& name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s: strParams) { size_t pos = s.find("="); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos+1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; } <commit_msg>fixed listunspent rpc convert parameter<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include <set> #include <stdint.h> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <univalue.h> using namespace std; class CRPCConvertParam { public: std::string methodName; //!< method whose params want conversion int paramIdx; //!< 0-based idx of param to convert std::string paramName; //!< parameter name }; /** * Specifiy a (method, idx, name) here if the argument is a non-string RPC * argument and needs to be converted from JSON. * * @note Parameter indexes start from 0. */ static const CRPCConvertParam vRPCConvertParams[] = { { "setmocktime", 0, "timestamp" }, { "generate", 0, "nblocks" }, { "generate", 1, "maxtries" }, { "generatetoaddress", 0, "nblocks" }, { "generatetoaddress", 2, "maxtries" }, { "getnetworkhashps", 0, "nblocks" }, { "getnetworkhashps", 1, "height" }, { "sendtoaddress", 1, "amount" }, { "sendtoaddress", 4, "subtractfeefromamount" }, { "settxfee", 0, "amount" }, { "getreceivedbyaddress", 1, "minconf" }, { "getreceivedbyaccount", 1, "minconf" }, { "listreceivedbyaddress", 0, "minconf" }, { "listreceivedbyaddress", 1, "include_empty" }, { "listreceivedbyaddress", 2, "include_watchonly" }, { "listreceivedbyaccount", 0, "minconf" }, { "listreceivedbyaccount", 1, "include_empty" }, { "listreceivedbyaccount", 2, "include_watchonly" }, { "getbalance", 1, "minconf" }, { "getbalance", 2, "include_watchonly" }, { "getblockhash", 0, "height" }, { "waitforblockheight", 0, "height" }, { "waitforblockheight", 1, "timeout" }, { "waitforblock", 1, "timeout" }, { "waitfornewblock", 0, "timeout" }, { "move", 2, "amount" }, { "move", 3, "minconf" }, { "sendfrom", 2, "amount" }, { "sendfrom", 3, "minconf" }, { "listtransactions", 1, "count" }, { "listtransactions", 2, "skip" }, { "listtransactions", 3, "include_watchonly" }, { "listaccounts", 0, "minconf" }, { "listaccounts", 1, "include_watchonly" }, { "walletpassphrase", 1, "timeout" }, { "getblocktemplate", 0, "template_request" }, { "listsinceblock", 1, "target_confirmations" }, { "listsinceblock", 2, "include_watchonly" }, { "sendmany", 1, "amounts" }, { "sendmany", 2, "minconf" }, { "sendmany", 4, "subtractfeefrom" }, { "addmultisigaddress", 0, "nrequired" }, { "addmultisigaddress", 1, "keys" }, { "createmultisig", 0, "nrequired" }, { "createmultisig", 1, "keys" }, { "listunspent", 0, "minconf" }, { "listunspent", 1, "maxconf" }, { "listunspent", 2, "addresses" }, { "listunspent", 3, "include_unsafe" }, { "listunspent", 4, "query_options" }, { "getblock", 1, "verbose" }, { "getblockheader", 1, "verbose" }, { "gettransaction", 1, "include_watchonly" }, { "getrawtransaction", 1, "verbose" }, { "createrawtransaction", 0, "inputs" }, { "createrawtransaction", 1, "outputs" }, { "createrawtransaction", 2, "locktime" }, { "signrawtransaction", 1, "prevtxs" }, { "signrawtransaction", 2, "privkeys" }, { "sendrawtransaction", 1, "allowhighfees" }, { "fundrawtransaction", 1, "options" }, { "gettxout", 1, "n" }, { "gettxout", 2, "include_mempool" }, { "gettxoutproof", 0, "txids" }, { "lockunspent", 0, "unlock" }, { "lockunspent", 1, "transactions" }, { "importprivkey", 2, "rescan" }, { "importaddress", 2, "rescan" }, { "importaddress", 3, "p2sh" }, { "importpubkey", 2, "rescan" }, { "importmulti", 0, "requests" }, { "importmulti", 1, "options" }, { "verifychain", 0, "checklevel" }, { "verifychain", 1, "nblocks" }, { "pruneblockchain", 0, "height" }, { "keypoolrefill", 0, "newsize" }, { "getrawmempool", 0, "verbose" }, { "estimatefee", 0, "nblocks" }, { "estimatepriority", 0, "nblocks" }, { "estimatesmartfee", 0, "nblocks" }, { "estimatesmartpriority", 0, "nblocks" }, { "prioritisetransaction", 1, "priority_delta" }, { "prioritisetransaction", 2, "fee_delta" }, { "setban", 2, "bantime" }, { "setban", 3, "absolute" }, { "setnetworkactive", 0, "state" }, { "getmempoolancestors", 1, "verbose" }, { "getmempooldescendants", 1, "verbose" }, { "bumpfee", 1, "options" }, // Echo with conversion (For testing only) { "echojson", 0, "arg0" }, { "echojson", 1, "arg1" }, { "echojson", 2, "arg2" }, { "echojson", 3, "arg3" }, { "echojson", 4, "arg4" }, { "echojson", 5, "arg5" }, { "echojson", 6, "arg6" }, { "echojson", 7, "arg7" }, { "echojson", 8, "arg8" }, { "echojson", 9, "arg9" }, }; class CRPCConvertTable { private: std::set<std::pair<std::string, int>> members; std::set<std::pair<std::string, std::string>> membersByName; public: CRPCConvertTable(); bool convert(const std::string& method, int idx) { return (members.count(std::make_pair(method, idx)) > 0); } bool convert(const std::string& method, const std::string& name) { return (membersByName.count(std::make_pair(method, name)) > 0); } }; CRPCConvertTable::CRPCConvertTable() { const unsigned int n_elem = (sizeof(vRPCConvertParams) / sizeof(vRPCConvertParams[0])); for (unsigned int i = 0; i < n_elem; i++) { members.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramIdx)); membersByName.insert(std::make_pair(vRPCConvertParams[i].methodName, vRPCConvertParams[i].paramName)); } } static CRPCConvertTable rpcCvtTable; /** Non-RFC4627 JSON parser, accepts internal values (such as numbers, true, false, null) * as well as objects and arrays. */ UniValue ParseNonRFCJSONValue(const std::string& strVal) { UniValue jVal; if (!jVal.read(std::string("[")+strVal+std::string("]")) || !jVal.isArray() || jVal.size()!=1) throw runtime_error(string("Error parsing JSON:")+strVal); return jVal[0]; } UniValue RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VARR); for (unsigned int idx = 0; idx < strParams.size(); idx++) { const std::string& strVal = strParams[idx]; if (!rpcCvtTable.convert(strMethod, idx)) { // insert string value directly params.push_back(strVal); } else { // parse string as JSON, insert bool/number/object/etc. value params.push_back(ParseNonRFCJSONValue(strVal)); } } return params; } UniValue RPCConvertNamedValues(const std::string &strMethod, const std::vector<std::string> &strParams) { UniValue params(UniValue::VOBJ); for (const std::string &s: strParams) { size_t pos = s.find("="); if (pos == std::string::npos) { throw(std::runtime_error("No '=' in named argument '"+s+"', this needs to be present for every argument (even if it is empty)")); } std::string name = s.substr(0, pos); std::string value = s.substr(pos+1); if (!rpcCvtTable.convert(strMethod, name)) { // insert string value directly params.pushKV(name, value); } else { // parse string as JSON, insert bool/number/object/etc. value params.pushKV(name, ParseNonRFCJSONValue(value)); } } return params; } <|endoftext|>
<commit_before>/* * Copyright (c) 2018, Ford Motor Company * 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 Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "appMain/life_cycle_impl.h" #include "utils/signals.h" #include "config_profile/profile.h" #include "application_manager/system_time/system_time_handler_impl.h" #include "resumption/last_state_impl.h" #ifdef ENABLE_SECURITY #include "security_manager/security_manager_impl.h" #include "security_manager/crypto_manager_impl.h" #include "security_manager/crypto_manager_settings_impl.h" #include "application_manager/policies/policy_handler.h" #endif // ENABLE_SECURITY #ifdef ENABLE_LOG #include "utils/log_message_loop_thread.h" #endif // ENABLE_LOG #include "appMain/low_voltage_signals_handler.h" using threads::Thread; namespace main_namespace { CREATE_LOGGERPTR_GLOBAL(logger_, "SDLMain") LifeCycleImpl::LifeCycleImpl(const profile::Profile& profile) : transport_manager_(NULL) , protocol_handler_(NULL) , connection_handler_(NULL) , app_manager_(NULL) #ifdef ENABLE_SECURITY , crypto_manager_(NULL) , security_manager_(NULL) #endif // ENABLE_SECURITY , hmi_handler_(NULL) , hmi_message_adapter_(NULL) , media_manager_(NULL) , last_state_(NULL) #ifdef TELEMETRY_MONITOR , telemetry_monitor_(NULL) #endif // TELEMETRY_MONITOR #ifdef MESSAGEBROKER_HMIADAPTER , mb_adapter_(NULL) , mb_adapter_thread_(NULL) #endif // MESSAGEBROKER_HMIADAPTER , profile_(profile) { } bool LifeCycleImpl::StartComponents() { LOG4CXX_AUTO_TRACE(logger_); DCHECK(!last_state_); last_state_ = new resumption::LastStateImpl(profile_.app_storage_folder(), profile_.app_info_storage()); DCHECK(!transport_manager_); transport_manager_ = new transport_manager::TransportManagerDefault(profile_); DCHECK(!connection_handler_); connection_handler_ = new connection_handler::ConnectionHandlerImpl( profile_, *transport_manager_); DCHECK(!protocol_handler_); protocol_handler_ = new protocol_handler::ProtocolHandlerImpl(profile_, *connection_handler_, *connection_handler_, *transport_manager_); DCHECK(protocol_handler_); DCHECK(!app_manager_); app_manager_ = new application_manager::ApplicationManagerImpl(profile_, profile_); DCHECK(!hmi_handler_); hmi_handler_ = new hmi_message_handler::HMIMessageHandlerImpl(profile_); hmi_handler_->set_message_observer(&(app_manager_->GetRPCHandler())); app_manager_->set_hmi_message_handler(hmi_handler_); media_manager_ = new media_manager::MediaManagerImpl(*app_manager_, profile_); app_manager_->set_connection_handler(connection_handler_); if (!app_manager_->Init(*last_state_, media_manager_)) { LOG4CXX_ERROR(logger_, "Application manager init failed."); return false; } #ifdef ENABLE_SECURITY auto system_time_handler = std::unique_ptr<application_manager::SystemTimeHandlerImpl>( new application_manager::SystemTimeHandlerImpl(*app_manager_)); security_manager_ = new security_manager::SecurityManagerImpl(std::move(system_time_handler)); crypto_manager_ = new security_manager::CryptoManagerImpl( std::make_shared<security_manager::CryptoManagerSettingsImpl>( profile_, app_manager_->GetPolicyHandler().RetrieveCertificate())); protocol_handler_->AddProtocolObserver(security_manager_); protocol_handler_->set_security_manager(security_manager_); security_manager_->set_session_observer(connection_handler_); security_manager_->set_protocol_handler(protocol_handler_); security_manager_->set_crypto_manager(crypto_manager_); security_manager_->AddListener(app_manager_); app_manager_->AddPolicyObserver(security_manager_); app_manager_->AddPolicyObserver(protocol_handler_); if (!crypto_manager_->Init()) { LOG4CXX_ERROR(logger_, "CryptoManager initialization fail."); return false; } #endif // ENABLE_SECURITY transport_manager_->AddEventListener(protocol_handler_); transport_manager_->AddEventListener(connection_handler_); protocol_handler_->AddProtocolObserver(media_manager_); protocol_handler_->AddProtocolObserver(&(app_manager_->GetRPCHandler())); media_manager_->SetProtocolHandler(protocol_handler_); connection_handler_->set_protocol_handler(protocol_handler_); connection_handler_->set_connection_handler_observer(app_manager_); // it is important to initialise TelemetryMonitor before TM to listen TM // Adapters #ifdef TELEMETRY_MONITOR telemetry_monitor_ = new telemetry_monitor::TelemetryMonitor( profile_.server_address(), profile_.time_testing_port()); telemetry_monitor_->Start(); telemetry_monitor_->Init(protocol_handler_, app_manager_, transport_manager_); #endif // TELEMETRY_MONITOR // It's important to initialise TM after setting up listener chain // [TM -> CH -> AM], otherwise some events from TM could arrive at nowhere app_manager_->set_protocol_handler(protocol_handler_); if (!transport_manager_->Init(*last_state_)) { LOG4CXX_ERROR(logger_, "Transport manager init failed."); return false; } // start transport manager transport_manager_->Visibility(true); LowVoltageSignalsOffset signals_offset{profile_.low_voltage_signal_offset(), profile_.wake_up_signal_offset(), profile_.ignition_off_signal_offset()}; low_voltage_signals_handler_.reset( new LowVoltageSignalsHandler(*this, signals_offset)); return true; } void LifeCycleImpl::LowVoltage() { LOG4CXX_AUTO_TRACE(logger_); transport_manager_->Visibility(false); app_manager_->OnLowVoltage(); } void LifeCycleImpl::IgnitionOff() { LOG4CXX_AUTO_TRACE(logger_); kill(getpid(), SIGINT); } void LifeCycleImpl::WakeUp() { LOG4CXX_AUTO_TRACE(logger_); app_manager_->OnWakeUp(); transport_manager_->Reinit(); transport_manager_->Visibility(true); } #ifdef MESSAGEBROKER_HMIADAPTER bool LifeCycleImpl::InitMessageSystem() { mb_adapter_ = new hmi_message_handler::MessageBrokerAdapter( hmi_handler_, profile_.server_address(), profile_.server_port()); if (!mb_adapter_->StartListener()) { return false; } hmi_handler_->AddHMIMessageAdapter(mb_adapter_); mb_adapter_thread_ = new std::thread( &hmi_message_handler::MessageBrokerAdapter::Run, mb_adapter_); return true; } #endif // MESSAGEBROKER_HMIADAPTER namespace { void sig_handler(int sig) { switch (sig) { case SIGINT: LOG4CXX_DEBUG(logger_, "SIGINT signal has been caught"); break; case SIGTERM: LOG4CXX_DEBUG(logger_, "SIGTERM signal has been caught"); break; case SIGSEGV: LOG4CXX_DEBUG(logger_, "SIGSEGV signal has been caught"); FLUSH_LOGGER(); // exit need to prevent endless sending SIGSEGV // http://stackoverflow.com/questions/2663456/how-to-write-a-signal-handler-to-catch-sigsegv abort(); default: LOG4CXX_DEBUG(logger_, "Unexpected signal has been caught"); exit(EXIT_FAILURE); } } } // namespace void LifeCycleImpl::Run() { LOG4CXX_AUTO_TRACE(logger_); // Register signal handlers and wait sys signals // from OS if (!utils::Signals::WaitTerminationSignals(&sig_handler)) { LOG4CXX_FATAL(logger_, "Fail to catch system signal!"); } } void LifeCycleImpl::StopComponents() { LOG4CXX_AUTO_TRACE(logger_); DCHECK_OR_RETURN_VOID(hmi_handler_); hmi_handler_->set_message_observer(NULL); DCHECK_OR_RETURN_VOID(connection_handler_); connection_handler_->set_connection_handler_observer(NULL); DCHECK_OR_RETURN_VOID(protocol_handler_); protocol_handler_->RemoveProtocolObserver(&(app_manager_->GetRPCHandler())); DCHECK_OR_RETURN_VOID(app_manager_); app_manager_->Stop(); LOG4CXX_INFO(logger_, "Stopping Protocol Handler"); DCHECK_OR_RETURN_VOID(protocol_handler_); protocol_handler_->RemoveProtocolObserver(media_manager_); #ifdef ENABLE_SECURITY protocol_handler_->RemoveProtocolObserver(security_manager_); if (security_manager_) { security_manager_->RemoveListener(app_manager_); LOG4CXX_INFO(logger_, "Destroying Crypto Manager"); delete crypto_manager_; crypto_manager_ = NULL; LOG4CXX_INFO(logger_, "Destroying Security Manager"); delete security_manager_; security_manager_ = NULL; } #endif // ENABLE_SECURITY protocol_handler_->Stop(); LOG4CXX_INFO(logger_, "Destroying Media Manager"); DCHECK_OR_RETURN_VOID(media_manager_); media_manager_->SetProtocolHandler(NULL); delete media_manager_; media_manager_ = NULL; LOG4CXX_INFO(logger_, "Destroying Transport Manager."); DCHECK_OR_RETURN_VOID(transport_manager_); transport_manager_->Visibility(false); transport_manager_->Stop(); delete transport_manager_; transport_manager_ = NULL; LOG4CXX_INFO(logger_, "Stopping Connection Handler."); DCHECK_OR_RETURN_VOID(connection_handler_); connection_handler_->Stop(); LOG4CXX_INFO(logger_, "Destroying Protocol Handler"); DCHECK(protocol_handler_); delete protocol_handler_; protocol_handler_ = NULL; LOG4CXX_INFO(logger_, "Destroying Connection Handler."); delete connection_handler_; connection_handler_ = NULL; LOG4CXX_INFO(logger_, "Destroying Last State"); DCHECK(last_state_); delete last_state_; last_state_ = NULL; LOG4CXX_INFO(logger_, "Destroying Application Manager."); DCHECK(app_manager_); delete app_manager_; app_manager_ = NULL; LOG4CXX_INFO(logger_, "Destroying Low Voltage Signals Handler."); low_voltage_signals_handler_.reset(); LOG4CXX_INFO(logger_, "Destroying HMI Message Handler and MB adapter."); #ifdef MESSAGEBROKER_HMIADAPTER if (mb_adapter_) { DCHECK_OR_RETURN_VOID(hmi_handler_); hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_); mb_adapter_->unregisterController(); mb_adapter_->exitReceivingThread(); if (mb_adapter_thread_ != NULL) { mb_adapter_thread_->join(); } delete mb_adapter_; mb_adapter_ = NULL; delete mb_adapter_thread_; mb_adapter_thread_ = NULL; } LOG4CXX_INFO(logger_, "Destroying Message Broker"); #endif // MESSAGEBROKER_HMIADAPTER DCHECK_OR_RETURN_VOID(hmi_handler_); delete hmi_handler_; hmi_handler_ = NULL; #ifdef TELEMETRY_MONITOR // It's important to delete tester Obcervers after TM adapters destruction if (telemetry_monitor_) { telemetry_monitor_->Stop(); delete telemetry_monitor_; telemetry_monitor_ = NULL; } #endif // TELEMETRY_MONITOR } } // namespace main_namespace <commit_msg>Fix transport manager init check<commit_after>/* * Copyright (c) 2018, Ford Motor Company * 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 Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "appMain/life_cycle_impl.h" #include "utils/signals.h" #include "config_profile/profile.h" #include "application_manager/system_time/system_time_handler_impl.h" #include "resumption/last_state_impl.h" #ifdef ENABLE_SECURITY #include "security_manager/security_manager_impl.h" #include "security_manager/crypto_manager_impl.h" #include "security_manager/crypto_manager_settings_impl.h" #include "application_manager/policies/policy_handler.h" #endif // ENABLE_SECURITY #ifdef ENABLE_LOG #include "utils/log_message_loop_thread.h" #endif // ENABLE_LOG #include "appMain/low_voltage_signals_handler.h" using threads::Thread; namespace main_namespace { CREATE_LOGGERPTR_GLOBAL(logger_, "SDLMain") LifeCycleImpl::LifeCycleImpl(const profile::Profile& profile) : transport_manager_(NULL) , protocol_handler_(NULL) , connection_handler_(NULL) , app_manager_(NULL) #ifdef ENABLE_SECURITY , crypto_manager_(NULL) , security_manager_(NULL) #endif // ENABLE_SECURITY , hmi_handler_(NULL) , hmi_message_adapter_(NULL) , media_manager_(NULL) , last_state_(NULL) #ifdef TELEMETRY_MONITOR , telemetry_monitor_(NULL) #endif // TELEMETRY_MONITOR #ifdef MESSAGEBROKER_HMIADAPTER , mb_adapter_(NULL) , mb_adapter_thread_(NULL) #endif // MESSAGEBROKER_HMIADAPTER , profile_(profile) { } bool LifeCycleImpl::StartComponents() { LOG4CXX_AUTO_TRACE(logger_); DCHECK(!last_state_); last_state_ = new resumption::LastStateImpl(profile_.app_storage_folder(), profile_.app_info_storage()); DCHECK(!transport_manager_); transport_manager_ = new transport_manager::TransportManagerDefault(profile_); DCHECK(!connection_handler_); connection_handler_ = new connection_handler::ConnectionHandlerImpl( profile_, *transport_manager_); DCHECK(!protocol_handler_); protocol_handler_ = new protocol_handler::ProtocolHandlerImpl(profile_, *connection_handler_, *connection_handler_, *transport_manager_); DCHECK(protocol_handler_); DCHECK(!app_manager_); app_manager_ = new application_manager::ApplicationManagerImpl(profile_, profile_); DCHECK(!hmi_handler_); hmi_handler_ = new hmi_message_handler::HMIMessageHandlerImpl(profile_); hmi_handler_->set_message_observer(&(app_manager_->GetRPCHandler())); app_manager_->set_hmi_message_handler(hmi_handler_); media_manager_ = new media_manager::MediaManagerImpl(*app_manager_, profile_); app_manager_->set_connection_handler(connection_handler_); if (!app_manager_->Init(*last_state_, media_manager_)) { LOG4CXX_ERROR(logger_, "Application manager init failed."); return false; } #ifdef ENABLE_SECURITY auto system_time_handler = std::unique_ptr<application_manager::SystemTimeHandlerImpl>( new application_manager::SystemTimeHandlerImpl(*app_manager_)); security_manager_ = new security_manager::SecurityManagerImpl(std::move(system_time_handler)); crypto_manager_ = new security_manager::CryptoManagerImpl( std::make_shared<security_manager::CryptoManagerSettingsImpl>( profile_, app_manager_->GetPolicyHandler().RetrieveCertificate())); protocol_handler_->AddProtocolObserver(security_manager_); protocol_handler_->set_security_manager(security_manager_); security_manager_->set_session_observer(connection_handler_); security_manager_->set_protocol_handler(protocol_handler_); security_manager_->set_crypto_manager(crypto_manager_); security_manager_->AddListener(app_manager_); app_manager_->AddPolicyObserver(security_manager_); app_manager_->AddPolicyObserver(protocol_handler_); if (!crypto_manager_->Init()) { LOG4CXX_ERROR(logger_, "CryptoManager initialization fail."); return false; } #endif // ENABLE_SECURITY transport_manager_->AddEventListener(protocol_handler_); transport_manager_->AddEventListener(connection_handler_); protocol_handler_->AddProtocolObserver(media_manager_); protocol_handler_->AddProtocolObserver(&(app_manager_->GetRPCHandler())); media_manager_->SetProtocolHandler(protocol_handler_); connection_handler_->set_protocol_handler(protocol_handler_); connection_handler_->set_connection_handler_observer(app_manager_); // it is important to initialise TelemetryMonitor before TM to listen TM // Adapters #ifdef TELEMETRY_MONITOR telemetry_monitor_ = new telemetry_monitor::TelemetryMonitor( profile_.server_address(), profile_.time_testing_port()); telemetry_monitor_->Start(); telemetry_monitor_->Init(protocol_handler_, app_manager_, transport_manager_); #endif // TELEMETRY_MONITOR // It's important to initialise TM after setting up listener chain // [TM -> CH -> AM], otherwise some events from TM could arrive at nowhere app_manager_->set_protocol_handler(protocol_handler_); if (transport_manager::E_SUCCESS != transport_manager_->Init(*last_state_)) { LOG4CXX_ERROR(logger_, "Transport manager init failed."); return false; } // start transport manager transport_manager_->Visibility(true); LowVoltageSignalsOffset signals_offset{profile_.low_voltage_signal_offset(), profile_.wake_up_signal_offset(), profile_.ignition_off_signal_offset()}; low_voltage_signals_handler_.reset( new LowVoltageSignalsHandler(*this, signals_offset)); return true; } void LifeCycleImpl::LowVoltage() { LOG4CXX_AUTO_TRACE(logger_); transport_manager_->Visibility(false); app_manager_->OnLowVoltage(); } void LifeCycleImpl::IgnitionOff() { LOG4CXX_AUTO_TRACE(logger_); kill(getpid(), SIGINT); } void LifeCycleImpl::WakeUp() { LOG4CXX_AUTO_TRACE(logger_); app_manager_->OnWakeUp(); transport_manager_->Reinit(); transport_manager_->Visibility(true); } #ifdef MESSAGEBROKER_HMIADAPTER bool LifeCycleImpl::InitMessageSystem() { mb_adapter_ = new hmi_message_handler::MessageBrokerAdapter( hmi_handler_, profile_.server_address(), profile_.server_port()); if (!mb_adapter_->StartListener()) { return false; } hmi_handler_->AddHMIMessageAdapter(mb_adapter_); mb_adapter_thread_ = new std::thread( &hmi_message_handler::MessageBrokerAdapter::Run, mb_adapter_); return true; } #endif // MESSAGEBROKER_HMIADAPTER namespace { void sig_handler(int sig) { switch (sig) { case SIGINT: LOG4CXX_DEBUG(logger_, "SIGINT signal has been caught"); break; case SIGTERM: LOG4CXX_DEBUG(logger_, "SIGTERM signal has been caught"); break; case SIGSEGV: LOG4CXX_DEBUG(logger_, "SIGSEGV signal has been caught"); FLUSH_LOGGER(); // exit need to prevent endless sending SIGSEGV // http://stackoverflow.com/questions/2663456/how-to-write-a-signal-handler-to-catch-sigsegv abort(); default: LOG4CXX_DEBUG(logger_, "Unexpected signal has been caught"); exit(EXIT_FAILURE); } } } // namespace void LifeCycleImpl::Run() { LOG4CXX_AUTO_TRACE(logger_); // Register signal handlers and wait sys signals // from OS if (!utils::Signals::WaitTerminationSignals(&sig_handler)) { LOG4CXX_FATAL(logger_, "Fail to catch system signal!"); } } void LifeCycleImpl::StopComponents() { LOG4CXX_AUTO_TRACE(logger_); DCHECK_OR_RETURN_VOID(hmi_handler_); hmi_handler_->set_message_observer(NULL); DCHECK_OR_RETURN_VOID(connection_handler_); connection_handler_->set_connection_handler_observer(NULL); DCHECK_OR_RETURN_VOID(protocol_handler_); protocol_handler_->RemoveProtocolObserver(&(app_manager_->GetRPCHandler())); DCHECK_OR_RETURN_VOID(app_manager_); app_manager_->Stop(); LOG4CXX_INFO(logger_, "Stopping Protocol Handler"); DCHECK_OR_RETURN_VOID(protocol_handler_); protocol_handler_->RemoveProtocolObserver(media_manager_); #ifdef ENABLE_SECURITY protocol_handler_->RemoveProtocolObserver(security_manager_); if (security_manager_) { security_manager_->RemoveListener(app_manager_); LOG4CXX_INFO(logger_, "Destroying Crypto Manager"); delete crypto_manager_; crypto_manager_ = NULL; LOG4CXX_INFO(logger_, "Destroying Security Manager"); delete security_manager_; security_manager_ = NULL; } #endif // ENABLE_SECURITY protocol_handler_->Stop(); LOG4CXX_INFO(logger_, "Destroying Media Manager"); DCHECK_OR_RETURN_VOID(media_manager_); media_manager_->SetProtocolHandler(NULL); delete media_manager_; media_manager_ = NULL; LOG4CXX_INFO(logger_, "Destroying Transport Manager."); DCHECK_OR_RETURN_VOID(transport_manager_); transport_manager_->Visibility(false); transport_manager_->Stop(); delete transport_manager_; transport_manager_ = NULL; LOG4CXX_INFO(logger_, "Stopping Connection Handler."); DCHECK_OR_RETURN_VOID(connection_handler_); connection_handler_->Stop(); LOG4CXX_INFO(logger_, "Destroying Protocol Handler"); DCHECK(protocol_handler_); delete protocol_handler_; protocol_handler_ = NULL; LOG4CXX_INFO(logger_, "Destroying Connection Handler."); delete connection_handler_; connection_handler_ = NULL; LOG4CXX_INFO(logger_, "Destroying Last State"); DCHECK(last_state_); delete last_state_; last_state_ = NULL; LOG4CXX_INFO(logger_, "Destroying Application Manager."); DCHECK(app_manager_); delete app_manager_; app_manager_ = NULL; LOG4CXX_INFO(logger_, "Destroying Low Voltage Signals Handler."); low_voltage_signals_handler_.reset(); LOG4CXX_INFO(logger_, "Destroying HMI Message Handler and MB adapter."); #ifdef MESSAGEBROKER_HMIADAPTER if (mb_adapter_) { DCHECK_OR_RETURN_VOID(hmi_handler_); hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_); mb_adapter_->unregisterController(); mb_adapter_->exitReceivingThread(); if (mb_adapter_thread_ != NULL) { mb_adapter_thread_->join(); } delete mb_adapter_; mb_adapter_ = NULL; delete mb_adapter_thread_; mb_adapter_thread_ = NULL; } LOG4CXX_INFO(logger_, "Destroying Message Broker"); #endif // MESSAGEBROKER_HMIADAPTER DCHECK_OR_RETURN_VOID(hmi_handler_); delete hmi_handler_; hmi_handler_ = NULL; #ifdef TELEMETRY_MONITOR // It's important to delete tester Obcervers after TM adapters destruction if (telemetry_monitor_) { telemetry_monitor_->Stop(); delete telemetry_monitor_; telemetry_monitor_ = NULL; } #endif // TELEMETRY_MONITOR } } // namespace main_namespace <|endoftext|>
<commit_before>/* * Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 "application/Application.h" #include <fio/InFile.h> #include <strop/strop.h> #include <cassert> #include <cmath> #include "application/Messenger.h" #include "application/Terminal.h" #include "network/Network.h" Application::Application(const std::string& _name, const Component* _parent, MetadataHandler* _metadataHandler, Json::Value _settings) : Component(_name, _parent), metadataHandler_(_metadataHandler) { Network* network = gSim->getNetwork(); u32 radix = network->numInterfaces(); terminals_.resize(radix, nullptr); messengers_.resize(radix, nullptr); // extract maximum injection rate per terminal std::vector<f64> maxInjectionRates(radix); // get the base injection rate assert(_settings.isMember("max_injection_rate")); f64 baseInjection = _settings["max_injection_rate"].asDouble(); if (baseInjection <= 0.0) { baseInjection = INFINITY; } for (f64& mir : maxInjectionRates) { mir = baseInjection; } // if necessary, apply relative rates if (_settings.isMember("relative_injection")) { // if a file is given, it is a csv of injection rates fio::InFile inf(_settings["relative_injection"].asString()); std::string line; u32 lineNum = 0; fio::InFile::Status sts = fio::InFile::Status::OK; for (lineNum = 0; sts == fio::InFile::Status::OK;) { sts = inf.getLine(&line); assert(sts != fio::InFile::Status::ERROR); if (sts == fio::InFile::Status::OK) { if (line.size() > 0) { std::vector<std::string> strs = strop::split(line, ','); assert(strs.size() == 1); f64 ri = std::stod(strs.at(0)); maxInjectionRates.at(lineNum) *= ri; lineNum++; } } } assert(lineNum == radix); } else { assert(false); } // instantiate the messengers for (u32 id = 0; id < radix; id++) { // create the messenger std::string cname = "Messenger_" + std::to_string(id); messengers_.at(id) = new Messenger(cname, this, this, id, maxInjectionRates.at(id)); // link the messenger to the network messengers_.at(id)->linkInterface(network->getInterface(id)); } // create a MessageLog messageLog_ = new MessageLog(_settings["message_log"]); // create the rate log rateLog_ = new RateLog(_settings["rate_log"]); } Application::~Application() { for (u32 idx = 0; idx < terminals_.size(); idx++) { delete terminals_.at(idx); delete messengers_.at(idx); } delete messageLog_; delete rateLog_; } u32 Application::numTerminals() const { return terminals_.size(); } Terminal* Application::getTerminal(u32 _id) const { return terminals_.at(_id); } MessageLog* Application::getMessageLog() const { return messageLog_; } MetadataHandler* Application::getMetadataHandler() const { return metadataHandler_; } u64 Application::createTransaction(u32 _tid, u32 _lid) { u64 trans = ((u64)_tid << 32) | (u64)_lid; u64 now = gSim->time(); bool res = transactions_.insert(std::make_pair(trans, now)).second; (void)res; // unused assert(res); return trans; } u64 Application::transactionCreationTime(u64 _trans) const { return transactions_.at(_trans); } void Application::endTransaction(u64 _trans) { u64 res = transactions_.erase(_trans); (void)res; // unused assert(res == 1); } u64 Application::cyclesToSend(u32 _numFlits, f64 _maxInjectionRate) const { if (std::isinf(_maxInjectionRate)) { return 0; // infinite injection rate } f64 cycles = _numFlits / _maxInjectionRate; // if the number of cycles is not even, probablistic cycles must be computed f64 fraction = modf(cycles, &cycles); if (fraction != 0.0) { assert(fraction > 0.0); assert(fraction < 1.0); f64 rnd = gSim->rnd.nextF64(); if (fraction > rnd) { cycles += 1.0; } } return (u64)cycles; } void Application::startMonitoring() { for (u32 i = 0; i < messengers_.size(); i++) { messengers_.at(i)->startRateMonitors(); } } void Application::endMonitoring() { for (u32 i = 0; i < messengers_.size(); i++) { messengers_.at(i)->endRateMonitors(); } for (u32 i = 0; i < messengers_.size(); i++) { messengers_.at(i)->logRates(rateLog_); } } void Application::setTerminal(u32 _id, Terminal* _terminal) { terminals_.at(_id) = _terminal; messengers_.at(_id)->linkTerminal(terminals_.at(_id)); } <commit_msg>fixed bug from last commit<commit_after>/* * Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 "application/Application.h" #include <fio/InFile.h> #include <strop/strop.h> #include <cassert> #include <cmath> #include "application/Messenger.h" #include "application/Terminal.h" #include "network/Network.h" Application::Application(const std::string& _name, const Component* _parent, MetadataHandler* _metadataHandler, Json::Value _settings) : Component(_name, _parent), metadataHandler_(_metadataHandler) { Network* network = gSim->getNetwork(); u32 radix = network->numInterfaces(); terminals_.resize(radix, nullptr); messengers_.resize(radix, nullptr); // extract maximum injection rate per terminal std::vector<f64> maxInjectionRates(radix); // get the base injection rate assert(_settings.isMember("max_injection_rate")); f64 baseInjection = _settings["max_injection_rate"].asDouble(); if (baseInjection <= 0.0) { baseInjection = INFINITY; } for (f64& mir : maxInjectionRates) { mir = baseInjection; } // if necessary, apply relative rates if (_settings.isMember("relative_injection")) { // if a file is given, it is a csv of injection rates fio::InFile inf(_settings["relative_injection"].asString()); std::string line; u32 lineNum = 0; fio::InFile::Status sts = fio::InFile::Status::OK; for (lineNum = 0; sts == fio::InFile::Status::OK;) { sts = inf.getLine(&line); assert(sts != fio::InFile::Status::ERROR); if (sts == fio::InFile::Status::OK) { if (line.size() > 0) { std::vector<std::string> strs = strop::split(line, ','); assert(strs.size() == 1); f64 ri = std::stod(strs.at(0)); maxInjectionRates.at(lineNum) *= ri; lineNum++; } } } assert(lineNum == radix); } // instantiate the messengers for (u32 id = 0; id < radix; id++) { // create the messenger std::string cname = "Messenger_" + std::to_string(id); messengers_.at(id) = new Messenger(cname, this, this, id, maxInjectionRates.at(id)); // link the messenger to the network messengers_.at(id)->linkInterface(network->getInterface(id)); } // create a MessageLog messageLog_ = new MessageLog(_settings["message_log"]); // create the rate log rateLog_ = new RateLog(_settings["rate_log"]); } Application::~Application() { for (u32 idx = 0; idx < terminals_.size(); idx++) { delete terminals_.at(idx); delete messengers_.at(idx); } delete messageLog_; delete rateLog_; } u32 Application::numTerminals() const { return terminals_.size(); } Terminal* Application::getTerminal(u32 _id) const { return terminals_.at(_id); } MessageLog* Application::getMessageLog() const { return messageLog_; } MetadataHandler* Application::getMetadataHandler() const { return metadataHandler_; } u64 Application::createTransaction(u32 _tid, u32 _lid) { u64 trans = ((u64)_tid << 32) | (u64)_lid; u64 now = gSim->time(); bool res = transactions_.insert(std::make_pair(trans, now)).second; (void)res; // unused assert(res); return trans; } u64 Application::transactionCreationTime(u64 _trans) const { return transactions_.at(_trans); } void Application::endTransaction(u64 _trans) { u64 res = transactions_.erase(_trans); (void)res; // unused assert(res == 1); } u64 Application::cyclesToSend(u32 _numFlits, f64 _maxInjectionRate) const { if (std::isinf(_maxInjectionRate)) { return 0; // infinite injection rate } f64 cycles = _numFlits / _maxInjectionRate; // if the number of cycles is not even, probablistic cycles must be computed f64 fraction = modf(cycles, &cycles); if (fraction != 0.0) { assert(fraction > 0.0); assert(fraction < 1.0); f64 rnd = gSim->rnd.nextF64(); if (fraction > rnd) { cycles += 1.0; } } return (u64)cycles; } void Application::startMonitoring() { for (u32 i = 0; i < messengers_.size(); i++) { messengers_.at(i)->startRateMonitors(); } } void Application::endMonitoring() { for (u32 i = 0; i < messengers_.size(); i++) { messengers_.at(i)->endRateMonitors(); } for (u32 i = 0; i < messengers_.size(); i++) { messengers_.at(i)->logRates(rateLog_); } } void Application::setTerminal(u32 _id, Terminal* _terminal) { terminals_.at(_id) = _terminal; messengers_.at(_id)->linkTerminal(terminals_.at(_id)); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #include "spaces_cg_fem.hh" #include "spaces_rt_pdelab.hh" #include "operators_darcy.hh" #if HAVE_DUNE_FEM && HAVE_DUNE_PDELAB && HAVE_ALUGRID typedef testing::Types< // std::pair< SPACE_CG_FEM_ALUCONFORMGRID(2, 1, 1), SPACE_CG_FEM_ALUCONFORMGRID(2, 1, 2) > /*,*/ std::pair< SPACE_CG_FEM_ALUCONFORMGRID(2, 1, 1), SPACE_RT_PDELAB_ALUCONFORMGRID(2) > > SpaceTypes; TYPED_TEST_CASE(DarcyOperator, SpaceTypes); TYPED_TEST(DarcyOperator, produces_correct_results) { this->produces_correct_results(); } #else // HAVE_DUNE_FEM && HAVE_DUNE_PDELAB && HAVE_ALUGRID TEST(DISABLED_DarcyOperator, produces_correct_results) {} #endif // HAVE_DUNE_FEM && HAVE_DUNE_PDELAB && HAVE_ALUGRID <commit_msg>[test.operators_darcy] fix space dimension<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #include "spaces_cg_fem.hh" #include "spaces_rt_pdelab.hh" #include "operators_darcy.hh" #if HAVE_DUNE_FEM && HAVE_DUNE_PDELAB && HAVE_ALUGRID typedef testing::Types< // std::pair< SPACE_CG_FEM_ALUCONFORMGRID(2, 1, 1), SPACE_CG_FEM_ALUCONFORMGRID(2, 2, 1) > /*,*/ std::pair< SPACE_CG_FEM_ALUCONFORMGRID(2, 1, 1), SPACE_RT_PDELAB_ALUCONFORMGRID(2) > > SpaceTypes; TYPED_TEST_CASE(DarcyOperator, SpaceTypes); TYPED_TEST(DarcyOperator, produces_correct_results) { this->produces_correct_results(); } #else // HAVE_DUNE_FEM && HAVE_DUNE_PDELAB && HAVE_ALUGRID TEST(DISABLED_DarcyOperator, produces_correct_results) {} #endif // HAVE_DUNE_FEM && HAVE_DUNE_PDELAB && HAVE_ALUGRID <|endoftext|>
<commit_before>// Copyright (c) 2018 Google 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <algorithm> #include <vector> #ifdef SPIRV_EFFCEE #include "effcee/effcee.h" #endif #include "opt/basic_block.h" #include "opt/ir_builder.h" #include "opt/build_module.h" #include "opt/instruction.h" #include "opt/type_manager.h" #include "spirv-tools/libspirv.hpp" namespace { using namespace spvtools; using ir::IRContext; using Analysis = IRContext::Analysis; #ifdef SPIRV_EFFCEE using IRBuilderTest = ::testing::Test; bool Validate(const std::vector<uint32_t>& bin) { spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2; spv_context spvContext = spvContextCreate(target_env); spv_diagnostic diagnostic = nullptr; spv_const_binary_t binary = {bin.data(), bin.size()}; spv_result_t error = spvValidate(spvContext, &binary, &diagnostic); if (error != 0) spvDiagnosticPrint(diagnostic); spvDiagnosticDestroy(diagnostic); spvContextDestroy(spvContext); return error == 0; } void Match(const std::string& original, ir::IRContext* context, bool do_validation = true) { std::vector<uint32_t> bin; context->module()->ToBinary(&bin, true); if (do_validation) { EXPECT_TRUE(Validate(bin)); } std::string assembly; SpirvTools tools(SPV_ENV_UNIVERSAL_1_2); EXPECT_TRUE( tools.Disassemble(bin, &assembly, SpirvTools::kDefaultDisassembleOption)) << "Disassembling failed for shader:\n" << assembly << std::endl; auto match_result = effcee::Match(assembly, original); EXPECT_EQ(effcee::Result::Status::Ok, match_result.status()) << match_result.message() << "\nChecking result:\n" << assembly; } TEST_F(IRBuilderTest, TestInsnAddition) { const std::string text = R"( ; CHECK: %18 = OpLabel ; CHECK: OpPhi %int %int_0 %14 ; CHECK: OpPhi %bool %16 %14 ; CHECK: OpBranch %17 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %2 "main" %3 OpExecutionMode %2 OriginUpperLeft OpSource GLSL 330 OpName %2 "main" OpName %4 "i" OpName %3 "c" OpDecorate %3 Location 0 %5 = OpTypeVoid %6 = OpTypeFunction %5 %7 = OpTypeInt 32 1 %8 = OpTypePointer Function %7 %9 = OpConstant %7 0 %10 = OpTypeBool %11 = OpTypeFloat 32 %12 = OpTypeVector %11 4 %13 = OpTypePointer Output %12 %3 = OpVariable %13 Output %2 = OpFunction %5 None %6 %14 = OpLabel %4 = OpVariable %8 Function OpStore %4 %9 %15 = OpLoad %7 %4 %16 = OpINotEqual %10 %15 %9 OpSelectionMerge %17 None OpBranchConditional %16 %18 %17 %18 = OpLabel OpBranch %17 %17 = OpLabel OpReturn OpFunctionEnd )"; { std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); ir::BasicBlock* bb = context->cfg()->block(18); // Build managers. context->get_def_use_mgr(); context->get_instr_block(nullptr); opt::InstructionBuilder builder(context.get(), &*bb->begin()); ir::Instruction* phi1 = builder.AddPhi(7, {9, 14}); ir::Instruction* phi2 = builder.AddPhi(10, {16, 14}); // Make sure the InstructionBuilder did not update the def/use manager. EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr); EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr); EXPECT_EQ(context->get_instr_block(phi1), nullptr); EXPECT_EQ(context->get_instr_block(phi2), nullptr); Match(text, context.get()); } { std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); // Build managers. context->get_def_use_mgr(); context->get_instr_block(nullptr); ir::BasicBlock* bb = context->cfg()->block(18); opt::InstructionBuilder builder( context.get(), &*bb->begin(), ir::IRContext::kAnalysisDefUse | ir::IRContext::kAnalysisInstrToBlockMapping); ir::Instruction* phi1 = builder.AddPhi(7, {9, 14}); ir::Instruction* phi2 = builder.AddPhi(10, {16, 14}); // Make sure InstructionBuilder updated the def/use manager EXPECT_NE(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr); EXPECT_NE(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr); EXPECT_NE(context->get_instr_block(phi1), nullptr); EXPECT_NE(context->get_instr_block(phi2), nullptr); Match(text, context.get()); } } TEST_F(IRBuilderTest, TestCondBranchAddition) { const std::string text = R"( ; CHECK: %main = OpFunction %void None %6 ; CHECK-NEXT: %15 = OpLabel ; CHECK-NEXT: OpSelectionMerge %13 None ; CHECK-NEXT: OpBranchConditional %true %14 %13 ; CHECK-NEXT: %14 = OpLabel ; CHECK-NEXT: OpBranch %13 ; CHECK-NEXT: %13 = OpLabel ; CHECK-NEXT: OpReturn OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %2 "main" %3 OpExecutionMode %2 OriginUpperLeft OpSource GLSL 330 OpName %2 "main" OpName %4 "i" OpName %3 "c" OpDecorate %3 Location 0 %5 = OpTypeVoid %6 = OpTypeFunction %5 %7 = OpTypeBool %8 = OpTypePointer Function %7 %9 = OpConstantTrue %7 %10 = OpTypeFloat 32 %11 = OpTypeVector %10 4 %12 = OpTypePointer Output %11 %3 = OpVariable %12 Output %4 = OpVariable %8 Private %2 = OpFunction %5 None %6 %13 = OpLabel OpReturn OpFunctionEnd )"; { std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); ir::Function& fn = *context->module()->begin(); ir::BasicBlock& bb_merge = *fn.begin(); fn.begin().InsertBefore(std::unique_ptr<ir::BasicBlock>( new ir::BasicBlock(std::unique_ptr<ir::Instruction>(new ir::Instruction( context.get(), SpvOpLabel, 0, context->TakeNextId(), {}))))); ir::BasicBlock& bb_true = *fn.begin(); { opt::InstructionBuilder builder(context.get(), &*bb_true.begin()); builder.AddBranch(bb_merge.id()); } fn.begin().InsertBefore(std::unique_ptr<ir::BasicBlock>( new ir::BasicBlock(std::unique_ptr<ir::Instruction>(new ir::Instruction( context.get(), SpvOpLabel, 0, context->TakeNextId(), {}))))); ir::BasicBlock& bb_cond = *fn.begin(); opt::InstructionBuilder builder(context.get(), &bb_cond); // This also test consecutive instruction insertion: merge selection + // branch. builder.AddConditionalBranch(9, bb_true.id(), bb_merge.id(), bb_merge.id()); Match(text, context.get()); } } TEST_F(IRBuilderTest, AddSelect) { const std::string text = R"( ; CHECK: [[bool:%\w+]] = OpTypeBool ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0 ; CHECK: [[true:%\w+]] = OpConstantTrue [[bool]] ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1 ; CHECK: OpSelect [[uint]] [[true]] [[u0]] [[u1]] OpCapability Kernel OpCapability Linkage OpMemoryModel Logical OpenCL %1 = OpTypeVoid %2 = OpTypeBool %3 = OpTypeInt 32 0 %4 = OpConstantTrue %2 %5 = OpConstant %3 0 %6 = OpConstant %3 1 %7 = OpTypeFunction %1 %8 = OpFunction %1 None %7 %9 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); EXPECT_NE(nullptr, context); opt::InstructionBuilder builder( context.get(), &*context->module()->begin()->begin()->begin()); EXPECT_NE(nullptr, builder.AddSelect(3u, 4u, 5u, 6u)); Match(text, context.get()); } TEST_F(IRBuilderTest, AddCompositeConstruct) { const std::string text = R"( ; CHECK: [[uint:%\w+]] = OpTypeInt ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1 ; CHECK: [[struct:%\w+]] = OpTypeStruct [[uint]] [[uint]] [[uint]] [[uint]] ; CHECK: OpCompositeConstruct [[struct]] [[u0]] [[u1]] [[u1]] [[u0]] OpCapability Kernel OpCapability Linkage OpMemoryModel Logical OpenCL %1 = OpTypeVoid %2 = OpTypeInt 32 0 %3 = OpConstant %2 0 %4 = OpConstant %2 1 %5 = OpTypeStruct %2 %2 %2 %2 %6 = OpTypeFunction %1 %7 = OpFunction %1 None %6 %8 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); EXPECT_NE(nullptr, context); opt::InstructionBuilder builder( context.get(), &*context->module()->begin()->begin()->begin()); std::vector<uint32_t> ids = {3u, 4u, 4u, 3u}; EXPECT_NE(nullptr, builder.AddCompositeConstruct(5u, ids)); Match(text, context.get()); } #endif // SPIRV_EFFCEE } // anonymous namespace <commit_msg>Make IR builder use the type manager for constants<commit_after>// Copyright (c) 2018 Google 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <algorithm> #include <vector> #ifdef SPIRV_EFFCEE #include "effcee/effcee.h" #endif #include "opt/basic_block.h" #include "opt/ir_builder.h" #include "opt/build_module.h" #include "opt/instruction.h" #include "opt/type_manager.h" #include "spirv-tools/libspirv.hpp" namespace { using namespace spvtools; using ir::IRContext; using Analysis = IRContext::Analysis; #ifdef SPIRV_EFFCEE using IRBuilderTest = ::testing::Test; bool Validate(const std::vector<uint32_t>& bin) { spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2; spv_context spvContext = spvContextCreate(target_env); spv_diagnostic diagnostic = nullptr; spv_const_binary_t binary = {bin.data(), bin.size()}; spv_result_t error = spvValidate(spvContext, &binary, &diagnostic); if (error != 0) spvDiagnosticPrint(diagnostic); spvDiagnosticDestroy(diagnostic); spvContextDestroy(spvContext); return error == 0; } void Match(const std::string& original, ir::IRContext* context, bool do_validation = true) { std::vector<uint32_t> bin; context->module()->ToBinary(&bin, true); if (do_validation) { EXPECT_TRUE(Validate(bin)); } std::string assembly; SpirvTools tools(SPV_ENV_UNIVERSAL_1_2); EXPECT_TRUE( tools.Disassemble(bin, &assembly, SpirvTools::kDefaultDisassembleOption)) << "Disassembling failed for shader:\n" << assembly << std::endl; auto match_result = effcee::Match(assembly, original); EXPECT_EQ(effcee::Result::Status::Ok, match_result.status()) << match_result.message() << "\nChecking result:\n" << assembly; } TEST_F(IRBuilderTest, TestInsnAddition) { const std::string text = R"( ; CHECK: %18 = OpLabel ; CHECK: OpPhi %int %int_0 %14 ; CHECK: OpPhi %bool %16 %14 ; CHECK: OpBranch %17 OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %2 "main" %3 OpExecutionMode %2 OriginUpperLeft OpSource GLSL 330 OpName %2 "main" OpName %4 "i" OpName %3 "c" OpDecorate %3 Location 0 %5 = OpTypeVoid %6 = OpTypeFunction %5 %7 = OpTypeInt 32 1 %8 = OpTypePointer Function %7 %9 = OpConstant %7 0 %10 = OpTypeBool %11 = OpTypeFloat 32 %12 = OpTypeVector %11 4 %13 = OpTypePointer Output %12 %3 = OpVariable %13 Output %2 = OpFunction %5 None %6 %14 = OpLabel %4 = OpVariable %8 Function OpStore %4 %9 %15 = OpLoad %7 %4 %16 = OpINotEqual %10 %15 %9 OpSelectionMerge %17 None OpBranchConditional %16 %18 %17 %18 = OpLabel OpBranch %17 %17 = OpLabel OpReturn OpFunctionEnd )"; { std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); ir::BasicBlock* bb = context->cfg()->block(18); // Build managers. context->get_def_use_mgr(); context->get_instr_block(nullptr); opt::InstructionBuilder builder(context.get(), &*bb->begin()); ir::Instruction* phi1 = builder.AddPhi(7, {9, 14}); ir::Instruction* phi2 = builder.AddPhi(10, {16, 14}); // Make sure the InstructionBuilder did not update the def/use manager. EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr); EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr); EXPECT_EQ(context->get_instr_block(phi1), nullptr); EXPECT_EQ(context->get_instr_block(phi2), nullptr); Match(text, context.get()); } { std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); // Build managers. context->get_def_use_mgr(); context->get_instr_block(nullptr); ir::BasicBlock* bb = context->cfg()->block(18); opt::InstructionBuilder builder( context.get(), &*bb->begin(), ir::IRContext::kAnalysisDefUse | ir::IRContext::kAnalysisInstrToBlockMapping); ir::Instruction* phi1 = builder.AddPhi(7, {9, 14}); ir::Instruction* phi2 = builder.AddPhi(10, {16, 14}); // Make sure InstructionBuilder updated the def/use manager EXPECT_NE(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr); EXPECT_NE(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr); EXPECT_NE(context->get_instr_block(phi1), nullptr); EXPECT_NE(context->get_instr_block(phi2), nullptr); Match(text, context.get()); } } TEST_F(IRBuilderTest, TestCondBranchAddition) { const std::string text = R"( ; CHECK: %main = OpFunction %void None %6 ; CHECK-NEXT: %15 = OpLabel ; CHECK-NEXT: OpSelectionMerge %13 None ; CHECK-NEXT: OpBranchConditional %true %14 %13 ; CHECK-NEXT: %14 = OpLabel ; CHECK-NEXT: OpBranch %13 ; CHECK-NEXT: %13 = OpLabel ; CHECK-NEXT: OpReturn OpCapability Shader %1 = OpExtInstImport "GLSL.std.450" OpMemoryModel Logical GLSL450 OpEntryPoint Fragment %2 "main" %3 OpExecutionMode %2 OriginUpperLeft OpSource GLSL 330 OpName %2 "main" OpName %4 "i" OpName %3 "c" OpDecorate %3 Location 0 %5 = OpTypeVoid %6 = OpTypeFunction %5 %7 = OpTypeBool %8 = OpTypePointer Function %7 %9 = OpConstantTrue %7 %10 = OpTypeFloat 32 %11 = OpTypeVector %10 4 %12 = OpTypePointer Output %11 %3 = OpVariable %12 Output %4 = OpVariable %8 Private %2 = OpFunction %5 None %6 %13 = OpLabel OpReturn OpFunctionEnd )"; { std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); ir::Function& fn = *context->module()->begin(); ir::BasicBlock& bb_merge = *fn.begin(); fn.begin().InsertBefore(std::unique_ptr<ir::BasicBlock>( new ir::BasicBlock(std::unique_ptr<ir::Instruction>(new ir::Instruction( context.get(), SpvOpLabel, 0, context->TakeNextId(), {}))))); ir::BasicBlock& bb_true = *fn.begin(); { opt::InstructionBuilder builder(context.get(), &*bb_true.begin()); builder.AddBranch(bb_merge.id()); } fn.begin().InsertBefore(std::unique_ptr<ir::BasicBlock>( new ir::BasicBlock(std::unique_ptr<ir::Instruction>(new ir::Instruction( context.get(), SpvOpLabel, 0, context->TakeNextId(), {}))))); ir::BasicBlock& bb_cond = *fn.begin(); opt::InstructionBuilder builder(context.get(), &bb_cond); // This also test consecutive instruction insertion: merge selection + // branch. builder.AddConditionalBranch(9, bb_true.id(), bb_merge.id(), bb_merge.id()); Match(text, context.get()); } } TEST_F(IRBuilderTest, AddSelect) { const std::string text = R"( ; CHECK: [[bool:%\w+]] = OpTypeBool ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0 ; CHECK: [[true:%\w+]] = OpConstantTrue [[bool]] ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1 ; CHECK: OpSelect [[uint]] [[true]] [[u0]] [[u1]] OpCapability Kernel OpCapability Linkage OpMemoryModel Logical OpenCL %1 = OpTypeVoid %2 = OpTypeBool %3 = OpTypeInt 32 0 %4 = OpConstantTrue %2 %5 = OpConstant %3 0 %6 = OpConstant %3 1 %7 = OpTypeFunction %1 %8 = OpFunction %1 None %7 %9 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); EXPECT_NE(nullptr, context); opt::InstructionBuilder builder( context.get(), &*context->module()->begin()->begin()->begin()); EXPECT_NE(nullptr, builder.AddSelect(3u, 4u, 5u, 6u)); Match(text, context.get()); } TEST_F(IRBuilderTest, AddCompositeConstruct) { const std::string text = R"( ; CHECK: [[uint:%\w+]] = OpTypeInt ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1 ; CHECK: [[struct:%\w+]] = OpTypeStruct [[uint]] [[uint]] [[uint]] [[uint]] ; CHECK: OpCompositeConstruct [[struct]] [[u0]] [[u1]] [[u1]] [[u0]] OpCapability Kernel OpCapability Linkage OpMemoryModel Logical OpenCL %1 = OpTypeVoid %2 = OpTypeInt 32 0 %3 = OpConstant %2 0 %4 = OpConstant %2 1 %5 = OpTypeStruct %2 %2 %2 %2 %6 = OpTypeFunction %1 %7 = OpFunction %1 None %6 %8 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); EXPECT_NE(nullptr, context); opt::InstructionBuilder builder( context.get(), &*context->module()->begin()->begin()->begin()); std::vector<uint32_t> ids = {3u, 4u, 4u, 3u}; EXPECT_NE(nullptr, builder.AddCompositeConstruct(5u, ids)); Match(text, context.get()); } TEST_F(IRBuilderTest, ConstantAdder) { const std::string text = R"( ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0 ; CHECK: OpConstant [[uint]] 13 ; CHECK: [[sint:%\w+]] = OpTypeInt 32 1 ; CHECK: OpConstant [[sint]] -1 ; CHECK: OpConstant [[uint]] 1 ; CHECK: OpConstant [[sint]] 34 ; CHECK: OpConstant [[uint]] 0 ; CHECK: OpConstant [[sint]] 0 OpCapability Shader OpCapability Linkage OpMemoryModel Logical GLSL450 %1 = OpTypeVoid %2 = OpTypeFunction %1 %3 = OpFunction %1 None %2 %4 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); EXPECT_NE(nullptr, context); opt::InstructionBuilder builder( context.get(), &*context->module()->begin()->begin()->begin()); EXPECT_NE(nullptr, builder.Add32BitUnsignedIntegerConstant(13)); EXPECT_NE(nullptr, builder.Add32BitSignedIntegerConstant(-1)); // Try adding the same constants again to make sure they aren't added. EXPECT_NE(nullptr, builder.Add32BitUnsignedIntegerConstant(13)); EXPECT_NE(nullptr, builder.Add32BitSignedIntegerConstant(-1)); // Try adding different constants to make sure the type is reused. EXPECT_NE(nullptr, builder.Add32BitUnsignedIntegerConstant(1)); EXPECT_NE(nullptr, builder.Add32BitSignedIntegerConstant(34)); // Try adding 0 as both signed and unsigned. EXPECT_NE(nullptr, builder.Add32BitUnsignedIntegerConstant(0)); EXPECT_NE(nullptr, builder.Add32BitSignedIntegerConstant(0)); Match(text, context.get()); } TEST_F(IRBuilderTest, ConstantAdderTypeAlreadyExists) { const std::string text = R"( ; CHECK: OpConstant %uint 13 ; CHECK: OpConstant %int -1 ; CHECK: OpConstant %uint 1 ; CHECK: OpConstant %int 34 ; CHECK: OpConstant %uint 0 ; CHECK: OpConstant %int 0 OpCapability Shader OpCapability Linkage OpMemoryModel Logical GLSL450 %1 = OpTypeVoid %uint = OpTypeInt 32 0 %int = OpTypeInt 32 1 %4 = OpTypeFunction %1 %5 = OpFunction %1 None %4 %6 = OpLabel OpReturn OpFunctionEnd )"; std::unique_ptr<ir::IRContext> context = BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text); EXPECT_NE(nullptr, context); opt::InstructionBuilder builder( context.get(), &*context->module()->begin()->begin()->begin()); ir::Instruction* const_1 = builder.Add32BitUnsignedIntegerConstant(13); ir::Instruction* const_2 = builder.Add32BitSignedIntegerConstant(-1); EXPECT_NE(nullptr, const_1); EXPECT_NE(nullptr, const_2); // Try adding the same constants again to make sure they aren't added. EXPECT_EQ(const_1, builder.Add32BitUnsignedIntegerConstant(13)); EXPECT_EQ(const_2, builder.Add32BitSignedIntegerConstant(-1)); ir::Instruction* const_3 = builder.Add32BitUnsignedIntegerConstant(1); ir::Instruction* const_4 = builder.Add32BitSignedIntegerConstant(34); // Try adding different constants to make sure the type is reused. EXPECT_NE(nullptr, const_3); EXPECT_NE(nullptr, const_4); ir::Instruction* const_5 = builder.Add32BitUnsignedIntegerConstant(0); ir::Instruction* const_6 = builder.Add32BitSignedIntegerConstant(0); // Try adding 0 as both signed and unsigned. EXPECT_NE(nullptr, const_5); EXPECT_NE(nullptr, const_6); // They have the same value but different types so should be unique. EXPECT_NE(const_5, const_6); // Check the types are correct. uint32_t type_id_unsigned = const_1->GetSingleWordOperand(0); uint32_t type_id_signed = const_2->GetSingleWordOperand(0); EXPECT_NE(type_id_unsigned, type_id_signed); EXPECT_EQ(const_3->GetSingleWordOperand(0), type_id_unsigned); EXPECT_EQ(const_5->GetSingleWordOperand(0), type_id_unsigned); EXPECT_EQ(const_4->GetSingleWordOperand(0), type_id_signed); EXPECT_EQ(const_6->GetSingleWordOperand(0), type_id_signed); Match(text, context.get()); } #endif // SPIRV_EFFCEE } // anonymous namespace <|endoftext|>
<commit_before>#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->s_settingsDialog = 0; this->systemTrayIcon = 0; this->setWindowTitle(APP_TITLE); this->setMinimumSize(627, 500); this->view = new WebView(this); this->view->setUrl(APP_URL); this->setCentralWidget(this->view); this->view->show(); #ifndef Q_WS_MAC // Global keys QxtGlobalShortcut* previousMediaShortcut = new QxtGlobalShortcut(QKeySequence("Media Previous")); connect(previousMediaShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(previous())); QxtGlobalShortcut* previousShortcut = new QxtGlobalShortcut(QKeySequence("Meta+F10")); connect(previousShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(previous())); QxtGlobalShortcut* playMediaShortcut = new QxtGlobalShortcut(QKeySequence("Media Play")); connect(playMediaShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(pause())); QxtGlobalShortcut* playShortcut = new QxtGlobalShortcut(QKeySequence("Meta+F11")); connect(playShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(pause())); QxtGlobalShortcut* nextMediaShortcut = new QxtGlobalShortcut(QKeySequence("Media Next")); connect(nextMediaShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(next())); QxtGlobalShortcut* nextShortcut = new QxtGlobalShortcut(QKeySequence("Meta+F12")); connect(nextShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(next())); #endif // Tray menu QMenu *menu = new QMenu(); QAction *activateAction = menu->addAction(u("Активиров&ать")); connect(activateAction, SIGNAL(triggered()), this, SLOT(showAndRaise())); menu->addSeparator(); QAction *trackArtistAction = menu->addAction(""); trackArtistAction->setEnabled(false); trackArtistAction->setVisible(false); connect(qApp->bridge, SIGNAL(playing_change(bool)), trackArtistAction, SLOT(setVisible(bool))); QAction *trackTitleAction = menu->addAction(""); trackTitleAction->setEnabled(false); trackTitleAction->setVisible(false); connect(qApp->bridge, SIGNAL(playing_change(bool)), trackTitleAction, SLOT(setVisible(bool))); QAction *previousTrackAction = menu->addAction(u("П&редыдущий трек")); previousTrackAction->setEnabled(false); connect(previousTrackAction, SIGNAL(triggered()), qApp->bridge, SIGNAL(previous())); connect(qApp->bridge, SIGNAL(playing_change(bool)), previousTrackAction, SLOT(setEnabled(bool))); QAction *playPauseAction = menu->addAction(u("Пауза/продолж&ить")); playPauseAction->setEnabled(false); connect(playPauseAction, SIGNAL(triggered()), qApp->bridge, SIGNAL(pause())); connect(qApp->bridge, SIGNAL(playing_change(bool)), playPauseAction, SLOT(setEnabled(bool))); QAction *nextTrackAction = menu->addAction(u("С&ледующий трек")); nextTrackAction->setEnabled(false); connect(nextTrackAction, SIGNAL(triggered()), qApp->bridge, SIGNAL(next())); connect(qApp->bridge, SIGNAL(playing_change(bool)), nextTrackAction, SLOT(setEnabled(bool))); menu->addSeparator(); QAction *settingsDialogAction = menu->addAction(u("Уведомления и прокси...")); connect(settingsDialogAction, SIGNAL(triggered()), this, SLOT(settingsDialog())); QAction *quitAction = menu->addAction(u("В&ыход")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(qApp->bridge, SIGNAL(track_change(QString,QString)), this, SLOT(notify(QString,QString))); this->systemTrayIcon = new QSystemTrayIcon(); this->systemTrayIcon->setContextMenu(menu); #ifdef Q_WS_MAC this->systemTrayIcon->setIcon(QIcon(":/icon16-mac")); #endif #ifndef Q_WS_MAC this->systemTrayIcon->setIcon(QIcon(":/icon16")); connect(this->systemTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showAndRaise(QSystemTrayIcon::ActivationReason))); //mainWindow.setWindowIcon(icon); #endif this->systemTrayIcon->show(); connect(this->view, SIGNAL(titleChanged(QString)), this, SLOT(setWindowTitle(QString))); } void MainWindow::setWindowTitle(const QString &title) { QMainWindow::setWindowTitle(title); if (this->systemTrayIcon) { this->systemTrayIcon->setToolTip(title); } } MainWindow::~MainWindow() { delete this->systemTrayIcon; delete this->view; } void MainWindow::showAndRaise() { this->show(); this->raise(); } void MainWindow::showAndRaise(QSystemTrayIcon::ActivationReason reason) { if (QSystemTrayIcon::Trigger == reason) this->showAndRaise(); } void MainWindow::notify(QString artist, QString title) { QSettings settings; if (settings.value("Interface/Notifications", true).toBool()) { this->systemTrayIcon->showMessage(title, artist, QSystemTrayIcon::NoIcon, 2000); } this->systemTrayIcon->contextMenu()->actions()[2]->setText(artist); this->systemTrayIcon->contextMenu()->actions()[3]->setText(title); } void MainWindow::settingsDialog() { if (!this->s_settingsDialog) { this->s_settingsDialog = new SettingsDialog(this); } this->s_settingsDialog->show(); } <commit_msg>Активировать -> Показать главное окно closes #3<commit_after>#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->s_settingsDialog = 0; this->systemTrayIcon = 0; this->setWindowTitle(APP_TITLE); this->setMinimumSize(627, 500); this->view = new WebView(this); this->view->setUrl(APP_URL); this->setCentralWidget(this->view); this->view->show(); #ifndef Q_WS_MAC // Global keys QxtGlobalShortcut* previousMediaShortcut = new QxtGlobalShortcut(QKeySequence("Media Previous")); connect(previousMediaShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(previous())); QxtGlobalShortcut* previousShortcut = new QxtGlobalShortcut(QKeySequence("Meta+F10")); connect(previousShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(previous())); QxtGlobalShortcut* playMediaShortcut = new QxtGlobalShortcut(QKeySequence("Media Play")); connect(playMediaShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(pause())); QxtGlobalShortcut* playShortcut = new QxtGlobalShortcut(QKeySequence("Meta+F11")); connect(playShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(pause())); QxtGlobalShortcut* nextMediaShortcut = new QxtGlobalShortcut(QKeySequence("Media Next")); connect(nextMediaShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(next())); QxtGlobalShortcut* nextShortcut = new QxtGlobalShortcut(QKeySequence("Meta+F12")); connect(nextShortcut, SIGNAL(activated()), qApp->bridge, SIGNAL(next())); #endif // Tray menu QMenu *menu = new QMenu(); QAction *activateAction = menu->addAction(u("Показ&ать главное окно")); connect(activateAction, SIGNAL(triggered()), this, SLOT(showAndRaise())); menu->addSeparator(); QAction *trackArtistAction = menu->addAction(""); trackArtistAction->setEnabled(false); trackArtistAction->setVisible(false); connect(qApp->bridge, SIGNAL(playing_change(bool)), trackArtistAction, SLOT(setVisible(bool))); QAction *trackTitleAction = menu->addAction(""); trackTitleAction->setEnabled(false); trackTitleAction->setVisible(false); connect(qApp->bridge, SIGNAL(playing_change(bool)), trackTitleAction, SLOT(setVisible(bool))); QAction *previousTrackAction = menu->addAction(u("П&редыдущий трек")); previousTrackAction->setEnabled(false); connect(previousTrackAction, SIGNAL(triggered()), qApp->bridge, SIGNAL(previous())); connect(qApp->bridge, SIGNAL(playing_change(bool)), previousTrackAction, SLOT(setEnabled(bool))); QAction *playPauseAction = menu->addAction(u("Пауза/продолж&ить")); playPauseAction->setEnabled(false); connect(playPauseAction, SIGNAL(triggered()), qApp->bridge, SIGNAL(pause())); connect(qApp->bridge, SIGNAL(playing_change(bool)), playPauseAction, SLOT(setEnabled(bool))); QAction *nextTrackAction = menu->addAction(u("С&ледующий трек")); nextTrackAction->setEnabled(false); connect(nextTrackAction, SIGNAL(triggered()), qApp->bridge, SIGNAL(next())); connect(qApp->bridge, SIGNAL(playing_change(bool)), nextTrackAction, SLOT(setEnabled(bool))); menu->addSeparator(); QAction *settingsDialogAction = menu->addAction(u("Уведомления и прокси...")); connect(settingsDialogAction, SIGNAL(triggered()), this, SLOT(settingsDialog())); QAction *quitAction = menu->addAction(u("В&ыход")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(qApp->bridge, SIGNAL(track_change(QString,QString)), this, SLOT(notify(QString,QString))); this->systemTrayIcon = new QSystemTrayIcon(); this->systemTrayIcon->setContextMenu(menu); #ifdef Q_WS_MAC this->systemTrayIcon->setIcon(QIcon(":/icon16-mac")); #endif #ifndef Q_WS_MAC this->systemTrayIcon->setIcon(QIcon(":/icon16")); connect(this->systemTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(showAndRaise(QSystemTrayIcon::ActivationReason))); //mainWindow.setWindowIcon(icon); #endif this->systemTrayIcon->show(); connect(this->view, SIGNAL(titleChanged(QString)), this, SLOT(setWindowTitle(QString))); } void MainWindow::setWindowTitle(const QString &title) { QMainWindow::setWindowTitle(title); if (this->systemTrayIcon) { this->systemTrayIcon->setToolTip(title); } } MainWindow::~MainWindow() { delete this->systemTrayIcon; delete this->view; } void MainWindow::showAndRaise() { this->show(); this->raise(); } void MainWindow::showAndRaise(QSystemTrayIcon::ActivationReason reason) { if (QSystemTrayIcon::Trigger == reason) this->showAndRaise(); } void MainWindow::notify(QString artist, QString title) { QSettings settings; if (settings.value("Interface/Notifications", true).toBool()) { this->systemTrayIcon->showMessage(title, artist, QSystemTrayIcon::NoIcon, 2000); } this->systemTrayIcon->contextMenu()->actions()[2]->setText(artist); this->systemTrayIcon->contextMenu()->actions()[3]->setText(title); } void MainWindow::settingsDialog() { if (!this->s_settingsDialog) { this->s_settingsDialog = new SettingsDialog(this); } this->s_settingsDialog->show(); } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <program.hpp> #include <traits.hpp> #include <kernel_headers/KParam.hpp> #include <debug_opencl.hpp> #include <iostream> using cl::Buffer; using cl::Program; using cl::Kernel; using cl::EnqueueArgs; using cl::NDRange; using std::string; namespace opencl { const static std::string USE_DBL_SRC_STR("\n\ #ifdef USE_DOUBLE\n\ #pragma OPENCL EXTENSION cl_khr_fp64 : enable\n\ #endif\n"); void buildProgram(cl::Program &prog, const char *ker_str, const int ker_len, std::string options) { buildProgram(prog, 1, &ker_str, &ker_len, options); } void buildProgram(cl::Program &prog, const int num_files, const char **ker_strs, const int *ker_lens, std::string options) { try { Program::Sources setSrc; setSrc.emplace_back(USE_DBL_SRC_STR.c_str(), USE_DBL_SRC_STR.length()); setSrc.emplace_back(KParam_hpp, KParam_hpp_len); for (int i = 0; i < num_files; i++) { setSrc.emplace_back(ker_strs[i], ker_lens[i]); } static std::string defaults = std::string(" -D dim_t=") + std::string(dtype_traits<dim_t>::getName()); prog = cl::Program(getContext(), setSrc); auto device = getDevice(); std::string cl_std = std::string(" -cl-std=CL") + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>().substr(9, 3); // Braces needed to list initialize the vector for the first argument prog.build({device}, (cl_std + defaults + options).c_str()); } catch (...) { SHOW_BUILD_INFO(prog); throw; } } } <commit_msg>OPENCL: Bugfix for kernels missing M_PI<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <program.hpp> #include <traits.hpp> #include <kernel_headers/KParam.hpp> #include <debug_opencl.hpp> #include <iostream> using cl::Buffer; using cl::Program; using cl::Kernel; using cl::EnqueueArgs; using cl::NDRange; using std::string; namespace opencl { const static std::string USE_DBL_SRC_STR("\n\ #ifdef USE_DOUBLE\n\ #pragma OPENCL EXTENSION cl_khr_fp64 : enable\n\ #endif\n \ #ifndef M_PI\n \ #define M_PI 3.1415926535897932384626433832795028841971693993751058209749445923078164\n \ #endif\n \ "); void buildProgram(cl::Program &prog, const char *ker_str, const int ker_len, std::string options) { buildProgram(prog, 1, &ker_str, &ker_len, options); } void buildProgram(cl::Program &prog, const int num_files, const char **ker_strs, const int *ker_lens, std::string options) { try { Program::Sources setSrc; setSrc.emplace_back(USE_DBL_SRC_STR.c_str(), USE_DBL_SRC_STR.length()); setSrc.emplace_back(KParam_hpp, KParam_hpp_len); for (int i = 0; i < num_files; i++) { setSrc.emplace_back(ker_strs[i], ker_lens[i]); } static std::string defaults = std::string(" -D dim_t=") + std::string(dtype_traits<dim_t>::getName()); prog = cl::Program(getContext(), setSrc); auto device = getDevice(); std::string cl_std = std::string(" -cl-std=CL") + device.getInfo<CL_DEVICE_OPENCL_C_VERSION>().substr(9, 3); // Braces needed to list initialize the vector for the first argument prog.build({device}, (cl_std + defaults + options).c_str()); } catch (...) { SHOW_BUILD_INFO(prog); throw; } } } <|endoftext|>
<commit_before>#include "testing/testing.hpp" #include "coding/reader.hpp" #include "coding/writer.hpp" #include "routing_common/transit_serdes.hpp" #include "routing_common/transit_types.hpp" #include <algorithm> #include <cstdint> #include <vector> using namespace routing; using namespace routing::transit; using namespace std; namespace routing { namespace transit { template<class S, class D, class Obj> void TestCommonSerialization(Obj const & obj) { vector<uint8_t> buffer; MemWriter<vector<uint8_t>> writer(buffer); S serializer(writer); serializer(obj); MemReader reader(buffer.data(), buffer.size()); ReaderSource<MemReader> src(reader); Obj deserializedObj; D deserializer(src); deserializer(deserializedObj); TEST(obj.IsEqualForTesting(deserializedObj), (obj, deserializedObj)); } void TestSerialization(TransitHeader const & header) { TestCommonSerialization<FixedSizeSerializer<MemWriter<vector<uint8_t>>>, FixedSizeDeserializer<ReaderSource<MemReader>>>(header); } template<class Obj> void TestSerialization(Obj const & obj) { TestCommonSerialization<Serializer<MemWriter<vector<uint8_t>>>, Deserializer<ReaderSource<MemReader>>>(obj); } UNIT_TEST(Transit_HeaderRewriting) { TransitHeader const bigHeader(1 /* version */, 500 /* stopsOffset */, 1000 /* gatesOffset */, 200000 /* edgesOffset */, 300000 /* transfersOffset */, 400000 /* linesOffset */, 5000000 /* shapesOffset */, 6000000 /* networksOffset */, 700000000 /* endOffset */); TransitHeader header; vector<uint8_t> buffer; MemWriter<vector<uint8_t>> writer(buffer); // Writing. FixedSizeSerializer<MemWriter<vector<uint8_t>>> serializer(writer); serializer(header); auto const endOffset = writer.Pos(); // Rewriting. header = bigHeader; writer.Seek(0 /* start offset */); serializer(header); TEST_EQUAL(writer.Pos(), endOffset, ()); // Reading. MemReader reader(buffer.data(), buffer.size()); ReaderSource<MemReader> src(reader); TransitHeader deserializedHeader; FixedSizeDeserializer<ReaderSource<MemReader>> deserializer(src); deserializer(deserializedHeader); TEST(deserializedHeader.IsEqualForTesting(bigHeader), (deserializedHeader, bigHeader)); } } // namespace transit } // namespace routing namespace { UNIT_TEST(Transit_HeaderSerialization) { { TransitHeader header; TestSerialization(header); TEST(header.IsValid(), (header)); } { TransitHeader header(1 /* version */, 500 /* stopsOffset */, 1000 /* gatesOffset */, 2000 /* edgesOffset */, 3000 /* transfersOffset */, 4000 /* linesOffset */, 5000 /* shapesOffset */, 6000 /* networksOffset */, 7000 /* endOffset */); TestSerialization(header); TEST(header.IsValid(), (header)); } } UNIT_TEST(Transit_TransitHeaderValidity) { { TransitHeader header; TEST(header.IsValid(), (header)); } { TransitHeader const header(1 /* version */, 40 /* stopsOffset */, 44 /* gatesOffset */, 48 /* edgesOffset */, 52 /* transfersOffset */, 56 /* linesOffset */, 60 /* shapesOffset */, 64 /* networksOffset */, 68 /* endOffset */); TEST(header.IsValid(), (header)); } { TransitHeader const header(1 /* version */, 44 /* stopsOffset */, 40 /* gatesOffset */, 48 /* edgesOffset */, 52 /* transfersOffset */, 56 /* linesOffset */, 60 /* shapesOffset */, 64 /* networksOffset */, 68 /* endOffset */); TEST(!header.IsValid(), (header)); } } UNIT_TEST(Transit_TitleAnchorSerialization) { { TitleAnchor anchor(17 /* min zoom */, 0 /* anchor */); TestSerialization(anchor); TEST(anchor.IsValid(), (anchor)); } { TitleAnchor anchor(10 /* min zoom */, 2 /* anchor */); TestSerialization(anchor); TEST(anchor.IsValid(), (anchor)); } { TitleAnchor anchor(18 /* min zoom */, 7 /* anchor */); TestSerialization(anchor); TEST(anchor.IsValid(), (anchor)); } } UNIT_TEST(Transit_StopSerialization) { { Stop stop; TestSerialization(stop); TEST(!stop.IsValid(), (stop)); } { Stop stop(1234 /* id */, 1234567 /* osm id */, 5678 /* feature id */, 7 /* transfer id */, {7, 8, 9, 10} /* line id */, {55.0, 37.0} /* point */, {} /* anchors */); TestSerialization(stop); TEST(stop.IsValid(), (stop)); } } UNIT_TEST(Transit_SingleMwmSegmentSerialization) { { SingleMwmSegment s(12344 /* feature id */, 0 /* segmentIdx */, true /* forward */); TestSerialization(s); TEST(s.IsValid(), (s)); } { SingleMwmSegment s(12544 /* feature id */, 5 /* segmentIdx */, false /* forward */); TestSerialization(s); TEST(s.IsValid(), (s)); } } UNIT_TEST(Transit_GateSerialization) { Gate gate(12345678 /* osm id */, 12345 /* feature id */, true /* entrance */, false /* exit */, 117 /* weight */, {1, 2, 3} /* stop ids */, {30.0, 50.0} /* point */); TestSerialization(gate); TEST(gate.IsValid(), (gate)); } UNIT_TEST(Transit_GatesRelational) { vector<Gate> const gates = {{1234567 /* osm id */, 123 /* feature id */, true /* entrance */, false /* exit */, 1 /* weight */, {1, 2, 3} /* stops ids */, m2::PointD(0.0, 0.0)}, {12345678 /* osm id */, 1234 /* feature id */, true /* entrance */, false /* exit */, 1 /* weight */, {1, 2, 3} /* stops ids */, m2::PointD(0.0, 0.0)}, {12345678 /* osm id */, 1234 /* feature id */, true /* entrance */, false /* exit */, 1 /* weight */, {1, 2, 3, 4} /* stops ids */, m2::PointD(0.0, 0.0)}}; TEST(is_sorted(gates.cbegin(), gates.cend()), ()); } UNIT_TEST(Transit_EdgeSerialization) { Edge edge(1 /* start stop id */, 2 /* finish stop id */, 123 /* weight */, 11 /* line id */, false /* transfer */, {ShapeId(1, 2), ShapeId(3, 4), ShapeId(5, 6)} /* shape ids */); TestSerialization(edge); TEST(edge.IsValid(), (edge)); } UNIT_TEST(Transit_TransferSerialization) { Transfer transfer(1 /* id */, {40.0, 35.0} /* point */, {1, 2, 3} /* stop ids */, {TitleAnchor(16, 0 /* anchor */)}); TestSerialization(transfer); TEST(transfer.IsValid(), (transfer)); } UNIT_TEST(Transit_LineSerialization) { { Line line(1 /* line id */, "2" /* number */, "Линия" /* title */, "subway" /* type */, "red" /* color */, 3 /* network id */, {{1}} /* stop ids */, 10 /* interval */); TestSerialization(line); TEST(line.IsValid(), (line)); } { Line line(10 /* line id */, "11" /* number */, "Линия" /* title */, "subway" /* type */, "green" /* color */, 12 /* network id */, {{13, 14, 15}} /* stop ids */, 15 /* interval */); TestSerialization(line); TEST(line.IsValid(), (line)); } { Line line(100 /* line id */, "101" /* number */, "Линия" /* title */, "subway" /* type */, "blue" /* color */, 103 /* network id */, {{1, 2, 3}, {7, 8, 9}} /* stop ids */, 15 /* interval */); TestSerialization(line); TEST(line.IsValid(), (line)); } } UNIT_TEST(Transit_ShapeSerialization) { { Shape shape(ShapeId(10, 20), {m2::PointD(0.0, 20.0), m2::PointD(0.0, 0.0)} /* polyline */); TestSerialization(shape); TEST(shape.IsValid(), (shape)); } { Shape shape(ShapeId(11, 21), {m2::PointD(20.0, 20.0), m2::PointD(21.0, 21.0), m2::PointD(22.0, 22.0)} /* polyline */); TestSerialization(shape); TEST(shape.IsValid(), (shape)); } } UNIT_TEST(Transit_ShapeIdRelational) { vector<ShapeId> const ids = {{0, 10}, {0, 11}, {1, 10}, {1, 11}}; TEST(is_sorted(ids.cbegin(), ids.cend()), ()); } UNIT_TEST(Transit_NetworkSerialization) { Network network(0 /* network id */, "Title" /* title */); TestSerialization(network); TEST(network.IsValid(), (network)); } } // namespace <commit_msg>Tests on shape id list optimization at Edge.<commit_after>#include "testing/testing.hpp" #include "coding/reader.hpp" #include "coding/writer.hpp" #include "routing_common/transit_serdes.hpp" #include "routing_common/transit_types.hpp" #include <algorithm> #include <cstdint> #include <vector> using namespace routing; using namespace routing::transit; using namespace std; namespace routing { namespace transit { template<class S, class D, class Obj> void TestCommonSerialization(Obj const & obj) { vector<uint8_t> buffer; MemWriter<vector<uint8_t>> writer(buffer); S serializer(writer); serializer(obj); MemReader reader(buffer.data(), buffer.size()); ReaderSource<MemReader> src(reader); Obj deserializedObj; D deserializer(src); deserializer(deserializedObj); TEST(obj.IsEqualForTesting(deserializedObj), (obj, deserializedObj)); } void TestSerialization(TransitHeader const & header) { TestCommonSerialization<FixedSizeSerializer<MemWriter<vector<uint8_t>>>, FixedSizeDeserializer<ReaderSource<MemReader>>>(header); } template<class Obj> void TestSerialization(Obj const & obj) { TestCommonSerialization<Serializer<MemWriter<vector<uint8_t>>>, Deserializer<ReaderSource<MemReader>>>(obj); } UNIT_TEST(Transit_HeaderRewriting) { TransitHeader const bigHeader(1 /* version */, 500 /* stopsOffset */, 1000 /* gatesOffset */, 200000 /* edgesOffset */, 300000 /* transfersOffset */, 400000 /* linesOffset */, 5000000 /* shapesOffset */, 6000000 /* networksOffset */, 700000000 /* endOffset */); TransitHeader header; vector<uint8_t> buffer; MemWriter<vector<uint8_t>> writer(buffer); // Writing. FixedSizeSerializer<MemWriter<vector<uint8_t>>> serializer(writer); serializer(header); auto const endOffset = writer.Pos(); // Rewriting. header = bigHeader; writer.Seek(0 /* start offset */); serializer(header); TEST_EQUAL(writer.Pos(), endOffset, ()); // Reading. MemReader reader(buffer.data(), buffer.size()); ReaderSource<MemReader> src(reader); TransitHeader deserializedHeader; FixedSizeDeserializer<ReaderSource<MemReader>> deserializer(src); deserializer(deserializedHeader); TEST(deserializedHeader.IsEqualForTesting(bigHeader), (deserializedHeader, bigHeader)); } } // namespace transit } // namespace routing namespace { UNIT_TEST(Transit_HeaderSerialization) { { TransitHeader header; TestSerialization(header); TEST(header.IsValid(), (header)); } { TransitHeader header(1 /* version */, 500 /* stopsOffset */, 1000 /* gatesOffset */, 2000 /* edgesOffset */, 3000 /* transfersOffset */, 4000 /* linesOffset */, 5000 /* shapesOffset */, 6000 /* networksOffset */, 7000 /* endOffset */); TestSerialization(header); TEST(header.IsValid(), (header)); } } UNIT_TEST(Transit_TransitHeaderValidity) { { TransitHeader header; TEST(header.IsValid(), (header)); } { TransitHeader const header(1 /* version */, 40 /* stopsOffset */, 44 /* gatesOffset */, 48 /* edgesOffset */, 52 /* transfersOffset */, 56 /* linesOffset */, 60 /* shapesOffset */, 64 /* networksOffset */, 68 /* endOffset */); TEST(header.IsValid(), (header)); } { TransitHeader const header(1 /* version */, 44 /* stopsOffset */, 40 /* gatesOffset */, 48 /* edgesOffset */, 52 /* transfersOffset */, 56 /* linesOffset */, 60 /* shapesOffset */, 64 /* networksOffset */, 68 /* endOffset */); TEST(!header.IsValid(), (header)); } } UNIT_TEST(Transit_TitleAnchorSerialization) { { TitleAnchor anchor(17 /* min zoom */, 0 /* anchor */); TestSerialization(anchor); TEST(anchor.IsValid(), (anchor)); } { TitleAnchor anchor(10 /* min zoom */, 2 /* anchor */); TestSerialization(anchor); TEST(anchor.IsValid(), (anchor)); } { TitleAnchor anchor(18 /* min zoom */, 7 /* anchor */); TestSerialization(anchor); TEST(anchor.IsValid(), (anchor)); } } UNIT_TEST(Transit_StopSerialization) { { Stop stop; TestSerialization(stop); TEST(!stop.IsValid(), (stop)); } { Stop stop(1234 /* id */, 1234567 /* osm id */, 5678 /* feature id */, 7 /* transfer id */, {7, 8, 9, 10} /* line id */, {55.0, 37.0} /* point */, {} /* anchors */); TestSerialization(stop); TEST(stop.IsValid(), (stop)); } } UNIT_TEST(Transit_SingleMwmSegmentSerialization) { { SingleMwmSegment s(12344 /* feature id */, 0 /* segmentIdx */, true /* forward */); TestSerialization(s); TEST(s.IsValid(), (s)); } { SingleMwmSegment s(12544 /* feature id */, 5 /* segmentIdx */, false /* forward */); TestSerialization(s); TEST(s.IsValid(), (s)); } } UNIT_TEST(Transit_GateSerialization) { Gate gate(12345678 /* osm id */, 12345 /* feature id */, true /* entrance */, false /* exit */, 117 /* weight */, {1, 2, 3} /* stop ids */, {30.0, 50.0} /* point */); TestSerialization(gate); TEST(gate.IsValid(), (gate)); } UNIT_TEST(Transit_GatesRelational) { vector<Gate> const gates = {{1234567 /* osm id */, 123 /* feature id */, true /* entrance */, false /* exit */, 1 /* weight */, {1, 2, 3} /* stops ids */, m2::PointD(0.0, 0.0)}, {12345678 /* osm id */, 1234 /* feature id */, true /* entrance */, false /* exit */, 1 /* weight */, {1, 2, 3} /* stops ids */, m2::PointD(0.0, 0.0)}, {12345678 /* osm id */, 1234 /* feature id */, true /* entrance */, false /* exit */, 1 /* weight */, {1, 2, 3, 4} /* stops ids */, m2::PointD(0.0, 0.0)}}; TEST(is_sorted(gates.cbegin(), gates.cend()), ()); } UNIT_TEST(Transit_EdgeSerialization) { { Edge edge(1 /* start stop id */, 2 /* finish stop id */, 123 /* weight */, 11 /* line id */, false /* transfer */, {ShapeId(1, 2), ShapeId(3, 4), ShapeId(5, 6)} /* shape ids */); TestSerialization(edge); TEST(edge.IsValid(), (edge)); } { Edge edge(1 /* start stop id */, 2 /* finish stop id */, 123 /* weight */, 11 /* line id */, false /* transfer */, {ShapeId(1, 2)} /* shape ids */); TestSerialization(edge); TEST(edge.IsValid(), (edge)); } { Edge edge(1 /* start stop id */, 2 /* finish stop id */, 123 /* weight */, 11 /* line id */, false /* transfer */, {ShapeId(2, 1)} /* shape ids */); TestSerialization(edge); TEST(edge.IsValid(), (edge)); } { Edge edge(1 /* start stop id */, 2 /* finish stop id */, 123 /* weight */, 11 /* line id */, true /* transfer */, {} /* shape ids */); TestSerialization(edge); TEST(edge.IsValid(), (edge)); } } UNIT_TEST(Transit_TransferSerialization) { Transfer transfer(1 /* id */, {40.0, 35.0} /* point */, {1, 2, 3} /* stop ids */, {TitleAnchor(16, 0 /* anchor */)}); TestSerialization(transfer); TEST(transfer.IsValid(), (transfer)); } UNIT_TEST(Transit_LineSerialization) { { Line line(1 /* line id */, "2" /* number */, "Линия" /* title */, "subway" /* type */, "red" /* color */, 3 /* network id */, {{1}} /* stop ids */, 10 /* interval */); TestSerialization(line); TEST(line.IsValid(), (line)); } { Line line(10 /* line id */, "11" /* number */, "Линия" /* title */, "subway" /* type */, "green" /* color */, 12 /* network id */, {{13, 14, 15}} /* stop ids */, 15 /* interval */); TestSerialization(line); TEST(line.IsValid(), (line)); } { Line line(100 /* line id */, "101" /* number */, "Линия" /* title */, "subway" /* type */, "blue" /* color */, 103 /* network id */, {{1, 2, 3}, {7, 8, 9}} /* stop ids */, 15 /* interval */); TestSerialization(line); TEST(line.IsValid(), (line)); } } UNIT_TEST(Transit_ShapeSerialization) { { Shape shape(ShapeId(10, 20), {m2::PointD(0.0, 20.0), m2::PointD(0.0, 0.0)} /* polyline */); TestSerialization(shape); TEST(shape.IsValid(), (shape)); } { Shape shape(ShapeId(11, 21), {m2::PointD(20.0, 20.0), m2::PointD(21.0, 21.0), m2::PointD(22.0, 22.0)} /* polyline */); TestSerialization(shape); TEST(shape.IsValid(), (shape)); } } UNIT_TEST(Transit_ShapeIdRelational) { vector<ShapeId> const ids = {{0, 10}, {0, 11}, {1, 10}, {1, 11}}; TEST(is_sorted(ids.cbegin(), ids.cend()), ()); } UNIT_TEST(Transit_NetworkSerialization) { Network network(0 /* network id */, "Title" /* title */); TestSerialization(network); TEST(network.IsValid(), (network)); } } // namespace <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <fstream> #include <string> #include "Getopt.hpp" #include "snarkfront.hpp" using namespace snarkfront; using namespace snarklib; using namespace std; void printUsage(const char* exeName) { const string PAIR = " -p BN128|Edwards", VKEY = " -v key_file", IN = " -i proof_input_file", A = " -a file", B = " -b file", C = " -c file", H = " -h file", K = " -k file"; cout << "usage: " << exeName << PAIR << VKEY << IN << A << B << C << H << K << endl; exit(EXIT_FAILURE); } template <typename T> bool marshal_in(T& a, const string& filename) { ifstream ifs(filename); return !!ifs && a.marshal_in(ifs); } template <typename PAIRING> bool verifyProof(const string& keyfile, const string& pinfile, const string& afile, const string& bfile, const string& cfile, const string& hfile, const string& kfile) { PPZK_VerificationKey<PAIRING> vk; R1Witness<typename PAIRING::Fr> input; typename PPZK_WitnessA<PAIRING>::Val pA; typename PPZK_WitnessB<PAIRING>::Val pB; typename PPZK_WitnessC<PAIRING>::Val pC; typename PAIRING::G1 pH, pK; return marshal_in(vk, keyfile) && marshal_in(input, pinfile) && marshal_in(pA, afile) && marshal_in(pB, bfile) && marshal_in(pC, cfile) && marshal_in(pH, hfile) && marshal_in(pK, kfile) && strongVerify(vk, input, PPZK_Proof<PAIRING>(pA, pB, pC, pH, pK)); } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "pviabchk", "", ""); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'), keyfile = cmdLine.getString('v'), pinfile = cmdLine.getString('i'), afile = cmdLine.getString('a'), bfile = cmdLine.getString('b'), cfile = cmdLine.getString('c'), hfile = cmdLine.getString('h'), kfile = cmdLine.getString('k'); if (!validPairingName(pairing)) { cerr << "error: elliptic curve pairing " << pairing << endl; exit(EXIT_FAILURE); } bool ok = false; if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); ok = verifyProof<BN128_PAIRING>(keyfile, pinfile, afile, bfile, cfile, hfile, kfile); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); ok = verifyProof<EDWARDS_PAIRING>(keyfile, pinfile, afile, bfile, cfile, hfile, kfile); } cout << ok << endl; exit(EXIT_SUCCESS); } <commit_msg>raw binary format<commit_after>#include <cstdlib> #include <iostream> #include <fstream> #include <string> #include "Getopt.hpp" #include "snarkfront.hpp" using namespace snarkfront; using namespace snarklib; using namespace std; void printUsage(const char* exeName) { const string PAIR = " -p BN128|Edwards", VKEY = " -v key_file", IN = " -i proof_input_file", A = " -a file", B = " -b file", C = " -c file", H = " -h file", K = " -k file"; cout << "usage: " << exeName << PAIR << VKEY << IN << A << B << C << H << K << endl; exit(EXIT_FAILURE); } template <typename T> bool marshal_in(T& a, const string& filename) { ifstream ifs(filename); return !!ifs && a.marshal_in(ifs); } template <typename T> bool marshal_in_raw(T& a, const string& filename) { ifstream ifs(filename); return !!ifs && a.marshal_in_raw(ifs); } template <typename PAIRING> bool verifyProof(const string& keyfile, const string& pinfile, const string& afile, const string& bfile, const string& cfile, const string& hfile, const string& kfile) { PPZK_VerificationKey<PAIRING> vk; R1Witness<typename PAIRING::Fr> input; typename PPZK_WitnessA<PAIRING>::Val pA; typename PPZK_WitnessB<PAIRING>::Val pB; typename PPZK_WitnessC<PAIRING>::Val pC; typename PAIRING::G1 pH, pK; return marshal_in_raw(vk, keyfile) && marshal_in(input, pinfile) && marshal_in_raw(pA, afile) && marshal_in_raw(pB, bfile) && marshal_in_raw(pC, cfile) && marshal_in_raw(pH, hfile) && marshal_in_raw(pK, kfile) && strongVerify(vk, input, PPZK_Proof<PAIRING>(pA, pB, pC, pH, pK)); } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "pviabchk", "", ""); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto pairing = cmdLine.getString('p'), keyfile = cmdLine.getString('v'), pinfile = cmdLine.getString('i'), afile = cmdLine.getString('a'), bfile = cmdLine.getString('b'), cfile = cmdLine.getString('c'), hfile = cmdLine.getString('h'), kfile = cmdLine.getString('k'); if (!validPairingName(pairing)) { cerr << "error: elliptic curve pairing " << pairing << endl; exit(EXIT_FAILURE); } bool ok = false; if (pairingBN128(pairing)) { // Barreto-Naehrig 128 bits init_BN128(); ok = verifyProof<BN128_PAIRING>(keyfile, pinfile, afile, bfile, cfile, hfile, kfile); } else if (pairingEdwards(pairing)) { // Edwards 80 bits init_Edwards(); ok = verifyProof<EDWARDS_PAIRING>(keyfile, pinfile, afile, bfile, cfile, hfile, kfile); } cout << ok << endl; exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include <fstream> #include <sstream> #include <cstdio> #include <cstdlib> #include <map> #include <string> #include <time.h> #include <sys/stat.h> #include <sys/time.h> #include "stdarg.h" #include <signal.h> #include <errno.h> #include "simple_config.h" #include "simple_log.h" // log context const int MAX_SINGLE_LOG_SIZE = 2048; const int ONE_DAY_SECONDS = 86400; int log_level = DEBUG_LEVEL; std::string g_dir; std::string g_config_file; bool use_file_appender = false; FileAppender g_file_appender; FileAppender::FileAppender() { _is_inited = false; _retain_day = -1; } FileAppender::~FileAppender() { if (_fs.is_open()) { _fs.close(); } } int FileAppender::init(std::string dir, std::string log_file) { if (!dir.empty()) { int ret = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (ret != 0 && errno != EEXIST) { printf("mkdir error which dir:%s err:%s\n", dir.c_str(), strerror(errno)); _is_inited = true; return -1; } } else { dir = "."; // current dir } _log_dir = dir; _log_file = log_file; _log_file_path = dir + "/" + log_file; _fs.open(_log_file_path.c_str(), std::fstream::out | std::fstream::app); _is_inited = true; return 0; } int FileAppender::write_log(char *log, const char *format, va_list ap) { if (_fs.is_open()) { vsnprintf(log, MAX_SINGLE_LOG_SIZE - 1, format, ap); _fs << log << "\n"; _fs.flush(); } return 0; } int FileAppender::shift_file_if_need(struct timeval tv, struct timezone tz) { if (_last_sec == 0) { _last_sec = tv.tv_sec; return 0; } long fix_now_sec = tv.tv_sec - tz.tz_minuteswest * 60; long fix_last_sec = _last_sec - tz.tz_minuteswest * 60; if (fix_now_sec / ONE_DAY_SECONDS - fix_last_sec / ONE_DAY_SECONDS) { _fs.close(); struct tm *tm; tm = localtime(&tv.tv_sec); char new_file[100]; bzero(new_file, 100); sprintf(new_file, "%s.%04d-%02d-%02d", _log_file.c_str(), tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday - 1/*last day*/); std::string new_file_path = _log_dir + "/" + new_file; rename(_log_file_path.c_str(), new_file_path.c_str()); _fs.open(_log_file_path.c_str(), std::fstream::out | std::fstream::app); delete_old_log(tv); } _last_sec = tv.tv_sec; return 0; } bool FileAppender::is_inited() { return _is_inited; } void FileAppender::set_retain_day(int rd) { _retain_day = rd; } int FileAppender::delete_old_log(timeval tv) { if (_retain_day <= 0) { return 0; } struct timeval old_tv; old_tv.tv_sec = tv.tv_sec - _retain_day * 3600 * 24; old_tv.tv_usec = tv.tv_usec; char old_file[100]; memset(old_file, 0, 100); struct tm *tm; tm = localtime(&old_tv.tv_sec); sprintf(old_file, "%s.%04d-%02d-%02d", _log_file.c_str(), tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday - 1); std::string old_file_path = _log_dir + "/" + old_file; return remove(old_file_path.c_str()); } int _check_config_file() { std::map<std::string, std::string> configs; std::string log_config_file = g_dir + "/" + g_config_file; get_config_map(log_config_file.c_str(), configs); if (configs.empty()) { return 0; } // read log level std::string log_level_str = configs["log_level"]; set_log_level(log_level_str.c_str()); std::string rd = configs["retain_day"]; if (!rd.empty()) { g_file_appender.set_retain_day(atoi(rd.c_str())); } // read log file std::string dir = configs["log_dir"]; std::string log_file = configs["log_file"]; int ret = 0; if (!log_file.empty()) { use_file_appender = true; if (!g_file_appender.is_inited()) { ret = g_file_appender.init(dir, log_file); } } return ret; } void sigreload(int sig) { //printf("receive sig:%d \n", sig); _check_config_file(); } std::string _get_show_time(timeval tv) { char show_time[40]; memset(show_time, 0, 40); struct tm *tm; tm = localtime(&tv.tv_sec); sprintf(show_time, "%04d-%02d-%02d %02d:%02d:%02d.%03d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec/1000)); return std::string(show_time); } int _get_log_level(const char *level_str) { if(strcasecmp(level_str, "ERROR") == 0) { return ERROR_LEVEL; } if(strcasecmp(level_str, "WARN") == 0) { return WARN_LEVEL; } if(strcasecmp(level_str, "INFO") == 0) { return INFO_LEVEL; } if(strcasecmp(level_str, "DEBUG") == 0) { return DEBUG_LEVEL; } return DEBUG_LEVEL; } void set_log_level(const char *level) { log_level = _get_log_level(level); } void _log(const char *format, va_list ap) { if (!use_file_appender) { // if no config, send log to stdout vprintf(format, ap); printf("\n"); return; } struct timeval now; struct timezone tz; gettimeofday(&now, &tz); std::string fin_format = _get_show_time(now) + " " + format; g_file_appender.shift_file_if_need(now, tz); char single_log[MAX_SINGLE_LOG_SIZE]; bzero(single_log, MAX_SINGLE_LOG_SIZE); g_file_appender.write_log(single_log, fin_format.c_str(), ap); } int log_init(std::string dir, std::string file) { g_dir = dir; g_config_file = file; signal(SIGUSR1, sigreload); return _check_config_file(); } void log_error(const char *format, ...) { if (log_level < ERROR_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } void log_warn(const char *format, ...) { if (log_level < WARN_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } void log_info(const char *format, ...) { if (log_level < INFO_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } void log_debug(const char *format, ...) { if (log_level < DEBUG_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } <commit_msg>fix shift file bug<commit_after>#include <fstream> #include <sstream> #include <cstdio> #include <cstdlib> #include <map> #include <string> #include <time.h> #include <sys/stat.h> #include <sys/time.h> #include "stdarg.h" #include <signal.h> #include <errno.h> #include "simple_config.h" #include "simple_log.h" // log context const int MAX_SINGLE_LOG_SIZE = 2048; const int ONE_DAY_SECONDS = 86400; int log_level = DEBUG_LEVEL; std::string g_dir; std::string g_config_file; bool use_file_appender = false; FileAppender g_file_appender; FileAppender::FileAppender() { _is_inited = false; _retain_day = -1; } FileAppender::~FileAppender() { if (_fs.is_open()) { _fs.close(); } } int FileAppender::init(std::string dir, std::string log_file) { if (!dir.empty()) { int ret = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); if (ret != 0 && errno != EEXIST) { printf("mkdir error which dir:%s err:%s\n", dir.c_str(), strerror(errno)); _is_inited = true; return -1; } } else { dir = "."; // current dir } _log_dir = dir; _log_file = log_file; _log_file_path = dir + "/" + log_file; _fs.open(_log_file_path.c_str(), std::fstream::out | std::fstream::app); _is_inited = true; return 0; } int FileAppender::write_log(char *log, const char *format, va_list ap) { if (_fs.is_open()) { vsnprintf(log, MAX_SINGLE_LOG_SIZE - 1, format, ap); _fs << log << "\n"; _fs.flush(); } return 0; } int FileAppender::shift_file_if_need(struct timeval tv, struct timezone tz) { if (_last_sec == 0) { _last_sec = tv.tv_sec; return 0; } long fix_now_sec = tv.tv_sec - tz.tz_minuteswest * 60; long fix_last_sec = _last_sec - tz.tz_minuteswest * 60; if (fix_now_sec / ONE_DAY_SECONDS - fix_last_sec / ONE_DAY_SECONDS) { struct tm *tm; time_t y_sec = tv.tv_sec - ONE_DAY_SECONDS; tm = localtime(&y_sec); //yesterday char new_file[100]; bzero(new_file, 100); sprintf(new_file, "%s.%04d-%02d-%02d", _log_file.c_str(), tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday); std::string new_file_path = _log_dir + "/" + new_file; rename(_log_file_path.c_str(), new_file_path.c_str()); _fs.close(); _fs.open(_log_file_path.c_str(), std::fstream::out | std::fstream::app); delete_old_log(tv); } _last_sec = tv.tv_sec; return 0; } bool FileAppender::is_inited() { return _is_inited; } void FileAppender::set_retain_day(int rd) { _retain_day = rd; } int FileAppender::delete_old_log(timeval tv) { if (_retain_day <= 0) { return 0; } struct timeval old_tv; old_tv.tv_sec = tv.tv_sec - _retain_day * 3600 * 24; old_tv.tv_usec = tv.tv_usec; char old_file[100]; memset(old_file, 0, 100); struct tm *tm; tm = localtime(&old_tv.tv_sec); sprintf(old_file, "%s.%04d-%02d-%02d", _log_file.c_str(), tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday - 1); std::string old_file_path = _log_dir + "/" + old_file; return remove(old_file_path.c_str()); } int _check_config_file() { std::map<std::string, std::string> configs; std::string log_config_file = g_dir + "/" + g_config_file; get_config_map(log_config_file.c_str(), configs); if (configs.empty()) { return 0; } // read log level std::string log_level_str = configs["log_level"]; set_log_level(log_level_str.c_str()); std::string rd = configs["retain_day"]; if (!rd.empty()) { g_file_appender.set_retain_day(atoi(rd.c_str())); } // read log file std::string dir = configs["log_dir"]; std::string log_file = configs["log_file"]; int ret = 0; if (!log_file.empty()) { use_file_appender = true; if (!g_file_appender.is_inited()) { ret = g_file_appender.init(dir, log_file); } } return ret; } void sigreload(int sig) { //printf("receive sig:%d \n", sig); _check_config_file(); } std::string _get_show_time(timeval tv) { char show_time[40]; memset(show_time, 0, 40); struct tm *tm; tm = localtime(&tv.tv_sec); sprintf(show_time, "%04d-%02d-%02d %02d:%02d:%02d.%03d", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, (int)(tv.tv_usec/1000)); return std::string(show_time); } int _get_log_level(const char *level_str) { if(strcasecmp(level_str, "ERROR") == 0) { return ERROR_LEVEL; } if(strcasecmp(level_str, "WARN") == 0) { return WARN_LEVEL; } if(strcasecmp(level_str, "INFO") == 0) { return INFO_LEVEL; } if(strcasecmp(level_str, "DEBUG") == 0) { return DEBUG_LEVEL; } return DEBUG_LEVEL; } void set_log_level(const char *level) { log_level = _get_log_level(level); } void _log(const char *format, va_list ap) { if (!use_file_appender) { // if no config, send log to stdout vprintf(format, ap); printf("\n"); return; } struct timeval now; struct timezone tz; gettimeofday(&now, &tz); std::string fin_format = _get_show_time(now) + " " + format; g_file_appender.shift_file_if_need(now, tz); char single_log[MAX_SINGLE_LOG_SIZE]; bzero(single_log, MAX_SINGLE_LOG_SIZE); g_file_appender.write_log(single_log, fin_format.c_str(), ap); } int log_init(std::string dir, std::string file) { g_dir = dir; g_config_file = file; signal(SIGUSR1, sigreload); return _check_config_file(); } void log_error(const char *format, ...) { if (log_level < ERROR_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } void log_warn(const char *format, ...) { if (log_level < WARN_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } void log_info(const char *format, ...) { if (log_level < INFO_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } void log_debug(const char *format, ...) { if (log_level < DEBUG_LEVEL) { return; } va_list ap; va_start(ap, format); _log(format, ap); va_end(ap); } <|endoftext|>
<commit_before>#ifndef NOTCH_IO_H #define NOTCH_IO_H /// notch_io.hpp -- optional input-output helpers for Notch library /** The MIT License (MIT) Copyright (c) 2015 Sergey Astanin 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 <algorithm> // find_if #include <fstream> // ifstream #include <istream> #include <map> #include <ostream> #include <sstream> // ostringstream #include <stdexcept> // out_of_range #include "notch.hpp" /** * Vectors Input-Output * -------------------- **/ /** Input and Output values are space-separated values.*/ std::istream &operator>>(std::istream &in, Input &xs) { for (size_t i = 0; i < xs.size(); ++i) { in >> xs[i]; } return in; } std::ostream &operator<<(std::ostream &out, const Input &xs) { for (auto it = std::begin(xs); it != std::end(xs); ++it) { if (it != std::begin(xs)) { out << " "; } out << *it; } return out; } /** * Dataset Input-output * -------------------- **/ /** Load labeled datasets from FANN text file format. * * N_samples N_in N_out * X[0,0] X[0,1] ... X[0,N_in - 1] * Y[0,0] Y[0,1] ... Y[0,N_out - 1] * X[1,0] X[1,1] ... X[1,N_in - 1] * Y[1,0] Y[1,1] ... Y[1,N_out - 1] * ... * X[N_samples - 1,0] X[N_samples - 1,1] ... X[N_samples - 1,N_in - 1] * Y[N_samples - 1,0] Y[N_samples - 1,1] ... Y[N_samples - 1,N_out - 1] **/ class FANNReader { public: static LabeledDataset read(const std::string &path) { std::ifstream in(path); if (!in.is_open()) { throw std::runtime_error("cannot open " + path); } return FANNReader::read(in); } static LabeledDataset read(std::istream &in) { LabeledDataset ds; size_t nSamples, inputDimension, outputDimension; in >> nSamples >> inputDimension >> outputDimension; for (size_t i = 0; i < nSamples; ++i) { Input input(inputDimension); Output output(outputDimension); in >> input >> output; ds.append(input, output); } return ds; } }; /** Load labeled datasets from CSV files. * * Numeric columns are converted to `float` numbers. * * Values of non-numeric columns are converted to numbers in range [0;N-1], * where N is the number of unique values in the column. * * By default the last column is used as a label (`labelcols={-1}`). **/ template<char delimiter=','> class CSVReader { private: enum class CellTag { Number, String }; struct Cell { CellTag tag; float value; std::string str; }; using TextTable = std::vector<std::vector<std::string>>; using MixedTable = std::vector<std::vector<Cell>>; using MixedRow = std::vector<Cell>; using NumericTable = std::vector<std::vector<float>>; using NumericRow = std::vector<float>; enum class CSVReaderState { UnquotedField, QuotedField, QuotedQuote }; /// Parse a row of an Excel CSV file. static std::vector<std::string> readCSVRow(const std::string &row) { CSVReaderState state = CSVReaderState::UnquotedField; std::vector<std::string> fields {""}; size_t i = 0; // index of the current field for (char c : row) { switch (state) { case CSVReaderState::UnquotedField: switch (c) { case delimiter: // end of field fields.push_back(""); i++; break; case '"': state = CSVReaderState::QuotedField; break; default: fields[i].push_back(c); break; } break; case CSVReaderState::QuotedField: switch (c) { case '"': state = CSVReaderState::QuotedQuote; break; default: fields[i].push_back(c); break; } break; case CSVReaderState::QuotedQuote: switch (c) { case delimiter: // , after closing quote fields.push_back(""); i++; state = CSVReaderState::UnquotedField; break; case '"': // "" -> " fields[i].push_back('"'); state = CSVReaderState::QuotedField; break; default: // end of quote state = CSVReaderState::UnquotedField; break; } break; } } return fields; } /// Read Excel CSV file. Skip empty rows. static TextTable readCSV(std::istream &in, int skiprows=0, int skipcols=0) { TextTable table; std::string row; while (true) { std::getline(in, row); if (in.bad() || in.eof()) { break; } if (skiprows > 0) { --skiprows; continue; } if (row.size() == 0) { continue; } auto fields = readCSVRow(row); if (skipcols > 0) { auto field0 = std::begin(fields); auto fieldToKeep = field0 + skipcols; fields.erase(field0, fieldToKeep); } table.push_back(fields); } return table; } static Cell parseCell(const std::string &s) { // float value = std::stof(s); // doesn't work on MinGW-32; BUG #52015 const char *parseBegin = s.c_str(); char *parseEnd = nullptr; float value = strtof(parseBegin, &parseEnd); if (parseEnd == parseBegin || parseEnd == nullptr) { return Cell { CellTag::String, 0.0, s }; } else { return Cell { CellTag::Number, value, "" }; } } static MixedTable convertToMixed(const TextTable &table) { MixedTable cellTable(0); for (auto row : table) { MixedRow cellRow(0); for (auto s : row) { cellRow.push_back(parseCell(s)); } cellTable.push_back(cellRow); } return cellTable; } static bool isColumnNumeric(const MixedTable &t, size_t column_idx) throw (std::out_of_range) { return std::all_of(std::begin(t), std::end(t), [column_idx](const MixedRow &r) { return r.at(column_idx).tag == CellTag::Number; }); } /// static NumericTable convertToNumeric(const MixedTable &t) throw (std::out_of_range) { // analyze table size_t ncols = t.at(0).size(); std::vector<bool> isNumeric(ncols); for (size_t i = 0; i < ncols; ++i) { isNumeric[i] = isColumnNumeric(t, i); } // convert table std::vector<std::map<std::string, int>> columnKeys(ncols); NumericTable nt; for (auto row : t) { NumericRow nr; for (size_t i = 0; i < ncols; ++i) { if (isNumeric[i]) { nr.push_back(row[i].value); } else { // a non-numeric label auto label = row[i].str; if (columnKeys[i].count(label)) { // a previosly seen label int labelIndex = columnKeys[i][label]; nr.push_back(labelIndex); } else { // new label int labelIndex = columnKeys[i].size(); columnKeys[i][label] = labelIndex; nr.push_back(labelIndex); } } } nt.push_back(nr); } return nt; } public: /** Read a `LabeledDataset` from a CSV file. * * @param path CSV file name * @param labelcols indices of the columns to be used as labels; * indices can be negative (-1 is the last column) * @param skiprows discard the first @skiprows lines * @param skipcols discard the first @skipcols lines **/ static LabeledDataset read(const std::string &path, std::vector<int> labelcols = {-1}, int skiprows=0, int skipcols=0) { std::ifstream in(path); return CSVReader::read(in, skiprows, skipcols); } /** Read a `LabeledDataset` from an `std::istream`. * * @param in stream to read CSV data from * @param labelcols indices of the columns to be used as labels; * indices can be negative (-1 is the last column) * @param skiprows discard the first @skiprows lines * @param skipcols discard the first @skipcols lines **/ static LabeledDataset read(std::istream &in, std::vector<int> labelcols = {-1}, int skiprows=0, int skipcols=0) { LabeledDataset ds; auto rows = readCSV(in, skiprows, skipcols); auto mixedRows = convertToMixed(rows); auto numericRows = convertToNumeric(mixedRows); for (auto row : numericRows) { // build label vector Output label(labelcols.size()); size_t ncols = row.size(); for (size_t i = 0; i < labelcols.size(); ++i) { size_t colIdx = ((ncols + labelcols[i]) % ncols); label[i] = row[colIdx]; } // remove label columns from the row (from the end) for (int i = row.size()-1; i >= 0; --i) { auto found = std::find_if(labelcols.begin(), labelcols.end(), [=](int labelcol) { return (labelcol + ncols) % ncols == i; }); if (found != labelcols.end()) { row.erase(row.begin() + i); } } // build data vector Input data(row.size()); for (size_t i = 0; i < row.size(); ++i) { data[i] = row[i]; } ds.append(data, label); } return ds; } }; // TODO: IDX (MNIST) format reader /** A formatter to write a labeled dataset to FANN text file format. */ class FANNFormat { private: const LabeledDataset &dataset; public: FANNFormat(const LabeledDataset &dataset) : dataset(dataset) {} friend std::ostream &operator<<(std::ostream &out, const FANNFormat &w); }; std::ostream &operator<<(std::ostream &out, const FANNFormat &w) { out << w.dataset.size() << " " << w.dataset.inputDim() << " " << w.dataset.outputDim() << "\n"; for (auto sample : w.dataset) { out << sample.data << "\n" << sample.label << "\n"; } return out; } /** A formatter to write datasets as one mapping per line. */ class ArrowFormat { private: const LabeledDataset &dataset; public: ArrowFormat(const LabeledDataset &dataset) : dataset(dataset) {} friend std::ostream &operator<<(std::ostream &out, const ArrowFormat &w); }; std::ostream &operator<<(std::ostream &out, const ArrowFormat &w) { for (auto sample : w.dataset) { out << sample.data << " -> " << sample.label << "\n"; } return out; } /** A formatter to write a labeled dataset to CSV file. */ class CSVFormat { private: const LabeledDataset &dataset; public: CSVFormat(const LabeledDataset &dataset) : dataset(dataset) {} friend std::ostream &operator<<(std::ostream &out, const CSVFormat &w); }; std::ostream &operator<<(std::ostream &out, const CSVFormat &writer) { auto inDim = writer.dataset.inputDim(); auto outDim = writer.dataset.outputDim(); auto w = 11; auto p = 5; // header row for (auto i = 1u; i <= inDim; ++i) { std::ostringstream ss; ss << "feature_" << i; out << std::setw(w) << ss.str() << ","; } for (auto i = 1u; i <= outDim; ++i) { std::ostringstream ss; ss << "label_" << i; out << std::setw(w) << ss.str(); if (i < outDim) { out << ","; } } out << "\n"; // data rows for (auto sample : writer.dataset) { for (auto v : sample.data) { out << std::setw(w) << std::setprecision(p) << v << ","; } for (auto i = 0u; i < outDim; ++i) { out << std::setw(w) << std::setprecision(p) << sample.label[i]; if (i + 1 < outDim) { out << ","; } } out << "\n"; } return out; } /** * Neural Networks Input-Output * ---------------------------- **/ std::ostream &operator<<(std::ostream &out, const ActivationFunction &af) { af.print(out); return out; } std::ostream &operator<<(std::ostream &out, const ANeuron &neuron) { auto ws = neuron.getWeights(); for (auto it = std::begin(ws); it != std::end(ws); ++it) { if (std::next(it) != std::end(ws)) { out << *it << " "; } else { out << *it; } } return out; } std::ostream &operator<<(std::ostream &out, const FullyConnectedLayer &layer) { out << " inputs: " << layer.nInputs << "\n"; out << " outputs: " << layer.nOutputs << "\n"; out << " activation: " << layer.activationFunction << "\n"; out << " weights_and_bias:\n"; for (size_t r = 0; r < layer.nOutputs; ++r) { out << " "; for (size_t c = 0; c < layer.nInputs; ++c) { out << " " << layer.weights[r*layer.nInputs + c]; } out << "\n"; } return out; } std::ostream &operator<<(std::ostream &out, const MultilayerPerceptron &net) { int layerN = 1; for (FullyConnectedLayer l : net.layers) { out << "LAYER " << layerN << ":\n"; out << l; layerN++; } return out; } #endif <commit_msg>fix printing FullyConnectedLayer: print bias too<commit_after>#ifndef NOTCH_IO_H #define NOTCH_IO_H /// notch_io.hpp -- optional input-output helpers for Notch library /** The MIT License (MIT) Copyright (c) 2015 Sergey Astanin 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 <algorithm> // find_if #include <fstream> // ifstream #include <istream> #include <map> #include <ostream> #include <sstream> // ostringstream #include <stdexcept> // out_of_range #include "notch.hpp" /** * Vectors Input-Output * -------------------- **/ /** Input and Output values are space-separated values.*/ std::istream &operator>>(std::istream &in, Input &xs) { for (size_t i = 0; i < xs.size(); ++i) { in >> xs[i]; } return in; } std::ostream &operator<<(std::ostream &out, const Input &xs) { for (auto it = std::begin(xs); it != std::end(xs); ++it) { if (it != std::begin(xs)) { out << " "; } out << *it; } return out; } /** * Dataset Input-output * -------------------- **/ /** Load labeled datasets from FANN text file format. * * N_samples N_in N_out * X[0,0] X[0,1] ... X[0,N_in - 1] * Y[0,0] Y[0,1] ... Y[0,N_out - 1] * X[1,0] X[1,1] ... X[1,N_in - 1] * Y[1,0] Y[1,1] ... Y[1,N_out - 1] * ... * X[N_samples - 1,0] X[N_samples - 1,1] ... X[N_samples - 1,N_in - 1] * Y[N_samples - 1,0] Y[N_samples - 1,1] ... Y[N_samples - 1,N_out - 1] **/ class FANNReader { public: static LabeledDataset read(const std::string &path) { std::ifstream in(path); if (!in.is_open()) { throw std::runtime_error("cannot open " + path); } return FANNReader::read(in); } static LabeledDataset read(std::istream &in) { LabeledDataset ds; size_t nSamples, inputDimension, outputDimension; in >> nSamples >> inputDimension >> outputDimension; for (size_t i = 0; i < nSamples; ++i) { Input input(inputDimension); Output output(outputDimension); in >> input >> output; ds.append(input, output); } return ds; } }; /** Load labeled datasets from CSV files. * * Numeric columns are converted to `float` numbers. * * Values of non-numeric columns are converted to numbers in range [0;N-1], * where N is the number of unique values in the column. * * By default the last column is used as a label (`labelcols={-1}`). **/ template<char delimiter=','> class CSVReader { private: enum class CellTag { Number, String }; struct Cell { CellTag tag; float value; std::string str; }; using TextTable = std::vector<std::vector<std::string>>; using MixedTable = std::vector<std::vector<Cell>>; using MixedRow = std::vector<Cell>; using NumericTable = std::vector<std::vector<float>>; using NumericRow = std::vector<float>; enum class CSVReaderState { UnquotedField, QuotedField, QuotedQuote }; /// Parse a row of an Excel CSV file. static std::vector<std::string> readCSVRow(const std::string &row) { CSVReaderState state = CSVReaderState::UnquotedField; std::vector<std::string> fields {""}; size_t i = 0; // index of the current field for (char c : row) { switch (state) { case CSVReaderState::UnquotedField: switch (c) { case delimiter: // end of field fields.push_back(""); i++; break; case '"': state = CSVReaderState::QuotedField; break; default: fields[i].push_back(c); break; } break; case CSVReaderState::QuotedField: switch (c) { case '"': state = CSVReaderState::QuotedQuote; break; default: fields[i].push_back(c); break; } break; case CSVReaderState::QuotedQuote: switch (c) { case delimiter: // , after closing quote fields.push_back(""); i++; state = CSVReaderState::UnquotedField; break; case '"': // "" -> " fields[i].push_back('"'); state = CSVReaderState::QuotedField; break; default: // end of quote state = CSVReaderState::UnquotedField; break; } break; } } return fields; } /// Read Excel CSV file. Skip empty rows. static TextTable readCSV(std::istream &in, int skiprows=0, int skipcols=0) { TextTable table; std::string row; while (true) { std::getline(in, row); if (in.bad() || in.eof()) { break; } if (skiprows > 0) { --skiprows; continue; } if (row.size() == 0) { continue; } auto fields = readCSVRow(row); if (skipcols > 0) { auto field0 = std::begin(fields); auto fieldToKeep = field0 + skipcols; fields.erase(field0, fieldToKeep); } table.push_back(fields); } return table; } static Cell parseCell(const std::string &s) { // float value = std::stof(s); // doesn't work on MinGW-32; BUG #52015 const char *parseBegin = s.c_str(); char *parseEnd = nullptr; float value = strtof(parseBegin, &parseEnd); if (parseEnd == parseBegin || parseEnd == nullptr) { return Cell { CellTag::String, 0.0, s }; } else { return Cell { CellTag::Number, value, "" }; } } static MixedTable convertToMixed(const TextTable &table) { MixedTable cellTable(0); for (auto row : table) { MixedRow cellRow(0); for (auto s : row) { cellRow.push_back(parseCell(s)); } cellTable.push_back(cellRow); } return cellTable; } static bool isColumnNumeric(const MixedTable &t, size_t column_idx) throw (std::out_of_range) { return std::all_of(std::begin(t), std::end(t), [column_idx](const MixedRow &r) { return r.at(column_idx).tag == CellTag::Number; }); } /// static NumericTable convertToNumeric(const MixedTable &t) throw (std::out_of_range) { // analyze table size_t ncols = t.at(0).size(); std::vector<bool> isNumeric(ncols); for (size_t i = 0; i < ncols; ++i) { isNumeric[i] = isColumnNumeric(t, i); } // convert table std::vector<std::map<std::string, int>> columnKeys(ncols); NumericTable nt; for (auto row : t) { NumericRow nr; for (size_t i = 0; i < ncols; ++i) { if (isNumeric[i]) { nr.push_back(row[i].value); } else { // a non-numeric label auto label = row[i].str; if (columnKeys[i].count(label)) { // a previosly seen label int labelIndex = columnKeys[i][label]; nr.push_back(labelIndex); } else { // new label int labelIndex = columnKeys[i].size(); columnKeys[i][label] = labelIndex; nr.push_back(labelIndex); } } } nt.push_back(nr); } return nt; } public: /** Read a `LabeledDataset` from a CSV file. * * @param path CSV file name * @param labelcols indices of the columns to be used as labels; * indices can be negative (-1 is the last column) * @param skiprows discard the first @skiprows lines * @param skipcols discard the first @skipcols lines **/ static LabeledDataset read(const std::string &path, std::vector<int> labelcols = {-1}, int skiprows=0, int skipcols=0) { std::ifstream in(path); return CSVReader::read(in, skiprows, skipcols); } /** Read a `LabeledDataset` from an `std::istream`. * * @param in stream to read CSV data from * @param labelcols indices of the columns to be used as labels; * indices can be negative (-1 is the last column) * @param skiprows discard the first @skiprows lines * @param skipcols discard the first @skipcols lines **/ static LabeledDataset read(std::istream &in, std::vector<int> labelcols = {-1}, int skiprows=0, int skipcols=0) { LabeledDataset ds; auto rows = readCSV(in, skiprows, skipcols); auto mixedRows = convertToMixed(rows); auto numericRows = convertToNumeric(mixedRows); for (auto row : numericRows) { // build label vector Output label(labelcols.size()); size_t ncols = row.size(); for (size_t i = 0; i < labelcols.size(); ++i) { size_t colIdx = ((ncols + labelcols[i]) % ncols); label[i] = row[colIdx]; } // remove label columns from the row (from the end) for (int i = row.size()-1; i >= 0; --i) { auto found = std::find_if(labelcols.begin(), labelcols.end(), [=](int labelcol) { return (labelcol + ncols) % ncols == i; }); if (found != labelcols.end()) { row.erase(row.begin() + i); } } // build data vector Input data(row.size()); for (size_t i = 0; i < row.size(); ++i) { data[i] = row[i]; } ds.append(data, label); } return ds; } }; // TODO: IDX (MNIST) format reader /** A formatter to write a labeled dataset to FANN text file format. */ class FANNFormat { private: const LabeledDataset &dataset; public: FANNFormat(const LabeledDataset &dataset) : dataset(dataset) {} friend std::ostream &operator<<(std::ostream &out, const FANNFormat &w); }; std::ostream &operator<<(std::ostream &out, const FANNFormat &w) { out << w.dataset.size() << " " << w.dataset.inputDim() << " " << w.dataset.outputDim() << "\n"; for (auto sample : w.dataset) { out << sample.data << "\n" << sample.label << "\n"; } return out; } /** A formatter to write datasets as one mapping per line. */ class ArrowFormat { private: const LabeledDataset &dataset; public: ArrowFormat(const LabeledDataset &dataset) : dataset(dataset) {} friend std::ostream &operator<<(std::ostream &out, const ArrowFormat &w); }; std::ostream &operator<<(std::ostream &out, const ArrowFormat &w) { for (auto sample : w.dataset) { out << sample.data << " -> " << sample.label << "\n"; } return out; } /** A formatter to write a labeled dataset to CSV file. */ class CSVFormat { private: const LabeledDataset &dataset; public: CSVFormat(const LabeledDataset &dataset) : dataset(dataset) {} friend std::ostream &operator<<(std::ostream &out, const CSVFormat &w); }; std::ostream &operator<<(std::ostream &out, const CSVFormat &writer) { auto inDim = writer.dataset.inputDim(); auto outDim = writer.dataset.outputDim(); auto w = 11; auto p = 5; // header row for (auto i = 1u; i <= inDim; ++i) { std::ostringstream ss; ss << "feature_" << i; out << std::setw(w) << ss.str() << ","; } for (auto i = 1u; i <= outDim; ++i) { std::ostringstream ss; ss << "label_" << i; out << std::setw(w) << ss.str(); if (i < outDim) { out << ","; } } out << "\n"; // data rows for (auto sample : writer.dataset) { for (auto v : sample.data) { out << std::setw(w) << std::setprecision(p) << v << ","; } for (auto i = 0u; i < outDim; ++i) { out << std::setw(w) << std::setprecision(p) << sample.label[i]; if (i + 1 < outDim) { out << ","; } } out << "\n"; } return out; } /** * Neural Networks Input-Output * ---------------------------- **/ std::ostream &operator<<(std::ostream &out, const ActivationFunction &af) { af.print(out); return out; } std::ostream &operator<<(std::ostream &out, const ANeuron &neuron) { auto ws = neuron.getWeights(); for (auto it = std::begin(ws); it != std::end(ws); ++it) { if (std::next(it) != std::end(ws)) { out << *it << " "; } else { out << *it; } } return out; } std::ostream &operator<<(std::ostream &out, const FullyConnectedLayer &layer) { out << " inputs: " << layer.nInputs << "\n"; out << " outputs: " << layer.nOutputs << "\n"; out << " activation: " << layer.activationFunction << "\n"; out << " bias_and_weights:\n"; for (size_t r = 0; r < layer.nOutputs; ++r) { out << " "; out << " " << layer.bias[r]; for (size_t c = 0; c < layer.nInputs; ++c) { out << " " << layer.weights[r*layer.nInputs + c]; } out << "\n"; } return out; } std::ostream &operator<<(std::ostream &out, const MultilayerPerceptron &net) { int layerN = 1; for (FullyConnectedLayer l : net.layers) { out << "LAYER " << layerN << ":\n"; out << l; layerN++; } return out; } #endif <|endoftext|>
<commit_before>#pragma once #include "opencv2/opencv.hpp" #include "boost/date_time/posix_time/posix_time.hpp" namespace pt = boost::posix_time; /** * Information related to RGB-D pair images */ struct Image { const pt::ptime time; // Time taken const cv::Mat rgb; // 3-channel cv::Mat containing RGB data const cv::Mat dep; // 1-channel cv::Mat containing depth data const std::string rgb_path; // Path to rgb file const std::string dep_path; // Path to depth file }; /** * List of Image structs */ typedef std::vector<Image> Images; <commit_msg>"camFrame and camframes and keypoints"<commit_after>#pragma once #include "opencv2/opencv.hpp" #include "boost/date_time/posix_time/posix_time.hpp" namespace pt = boost::posix_time; /** * Information related to RGB-D pair images */ struct Image { const pt::ptime time; // Time taken const cv::Mat rgb; // 3-channel cv::Mat containing RGB data const cv::Mat dep; // 1-channel cv::Mat containing depth data const std::string rgb_path; // Path to rgb file const std::string dep_path; // Path to depth file }; /** * List of Image structs */ typedef std::vector<Image> Images; /** * List of key points */ typedef std::vector<cv::KeyPoint> KeyPoints; /** * Necessary information for each camera frame */ struct CamFrame { const KeyPoints key_points; // list of feature points found in this image // TODO add field for pose when pose_estimation R and t }; typedef std::vector<CamFrame> CamFrames; <|endoftext|>
<commit_before>#ifndef AST_HPP_INCLUDED #define AST_HPP_INCLUDED #include "../misc.hpp" #include "../runtime/runtime_info.hpp" #include <iostream> #include <memory> #include <string> #include <vector> namespace shiranui{ namespace syntax{ namespace ast{ struct VisitorForAST; } } } namespace shiranui{ namespace syntax{ namespace ast{ namespace DSL{ struct VisitorForDSL; } } } } namespace shiranui{ namespace syntax{ namespace ast{ struct LocationInfo{ int point,length; }; struct MainNode : LocationInfo{ runtime::infomation::RuntimeInfomation runtime_info; virtual void accept(VisitorForAST&) = 0; }; struct Expression : MainNode{ virtual ~Expression() {}; }; struct Statement : MainNode{ virtual ~Statement() {}; }; // metaelement. struct Identifier : MainNode{ std::string name; // whats this? Identifier() : name("") {} explicit Identifier(std::string); explicit Identifier(std::vector<char>); bool operator<(const Identifier&) const; bool operator==(const Identifier&) const; void accept(VisitorForAST&); }; // immediate values. struct Variable : Expression{ Identifier value; explicit Variable(Identifier v); void accept(VisitorForAST&); }; struct Number : Expression{ int value; explicit Number(int v); void accept(VisitorForAST&); }; struct String : Expression{ std::string value; explicit String(std::string v); explicit String(std::vector<char> v); void accept(VisitorForAST&); }; struct Boolean: Expression{ bool value; explicit Boolean(bool); void accept(VisitorForAST&); }; struct Array : Expression{ virtual ~Array() {}; }; struct Interval : Array{ sp<Expression> start,end,next; bool right_close; Interval(sp<Expression>,sp<Expression>,sp<Expression>,bool); void accept(VisitorForAST&); }; struct Enum : Array{ std::vector<sp<Expression>> expressions; explicit Enum(std::vector<sp<Expression>>); explicit Enum(); void accept(VisitorForAST&); }; struct FlyMark; // pre is unit -> unit // post is (type of return value) -> unit struct Block : Statement{ std::vector<sp<Statement>> statements; std::vector<sp<Block>> pre; std::vector<sp<Block>> post; std::vector<sp<Block>> invariant; std::vector<sp<FlyMark>> flymarks; std::vector<Identifier> post_id; Block(); void add_statement(sp<Statement>); void add_pre(sp<Block>); void add_post(Identifier i,sp<Block>); void add_invariant(sp<Block>); void add_flymark(sp<FlyMark>); void accept(VisitorForAST&); }; struct Function : Expression{ Identifier lambda_id; std::vector<Identifier> parameters; sp<Block> body; Function(Identifier,std::vector<Identifier>,sp<Block>); Function(std::vector<Identifier>,sp<Block>); void accept(VisitorForAST&); }; // expression. struct FunctionCall : Expression{ sp<Expression> function; std::vector<sp<Expression>> arguments; FunctionCall(sp<Expression>,std::vector<sp<Expression>>); void accept(VisitorForAST&); }; struct BinaryOperator : Expression{ std::string op; sp<Expression> left,right; BinaryOperator(std::string,sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; struct UnaryOperator : Expression{ std::string op; sp<Expression> exp; UnaryOperator(std::string,sp<Expression>); void accept(VisitorForAST&); }; struct IfElseExpression : Expression{ sp<Expression> pred; sp<Expression> ife; sp<Expression> elsee; IfElseExpression(sp<Expression>,sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; // statement. struct Definement : Statement{ Identifier id; sp<Expression> value; bool is_const; Definement(Identifier,sp<Expression>,bool); void accept(VisitorForAST&); }; struct ExpressionStatement : Statement{ sp<Expression> exp; ExpressionStatement(sp<Expression>); void accept(VisitorForAST&); }; struct IfElseStatement : Statement{ sp<Expression> pred; sp<Block> ifblock; sp<Block> elseblock; IfElseStatement(sp<Expression>,sp<Block>); IfElseStatement(sp<Expression>,sp<Block>,sp<Block>); void accept(VisitorForAST&); }; struct ForStatement : Statement{ Identifier loop_var; sp<Expression> loop_exp; sp<Block> block; ForStatement(Identifier,sp<Expression>,sp<Block>); void accept(VisitorForAST&); }; struct Assignment : Statement{ Identifier id; sp<Expression> value; Assignment(Identifier,sp<Expression>); void accept(VisitorForAST&); }; struct ReturnStatement : Statement{ sp<Expression> value; ReturnStatement(sp<Expression>); void accept(VisitorForAST&); }; struct ProbeStatement : Statement{ sp<Expression> value; ProbeStatement(sp<Expression>); void accept(VisitorForAST&); }; struct AssertStatement : Statement{ sp<Expression> value; AssertStatement(sp<Expression>); void accept(VisitorForAST&); }; struct FlyLine : MainNode{ }; struct TestFlyLine : FlyLine{ sp<Expression> left,right,error; explicit TestFlyLine(sp<Expression>,sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; struct IdleFlyLine : FlyLine{ sp<Expression> left,right; explicit IdleFlyLine(sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; struct FlyMark : MainNode{ sp<Expression> left; std::vector<sp<Expression>> right; explicit FlyMark(sp<Expression>); FlyMark(sp<Expression>,std::vector<sp<Expression>>); void accept(VisitorForAST&); }; struct SourceCode : MainNode{ std::vector<sp<Statement>> statements; std::vector<sp<FlyLine>> flylines; std::map<sp<Block>,sp<Function> > where_is_function_from; // FIXME: sp<fucntion> is NOT exact.It's copy. std::map<Identifier,sp<Function> > marker_to_lambda; explicit SourceCode(std::vector<sp<Statement>>); SourceCode(); ~SourceCode(); void add_statement(sp<Statement>); void add_flyline(sp<FlyLine>); void accept(VisitorForAST&); }; namespace DSL{ struct DSLInner : LocationInfo{ virtual void accept(VisitorForDSL&) = 0; }; struct DSLVariable : DSLInner{ std::string name; DSLVariable(); explicit DSLVariable(std::string); explicit DSLVariable(std::vector<char>); bool operator<(const DSLVariable&) const; void accept(VisitorForDSL&); }; struct DSLDefine : DSLInner{ sp<DSLVariable> var; sp<DSLInner> value; DSLDefine(sp<DSLVariable>,sp<DSLInner>); void accept(VisitorForDSL&); }; struct DSLImmediate : DSLInner{ }; struct DSLInteger : DSLImmediate{ int value; explicit DSLInteger(int); void accept(VisitorForDSL&); }; struct DSLBoolean : DSLImmediate{ bool value; explicit DSLBoolean(bool); void accept(VisitorForDSL&); }; struct DSLString : DSLImmediate{ std::string value; explicit DSLString(std::string); void accept(VisitorForDSL&); }; struct DSLArray : DSLImmediate{ std::vector<sp<DSLInner> > value; explicit DSLArray(std::vector<sp<DSLInner>>); explicit DSLArray(); void accept(VisitorForDSL&); }; struct DSLRef : DSLImmediate{ sp<DSLInner> to; explicit DSLRef(sp<DSLInner>); void accept(VisitorForDSL&); }; struct DSLFunction : DSLImmediate{ typedef std::vector<std::pair<sp<ast::DSL::DSLVariable>, sp<ast::DSL::DSLInner> > > myenv; myenv environment; Identifier lambda_id; DSLFunction(myenv,sp<DSLVariable>); void accept(VisitorForDSL&); }; struct DataDSL : Expression{ sp<DSLInner> inner; explicit DataDSL(sp<DSLInner>); void accept(VisitorForAST&); }; } } } } namespace shiranui{ namespace syntax{ namespace ast{ struct VisitorForAST{ virtual ~VisitorForAST() {}; virtual void visit(Identifier&) = 0; virtual void visit(Variable&) = 0; virtual void visit(Number&) = 0; virtual void visit(String&) = 0; virtual void visit(Boolean&) = 0; virtual void visit(Enum&) = 0; virtual void visit(Interval&) = 0; virtual void visit(Block&) = 0; virtual void visit(Function&) = 0; virtual void visit(FunctionCall&) = 0; virtual void visit(BinaryOperator&) = 0; virtual void visit(UnaryOperator&) = 0; virtual void visit(IfElseExpression&) = 0; virtual void visit(Definement&) = 0; virtual void visit(ExpressionStatement&) = 0; virtual void visit(ReturnStatement&) = 0; virtual void visit(ProbeStatement&) = 0; virtual void visit(AssertStatement&) = 0; virtual void visit(IfElseStatement&) = 0; virtual void visit(ForStatement&) = 0; virtual void visit(Assignment&) = 0; virtual void visit(TestFlyLine&) = 0; virtual void visit(IdleFlyLine&) = 0; virtual void visit(FlyMark&) = 0; virtual void visit(SourceCode&) = 0; virtual void visit(DSL::DataDSL&) = 0; }; struct PrettyPrinterForAST : VisitorForAST{ std::ostream& os; int indent; PrettyPrinterForAST(std::ostream& o) : os(o),indent(0) {}; void visit(Identifier&); void visit(Variable&); void visit(Number&); void visit(String&); void visit(Boolean&); void visit(Enum&); void visit(Interval&); void visit(Block&); void visit(Function&); void visit(FunctionCall&); void visit(BinaryOperator&); void visit(UnaryOperator&); void visit(IfElseExpression&); void visit(Definement&); void visit(ExpressionStatement&); void visit(ReturnStatement&); void visit(ProbeStatement&); void visit(AssertStatement&); void visit(IfElseStatement&); void visit(ForStatement&); void visit(Assignment&); void visit(TestFlyLine&); void visit(IdleFlyLine&); void visit(FlyMark&); void visit(SourceCode&); void visit(DSL::DataDSL&); std::string ind(); }; } } } namespace shiranui{ namespace syntax{ namespace ast{ namespace DSL{ struct VisitorForDSL{ virtual void operator()(DSLVariable&) = 0; virtual void operator()(DSLDefine&) = 0; virtual void operator()(DSLInteger&) = 0; virtual void operator()(DSLBoolean&) = 0; virtual void operator()(DSLString&) = 0; virtual void operator()(DSLArray&) = 0; virtual void operator()(DSLRef&) = 0; virtual void operator()(DSLFunction&) = 0; }; } } } } #endif <commit_msg>there is AST node that doesn't have point and length<commit_after>#ifndef AST_HPP_INCLUDED #define AST_HPP_INCLUDED #include "../misc.hpp" #include "../runtime/runtime_info.hpp" #include <iostream> #include <memory> #include <string> #include <vector> namespace shiranui{ namespace syntax{ namespace ast{ struct VisitorForAST; } } } namespace shiranui{ namespace syntax{ namespace ast{ namespace DSL{ struct VisitorForDSL; } } } } namespace shiranui{ namespace syntax{ namespace ast{ struct LocationInfo{ int point=0,length=0; }; struct MainNode : LocationInfo{ runtime::infomation::RuntimeInfomation runtime_info; virtual void accept(VisitorForAST&) = 0; }; struct Expression : MainNode{ virtual ~Expression() {}; }; struct Statement : MainNode{ virtual ~Statement() {}; }; // metaelement. struct Identifier : MainNode{ std::string name; // whats this? Identifier() : name("") {} explicit Identifier(std::string); explicit Identifier(std::vector<char>); bool operator<(const Identifier&) const; bool operator==(const Identifier&) const; void accept(VisitorForAST&); }; // immediate values. struct Variable : Expression{ Identifier value; explicit Variable(Identifier v); void accept(VisitorForAST&); }; struct Number : Expression{ int value; explicit Number(int v); void accept(VisitorForAST&); }; struct String : Expression{ std::string value; explicit String(std::string v); explicit String(std::vector<char> v); void accept(VisitorForAST&); }; struct Boolean: Expression{ bool value; explicit Boolean(bool); void accept(VisitorForAST&); }; struct Array : Expression{ virtual ~Array() {}; }; struct Interval : Array{ sp<Expression> start,end,next; bool right_close; Interval(sp<Expression>,sp<Expression>,sp<Expression>,bool); void accept(VisitorForAST&); }; struct Enum : Array{ std::vector<sp<Expression>> expressions; explicit Enum(std::vector<sp<Expression>>); explicit Enum(); void accept(VisitorForAST&); }; struct FlyMark; // pre is unit -> unit // post is (type of return value) -> unit struct Block : Statement{ std::vector<sp<Statement>> statements; std::vector<sp<Block>> pre; std::vector<sp<Block>> post; std::vector<sp<Block>> invariant; std::vector<sp<FlyMark>> flymarks; std::vector<Identifier> post_id; Block(); void add_statement(sp<Statement>); void add_pre(sp<Block>); void add_post(Identifier i,sp<Block>); void add_invariant(sp<Block>); void add_flymark(sp<FlyMark>); void accept(VisitorForAST&); }; struct Function : Expression{ Identifier lambda_id; std::vector<Identifier> parameters; sp<Block> body; Function(Identifier,std::vector<Identifier>,sp<Block>); Function(std::vector<Identifier>,sp<Block>); void accept(VisitorForAST&); }; // expression. struct FunctionCall : Expression{ sp<Expression> function; std::vector<sp<Expression>> arguments; FunctionCall(sp<Expression>,std::vector<sp<Expression>>); void accept(VisitorForAST&); }; struct BinaryOperator : Expression{ std::string op; sp<Expression> left,right; BinaryOperator(std::string,sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; struct UnaryOperator : Expression{ std::string op; sp<Expression> exp; UnaryOperator(std::string,sp<Expression>); void accept(VisitorForAST&); }; struct IfElseExpression : Expression{ sp<Expression> pred; sp<Expression> ife; sp<Expression> elsee; IfElseExpression(sp<Expression>,sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; // statement. struct Definement : Statement{ Identifier id; sp<Expression> value; bool is_const; Definement(Identifier,sp<Expression>,bool); void accept(VisitorForAST&); }; struct ExpressionStatement : Statement{ sp<Expression> exp; ExpressionStatement(sp<Expression>); void accept(VisitorForAST&); }; struct IfElseStatement : Statement{ sp<Expression> pred; sp<Block> ifblock; sp<Block> elseblock; IfElseStatement(sp<Expression>,sp<Block>); IfElseStatement(sp<Expression>,sp<Block>,sp<Block>); void accept(VisitorForAST&); }; struct ForStatement : Statement{ Identifier loop_var; sp<Expression> loop_exp; sp<Block> block; ForStatement(Identifier,sp<Expression>,sp<Block>); void accept(VisitorForAST&); }; struct Assignment : Statement{ Identifier id; sp<Expression> value; Assignment(Identifier,sp<Expression>); void accept(VisitorForAST&); }; struct ReturnStatement : Statement{ sp<Expression> value; ReturnStatement(sp<Expression>); void accept(VisitorForAST&); }; struct ProbeStatement : Statement{ sp<Expression> value; ProbeStatement(sp<Expression>); void accept(VisitorForAST&); }; struct AssertStatement : Statement{ sp<Expression> value; AssertStatement(sp<Expression>); void accept(VisitorForAST&); }; struct FlyLine : MainNode{ }; struct TestFlyLine : FlyLine{ sp<Expression> left,right,error; explicit TestFlyLine(sp<Expression>,sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; struct IdleFlyLine : FlyLine{ sp<Expression> left,right; explicit IdleFlyLine(sp<Expression>,sp<Expression>); void accept(VisitorForAST&); }; struct FlyMark : MainNode{ sp<Expression> left; std::vector<sp<Expression>> right; explicit FlyMark(sp<Expression>); FlyMark(sp<Expression>,std::vector<sp<Expression>>); void accept(VisitorForAST&); }; struct SourceCode : MainNode{ std::vector<sp<Statement>> statements; std::vector<sp<FlyLine>> flylines; std::map<sp<Block>,sp<Function> > where_is_function_from; // FIXME: sp<fucntion> is NOT exact.It's copy. std::map<Identifier,sp<Function> > marker_to_lambda; explicit SourceCode(std::vector<sp<Statement>>); SourceCode(); ~SourceCode(); void add_statement(sp<Statement>); void add_flyline(sp<FlyLine>); void accept(VisitorForAST&); }; namespace DSL{ struct DSLInner : LocationInfo{ virtual void accept(VisitorForDSL&) = 0; }; struct DSLVariable : DSLInner{ std::string name; DSLVariable(); explicit DSLVariable(std::string); explicit DSLVariable(std::vector<char>); bool operator<(const DSLVariable&) const; void accept(VisitorForDSL&); }; struct DSLDefine : DSLInner{ sp<DSLVariable> var; sp<DSLInner> value; DSLDefine(sp<DSLVariable>,sp<DSLInner>); void accept(VisitorForDSL&); }; struct DSLImmediate : DSLInner{ }; struct DSLInteger : DSLImmediate{ int value; explicit DSLInteger(int); void accept(VisitorForDSL&); }; struct DSLBoolean : DSLImmediate{ bool value; explicit DSLBoolean(bool); void accept(VisitorForDSL&); }; struct DSLString : DSLImmediate{ std::string value; explicit DSLString(std::string); void accept(VisitorForDSL&); }; struct DSLArray : DSLImmediate{ std::vector<sp<DSLInner> > value; explicit DSLArray(std::vector<sp<DSLInner>>); explicit DSLArray(); void accept(VisitorForDSL&); }; struct DSLRef : DSLImmediate{ sp<DSLInner> to; explicit DSLRef(sp<DSLInner>); void accept(VisitorForDSL&); }; struct DSLFunction : DSLImmediate{ typedef std::vector<std::pair<sp<ast::DSL::DSLVariable>, sp<ast::DSL::DSLInner> > > myenv; myenv environment; Identifier lambda_id; DSLFunction(myenv,sp<DSLVariable>); void accept(VisitorForDSL&); }; struct DataDSL : Expression{ sp<DSLInner> inner; explicit DataDSL(sp<DSLInner>); void accept(VisitorForAST&); }; } } } } namespace shiranui{ namespace syntax{ namespace ast{ struct VisitorForAST{ virtual ~VisitorForAST() {}; virtual void visit(Identifier&) = 0; virtual void visit(Variable&) = 0; virtual void visit(Number&) = 0; virtual void visit(String&) = 0; virtual void visit(Boolean&) = 0; virtual void visit(Enum&) = 0; virtual void visit(Interval&) = 0; virtual void visit(Block&) = 0; virtual void visit(Function&) = 0; virtual void visit(FunctionCall&) = 0; virtual void visit(BinaryOperator&) = 0; virtual void visit(UnaryOperator&) = 0; virtual void visit(IfElseExpression&) = 0; virtual void visit(Definement&) = 0; virtual void visit(ExpressionStatement&) = 0; virtual void visit(ReturnStatement&) = 0; virtual void visit(ProbeStatement&) = 0; virtual void visit(AssertStatement&) = 0; virtual void visit(IfElseStatement&) = 0; virtual void visit(ForStatement&) = 0; virtual void visit(Assignment&) = 0; virtual void visit(TestFlyLine&) = 0; virtual void visit(IdleFlyLine&) = 0; virtual void visit(FlyMark&) = 0; virtual void visit(SourceCode&) = 0; virtual void visit(DSL::DataDSL&) = 0; }; struct PrettyPrinterForAST : VisitorForAST{ std::ostream& os; int indent; PrettyPrinterForAST(std::ostream& o) : os(o),indent(0) {}; void visit(Identifier&); void visit(Variable&); void visit(Number&); void visit(String&); void visit(Boolean&); void visit(Enum&); void visit(Interval&); void visit(Block&); void visit(Function&); void visit(FunctionCall&); void visit(BinaryOperator&); void visit(UnaryOperator&); void visit(IfElseExpression&); void visit(Definement&); void visit(ExpressionStatement&); void visit(ReturnStatement&); void visit(ProbeStatement&); void visit(AssertStatement&); void visit(IfElseStatement&); void visit(ForStatement&); void visit(Assignment&); void visit(TestFlyLine&); void visit(IdleFlyLine&); void visit(FlyMark&); void visit(SourceCode&); void visit(DSL::DataDSL&); std::string ind(); }; } } } namespace shiranui{ namespace syntax{ namespace ast{ namespace DSL{ struct VisitorForDSL{ virtual void operator()(DSLVariable&) = 0; virtual void operator()(DSLDefine&) = 0; virtual void operator()(DSLInteger&) = 0; virtual void operator()(DSLBoolean&) = 0; virtual void operator()(DSLString&) = 0; virtual void operator()(DSLArray&) = 0; virtual void operator()(DSLRef&) = 0; virtual void operator()(DSLFunction&) = 0; }; } } } } #endif <|endoftext|>
<commit_before>#include "message_row.h" #include <gdkmm/pixbufloader.h> #include <gtkmm/stock.h> #include <libsoup/soup-uri.h> #include <iostream> #include <regex> static std::string convert_links(const std::string &slack_markup); static std::string convert_link(const std::string &linker); MessageRow::MessageRow(icon_loader &icon_loader, const users_store &users_store, const Json::Value &payload) : hbox_(Gtk::ORIENTATION_HORIZONTAL), vbox_(Gtk::ORIENTATION_VERTICAL), user_image_(Gtk::Stock::MISSING_IMAGE, Gtk::IconSize(Gtk::ICON_SIZE_BUTTON)), user_label_("", Gtk::ALIGN_START, Gtk::ALIGN_CENTER), message_label_("", Gtk::ALIGN_START, Gtk::ALIGN_CENTER), icon_loader_(icon_loader), users_store_(users_store) { add(hbox_); hbox_.pack_start(user_image_, Gtk::PACK_SHRINK); hbox_.pack_end(vbox_); vbox_.pack_start(user_label_, Gtk::PACK_SHRINK); vbox_.pack_end(message_label_); Pango::AttrList attrs; Pango::Attribute weight = Pango::Attribute::create_attr_weight(Pango::WEIGHT_BOLD); attrs.insert(weight); user_label_.set_attributes(attrs); message_label_.set_line_wrap(true); message_label_.set_line_wrap_mode(Pango::WRAP_WORD_CHAR); const Json::Value subtype_value = payload["subtype"]; std::string text = payload["text"].asString(); const std::string user_id = payload["user"].asString(); const boost::optional<user> o_user = users_store_.find(user_id); if (o_user) { const user &user = o_user.get(); user_label_.set_text(user.name); load_user_icon(user.profile.image_72); } if (!subtype_value.isNull()) { const std::string subtype = subtype_value.asString(); if (subtype == "bot_message") { user_label_.set_text(payload["username"].asString() + " [BOT]"); const Json::Value image64 = payload["icons"]["image_64"]; const Json::Value image48 = payload["icons"]["image_48"]; const Json::Value bot_id = payload["bot_id"]; if (image64.isString()) { load_user_icon(image64.asString()); } else if (image48.isString()) { load_user_icon(image48.asString()); } else if (bot_id.isString()) { const boost::optional<user> ou = users_store_.find(bot_id.asString()); if (ou) { load_user_icon(ou.get().icons.image_72); } else { std::cerr << "[MessageRow] cannot find bot user " << bot_id << std::endl; } } else { std::cerr << "[MessageRow] cannot load bot icon: " << payload << std::endl; } } else if (subtype == "channel_join") { const Json::Value inviter_value = payload["inviter"]; if (inviter_value.isString()) { const boost::optional<user> o_inviter = users_store_.find(inviter_value.asString()); if (o_inviter) { const user &inviter = o_inviter.get(); text.append(" by invitation from <@") .append(inviter.id) .append("|") .append(inviter.name) .append(">"); } else { std::cerr << "[MessageRow] cannot find channel_join inviter " << inviter_value << std::endl; } } } else if (subtype == "bot_add") { // nothing special } else if (subtype == "bot_remove") { // nothing special } else { std::cout << "Unhandled subtype " << subtype << ": \n" << payload << std::endl; } } message_label_.set_markup(convert_links(text)); show_all_children(); } MessageRow::~MessageRow() { } void MessageRow::load_user_icon(const std::string &icon_url) { icon_loader_.load(icon_url, std::bind(&MessageRow::on_user_icon_loaded, this, std::placeholders::_1)); } void MessageRow::on_user_icon_loaded(Glib::RefPtr<Gdk::Pixbuf> pixbuf) { user_image_.set(pixbuf->scale_simple(36, 36, Gdk::INTERP_BILINEAR)); } std::string convert_links(const std::string &slack_markup) { std::regex markup_re("<([^<>]*)>"); std::sregex_iterator re_it(slack_markup.begin(), slack_markup.end(), markup_re), re_end; if (re_it == re_end) { return slack_markup; } std::string pango_markup; std::size_t pos = 0; for (; re_it != re_end; ++re_it) { pango_markup.append(slack_markup, pos, re_it->position() - pos) .append(convert_link((*re_it)[1].str())); pos = re_it->position() + re_it->length(); } pango_markup.append(slack_markup, pos, slack_markup.size() - pos); return pango_markup; } // https://api.slack.com/docs/formatting std::string convert_link(const std::string &linker) { std::regex url_re("^(.+)\\|(.+)$"); std::smatch match; std::string ret; if (std::regex_match(linker, match, url_re)) { const std::string &left = match[1]; const std::string &right = match[2]; switch (left[0]) { case '@': case '#': ret.append("<a href=\"") .append(left) .append("\">") .append(left, 0, 1) .append(right) .append("</a>"); break; default: ret.append("<a href=\"") .append(left) .append("\">") .append(right) .append("</a>"); break; } } else { switch (linker[0]) { case '@': case '#': // TODO: Resolve user id and channel id ret.append("<a href=\"") .append(linker) .append("\">") .append(linker) .append("</a>"); break; default: ret.append("<a href=\"") .append(linker) .append("\">") .append(linker) .append("</a>"); break; } } return ret; } <commit_msg>Change non-message color<commit_after>#include "message_row.h" #include <gdkmm/pixbufloader.h> #include <gtkmm/stock.h> #include <libsoup/soup-uri.h> #include <iostream> #include <regex> static std::string convert_links(const std::string &slack_markup, bool is_message); static std::string convert_link(const std::string &linker); MessageRow::MessageRow(icon_loader &icon_loader, const users_store &users_store, const Json::Value &payload) : hbox_(Gtk::ORIENTATION_HORIZONTAL), vbox_(Gtk::ORIENTATION_VERTICAL), user_image_(Gtk::Stock::MISSING_IMAGE, Gtk::IconSize(Gtk::ICON_SIZE_BUTTON)), user_label_("", Gtk::ALIGN_START, Gtk::ALIGN_CENTER), message_label_("", Gtk::ALIGN_START, Gtk::ALIGN_CENTER), icon_loader_(icon_loader), users_store_(users_store) { add(hbox_); hbox_.pack_start(user_image_, Gtk::PACK_SHRINK); hbox_.pack_end(vbox_); vbox_.pack_start(user_label_, Gtk::PACK_SHRINK); vbox_.pack_end(message_label_); Pango::AttrList attrs; Pango::Attribute weight = Pango::Attribute::create_attr_weight(Pango::WEIGHT_BOLD); attrs.insert(weight); user_label_.set_attributes(attrs); message_label_.set_line_wrap(true); message_label_.set_line_wrap_mode(Pango::WRAP_WORD_CHAR); const Json::Value subtype_value = payload["subtype"]; std::string text = payload["text"].asString(); const std::string user_id = payload["user"].asString(); const boost::optional<user> o_user = users_store_.find(user_id); if (o_user) { const user &user = o_user.get(); user_label_.set_text(user.name); load_user_icon(user.profile.image_72); } bool is_message = false; if (subtype_value.isNull()) { is_message = true; } else { const std::string subtype = subtype_value.asString(); if (subtype == "bot_message") { is_message = true; user_label_.set_text(payload["username"].asString() + " [BOT]"); const Json::Value image64 = payload["icons"]["image_64"]; const Json::Value image48 = payload["icons"]["image_48"]; const Json::Value bot_id = payload["bot_id"]; if (image64.isString()) { load_user_icon(image64.asString()); } else if (image48.isString()) { load_user_icon(image48.asString()); } else if (bot_id.isString()) { const boost::optional<user> ou = users_store_.find(bot_id.asString()); if (ou) { load_user_icon(ou.get().icons.image_72); } else { std::cerr << "[MessageRow] cannot find bot user " << bot_id << std::endl; } } else { std::cerr << "[MessageRow] cannot load bot icon: " << payload << std::endl; } } else if (subtype == "channel_join") { const Json::Value inviter_value = payload["inviter"]; if (inviter_value.isString()) { const boost::optional<user> o_inviter = users_store_.find(inviter_value.asString()); if (o_inviter) { const user &inviter = o_inviter.get(); text.append(" by invitation from <@") .append(inviter.id) .append("|") .append(inviter.name) .append(">"); } else { std::cerr << "[MessageRow] cannot find channel_join inviter " << inviter_value << std::endl; } } } else if (subtype == "bot_add") { // nothing special } else if (subtype == "bot_remove") { // nothing special } else { std::cout << "Unhandled subtype " << subtype << ": \n" << payload << std::endl; } } message_label_.set_markup(convert_links(text, is_message)); show_all_children(); } MessageRow::~MessageRow() { } void MessageRow::load_user_icon(const std::string &icon_url) { icon_loader_.load(icon_url, std::bind(&MessageRow::on_user_icon_loaded, this, std::placeholders::_1)); } void MessageRow::on_user_icon_loaded(Glib::RefPtr<Gdk::Pixbuf> pixbuf) { user_image_.set(pixbuf->scale_simple(36, 36, Gdk::INTERP_BILINEAR)); } std::string convert_links(const std::string &slack_markup, bool is_message) { std::regex markup_re("<([^<>]*)>"); std::sregex_iterator re_it(slack_markup.begin(), slack_markup.end(), markup_re), re_end; if (re_it == re_end) { return slack_markup; } std::string pango_markup; std::size_t pos = 0; static const std::string non_message_color = "#aaa"; for (; re_it != re_end; ++re_it) { if (!is_message) { pango_markup.append("<span color=\"") .append(non_message_color) .append("\">"); } pango_markup.append(slack_markup, pos, re_it->position() - pos); if (!is_message) { pango_markup.append("</span>"); } pango_markup.append(convert_link((*re_it)[1].str())); pos = re_it->position() + re_it->length(); } pango_markup.append(slack_markup, pos, slack_markup.size() - pos); return pango_markup; } // https://api.slack.com/docs/formatting std::string convert_link(const std::string &linker) { std::regex url_re("^(.+)\\|(.+)$"); std::smatch match; std::string ret; if (std::regex_match(linker, match, url_re)) { const std::string &left = match[1]; const std::string &right = match[2]; switch (left[0]) { case '@': case '#': ret.append("<a href=\"") .append(left) .append("\">") .append(left, 0, 1) .append(right) .append("</a>"); break; default: ret.append("<a href=\"") .append(left) .append("\">") .append(right) .append("</a>"); break; } } else { switch (linker[0]) { case '@': case '#': // TODO: Resolve user id and channel id ret.append("<a href=\"") .append(linker) .append("\">") .append(linker) .append("</a>"); break; default: ret.append("<a href=\"") .append(linker) .append("\">") .append(linker) .append("</a>"); break; } } return ret; } <|endoftext|>
<commit_before>#include "taskqueuer.h" WARNINGS_DISABLE #include <QCoreApplication> #include <QEventLoop> #include <QVariant> WARNINGS_ENABLE #include "cmdlinetask.h" /*! Track info about tasks. */ struct TaskMeta { /*! Actual task. */ CmdlineTask *task; /*! Does this task need to be the only one happening? */ bool isExclusive; /*! This is a "create archive" task? */ bool isBackup; }; TaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance()) { #ifdef QT_TESTLIB_LIB _fakeNextTask = false; #endif } TaskQueuer::~TaskQueuer() { // Wait up to 1 second to finish any background tasks _threadPool->waitForDone(1000); // Wait up to 1 second to delete objects scheduled with ->deleteLater() QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } void TaskQueuer::stopTasks(bool interrupt, bool running, bool queued) { // Clear the queue first, to avoid starting a queued task // after already clearing the running task(s). if(queued) { while(!_taskQueue.isEmpty()) { TaskMeta * tm = _taskQueue.dequeue(); CmdlineTask *task = tm->task; if(task) { task->emitCanceled(); task->deleteLater(); } } emit message("Cleared queued tasks."); } // Deal with a running backup. if(interrupt) { // Sending a SIGQUIT will cause the tarsnap binary to // create a checkpoint. Non-tarsnap binaries should be // receive a CmdlineTask::stop() instead of a SIGQUIT. if(!_runningTasks.isEmpty()) _runningTasks.first()->task->sigquit(); emit message("Interrupting current backup."); } // Stop running tasks. if(running) { for(TaskMeta *tm : _runningTasks) { CmdlineTask *task = tm->task; if(task) task->stop(); } emit message("Stopped running tasks."); } } void TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup) { // Sanity check. Q_ASSERT(task != nullptr); // Create & initialize the TaskMeta object. TaskMeta *tm = new TaskMeta; tm->task = task; tm->isExclusive = exclusive; tm->isBackup = isBackup; // Add to the queue and trigger starting a new task. _taskQueue.enqueue(tm); startTasks(); } void TaskQueuer::startTasks() { while(!_taskQueue.isEmpty() && !isExclusiveTaskRunning()) { // Bail if the next task requires exclusive running, but // still send the updated task numbers. if(!_runningTasks.isEmpty() && _taskQueue.head()->isExclusive) { updateTaskNumbers(); return; } startTask(); } // Send the updated task numbers. updateTaskNumbers(); } void TaskQueuer::startTask() { // Bail if there's nothing to do. if(_taskQueue.isEmpty()) return; // Check for exclusive. if(isExclusiveTaskRunning()) return; // Get a new task. TaskMeta *tm = _taskQueue.dequeue(); // Set up the task ending. CmdlineTask *task = tm->task; connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask); task->setAutoDelete(false); // Record this thread as "running", even though it hasn't actually // started yet. QThreadPool::start() is non-blocking, and in fact // explicitly states that a QRunnable can be added to an internal // run queue if it's exceeded QThreadPoll::maxThreadCount(). // // However, for the purpose of this TaskQueuer, the task should not // be recorded in our _taskQueue (because we've just dequeued()'d it). // The "strictly correct" solution would be to add a // _waitingForStart queue, and move items out of that queue when the // relevant CmdlineTask::started signal was emitted. At the moment, // I don't think that step is necessary, but I might need to revisit // that decision later. _runningTasks.append(tm); // Start the task. #ifdef QT_TESTLIB_LIB if(_fakeNextTask) task->fake(); #endif _threadPool->start(task); } void TaskQueuer::dequeueTask() { // Get the task. CmdlineTask *task = qobject_cast<CmdlineTask *>(sender()); // Sanity check. if(task == nullptr) return; // Clean up task. for(TaskMeta *tm : _runningTasks) { if(tm->task == task) { _runningTasks.removeOne(tm); delete tm; break; } } task->deleteLater(); // Start another task(s) if applicable. startTasks(); } bool TaskQueuer::isExclusiveTaskRunning() { for(TaskMeta *tm : _runningTasks) { if(tm->isExclusive) return true; } return false; } bool TaskQueuer::isBackupTaskRunning() { for(TaskMeta *tm : _runningTasks) { if(tm->isBackup) return true; } return false; } void TaskQueuer::updateTaskNumbers() { bool backupTaskRunning = isBackupTaskRunning(); emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count()); } #ifdef QT_TESTLIB_LIB void TaskQueuer::fakeNextTask() { _fakeNextTask = true; } void TaskQueuer::waitUntilIdle() { while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty())) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } #endif <commit_msg>TaskQueuer: refactor startTasks()<commit_after>#include "taskqueuer.h" WARNINGS_DISABLE #include <QCoreApplication> #include <QEventLoop> #include <QVariant> WARNINGS_ENABLE #include "cmdlinetask.h" /*! Track info about tasks. */ struct TaskMeta { /*! Actual task. */ CmdlineTask *task; /*! Does this task need to be the only one happening? */ bool isExclusive; /*! This is a "create archive" task? */ bool isBackup; }; TaskQueuer::TaskQueuer() : _threadPool(QThreadPool::globalInstance()) { #ifdef QT_TESTLIB_LIB _fakeNextTask = false; #endif } TaskQueuer::~TaskQueuer() { // Wait up to 1 second to finish any background tasks _threadPool->waitForDone(1000); // Wait up to 1 second to delete objects scheduled with ->deleteLater() QCoreApplication::processEvents(QEventLoop::AllEvents, 1000); } void TaskQueuer::stopTasks(bool interrupt, bool running, bool queued) { // Clear the queue first, to avoid starting a queued task // after already clearing the running task(s). if(queued) { while(!_taskQueue.isEmpty()) { TaskMeta * tm = _taskQueue.dequeue(); CmdlineTask *task = tm->task; if(task) { task->emitCanceled(); task->deleteLater(); } } emit message("Cleared queued tasks."); } // Deal with a running backup. if(interrupt) { // Sending a SIGQUIT will cause the tarsnap binary to // create a checkpoint. Non-tarsnap binaries should be // receive a CmdlineTask::stop() instead of a SIGQUIT. if(!_runningTasks.isEmpty()) _runningTasks.first()->task->sigquit(); emit message("Interrupting current backup."); } // Stop running tasks. if(running) { for(TaskMeta *tm : _runningTasks) { CmdlineTask *task = tm->task; if(task) task->stop(); } emit message("Stopped running tasks."); } } void TaskQueuer::queueTask(CmdlineTask *task, bool exclusive, bool isBackup) { // Sanity check. Q_ASSERT(task != nullptr); // Create & initialize the TaskMeta object. TaskMeta *tm = new TaskMeta; tm->task = task; tm->isExclusive = exclusive; tm->isBackup = isBackup; // Add to the queue and trigger starting a new task. _taskQueue.enqueue(tm); startTasks(); } void TaskQueuer::startTasks() { while(!_taskQueue.isEmpty() && !isExclusiveTaskRunning()) { // Bail from loop if the next task requires exclusive running. if(!_runningTasks.isEmpty() && _taskQueue.head()->isExclusive) break; startTask(); } // Send the updated task numbers. updateTaskNumbers(); } void TaskQueuer::startTask() { // Bail if there's nothing to do. if(_taskQueue.isEmpty()) return; // Check for exclusive. if(isExclusiveTaskRunning()) return; // Get a new task. TaskMeta *tm = _taskQueue.dequeue(); // Set up the task ending. CmdlineTask *task = tm->task; connect(task, &CmdlineTask::dequeue, this, &TaskQueuer::dequeueTask); task->setAutoDelete(false); // Record this thread as "running", even though it hasn't actually // started yet. QThreadPool::start() is non-blocking, and in fact // explicitly states that a QRunnable can be added to an internal // run queue if it's exceeded QThreadPoll::maxThreadCount(). // // However, for the purpose of this TaskQueuer, the task should not // be recorded in our _taskQueue (because we've just dequeued()'d it). // The "strictly correct" solution would be to add a // _waitingForStart queue, and move items out of that queue when the // relevant CmdlineTask::started signal was emitted. At the moment, // I don't think that step is necessary, but I might need to revisit // that decision later. _runningTasks.append(tm); // Start the task. #ifdef QT_TESTLIB_LIB if(_fakeNextTask) task->fake(); #endif _threadPool->start(task); } void TaskQueuer::dequeueTask() { // Get the task. CmdlineTask *task = qobject_cast<CmdlineTask *>(sender()); // Sanity check. if(task == nullptr) return; // Clean up task. for(TaskMeta *tm : _runningTasks) { if(tm->task == task) { _runningTasks.removeOne(tm); delete tm; break; } } task->deleteLater(); // Start another task(s) if applicable. startTasks(); } bool TaskQueuer::isExclusiveTaskRunning() { for(TaskMeta *tm : _runningTasks) { if(tm->isExclusive) return true; } return false; } bool TaskQueuer::isBackupTaskRunning() { for(TaskMeta *tm : _runningTasks) { if(tm->isBackup) return true; } return false; } void TaskQueuer::updateTaskNumbers() { bool backupTaskRunning = isBackupTaskRunning(); emit numTasks(backupTaskRunning, _runningTasks.count(), _taskQueue.count()); } #ifdef QT_TESTLIB_LIB void TaskQueuer::fakeNextTask() { _fakeNextTask = true; } void TaskQueuer::waitUntilIdle() { while(!(_taskQueue.isEmpty() && _runningTasks.isEmpty())) QCoreApplication::processEvents(QEventLoop::AllEvents, 100); } #endif <|endoftext|>
<commit_before>#ifndef regex_impl_hh_INCLUDED #define regex_impl_hh_INCLUDED #include "unicode.hh" #include "utf8.hh" #include "utf8_iterator.hh" #include "vector.hh" #include "flags.hh" namespace Kakoune { struct CompiledRegex { enum Op : char { Match, Literal, LiteralIgnoreCase, AnyChar, Matcher, Jump, Split_PrioritizeParent, Split_PrioritizeChild, Save, LineStart, LineEnd, WordBoundary, NotWordBoundary, SubjectBegin, SubjectEnd, LookAhead, LookBehind, NegativeLookAhead, NegativeLookBehind, }; using Offset = unsigned; static constexpr Offset search_prefix_size = 3 + 2 * sizeof(Offset); explicit operator bool() const { return not bytecode.empty(); } Vector<char> bytecode; Vector<std::function<bool (Codepoint)>> matchers; size_t save_count; }; CompiledRegex compile_regex(StringView re); enum class RegexExecFlags { None = 0, Search = 1 << 0, NotBeginOfLine = 1 << 1, NotEndOfLine = 1 << 2, NotBeginOfWord = 1 << 3, NotEndOfWord = 1 << 4, NotBeginOfSubject = 1 << 5, NotInitialNull = 1 << 6, AnyMatch = 1 << 7, NoSaves = 1 << 8, }; constexpr bool with_bit_ops(Meta::Type<RegexExecFlags>) { return true; } template<typename Iterator> struct ThreadedRegexVM { ThreadedRegexVM(const CompiledRegex& program) : m_program{program} { kak_assert(m_program); } ~ThreadedRegexVM() { for (auto* saves : m_saves) { for (size_t i = m_program.save_count-1; i > 0; --i) saves->pos[i].~Iterator(); saves->~Saves(); } } struct Saves { int refcount; Iterator pos[1]; static Saves* allocate(size_t count) { void* ptr = ::operator new (sizeof(Saves) + (count-1) * sizeof(Iterator)); Saves* saves = new (ptr) Saves{1, {}}; for (int i = 1; i < count; ++i) new (&saves->pos[i]) Iterator{}; return saves; } static Saves* allocate(size_t count, const Iterator* pos) { void* ptr = ::operator new (sizeof(Saves) + (count-1) * sizeof(Iterator)); Saves* saves = new (ptr) Saves{1, pos[0]}; for (size_t i = 1; i < count; ++i) new (&saves->pos[i]) Iterator{pos[i]}; return saves; } }; Saves* clone_saves(Saves* saves) { if (not m_free_saves.empty()) { Saves* res = m_free_saves.back(); m_free_saves.pop_back(); res->refcount = 1; std::copy(saves->pos, saves->pos + m_program.save_count, res->pos); return res; } m_saves.push_back(Saves::allocate(m_program.save_count, saves->pos)); return m_saves.back(); } void release_saves(Saves* saves) { if (saves and --saves->refcount == 0) m_free_saves.push_back(saves); }; struct Thread { const char* inst; Saves* saves; }; enum class StepResult { Consumed, Matched, Failed }; StepResult step(Thread& thread, Vector<Thread>& threads) { const auto prog_start = m_program.bytecode.data(); const auto prog_end = prog_start + m_program.bytecode.size(); while (true) { const Codepoint cp = m_pos == m_end ? 0 : *m_pos; const CompiledRegex::Op op = (CompiledRegex::Op)*thread.inst++; switch (op) { case CompiledRegex::Literal: if (utf8::read_codepoint(thread.inst, prog_end) == cp) return StepResult::Consumed; return StepResult::Failed; case CompiledRegex::LiteralIgnoreCase: if (utf8::read_codepoint(thread.inst, prog_end) == to_lower(cp)) return StepResult::Consumed; return StepResult::Failed; case CompiledRegex::AnyChar: return StepResult::Consumed; case CompiledRegex::Jump: thread.inst = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst); break; case CompiledRegex::Split_PrioritizeParent: { auto parent = thread.inst + sizeof(CompiledRegex::Offset); auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst); thread.inst = parent; if (thread.saves) ++thread.saves->refcount; threads.push_back({child, thread.saves}); break; } case CompiledRegex::Split_PrioritizeChild: { auto parent = thread.inst + sizeof(CompiledRegex::Offset); auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst); thread.inst = child; if (thread.saves) ++thread.saves->refcount; threads.push_back({parent, thread.saves}); break; } case CompiledRegex::Save: { if (thread.saves == nullptr) break; if (thread.saves->refcount > 1) { --thread.saves->refcount; thread.saves = clone_saves(thread.saves); } const size_t index = *thread.inst++; thread.saves->pos[index] = m_pos.base(); break; } case CompiledRegex::Matcher: { const int matcher_id = *thread.inst++; return m_program.matchers[matcher_id](*m_pos) ? StepResult::Consumed : StepResult::Failed; } case CompiledRegex::LineStart: if (not is_line_start()) return StepResult::Failed; break; case CompiledRegex::LineEnd: if (not is_line_end()) return StepResult::Failed; break; case CompiledRegex::WordBoundary: if (not is_word_boundary()) return StepResult::Failed; break; case CompiledRegex::NotWordBoundary: if (is_word_boundary()) return StepResult::Failed; break; case CompiledRegex::SubjectBegin: if (m_pos != m_begin or m_flags & RegexExecFlags::NotBeginOfSubject) return StepResult::Failed; break; case CompiledRegex::SubjectEnd: if (m_pos != m_end) return StepResult::Failed; break; case CompiledRegex::LookAhead: case CompiledRegex::NegativeLookAhead: { int count = *thread.inst++; for (auto it = m_pos; count and it != m_end; ++it, --count) if (*it != utf8::read(thread.inst)) break; if ((op == CompiledRegex::LookAhead and count != 0) or (op == CompiledRegex::NegativeLookAhead and count == 0)) return StepResult::Failed; thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1}); break; } case CompiledRegex::LookBehind: case CompiledRegex::NegativeLookBehind: { int count = *thread.inst++; for (auto it = m_pos-1; count and it >= m_begin; --it, --count) if (*it != utf8::read(thread.inst)) break; if ((op == CompiledRegex::LookBehind and count != 0) or (op == CompiledRegex::NegativeLookBehind and count == 0)) return StepResult::Failed; thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1}); break; } case CompiledRegex::Match: return StepResult::Matched; } } return StepResult::Failed; } bool exec(Iterator begin, Iterator end, RegexExecFlags flags) { m_begin = begin; m_end = end; m_flags = flags; bool found_match = false; if (flags & RegexExecFlags::NotInitialNull and m_begin == m_end) return false; Saves* initial_saves = nullptr; if (not (m_flags & RegexExecFlags::NoSaves)) { m_saves.push_back(Saves::allocate(m_program.save_count)); initial_saves = m_saves.back(); } const bool search = (flags & RegexExecFlags::Search); const auto start_offset = search ? 0 : CompiledRegex::search_prefix_size; Vector<Thread> current_threads{Thread{m_program.bytecode.data() + start_offset, initial_saves}}; Vector<Thread> next_threads; for (m_pos = Utf8It{m_begin, m_begin, m_end}; m_pos != m_end; ++m_pos) { while (not current_threads.empty()) { auto thread = current_threads.back(); current_threads.pop_back(); switch (step(thread, current_threads)) { case StepResult::Matched: if (not (flags & RegexExecFlags::Search) or // We are not at end, this is not a full match (flags & RegexExecFlags::NotInitialNull and m_pos == m_begin)) { release_saves(thread.saves); continue; } if (thread.saves) m_captures = thread.saves; if (flags & RegexExecFlags::AnyMatch) return true; found_match = true; current_threads.clear(); // remove this and lower priority threads break; case StepResult::Failed: release_saves(thread.saves); break; case StepResult::Consumed: if (contains_that(next_threads, [&](auto& t) { return t.inst == thread.inst; })) release_saves(thread.saves); else next_threads.push_back(thread); break; } } if (next_threads.empty()) return found_match; std::swap(current_threads, next_threads); std::reverse(current_threads.begin(), current_threads.end()); } if (found_match) return true; // Step remaining threads to see if they match without consuming anything else while (not current_threads.empty()) { auto thread = current_threads.back(); current_threads.pop_back(); if (step(thread, current_threads) == StepResult::Matched) { if (thread.saves) m_captures = thread.saves; return true; } } return false; } bool is_line_start() const { return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfLine)) or *(m_pos-1) == '\n'; } bool is_line_end() const { return (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfLine)) or *m_pos == '\n'; } bool is_word_boundary() const { return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfWord)) or (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfWord)) or is_word(*(m_pos-1)) != is_word(*m_pos); } const CompiledRegex& m_program; using Utf8It = utf8::iterator<Iterator>; Iterator m_begin; Iterator m_end; Utf8It m_pos; RegexExecFlags m_flags; Vector<Saves*> m_saves; Vector<Saves*> m_free_saves; Saves* m_captures = nullptr; }; template<typename It> bool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves); } template<typename It> bool regex_match(It begin, It end, Vector<It>& captures, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; if (vm.exec(begin, end, flags & ~(RegexExecFlags::Search))) { std::copy(vm.m_captures->pos, vm.m_captures->pos + re.save_count, std::back_inserter(captures)); return true; } return false; } template<typename It> bool regex_search(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves); } template<typename It> bool regex_search(It begin, It end, Vector<It>& captures, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; if (vm.exec(begin, end, flags | RegexExecFlags::Search)) { std::copy(vm.m_captures->pos, vm.m_captures->pos + re.save_count, std::back_inserter(captures)); return true; } return false; } } #endif // regex_impl_hh_INCLUDED <commit_msg>Regex: small code tweak<commit_after>#ifndef regex_impl_hh_INCLUDED #define regex_impl_hh_INCLUDED #include "unicode.hh" #include "utf8.hh" #include "utf8_iterator.hh" #include "vector.hh" #include "flags.hh" namespace Kakoune { struct CompiledRegex { enum Op : char { Match, Literal, LiteralIgnoreCase, AnyChar, Matcher, Jump, Split_PrioritizeParent, Split_PrioritizeChild, Save, LineStart, LineEnd, WordBoundary, NotWordBoundary, SubjectBegin, SubjectEnd, LookAhead, LookBehind, NegativeLookAhead, NegativeLookBehind, }; using Offset = unsigned; static constexpr Offset search_prefix_size = 3 + 2 * sizeof(Offset); explicit operator bool() const { return not bytecode.empty(); } Vector<char> bytecode; Vector<std::function<bool (Codepoint)>> matchers; size_t save_count; }; CompiledRegex compile_regex(StringView re); enum class RegexExecFlags { None = 0, Search = 1 << 0, NotBeginOfLine = 1 << 1, NotEndOfLine = 1 << 2, NotBeginOfWord = 1 << 3, NotEndOfWord = 1 << 4, NotBeginOfSubject = 1 << 5, NotInitialNull = 1 << 6, AnyMatch = 1 << 7, NoSaves = 1 << 8, }; constexpr bool with_bit_ops(Meta::Type<RegexExecFlags>) { return true; } template<typename Iterator> struct ThreadedRegexVM { ThreadedRegexVM(const CompiledRegex& program) : m_program{program} { kak_assert(m_program); } ~ThreadedRegexVM() { for (auto* saves : m_saves) { for (size_t i = m_program.save_count-1; i > 0; --i) saves->pos[i].~Iterator(); saves->~Saves(); } } struct Saves { int refcount; Iterator pos[1]; static Saves* allocate(size_t count) { void* ptr = ::operator new (sizeof(Saves) + (count-1) * sizeof(Iterator)); Saves* saves = new (ptr) Saves{1, {}}; for (int i = 1; i < count; ++i) new (&saves->pos[i]) Iterator{}; return saves; } static Saves* allocate(size_t count, const Iterator* pos) { void* ptr = ::operator new (sizeof(Saves) + (count-1) * sizeof(Iterator)); Saves* saves = new (ptr) Saves{1, pos[0]}; for (size_t i = 1; i < count; ++i) new (&saves->pos[i]) Iterator{pos[i]}; return saves; } }; Saves* clone_saves(Saves* saves) { if (not m_free_saves.empty()) { Saves* res = m_free_saves.back(); m_free_saves.pop_back(); res->refcount = 1; std::copy(saves->pos, saves->pos + m_program.save_count, res->pos); return res; } m_saves.push_back(Saves::allocate(m_program.save_count, saves->pos)); return m_saves.back(); } void release_saves(Saves* saves) { if (saves and --saves->refcount == 0) m_free_saves.push_back(saves); }; struct Thread { const char* inst; Saves* saves; }; enum class StepResult { Consumed, Matched, Failed }; StepResult step(Thread& thread, Vector<Thread>& threads) { const auto prog_start = m_program.bytecode.data(); const auto prog_end = prog_start + m_program.bytecode.size(); while (true) { const Codepoint cp = m_pos == m_end ? 0 : *m_pos; const CompiledRegex::Op op = (CompiledRegex::Op)*thread.inst++; switch (op) { case CompiledRegex::Literal: if (utf8::read_codepoint(thread.inst, prog_end) == cp) return StepResult::Consumed; return StepResult::Failed; case CompiledRegex::LiteralIgnoreCase: if (utf8::read_codepoint(thread.inst, prog_end) == to_lower(cp)) return StepResult::Consumed; return StepResult::Failed; case CompiledRegex::AnyChar: return StepResult::Consumed; case CompiledRegex::Jump: thread.inst = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst); break; case CompiledRegex::Split_PrioritizeParent: { auto parent = thread.inst + sizeof(CompiledRegex::Offset); auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst); thread.inst = parent; if (thread.saves) ++thread.saves->refcount; threads.push_back({child, thread.saves}); break; } case CompiledRegex::Split_PrioritizeChild: { auto parent = thread.inst + sizeof(CompiledRegex::Offset); auto child = prog_start + *reinterpret_cast<const CompiledRegex::Offset*>(thread.inst); thread.inst = child; if (thread.saves) ++thread.saves->refcount; threads.push_back({parent, thread.saves}); break; } case CompiledRegex::Save: { if (thread.saves == nullptr) break; if (thread.saves->refcount > 1) { --thread.saves->refcount; thread.saves = clone_saves(thread.saves); } const size_t index = *thread.inst++; thread.saves->pos[index] = m_pos.base(); break; } case CompiledRegex::Matcher: { const int matcher_id = *thread.inst++; return m_program.matchers[matcher_id](*m_pos) ? StepResult::Consumed : StepResult::Failed; } case CompiledRegex::LineStart: if (not is_line_start()) return StepResult::Failed; break; case CompiledRegex::LineEnd: if (not is_line_end()) return StepResult::Failed; break; case CompiledRegex::WordBoundary: if (not is_word_boundary()) return StepResult::Failed; break; case CompiledRegex::NotWordBoundary: if (is_word_boundary()) return StepResult::Failed; break; case CompiledRegex::SubjectBegin: if (m_pos != m_begin or m_flags & RegexExecFlags::NotBeginOfSubject) return StepResult::Failed; break; case CompiledRegex::SubjectEnd: if (m_pos != m_end) return StepResult::Failed; break; case CompiledRegex::LookAhead: case CompiledRegex::NegativeLookAhead: { int count = *thread.inst++; for (auto it = m_pos; count and it != m_end; ++it, --count) if (*it != utf8::read(thread.inst)) break; if ((op == CompiledRegex::LookAhead and count != 0) or (op == CompiledRegex::NegativeLookAhead and count == 0)) return StepResult::Failed; thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1}); break; } case CompiledRegex::LookBehind: case CompiledRegex::NegativeLookBehind: { int count = *thread.inst++; for (auto it = m_pos-1; count and it >= m_begin; --it, --count) if (*it != utf8::read(thread.inst)) break; if ((op == CompiledRegex::LookBehind and count != 0) or (op == CompiledRegex::NegativeLookBehind and count == 0)) return StepResult::Failed; thread.inst = utf8::advance(thread.inst, prog_end, CharCount{count - 1}); break; } case CompiledRegex::Match: return StepResult::Matched; } } return StepResult::Failed; } bool exec(Iterator begin, Iterator end, RegexExecFlags flags) { m_begin = begin; m_end = end; m_flags = flags; bool found_match = false; if (flags & RegexExecFlags::NotInitialNull and m_begin == m_end) return false; Saves* initial_saves = nullptr; if (not (m_flags & RegexExecFlags::NoSaves)) { m_saves.push_back(Saves::allocate(m_program.save_count)); initial_saves = m_saves.back(); } const bool search = (flags & RegexExecFlags::Search); const auto start_offset = search ? 0 : CompiledRegex::search_prefix_size; Vector<Thread> current_threads{Thread{m_program.bytecode.data() + start_offset, initial_saves}}; Vector<Thread> next_threads; for (m_pos = Utf8It{m_begin, m_begin, m_end}; m_pos != m_end; ++m_pos) { while (not current_threads.empty()) { auto thread = current_threads.back(); current_threads.pop_back(); switch (step(thread, current_threads)) { case StepResult::Matched: if (not search or // We are not at end, this is not a full match (flags & RegexExecFlags::NotInitialNull and m_pos == m_begin)) { release_saves(thread.saves); continue; } m_captures = thread.saves; if (flags & RegexExecFlags::AnyMatch) return true; found_match = true; current_threads.clear(); // remove this and lower priority threads break; case StepResult::Failed: release_saves(thread.saves); break; case StepResult::Consumed: if (contains_that(next_threads, [&](auto& t) { return t.inst == thread.inst; })) release_saves(thread.saves); else next_threads.push_back(thread); break; } } if (next_threads.empty()) return found_match; std::swap(current_threads, next_threads); std::reverse(current_threads.begin(), current_threads.end()); } if (found_match) return true; // Step remaining threads to see if they match without consuming anything else while (not current_threads.empty()) { auto thread = current_threads.back(); current_threads.pop_back(); if (step(thread, current_threads) == StepResult::Matched) { m_captures = thread.saves; return true; } } return false; } bool is_line_start() const { return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfLine)) or *(m_pos-1) == '\n'; } bool is_line_end() const { return (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfLine)) or *m_pos == '\n'; } bool is_word_boundary() const { return (m_pos == m_begin and not (m_flags & RegexExecFlags::NotBeginOfWord)) or (m_pos == m_end and not (m_flags & RegexExecFlags::NotEndOfWord)) or is_word(*(m_pos-1)) != is_word(*m_pos); } const CompiledRegex& m_program; using Utf8It = utf8::iterator<Iterator>; Iterator m_begin; Iterator m_end; Utf8It m_pos; RegexExecFlags m_flags; Vector<Saves*> m_saves; Vector<Saves*> m_free_saves; Saves* m_captures = nullptr; }; template<typename It> bool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves); } template<typename It> bool regex_match(It begin, It end, Vector<It>& captures, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; if (vm.exec(begin, end, flags & ~(RegexExecFlags::Search))) { std::copy(vm.m_captures->pos, vm.m_captures->pos + re.save_count, std::back_inserter(captures)); return true; } return false; } template<typename It> bool regex_search(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves); } template<typename It> bool regex_search(It begin, It end, Vector<It>& captures, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None) { ThreadedRegexVM<It> vm{re}; if (vm.exec(begin, end, flags | RegexExecFlags::Search)) { std::copy(vm.m_captures->pos, vm.m_captures->pos + re.save_count, std::back_inserter(captures)); return true; } return false; } } #endif // regex_impl_hh_INCLUDED <|endoftext|>
<commit_before>#include <mos/assets.hpp> #include <rapidxml.hpp> #include <rapidxml_utils.hpp> #include <lodepng.h> #include <exception> #include <memory> #include <cstring> #include <fstream> #include <iostream> #include <iterator> #include <stb_vorbis.h> #include <glm/gtx/io.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtc/type_ptr.hpp> #include <mos/util.hpp> #include <algorithm> namespace mos { using namespace std; using namespace glm; using namespace nlohmann; Assets::Assets(const std::string directory) : directory_(directory) {} Assets::~Assets() {} Model Assets::model_value(const json &value) { auto name = value.value("name", ""); std::string mesh = value.value("mesh", ""); std::string texture_name = value.value("texture", ""); std::string texture2_name = value.value("texture2", ""); std::string lightmap_name = value["lightmap"].is_null() ? "" : value.value("lightmap", ""); std::string material_name = value.value("material", ""); bool recieves_light = value.value("receives_light", true); glm::mat4 transform = glm::mat4(1.0f); if (!value["transform"].is_null()) { std::vector<float> nums; for (auto &num : value["transform"]) { nums.push_back(num); } transform = glm::make_mat4x4(nums.data()); } auto created_model = mos::Model( name, mesh_cached(mesh), Textures(texture_cached(texture_name), texture_cached(texture2_name)), transform, material_cached(material_name), Lightmaps(texture_cached(lightmap_name)), nullptr, recieves_light); for (auto & m: value["models"]) { created_model.models.push_back(model_value(m)); } return created_model; } Model Assets::model(const std::string &path) { //auto doc = document(directory_ + path); auto doc = json::parse(mos::text(directory_ + path)); return model_value(doc); } Animation Assets::animation(const string &path) { auto doc = document(directory_ + path); auto frame_rate = doc["frame_rate"].GetInt(); std::map<unsigned int, std::shared_ptr<Mesh const>> keyframes; for (auto it = doc["keyframes"].Begin(); it != doc["keyframes"].End(); it++) { auto key = (*it)["key"].GetInt(); auto mesh_path = (*it)["mesh"].GetString(); keyframes.insert({key, mesh_cached(mesh_path)}); } Animation animation(keyframes, frame_rate); return animation; } std::shared_ptr<Mesh> Assets::mesh(const std::string &path) const { return std::make_shared<Mesh>(Mesh(directory_ + path)); } std::shared_ptr<Mesh> Assets::mesh_cached(const std::string &path) { if (meshes_.find(path) == meshes_.end()) { meshes_.insert(MeshPair(path, mesh(path))); } return meshes_.at(path); } std::shared_ptr<Texture> Assets::texture(const std::string &path, const bool mipmaps) const { if (path.empty()) { return std::shared_ptr<Texture>(nullptr); } return std::make_shared<Texture>(directory_ + path, mipmaps); } std::shared_ptr<Texture> Assets::texture_cached(const std::string &path, const bool mipmaps) { if (!path.empty()) { if (textures_.find(path) == textures_.end()) { textures_.insert(TexturePair(path, texture(path, mipmaps))); } return textures_.at(path); } else { return std::shared_ptr<Texture>(nullptr); } } std::shared_ptr<Sound> Assets::sound(const std::string &path) const { return std::make_shared<Sound>(Sound(directory_ + path)); } std::shared_ptr<Stream> Assets::stream(const string &path) const { return std::make_shared<mos::Stream>(directory_ + path); } Font Assets::font(const string &path) { std::map<char, Character> characters; rapidxml::xml_document<> doc; auto xml_string = text(directory_ + path); doc.parse<0>(&xml_string[0]); auto *chars_node = doc.first_node("font")->first_node("chars"); auto *description_node = doc.first_node("font")->first_node("description"); std::string name = description_node->first_attribute("family")->value(); float size = atof(description_node->first_attribute("family")->value()); auto *metrics_node = doc.first_node("font")->first_node("metrics"); float height = atof(metrics_node->first_attribute("height")->value()); float ascender = atof(metrics_node->first_attribute("ascender")->value()); float descender = atof(metrics_node->first_attribute("descender")->value()); auto *texture_node = doc.first_node("font")->first_node("texture"); std::string file = texture_node->first_attribute("file")->value(); //std::transform(file.begin(), file.end(), file.begin(), ::tolower); for (auto *char_node = chars_node->first_node("char"); char_node; char_node = char_node->next_sibling()) { Character character; character.offset_x = atof(char_node->first_attribute("offset_x")->value()); character.offset_y = atof(char_node->first_attribute("offset_y")->value()); character.advance = atof(char_node->first_attribute("advance")->value()); character.rect_w = atof(char_node->first_attribute("rect_w")->value()); character.id = *char_node->first_attribute("id")->value(); character.rect_x = atof(char_node->first_attribute("rect_x")->value()); character.rect_y = atof(char_node->first_attribute("rect_y")->value()); character.rect_h = atof(char_node->first_attribute("rect_h")->value()); characters.insert(std::pair<char, Character>(character.id, character)); } auto char_map = characters; auto texture = texture_cached(file); return Font(char_map, texture, height, ascender, descender); } std::shared_ptr<Sound> Assets::sound_cached(const std::string &path) { if (sounds_.find(path) == sounds_.end()) { sounds_.insert(SoundPair(path, sound(path))); return sounds_.at(path); } else { return sounds_.at(path); } } std::shared_ptr<Material> Assets::material(const std::string &path) const { return std::make_shared<Material>(directory_ + path); } std::shared_ptr<Material> Assets::material_cached(const std::string &path) { if (materials_.find(path) == materials_.end()) { materials_.insert(MaterialPair(path, material(path))); return materials_.at(path); } else { return materials_.at(path); } } void Assets::clear_unused() { for (auto it = textures_.begin(); it != textures_.end();) { if (it->second.use_count() <= 1) { textures_.erase(it++); } else { ++it; } } for (auto it = meshes_.begin(); it != meshes_.end();) { if (it->second.use_count() <= 1) { meshes_.erase(it++); } else { ++it; } } for (auto it = sounds_.begin(); it != sounds_.end();) { if (it->second.use_count() <= 1) { sounds_.erase(it++); } else { ++it; } } for (auto it = materials_.begin(); it != materials_.end();) { if (it->second.use_count() <= 1) { materials_.erase(it++); } else { ++it; } } } } <commit_msg>Fix build.<commit_after>#include <mos/assets.hpp> #include <rapidxml.hpp> #include <rapidxml_utils.hpp> #include <lodepng.h> #include <exception> #include <memory> #include <cstring> #include <fstream> #include <iostream> #include <iterator> #include <stb_vorbis.h> #include <glm/gtx/io.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtc/type_ptr.hpp> #include <mos/util.hpp> #include <algorithm> namespace mos { using namespace std; using namespace glm; using namespace nlohmann; Assets::Assets(const std::string directory) : directory_(directory) {} Assets::~Assets() {} Model Assets::model_value(const json &value) { auto name = value.value("name", ""); std::string mesh = value.value("mesh", ""); std::string texture_name = value.value("texture", ""); std::string texture2_name = value.value("texture2", ""); std::string lightmap_name = value["lightmap"].is_null() ? "" : value.value("lightmap", ""); std::string material_name = value.value("material", ""); bool recieves_light = value.value("receives_light", true); glm::mat4 transform = glm::mat4(1.0f); if (!value["transform"].is_null()) { std::vector<float> nums; for (auto &num : value["transform"]) { nums.push_back(num); } transform = glm::make_mat4x4(nums.data()); } auto created_model = mos::Model( name, mesh_cached(mesh), Textures(texture_cached(texture_name), texture_cached(texture2_name)), transform, material_cached(material_name), Lightmaps(texture_cached(lightmap_name)), nullptr, recieves_light); for (auto & m: value["models"]) { created_model.models.push_back(model_value(m)); } return created_model; } Model Assets::model(const std::string &path) { auto doc = json::parse(mos::text(directory_ + path)); return model_value(doc); } Animation Assets::animation(const string &path) { auto doc = json::parse(mos::text(directory_ + path)); auto frame_rate = doc["frame_rate"]; std::map<unsigned int, std::shared_ptr<Mesh const>> keyframes; for (auto &keyframe : doc["keyframes"]) { auto key = keyframe["key"]; auto mesh_path = keyframe["mesh"]; keyframes.insert({key, mesh_cached(mesh_path)}); } Animation animation(keyframes, frame_rate); return animation; } std::shared_ptr<Mesh> Assets::mesh(const std::string &path) const { return std::make_shared<Mesh>(Mesh(directory_ + path)); } std::shared_ptr<Mesh> Assets::mesh_cached(const std::string &path) { if (meshes_.find(path) == meshes_.end()) { meshes_.insert(MeshPair(path, mesh(path))); } return meshes_.at(path); } std::shared_ptr<Texture> Assets::texture(const std::string &path, const bool mipmaps) const { if (path.empty()) { return std::shared_ptr<Texture>(nullptr); } return std::make_shared<Texture>(directory_ + path, mipmaps); } std::shared_ptr<Texture> Assets::texture_cached(const std::string &path, const bool mipmaps) { if (!path.empty()) { if (textures_.find(path) == textures_.end()) { textures_.insert(TexturePair(path, texture(path, mipmaps))); } return textures_.at(path); } else { return std::shared_ptr<Texture>(nullptr); } } std::shared_ptr<Sound> Assets::sound(const std::string &path) const { return std::make_shared<Sound>(Sound(directory_ + path)); } std::shared_ptr<Stream> Assets::stream(const string &path) const { return std::make_shared<mos::Stream>(directory_ + path); } Font Assets::font(const string &path) { std::map<char, Character> characters; rapidxml::xml_document<> doc; auto xml_string = text(directory_ + path); doc.parse<0>(&xml_string[0]); auto *chars_node = doc.first_node("font")->first_node("chars"); auto *description_node = doc.first_node("font")->first_node("description"); std::string name = description_node->first_attribute("family")->value(); float size = atof(description_node->first_attribute("family")->value()); auto *metrics_node = doc.first_node("font")->first_node("metrics"); float height = atof(metrics_node->first_attribute("height")->value()); float ascender = atof(metrics_node->first_attribute("ascender")->value()); float descender = atof(metrics_node->first_attribute("descender")->value()); auto *texture_node = doc.first_node("font")->first_node("texture"); std::string file = texture_node->first_attribute("file")->value(); //std::transform(file.begin(), file.end(), file.begin(), ::tolower); for (auto *char_node = chars_node->first_node("char"); char_node; char_node = char_node->next_sibling()) { Character character; character.offset_x = atof(char_node->first_attribute("offset_x")->value()); character.offset_y = atof(char_node->first_attribute("offset_y")->value()); character.advance = atof(char_node->first_attribute("advance")->value()); character.rect_w = atof(char_node->first_attribute("rect_w")->value()); character.id = *char_node->first_attribute("id")->value(); character.rect_x = atof(char_node->first_attribute("rect_x")->value()); character.rect_y = atof(char_node->first_attribute("rect_y")->value()); character.rect_h = atof(char_node->first_attribute("rect_h")->value()); characters.insert(std::pair<char, Character>(character.id, character)); } auto char_map = characters; auto texture = texture_cached(file); return Font(char_map, texture, height, ascender, descender); } std::shared_ptr<Sound> Assets::sound_cached(const std::string &path) { if (sounds_.find(path) == sounds_.end()) { sounds_.insert(SoundPair(path, sound(path))); return sounds_.at(path); } else { return sounds_.at(path); } } std::shared_ptr<Material> Assets::material(const std::string &path) const { return std::make_shared<Material>(directory_ + path); } std::shared_ptr<Material> Assets::material_cached(const std::string &path) { if (materials_.find(path) == materials_.end()) { materials_.insert(MaterialPair(path, material(path))); return materials_.at(path); } else { return materials_.at(path); } } void Assets::clear_unused() { for (auto it = textures_.begin(); it != textures_.end();) { if (it->second.use_count() <= 1) { textures_.erase(it++); } else { ++it; } } for (auto it = meshes_.begin(); it != meshes_.end();) { if (it->second.use_count() <= 1) { meshes_.erase(it++); } else { ++it; } } for (auto it = sounds_.begin(); it != sounds_.end();) { if (it->second.use_count() <= 1) { sounds_.erase(it++); } else { ++it; } } for (auto it = materials_.begin(); it != materials_.end();) { if (it->second.use_count() <= 1) { materials_.erase(it++); } else { ++it; } } } } <|endoftext|>
<commit_before>#include "includes/truthtable.h" #include <algorithm> #include <cassert> #include <cmath> #include <iomanip> #include <sstream> #include <stack> #include "includes/symbols.h" #include "includes/tokenizer.h" TruthTable::TruthTable() : m_operator_map(std::map<std::string, Op>()), m_keywords_set(std::set<std::string>()), m_operator_precedence_map(std::map<std::string, int>()), m_operands(std::vector<std::string>()), m_expression_tree(nullptr), m_pretty_print(false) { m_operator_map[symbol::AND] = Op::AND; m_operator_map[symbol::OR] = Op::OR; m_operator_map[symbol::NOT] = Op::NOT; m_operator_map[symbol::XOR] = Op::XOR; m_operator_map[symbol::IMPLICATION] = Op::IMPLICATION; m_operator_map[symbol::EQUIVALENCE] = Op::EQUIVALENCE; for (auto &&entry : m_operator_map) { m_keywords_set.insert(entry.first); } m_keywords_set.insert(symbol::LEFT_PAREN); m_keywords_set.insert(symbol::RIGHT_PAREN); m_operator_precedence_map[symbol::NOT] = 1; m_operator_precedence_map[symbol::AND] = 2; m_operator_precedence_map[symbol::OR] = 3; m_operator_precedence_map[symbol::IMPLICATION] = 4; m_operator_precedence_map[symbol::EQUIVALENCE] = 5; } TruthTable::~TruthTable() { delete_expression_tree(m_expression_tree); } bool TruthTable::generate(const std::string &input) { m_operands.clear(); Tokenizer tokenizer(input); if (!tokenizer.tokenize()) { return false; } std::vector<std::string> tokens = tokenizer.get(); std::set<std::string> operands; for (const auto &t : tokens) { if (is_operand(t)) { operands.insert(t); } } std::for_each(std::begin(operands), std::end(operands), [this](std::string s) { m_operands.push_back(s); }); std::sort(m_operands.begin(), m_operands.end()); std::vector<std::string> postfix = to_post_fix(tokens); if (postfix.empty()) { return false; } // print_container(postfix); m_expression_tree = to_expression_tree(postfix); if (!m_expression_tree) { return false; } solve(tokens); return true; } std::vector<std::string> TruthTable::to_post_fix(const std::vector<std::string> &tokens) { std::stack<std::string> op_stack; std::vector<std::string> postfix; std::string last_symbol; bool error_possibility = false; unsigned int i = 0; while (i < tokens.size()) { auto symbol = tokens[i++]; if (is_operand(symbol)) { error_possibility = false; postfix.push_back(symbol); } else { if (error_possibility && symbol != symbol::NOT) { postfix.clear(); return postfix; } if (last_symbol == symbol::NOT) { error_possibility = true; } if (op_stack.empty() || op_stack.top() == symbol::LEFT_PAREN) { op_stack.push(symbol); } else if (symbol == symbol::LEFT_PAREN) { op_stack.push(symbol); } else if (symbol == symbol::RIGHT_PAREN) { for (std::string &top = op_stack.top(); top != symbol::LEFT_PAREN; top = op_stack.top()) { postfix.push_back(top); op_stack.pop(); } op_stack.pop(); // discard left parenthesis } else if (has_higher_precendence(symbol, op_stack.top()) || has_equal_precendence(symbol, op_stack.top())) { op_stack.push(symbol); } else { std::string &top = op_stack.top(); postfix.push_back(top); op_stack.pop(); --i; } } last_symbol = symbol; } if (last_symbol == symbol::NOT) { postfix.clear(); return postfix; } while (op_stack.size() > 0) { std::string &top = op_stack.top(); if (top == symbol::LEFT_PAREN || top == symbol::RIGHT_PAREN) { postfix.clear(); break; } postfix.push_back(top); op_stack.pop(); } return postfix; } TruthTable::Node *TruthTable::to_expression_tree(std::vector<std::string> postfix) { std::stack<Node *> expression_stack; for (const auto &symbol : postfix) { if (is_operand(symbol)) { expression_stack.push(new Node(symbol)); } else { if (expression_stack.empty()) { return nullptr; } Node *node = new Node(symbol); Node *left = expression_stack.top(); expression_stack.pop(); node->left = left; if (symbol != symbol::NOT) // special case { if (expression_stack.empty()) { return nullptr; } Node *right = expression_stack.top(); expression_stack.pop(); node->right = right; } expression_stack.push(node); } } if (expression_stack.size() > 1) { Node *node = expression_stack.top(); expression_stack.pop(); while (!expression_stack.empty()) { delete_expression_tree(node); node = expression_stack.top(); expression_stack.pop(); } return nullptr; } return expression_stack.top(); } void TruthTable::delete_expression_tree(TruthTable::Node *node) { if (node) { delete_expression_tree(node->left); delete_expression_tree(node->right); delete node; } } void TruthTable::print_expression_tree(TruthTable::Node *node, std::string indent) { if (node) { print_expression_tree(node->left, indent += " "); std::cout << indent << node->value << std::endl; print_expression_tree(node->right, indent += " "); } } bool TruthTable::calculate(bool left, Op op, bool right) { switch (op) { case Op::NOT: { return !left; } case Op::AND: { return left && right; } case Op::OR: { return left || right; } case Op::XOR: { return (left || right) && !(left && right); } case Op::IMPLICATION: { return !left || right; } case Op::EQUIVALENCE: { return !((left || right) && !(left && right)); } default: { assert(!"Error: invalid code path"); return false; } } } void TruthTable::solve(std::vector<std::string> &tokens) { std::ostream &os = std::cout; unsigned int max_operand_text_width = 0; std::string input; if (m_pretty_print) { expression_tree_to_string(m_expression_tree, input); for (const auto &operand : m_operands) { if (operand.size() > max_operand_text_width) { max_operand_text_width = static_cast<unsigned int>(operand.size()); } } max_operand_text_width += 1; } unsigned int input_text_width = static_cast<unsigned int>(input.size()); unsigned long operand_count = m_operands.size(); unsigned int max_chars = static_cast<unsigned int>(operand_count) * max_operand_text_width + input_text_width + static_cast<unsigned int>(operand_count) + 2; auto print_row_separator = [&]() { for (unsigned int i = 0; i < max_chars; ++i) { if ((i < (max_chars - input_text_width) && i % (max_operand_text_width + 1) == 0) || i == max_chars - 1) { os << "+"; } else { os << "-"; } } os << std::endl; }; if (m_pretty_print) { print_row_separator(); for (auto &&s : m_operands) { os << "|"; os << std::setw(max_operand_text_width) << s; } os << "|" << std::setw(input_text_width) << input << "|" << std::endl; print_row_separator(); } unsigned long num_permutations = 1; unsigned long interval_count = 0; for (const auto &operand : m_operands) { if (operand != symbol::TRUE && operand != symbol::FALSE) { num_permutations *= 2; ++interval_count; } } bool *intervals = new bool[interval_count]; for (unsigned long i = 0; i < interval_count; ++i) { intervals[i] = true; } unsigned long *counters = new unsigned long[interval_count]; counters[0] = 1; for (unsigned long i = 1; i < interval_count; ++i) { counters[i] = counters[i - 1] * 2; } std::map<std::string, bool> map; for (unsigned long i = 0; i < num_permutations; ++i) { for (unsigned long j = 0; j < interval_count; ++j) { if (i % counters[j] == 0) { intervals[j] = !intervals[j]; } } map.clear(); int index = 0; for (const auto &operand : m_operands) { if (operand == symbol::FALSE) { map[operand] = false; } else if (operand == symbol::TRUE) { map[operand] = true; } else { map[operand] = intervals[index]; ++index; } } bool result = solve_helper(map, m_expression_tree); if (m_pretty_print) { os << "|"; for (unsigned long j = 0; j < operand_count; ++j) { os << std::setw(max_operand_text_width) << std::internal << map[m_operands[j]]; os << "|"; } os << std::setw(input_text_width) << result; os << "|"; } else { for (unsigned long j = 0; j < operand_count; ++j) { os << map[m_operands[j]]; } os << result; } os << std::endl; } if (m_pretty_print) { print_row_separator(); } delete[] counters; delete[] intervals; } bool TruthTable::solve_helper(std::map<std::string, bool> &value_map, TruthTable::Node *node) { if (is_operand(node->value)) { return value_map[node->value]; } bool result_left = solve_helper(value_map, node->left); bool result_right = false; if (node->right) { result_right = solve_helper(value_map, node->right); } return calculate(result_left, m_operator_map[node->value], result_right); } void TruthTable::expression_tree_to_string(TruthTable::Node *node, std::string &result, int depth) { if (node) { bool can_print_paren = (node->left || node->right) && depth > 0; if (can_print_paren) { result += symbol::LEFT_PAREN; } expression_tree_to_string(node->right, result, depth + 1); result += node->value; expression_tree_to_string(node->left, result, depth + 1); if (can_print_paren) { result += symbol::RIGHT_PAREN; } } } template <typename T> void TruthTable::print_container(const T &v) { auto itr = std::begin(v); if (itr != std::end(v)) { while (itr != std::end(v)) { std::cout << *itr; if (itr + 1 != std::end(v)) { std::cout << ", "; } ++itr; } std::cout << std::endl; } } <commit_msg>change auto && to const auto & for for-each loops<commit_after>#include "includes/truthtable.h" #include <algorithm> #include <cassert> #include <cmath> #include <iomanip> #include <sstream> #include <stack> #include "includes/symbols.h" #include "includes/tokenizer.h" TruthTable::TruthTable() : m_operator_map(std::map<std::string, Op>()), m_keywords_set(std::set<std::string>()), m_operator_precedence_map(std::map<std::string, int>()), m_operands(std::vector<std::string>()), m_expression_tree(nullptr), m_pretty_print(false) { m_operator_map[symbol::AND] = Op::AND; m_operator_map[symbol::OR] = Op::OR; m_operator_map[symbol::NOT] = Op::NOT; m_operator_map[symbol::XOR] = Op::XOR; m_operator_map[symbol::IMPLICATION] = Op::IMPLICATION; m_operator_map[symbol::EQUIVALENCE] = Op::EQUIVALENCE; for (const auto &entry : m_operator_map) { m_keywords_set.insert(entry.first); } m_keywords_set.insert(symbol::LEFT_PAREN); m_keywords_set.insert(symbol::RIGHT_PAREN); m_operator_precedence_map[symbol::NOT] = 1; m_operator_precedence_map[symbol::AND] = 2; m_operator_precedence_map[symbol::OR] = 3; m_operator_precedence_map[symbol::IMPLICATION] = 4; m_operator_precedence_map[symbol::EQUIVALENCE] = 5; } TruthTable::~TruthTable() { delete_expression_tree(m_expression_tree); } bool TruthTable::generate(const std::string &input) { m_operands.clear(); Tokenizer tokenizer(input); if (!tokenizer.tokenize()) { return false; } std::vector<std::string> tokens = tokenizer.get(); std::set<std::string> operands; for (const auto &t : tokens) { if (is_operand(t)) { operands.insert(t); } } std::for_each(std::begin(operands), std::end(operands), [this](std::string s) { m_operands.push_back(s); }); std::sort(m_operands.begin(), m_operands.end()); std::vector<std::string> postfix = to_post_fix(tokens); if (postfix.empty()) { return false; } // print_container(postfix); m_expression_tree = to_expression_tree(postfix); if (!m_expression_tree) { return false; } solve(tokens); return true; } std::vector<std::string> TruthTable::to_post_fix(const std::vector<std::string> &tokens) { std::stack<std::string> op_stack; std::vector<std::string> postfix; std::string last_symbol; bool error_possibility = false; unsigned int i = 0; while (i < tokens.size()) { auto symbol = tokens[i++]; if (is_operand(symbol)) { error_possibility = false; postfix.push_back(symbol); } else { if (error_possibility && symbol != symbol::NOT) { postfix.clear(); return postfix; } if (last_symbol == symbol::NOT) { error_possibility = true; } if (op_stack.empty() || op_stack.top() == symbol::LEFT_PAREN) { op_stack.push(symbol); } else if (symbol == symbol::LEFT_PAREN) { op_stack.push(symbol); } else if (symbol == symbol::RIGHT_PAREN) { for (std::string &top = op_stack.top(); top != symbol::LEFT_PAREN; top = op_stack.top()) { postfix.push_back(top); op_stack.pop(); } op_stack.pop(); // discard left parenthesis } else if (has_higher_precendence(symbol, op_stack.top()) || has_equal_precendence(symbol, op_stack.top())) { op_stack.push(symbol); } else { std::string &top = op_stack.top(); postfix.push_back(top); op_stack.pop(); --i; } } last_symbol = symbol; } if (last_symbol == symbol::NOT) { postfix.clear(); return postfix; } while (op_stack.size() > 0) { std::string &top = op_stack.top(); if (top == symbol::LEFT_PAREN || top == symbol::RIGHT_PAREN) { postfix.clear(); break; } postfix.push_back(top); op_stack.pop(); } return postfix; } TruthTable::Node *TruthTable::to_expression_tree(std::vector<std::string> postfix) { std::stack<Node *> expression_stack; for (const auto &symbol : postfix) { if (is_operand(symbol)) { expression_stack.push(new Node(symbol)); } else { if (expression_stack.empty()) { return nullptr; } Node *node = new Node(symbol); Node *left = expression_stack.top(); expression_stack.pop(); node->left = left; if (symbol != symbol::NOT) // special case { if (expression_stack.empty()) { return nullptr; } Node *right = expression_stack.top(); expression_stack.pop(); node->right = right; } expression_stack.push(node); } } if (expression_stack.size() > 1) { Node *node = expression_stack.top(); expression_stack.pop(); while (!expression_stack.empty()) { delete_expression_tree(node); node = expression_stack.top(); expression_stack.pop(); } return nullptr; } return expression_stack.top(); } void TruthTable::delete_expression_tree(TruthTable::Node *node) { if (node) { delete_expression_tree(node->left); delete_expression_tree(node->right); delete node; } } void TruthTable::print_expression_tree(TruthTable::Node *node, std::string indent) { if (node) { print_expression_tree(node->left, indent += " "); std::cout << indent << node->value << std::endl; print_expression_tree(node->right, indent += " "); } } bool TruthTable::calculate(bool left, Op op, bool right) { switch (op) { case Op::NOT: { return !left; } case Op::AND: { return left && right; } case Op::OR: { return left || right; } case Op::XOR: { return (left || right) && !(left && right); } case Op::IMPLICATION: { return !left || right; } case Op::EQUIVALENCE: { return !((left || right) && !(left && right)); } default: { assert(!"Error: invalid code path"); return false; } } } void TruthTable::solve(std::vector<std::string> &tokens) { std::ostream &os = std::cout; unsigned int max_operand_text_width = 0; std::string input; if (m_pretty_print) { expression_tree_to_string(m_expression_tree, input); for (const auto &operand : m_operands) { if (operand.size() > max_operand_text_width) { max_operand_text_width = static_cast<unsigned int>(operand.size()); } } max_operand_text_width += 1; } unsigned int input_text_width = static_cast<unsigned int>(input.size()); unsigned long operand_count = m_operands.size(); unsigned int max_chars = static_cast<unsigned int>(operand_count) * max_operand_text_width + input_text_width + static_cast<unsigned int>(operand_count) + 2; auto print_row_separator = [&]() { for (unsigned int i = 0; i < max_chars; ++i) { if ((i < (max_chars - input_text_width) && i % (max_operand_text_width + 1) == 0) || i == max_chars - 1) { os << "+"; } else { os << "-"; } } os << std::endl; }; if (m_pretty_print) { print_row_separator(); for (const auto &s : m_operands) { os << "|"; os << std::setw(max_operand_text_width) << s; } os << "|" << std::setw(input_text_width) << input << "|" << std::endl; print_row_separator(); } unsigned long num_permutations = 1; unsigned long interval_count = 0; for (const auto &operand : m_operands) { if (operand != symbol::TRUE && operand != symbol::FALSE) { num_permutations *= 2; ++interval_count; } } bool *intervals = new bool[interval_count]; for (unsigned long i = 0; i < interval_count; ++i) { intervals[i] = true; } unsigned long *counters = new unsigned long[interval_count]; counters[0] = 1; for (unsigned long i = 1; i < interval_count; ++i) { counters[i] = counters[i - 1] * 2; } std::map<std::string, bool> map; for (unsigned long i = 0; i < num_permutations; ++i) { for (unsigned long j = 0; j < interval_count; ++j) { if (i % counters[j] == 0) { intervals[j] = !intervals[j]; } } map.clear(); int index = 0; for (const auto &operand : m_operands) { if (operand == symbol::FALSE) { map[operand] = false; } else if (operand == symbol::TRUE) { map[operand] = true; } else { map[operand] = intervals[index]; ++index; } } bool result = solve_helper(map, m_expression_tree); if (m_pretty_print) { os << "|"; for (unsigned long j = 0; j < operand_count; ++j) { os << std::setw(max_operand_text_width) << std::internal << map[m_operands[j]]; os << "|"; } os << std::setw(input_text_width) << result; os << "|"; } else { for (unsigned long j = 0; j < operand_count; ++j) { os << map[m_operands[j]]; } os << result; } os << std::endl; } if (m_pretty_print) { print_row_separator(); } delete[] counters; delete[] intervals; } bool TruthTable::solve_helper(std::map<std::string, bool> &value_map, TruthTable::Node *node) { if (is_operand(node->value)) { return value_map[node->value]; } bool result_left = solve_helper(value_map, node->left); bool result_right = false; if (node->right) { result_right = solve_helper(value_map, node->right); } return calculate(result_left, m_operator_map[node->value], result_right); } void TruthTable::expression_tree_to_string(TruthTable::Node *node, std::string &result, int depth) { if (node) { bool can_print_paren = (node->left || node->right) && depth > 0; if (can_print_paren) { result += symbol::LEFT_PAREN; } expression_tree_to_string(node->right, result, depth + 1); result += node->value; expression_tree_to_string(node->left, result, depth + 1); if (can_print_paren) { result += symbol::RIGHT_PAREN; } } } template <typename T> void TruthTable::print_container(const T &v) { auto itr = std::begin(v); if (itr != std::end(v)) { while (itr != std::end(v)) { std::cout << *itr; if (itr + 1 != std::end(v)) { std::cout << ", "; } ++itr; } std::cout << std::endl; } } <|endoftext|>
<commit_before>#include "libtorrent/udp_socket.hpp" #include "libtorrent/connection_queue.hpp" #include <stdlib.h> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <boost/array.hpp> #include <asio/read.hpp> using namespace libtorrent; udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c , connection_queue& cc) : m_callback(c) , m_ipv4_sock(ios) , m_ipv6_sock(ios) , m_bind_port(0) , m_socks5_sock(ios) , m_connection_ticket(-1) , m_cc(cc) , m_resolver(ios) , m_tunnel_packets(false) { } void udp_socket::send(udp::endpoint const& ep, char const* p, int len) { if (m_tunnel_packets) { // send udp packets through SOCKS5 server wrap(ep, p, len); return; } asio::error_code ec; if (ep.address().is_v4() && m_ipv4_sock.is_open()) m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec); else m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec); } void udp_socket::on_read(udp::socket* s, asio::error_code const& e, std::size_t bytes_transferred) { if (e) return; if (!m_callback) return; if (s == &m_ipv4_sock) { #ifndef BOOST_NO_EXCEPTIONS try { #endif if (m_tunnel_packets && m_v4_ep == m_proxy_addr) unwrap(m_v4_buf, bytes_transferred); else m_callback(m_v4_ep, m_v4_buf, bytes_transferred); #ifndef BOOST_NO_EXCEPTIONS } catch(std::exception&) {} #endif s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf)) , m_v4_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2)); } else { #ifndef BOOST_NO_EXCEPTIONS try { #endif if (m_tunnel_packets && m_v6_ep == m_proxy_addr) unwrap(m_v6_buf, bytes_transferred); else m_callback(m_v6_ep, m_v6_buf, bytes_transferred); #ifndef BOOST_NO_EXCEPTIONS } catch(std::exception&) {} #endif s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf)) , m_v6_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2)); } } void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len) { using namespace libtorrent::detail; char header[20]; char* h = header; write_uint16(0, h); // reserved write_uint8(0, h); // fragment write_uint8(ep.address().is_v4()?1:4, h); // atyp write_address(ep.address(), h); write_uint16(ep.port(), h); boost::array<asio::const_buffer, 2> iovec; iovec[0] = asio::const_buffer(header, h - header); iovec[1] = asio::const_buffer(p, len); asio::error_code ec; if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open()) m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec); else m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec); } // unwrap the UDP packet from the SOCKS5 header void udp_socket::unwrap(char const* buf, int size) { using namespace libtorrent::detail; // the minimum socks5 header size if (size <= 10) return; char const* p = buf; p += 2; // reserved int frag = read_uint8(p); // fragmentation is not supported if (frag != 0) return; udp::endpoint sender; int atyp = read_uint8(p); if (atyp == 1) { // IPv4 sender.address(address_v4(read_uint32(p))); sender.port(read_uint16(p)); } else if (atyp == 4) { // IPv6 TORRENT_ASSERT(false && "not supported yet"); } else { // domain name not supported return; } m_callback(sender, p, size - (p - buf)); } void udp_socket::close() { m_ipv4_sock.close(); m_ipv6_sock.close(); m_socks5_sock.close(); m_callback.clear(); if (m_connection_ticket >= 0) { m_cc.done(m_connection_ticket); m_connection_ticket = -1; } } void udp_socket::bind(int port) { asio::error_code ec; if (m_ipv4_sock.is_open()) m_ipv4_sock.close(); if (m_ipv6_sock.is_open()) m_ipv6_sock.close(); m_ipv4_sock.open(udp::v4(), ec); if (!ec) { m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec); m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf)) , m_v4_ep, boost::bind(&udp_socket::on_read, this, &m_ipv4_sock, _1, _2)); } m_ipv6_sock.open(udp::v6(), ec); if (!ec) { m_ipv6_sock.set_option(v6only(true), ec); m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec); m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf)) , m_v6_ep, boost::bind(&udp_socket::on_read, this, &m_ipv6_sock, _1, _2)); } m_bind_port = port; } void udp_socket::set_proxy_settings(proxy_settings const& ps) { m_socks5_sock.close(); m_tunnel_packets = false; m_proxy_settings = ps; if (ps.type == proxy_settings::socks5 || ps.type == proxy_settings::socks5_pw) { // connect to socks5 server and open up the UDP tunnel tcp::resolver::query q(ps.hostname , boost::lexical_cast<std::string>(ps.port)); m_resolver.async_resolve(q, boost::bind( &udp_socket::on_name_lookup, this, _1, _2)); } } void udp_socket::on_name_lookup(asio::error_code const& e, tcp::resolver::iterator i) { if (e) return; m_proxy_addr.address(i->endpoint().address()); m_proxy_addr.port(i->endpoint().port()); m_cc.enqueue(boost::bind(&udp_socket::on_connect, this, _1) , boost::bind(&udp_socket::on_timeout, this), seconds(10)); } void udp_socket::on_timeout() { m_socks5_sock.close(); m_connection_ticket = -1; } void udp_socket::on_connect(int ticket) { m_connection_ticket = ticket; asio::error_code ec; m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec); m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port()) , boost::bind(&udp_socket::on_connected, this, _1)); } void udp_socket::on_connected(asio::error_code const& e) { m_cc.done(m_connection_ticket); m_connection_ticket = -1; if (e) return; using namespace libtorrent::detail; // send SOCKS5 authentication methods char* p = &m_tmp_buf[0]; write_uint8(5, p); // SOCKS VERSION 5 if (m_proxy_settings.username.empty() || m_proxy_settings.type == proxy_settings::socks5) { write_uint8(1, p); // 1 authentication method (no auth) write_uint8(0, p); // no authentication } else { write_uint8(2, p); // 2 authentication methods write_uint8(0, p); // no authentication write_uint8(2, p); // username/password } asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf) , boost::bind(&udp_socket::handshake1, this, _1)); } void udp_socket::handshake1(asio::error_code const& e) { if (e) return; asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2) , boost::bind(&udp_socket::handshake2, this, _1)); } void udp_socket::handshake2(asio::error_code const& e) { if (e) return; using namespace libtorrent::detail; char* p = &m_tmp_buf[0]; int version = read_uint8(p); int method = read_uint8(p); if (version < 5) return; if (method == 0) { socks_forward_udp(); } else if (method == 2) { if (m_proxy_settings.username.empty()) { m_socks5_sock.close(); return; } // start sub-negotiation char* p = &m_tmp_buf[0]; write_uint8(1, p); write_uint8(m_proxy_settings.username.size(), p); write_string(m_proxy_settings.username, p); write_uint8(m_proxy_settings.password.size(), p); write_string(m_proxy_settings.password, p); asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf) , boost::bind(&udp_socket::handshake3, this, _1)); } else { m_socks5_sock.close(); return; } } void udp_socket::handshake3(asio::error_code const& e) { if (e) return; asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2) , boost::bind(&udp_socket::handshake4, this, _1)); } void udp_socket::handshake4(asio::error_code const& e) { if (e) return; using namespace libtorrent::detail; char* p = &m_tmp_buf[0]; int version = read_uint8(p); int status = read_uint8(p); if (version != 1) return; if (status != 0) return; socks_forward_udp(); } void udp_socket::socks_forward_udp() { using namespace libtorrent::detail; // send SOCKS5 UDP command char* p = &m_tmp_buf[0]; write_uint8(5, p); // SOCKS VERSION 5 write_uint8(3, p); // UDP ASSOCIATE command write_uint8(0, p); // reserved write_uint8(0, p); // ATYP IPv4 write_uint32(0, p); // IP any write_uint16(m_bind_port, p); asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf) , boost::bind(&udp_socket::connect1, this, _1)); } void udp_socket::connect1(asio::error_code const& e) { if (e) return; asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10) , boost::bind(&udp_socket::connect2, this, _1)); } void udp_socket::connect2(asio::error_code const& e) { if (e) return; using namespace libtorrent::detail; char* p = &m_tmp_buf[0]; int version = read_uint8(p); // VERSION int status = read_uint8(p); // STATUS read_uint8(p); // RESERVED int atyp = read_uint8(p); // address type if (version != 5) return; if (status != 0) return; if (atyp == 1) { m_proxy_addr.address(address_v4(read_uint32(p))); m_proxy_addr.port(read_uint16(p)); } else { // in this case we need to read more data from the socket TORRENT_ASSERT(false && "not implemented yet!"); } m_tunnel_packets = true; } <commit_msg>made udp_socket not use exception<commit_after>#include "libtorrent/udp_socket.hpp" #include "libtorrent/connection_queue.hpp" #include <stdlib.h> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #include <boost/array.hpp> #include <asio/read.hpp> using namespace libtorrent; udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c , connection_queue& cc) : m_callback(c) , m_ipv4_sock(ios) , m_ipv6_sock(ios) , m_bind_port(0) , m_socks5_sock(ios) , m_connection_ticket(-1) , m_cc(cc) , m_resolver(ios) , m_tunnel_packets(false) { } void udp_socket::send(udp::endpoint const& ep, char const* p, int len) { if (m_tunnel_packets) { // send udp packets through SOCKS5 server wrap(ep, p, len); return; } asio::error_code ec; if (ep.address().is_v4() && m_ipv4_sock.is_open()) m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec); else m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec); } void udp_socket::on_read(udp::socket* s, asio::error_code const& e, std::size_t bytes_transferred) { if (e) return; if (!m_callback) return; if (s == &m_ipv4_sock) { #ifndef BOOST_NO_EXCEPTIONS try { #endif if (m_tunnel_packets && m_v4_ep == m_proxy_addr) unwrap(m_v4_buf, bytes_transferred); else m_callback(m_v4_ep, m_v4_buf, bytes_transferred); #ifndef BOOST_NO_EXCEPTIONS } catch(std::exception&) {} #endif s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf)) , m_v4_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2)); } else { #ifndef BOOST_NO_EXCEPTIONS try { #endif if (m_tunnel_packets && m_v6_ep == m_proxy_addr) unwrap(m_v6_buf, bytes_transferred); else m_callback(m_v6_ep, m_v6_buf, bytes_transferred); #ifndef BOOST_NO_EXCEPTIONS } catch(std::exception&) {} #endif s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf)) , m_v6_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2)); } } void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len) { using namespace libtorrent::detail; char header[20]; char* h = header; write_uint16(0, h); // reserved write_uint8(0, h); // fragment write_uint8(ep.address().is_v4()?1:4, h); // atyp write_address(ep.address(), h); write_uint16(ep.port(), h); boost::array<asio::const_buffer, 2> iovec; iovec[0] = asio::const_buffer(header, h - header); iovec[1] = asio::const_buffer(p, len); asio::error_code ec; if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open()) m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec); else m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec); } // unwrap the UDP packet from the SOCKS5 header void udp_socket::unwrap(char const* buf, int size) { using namespace libtorrent::detail; // the minimum socks5 header size if (size <= 10) return; char const* p = buf; p += 2; // reserved int frag = read_uint8(p); // fragmentation is not supported if (frag != 0) return; udp::endpoint sender; int atyp = read_uint8(p); if (atyp == 1) { // IPv4 sender.address(address_v4(read_uint32(p))); sender.port(read_uint16(p)); } else if (atyp == 4) { // IPv6 TORRENT_ASSERT(false && "not supported yet"); } else { // domain name not supported return; } m_callback(sender, p, size - (p - buf)); } void udp_socket::close() { asio::error_code ec; m_ipv4_sock.close(ec); m_ipv6_sock.close(ec); m_socks5_sock.close(ec); m_callback.clear(); if (m_connection_ticket >= 0) { m_cc.done(m_connection_ticket); m_connection_ticket = -1; } } void udp_socket::bind(int port) { asio::error_code ec; if (m_ipv4_sock.is_open()) m_ipv4_sock.close(ec); if (m_ipv6_sock.is_open()) m_ipv6_sock.close(ec); m_ipv4_sock.open(udp::v4(), ec); if (!ec) { m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec); m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf)) , m_v4_ep, boost::bind(&udp_socket::on_read, this, &m_ipv4_sock, _1, _2)); } m_ipv6_sock.open(udp::v6(), ec); if (!ec) { m_ipv6_sock.set_option(v6only(true), ec); m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec); m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf)) , m_v6_ep, boost::bind(&udp_socket::on_read, this, &m_ipv6_sock, _1, _2)); } m_bind_port = port; } void udp_socket::set_proxy_settings(proxy_settings const& ps) { asio::error_code ec; m_socks5_sock.close(ec); m_tunnel_packets = false; m_proxy_settings = ps; if (ps.type == proxy_settings::socks5 || ps.type == proxy_settings::socks5_pw) { // connect to socks5 server and open up the UDP tunnel tcp::resolver::query q(ps.hostname , boost::lexical_cast<std::string>(ps.port)); m_resolver.async_resolve(q, boost::bind( &udp_socket::on_name_lookup, this, _1, _2)); } } void udp_socket::on_name_lookup(asio::error_code const& e, tcp::resolver::iterator i) { if (e) return; m_proxy_addr.address(i->endpoint().address()); m_proxy_addr.port(i->endpoint().port()); m_cc.enqueue(boost::bind(&udp_socket::on_connect, this, _1) , boost::bind(&udp_socket::on_timeout, this), seconds(10)); } void udp_socket::on_timeout() { asio::error_code ec; m_socks5_sock.close(ec); m_connection_ticket = -1; } void udp_socket::on_connect(int ticket) { m_connection_ticket = ticket; asio::error_code ec; m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec); m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port()) , boost::bind(&udp_socket::on_connected, this, _1)); } void udp_socket::on_connected(asio::error_code const& e) { m_cc.done(m_connection_ticket); m_connection_ticket = -1; if (e) return; using namespace libtorrent::detail; // send SOCKS5 authentication methods char* p = &m_tmp_buf[0]; write_uint8(5, p); // SOCKS VERSION 5 if (m_proxy_settings.username.empty() || m_proxy_settings.type == proxy_settings::socks5) { write_uint8(1, p); // 1 authentication method (no auth) write_uint8(0, p); // no authentication } else { write_uint8(2, p); // 2 authentication methods write_uint8(0, p); // no authentication write_uint8(2, p); // username/password } asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf) , boost::bind(&udp_socket::handshake1, this, _1)); } void udp_socket::handshake1(asio::error_code const& e) { if (e) return; asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2) , boost::bind(&udp_socket::handshake2, this, _1)); } void udp_socket::handshake2(asio::error_code const& e) { if (e) return; using namespace libtorrent::detail; char* p = &m_tmp_buf[0]; int version = read_uint8(p); int method = read_uint8(p); if (version < 5) return; if (method == 0) { socks_forward_udp(); } else if (method == 2) { if (m_proxy_settings.username.empty()) { asio::error_code ec; m_socks5_sock.close(ec); return; } // start sub-negotiation char* p = &m_tmp_buf[0]; write_uint8(1, p); write_uint8(m_proxy_settings.username.size(), p); write_string(m_proxy_settings.username, p); write_uint8(m_proxy_settings.password.size(), p); write_string(m_proxy_settings.password, p); asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf) , boost::bind(&udp_socket::handshake3, this, _1)); } else { asio::error_code ec; m_socks5_sock.close(ec); return; } } void udp_socket::handshake3(asio::error_code const& e) { if (e) return; asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2) , boost::bind(&udp_socket::handshake4, this, _1)); } void udp_socket::handshake4(asio::error_code const& e) { if (e) return; using namespace libtorrent::detail; char* p = &m_tmp_buf[0]; int version = read_uint8(p); int status = read_uint8(p); if (version != 1) return; if (status != 0) return; socks_forward_udp(); } void udp_socket::socks_forward_udp() { using namespace libtorrent::detail; // send SOCKS5 UDP command char* p = &m_tmp_buf[0]; write_uint8(5, p); // SOCKS VERSION 5 write_uint8(3, p); // UDP ASSOCIATE command write_uint8(0, p); // reserved write_uint8(0, p); // ATYP IPv4 write_uint32(0, p); // IP any write_uint16(m_bind_port, p); asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf) , boost::bind(&udp_socket::connect1, this, _1)); } void udp_socket::connect1(asio::error_code const& e) { if (e) return; asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10) , boost::bind(&udp_socket::connect2, this, _1)); } void udp_socket::connect2(asio::error_code const& e) { if (e) return; using namespace libtorrent::detail; char* p = &m_tmp_buf[0]; int version = read_uint8(p); // VERSION int status = read_uint8(p); // STATUS read_uint8(p); // RESERVED int atyp = read_uint8(p); // address type if (version != 5) return; if (status != 0) return; if (atyp == 1) { m_proxy_addr.address(address_v4(read_uint32(p))); m_proxy_addr.port(read_uint16(p)); } else { // in this case we need to read more data from the socket TORRENT_ASSERT(false && "not implemented yet!"); } m_tunnel_packets = true; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ /* ************************************************************************** */ /* User Pool */ /* ************************************************************************** */ #include "UserPool.h" #include "NebulaLog.h" #include "Nebula.h" #include "AuthManager.h" #include <fstream> #include <sys/types.h> #include <pwd.h> #include <stdlib.h> /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::init_cb(void *nil, int num, char **values, char **names) { if ( num == 0 || values == 0 || values[0] == 0 ) { return -1; } known_users.insert(make_pair(values[1],atoi(values[0]))); return 0; } /* -------------------------------------------------------------------------- */ UserPool::UserPool(SqlDB * db):PoolSQL(db,User::table) { ostringstream sql; set_callback(static_cast<Callbackable::Callback>(&UserPool::init_cb)); sql << "SELECT oid,user_name FROM " << User::table; db->exec(sql, this); unset_callback(); if ((int) known_users.size() == 0) { // User oneadmin needs to be added in the bootstrap int one_uid = -1; ostringstream oss; string one_token; string one_name; string one_pass; string one_auth_file; const char * one_auth; ifstream file; one_auth = getenv("ONE_AUTH"); if (!one_auth) { struct passwd * pw_ent; pw_ent = getpwuid(getuid()); if ((pw_ent != NULL) && (pw_ent->pw_dir != NULL)) { one_auth_file = pw_ent->pw_dir; one_auth_file += "/.one/one_auth"; one_auth = one_auth_file.c_str(); } else { oss << "Could not get one_auth file location"; } } file.open(one_auth); if (file.good()) { getline(file,one_token); if (file.fail()) { oss << "Error reading file: " << one_auth; } else { if (User::split_secret(one_token,one_name,one_pass) == 0) { string sha1_pass = User::sha1_digest(one_pass); allocate(&one_uid, one_name, sha1_pass, true); } else { oss << "Wrong format must be <username>:<password>"; } } } else { oss << "Cloud not open file: " << one_auth; } file.close(); if (one_uid != 0) { NebulaLog::log("ONE",Log::ERROR,oss); throw; } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::allocate ( int * oid, string username, string password, bool enabled) { User * user; // Build a new User object user = new User(-1, username, password, enabled); // Insert the Object in the pool *oid = PoolSQL::allocate(user); if (*oid != -1) { // Add the user to the map of known_users known_users.insert(make_pair(username,*oid)); } return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::authenticate(string& session) { map<string, int>::iterator index; string username; string password; int user_id = -1; // session holds username:password if ( User::split_secret(session,username,password) == 0 ) { index = known_users.find(username); if ( index != known_users.end() ) { User * user = get((int)index->second,true); if ( user != 0 ) { AuthRequest ar(user->get_uid()); Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); ar.add_authenticate(user->username, user->password, password); if (authm == 0) { if (ar.plain_authenticate()) { user_id = user->get_uid(); } } else { authm->trigger(AuthManager::AUTHENTICATE,&ar); ar.wait(); if (ar.result==true) { user_id = user->get_uid(); } else { ostringstream oss; oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); } } user->unlock(); } } } return user_id; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::authorize(AuthRequest& ar) { Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); int rc = -1; if (authm == 0) { if (ar.plain_authorize()) { rc = 0; } } else { authm->trigger(AuthManager::AUTHORIZE,&ar); ar.wait(); if (ar.result==true) { rc = 0; } else { ostringstream oss; oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); } } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::dump_cb(void * _oss, int num, char **values, char **names) { ostringstream * oss; oss = static_cast<ostringstream *>(_oss); return User::dump(*oss, num, values, names); } /* -------------------------------------------------------------------------- */ int UserPool::dump(ostringstream& oss, const string& where) { int rc; ostringstream cmd; oss << "<USER_POOL>"; set_callback(static_cast<Callbackable::Callback>(&UserPool::dump_cb), static_cast<void *>(&oss)); cmd << "SELECT * FROM " << User::table; if ( !where.empty() ) { cmd << " WHERE " << where; } rc = db->exec(cmd, this); unset_callback(); oss << "</USER_POOL>"; return rc; } <commit_msg>feature #203: New authenticate.<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ /* ************************************************************************** */ /* User Pool */ /* ************************************************************************** */ #include "UserPool.h" #include "NebulaLog.h" #include "Nebula.h" #include "AuthManager.h" #include <fstream> #include <sys/types.h> #include <pwd.h> #include <stdlib.h> /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::init_cb(void *nil, int num, char **values, char **names) { if ( num == 0 || values == 0 || values[0] == 0 ) { return -1; } known_users.insert(make_pair(values[1],atoi(values[0]))); return 0; } /* -------------------------------------------------------------------------- */ UserPool::UserPool(SqlDB * db):PoolSQL(db,User::table) { ostringstream sql; set_callback(static_cast<Callbackable::Callback>(&UserPool::init_cb)); sql << "SELECT oid,user_name FROM " << User::table; db->exec(sql, this); unset_callback(); if ((int) known_users.size() == 0) { // User oneadmin needs to be added in the bootstrap int one_uid = -1; ostringstream oss; string one_token; string one_name; string one_pass; string one_auth_file; const char * one_auth; ifstream file; one_auth = getenv("ONE_AUTH"); if (!one_auth) { struct passwd * pw_ent; pw_ent = getpwuid(getuid()); if ((pw_ent != NULL) && (pw_ent->pw_dir != NULL)) { one_auth_file = pw_ent->pw_dir; one_auth_file += "/.one/one_auth"; one_auth = one_auth_file.c_str(); } else { oss << "Could not get one_auth file location"; } } file.open(one_auth); if (file.good()) { getline(file,one_token); if (file.fail()) { oss << "Error reading file: " << one_auth; } else { if (User::split_secret(one_token,one_name,one_pass) == 0) { string sha1_pass = User::sha1_digest(one_pass); allocate(&one_uid, one_name, sha1_pass, true); } else { oss << "Wrong format must be <username>:<password>"; } } } else { oss << "Cloud not open file: " << one_auth; } file.close(); if (one_uid != 0) { NebulaLog::log("ONE",Log::ERROR,oss); throw; } } } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::allocate ( int * oid, string username, string password, bool enabled) { User * user; // Build a new User object user = new User(-1, username, password, enabled); // Insert the Object in the pool *oid = PoolSQL::allocate(user); if (*oid != -1) { // Add the user to the map of known_users known_users.insert(make_pair(username,*oid)); } return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::authenticate(string& session) { map<string, int>::iterator index; User * user = 0; string username; string secret, u_pass; int uid; int user_id = -1; int rc; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); rc = User::split_secret(session,username,secret); if ( rc != 0 ) { return -1; } index = known_users.find(username); if ( index != known_users.end() ) //User known to OpenNebula { user = get((int)index->second,true); if ( user == 0 ) { return -1; } u_pass = user->password; uid = user->get_uid(); user->unlock(); } else //External User { u_pass = "-"; uid = -1; } AuthRequest ar(uid); ar.add_authenticate(username,u_pass,secret); if ( uid == 0 ) //oneadmin { if (ar.plain_authenticate()) { user_id = 0; } } else if (authm == 0) //plain auth { if ( user != 0 && ar.plain_authenticate()) //no plain for external users { user_id = uid; } } else //use the driver { authm->trigger(AuthManager::AUTHENTICATE,&ar); ar.wait(); if (ar.result==true) { if ( user != 0 ) //knwon user_id { user_id = uid; } else //External user, user_id in driver message { istringstream is(ar.message); if ( is.good() ) { is >> user_id; } if ( is.fail() || user_id <= 0 ) { ar.message = "Can't convert user_id from driver"; user_id = -1; } } } if (user_id == -1) { ostringstream oss; oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); } } return user_id; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::authorize(AuthRequest& ar) { Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); int rc = -1; if (authm == 0) { if (ar.plain_authorize()) { rc = 0; } } else { authm->trigger(AuthManager::AUTHORIZE,&ar); ar.wait(); if (ar.result==true) { rc = 0; } else { ostringstream oss; oss << "Auth Error: " << ar.message; NebulaLog::log("AuM",Log::ERROR,oss); } } return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int UserPool::dump_cb(void * _oss, int num, char **values, char **names) { ostringstream * oss; oss = static_cast<ostringstream *>(_oss); return User::dump(*oss, num, values, names); } /* -------------------------------------------------------------------------- */ int UserPool::dump(ostringstream& oss, const string& where) { int rc; ostringstream cmd; oss << "<USER_POOL>"; set_callback(static_cast<Callbackable::Callback>(&UserPool::dump_cb), static_cast<void *>(&oss)); cmd << "SELECT * FROM " << User::table; if ( !where.empty() ) { cmd << " WHERE " << where; } rc = db->exec(cmd, this); unset_callback(); oss << "</USER_POOL>"; return rc; } <|endoftext|>
<commit_before>#include "webcam.hpp" #include <chrono> using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } unsigned long long getMilliseconds() { return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1); } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } unsigned long long times[100]; int f = 0; for (int i=0; i<100; i++) times[i] = 0; ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; unsigned long long timenow = getMilliseconds(); CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); while (keepGoing) { image = cvQueryFrame(capture); times[0] = getMilliseconds() - timenow; timenow = getMilliseconds(); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); times[1] = getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask filters out areas which have not changed much // this is horrible with new background; redo it Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); imshow("pre morph", flow); // morphFast(flow); equalizeHist(flow, flow); imshow("post morph", flow); threshold(flow, flow, 60, 1, THRESH_BINARY); imshow("flow mask", gray.mul(flow)); times[2] = getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark(height, width, CV_8UC1, 1); equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); times[3] = getMilliseconds() - timenow; timenow = getMilliseconds(); // combine mask with its opening Mat mask = flow.mul(kindofdark); Mat smallMask0, smallMask1; resize(mask, smallMask0, Size(width/5,height/5)); Mat smallKernel = ellipticKernel(69,79); erode(smallMask0, smallMask1, smallKernel); dilate(smallMask1, smallMask1, smallKernel); bitwise_and(smallMask0, smallMask1, smallMask1); resize(smallMask1, mask, Size(width, height)); // imshow("morph mask", gray.mul(mask)); times[4] = getMilliseconds() - timenow; timenow = getMilliseconds(); // run haar classifier on nonflow parts of image vector<Rect> mouths; int scale = 3; Mat classifyThis; equalizeHist(gray, gray); resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale)); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE); Mat rectImage(height, width, CV_8UC1, Scalar(0)); for (size_t i=0; i<mouths.size(); i++) { Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale); Mat newRect(height, width, CV_8UC1, Scalar(0)); rectangle(newRect, scaled, Scalar(1), CV_FILLED); rectImage += newRect; } double minVal, maxVal;//ignore minVal, it'll be 0 minMaxLoc(rectImage, &minVal, &maxVal); Mat recThresh; threshold(rectImage, recThresh, maxVal*0.8, 1, THRESH_BINARY); bitwise_and(recThresh, mask, mask); times[5] = getMilliseconds() - timenow; timenow = getMilliseconds(); // imshow("mouth", recThresh.mul(gray)); /* Moments lol = moments(recThresh, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); */ // update background with new morph mask Mat mask_; subtract(1, mask ,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2); times[6] = getMilliseconds() - timenow; timenow = getMilliseconds(); // imshow("bg", background); for (int i=0; i<7; i++) { printf("%llu , ", times[i]); } printf("\n"); keepGoing = (waitKey(1)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" #include <chrono> using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } unsigned long long getMilliseconds() { return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1); } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } unsigned long long times[100]; int f = 0; for (int i=0; i<100; i++) times[i] = 0; ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; unsigned long long timenow = getMilliseconds(); CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); while (keepGoing) { image = cvQueryFrame(capture); times[0] = getMilliseconds() - timenow; timenow = getMilliseconds(); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); times[1] = getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask filters out areas which have not changed much // this is horrible with new background; redo it Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); imshow("pre morph", flow); // morphFast(flow); imshow("post morph", flow); threshold(flow, flow, tracker1*3, 1, THRESH_BINARY); imshow("flow mask", gray.mul(flow)); times[2] = getMilliseconds() - timenow; timenow = getMilliseconds(); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark(height, width, CV_8UC1, 1); equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); times[3] = getMilliseconds() - timenow; timenow = getMilliseconds(); // combine mask with its opening Mat mask = flow.mul(kindofdark); Mat smallMask0, smallMask1; resize(mask, smallMask0, Size(width/5,height/5)); Mat smallKernel = ellipticKernel(69,79); erode(smallMask0, smallMask1, smallKernel); dilate(smallMask1, smallMask1, smallKernel); bitwise_and(smallMask0, smallMask1, smallMask1); resize(smallMask1, mask, Size(width, height)); // imshow("morph mask", gray.mul(mask)); times[4] = getMilliseconds() - timenow; timenow = getMilliseconds(); // run haar classifier on nonflow parts of image vector<Rect> mouths; int scale = 3; Mat classifyThis; equalizeHist(gray, gray); resize(gray.mul(mask), classifyThis, Size(width/scale,height/scale)); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 0, CV_HAAR_SCALE_IMAGE); Mat rectImage(height, width, CV_8UC1, Scalar(0)); for (size_t i=0; i<mouths.size(); i++) { Rect scaled(mouths[i].x*scale, mouths[i].y*scale, mouths[i].width*scale,mouths[i].height*scale); Mat newRect(height, width, CV_8UC1, Scalar(0)); rectangle(newRect, scaled, Scalar(1), CV_FILLED); rectImage += newRect; } double minVal, maxVal;//ignore minVal, it'll be 0 minMaxLoc(rectImage, &minVal, &maxVal); Mat recThresh; threshold(rectImage, recThresh, maxVal*0.8, 1, THRESH_BINARY); bitwise_and(recThresh, mask, mask); times[5] = getMilliseconds() - timenow; timenow = getMilliseconds(); // imshow("mouth", recThresh.mul(gray)); /* Moments lol = moments(recThresh, 1); circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); imshow("leimage", image); */ // update background with new morph mask Mat mask_; subtract(1, mask ,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_)/2 + blurred_img.mul(mask3_)/2); times[6] = getMilliseconds() - timenow; timenow = getMilliseconds(); // imshow("bg", background); for (int i=0; i<7; i++) { printf("%llu , ", times[i]); } printf("\n"); keepGoing = (waitKey(1)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; factor = factor + (1-(factor%2)); Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = getStructuringElement(MORPH_ELLIPSE,Size(factor,factor)); if (diler) { dilate(downsample, downsample, kernel); } else { erode(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray; cvtColor(image, gray, CV_RGB2GRAY); // this mask filters out areas with too many edges Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); // imshow("canny mask", gray.mul(canny)); // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; blur(image, flow, Size(50,50)); absdiff(flow, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); // imshow("flow mask", gray.mul(flow)); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); Mat mask = flow.mul(kindofdark).mul(canny); imshow("premask", gray.mul(mask)); waitKey(1); morphFast(mask, 100, tracker1+1-(tracker1%2), 0, 1); imshow("erode mask", gray.mul(mask)); waitKey(1); morphFast(mask, 100, tracker2+1-(tracker2%2), 0, 0); imshow("mask", gray.mul(mask)); // Moments lol = moments(mask, 1); // circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); // imshow("leimage", image); /* CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; Mat classifyThis; bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; factor = factor + (1-(factor%2)); Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = getStructuringElement(MORPH_ELLIPSE,Size(factor,factor)); if (diler) { dilate(downsample, downsample, kernel); } else { erode(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray; cvtColor(image, gray, CV_RGB2GRAY); // this mask filters out areas with too many edges Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); // imshow("canny mask", gray.mul(canny)); // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; blur(image, flow, Size(50,50)); absdiff(flow, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); // imshow("flow mask", gray.mul(flow)); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); // imshow("dark mask", gray.mul(kindofdark)); Mat mask = flow.mul(kindofdark).mul(canny); imshow("premask", gray.mul(mask)); waitKey(1); morphFast(mask, 100, tracker1+5-(tracker1%2), 0, 1); imshow("erode mask", gray.mul(mask)); waitKey(1); morphFast(mask, 100, tracker2+5-(tracker2%2), 0, 0); imshow("mask", gray.mul(mask)); // Moments lol = moments(mask, 1); // circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); // imshow("leimage", image); /* CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; Mat classifyThis; bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>#include <allegro.h> #include <cstring> #include <iostream> #include <sstream> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <vector> #include <map> #include "globals.h" #include "mugen_reader.h" #include "mugen_section.h" #include "mugen_item_content.h" #include "mugen_item.h" #include "mugen_character.h" #include "mugen_animation.h" #include "mugen_sprite.h" #include "mugen_stage.h" #include "util/bitmap.h" #include "util/funcs.h" #include "factory/font_render.h" #include "gui/keyinput_manager.h" #include "object/object.h" #include "object/player.h" #include "game.h" #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" using namespace std; static void showCollision( const std::vector< MugenArea > &vec, Bitmap &bmp, int x, int y, int color, int &start ){ int next = start; for( unsigned int i = 0; i < vec.size(); ++i ){ bmp.rectangle( x + vec[i].x1, y + vec[i].y1, x + vec[i].x2, y + vec[i].y2, color ); Font::getDefaultFont().printf( 15, 310 + next, color, bmp, "CLSN: x1(%i),y1(%i),x2(%i),y2(%i)",0, vec[i].x1,vec[i].y1,vec[i].x2,vec[i].y2 ); next+=10; } start = next; } static bool isArg( const char * s1, const char * s2 ){ return strcasecmp( s1, s2 ) == 0; } static void showOptions(){ Global::debug(0) << "M.U.G.E.N. Config Reader:" << endl; Global::debug(0) << "-f <file>: Load a M.U.G.E.N. config file and output to screen." << endl; Global::debug(0) << "-c <name>: Load a M.U.G.E.N. character and output some data about it.\n ie: 'data/mugen/chars/name' only pass name." << endl; Global::debug(0) << "-s <name>: Load a M.U.G.E.N. stage and output some data about it.\n ie: 'data/mugen/stages/name.def' only pass name.def." << endl; Global::debug(0) << "-l <level>: Set debug level." << endl; Global::debug(0) << endl; } /* testing testing 1 2 3 */ void testPCX(){ unsigned char data[1 << 18]; FILE * f = fopen("x.pcx", "r"); int length; length = fread(data, sizeof(char), 1<<18, f); Global::debug(0) << "Size is " << length << endl; fclose(f); Bitmap b = Bitmap::memoryPCX(data, length); // Bitmap b("x.pcx"); if (b.getError()){ Global::debug(0) << "what the hell" << endl; } Bitmap work(640, 480); work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0)); b.draw(0, 0, work); Global::debug(0) << "Width " << b.getWidth() << " Height " << b.getHeight() << endl; work.BlitToScreen(); Util::rest(3000); } void showCharacter(const string & ourFile){ set_color_depth(16); Bitmap::setGfxModeWindowed(640, 480); Global::debug(0) << "Trying to load character: " << ourFile << "..." << endl; MugenCharacter character( ourFile ); character.load(); Global::debug(0) << "Loaded character: \"" << character.getName() << "\" successfully." << endl; bool quit = false; bool animate = false; bool showClsn1 = false; bool showClsn2 = false; bool moveImage = false; map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); unsigned int currentAnim = 0; unsigned int lastAnim = character.getAnimations().size() -1; unsigned int currentFrame = 0; if (it->second->getFrames().size() == 0){ Global::debug(0) << "No frames!" << endl; exit(0); } Bitmap work( 640, 480 ); int xaxis = 260; int yaxis = 230; while( !quit ){ work.clear(); keyInputManager::update(); if( animate ) it->second->logic(); if( keyInputManager::keyState(keys::UP, true) ){ if( currentAnim < lastAnim ){ currentAnim++; it++; } currentFrame = 0; } else if( keyInputManager::keyState(keys::DOWN, true) ){ if( currentAnim > 0 ){ currentAnim--; it--; } currentFrame = 0; } else if( keyInputManager::keyState(keys::LEFT, true) && !animate){ it->second->forwardFrame(); currentFrame = it->second->getCurrentPosition(); } else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){ it->second->backFrame(); currentFrame = it->second->getCurrentPosition(); } else if( keyInputManager::keyState(keys::SPACE, true) ){ animate = !animate; } else if( keyInputManager::keyState('a', true) ){ showClsn1 = !showClsn1; it->second->toggleOffense(); } else if( keyInputManager::keyState('d', true) ){ showClsn2 = !showClsn2; it->second->toggleDefense(); } if( mouse_b & 1 )moveImage = true; else if( !(mouse_b & 1) )moveImage = false; quit |= keyInputManager::keyState(keys::ESC, true ); if( moveImage ){ xaxis=mouse_x; yaxis =mouse_y; } it->second->render( xaxis, yaxis, work ); int start = 10; if( showClsn2 )showCollision( it->second->getCurrentFrame()->defenseCollision, work, xaxis, yaxis, Bitmap::makeColor( 0,255,0 ), start ); if( showClsn1 )showCollision( it->second->getCurrentFrame()->attackCollision, work, xaxis, yaxis, Bitmap::makeColor( 255,0,0 ), start ); Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, "Current Animation: %i (%s), Frame: %i, xoffset: %i, yoffset: %i", 0, it->first, MugenAnimation::getName(MugenAnimationType(it->first)).c_str() ,currentFrame, it->second->getFrames()[currentFrame]->xoffset, it->second->getFrames()[currentFrame]->yoffset ); if(it->second->getCurrentFrame()->sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, "Length: %d | x-axis: %d | y-axis: %d | Group: %d | Image: %d",0, it->second->getCurrentFrame()->sprite->length, it->second->getCurrentFrame()->sprite->x, it->second->getCurrentFrame()->sprite->y, it->second->getCurrentFrame()->sprite->groupNumber, it->second->getCurrentFrame()->sprite->imageNumber); Font::getDefaultFont().printf( 15, 280, Bitmap::makeColor( 255, 255, 255 ), work, "Bitmap info - Width: %i Height: %i",0, it->second->getCurrentFrame()->bmp->getWidth(), it->second->getCurrentFrame()->bmp->getHeight() ); Font::getDefaultFont().printf( 15, 290, Bitmap::makeColor( 255, 255, 255 ), work, "(space) Animation enabled: %i",0, animate ); Font::getDefaultFont().printf( 15, 300, Bitmap::makeColor( 255, 255, 255 ), work, "(d) Show Defense enabled (green): %i",0, showClsn2 ); Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor( 255, 255, 255 ), work, "(a) Show Attack enabled (red): %i",0, showClsn1 ); show_mouse(work.getBitmap()); work.BlitToScreen(); Util::rest(1); } } void showStage(const string & ourFile){ set_color_depth(16); Bitmap::setGfxModeWindowed(640, 480); loadpng_init(); Global::debug(0) << "Trying to load stage: " << ourFile << "..." << endl; MugenStage stage( ourFile ); stage.load(); Global::debug(0) << "Loaded stage: \"" << stage.getName() << "\" successfully." << endl; bool quit = false; Bitmap work( 320, 240 ); Bitmap back( 640, 480 ); // Get players Object *p1 = new Player( "data/players/blanka/blanka.txt" );//Game::selectPlayer( false, "Pick player1" ); Object *p2 = new Player( "data/players/akuma/akuma.txt" );//Game::selectPlayer( false, "Pick player2" ); ((Player *)p1)->setInvincible( false ); //p1->setMap( remap ); ((Player *)p1)->testAnimation(); ((Player *)p2)->setInvincible( false ); //p2->setMap( remap ); ((Player *)p2)->testAnimation(); stage.addp1(p1); stage.addp2(p2); while( !quit ){ keyInputManager::update(); stage.logic(); if( keyInputManager::keyState(keys::UP, false) ){ stage.moveCamera(0,-1); } if( keyInputManager::keyState(keys::DOWN, false) ){ stage.moveCamera(0,1); } if( keyInputManager::keyState(keys::LEFT, false)){ stage.moveCamera(-1,0); } if( keyInputManager::keyState(keys::RIGHT, false)){ stage.moveCamera(1,0); } if( keyInputManager::keyState(keys::SPACE, true)){ stage.reset(); } if( keyInputManager::keyState(keys::ENTER, false)){ stage.Quake( 5 ); } quit |= keyInputManager::keyState(keys::ESC, true ); stage.render(&work); work.Stretch(back); Font::getDefaultFont().printf( 15, 220, Bitmap::makeColor( 255, 255, 255 ), back, "viewport x: %i | viewport y: %i",0, stage.getCameraX(), stage.getCameraY() ); Font::getDefaultFont().printf( 15, 230, Bitmap::makeColor( 255, 255, 255 ), back, "Frames: %i",0, stage.getTicks() ); back.BlitToScreen(); Util::rest(1); } } int main( int argc, char ** argv ){ if(argc <= 1){ showOptions(); return 0; } const char * FILE_ARG = "-f"; const char * CHAR_ARG = "-c"; const char * DEBUG_ARG = "-l"; const char * STAGE_ARG = "-s"; std::string ourFile; int configLoaded = -1; allegro_init(); install_timer(); install_keyboard(); install_mouse(); for ( int q = 1; q < argc; q++ ){ if ( isArg( argv[ q ], FILE_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = 0; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if ( isArg( argv[ q ], CHAR_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = 1; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if ( isArg( argv[ q ], STAGE_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = 2; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if (isArg(argv[q], DEBUG_ARG)){ q += 1; if (q < argc){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } else { Global::debug(0) << "No number given for " << DEBUG_ARG << endl; } } else { // WHAT? showOptions(); return 0; } } if( configLoaded == 0 ){ MugenReader reader( ourFile ); std::vector< MugenSection * > collection; try{ collection = reader.getCollection(); Global::debug(0) << endl << "---------------------------------------------------------" << endl; for( unsigned int i = 0; i < collection.size(); ++i ){ Global::debug(0) << collection[i]->getHeader() << endl; Global::debug(0) << "---------------------------------------------------------" << endl; while( collection[i]->hasItems() ){ MugenItemContent *content = collection[i]->getNext(); while( content->hasItems() ){ Global::debug(0) << content->getNext()->query(); if( content->hasItems() ) Global::debug(0) << ","; } Global::debug(0) << endl; } Global::debug(0) << "---------------------------------------------------------" << endl; } Global::debug(0) << endl; } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } } else if (configLoaded == 1){ try{ showCharacter(ourFile); } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } catch(...){ Global::debug(0) << "Unknown problem loading file" << endl; return 1; } } else if ( configLoaded == 2 ){ try{ showStage(ourFile); } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } catch(...){ Global::debug(0) << "Unknown problem loading file" << endl; return 1; } } else showOptions(); return 0; } <commit_msg>Reassigned reset to 'r' in test<commit_after>#include <allegro.h> #include <cstring> #include <iostream> #include <sstream> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <vector> #include <map> #include "globals.h" #include "mugen_reader.h" #include "mugen_section.h" #include "mugen_item_content.h" #include "mugen_item.h" #include "mugen_character.h" #include "mugen_animation.h" #include "mugen_sprite.h" #include "mugen_stage.h" #include "util/bitmap.h" #include "util/funcs.h" #include "factory/font_render.h" #include "gui/keyinput_manager.h" #include "object/object.h" #include "object/player.h" #include "game.h" #include "dumb/include/dumb.h" #include "dumb/include/aldumb.h" #include "loadpng/loadpng.h" using namespace std; static void showCollision( const std::vector< MugenArea > &vec, Bitmap &bmp, int x, int y, int color, int &start ){ int next = start; for( unsigned int i = 0; i < vec.size(); ++i ){ bmp.rectangle( x + vec[i].x1, y + vec[i].y1, x + vec[i].x2, y + vec[i].y2, color ); Font::getDefaultFont().printf( 15, 310 + next, color, bmp, "CLSN: x1(%i),y1(%i),x2(%i),y2(%i)",0, vec[i].x1,vec[i].y1,vec[i].x2,vec[i].y2 ); next+=10; } start = next; } static bool isArg( const char * s1, const char * s2 ){ return strcasecmp( s1, s2 ) == 0; } static void showOptions(){ Global::debug(0) << "M.U.G.E.N. Config Reader:" << endl; Global::debug(0) << "-f <file>: Load a M.U.G.E.N. config file and output to screen." << endl; Global::debug(0) << "-c <name>: Load a M.U.G.E.N. character and output some data about it.\n ie: 'data/mugen/chars/name' only pass name." << endl; Global::debug(0) << "-s <name>: Load a M.U.G.E.N. stage and output some data about it.\n ie: 'data/mugen/stages/name.def' only pass name.def." << endl; Global::debug(0) << "-l <level>: Set debug level." << endl; Global::debug(0) << endl; } /* testing testing 1 2 3 */ void testPCX(){ unsigned char data[1 << 18]; FILE * f = fopen("x.pcx", "r"); int length; length = fread(data, sizeof(char), 1<<18, f); Global::debug(0) << "Size is " << length << endl; fclose(f); Bitmap b = Bitmap::memoryPCX(data, length); // Bitmap b("x.pcx"); if (b.getError()){ Global::debug(0) << "what the hell" << endl; } Bitmap work(640, 480); work.circleFill(40, 40, 100, Bitmap::makeColor(255, 0, 0)); b.draw(0, 0, work); Global::debug(0) << "Width " << b.getWidth() << " Height " << b.getHeight() << endl; work.BlitToScreen(); Util::rest(3000); } void showCharacter(const string & ourFile){ set_color_depth(16); Bitmap::setGfxModeWindowed(640, 480); Global::debug(0) << "Trying to load character: " << ourFile << "..." << endl; MugenCharacter character( ourFile ); character.load(); Global::debug(0) << "Loaded character: \"" << character.getName() << "\" successfully." << endl; bool quit = false; bool animate = false; bool showClsn1 = false; bool showClsn2 = false; bool moveImage = false; map<int,MugenAnimation*>::const_iterator it = character.getAnimations().begin(); unsigned int currentAnim = 0; unsigned int lastAnim = character.getAnimations().size() -1; unsigned int currentFrame = 0; if (it->second->getFrames().size() == 0){ Global::debug(0) << "No frames!" << endl; exit(0); } Bitmap work( 640, 480 ); int xaxis = 260; int yaxis = 230; while( !quit ){ work.clear(); keyInputManager::update(); if( animate ) it->second->logic(); if( keyInputManager::keyState(keys::UP, true) ){ if( currentAnim < lastAnim ){ currentAnim++; it++; } currentFrame = 0; } else if( keyInputManager::keyState(keys::DOWN, true) ){ if( currentAnim > 0 ){ currentAnim--; it--; } currentFrame = 0; } else if( keyInputManager::keyState(keys::LEFT, true) && !animate){ it->second->forwardFrame(); currentFrame = it->second->getCurrentPosition(); } else if( keyInputManager::keyState(keys::RIGHT, true) && !animate){ it->second->backFrame(); currentFrame = it->second->getCurrentPosition(); } else if( keyInputManager::keyState(keys::SPACE, true) ){ animate = !animate; } else if( keyInputManager::keyState('a', true) ){ showClsn1 = !showClsn1; it->second->toggleOffense(); } else if( keyInputManager::keyState('d', true) ){ showClsn2 = !showClsn2; it->second->toggleDefense(); } if( mouse_b & 1 )moveImage = true; else if( !(mouse_b & 1) )moveImage = false; quit |= keyInputManager::keyState(keys::ESC, true ); if( moveImage ){ xaxis=mouse_x; yaxis =mouse_y; } it->second->render( xaxis, yaxis, work ); int start = 10; if( showClsn2 )showCollision( it->second->getCurrentFrame()->defenseCollision, work, xaxis, yaxis, Bitmap::makeColor( 0,255,0 ), start ); if( showClsn1 )showCollision( it->second->getCurrentFrame()->attackCollision, work, xaxis, yaxis, Bitmap::makeColor( 255,0,0 ), start ); Font::getDefaultFont().printf( 15, 250, Bitmap::makeColor( 255, 255, 255 ), work, "Current Animation: %i (%s), Frame: %i, xoffset: %i, yoffset: %i", 0, it->first, MugenAnimation::getName(MugenAnimationType(it->first)).c_str() ,currentFrame, it->second->getFrames()[currentFrame]->xoffset, it->second->getFrames()[currentFrame]->yoffset ); if(it->second->getCurrentFrame()->sprite!=0)Font::getDefaultFont().printf( 15, 270, Bitmap::makeColor( 255, 255, 255 ), work, "Length: %d | x-axis: %d | y-axis: %d | Group: %d | Image: %d",0, it->second->getCurrentFrame()->sprite->length, it->second->getCurrentFrame()->sprite->x, it->second->getCurrentFrame()->sprite->y, it->second->getCurrentFrame()->sprite->groupNumber, it->second->getCurrentFrame()->sprite->imageNumber); Font::getDefaultFont().printf( 15, 280, Bitmap::makeColor( 255, 255, 255 ), work, "Bitmap info - Width: %i Height: %i",0, it->second->getCurrentFrame()->bmp->getWidth(), it->second->getCurrentFrame()->bmp->getHeight() ); Font::getDefaultFont().printf( 15, 290, Bitmap::makeColor( 255, 255, 255 ), work, "(space) Animation enabled: %i",0, animate ); Font::getDefaultFont().printf( 15, 300, Bitmap::makeColor( 255, 255, 255 ), work, "(d) Show Defense enabled (green): %i",0, showClsn2 ); Font::getDefaultFont().printf( 15, 310, Bitmap::makeColor( 255, 255, 255 ), work, "(a) Show Attack enabled (red): %i",0, showClsn1 ); show_mouse(work.getBitmap()); work.BlitToScreen(); Util::rest(1); } } void showStage(const string & ourFile){ set_color_depth(16); Bitmap::setGfxModeWindowed(640, 480); loadpng_init(); Global::debug(0) << "Trying to load stage: " << ourFile << "..." << endl; MugenStage stage( ourFile ); stage.load(); Global::debug(0) << "Loaded stage: \"" << stage.getName() << "\" successfully." << endl; bool quit = false; Bitmap work( 320, 240 ); Bitmap back( 640, 480 ); // Get players Object *p1 = new Player( "data/players/blanka/blanka.txt" );//Game::selectPlayer( false, "Pick player1" ); Object *p2 = new Player( "data/players/akuma/akuma.txt" );//Game::selectPlayer( false, "Pick player2" ); ((Player *)p1)->setInvincible( false ); //p1->setMap( remap ); ((Player *)p1)->testAnimation(); ((Player *)p2)->setInvincible( false ); //p2->setMap( remap ); ((Player *)p2)->testAnimation(); stage.addp1(p1); stage.addp2(p2); while( !quit ){ keyInputManager::update(); stage.logic(); if( keyInputManager::keyState(keys::UP, false) ){ stage.moveCamera(0,-1); } if( keyInputManager::keyState(keys::DOWN, false) ){ stage.moveCamera(0,1); } if( keyInputManager::keyState(keys::LEFT, false)){ stage.moveCamera(-1,0); } if( keyInputManager::keyState(keys::RIGHT, false)){ stage.moveCamera(1,0); } if( keyInputManager::keyState('r', true)){ stage.reset(); } if( keyInputManager::keyState(keys::ENTER, false)){ stage.Quake( 5 ); } quit |= keyInputManager::keyState(keys::ESC, true ); stage.render(&work); work.Stretch(back); Font::getDefaultFont().printf( 15, 220, Bitmap::makeColor( 255, 255, 255 ), back, "viewport x: %i | viewport y: %i",0, stage.getCameraX(), stage.getCameraY() ); Font::getDefaultFont().printf( 15, 230, Bitmap::makeColor( 255, 255, 255 ), back, "Frames: %i",0, stage.getTicks() ); back.BlitToScreen(); Util::rest(1); } } int main( int argc, char ** argv ){ if(argc <= 1){ showOptions(); return 0; } const char * FILE_ARG = "-f"; const char * CHAR_ARG = "-c"; const char * DEBUG_ARG = "-l"; const char * STAGE_ARG = "-s"; std::string ourFile; int configLoaded = -1; allegro_init(); install_timer(); install_keyboard(); install_mouse(); for ( int q = 1; q < argc; q++ ){ if ( isArg( argv[ q ], FILE_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = 0; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if ( isArg( argv[ q ], CHAR_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = 1; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if ( isArg( argv[ q ], STAGE_ARG ) ){ q += 1; if ( q < argc ){ ourFile = std::string( argv[ q ] ); configLoaded = 2; } else{ Global::debug(0) << "Error no file given!" << endl; showOptions(); return 0; } } else if (isArg(argv[q], DEBUG_ARG)){ q += 1; if (q < argc){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } else { Global::debug(0) << "No number given for " << DEBUG_ARG << endl; } } else { // WHAT? showOptions(); return 0; } } if( configLoaded == 0 ){ MugenReader reader( ourFile ); std::vector< MugenSection * > collection; try{ collection = reader.getCollection(); Global::debug(0) << endl << "---------------------------------------------------------" << endl; for( unsigned int i = 0; i < collection.size(); ++i ){ Global::debug(0) << collection[i]->getHeader() << endl; Global::debug(0) << "---------------------------------------------------------" << endl; while( collection[i]->hasItems() ){ MugenItemContent *content = collection[i]->getNext(); while( content->hasItems() ){ Global::debug(0) << content->getNext()->query(); if( content->hasItems() ) Global::debug(0) << ","; } Global::debug(0) << endl; } Global::debug(0) << "---------------------------------------------------------" << endl; } Global::debug(0) << endl; } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } } else if (configLoaded == 1){ try{ showCharacter(ourFile); } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } catch(...){ Global::debug(0) << "Unknown problem loading file" << endl; return 1; } } else if ( configLoaded == 2 ){ try{ showStage(ourFile); } catch( MugenException &ex){ Global::debug(0) << "Problem loading file, error was: " << ex.getReason() << endl; return 1; } catch(...){ Global::debug(0) << "Unknown problem loading file" << endl; return 1; } } else showOptions(); return 0; } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2015 nabijaczleweli // 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 "scope.hpp" quickscope_wrapper::~quickscope_wrapper() { destructor(); } <commit_msg>Invoke the destructor only if there is one<commit_after>// The MIT License (MIT) // Copyright (c) 2015 nabijaczleweli // 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 "scope.hpp" quickscope_wrapper::~quickscope_wrapper() { if(destructor) destructor(); } <|endoftext|>
<commit_before>#ifndef TESTLEVEL #define TESTLEVEL #include <Annwvyn.h> #include "DemoUtils.hpp" using namespace Annwvyn; //Custom object: class Sinbad : public AnnGameObject { public: void postInit() override { setPosition(0, 0, -5); setScale(0.2f, 0.2f, 0.2f); setAnimation("Dance"); playAnimation(true); loopAnimation(true); } void atRefresh() override { //AnnDebug() << "Sinbad position is : " << getPosition(); //AnnDebug() << getName(); } }; class TestLevel : LEVEL { public: ///Construct the Level : void load() override { AnnGetEventManager()->addListener(goBackListener = std::make_shared<GoBackToDemoHub>()); //Set some ambient light AnnGetSceneryManager()->setExposure(1, -0.25, +0.25); AnnGetSceneryManager()->setSkyColor(AnnColor(0.05f, 0.45f, 1.f), 15.f); //We add our brand new 3D object auto MyObject = addGameObject("MyObject.mesh"); MyObject->setPosition(5, 1, 0); //We put it 5 meters to the right, and 1 meter up... //MyObject->setUpPhysics(); // <---- This activate the physics for the object as static geometry MyObject->setUpPhysics(100, convexShape); // <---- This activate the physics as a dynamic object. We need to tell the shape approximation to use. and a mass in Kg MyObject->attachScript("DummyBehavior2"); //The shape approximation is put at the Object CENTER POINT. The CENTER POINT should be at the object's bounding box CENTER before exporting from blender. MyObject->setFrictionCoef(0.84f); auto text = std::make_shared<Ann3DTextPlane>(1.0f, 0.5f, "Hello, Virtual World!\n\nTesting line wrap right now : a bc def ghij klmn opqr stuvw xyz ", 128, 96.0f, "LibSerif", "LiberationSerif-Regular.ttf"); //text->setTextAlign(text->ALIGN_CENTER); text->setBackgroundColor(AnnColor(0, 1, 0)); text->setPosition({ 0, 0.5f, -1 }); text->setBackgroundImage("background.png"); text->setMargin(0.1f); text->update(); addManualMovableObject(text); //Add other source of light auto Sun = addLightObject(); Sun->setType(AnnLightObject::ANN_LIGHT_DIRECTIONAL); Sun->setDirection(AnnVect3{ 0.5f, -1.5f, -2.25f }.normalisedCopy()); Sun->setPower(97.f); //Create objects and register them as content of the level auto S = AnnGetGameObjectManager()->createGameObject("Sinbad.mesh", "SuperSinbad", std::make_shared<Sinbad>()); levelContent.push_back(S); S->playSound("monster.wav", true, 1); S->attachScript("DummyBehavior"); S->setUpPhysics(10, boxShape); S->setFrictionCoef(0.75f); //Add water auto Water = addGameObject("environment/Water.mesh"); //Add the island auto Island = addGameObject("environment/Island.mesh"); Island->setUpPhysics(); Island->setFrictionCoef(0.75); //Add the sign auto Sign(addGameObject("environment/Sign.mesh")); Sign->setPosition(1, -0.15, -2); Sign->setUpPhysics(0, staticShape); Sign->setOrientation(Ogre::Quaternion(Ogre::Degree(-45), Ogre::Vector3::UNIT_Y)); //Put some music here //AnnGetAudioEngine()->playBGM("media/bgm/bensound-happyrock.ogg", 0.4); //Place the starting point AnnGetPlayer()->setPosition(AnnVect3::ZERO); AnnGetPlayer()->setOrientation(Ogre::Euler(0)); AnnGetPlayer()->resetPlayerPhysics(); AnnGetPlayer()->regroundOnPhysicsBody(1000, { 0, 100, 0 }); } void unload() override { AnnGetEventManager()->removeListener(goBackListener); //Do the normal unloading AnnLevel::unload(); } void runLogic() override { //AnnGetPlayer()->regroundOnPhysicsBody(1000, { 0, 100, 0 }); } private: std::shared_ptr<GoBackToDemoHub> goBackListener; }; class PhysicsDebugLevel : LEVEL { void load() override { //AnnGetSceneryManager()->setWorldBackgroundColor(AnnColor(0, 0, 0)); AnnGetPhysicsEngine()->getWorld()->setGravity(btVector3(0, 0, 0)); AnnGetPlayer()->setPosition(AnnVect3::ZERO); AnnGetPlayer()->resetPlayerPhysics(); } void runLogic() override { AnnDebug() << "Player position is : " << AnnGetPlayer()->getPosition(); } }; #endif //TESTLEVEL<commit_msg>give an unique name to the font in the pannel on the testlevel<commit_after>#ifndef TESTLEVEL #define TESTLEVEL #include <Annwvyn.h> #include "DemoUtils.hpp" using namespace Annwvyn; //Custom object: class Sinbad : public AnnGameObject { public: void postInit() override { setPosition(0, 0, -5); setScale(0.2f, 0.2f, 0.2f); setAnimation("Dance"); playAnimation(true); loopAnimation(true); } void atRefresh() override { //AnnDebug() << "Sinbad position is : " << getPosition(); //AnnDebug() << getName(); } }; class TestLevel : LEVEL { public: ///Construct the Level : void load() override { AnnGetEventManager()->addListener(goBackListener = std::make_shared<GoBackToDemoHub>()); //Set some ambient light AnnGetSceneryManager()->setExposure(1, -0.25, +0.25); AnnGetSceneryManager()->setSkyColor(AnnColor(0.05f, 0.45f, 1.f), 15.f); //We add our brand new 3D object auto MyObject = addGameObject("MyObject.mesh"); MyObject->setPosition(5, 1, 0); //We put it 5 meters to the right, and 1 meter up... //MyObject->setUpPhysics(); // <---- This activate the physics for the object as static geometry MyObject->setUpPhysics(100, convexShape); // <---- This activate the physics as a dynamic object. We need to tell the shape approximation to use. and a mass in Kg MyObject->attachScript("DummyBehavior2"); //The shape approximation is put at the Object CENTER POINT. The CENTER POINT should be at the object's bounding box CENTER before exporting from blender. MyObject->setFrictionCoef(0.84f); auto text = std::make_shared<Ann3DTextPlane>(1.0f, 0.5f, "Hello, Virtual World!\n\nTesting line wrap right now : a bc def ghij klmn opqr stuvw xyz ", 128, 96.0f, "LibSerifTestLevel", "LiberationSerif-Regular.ttf"); //text->setTextAlign(text->ALIGN_CENTER); text->setBackgroundColor(AnnColor(0, 1, 0)); text->setPosition({ 0, 0.5f, -1 }); text->setBackgroundImage("background.png"); text->setMargin(0.1f); text->update(); addManualMovableObject(text); //Add other source of light auto Sun = addLightObject(); Sun->setType(AnnLightObject::ANN_LIGHT_DIRECTIONAL); Sun->setDirection(AnnVect3{ 0.5f, -1.5f, -2.25f }.normalisedCopy()); Sun->setPower(97.f); //Create objects and register them as content of the level auto S = AnnGetGameObjectManager()->createGameObject("Sinbad.mesh", "SuperSinbad", std::make_shared<Sinbad>()); levelContent.push_back(S); S->playSound("monster.wav", true, 1); S->attachScript("DummyBehavior"); S->setUpPhysics(10, boxShape); S->setFrictionCoef(0.75f); //Add water auto Water = addGameObject("environment/Water.mesh"); //Add the island auto Island = addGameObject("environment/Island.mesh"); Island->setUpPhysics(); Island->setFrictionCoef(0.75); //Add the sign auto Sign(addGameObject("environment/Sign.mesh")); Sign->setPosition(1, -0.15, -2); Sign->setUpPhysics(0, staticShape); Sign->setOrientation(Ogre::Quaternion(Ogre::Degree(-45), Ogre::Vector3::UNIT_Y)); //Put some music here //AnnGetAudioEngine()->playBGM("media/bgm/bensound-happyrock.ogg", 0.4); //Place the starting point AnnGetPlayer()->setPosition(AnnVect3::ZERO); AnnGetPlayer()->setOrientation(Ogre::Euler(0)); AnnGetPlayer()->resetPlayerPhysics(); AnnGetPlayer()->regroundOnPhysicsBody(1000, { 0, 100, 0 }); } void unload() override { AnnGetEventManager()->removeListener(goBackListener); //Do the normal unloading AnnLevel::unload(); } void runLogic() override { //AnnGetPlayer()->regroundOnPhysicsBody(1000, { 0, 100, 0 }); } private: std::shared_ptr<GoBackToDemoHub> goBackListener; }; class PhysicsDebugLevel : LEVEL { void load() override { //AnnGetSceneryManager()->setWorldBackgroundColor(AnnColor(0, 0, 0)); AnnGetPhysicsEngine()->getWorld()->setGravity(btVector3(0, 0, 0)); AnnGetPlayer()->setPosition(AnnVect3::ZERO); AnnGetPlayer()->resetPlayerPhysics(); } void runLogic() override { AnnDebug() << "Player position is : " << AnnGetPlayer()->getPosition(); } }; #endif //TESTLEVEL<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include "objectives.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "accounts.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "budget_exception.hpp" #include "compute.hpp" #include "writer.hpp" using namespace budget; namespace { static data_handler<objective> objectives { "objectives", "objectives.data" }; void edit(budget::objective& objective){ edit_string(objective.name, "Name", not_empty_checker()); edit_string_complete(objective.type, "Type", {"monthly","yearly"}, not_empty_checker(), one_of_checker({"monthly","yearly"})); edit_string_complete(objective.source, "Source", {"balance", "earnings", "expenses", "savings_rate"}, not_empty_checker(), one_of_checker({"balance", "earnings", "expenses", "savings_rate"})); edit_string_complete(objective.op, "Operator", {"min", "max"}, not_empty_checker(), one_of_checker({"min", "max"})); edit_money(objective.amount, "Amount"); } } //end of anonymous namespace std::map<std::string, std::string> budget::objective::get_params(){ std::map<std::string, std::string> params; params["input_id"] = budget::to_string(id); params["input_guid"] = guid; params["input_date"] = budget::to_string(date); params["input_name"] = name; params["input_type"] = type; params["input_source"] = source; params["input_op"] = op; params["input_amount"] = budget::to_string(amount); return params; } void budget::yearly_objective_status(budget::writer& w, bool lines, bool full_align){ size_t yearly = 0; for (auto& objective : objectives.data) { if (objective.type == "yearly") { ++yearly; } } if (yearly) { w << title_begin << "Year objectives" << title_end; if (lines) { w << end_of_line; } size_t width = 0; if (full_align) { for (auto& objective : objectives.data) { width = std::max(rsize(objective.name), width); } } else { for (auto& objective : objectives.data) { if (objective.type == "yearly") { width = std::max(rsize(objective.name), width); } } } //Compute the year status auto year_status = budget::compute_year_status(); std::vector<std::string> columns = {"Objective", "Status", "Progress"}; std::vector<std::vector<std::string>> contents; for (auto& objective : objectives.data) { if (objective.type == "yearly") { contents.push_back({objective.name, get_status(year_status, objective), get_success(year_status, objective)}); } } w.display_table(columns, contents); } } void budget::monthly_objective_status(budget::writer& w){ w << title_begin << "Month objectives" << title_end; auto today = budget::local_day(); auto current_month = today.month(); auto current_year = today.year(); auto sm = start_month(current_year); for (auto& objective : objectives.data) { if (objective.type == "monthly") { std::vector<std::string> columns = {objective.name, "Status", "Progress"}; std::vector<std::vector<std::string>> contents; for (unsigned short i = sm; i <= current_month; ++i) { budget::month month = i; // Compute the month status auto status = budget::compute_month_status(current_year, month); contents.push_back({to_string(month), get_status(status, objective), get_success(status, objective)}); } w.display_table(columns, contents); } } } void budget::current_monthly_objective_status(budget::writer& w, bool full_align){ if (objectives.data.empty()) { w << title_begin << "No objectives" << title_end; return; } auto monthly_objectives = std::count_if(objectives.data.begin(), objectives.data.end(), [](auto& objective) { return objective.type == "monthly"; }); if (!monthly_objectives) { w << title_begin << "No objectives" << title_end; return; } w << title_begin << "Month objectives" << title_end; auto today = budget::local_day(); size_t width = 0; if (full_align) { for (auto& objective : objectives.data) { width = std::max(rsize(objective.name), width); } } else { for (auto& objective : objectives.data) { if (objective.type == "monthly") { width = std::max(rsize(objective.name), width); } } } std::vector<std::string> columns = {"Objective", "Status", "Progress"}; std::vector<std::vector<std::string>> contents; // Compute the month status auto status = budget::compute_month_status(today.year(), today.month()); for (auto& objective : objectives.data) { if (objective.type == "monthly") { contents.push_back({objective.name, get_status(status, objective), get_success(status, objective)}); } } w.display_table(columns, contents); } int budget::compute_success(const budget::status& status, const budget::objective& objective){ auto amount = objective.amount; budget::money basis; if (objective.source == "expenses") { basis = status.expenses; } else if (objective.source == "earnings") { basis = status.earnings; } else if (objective.source == "savings_rate") { auto savings = status.income - status.expenses; double savings_rate = 0.0; if (savings.dollars() > 0) { savings_rate = 100 * (savings / status.income); } basis = budget::money(int(savings_rate)); } else { basis = status.balance; } int success = 0; if (objective.op == "min") { auto percent = basis.dollars() / static_cast<double>(amount.dollars()); success = percent * 100; } else if (objective.op == "max") { auto percent = amount.dollars() / static_cast<double>(basis.dollars()); success = percent * 100; } success = std::max(0, success); return success; } void budget::objectives_module::load(){ load_expenses(); load_earnings(); load_accounts(); load_objectives(); } void budget::objectives_module::unload(){ save_objectives(); } void budget::objectives_module::handle(const std::vector<std::string>& args){ if(args.size() == 1){ console_writer w(std::cout); status_objectives(w); } else { auto& subcommand = args[1]; if(subcommand == "list"){ console_writer w(std::cout); budget::list_objectives(w); } else if(subcommand == "status"){ console_writer w(std::cout); status_objectives(w); } else if(subcommand == "add"){ objective objective; objective.guid = generate_guid(); objective.date = budget::local_day(); edit(objective); auto id = objectives.add(std::move(objective)); std::cout << "Objective " << id << " has been created" << std::endl; } else if(subcommand == "delete"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); if(!objectives.exists(id)){ throw budget_exception("There are no objective with id " + args[2]); } objectives.remove(id); std::cout << "Objective " << id << " has been deleted" << std::endl; } else if(subcommand == "edit"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); if(!objectives.exists(id)){ throw budget_exception("There are no objective with id " + args[2]); } auto& objective = objectives[id]; edit(objective); if (objectives.edit(objective)) { std::cout << "Objective " << id << " has been modified" << std::endl; } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::load_objectives(){ objectives.load(); } void budget::save_objectives(){ objectives.save(); } std::ostream& budget::operator<<(std::ostream& stream, const objective& objective){ return stream << objective.id << ':' << objective.guid << ':' << objective.name << ':' << objective.type << ':' << objective.source << ':' << objective.op << ':' << objective.amount << ':' << to_string(objective.date); } void budget::operator>>(const std::vector<std::string>& parts, objective& objective){ bool random = config_contains("random"); objective.id = to_number<size_t>(parts[0]); objective.guid = parts[1]; objective.name = parts[2]; objective.type = parts[3]; objective.source = parts[4]; objective.op = parts[5]; objective.date = from_string(parts[7]); if(random){ objective.amount = budget::random_money(1000, 10000); } else { objective.amount = parse_money(parts[6]); } } std::vector<objective>& budget::all_objectives(){ return objectives.data; } void budget::set_objectives_changed(){ objectives.set_changed(); } void budget::set_objectives_next_id(size_t next_id){ objectives.next_id = next_id; } void budget::list_objectives(budget::writer& w){ w << title_begin << "Objectives " << add_button("objectives") << title_end; if (objectives.data.size() == 0) { w << "No objectives" << end_of_line; } else { std::vector<std::string> columns = {"ID", "Name", "Type", "Source", "Operator", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; for (auto& objective : objectives.data) { contents.push_back({to_string(objective.id), objective.name, objective.type, objective.source, objective.op, to_string(objective.amount), "::edit::objectives::" + to_string(objective.id)}); } w.display_table(columns, contents); } } void budget::status_objectives(budget::writer& w){ w << title_begin << "Objectives " << add_button("objectives") << title_end; if(objectives.data.size() == 0){ w << "No objectives" << end_of_line; } else { auto today = budget::local_day(); if(today.day() < 12){ w << p_begin << "WARNING: It is early in the month, no one can know what may happen ;)" << p_end; } size_t monthly = 0; size_t yearly = 0; for(auto& objective : objectives.data){ if(objective.type == "yearly"){ ++yearly; } else if(objective.type == "monthly"){ ++monthly; } } if(yearly){ budget::yearly_objective_status(w, true, false); if(monthly){ w << end_of_line; } } if(monthly){ budget::monthly_objective_status(w); } } } bool budget::objective_exists(size_t id){ return objectives.exists(id); } void budget::objective_delete(size_t id) { if (!objectives.exists(id)) { throw budget_exception("There are no objective with id "); } objectives.remove(id); } objective& budget::objective_get(size_t id) { if (!objectives.exists(id)) { throw budget_exception("There are no objective with id "); } return objectives[id]; } void budget::add_objective(budget::objective&& objective){ objectives.add(std::forward<budget::objective>(objective)); } std::string budget::get_status(const budget::status& status, const budget::objective& objective){ std::string result; budget::money basis; if(objective.source == "expenses"){ basis = status.expenses; } else if (objective.source == "earnings") { basis = status.earnings; } else if (objective.source == "savings_rate") { auto savings = status.income - status.expenses; double savings_rate = 0.0; if (savings.dollars() > 0) { savings_rate = 100 * (savings / status.income); } basis = budget::money(int(savings_rate)); } else { basis = status.balance; } result += to_string(basis.dollars()); result += "/"; result += to_string(objective.amount.dollars()); return result; } std::string budget::get_success(const budget::status& status, const budget::objective& objective){ auto success = compute_success(status, objective); return "::success" + std::to_string(success); } <commit_msg>Fix savings objectives<commit_after>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include "objectives.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "accounts.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "budget_exception.hpp" #include "compute.hpp" #include "writer.hpp" using namespace budget; namespace { static data_handler<objective> objectives { "objectives", "objectives.data" }; void edit(budget::objective& objective){ edit_string(objective.name, "Name", not_empty_checker()); edit_string_complete(objective.type, "Type", {"monthly","yearly"}, not_empty_checker(), one_of_checker({"monthly","yearly"})); edit_string_complete(objective.source, "Source", {"balance", "earnings", "expenses", "savings_rate"}, not_empty_checker(), one_of_checker({"balance", "earnings", "expenses", "savings_rate"})); edit_string_complete(objective.op, "Operator", {"min", "max"}, not_empty_checker(), one_of_checker({"min", "max"})); edit_money(objective.amount, "Amount"); } } //end of anonymous namespace std::map<std::string, std::string> budget::objective::get_params(){ std::map<std::string, std::string> params; params["input_id"] = budget::to_string(id); params["input_guid"] = guid; params["input_date"] = budget::to_string(date); params["input_name"] = name; params["input_type"] = type; params["input_source"] = source; params["input_op"] = op; params["input_amount"] = budget::to_string(amount); return params; } void budget::yearly_objective_status(budget::writer& w, bool lines, bool full_align){ size_t yearly = 0; for (auto& objective : objectives.data) { if (objective.type == "yearly") { ++yearly; } } if (yearly) { w << title_begin << "Year objectives" << title_end; if (lines) { w << end_of_line; } size_t width = 0; if (full_align) { for (auto& objective : objectives.data) { width = std::max(rsize(objective.name), width); } } else { for (auto& objective : objectives.data) { if (objective.type == "yearly") { width = std::max(rsize(objective.name), width); } } } //Compute the year status auto year_status = budget::compute_year_status(); std::vector<std::string> columns = {"Objective", "Status", "Progress"}; std::vector<std::vector<std::string>> contents; for (auto& objective : objectives.data) { if (objective.type == "yearly") { contents.push_back({objective.name, get_status(year_status, objective), get_success(year_status, objective)}); } } w.display_table(columns, contents); } } void budget::monthly_objective_status(budget::writer& w){ w << title_begin << "Month objectives" << title_end; auto today = budget::local_day(); auto current_month = today.month(); auto current_year = today.year(); auto sm = start_month(current_year); for (auto& objective : objectives.data) { if (objective.type == "monthly") { std::vector<std::string> columns = {objective.name, "Status", "Progress"}; std::vector<std::vector<std::string>> contents; for (unsigned short i = sm; i <= current_month; ++i) { budget::month month = i; // Compute the month status auto status = budget::compute_month_status(current_year, month); contents.push_back({to_string(month), get_status(status, objective), get_success(status, objective)}); } w.display_table(columns, contents); } } } void budget::current_monthly_objective_status(budget::writer& w, bool full_align){ if (objectives.data.empty()) { w << title_begin << "No objectives" << title_end; return; } auto monthly_objectives = std::count_if(objectives.data.begin(), objectives.data.end(), [](auto& objective) { return objective.type == "monthly"; }); if (!monthly_objectives) { w << title_begin << "No objectives" << title_end; return; } w << title_begin << "Month objectives" << title_end; auto today = budget::local_day(); size_t width = 0; if (full_align) { for (auto& objective : objectives.data) { width = std::max(rsize(objective.name), width); } } else { for (auto& objective : objectives.data) { if (objective.type == "monthly") { width = std::max(rsize(objective.name), width); } } } std::vector<std::string> columns = {"Objective", "Status", "Progress"}; std::vector<std::vector<std::string>> contents; // Compute the month status auto status = budget::compute_month_status(today.year(), today.month()); for (auto& objective : objectives.data) { if (objective.type == "monthly") { contents.push_back({objective.name, get_status(status, objective), get_success(status, objective)}); } } w.display_table(columns, contents); } int budget::compute_success(const budget::status& status, const budget::objective& objective){ auto amount = objective.amount; budget::money basis; if (objective.source == "expenses") { basis = status.expenses; } else if (objective.source == "earnings") { basis = status.earnings; } else if (objective.source == "savings_rate") { auto savings = status.income - status.expenses; double savings_rate = 0.0; if (savings.dollars() > 0) { savings_rate = 100 * (savings / status.income); } basis = budget::money(int(savings_rate)); } else { basis = status.savings; } int success = 0; if (objective.op == "min") { auto percent = basis.dollars() / static_cast<double>(amount.dollars()); success = percent * 100; } else if (objective.op == "max") { auto percent = amount.dollars() / static_cast<double>(basis.dollars()); success = percent * 100; } success = std::max(0, success); return success; } void budget::objectives_module::load(){ load_expenses(); load_earnings(); load_accounts(); load_objectives(); } void budget::objectives_module::unload(){ save_objectives(); } void budget::objectives_module::handle(const std::vector<std::string>& args){ if(args.size() == 1){ console_writer w(std::cout); status_objectives(w); } else { auto& subcommand = args[1]; if(subcommand == "list"){ console_writer w(std::cout); budget::list_objectives(w); } else if(subcommand == "status"){ console_writer w(std::cout); status_objectives(w); } else if(subcommand == "add"){ objective objective; objective.guid = generate_guid(); objective.date = budget::local_day(); edit(objective); auto id = objectives.add(std::move(objective)); std::cout << "Objective " << id << " has been created" << std::endl; } else if(subcommand == "delete"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); if(!objectives.exists(id)){ throw budget_exception("There are no objective with id " + args[2]); } objectives.remove(id); std::cout << "Objective " << id << " has been deleted" << std::endl; } else if(subcommand == "edit"){ enough_args(args, 3); size_t id = to_number<size_t>(args[2]); if(!objectives.exists(id)){ throw budget_exception("There are no objective with id " + args[2]); } auto& objective = objectives[id]; edit(objective); if (objectives.edit(objective)) { std::cout << "Objective " << id << " has been modified" << std::endl; } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::load_objectives(){ objectives.load(); } void budget::save_objectives(){ objectives.save(); } std::ostream& budget::operator<<(std::ostream& stream, const objective& objective){ return stream << objective.id << ':' << objective.guid << ':' << objective.name << ':' << objective.type << ':' << objective.source << ':' << objective.op << ':' << objective.amount << ':' << to_string(objective.date); } void budget::operator>>(const std::vector<std::string>& parts, objective& objective){ bool random = config_contains("random"); objective.id = to_number<size_t>(parts[0]); objective.guid = parts[1]; objective.name = parts[2]; objective.type = parts[3]; objective.source = parts[4]; objective.op = parts[5]; objective.date = from_string(parts[7]); if(random){ objective.amount = budget::random_money(1000, 10000); } else { objective.amount = parse_money(parts[6]); } } std::vector<objective>& budget::all_objectives(){ return objectives.data; } void budget::set_objectives_changed(){ objectives.set_changed(); } void budget::set_objectives_next_id(size_t next_id){ objectives.next_id = next_id; } void budget::list_objectives(budget::writer& w){ w << title_begin << "Objectives " << add_button("objectives") << title_end; if (objectives.data.size() == 0) { w << "No objectives" << end_of_line; } else { std::vector<std::string> columns = {"ID", "Name", "Type", "Source", "Operator", "Amount", "Edit"}; std::vector<std::vector<std::string>> contents; for (auto& objective : objectives.data) { contents.push_back({to_string(objective.id), objective.name, objective.type, objective.source, objective.op, to_string(objective.amount), "::edit::objectives::" + to_string(objective.id)}); } w.display_table(columns, contents); } } void budget::status_objectives(budget::writer& w){ w << title_begin << "Objectives " << add_button("objectives") << title_end; if(objectives.data.size() == 0){ w << "No objectives" << end_of_line; } else { auto today = budget::local_day(); if(today.day() < 12){ w << p_begin << "WARNING: It is early in the month, no one can know what may happen ;)" << p_end; } size_t monthly = 0; size_t yearly = 0; for(auto& objective : objectives.data){ if(objective.type == "yearly"){ ++yearly; } else if(objective.type == "monthly"){ ++monthly; } } if(yearly){ budget::yearly_objective_status(w, true, false); if(monthly){ w << end_of_line; } } if(monthly){ budget::monthly_objective_status(w); } } } bool budget::objective_exists(size_t id){ return objectives.exists(id); } void budget::objective_delete(size_t id) { if (!objectives.exists(id)) { throw budget_exception("There are no objective with id "); } objectives.remove(id); } objective& budget::objective_get(size_t id) { if (!objectives.exists(id)) { throw budget_exception("There are no objective with id "); } return objectives[id]; } void budget::add_objective(budget::objective&& objective){ objectives.add(std::forward<budget::objective>(objective)); } std::string budget::get_status(const budget::status& status, const budget::objective& objective){ std::string result; budget::money basis; if(objective.source == "expenses"){ basis = status.expenses; } else if (objective.source == "earnings") { basis = status.earnings; } else if (objective.source == "savings_rate") { auto savings = status.income - status.expenses; double savings_rate = 0.0; if (savings.dollars() > 0) { savings_rate = 100 * (savings / status.income); } basis = budget::money(int(savings_rate)); } else { basis = status.savings; } result += to_string(basis.dollars()); result += "/"; result += to_string(objective.amount.dollars()); return result; } std::string budget::get_success(const budget::status& status, const budget::objective& objective){ auto success = compute_success(status, objective); return "::success" + std::to_string(success); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MasterPagesPanel.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: ihi $ $Date: 2006-08-01 09:23:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "MasterPagesPanel.hxx" #include "taskpane/ScrollPanel.hxx" #include "CurrentMasterPagesSelector.hxx" #include "RecentMasterPagesSelector.hxx" #include "AllMasterPagesSelector.hxx" #include "taskpane/TaskPaneControlFactory.hxx" #include "taskpane/TitledControl.hxx" #include "../TaskPaneShellManager.hxx" #include "DrawViewShell.hxx" #include "ViewShellBase.hxx" #include "strings.hrc" #include "sdresid.hxx" #include "helpids.h" #include <svtools/valueset.hxx> namespace sd { namespace toolpanel { namespace controls { MasterPagesPanel::MasterPagesPanel (TreeNode* pParent, ViewShellBase& rBase) : ScrollPanel (pParent) { SdDrawDocument* pDocument = rBase.GetDocument(); ::std::auto_ptr<controls::MasterPagesSelector> pSelector; TitledControl* pTitledControl; ::boost::shared_ptr<MasterPageContainer> pContainer (new MasterPageContainer()); // Create a panel with the master pages that are in use by the currently // edited document. DrawViewShell* pDrawViewShell = static_cast<DrawViewShell*>( rBase.GetMainViewShell()); pSelector.reset(new controls::CurrentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_CURRENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_CURRENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_CURRENT_MASTER_PAGES_TITLE), HID_SD_CURRENT_MASTERS); // Create a panel with the most recently used master pages. pSelector.reset(new controls::RecentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_RECENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_RECENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_RECENT_MASTER_PAGES_TITLE), HID_SD_RECENT_MASTERS); // Create a panel with all available master pages. pSelector.reset(new controls::AllMasterPagesSelector ( this, *pDocument, rBase, *pDrawViewShell, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_ALL) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_ALL, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_ALL_MASTER_PAGES_TITLE), HID_SD_ALL_MASTERS); } MasterPagesPanel::~MasterPagesPanel (void) { } std::auto_ptr<ControlFactory> MasterPagesPanel::CreateControlFactory (ViewShellBase& rBase) { return std::auto_ptr<ControlFactory>( new ControlFactoryWithArgs1<MasterPagesPanel,ViewShellBase>(rBase)); } } } } // end of namespace ::sd::toolpanel::controls <commit_msg>INTEGRATION: CWS pchfix02 (1.11.26); FILE MERGED 2006/09/01 17:37:25 kaib 1.11.26.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: MasterPagesPanel.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-16 19:19:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "MasterPagesPanel.hxx" #include "taskpane/ScrollPanel.hxx" #include "CurrentMasterPagesSelector.hxx" #include "RecentMasterPagesSelector.hxx" #include "AllMasterPagesSelector.hxx" #include "taskpane/TaskPaneControlFactory.hxx" #include "taskpane/TitledControl.hxx" #include "../TaskPaneShellManager.hxx" #include "DrawViewShell.hxx" #include "ViewShellBase.hxx" #include "strings.hrc" #include "sdresid.hxx" #include "helpids.h" #include <svtools/valueset.hxx> namespace sd { namespace toolpanel { namespace controls { MasterPagesPanel::MasterPagesPanel (TreeNode* pParent, ViewShellBase& rBase) : ScrollPanel (pParent) { SdDrawDocument* pDocument = rBase.GetDocument(); ::std::auto_ptr<controls::MasterPagesSelector> pSelector; TitledControl* pTitledControl; ::boost::shared_ptr<MasterPageContainer> pContainer (new MasterPageContainer()); // Create a panel with the master pages that are in use by the currently // edited document. DrawViewShell* pDrawViewShell = static_cast<DrawViewShell*>( rBase.GetMainViewShell()); pSelector.reset(new controls::CurrentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_CURRENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_CURRENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_CURRENT_MASTER_PAGES_TITLE), HID_SD_CURRENT_MASTERS); // Create a panel with the most recently used master pages. pSelector.reset(new controls::RecentMasterPagesSelector ( this, *pDocument, rBase, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_RECENT) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_RECENT, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_RECENT_MASTER_PAGES_TITLE), HID_SD_RECENT_MASTERS); // Create a panel with all available master pages. pSelector.reset(new controls::AllMasterPagesSelector ( this, *pDocument, rBase, *pDrawViewShell, pContainer)); pSelector->LateInit(); pSelector->SetSmartHelpId( SmartId(HID_SD_TASK_PANE_PREVIEW_ALL) ); GetShellManager()->AddSubShell( HID_SD_TASK_PANE_PREVIEW_ALL, pSelector.get(), pSelector->GetWindow()); pTitledControl = AddControl ( ::std::auto_ptr<TreeNode>(pSelector.release()), SdResId(STR_TASKPANEL_ALL_MASTER_PAGES_TITLE), HID_SD_ALL_MASTERS); } MasterPagesPanel::~MasterPagesPanel (void) { } std::auto_ptr<ControlFactory> MasterPagesPanel::CreateControlFactory (ViewShellBase& rBase) { return std::auto_ptr<ControlFactory>( new ControlFactoryWithArgs1<MasterPagesPanel,ViewShellBase>(rBase)); } } } } // end of namespace ::sd::toolpanel::controls <|endoftext|>
<commit_before>/** * @file CameraMatrixCorrectorV2.cpp * * @author <a href="mailto:[email protected]">Steffen Kaden</a> */ #include "CameraMatrixCorrectorV2.h" #include <array> CameraMatrixCorrectorV2::CameraMatrixCorrectorV2() { getDebugParameterList().add(&getCameraMatrixOffset()); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrate_camera_matrix_line_matching", "calculates the roll and tilt offset of the camera using field lines (it. shoult be exactely 3000mm in front of the robot)", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:reset_calibration", "set the calibration offsets of the CM to 0", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:reset_lm_minimizer", "reset lm parameters to initial values", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:collect_calibration_data", "collect the data for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:clear_calibration_data", "clears the data used for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:enable_CamMatErrorFunction_drawings", "needed to be activated for error function drawings", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:automatic_mode","try to do automatic calibration", true); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrateOnlyPos","",false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrateOnlyOffsets","",false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrateSimultaneously","",false); theCamMatErrorFunction = registerModule<CamMatErrorFunction>("CamMatErrorFunction", true); auto_cleared_data = auto_collected = auto_calibrated_phase1 = auto_calibrated = false; play_calibrated = play_calibrating = play_collecting = true; last_error = 0; // sampling coordinates std::array<double,3> pitchs {-22 , 0, 10}; std::vector<double> yaws; for (int i = -88; i <= 88; i=i+16) { yaws.push_back(i); } for(double pitch : pitchs){ for(double yaw : yaws){ target_points.push_back(Vector2d(yaw, pitch)); } } current_target = target_points.begin(); } CameraMatrixCorrectorV2::~CameraMatrixCorrectorV2() { } void CameraMatrixCorrectorV2::execute() { if (getSoundPlayData().soundFile == "finished.wav" || getSoundPlayData().soundFile == "collectingdata.wav" || getSoundPlayData().soundFile == "calibrating.wav") { getSoundPlayData().mute = true; getSoundPlayData().soundFile = ""; } // sit down if auto calibrated if(auto_calibrated){ getMotionRequest().id = motion::sit; } else { getMotionRequest().id = motion::stand; } // enable debug drawings in manual and auto mode DEBUG_REQUEST("CameraMatrixV2:enable_CamMatErrorFunction_drawings", theCamMatErrorFunction->getModuleT()->plot_CalibrationData(cam_mat_offsets); ); bool use_automatic_mode = false; DEBUG_REQUEST("CameraMatrixV2:automatic_mode", use_automatic_mode = true; ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:automatic_mode", // Note: wanted behavior because we want to save the "best" solution so far if(!auto_calibrated){ writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); } // reset to intial getHeadMotionRequest().id = HeadMotionRequest::hold; current_target = target_points.begin(); auto_cleared_data = auto_collected = auto_calibrated_phase1 = auto_calibrated = false; play_calibrated = play_calibrating = play_collecting = true; derrors.clear(); derrors_pos.clear(); derrors_offset.clear(); last_error = 0; lm_minimizer.reset(); lm_minimizer_pos.reset(); lm_minimizer_offset.reset(); ); DEBUG_REQUEST("CameraMatrixV2:reset_lm_minimizer", lm_minimizer.reset(); lm_minimizer_pos.reset(); lm_minimizer_offset.reset(); ); if(use_automatic_mode){ if(!auto_calibrated){ doItAutomatically(); } } else { // manual mode DEBUG_REQUEST("CameraMatrixV2:clear_calibration_data", (theCamMatErrorFunction->getModuleT())->clear(); ); DEBUG_REQUEST("CameraMatrixV2:collect_calibration_data", collectingData(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:collect_calibration_data", // reset to initial getHeadMotionRequest().id = HeadMotionRequest::hold; current_target = target_points.begin(); ); DEBUG_REQUEST("CameraMatrixV2:calibrate_camera_matrix_line_matching", calibrate(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:calibrate_camera_matrix_line_matching", writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); ); DEBUG_REQUEST("CameraMatrixV2:reset_calibration", reset_calibration(); lm_minimizer.reset(); lm_minimizer_pos.reset(); lm_minimizer_offset.reset(); derrors.clear(); derrors_offset.clear(); derrors_pos.clear(); last_error = 0; ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:reset_calibration", writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); ); } last_frame_info = getFrameInfo(); }//end execute void CameraMatrixCorrectorV2::reset_calibration() { getCameraMatrixOffset().body_rot = Vector2d(); getCameraMatrixOffset().head_rot = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Top] = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] = Vector3d(); cam_mat_offsets = Eigen::Matrix<double, 14, 1>::Zero(); //theCamMatErrorFunction->getModuleT()->globalPosition = Vector3d(); } bool CameraMatrixCorrectorV2::calibrate(){ DEBUG_REQUEST("CameraMatrixV2:calibrateSimultaneously", return calibrateSimultaneously(); ); DEBUG_REQUEST("CameraMatrixV2:calibrateOnlyPos", return calibrateOnlyPose(); ); DEBUG_REQUEST("CameraMatrixV2:calibrateOnlyOffsets", return calibrateOnlyOffsets(); ); return false; } // returns true if the averaged reduction per second decreases under a heuristic value bool CameraMatrixCorrectorV2::calibrateSimultaneously() { double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); // calibrate the camera matrix Eigen::Matrix<double, 14, 1> epsilon = 1e-4*Eigen::Matrix<double, 14, 1>::Constant(1); epsilon(11) = 1e2; epsilon(12) = 1e2; epsilon(13) = Math::pi_4/2; double error; Eigen::Matrix<double, 14, 1> offset = lm_minimizer.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()), cam_mat_offsets, epsilon, error); double de_dt = (error-last_error)/dt; // improvement per second if(last_error != 0){ //ignore the jump from zero to initial error value derrors.add(de_dt); } last_error = error; PLOT("CameraMatrixV2:error", error); PLOT("CameraMatrixV2:de/dt", de_dt); PLOT("CameraMatrixV2:avg_derror", derrors.getAverage()); // update offsets cam_mat_offsets += offset; return ( (derrors.getAverage() > -50) // average error decreases by less than this per second && derrors.isFull() ); // and we have a full history }//end calibrate // returns true if the averaged reduction per second decreases under a heuristic value bool CameraMatrixCorrectorV2::calibrateOnlyPose() { double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); // calibrate the camera matrix Eigen::Matrix<double, 14, 1> epsilon = Eigen::Matrix<double, 14, 1>::Constant(std::numeric_limits<double>::quiet_NaN()); double epsilon_pos = 1e2; double epsilon_angle = Math::pi_4/2; MODIFY("CameraMatrixV2:epsilon:pos", epsilon_pos); MODIFY("CameraMatrixV2:epsilon:angle", epsilon_angle); epsilon.block<3,1>(11,0) << epsilon_pos, epsilon_pos, epsilon_angle; double error; Eigen::Matrix<double, 14, 1> offset = lm_minimizer_pos.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()), cam_mat_offsets, epsilon, error); double de_dt = (error-last_error)/dt; // improvement per second if(last_error != 0){ //ignore the jump from zero to initial error value derrors_pos.add(de_dt); } last_error = error; PLOT("CameraMatrixV2:error", error); PLOT("CameraMatrixV2:de/dt", de_dt); PLOT("CameraMatrixV2:avg_derror_pose", derrors_pos.getAverage()); // update offsets cam_mat_offsets += offset; return ( (derrors_pos.getAverage() > -50) // average error decreases by less than this per second && derrors_pos.isFull() ); // and we have a full history }//end calibrate // returns true if the averaged reduction per second decreases under a heuristic value bool CameraMatrixCorrectorV2::calibrateOnlyOffsets() { double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); // calibrate the camera matrix Eigen::Matrix<double, 14, 1> epsilon = Eigen::Matrix<double, 14, 1>::Constant(1e-4); epsilon.block<3,1>(11,0) << std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(); double error; Eigen::Matrix<double, 14, 1> offset = lm_minimizer_offset.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()), cam_mat_offsets, epsilon, error); double de_dt = (error-last_error)/dt; // improvement per second if(last_error != 0){ //ignore the jump from zero to initial error value derrors_offset.add(de_dt); } last_error = error; PLOT("CameraMatrixV2:error", error); PLOT("CameraMatrixV2:de/dt", de_dt); PLOT("CameraMatrixV2:avg_derror_offset", derrors_offset.getAverage()); // update offsets cam_mat_offsets += offset; return ( (derrors_offset.getAverage() > -50) // average error decreases by less than this per second && derrors_offset.isFull() ); // and we have a full history }//end calibrate // returns true, if the trajectory is starting again from beginning bool CameraMatrixCorrectorV2::collectingData() { getHeadMotionRequest().id = HeadMotionRequest::goto_angle; getHeadMotionRequest().targetJointPosition.x = Math::fromDegrees(current_target->x); getHeadMotionRequest().targetJointPosition.y = Math::fromDegrees(current_target->y); getHeadMotionRequest().velocity = 20; MODIFY("CameraMatrixV2:collecting_velocity", getHeadMotionRequest().velocity); double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); double current_yaw = Math::toDegrees(getSensorJointData().position[JointData::HeadYaw]); double current_pitch = Math::toDegrees(getSensorJointData().position[JointData::HeadPitch]); static double last_yaw(current_yaw); static double last_pitch(current_pitch); double vel_yaw = (last_yaw - current_yaw)/dt; double vel_pitch = (last_pitch - current_pitch)/dt; last_yaw = current_yaw; last_pitch = current_pitch; // state transitions and triggering sampling bool target_reached = fabs(current_yaw - current_target->x) < 3 && fabs(current_pitch - current_target->y) < 3 && fabs(vel_yaw) < 0.5 && fabs(vel_pitch) < 0.5; if(target_reached && current_target != target_points.end()){ sampling(); current_target++; } PLOT("CameraMatrixV2:vel_yaw",vel_yaw); PLOT("CameraMatrixV2:vel_pitch", vel_pitch); PLOT("CameraMatrixV2:target_reached", target_reached); return current_target == target_points.end(); } void CameraMatrixCorrectorV2::sampling() { LineGraphPercept lineGraphPercept(getLineGraphPercept()); // TODO: ignore upper image if the center is above the horizon // HACK: ignore it if headpitch is smaller than -15 //if(head_state == look_right_up || head_state == look_left_up // || last_head_state == look_right_up || last_head_state == look_left_up){ if(Math::toDegrees(getSensorJointData().position[JointData::HeadPitch]) < -15) { lineGraphPercept.edgelsInImageTop.clear(); } (theCamMatErrorFunction->getModuleT())->add(CamMatErrorFunction::CalibrationDataSample(getKinematicChain().theLinks[KinematicChain::Torso].M, lineGraphPercept, getInertialModel(), getSensorJointData().position[JointData::HeadYaw], getSensorJointData().position[JointData::HeadPitch] )); } void CameraMatrixCorrectorV2::doItAutomatically() { if(!auto_cleared_data) { (theCamMatErrorFunction->getModuleT())->clear(); auto_cleared_data = true; } if(!auto_collected){ auto_collected = collectingData(); if(play_collecting){ getSoundPlayData().mute = false; getSoundPlayData().soundFile = "collectingdata.wav"; play_collecting = false; } } if(auto_collected && !auto_calibrated_phase1){ auto_calibrated_phase1 = calibrateSimultaneously(); if(auto_calibrated_phase1){ derrors_offset.clear(); lm_minimizer_offset.reset(); } if(play_calibrating){ getSoundPlayData().mute = false; getSoundPlayData().soundFile = "calibrating.wav"; play_calibrating = false; } } if(auto_calibrated_phase1 && !auto_calibrated){ auto_calibrated = calibrateOnlyOffsets(); } if(auto_calibrated){ writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); if(play_calibrated) { getSoundPlayData().mute = false; getSoundPlayData().soundFile = "finished.wav"; play_calibrated = false; } } } void CameraMatrixCorrectorV2::writeToRepresentation() { getCameraMatrixOffset().body_rot += Vector2d(cam_mat_offsets(0),cam_mat_offsets(1)); getCameraMatrixOffset().head_rot += Vector3d(cam_mat_offsets(2),cam_mat_offsets(3),cam_mat_offsets(4)); getCameraMatrixOffset().cam_rot[CameraInfo::Top] += Vector3d(cam_mat_offsets(5),cam_mat_offsets(6),cam_mat_offsets(7)); getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] += Vector3d(cam_mat_offsets(8),cam_mat_offsets(9),cam_mat_offsets(10)); } <commit_msg>increase grid and decrease velocity criteria<commit_after>/** * @file CameraMatrixCorrectorV2.cpp * * @author <a href="mailto:[email protected]">Steffen Kaden</a> */ #include "CameraMatrixCorrectorV2.h" #include <array> CameraMatrixCorrectorV2::CameraMatrixCorrectorV2() { getDebugParameterList().add(&getCameraMatrixOffset()); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrate_camera_matrix_line_matching", "calculates the roll and tilt offset of the camera using field lines (it. shoult be exactely 3000mm in front of the robot)", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:reset_calibration", "set the calibration offsets of the CM to 0", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:reset_lm_minimizer", "reset lm parameters to initial values", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:collect_calibration_data", "collect the data for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:clear_calibration_data", "clears the data used for calibration", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:enable_CamMatErrorFunction_drawings", "needed to be activated for error function drawings", false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:automatic_mode","try to do automatic calibration", true); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrateOnlyPos","",false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrateOnlyOffsets","",false); DEBUG_REQUEST_REGISTER("CameraMatrixV2:calibrateSimultaneously","",false); theCamMatErrorFunction = registerModule<CamMatErrorFunction>("CamMatErrorFunction", true); auto_cleared_data = auto_collected = auto_calibrated_phase1 = auto_calibrated = false; play_calibrated = play_calibrating = play_collecting = true; last_error = 0; // sampling coordinates std::array<double,4> pitchs {-20, -10 , 0, 10}; std::vector<double> yaws; for (int i = -88; i <= 88; i=i+8) { yaws.push_back(i); } for(double pitch : pitchs){ for(double yaw : yaws){ target_points.push_back(Vector2d(yaw, pitch)); } } current_target = target_points.begin(); } CameraMatrixCorrectorV2::~CameraMatrixCorrectorV2() { } void CameraMatrixCorrectorV2::execute() { if (getSoundPlayData().soundFile == "finished.wav" || getSoundPlayData().soundFile == "collectingdata.wav" || getSoundPlayData().soundFile == "calibrating.wav") { getSoundPlayData().mute = true; getSoundPlayData().soundFile = ""; } // sit down if auto calibrated if(auto_calibrated){ getMotionRequest().id = motion::sit; } else { getMotionRequest().id = motion::stand; } // enable debug drawings in manual and auto mode DEBUG_REQUEST("CameraMatrixV2:enable_CamMatErrorFunction_drawings", theCamMatErrorFunction->getModuleT()->plot_CalibrationData(cam_mat_offsets); ); bool use_automatic_mode = false; DEBUG_REQUEST("CameraMatrixV2:automatic_mode", use_automatic_mode = true; ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:automatic_mode", // Note: wanted behavior because we want to save the "best" solution so far if(!auto_calibrated){ writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); } // reset to intial getHeadMotionRequest().id = HeadMotionRequest::hold; current_target = target_points.begin(); auto_cleared_data = auto_collected = auto_calibrated_phase1 = auto_calibrated = false; play_calibrated = play_calibrating = play_collecting = true; derrors.clear(); derrors_pos.clear(); derrors_offset.clear(); last_error = 0; lm_minimizer.reset(); lm_minimizer_pos.reset(); lm_minimizer_offset.reset(); ); DEBUG_REQUEST("CameraMatrixV2:reset_lm_minimizer", lm_minimizer.reset(); lm_minimizer_pos.reset(); lm_minimizer_offset.reset(); ); if(use_automatic_mode){ if(!auto_calibrated){ doItAutomatically(); } } else { // manual mode DEBUG_REQUEST("CameraMatrixV2:clear_calibration_data", (theCamMatErrorFunction->getModuleT())->clear(); ); DEBUG_REQUEST("CameraMatrixV2:collect_calibration_data", collectingData(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:collect_calibration_data", // reset to initial getHeadMotionRequest().id = HeadMotionRequest::hold; current_target = target_points.begin(); ); DEBUG_REQUEST("CameraMatrixV2:calibrate_camera_matrix_line_matching", calibrate(); ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:calibrate_camera_matrix_line_matching", writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); ); DEBUG_REQUEST("CameraMatrixV2:reset_calibration", reset_calibration(); lm_minimizer.reset(); lm_minimizer_pos.reset(); lm_minimizer_offset.reset(); derrors.clear(); derrors_offset.clear(); derrors_pos.clear(); last_error = 0; ); DEBUG_REQUEST_ON_DEACTIVE("CameraMatrixV2:reset_calibration", writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); ); } last_frame_info = getFrameInfo(); }//end execute void CameraMatrixCorrectorV2::reset_calibration() { getCameraMatrixOffset().body_rot = Vector2d(); getCameraMatrixOffset().head_rot = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Top] = Vector3d(); getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] = Vector3d(); cam_mat_offsets = Eigen::Matrix<double, 14, 1>::Zero(); //theCamMatErrorFunction->getModuleT()->globalPosition = Vector3d(); } bool CameraMatrixCorrectorV2::calibrate(){ DEBUG_REQUEST("CameraMatrixV2:calibrateSimultaneously", return calibrateSimultaneously(); ); DEBUG_REQUEST("CameraMatrixV2:calibrateOnlyPos", return calibrateOnlyPose(); ); DEBUG_REQUEST("CameraMatrixV2:calibrateOnlyOffsets", return calibrateOnlyOffsets(); ); return false; } // returns true if the averaged reduction per second decreases under a heuristic value bool CameraMatrixCorrectorV2::calibrateSimultaneously() { double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); // calibrate the camera matrix Eigen::Matrix<double, 14, 1> epsilon = 1e-4*Eigen::Matrix<double, 14, 1>::Constant(1); epsilon(11) = 1e2; epsilon(12) = 1e2; epsilon(13) = Math::pi_4/2; double error; Eigen::Matrix<double, 14, 1> offset = lm_minimizer.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()), cam_mat_offsets, epsilon, error); double de_dt = (error-last_error)/dt; // improvement per second if(last_error != 0){ //ignore the jump from zero to initial error value derrors.add(de_dt); } last_error = error; PLOT("CameraMatrixV2:error", error); PLOT("CameraMatrixV2:de/dt", de_dt); PLOT("CameraMatrixV2:avg_derror", derrors.getAverage()); // update offsets cam_mat_offsets += offset; return ( (derrors.getAverage() > -50) // average error decreases by less than this per second && derrors.isFull() ); // and we have a full history }//end calibrate // returns true if the averaged reduction per second decreases under a heuristic value bool CameraMatrixCorrectorV2::calibrateOnlyPose() { double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); // calibrate the camera matrix Eigen::Matrix<double, 14, 1> epsilon = Eigen::Matrix<double, 14, 1>::Constant(std::numeric_limits<double>::quiet_NaN()); double epsilon_pos = 1e2; double epsilon_angle = Math::pi_4/2; MODIFY("CameraMatrixV2:epsilon:pos", epsilon_pos); MODIFY("CameraMatrixV2:epsilon:angle", epsilon_angle); epsilon.block<3,1>(11,0) << epsilon_pos, epsilon_pos, epsilon_angle; double error; Eigen::Matrix<double, 14, 1> offset = lm_minimizer_pos.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()), cam_mat_offsets, epsilon, error); double de_dt = (error-last_error)/dt; // improvement per second if(last_error != 0){ //ignore the jump from zero to initial error value derrors_pos.add(de_dt); } last_error = error; PLOT("CameraMatrixV2:error", error); PLOT("CameraMatrixV2:de/dt", de_dt); PLOT("CameraMatrixV2:avg_derror_pose", derrors_pos.getAverage()); // update offsets cam_mat_offsets += offset; return ( (derrors_pos.getAverage() > -50) // average error decreases by less than this per second && derrors_pos.isFull() ); // and we have a full history }//end calibrate // returns true if the averaged reduction per second decreases under a heuristic value bool CameraMatrixCorrectorV2::calibrateOnlyOffsets() { double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); // calibrate the camera matrix Eigen::Matrix<double, 14, 1> epsilon = Eigen::Matrix<double, 14, 1>::Constant(1e-4); epsilon.block<3,1>(11,0) << std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN(); double error; Eigen::Matrix<double, 14, 1> offset = lm_minimizer_offset.minimizeOneStep(*(theCamMatErrorFunction->getModuleT()), cam_mat_offsets, epsilon, error); double de_dt = (error-last_error)/dt; // improvement per second if(last_error != 0){ //ignore the jump from zero to initial error value derrors_offset.add(de_dt); } last_error = error; PLOT("CameraMatrixV2:error", error); PLOT("CameraMatrixV2:de/dt", de_dt); PLOT("CameraMatrixV2:avg_derror_offset", derrors_offset.getAverage()); // update offsets cam_mat_offsets += offset; return ( (derrors_offset.getAverage() > -50) // average error decreases by less than this per second && derrors_offset.isFull() ); // and we have a full history }//end calibrate // returns true, if the trajectory is starting again from beginning bool CameraMatrixCorrectorV2::collectingData() { getHeadMotionRequest().id = HeadMotionRequest::goto_angle; getHeadMotionRequest().targetJointPosition.x = Math::fromDegrees(current_target->x); getHeadMotionRequest().targetJointPosition.y = Math::fromDegrees(current_target->y); getHeadMotionRequest().velocity = 20; MODIFY("CameraMatrixV2:collecting_velocity", getHeadMotionRequest().velocity); double dt = getFrameInfo().getTimeInSeconds()-last_frame_info.getTimeInSeconds(); double current_yaw = Math::toDegrees(getSensorJointData().position[JointData::HeadYaw]); double current_pitch = Math::toDegrees(getSensorJointData().position[JointData::HeadPitch]); static double last_yaw(current_yaw); static double last_pitch(current_pitch); double vel_yaw = (last_yaw - current_yaw)/dt; double vel_pitch = (last_pitch - current_pitch)/dt; last_yaw = current_yaw; last_pitch = current_pitch; // state transitions and triggering sampling bool target_reached = fabs(current_yaw - current_target->x) < 3 && fabs(current_pitch - current_target->y) < 3 && fabs(vel_yaw) < 0.2 && fabs(vel_pitch) < 0.2; if(target_reached && current_target != target_points.end()){ sampling(); current_target++; } PLOT("CameraMatrixV2:vel_yaw",vel_yaw); PLOT("CameraMatrixV2:vel_pitch", vel_pitch); PLOT("CameraMatrixV2:target_reached", target_reached); return current_target == target_points.end(); } void CameraMatrixCorrectorV2::sampling() { LineGraphPercept lineGraphPercept(getLineGraphPercept()); // TODO: ignore upper image if the center is above the horizon // HACK: ignore it if headpitch is smaller than -15 //if(head_state == look_right_up || head_state == look_left_up // || last_head_state == look_right_up || last_head_state == look_left_up){ if(Math::toDegrees(getSensorJointData().position[JointData::HeadPitch]) < -15) { lineGraphPercept.edgelsInImageTop.clear(); } (theCamMatErrorFunction->getModuleT())->add(CamMatErrorFunction::CalibrationDataSample(getKinematicChain().theLinks[KinematicChain::Torso].M, lineGraphPercept, getInertialModel(), getSensorJointData().position[JointData::HeadYaw], getSensorJointData().position[JointData::HeadPitch] )); } void CameraMatrixCorrectorV2::doItAutomatically() { if(!auto_cleared_data) { (theCamMatErrorFunction->getModuleT())->clear(); auto_cleared_data = true; } if(!auto_collected){ auto_collected = collectingData(); if(play_collecting){ getSoundPlayData().mute = false; getSoundPlayData().soundFile = "collectingdata.wav"; play_collecting = false; } } if(auto_collected && !auto_calibrated_phase1){ auto_calibrated_phase1 = calibrateSimultaneously(); if(auto_calibrated_phase1){ derrors_offset.clear(); lm_minimizer_offset.reset(); } if(play_calibrating){ getSoundPlayData().mute = false; getSoundPlayData().soundFile = "calibrating.wav"; play_calibrating = false; } } if(auto_calibrated_phase1 && !auto_calibrated){ auto_calibrated = calibrateOnlyOffsets(); } if(auto_calibrated){ writeToRepresentation(); getCameraMatrixOffset().saveToConfig(); if(play_calibrated) { getSoundPlayData().mute = false; getSoundPlayData().soundFile = "finished.wav"; play_calibrated = false; } } } void CameraMatrixCorrectorV2::writeToRepresentation() { getCameraMatrixOffset().body_rot += Vector2d(cam_mat_offsets(0),cam_mat_offsets(1)); getCameraMatrixOffset().head_rot += Vector3d(cam_mat_offsets(2),cam_mat_offsets(3),cam_mat_offsets(4)); getCameraMatrixOffset().cam_rot[CameraInfo::Top] += Vector3d(cam_mat_offsets(5),cam_mat_offsets(6),cam_mat_offsets(7)); getCameraMatrixOffset().cam_rot[CameraInfo::Bottom] += Vector3d(cam_mat_offsets(8),cam_mat_offsets(9),cam_mat_offsets(10)); } <|endoftext|>
<commit_before>/* Copyright (c) 2015, 2016, Andreas Fett. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <cassert> #include <cstring> #include "parser-impl.h" #include "error.h" #include "token-stream.h" #include "utf8stream.h" namespace { /* * Generic parser state engine * Check all transitions for the current State * until the token is found in Transition::match, * change to the associated state. * * Instances of this are build for Document, Array and Object */ template <typename State> struct Transition { const char *match; State state; }; template <typename T> class StateEngine : public T { public: StateEngine(Json::TokenStream & tokenizer_, size_t depth) : T(tokenizer_, depth) { } Json::Value parse() { auto state(T::SSTART); do { T::tokenizer.scan(); state = transition(T::tokenizer.token.type, state); } while (state != T::SEND); return T::result; } private: typename T::State transition(Json::Token::Type token, typename T::State state) { for (auto t(0); t < T::SMAX; ++t) { if (!is_match(token, T::transitions[state][t].match)) { continue; } auto nstate(T::transitions[state][t].state); if (nstate == T::SERROR) { T::throw_error(state); JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } else { T::build(nstate); } return nstate; } return T::SERROR; } bool is_match(Json::Token::Type token, const char *match) const { return !match || (!match[0] && token == Json::Token::END) || strchr(match, token); } }; /* Base class for state engine configurations */ class ParserState { protected: ParserState(Json::TokenStream & tokenizer_, size_t depth) : tokenizer(tokenizer_), depth_(depth + 1) { if (depth > 255) { JSONCC_THROW(PARSER_OVERFLOW); } } Json::Value parse_value(); Json::TokenStream & tokenizer; private: size_t depth_; }; /* State engine config for Json::Array */ class ArrayState : public ParserState { protected: ArrayState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result << parse_value(); break; case SNEXT: break; case SEND: break; case SMAX: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_ARRAY_START); case SVALUE: JSONCC_THROW(BAD_TOKEN_ARRAY_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_ARRAY_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Array result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ArrayState::State> ArrayState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SVALUE */ {{",", SNEXT}, {"]", SEND}, {0, SERROR}}, /* SNEXT */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; std::string validate_name(std::string const& name) { if (name.empty()) { JSONCC_THROW(EMPTY_NAME); } return name; } /* State engine config for Json::Object */ class ObjectState : public ParserState { protected: ObjectState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SNAME, SSEP, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SNAME: key = validate_name(tokenizer.token.str_value); break; case SVALUE: result << Json::Member(std::move(key), parse_value()); break; case SNEXT: break; case SEND: break; case SSEP: break; case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_OBJECT_START); case SNAME: JSONCC_THROW(BAD_TOKEN_OBJECT_NAME); case SSEP: JSONCC_THROW(BAD_TOKEN_OBJECT_SEP); case SVALUE: JSONCC_THROW(BAD_TOKEN_OBJECT_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_OBJECT_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } std::string key; Json::Object result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ObjectState::State> ObjectState::transitions[SMAX][SMAX] = { /* SO_ERROR */ { {0, SERROR}}, /* SO_START */ {{"\"", SNAME}, {"}", SEND}, {0, SERROR}}, /* SO_NAME */ {{":", SSEP}, {0, SERROR}}, /* SO_SEP */ {{"[{tfn\"0", SVALUE}, {0, SERROR}}, /* SO_VALUE */ {{",", SNEXT}, {"}", SEND}, {0, SERROR}}, /* SO_NEXT */ {{"\"", SNAME}, {0, SERROR}}, /* SO_END */ { {0, SERROR}}, }; /* State engine config for a Json document */ class DocState : public ParserState { protected: DocState(Json::TokenStream & tokenizer_, size_t & depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result = parse_value(); break; case SEND: break; case SSTART: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SVALUE: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Value result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<DocState::State> DocState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{", SVALUE}, {"", SEND}, {0, SERROR}}, /* SVALUE */ { {"", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; /* select recursive parser for nested constructs */ Json::Value ParserState::parse_value() { switch (tokenizer.token.type) { case Json::Token::TRUE_LITERAL: return Json::True(); case Json::Token::FALSE_LITERAL: return Json::False(); case Json::Token::NULL_LITERAL: return Json::Null(); case Json::Token::STRING: return tokenizer.token.str_value; case Json::Token::NUMBER: if (tokenizer.token.number_type == Json::Token::FLOAT) { return Json::Number(tokenizer.token.float_value); } else { return Json::Number(tokenizer.token.int_value); } break; case Json::Token::BEGIN_ARRAY: return StateEngine<ArrayState>(tokenizer, depth_).parse(); case Json::Token::BEGIN_OBJECT: return StateEngine<ObjectState>(tokenizer, depth_).parse(); case Json::Token::END: assert(false); // LCOV_EXCL_LINE case Json::Token::INVALID: assert(false); // LCOV_EXCL_LINE case Json::Token::END_ARRAY: assert(false); // LCOV_EXCL_LINE case Json::Token::END_OBJECT: assert(false); // LCOV_EXCL_LINE case Json::Token::NAME_SEPARATOR: assert(false); // LCOV_EXCL_LINE case Json::Token::VALUE_SEPARATOR: assert(false); // LCOV_EXCL_LINE } JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE return Json::Value(); } } namespace Json { /* Toplevel parser for a single document */ Value ParserImpl::parse(char const * data, size_t size) { Utf8Stream utf8stream(data, size); TokenStream tokenizer(utf8stream); try { return StateEngine<DocState>(tokenizer, 0).parse(); } catch (Error & e) { throw; } } } <commit_msg>Parser: move result member on return<commit_after>/* Copyright (c) 2015, 2016, Andreas Fett. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <cassert> #include <cstring> #include "parser-impl.h" #include "error.h" #include "token-stream.h" #include "utf8stream.h" namespace { /* * Generic parser state engine * Check all transitions for the current State * until the token is found in Transition::match, * change to the associated state. * * Instances of this are build for Document, Array and Object */ template <typename State> struct Transition { const char *match; State state; }; template <typename T> class StateEngine : public T { public: StateEngine(Json::TokenStream & tokenizer_, size_t depth) : T(tokenizer_, depth) { } Json::Value parse() { auto state(T::SSTART); do { T::tokenizer.scan(); state = transition(T::tokenizer.token.type, state); } while (state != T::SEND); return std::move(T::result); } private: typename T::State transition(Json::Token::Type token, typename T::State state) { for (auto t(0); t < T::SMAX; ++t) { if (!is_match(token, T::transitions[state][t].match)) { continue; } auto nstate(T::transitions[state][t].state); if (nstate == T::SERROR) { T::throw_error(state); JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } else { T::build(nstate); } return nstate; } return T::SERROR; } bool is_match(Json::Token::Type token, const char *match) const { return !match || (!match[0] && token == Json::Token::END) || strchr(match, token); } }; /* Base class for state engine configurations */ class ParserState { protected: ParserState(Json::TokenStream & tokenizer_, size_t depth) : tokenizer(tokenizer_), depth_(depth + 1) { if (depth > 255) { JSONCC_THROW(PARSER_OVERFLOW); } } Json::Value parse_value(); Json::TokenStream & tokenizer; private: size_t depth_; }; /* State engine config for Json::Array */ class ArrayState : public ParserState { protected: ArrayState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result << parse_value(); break; case SNEXT: break; case SEND: break; case SMAX: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_ARRAY_START); case SVALUE: JSONCC_THROW(BAD_TOKEN_ARRAY_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_ARRAY_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Array result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ArrayState::State> ArrayState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SVALUE */ {{",", SNEXT}, {"]", SEND}, {0, SERROR}}, /* SNEXT */ {{"[{tfn\"0", SVALUE}, {"]", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; std::string validate_name(std::string const& name) { if (name.empty()) { JSONCC_THROW(EMPTY_NAME); } return name; } /* State engine config for Json::Object */ class ObjectState : public ParserState { protected: ObjectState(Json::TokenStream & tokenizer_, size_t depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SNAME, SSEP, SVALUE, SNEXT, SEND, SMAX, }; void build(State state) { switch (state) { case SNAME: key = validate_name(tokenizer.token.str_value); break; case SVALUE: result << Json::Member(std::move(key), parse_value()); break; case SNEXT: break; case SEND: break; case SSEP: break; case SERROR: assert(false); // LCOV_EXCL_LINE case SSTART: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_OBJECT_START); case SNAME: JSONCC_THROW(BAD_TOKEN_OBJECT_NAME); case SSEP: JSONCC_THROW(BAD_TOKEN_OBJECT_SEP); case SVALUE: JSONCC_THROW(BAD_TOKEN_OBJECT_VALUE); case SNEXT: JSONCC_THROW(BAD_TOKEN_OBJECT_NEXT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } std::string key; Json::Object result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<ObjectState::State> ObjectState::transitions[SMAX][SMAX] = { /* SO_ERROR */ { {0, SERROR}}, /* SO_START */ {{"\"", SNAME}, {"}", SEND}, {0, SERROR}}, /* SO_NAME */ {{":", SSEP}, {0, SERROR}}, /* SO_SEP */ {{"[{tfn\"0", SVALUE}, {0, SERROR}}, /* SO_VALUE */ {{",", SNEXT}, {"}", SEND}, {0, SERROR}}, /* SO_NEXT */ {{"\"", SNAME}, {0, SERROR}}, /* SO_END */ { {0, SERROR}}, }; /* State engine config for a Json document */ class DocState : public ParserState { protected: DocState(Json::TokenStream & tokenizer_, size_t & depth) : ParserState(tokenizer_, depth) { } enum State { SERROR = 0, SSTART, SVALUE, SEND, SMAX, }; void build(State state) { switch (state) { case SVALUE: result = parse_value(); break; case SEND: break; case SSTART: assert(false); // LCOV_EXCL_LINE case SERROR: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE } } void throw_error(State state) const { switch (state) { case SSTART: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SVALUE: JSONCC_THROW(BAD_TOKEN_DOCUMENT); case SERROR: assert(false); // LCOV_EXCL_LINE case SEND: assert(false); // LCOV_EXCL_LINE case SMAX: assert(false); // LCOV_EXCL_LINE } } Json::Value result; static Transition<State> transitions[SMAX][SMAX]; }; Transition<DocState::State> DocState::transitions[SMAX][SMAX] = { /* SERROR */ { {0, SERROR}}, /* SSTART */ {{"[{", SVALUE}, {"", SEND}, {0, SERROR}}, /* SVALUE */ { {"", SEND}, {0, SERROR}}, /* SEND */ { {0, SERROR}}, }; /* select recursive parser for nested constructs */ Json::Value ParserState::parse_value() { switch (tokenizer.token.type) { case Json::Token::TRUE_LITERAL: return Json::True(); case Json::Token::FALSE_LITERAL: return Json::False(); case Json::Token::NULL_LITERAL: return Json::Null(); case Json::Token::STRING: return tokenizer.token.str_value; case Json::Token::NUMBER: if (tokenizer.token.number_type == Json::Token::FLOAT) { return Json::Number(tokenizer.token.float_value); } else { return Json::Number(tokenizer.token.int_value); } break; case Json::Token::BEGIN_ARRAY: return StateEngine<ArrayState>(tokenizer, depth_).parse(); case Json::Token::BEGIN_OBJECT: return StateEngine<ObjectState>(tokenizer, depth_).parse(); case Json::Token::END: assert(false); // LCOV_EXCL_LINE case Json::Token::INVALID: assert(false); // LCOV_EXCL_LINE case Json::Token::END_ARRAY: assert(false); // LCOV_EXCL_LINE case Json::Token::END_OBJECT: assert(false); // LCOV_EXCL_LINE case Json::Token::NAME_SEPARATOR: assert(false); // LCOV_EXCL_LINE case Json::Token::VALUE_SEPARATOR: assert(false); // LCOV_EXCL_LINE } JSONCC_THROW(INTERNAL_ERROR); // LCOV_EXCL_LINE return Json::Value(); } } namespace Json { /* Toplevel parser for a single document */ Value ParserImpl::parse(char const * data, size_t size) { Utf8Stream utf8stream(data, size); TokenStream tokenizer(utf8stream); try { return StateEngine<DocState>(tokenizer, 0).parse(); } catch (Error & e) { throw; } } } <|endoftext|>
<commit_before>// Copyright (c) 2016-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <policy/rbf.h> #include <policy/policy.h> #include <policy/settings.h> #include <tinyformat.h> #include <util/moneystr.h> #include <util/rbf.h> RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool) { AssertLockHeld(pool.cs); CTxMemPool::setEntries ancestors; // First check the transaction itself. if (SignalsOptInRBF(tx)) { return RBFTransactionState::REPLACEABLE_BIP125; } // If this transaction is not in our mempool, then we can't be sure // we will know about all its inputs. if (!pool.exists(GenTxid::Txid(tx.GetHash()))) { return RBFTransactionState::UNKNOWN; } // If all the inputs have nSequence >= maxint-1, it still might be // signaled for RBF if any unconfirmed parents have signaled. uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash()); pool.CalculateMemPoolAncestors(entry, ancestors, noLimit, noLimit, noLimit, noLimit, dummy, false); for (CTxMemPool::txiter it : ancestors) { if (SignalsOptInRBF(it->GetTx())) { return RBFTransactionState::REPLACEABLE_BIP125; } } return RBFTransactionState::FINAL; } RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx) { // If we don't have a local mempool we can only check the transaction itself. return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN; } std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx, CTxMemPool& pool, const CTxMemPool::setEntries& iters_conflicting, CTxMemPool::setEntries& all_conflicts, const ignore_rejects_type& ignore_rejects) { AssertLockHeld(pool.cs); const uint256 txid = tx.GetHash(); uint64_t nConflictingCount = 0; for (const auto& mi : iters_conflicting) { nConflictingCount += mi->GetCountWithDescendants(); // BIP125 Rule #5: don't consider replacing more than MAX_BIP125_REPLACEMENT_CANDIDATES // entries from the mempool. This potentially overestimates the number of actual // descendants (i.e. if multiple conflicts share a descendant, it will be counted multiple // times), but we just want to be conservative to avoid doing too much work. if (nConflictingCount > MAX_BIP125_REPLACEMENT_CANDIDATES && !ignore_rejects.count("too-many-replacements")) { return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n", txid.ToString(), nConflictingCount, MAX_BIP125_REPLACEMENT_CANDIDATES); } } // Calculate the set of all transactions that would have to be evicted. for (CTxMemPool::txiter it : iters_conflicting) { pool.CalculateDescendants(it, all_conflicts); } return std::nullopt; } std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx, const CTxMemPool& pool, const CTxMemPool::setEntries& iters_conflicting) { AssertLockHeld(pool.cs); std::set<uint256> parents_of_conflicts; for (const auto& mi : iters_conflicting) { for (const CTxIn& txin : mi->GetTx().vin) { parents_of_conflicts.insert(txin.prevout.hash); } } for (unsigned int j = 0; j < tx.vin.size(); j++) { // BIP125 Rule #2: We don't want to accept replacements that require low feerate junk to be // mined first. Ideally we'd keep track of the ancestor feerates and make the decision // based on that, but for now requiring all new inputs to be confirmed works. // // Note that if you relax this to make RBF a little more useful, this may break the // CalculateMempoolAncestors RBF relaxation which subtracts the conflict count/size from the // descendant limit. if (!parents_of_conflicts.count(tx.vin[j].prevout.hash)) { // Rather than check the UTXO set - potentially expensive - it's cheaper to just check // if the new input refers to a tx that's in the mempool. if (pool.exists(GenTxid::Txid(tx.vin[j].prevout.hash))) { return strprintf("replacement %s adds unconfirmed input, idx %d", tx.GetHash().ToString(), j); } } } return std::nullopt; } std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors, const std::set<uint256>& direct_conflicts, const uint256& txid) { for (CTxMemPool::txiter ancestorIt : ancestors) { const uint256& hashAncestor = ancestorIt->GetTx().GetHash(); if (direct_conflicts.count(hashAncestor)) { return strprintf("%s spends conflicting transaction %s", txid.ToString(), hashAncestor.ToString()); } } return std::nullopt; } std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting, CFeeRate replacement_feerate, const uint256& txid) { for (const auto& mi : iters_conflicting) { // Don't allow the replacement to reduce the feerate of the mempool. // // We usually don't want to accept replacements with lower feerates than what they replaced // as that would lower the feerate of the next block. Requiring that the feerate always be // increased is also an easy-to-reason about way to prevent DoS attacks via replacements. // // We only consider the feerates of transactions being directly replaced, not their indirect // descendants. While that does mean high feerate children are ignored when deciding whether // or not to replace, we do require the replacement to pay more overall fees too, mitigating // most cases. CFeeRate original_feerate(mi->GetModifiedFee(), mi->GetTxSize()); if (replacement_feerate <= original_feerate) { return strprintf("rejecting replacement %s; new feerate %s <= old feerate %s", txid.ToString(), replacement_feerate.ToString(), original_feerate.ToString()); } } return std::nullopt; } std::optional<std::string> PaysForRBF(CAmount original_fees, CAmount replacement_fees, size_t replacement_vsize, CFeeRate relay_fee, const uint256& txid) { // BIP125 Rule #3: The replacement fees must be greater than or equal to fees of the // transactions it replaces, otherwise the bandwidth used by those conflicting transactions // would not be paid for. if (replacement_fees < original_fees) { return strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s", txid.ToString(), FormatMoney(replacement_fees), FormatMoney(original_fees)); } // BIP125 Rule #4: The new transaction must pay for its own bandwidth. Otherwise, we have a DoS // vector where attackers can cause a transaction to be replaced (and relayed) repeatedly by // increasing the fee by tiny amounts. CAmount additional_fees = replacement_fees - original_fees; if (additional_fees < relay_fee.GetFee(replacement_vsize)) { return strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s", txid.ToString(), FormatMoney(additional_fees), FormatMoney(relay_fee.GetFee(replacement_vsize))); } return std::nullopt; } <commit_msg>Bugfix: policy/rbf: Recognise "too many potential replacements" string in ignore_rejects<commit_after>// Copyright (c) 2016-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <policy/rbf.h> #include <policy/policy.h> #include <policy/settings.h> #include <tinyformat.h> #include <util/moneystr.h> #include <util/rbf.h> RBFTransactionState IsRBFOptIn(const CTransaction& tx, const CTxMemPool& pool) { AssertLockHeld(pool.cs); CTxMemPool::setEntries ancestors; // First check the transaction itself. if (SignalsOptInRBF(tx)) { return RBFTransactionState::REPLACEABLE_BIP125; } // If this transaction is not in our mempool, then we can't be sure // we will know about all its inputs. if (!pool.exists(GenTxid::Txid(tx.GetHash()))) { return RBFTransactionState::UNKNOWN; } // If all the inputs have nSequence >= maxint-1, it still might be // signaled for RBF if any unconfirmed parents have signaled. uint64_t noLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; CTxMemPoolEntry entry = *pool.mapTx.find(tx.GetHash()); pool.CalculateMemPoolAncestors(entry, ancestors, noLimit, noLimit, noLimit, noLimit, dummy, false); for (CTxMemPool::txiter it : ancestors) { if (SignalsOptInRBF(it->GetTx())) { return RBFTransactionState::REPLACEABLE_BIP125; } } return RBFTransactionState::FINAL; } RBFTransactionState IsRBFOptInEmptyMempool(const CTransaction& tx) { // If we don't have a local mempool we can only check the transaction itself. return SignalsOptInRBF(tx) ? RBFTransactionState::REPLACEABLE_BIP125 : RBFTransactionState::UNKNOWN; } std::optional<std::string> GetEntriesForConflicts(const CTransaction& tx, CTxMemPool& pool, const CTxMemPool::setEntries& iters_conflicting, CTxMemPool::setEntries& all_conflicts, const ignore_rejects_type& ignore_rejects) { AssertLockHeld(pool.cs); const uint256 txid = tx.GetHash(); uint64_t nConflictingCount = 0; for (const auto& mi : iters_conflicting) { nConflictingCount += mi->GetCountWithDescendants(); // BIP125 Rule #5: don't consider replacing more than MAX_BIP125_REPLACEMENT_CANDIDATES // entries from the mempool. This potentially overestimates the number of actual // descendants (i.e. if multiple conflicts share a descendant, it will be counted multiple // times), but we just want to be conservative to avoid doing too much work. if (nConflictingCount > MAX_BIP125_REPLACEMENT_CANDIDATES && !ignore_rejects.count("too-many-replacements") && !ignore_rejects.count("too many potential replacements")) { return strprintf("rejecting replacement %s; too many potential replacements (%d > %d)\n", txid.ToString(), nConflictingCount, MAX_BIP125_REPLACEMENT_CANDIDATES); } } // Calculate the set of all transactions that would have to be evicted. for (CTxMemPool::txiter it : iters_conflicting) { pool.CalculateDescendants(it, all_conflicts); } return std::nullopt; } std::optional<std::string> HasNoNewUnconfirmed(const CTransaction& tx, const CTxMemPool& pool, const CTxMemPool::setEntries& iters_conflicting) { AssertLockHeld(pool.cs); std::set<uint256> parents_of_conflicts; for (const auto& mi : iters_conflicting) { for (const CTxIn& txin : mi->GetTx().vin) { parents_of_conflicts.insert(txin.prevout.hash); } } for (unsigned int j = 0; j < tx.vin.size(); j++) { // BIP125 Rule #2: We don't want to accept replacements that require low feerate junk to be // mined first. Ideally we'd keep track of the ancestor feerates and make the decision // based on that, but for now requiring all new inputs to be confirmed works. // // Note that if you relax this to make RBF a little more useful, this may break the // CalculateMempoolAncestors RBF relaxation which subtracts the conflict count/size from the // descendant limit. if (!parents_of_conflicts.count(tx.vin[j].prevout.hash)) { // Rather than check the UTXO set - potentially expensive - it's cheaper to just check // if the new input refers to a tx that's in the mempool. if (pool.exists(GenTxid::Txid(tx.vin[j].prevout.hash))) { return strprintf("replacement %s adds unconfirmed input, idx %d", tx.GetHash().ToString(), j); } } } return std::nullopt; } std::optional<std::string> EntriesAndTxidsDisjoint(const CTxMemPool::setEntries& ancestors, const std::set<uint256>& direct_conflicts, const uint256& txid) { for (CTxMemPool::txiter ancestorIt : ancestors) { const uint256& hashAncestor = ancestorIt->GetTx().GetHash(); if (direct_conflicts.count(hashAncestor)) { return strprintf("%s spends conflicting transaction %s", txid.ToString(), hashAncestor.ToString()); } } return std::nullopt; } std::optional<std::string> PaysMoreThanConflicts(const CTxMemPool::setEntries& iters_conflicting, CFeeRate replacement_feerate, const uint256& txid) { for (const auto& mi : iters_conflicting) { // Don't allow the replacement to reduce the feerate of the mempool. // // We usually don't want to accept replacements with lower feerates than what they replaced // as that would lower the feerate of the next block. Requiring that the feerate always be // increased is also an easy-to-reason about way to prevent DoS attacks via replacements. // // We only consider the feerates of transactions being directly replaced, not their indirect // descendants. While that does mean high feerate children are ignored when deciding whether // or not to replace, we do require the replacement to pay more overall fees too, mitigating // most cases. CFeeRate original_feerate(mi->GetModifiedFee(), mi->GetTxSize()); if (replacement_feerate <= original_feerate) { return strprintf("rejecting replacement %s; new feerate %s <= old feerate %s", txid.ToString(), replacement_feerate.ToString(), original_feerate.ToString()); } } return std::nullopt; } std::optional<std::string> PaysForRBF(CAmount original_fees, CAmount replacement_fees, size_t replacement_vsize, CFeeRate relay_fee, const uint256& txid) { // BIP125 Rule #3: The replacement fees must be greater than or equal to fees of the // transactions it replaces, otherwise the bandwidth used by those conflicting transactions // would not be paid for. if (replacement_fees < original_fees) { return strprintf("rejecting replacement %s, less fees than conflicting txs; %s < %s", txid.ToString(), FormatMoney(replacement_fees), FormatMoney(original_fees)); } // BIP125 Rule #4: The new transaction must pay for its own bandwidth. Otherwise, we have a DoS // vector where attackers can cause a transaction to be replaced (and relayed) repeatedly by // increasing the fee by tiny amounts. CAmount additional_fees = replacement_fees - original_fees; if (additional_fees < relay_fee.GetFee(replacement_vsize)) { return strprintf("rejecting replacement %s, not enough additional fees to relay; %s < %s", txid.ToString(), FormatMoney(additional_fees), FormatMoney(relay_fee.GetFee(replacement_vsize))); } return std::nullopt; } <|endoftext|>
<commit_before>/* * ============================================================================ * * Filename: gbsqc.cc * Description: A GBS quality control pipeline * License: LGPL-3+ * Author: Kevin Murray, [email protected] * * ============================================================================ */ /* Copyright (c) 2015 Kevin Murray * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <fstream> #include <string> #include <chrono> #include <iomanip> #include <getopt.h> #include "qcpp.hh" #include "qc-measure.hh" #include "qc-length.hh" #include "qc-qualtrim.hh" #include "qc-gbs.hh" #include "qc-adaptor.hh" using std::chrono::system_clock; inline void progress(size_t n, system_clock::time_point start) { std::chrono::duration<double> tdiff = system_clock::now() - start; double secs = tdiff.count(); double k_reads = n / 1000.0; double rate = k_reads / secs; std::cerr << "\x1b[2K" << "Kept " << k_reads << "K read pairs in " << (int)secs << "s (" << std::setprecision(3) << rate << std::setprecision(9) << "K RP/sec)\r"; } int usage_err() { using std::cerr; using std::endl; cerr << "USAGE: gbsqc [-b -y REPORT -o OUTPUT] <read_file>" << std::endl << std::endl; cerr << "OPTIONS:" << endl; cerr << " -b Use broken-paired output (don't keep read pairing) [default: false]" << endl; cerr << " -y YAML YAML report file. [default: none]" << endl; cerr << " -o OUTPUT Output file. [default: stdout]" << endl; return EXIT_FAILURE; } const char *cli_opts = "y:o:b"; int main (int argc, char *argv[]) { using namespace qcpp; std::string yaml_fname; bool broken_paired = false; bool use_stdout = true; std::ofstream read_output; int c = 0; while ((c = getopt(argc, argv, cli_opts)) > 0) { switch (c) { case 'y': yaml_fname = optarg; break; case 'o': read_output.open(optarg); use_stdout = false; break; case 'b': broken_paired = true; break; default: std::cerr << "Bad arg '" << std::string(1, optopt) << "'" << std::endl << std::endl; return usage_err(); } } if (optind + 1 > argc) { std::cerr << "Must provide filename" << std::endl << std::endl; return usage_err(); } ReadPair rp; ProcessedReadStream stream(argv[optind]); uint64_t n_pairs = 0; bool qc_before = false; if (qc_before) { stream.append_processor<PerBaseQuality>("before qc"); } stream.append_processor<AdaptorTrimPE>("trim or merge reads", 10); stream.append_processor<WindowedQualTrim>("QC", SangerEncoding, 28, 64); stream.append_processor<PerBaseQuality>("after qc"); system_clock::time_point start = system_clock::now(); while (stream.parse_read_pair(rp)) { if (n_pairs % 100000 == 0) { progress(n_pairs, start); } n_pairs++; if (broken_paired) { if (use_stdout) { if (rp.first.size() >= 64) { std::cout << rp.first.str(); } if (rp.second.size() >= 64) { std::cout << rp.second.str(); } } else { if (rp.first.size() >= 64) { read_output << rp.first.str(); } if (rp.second.size() >= 64) { read_output << rp.second.str(); } } } else { if (use_stdout) { std::cout << rp.str(); } else { read_output << rp.str(); } } } progress(n_pairs, start); std::cerr << std::endl; if (yaml_fname.size() > 0) { std::ofstream yml_output(yaml_fname); yml_output << stream.report(); } return EXIT_SUCCESS; } <commit_msg>Refactor output code in gbsqc<commit_after>/* * ============================================================================ * * Filename: gbsqc.cc * Description: A GBS quality control pipeline * License: LGPL-3+ * Author: Kevin Murray, [email protected] * * ============================================================================ */ /* Copyright (c) 2015 Kevin Murray * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <fstream> #include <string> #include <chrono> #include <iomanip> #include <getopt.h> #include "qcpp.hh" #include "qc-measure.hh" #include "qc-length.hh" #include "qc-qualtrim.hh" #include "qc-gbs.hh" #include "qc-adaptor.hh" using std::chrono::system_clock; inline void progress(size_t n, system_clock::time_point start) { std::chrono::duration<double> tdiff = system_clock::now() - start; double secs = tdiff.count(); double k_reads = n / 1000.0; double rate = k_reads / secs; std::cerr << "\x1b[2K" << "Kept " << k_reads << "K read pairs in " << (int)secs << "s (" << std::setprecision(3) << rate << std::setprecision(9) << "K RP/sec)\r"; } int usage_err() { using std::cerr; using std::endl; cerr << "USAGE: gbsqc [-b -y REPORT -o OUTPUT] <read_file>" << std::endl << std::endl; cerr << "OPTIONS:" << endl; cerr << " -b Use broken-paired output (don't keep read pairing) [default: false]" << endl; cerr << " -y YAML YAML report file. [default: none]" << endl; cerr << " -o OUTPUT Output file. [default: stdout]" << endl; return EXIT_FAILURE; } const char *cli_opts = "y:o:b"; int main (int argc, char *argv[]) { using namespace qcpp; std::string yaml_fname; bool broken_paired = false; bool use_stdout = true; std::ofstream read_output; int c = 0; while ((c = getopt(argc, argv, cli_opts)) > 0) { switch (c) { case 'y': yaml_fname = optarg; break; case 'o': read_output.open(optarg); use_stdout = false; break; case 'b': broken_paired = true; break; default: std::cerr << "Bad arg '" << std::string(1, optopt) << "'" << std::endl << std::endl; return usage_err(); } } if (optind + 1 > argc) { std::cerr << "Must provide filename" << std::endl << std::endl; return usage_err(); } ReadPair rp; ProcessedReadStream stream(argv[optind]); uint64_t n_pairs = 0; bool qc_before = false; if (qc_before) { stream.append_processor<PerBaseQuality>("before qc"); } stream.append_processor<AdaptorTrimPE>("trim or merge reads", 10); stream.append_processor<WindowedQualTrim>("QC", SangerEncoding, 28, 64); stream.append_processor<PerBaseQuality>("after qc"); system_clock::time_point start = system_clock::now(); while (stream.parse_read_pair(rp)) { std::string rp_str = ""; if (broken_paired) { if (rp.first.size() >= 64) { rp_str = rp.first.str(); } if (rp.second.size() >= 64) { rp_str += rp.second.str(); } } else { rp_str = rp.str(); } if (n_pairs % 100000 == 0) { progress(n_pairs, start); } n_pairs++; if (use_stdout) { std::cout << rp_str; } else { read_output << rp_str; } } progress(n_pairs, start); std::cerr << std::endl; if (yaml_fname.size() > 0) { std::ofstream yml_output(yaml_fname); yml_output << stream.report(); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "qtwin.h" #include "headers.h" #include "init.h" #include <QApplication> #include <QMessageBox> #include <QThread> #include <QLocale> #include <QTranslator> #include <QSplashScreen> // Need a global reference for the notifications to find the GUI BitcoinGUI *guiref; QSplashScreen *splashref; int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y) { // Message from main thread if(guiref) { guiref->error(QString::fromStdString(caption), QString::fromStdString(message)); } else { QMessageBox::critical(0, QString::fromStdString(caption), QString::fromStdString(message), QMessageBox::Ok, QMessageBox::Ok); } return 4; } int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y) { // Message from network thread if(guiref) { QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message))); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; // Call slot on GUI thread. // If called from another thread, use a blocking QueuedConnection. Qt::ConnectionType connectionType = Qt::DirectConnection; if(QThread::currentThread() != QCoreApplication::instance()->thread()) { connectionType = Qt::BlockingQueuedConnection; } QMetaObject::invokeMethod(guiref, "askFee", connectionType, Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void CalledSetStatusBar(const std::string& strText, int nField) { // Only used for built-in mining, which is disabled, simple ignore } void UIThreadCall(boost::function0<void> fn) { // Only used for built-in mining, which is disabled, simple ignore } void MainFrameRepaint() { } void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } int main(int argc, char *argv[]) { Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Load language file for system locale QString locale = QLocale::system().name(); QTranslator translator; translator.load("bitcoin_"+locale); app.installTranslator(&translator); QSplashScreen splash(QPixmap(":/images/splash"), Qt::WindowStaysOnTopHint); splash.show(); splash.setAutoFillBackground(true); splashref = &splash; app.processEvents(); app.setQuitOnLastWindowClosed(false); try { if(AppInit2(argc, argv)) { { // Put this in a block, so that BitcoinGUI is cleaned up properly before // calling Shutdown(). BitcoinGUI window; splash.finish(&window); OptionsModel optionsModel(pwalletMain); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); guiref = &window; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); if (QtWin::isCompositionEnabled()) { #ifdef Q_WS_WIN32 // Windows-specific customization window.setAttribute(Qt::WA_TranslucentBackground); window.setAttribute(Qt::WA_NoSystemBackground, false); QPalette pal = window.palette(); QColor bg = pal.window().color(); bg.setAlpha(0); pal.setColor(QPalette::Window, bg); window.setPalette(pal); window.ensurePolished(); window.setAttribute(Qt::WA_StyledBackground, false); #endif QtWin::extendFrameIntoClientArea(&window); window.setContentsMargins(0, 0, 0, 0); } window.show(); app.exec(); guiref = 0; } Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { PrintException(&e, "Runaway exception"); } catch (...) { PrintException(NULL, "Runaway exception"); } return 0; } <commit_msg>fix issue #13<commit_after>/* * W.J. van der Laan 2011 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "qtwin.h" #include "headers.h" #include "init.h" #include <QApplication> #include <QMessageBox> #include <QThread> #include <QLocale> #include <QTranslator> #include <QSplashScreen> // Need a global reference for the notifications to find the GUI BitcoinGUI *guiref; QSplashScreen *splashref; int MyMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y) { // Message from main thread if(guiref) { guiref->error(QString::fromStdString(caption), QString::fromStdString(message)); } else { QMessageBox::critical(0, QString::fromStdString(caption), QString::fromStdString(message), QMessageBox::Ok, QMessageBox::Ok); } return 4; } int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style, wxWindow* parent, int x, int y) { // Message from network thread if(guiref) { QMetaObject::invokeMethod(guiref, "error", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message))); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; // Call slot on GUI thread. // If called from another thread, use a blocking QueuedConnection. Qt::ConnectionType connectionType = Qt::DirectConnection; if(QThread::currentThread() != QCoreApplication::instance()->thread()) { connectionType = Qt::BlockingQueuedConnection; } QMetaObject::invokeMethod(guiref, "askFee", connectionType, Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void CalledSetStatusBar(const std::string& strText, int nField) { // Only used for built-in mining, which is disabled, simple ignore } void UIThreadCall(boost::function0<void> fn) { // Only used for built-in mining, which is disabled, simple ignore } void MainFrameRepaint() { } void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } int main(int argc, char *argv[]) { Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Load language file for system locale QString locale = QLocale::system().name(); QTranslator translator; translator.load("bitcoin_"+locale); app.installTranslator(&translator); QSplashScreen splash(QPixmap(":/images/splash"), 0); splash.show(); splash.setAutoFillBackground(true); splashref = &splash; app.processEvents(); app.setQuitOnLastWindowClosed(false); try { if(AppInit2(argc, argv)) { { // Put this in a block, so that BitcoinGUI is cleaned up properly before // calling Shutdown(). BitcoinGUI window; splash.finish(&window); OptionsModel optionsModel(pwalletMain); ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); guiref = &window; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); if (QtWin::isCompositionEnabled()) { #ifdef Q_WS_WIN32 // Windows-specific customization window.setAttribute(Qt::WA_TranslucentBackground); window.setAttribute(Qt::WA_NoSystemBackground, false); QPalette pal = window.palette(); QColor bg = pal.window().color(); bg.setAlpha(0); pal.setColor(QPalette::Window, bg); window.setPalette(pal); window.ensurePolished(); window.setAttribute(Qt::WA_StyledBackground, false); #endif QtWin::extendFrameIntoClientArea(&window); window.setContentsMargins(0, 0, 0, 0); } window.show(); app.exec(); guiref = 0; } Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { PrintException(&e, "Runaway exception"); } catch (...) { PrintException(NULL, "Runaway exception"); } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2014, Nicolas Mansard, LAAS-CNRS * * This file is part of eigenpy. * eigenpy is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __eigenpy_quaternion_hpp__ #define __eigenpy_quaternion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "eigenpy/exception.hpp" namespace eigenpy { class ExceptionIndex : public Exception { public: ExceptionIndex(int index,int imin,int imax) : Exception("") { std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<"."; message = oss.str(); } }; namespace bp = boost::python; template<typename Quaternion> class QuaternionVisitor : public boost::python::def_visitor< QuaternionVisitor<Quaternion> > { typedef Eigen::QuaternionBase<Quaternion> QuaternionBase; typedef typename QuaternionBase::Scalar Scalar; typedef typename Quaternion::Coefficients Coefficients; typedef typename QuaternionBase::Vector3 Vector3; typedef typename Eigen::Matrix<Scalar,4,1> Vector4; typedef typename QuaternionBase::Matrix3 Matrix3; typedef typename QuaternionBase::AngleAxisType AngleAxis; public: template<class PyClass> void visit(PyClass& cl) const { cl .def(bp::init<>("Default constructor")) .def(bp::init<Matrix3>((bp::arg("matrixRotation")),"Initialize from rotation matrix.")) .def(bp::init<AngleAxis>((bp::arg("angleaxis")),"Initialize from angle axis.")) .def(bp::init<Quaternion>((bp::arg("clone")),"Copy constructor.")) .def("__init__",bp::make_constructor(&QuaternionVisitor::fromTwoVectors, bp::default_call_policies(), (bp::arg("u"),bp::arg("v"))),"Initialize from two vector u,v") .def(bp::init<Scalar,Scalar,Scalar,Scalar> ((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")), "Initialize from coefficients.\n\n" "... note:: The order of coefficients is *w*, *x*, *y*, *z*. " "The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!")) .add_property("x", (Scalar (Quaternion::*)()const)&Quaternion::x, &QuaternionVisitor::setCoeff<0>,"The x coefficient.") .add_property("y", (Scalar (Quaternion::*)()const)&Quaternion::y, &QuaternionVisitor::setCoeff<1>,"The y coefficient.") .add_property("z", (Scalar (Quaternion::*)()const)&Quaternion::z, &QuaternionVisitor::setCoeff<2>,"The z coefficient.") .add_property("w", (Scalar (Quaternion::*)()const)&Quaternion::w, &QuaternionVisitor::setCoeff<3>,"The w coefficient.") .def("isApprox",(bool (Quaternion::*)(const Quaternion &))&Quaternion::template isApprox<Quaternion>, "Returns true if *this is approximately equal to other.") .def("isApprox",(bool (Quaternion::*)(const Quaternion &, const Scalar prec))&Quaternion::template isApprox<Quaternion>, "Returns true if *this is approximately equal to other, within the precision determined by prec..") /* --- Methods --- */ .def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs, bp::return_value_policy<bp::copy_const_reference>()) .def("matrix",&Quaternion::matrix,"Returns an equivalent rotation matrix") .def("toRotationMatrix ",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.") .def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transform a into b through a rotation." ,bp::return_self<>()) .def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.") .def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.") .def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.") .def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.") .def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.") .def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.") .def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.") .def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other" "Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.") .def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.") .def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).") .def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.") .def("slerp",&Quaternion::template slerp<Quaternion>,bp::args("t","other"), "Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].") /* --- Operators --- */ .def(bp::self * bp::self) .def(bp::self *= bp::self) .def(bp::self * bp::other<Vector3>()) .def("__eq__",&QuaternionVisitor::__eq__) .def("__ne__",&QuaternionVisitor::__ne__) .def("__abs__",&Quaternion::norm) .def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__") .def("__setitem__",&QuaternionVisitor::__setitem__) .def("__getitem__",&QuaternionVisitor::__getitem__) .def("assign",&assign<Quaternion>, bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>()) .def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=, bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>()) .def("__str__",&print) .def("__repr__",&print) .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>, bp::args("a","b"), "Returns the quaternion which transform a into b through a rotation.") .staticmethod("FromTwoVectors") .def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.") .staticmethod("Identity") ; } private: template<int i> static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; } static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b) { return self.setFromTwoVectors(a,b); } template<typename OtherQuat> static Quaternion & assign(Quaternion & self, const OtherQuat & quat) { return self = quat; } static Quaternion* fromTwoVectors(const Vector3& u, const Vector3& v) { Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v); return q; } static bool __eq__(const Quaternion& u, const Quaternion& v) { return u.isApprox(v,1e-9); } static bool __ne__(const Quaternion& u, const Quaternion& v) { return !__eq__(u,v); } static Scalar __getitem__(const Quaternion & self, int idx) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); return self.coeffs()[idx]; } static void __setitem__(Quaternion& self, int idx, const Scalar value) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); self.coeffs()[idx] = value; } static int __len__() { return 4; } static Vector3 vec(const Quaternion & self) { return self.vec(); } static std::string print(const Quaternion & self) { std::stringstream ss; ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl; return ss.str(); } public: static void expose() { bp::class_<Quaternion>("Quaternion", "Quaternion representing rotation.\n\n" "Supported operations " "('q is a Quaternion, 'v' is a Vector3): " "'q*q' (rotation composition), " "'q*=q', " "'q*v' (rotating 'v' by 'q'), " "'q==q', 'q!=q', 'q[0..3]'.", bp::no_init) .def(QuaternionVisitor<Quaternion>()) ; } }; } // namespace eigenpy #endif // ifndef __eigenpy_quaternion_hpp__ <commit_msg>[Quaternion] Remove depending version methods<commit_after>/* * Copyright 2014, Nicolas Mansard, LAAS-CNRS * * This file is part of eigenpy. * eigenpy is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __eigenpy_quaternion_hpp__ #define __eigenpy_quaternion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "eigenpy/exception.hpp" namespace eigenpy { class ExceptionIndex : public Exception { public: ExceptionIndex(int index,int imin,int imax) : Exception("") { std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<"."; message = oss.str(); } }; namespace bp = boost::python; template<typename Quaternion> class QuaternionVisitor : public boost::python::def_visitor< QuaternionVisitor<Quaternion> > { typedef Eigen::QuaternionBase<Quaternion> QuaternionBase; typedef typename QuaternionBase::Scalar Scalar; typedef typename Quaternion::Coefficients Coefficients; typedef typename QuaternionBase::Vector3 Vector3; typedef typename Eigen::Matrix<Scalar,4,1> Vector4; typedef typename QuaternionBase::Matrix3 Matrix3; typedef typename QuaternionBase::AngleAxisType AngleAxis; public: template<class PyClass> void visit(PyClass& cl) const { cl .def(bp::init<>("Default constructor")) .def(bp::init<Matrix3>((bp::arg("matrixRotation")),"Initialize from rotation matrix.")) .def(bp::init<AngleAxis>((bp::arg("angleaxis")),"Initialize from angle axis.")) .def(bp::init<Quaternion>((bp::arg("clone")),"Copy constructor.")) .def("__init__",bp::make_constructor(&QuaternionVisitor::fromTwoVectors, bp::default_call_policies(), (bp::arg("u"),bp::arg("v"))),"Initialize from two vector u,v") .def(bp::init<Scalar,Scalar,Scalar,Scalar> ((bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")), "Initialize from coefficients.\n\n" "... note:: The order of coefficients is *w*, *x*, *y*, *z*. " "The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!")) .add_property("x", (Scalar (Quaternion::*)()const)&Quaternion::x, &QuaternionVisitor::setCoeff<0>,"The x coefficient.") .add_property("y", (Scalar (Quaternion::*)()const)&Quaternion::y, &QuaternionVisitor::setCoeff<1>,"The y coefficient.") .add_property("z", (Scalar (Quaternion::*)()const)&Quaternion::z, &QuaternionVisitor::setCoeff<2>,"The z coefficient.") .add_property("w", (Scalar (Quaternion::*)()const)&Quaternion::w, &QuaternionVisitor::setCoeff<3>,"The w coefficient.") .def("isApprox",(bool (Quaternion::*)(const Quaternion &))&Quaternion::template isApprox<Quaternion>, "Returns true if *this is approximately equal to other.") .def("isApprox",(bool (Quaternion::*)(const Quaternion &, const Scalar prec))&Quaternion::template isApprox<Quaternion>, "Returns true if *this is approximately equal to other, within the precision determined by prec..") /* --- Methods --- */ .def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs, bp::return_value_policy<bp::copy_const_reference>()) .def("matrix",&Quaternion::matrix,"Returns an equivalent rotation matrix") .def("toRotationMatrix ",&Quaternion::toRotationMatrix,"Returns an equivalent 3x3 rotation matrix.") .def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("a"),bp::arg("b"))),"Set *this to be the quaternion which transform a into b through a rotation." ,bp::return_self<>()) .def("conjugate",&Quaternion::conjugate,"Returns the conjugated quaternion. The conjugate of a quaternion represents the opposite rotation.") .def("inverse",&Quaternion::inverse,"Returns the quaternion describing the inverse rotation.") .def("setIdentity",&Quaternion::setIdentity,bp::return_self<>(),"Set *this to the idendity rotation.") .def("norm",&Quaternion::norm,"Returns the norm of the quaternion's coefficients.") .def("normalize",&Quaternion::normalize,"Normalizes the quaternion *this.") .def("normalized",&Quaternion::normalized,"Returns a normalized copy of *this.") .def("squaredNorm",&Quaternion::squaredNorm,"Returns the squared norm of the quaternion's coefficients.") .def("dot",&Quaternion::template dot<Quaternion>,bp::arg("other"),"Returns the dot product of *this with other" "Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.") .def("_transformVector",&Quaternion::_transformVector,bp::arg("vector"),"Rotation of a vector by a quaternion.") .def("vec",&vec,"Returns a vector expression of the imaginary part (x,y,z).") .def("angularDistance",&Quaternion::template angularDistance<Quaternion>,"Returns the angle (in radian) between two rotations.") .def("slerp",&Quaternion::template slerp<Quaternion>,bp::args("t","other"), "Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].") /* --- Operators --- */ .def(bp::self * bp::self) .def(bp::self *= bp::self) .def(bp::self * bp::other<Vector3>()) .def("__eq__",&QuaternionVisitor::__eq__) .def("__ne__",&QuaternionVisitor::__ne__) .def("__abs__",&Quaternion::norm) .def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__") .def("__setitem__",&QuaternionVisitor::__setitem__) .def("__getitem__",&QuaternionVisitor::__getitem__) .def("assign",&assign<Quaternion>, bp::arg("quat"),"Set *this from an quaternion quat and returns a reference to *this.",bp::return_self<>()) .def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=, bp::arg("aa"),"Set *this from an angle-axis aa and returns a reference to *this.",bp::return_self<>()) .def("__str__",&print) .def("__repr__",&print) // .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>, // bp::args("a","b"), // "Returns the quaternion which transform a into b through a rotation.") .staticmethod("FromTwoVectors") .def("Identity",&Quaternion::Identity,"Returns a quaternion representing an identity rotation.") .staticmethod("Identity") ; } private: template<int i> static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; } static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b) { return self.setFromTwoVectors(a,b); } template<typename OtherQuat> static Quaternion & assign(Quaternion & self, const OtherQuat & quat) { return self = quat; } static Quaternion* fromTwoVectors(const Vector3& u, const Vector3& v) { Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v); return q; } static bool __eq__(const Quaternion& u, const Quaternion& v) { return u.isApprox(v,1e-9); } static bool __ne__(const Quaternion& u, const Quaternion& v) { return !__eq__(u,v); } static Scalar __getitem__(const Quaternion & self, int idx) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); return self.coeffs()[idx]; } static void __setitem__(Quaternion& self, int idx, const Scalar value) { if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3); self.coeffs()[idx] = value; } static int __len__() { return 4; } static Vector3 vec(const Quaternion & self) { return self.vec(); } static std::string print(const Quaternion & self) { std::stringstream ss; ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl; return ss.str(); } public: static void expose() { bp::class_<Quaternion>("Quaternion", "Quaternion representing rotation.\n\n" "Supported operations " "('q is a Quaternion, 'v' is a Vector3): " "'q*q' (rotation composition), " "'q*=q', " "'q*v' (rotating 'v' by 'q'), " "'q==q', 'q!=q', 'q[0..3]'.", bp::no_init) .def(QuaternionVisitor<Quaternion>()) ; } }; } // namespace eigenpy #endif // ifndef __eigenpy_quaternion_hpp__ <|endoftext|>
<commit_before>#include "qzmqsocket.h" #include <stdio.h> #include <assert.h> #include <QStringList> #include <QTimer> #include <QSocketNotifier> #include <QMutex> #include <zmq.h> #include "qzmqcontext.h" namespace QZmq { static bool get_rcvmore(void *sock) { qint64 more; size_t opt_len = sizeof(more); int ret = zmq_getsockopt(sock, ZMQ_RCVMORE, &more, &opt_len); assert(ret == 0); return more ? true : false; } static int get_fd(void *sock) { int fd; size_t opt_len = sizeof(fd); int ret = zmq_getsockopt(sock, ZMQ_FD, &fd, &opt_len); assert(ret == 0); return fd; } static int get_events(void *sock) { quint32 events; size_t opt_len = sizeof(events); int ret = zmq_getsockopt(sock, ZMQ_EVENTS, &events, &opt_len); assert(ret == 0); return (int)events; } static void set_subscribe(void *sock, const char *data, int size) { size_t opt_len = size; int ret = zmq_setsockopt(sock, ZMQ_SUBSCRIBE, data, opt_len); assert(ret == 0); } static void set_unsubscribe(void *sock, const char *data, int size) { size_t opt_len = size; zmq_setsockopt(sock, ZMQ_UNSUBSCRIBE, data, opt_len); // note: we ignore errors, such as unsubscribing a nonexisting filter } static void set_linger(void *sock, int value) { size_t opt_len = sizeof(value); int ret = zmq_setsockopt(sock, ZMQ_LINGER, &value, opt_len); assert(ret == 0); } Q_GLOBAL_STATIC(QMutex, g_mutex) class Global { public: Context context; int refs; Global() : refs(0) { } }; static Global *global = 0; static Context *addGlobalContextRef() { QMutexLocker locker(g_mutex()); if(!global) global = new Global; ++(global->refs); return &(global->context); } static void removeGlobalContextRef() { QMutexLocker locker(g_mutex()); assert(global); assert(global->refs > 0); --(global->refs); if(global->refs == 0) { delete global; global = 0; } } class Socket::Private : public QObject { Q_OBJECT public: Socket *q; bool usingGlobalContext; Context *context; void *sock; QSocketNotifier *sn_read; bool canWrite, canRead; QList<QByteArray> pendingRead; bool readComplete; QList<QList<QByteArray> > pendingWrites; QTimer *updateTimer; bool pendingUpdate; int shutdownWaitTime; Private(Socket *_q, Socket::Type type, Context *_context) : QObject(_q), q(_q), canWrite(false), canRead(false), readComplete(false), pendingUpdate(false), shutdownWaitTime(-1) { if(_context) { usingGlobalContext = false; context = _context; } else { usingGlobalContext = true; context = addGlobalContextRef(); } int ztype; switch(type) { case Socket::Pair: ztype = ZMQ_PAIR; break; case Socket::Dealer: ztype = ZMQ_DEALER; break; case Socket::Router: ztype = ZMQ_ROUTER; break; case Socket::Req: ztype = ZMQ_REQ; break; case Socket::Rep: ztype = ZMQ_REP; break; case Socket::Push: ztype = ZMQ_PUSH; break; case Socket::Pull: ztype = ZMQ_PULL; break; case Socket::Pub: ztype = ZMQ_PUB; break; case Socket::Sub: ztype = ZMQ_SUB; break; default: assert(0); } sock = zmq_socket(context->context(), ztype); assert(sock != NULL); sn_read = new QSocketNotifier(get_fd(sock), QSocketNotifier::Read, this); connect(sn_read, SIGNAL(activated(int)), SLOT(sn_read_activated())); sn_read->setEnabled(true); updateTimer = new QTimer(this); connect(updateTimer, SIGNAL(timeout()), SLOT(update_timeout())); updateTimer->setSingleShot(true); } ~Private() { set_linger(sock, shutdownWaitTime); zmq_close(sock); if(usingGlobalContext) removeGlobalContextRef(); } QList<QByteArray> read() { if(readComplete) { QList<QByteArray> out = pendingRead; pendingRead.clear(); readComplete = false; if(canRead && !pendingUpdate) { pendingUpdate = true; updateTimer->start(); } return out; } else return QList<QByteArray>(); } void write(const QList<QByteArray> &message) { assert(!message.isEmpty()); pendingWrites += message; if(canWrite && !pendingUpdate) { pendingUpdate = true; updateTimer->start(); } } void processEvents(bool *readyRead, int *messagesWritten) { bool again; do { again = false; int flags = get_events(sock); if(flags & ZMQ_POLLOUT) { canWrite = true; again = tryWrite(messagesWritten) || again; } if(flags & ZMQ_POLLIN) { canRead = true; again = tryRead(readyRead) || again; } } while(again); } bool tryWrite(int *messagesWritten) { if(!pendingWrites.isEmpty()) { bool writeComplete = false; QByteArray buf = pendingWrites.first().takeFirst(); if(pendingWrites.first().isEmpty()) { pendingWrites.removeFirst(); writeComplete = true; } zmq_msg_t msg; int ret = zmq_msg_init_size(&msg, buf.size()); assert(ret == 0); memcpy(zmq_msg_data(&msg), buf.data(), buf.size()); ret = zmq_send(sock, &msg, !writeComplete ? ZMQ_SNDMORE : 0); assert(ret == 0); ret = zmq_msg_close(&msg); assert(ret == 0); canWrite = false; if(writeComplete) ++(*messagesWritten); return true; } return false; } // return true if a read was performed bool tryRead(bool *readyRead) { if(!readComplete) { zmq_msg_t msg; int ret = zmq_msg_init(&msg); assert(ret == 0); ret = zmq_recv(sock, &msg, 0); assert(ret == 0); QByteArray buf((const char *)zmq_msg_data(&msg), zmq_msg_size(&msg)); ret = zmq_msg_close(&msg); assert(ret == 0); pendingRead += buf; canRead = false; if(!get_rcvmore(sock)) { readComplete = true; *readyRead = true; } return true; } return false; } public slots: void sn_read_activated() { bool readyRead = false; int messagesWritten = 0; processEvents(&readyRead, &messagesWritten); if(readyRead) emit q->readyRead(); if(messagesWritten > 0) emit q->messagesWritten(messagesWritten); } void update_timeout() { pendingUpdate = false; bool readyRead = false; int messagesWritten = 0; if(canWrite) { bool ret = tryWrite(&messagesWritten); assert(ret); processEvents(&readyRead, &messagesWritten); } if(canRead) { bool ret = tryRead(&readyRead); assert(ret); processEvents(&readyRead, &messagesWritten); } if(readyRead) emit q->readyRead(); if(messagesWritten > 0) emit q->messagesWritten(messagesWritten); } }; Socket::Socket(Type type, QObject *parent) : QObject(parent) { d = new Private(this, type, 0); } Socket::Socket(Type type, Context *context, QObject *parent) : QObject(parent) { d = new Private(this, type, context); } Socket::~Socket() { delete d; } void Socket::setShutdownWaitTime(int msecs) { d->shutdownWaitTime = msecs; } void Socket::subscribe(const QByteArray &filter) { set_subscribe(d->sock, filter.data(), filter.size()); } void Socket::unsubscribe(const QByteArray &filter) { set_unsubscribe(d->sock, filter.data(), filter.size()); } void Socket::connectToAddress(const QString &addr) { int ret = zmq_connect(d->sock, addr.toUtf8().data()); assert(ret == 0); } bool Socket::bind(const QString &addr) { int ret = zmq_bind(d->sock, addr.toUtf8().data()); if(ret != 0) return false; return true; } bool Socket::canRead() const { return d->readComplete; } QList<QByteArray> Socket::read() { return d->read(); } void Socket::write(const QList<QByteArray> &message) { d->write(message); } } #include "qzmqsocket.moc" <commit_msg>seems these can return false here<commit_after>#include "qzmqsocket.h" #include <stdio.h> #include <assert.h> #include <QStringList> #include <QTimer> #include <QSocketNotifier> #include <QMutex> #include <zmq.h> #include "qzmqcontext.h" namespace QZmq { static bool get_rcvmore(void *sock) { qint64 more; size_t opt_len = sizeof(more); int ret = zmq_getsockopt(sock, ZMQ_RCVMORE, &more, &opt_len); assert(ret == 0); return more ? true : false; } static int get_fd(void *sock) { int fd; size_t opt_len = sizeof(fd); int ret = zmq_getsockopt(sock, ZMQ_FD, &fd, &opt_len); assert(ret == 0); return fd; } static int get_events(void *sock) { quint32 events; size_t opt_len = sizeof(events); int ret = zmq_getsockopt(sock, ZMQ_EVENTS, &events, &opt_len); assert(ret == 0); return (int)events; } static void set_subscribe(void *sock, const char *data, int size) { size_t opt_len = size; int ret = zmq_setsockopt(sock, ZMQ_SUBSCRIBE, data, opt_len); assert(ret == 0); } static void set_unsubscribe(void *sock, const char *data, int size) { size_t opt_len = size; zmq_setsockopt(sock, ZMQ_UNSUBSCRIBE, data, opt_len); // note: we ignore errors, such as unsubscribing a nonexisting filter } static void set_linger(void *sock, int value) { size_t opt_len = sizeof(value); int ret = zmq_setsockopt(sock, ZMQ_LINGER, &value, opt_len); assert(ret == 0); } Q_GLOBAL_STATIC(QMutex, g_mutex) class Global { public: Context context; int refs; Global() : refs(0) { } }; static Global *global = 0; static Context *addGlobalContextRef() { QMutexLocker locker(g_mutex()); if(!global) global = new Global; ++(global->refs); return &(global->context); } static void removeGlobalContextRef() { QMutexLocker locker(g_mutex()); assert(global); assert(global->refs > 0); --(global->refs); if(global->refs == 0) { delete global; global = 0; } } class Socket::Private : public QObject { Q_OBJECT public: Socket *q; bool usingGlobalContext; Context *context; void *sock; QSocketNotifier *sn_read; bool canWrite, canRead; QList<QByteArray> pendingRead; bool readComplete; QList< QList<QByteArray> > pendingWrites; QTimer *updateTimer; bool pendingUpdate; int shutdownWaitTime; Private(Socket *_q, Socket::Type type, Context *_context) : QObject(_q), q(_q), canWrite(false), canRead(false), readComplete(false), pendingUpdate(false), shutdownWaitTime(-1) { if(_context) { usingGlobalContext = false; context = _context; } else { usingGlobalContext = true; context = addGlobalContextRef(); } int ztype; switch(type) { case Socket::Pair: ztype = ZMQ_PAIR; break; case Socket::Dealer: ztype = ZMQ_DEALER; break; case Socket::Router: ztype = ZMQ_ROUTER; break; case Socket::Req: ztype = ZMQ_REQ; break; case Socket::Rep: ztype = ZMQ_REP; break; case Socket::Push: ztype = ZMQ_PUSH; break; case Socket::Pull: ztype = ZMQ_PULL; break; case Socket::Pub: ztype = ZMQ_PUB; break; case Socket::Sub: ztype = ZMQ_SUB; break; default: assert(0); } sock = zmq_socket(context->context(), ztype); assert(sock != NULL); sn_read = new QSocketNotifier(get_fd(sock), QSocketNotifier::Read, this); connect(sn_read, SIGNAL(activated(int)), SLOT(sn_read_activated())); sn_read->setEnabled(true); updateTimer = new QTimer(this); connect(updateTimer, SIGNAL(timeout()), SLOT(update_timeout())); updateTimer->setSingleShot(true); } ~Private() { set_linger(sock, shutdownWaitTime); zmq_close(sock); if(usingGlobalContext) removeGlobalContextRef(); } QList<QByteArray> read() { if(readComplete) { QList<QByteArray> out = pendingRead; pendingRead.clear(); readComplete = false; if(canRead && !pendingUpdate) { pendingUpdate = true; updateTimer->start(); } return out; } else return QList<QByteArray>(); } void write(const QList<QByteArray> &message) { assert(!message.isEmpty()); pendingWrites += message; if(canWrite && !pendingUpdate) { pendingUpdate = true; updateTimer->start(); } } void processEvents(bool *readyRead, int *messagesWritten) { bool again; do { again = false; int flags = get_events(sock); if(flags & ZMQ_POLLOUT) { canWrite = true; again = tryWrite(messagesWritten) || again; } if(flags & ZMQ_POLLIN) { canRead = true; again = tryRead(readyRead) || again; } } while(again); } bool tryWrite(int *messagesWritten) { if(!pendingWrites.isEmpty()) { bool writeComplete = false; QByteArray buf = pendingWrites.first().takeFirst(); if(pendingWrites.first().isEmpty()) { pendingWrites.removeFirst(); writeComplete = true; } zmq_msg_t msg; int ret = zmq_msg_init_size(&msg, buf.size()); assert(ret == 0); memcpy(zmq_msg_data(&msg), buf.data(), buf.size()); ret = zmq_send(sock, &msg, !writeComplete ? ZMQ_SNDMORE : 0); assert(ret == 0); ret = zmq_msg_close(&msg); assert(ret == 0); canWrite = false; if(writeComplete) ++(*messagesWritten); return true; } return false; } // return true if a read was performed bool tryRead(bool *readyRead) { if(!readComplete) { zmq_msg_t msg; int ret = zmq_msg_init(&msg); assert(ret == 0); ret = zmq_recv(sock, &msg, 0); assert(ret == 0); QByteArray buf((const char *)zmq_msg_data(&msg), zmq_msg_size(&msg)); ret = zmq_msg_close(&msg); assert(ret == 0); pendingRead += buf; canRead = false; if(!get_rcvmore(sock)) { readComplete = true; *readyRead = true; } return true; } return false; } public slots: void sn_read_activated() { bool readyRead = false; int messagesWritten = 0; processEvents(&readyRead, &messagesWritten); if(readyRead) emit q->readyRead(); if(messagesWritten > 0) emit q->messagesWritten(messagesWritten); } void update_timeout() { pendingUpdate = false; bool readyRead = false; int messagesWritten = 0; if(canWrite) { if(tryWrite(&messagesWritten)) processEvents(&readyRead, &messagesWritten); } if(canRead) { if(tryRead(&readyRead)) processEvents(&readyRead, &messagesWritten); } if(readyRead) emit q->readyRead(); if(messagesWritten > 0) emit q->messagesWritten(messagesWritten); } }; Socket::Socket(Type type, QObject *parent) : QObject(parent) { d = new Private(this, type, 0); } Socket::Socket(Type type, Context *context, QObject *parent) : QObject(parent) { d = new Private(this, type, context); } Socket::~Socket() { delete d; } void Socket::setShutdownWaitTime(int msecs) { d->shutdownWaitTime = msecs; } void Socket::subscribe(const QByteArray &filter) { set_subscribe(d->sock, filter.data(), filter.size()); } void Socket::unsubscribe(const QByteArray &filter) { set_unsubscribe(d->sock, filter.data(), filter.size()); } void Socket::connectToAddress(const QString &addr) { int ret = zmq_connect(d->sock, addr.toUtf8().data()); assert(ret == 0); } bool Socket::bind(const QString &addr) { int ret = zmq_bind(d->sock, addr.toUtf8().data()); if(ret != 0) return false; return true; } bool Socket::canRead() const { return d->readComplete; } QList<QByteArray> Socket::read() { return d->read(); } void Socket::write(const QList<QByteArray> &message) { d->write(message); } } #include "qzmqsocket.moc" <|endoftext|>
<commit_before><commit_msg>#104320# update cache after changing font properties<commit_after><|endoftext|>
<commit_before>#include "optimizers.h" #include "common/io.h" #include "tensors/tensor_operators.h" namespace marian { void Sgd::updateImpl(Tensor params, Tensor grads) { using namespace functional; Element(_1 -= (multiplyFactor_ * eta_) * _2, params, grads); params->getBackend()->synchronize(); } // temporary: helpers for scattering optimizer state in load() static void scatter(const std::vector<float>& data, const std::function<void(size_t, std::vector<float>::const_iterator, std::vector<float>::const_iterator)>& setFn, size_t numShards) { for(size_t id = 0; id < numShards; id++) { size_t dataSize = data.size(); size_t shardSize = (size_t)(ceil(dataSize / (float)numShards)); size_t shift = id * shardSize; size_t size = std::min(shardSize, dataSize-shift); setFn(id, data.begin() + shift, data.begin() + shift + size); } } // Aagrad void Adagrad::updateImpl(Tensor params, Tensor grads) { if(!alloc_) alloc_ = New<TensorAllocator>(params->getBackend()); if(!gt_) { int elements = (int)params->size(); alloc_->reserveExact(params->memory()->size()); alloc_->allocate(gt_, {1, elements}); gt_->set(0.f); } using namespace functional; Element(_1 += (_2 * _2), gt_, grads); Element(_1 -= ((multiplyFactor_ * eta_) / (sqrt(_2) + eps_)) * _3, params, gt_, grads); params->getBackend()->synchronize(); } void Adagrad::load(const std::string& name, std::vector<Ptr<OptimizerBase>> opts, std::vector<Ptr<Backend>> backends) { ABORT_IF(opts.size() != backends.size(), "opts and backends of different sizes??"); if(!boost::filesystem::exists(name)) return; LOG(info, "Loading Adagrad parameters from {}", name); std::vector<float> vGt; // @TODO: use new IO auto items = io::loadItems(name); for(auto item : items) { // get the size of gt_ auto totalSize = item.shape.elements(); // extract data into vectors if(item.name == "adagrad_gt") { vGt.resize(totalSize); std::copy( (float*)item.data(), (float*)item.data() + totalSize, vGt.begin()); } } if(vGt.empty()) { LOG(warn, "[warn] Adagrad parameters not found in .npz file"); return; } auto setGt = [&](size_t id, std::vector<float>::const_iterator begin, std::vector<float>::const_iterator end) { auto opt = std::dynamic_pointer_cast<Adagrad>(opts[id]); if(!opt->gt_) { if(!opt->alloc_) opt->alloc_ = New<TensorAllocator>(backends[id]); auto size = end-begin; opt->alloc_->reserveExact(sizeof(float) * size); opt->alloc_->allocate(opt->gt_, {1, (int)size}); } opt->gt_->set(std::vector<float>(begin, end)); }; scatter(vGt, setGt, opts.size()); } void Adagrad::save(const std::string& name, std::vector<Ptr<OptimizerBase>> opts) { LOG(info, "Saving Adagrad parameters to {}", name); // fetch and concatenate state vectors from shards into a CPU-side vector std::vector<float> vGt; for(auto optBase : opts) { auto opt = std::dynamic_pointer_cast<Adagrad>(optBase); std::vector<float> tmp; opt->gt_->get(tmp); vGt.insert(vGt.end(), tmp.begin(), tmp.end()); } // save to file io::Item item; item.name = "adagrad_gt"; item.shape = Shape({1, (int)vGt.size()}); item.type = Type::float32; item.bytes.resize(vGt.size() * sizeOf(item.type)); std::copy( (char*)vGt.data(), (char*)vGt.data() + vGt.size(), item.bytes.begin()); io::saveItems(name, {item}); } void Adagrad::resetStats() { if(gt_) gt_->set(0.f); } // Adam void Adam::updateImpl(Tensor params, Tensor grads) { if(!alloc_) alloc_ = New<TensorAllocator>(params->getBackend()); if(!mt_) { int elements = (int)params->size(); alloc_->reserveExact(2 * params->memory()->size()); alloc_->allocate(mt_, {1, elements}); mt_->set(0.f); alloc_->allocate(vt_, {1, elements}); vt_->set(0.f); } t_++; float denom1 = 1 - (float)std::pow(beta1_, t_); float denom2 = 1 - (float)std::pow(beta2_, t_); using namespace functional; Element(_1 = (beta1_ * _1) + ((1 - beta1_) * _2), mt_, grads); Element(_1 = (beta2_ * _1) + ((1 - beta2_) * (_2 * _2)), vt_, grads); Element(_1 -= (multiplyFactor_ * eta_) * (_2 / denom1) / (sqrt(_3 / denom2) + eps_), params, mt_, vt_); params->getBackend()->synchronize(); } void Adam::load(const std::string& name, std::vector<Ptr<OptimizerBase>> opts, std::vector<Ptr<Backend>> backends) { ABORT_IF(opts.size() != backends.size(), "opts and backends of different sizes??"); if(!boost::filesystem::exists(name)) return; LOG(info, "Loading Adam parameters from {}", name); std::vector<float> vMt; std::vector<float> vVt; auto items = io::loadItems(name); for(auto item : items) { // get the size of mt_ and vt_, they are the same auto totalSize = item.shape.elements(); // extract data into vectors if(item.name == "adam_mt") { vMt.resize(totalSize); std::copy( (float*)item.data(), (float*)item.data() + totalSize, vMt.begin()); } if(item.name == "adam_vt") { vVt.resize(totalSize); std::copy( (float*)item.data(), (float*)item.data() + totalSize, vVt.begin()); } } if(vMt.empty() || vVt.empty()) { LOG(warn, "[warn] Adam parameters not found in .npz file"); return; } ABORT_IF(vMt.size() != vVt.size(), "mt and vt have different sizes??"); auto setMt = [&](size_t id, std::vector<float>::const_iterator begin, std::vector<float>::const_iterator end) { auto opt = std::dynamic_pointer_cast<Adam>(opts[id]); if(!opt->mt_ || !opt->vt_) { // lazily allocate if(!opt->alloc_) opt->alloc_ = New<TensorAllocator>(backends[id]); auto size = end-begin; opt->alloc_->reserveExact(2 * sizeof(float) * size); opt->alloc_->allocate(opt->mt_, {1, (int)size}); opt->alloc_->allocate(opt->vt_, {1, (int)size}); } opt->mt_->set(std::vector<float>(begin, end)); // set the value }; auto setVt = [&](size_t id, std::vector<float>::const_iterator begin, std::vector<float>::const_iterator end) { auto opt = std::dynamic_pointer_cast<Adam>(opts[id]); opt->vt_->set(std::vector<float>(begin, end)); }; scatter(vMt, setMt, opts.size()); scatter(vVt, setMt, opts.size()); } void Adam::save(const std::string& name, std::vector<Ptr<OptimizerBase>> opts) { LOG(info, "Saving Adam parameters to {}", name); // fetch and concatenate state vectors from shards into a CPU-side vector std::vector<float> vMt; for(auto optBase : opts) { auto opt = std::dynamic_pointer_cast<Adam>(optBase); std::vector<float> tmp; opt->mt_->get(tmp); vMt.insert(vMt.end(), tmp.begin(), tmp.end()); } std::vector<float> vVt; for(auto optBase : opts) { auto opt = std::dynamic_pointer_cast<Adam>(optBase); std::vector<float> tmp; opt->vt_->get(tmp); vVt.insert(vVt.end(), tmp.begin(), tmp.end()); } // save to file io::Item itemMt; itemMt.name = "adam_mt"; itemMt.shape = Shape({1, (int)vMt.size()}); itemMt.type = Type::float32; itemMt.bytes.resize(vMt.size() * sizeOf(itemMt.type)); std::copy( (char*)vMt.data(), (char*)vMt.data() + vMt.size(), itemMt.bytes.begin()); io::Item itemVt; itemVt.name = "adam_vt"; itemVt.shape = Shape({1, (int)vVt.size()}); itemVt.type = Type::float32; itemVt.bytes.resize(vVt.size() * sizeOf(itemVt.type)); std::copy( (char*)vVt.data(), (char*)vVt.data() + vVt.size(), itemVt.bytes.begin()); io::saveItems(name, {itemMt, itemVt}); } void Adam::resetStats() { if(mt_) mt_->set(0.f); if(vt_) vt_->set(0.f); } Ptr<OptimizerBase> Optimizer(Ptr<Config> options) { float lrate = (float)options->get<double>("learn-rate"); // @TODO: should this be <float>? auto params = options->has("optimizer-params") ? options->get<std::vector<float>>("optimizer-params") : std::vector<float>({}); Ptr<ClipperBase> clipper = nullptr; float clipNorm = (float)options->get<double>("clip-norm"); // @TODO: should this be <float>? if(clipNorm > 0) clipper = Clipper<Norm>(clipNorm); auto opt = options->get<std::string>("optimizer"); if(opt == "sgd") { return Optimizer<Sgd>(lrate, clipper, params); } else if(opt == "adagrad") { return Optimizer<Adagrad>(lrate, clipper, params); } else if(opt == "adam") { return Optimizer<Adam>(lrate, clipper, params); } else { ABORT("Unknown optimizer: {}", opt); } } } // namespace marian <commit_msg>last refactoring of Optimizer::save()<commit_after>#include "optimizers.h" #include "common/io.h" #include "tensors/tensor_operators.h" namespace marian { void Sgd::updateImpl(Tensor params, Tensor grads) { using namespace functional; Element(_1 -= (multiplyFactor_ * eta_) * _2, params, grads); params->getBackend()->synchronize(); } // temporary: helpers for scattering optimizer state in load() static void scatter(const std::vector<float>& data, const std::function<void(size_t, std::vector<float>::const_iterator, std::vector<float>::const_iterator)>& setFn, size_t numShards) { for(size_t id = 0; id < numShards; id++) { size_t dataSize = data.size(); size_t shardSize = (size_t)(ceil(dataSize / (float)numShards)); size_t shift = id * shardSize; size_t size = std::min(shardSize, dataSize-shift); setFn(id, data.begin() + shift, data.begin() + shift + size); } } static void gather(std::vector<float>& data, const std::function<void(size_t, std::vector<float>&)>& getFn, size_t numShards) { for (size_t id = 0; id < numShards; id++) { std::vector<float> tmp; getFn(id, tmp); data.insert(data.end(), tmp.begin(), tmp.end()); } } // Aagrad void Adagrad::updateImpl(Tensor params, Tensor grads) { if(!alloc_) alloc_ = New<TensorAllocator>(params->getBackend()); if(!gt_) { int elements = (int)params->size(); alloc_->reserveExact(params->memory()->size()); alloc_->allocate(gt_, {1, elements}); gt_->set(0.f); } using namespace functional; Element(_1 += (_2 * _2), gt_, grads); Element(_1 -= ((multiplyFactor_ * eta_) / (sqrt(_2) + eps_)) * _3, params, gt_, grads); params->getBackend()->synchronize(); } void Adagrad::load(const std::string& name, std::vector<Ptr<OptimizerBase>> opts, std::vector<Ptr<Backend>> backends) { ABORT_IF(opts.size() != backends.size(), "opts and backends of different sizes??"); if(!boost::filesystem::exists(name)) return; LOG(info, "Loading Adagrad parameters from {}", name); std::vector<float> vGt; // @TODO: use new IO auto items = io::loadItems(name); for(auto item : items) { // get the size of gt_ auto totalSize = item.shape.elements(); // extract data into vectors if(item.name == "adagrad_gt") { vGt.resize(totalSize); std::copy( (float*)item.data(), (float*)item.data() + totalSize, vGt.begin()); } } if(vGt.empty()) { LOG(warn, "[warn] Adagrad parameters not found in .npz file"); return; } auto setGt = [&](size_t id, std::vector<float>::const_iterator begin, std::vector<float>::const_iterator end) { auto opt = std::dynamic_pointer_cast<Adagrad>(opts[id]); if(!opt->gt_) { if(!opt->alloc_) opt->alloc_ = New<TensorAllocator>(backends[id]); auto size = end-begin; opt->alloc_->reserveExact(sizeof(float) * size); opt->alloc_->allocate(opt->gt_, {1, (int)size}); } opt->gt_->set(std::vector<float>(begin, end)); }; scatter(vGt, setGt, opts.size()); } void Adagrad::save(const std::string& name, std::vector<Ptr<OptimizerBase>> opts) { LOG(info, "Saving Adagrad parameters to {}", name); // fetch and concatenate state vectors from shards into a CPU-side vector std::vector<float> vGt; auto getGt = [&](size_t id, std::vector<float>& data) { auto opt = std::dynamic_pointer_cast<Adagrad>(opts[id]); opt->gt_->get(data); }; gather(vGt, getGt, opts.size()); // save to file io::Item item; item.name = "adagrad_gt"; item.shape = Shape({1, (int)vGt.size()}); item.type = Type::float32; item.bytes.resize(vGt.size() * sizeOf(item.type)); std::copy( (char*)vGt.data(), (char*)vGt.data() + vGt.size(), item.bytes.begin()); io::saveItems(name, {item}); } void Adagrad::resetStats() { if(gt_) gt_->set(0.f); } // Adam void Adam::updateImpl(Tensor params, Tensor grads) { if(!alloc_) alloc_ = New<TensorAllocator>(params->getBackend()); if(!mt_) { int elements = (int)params->size(); alloc_->reserveExact(2 * params->memory()->size()); alloc_->allocate(mt_, {1, elements}); mt_->set(0.f); alloc_->allocate(vt_, {1, elements}); vt_->set(0.f); } t_++; float denom1 = 1 - (float)std::pow(beta1_, t_); float denom2 = 1 - (float)std::pow(beta2_, t_); using namespace functional; Element(_1 = (beta1_ * _1) + ((1 - beta1_) * _2), mt_, grads); Element(_1 = (beta2_ * _1) + ((1 - beta2_) * (_2 * _2)), vt_, grads); Element(_1 -= (multiplyFactor_ * eta_) * (_2 / denom1) / (sqrt(_3 / denom2) + eps_), params, mt_, vt_); params->getBackend()->synchronize(); } void Adam::load(const std::string& name, std::vector<Ptr<OptimizerBase>> opts, std::vector<Ptr<Backend>> backends) { ABORT_IF(opts.size() != backends.size(), "opts and backends of different sizes??"); if(!boost::filesystem::exists(name)) return; LOG(info, "Loading Adam parameters from {}", name); std::vector<float> vMt; std::vector<float> vVt; auto items = io::loadItems(name); for(auto item : items) { // get the size of mt_ and vt_, they are the same auto totalSize = item.shape.elements(); // extract data into vectors if(item.name == "adam_mt") { vMt.resize(totalSize); std::copy( (float*)item.data(), (float*)item.data() + totalSize, vMt.begin()); } if(item.name == "adam_vt") { vVt.resize(totalSize); std::copy( (float*)item.data(), (float*)item.data() + totalSize, vVt.begin()); } } if(vMt.empty() || vVt.empty()) { LOG(warn, "[warn] Adam parameters not found in .npz file"); return; } ABORT_IF(vMt.size() != vVt.size(), "mt and vt have different sizes??"); auto setMt = [&](size_t id, std::vector<float>::const_iterator begin, std::vector<float>::const_iterator end) { auto opt = std::dynamic_pointer_cast<Adam>(opts[id]); if(!opt->mt_ || !opt->vt_) { // lazily allocate if(!opt->alloc_) opt->alloc_ = New<TensorAllocator>(backends[id]); auto size = end-begin; opt->alloc_->reserveExact(2 * sizeof(float) * size); opt->alloc_->allocate(opt->mt_, {1, (int)size}); opt->alloc_->allocate(opt->vt_, {1, (int)size}); } opt->mt_->set(std::vector<float>(begin, end)); // set the value }; auto setVt = [&](size_t id, std::vector<float>::const_iterator begin, std::vector<float>::const_iterator end) { auto opt = std::dynamic_pointer_cast<Adam>(opts[id]); opt->vt_->set(std::vector<float>(begin, end)); }; scatter(vMt, setMt, opts.size()); scatter(vVt, setMt, opts.size()); } void Adam::save(const std::string& name, std::vector<Ptr<OptimizerBase>> opts) { LOG(info, "Saving Adam parameters to {}", name); // fetch and concatenate state vectors from shards into a CPU-side vector auto getMt = [&](size_t id, std::vector<float>& data) { auto opt = std::dynamic_pointer_cast<Adam>(opts[id]); opt->mt_->get(data); }; auto getVt = [&](size_t id, std::vector<float>& data) { auto opt = std::dynamic_pointer_cast<Adam>(opts[id]); opt->vt_->get(data); }; std::vector<float> vMt; std::vector<float> vVt; gather(vMt, getMt, opts.size()); gather(vVt, getVt, opts.size()); // save to file io::Item itemMt; itemMt.name = "adam_mt"; itemMt.shape = Shape({1, (int)vMt.size()}); itemMt.type = Type::float32; itemMt.bytes.resize(vMt.size() * sizeOf(itemMt.type)); std::copy( (char*)vMt.data(), (char*)vMt.data() + vMt.size(), itemMt.bytes.begin()); io::Item itemVt; itemVt.name = "adam_vt"; itemVt.shape = Shape({1, (int)vVt.size()}); itemVt.type = Type::float32; itemVt.bytes.resize(vVt.size() * sizeOf(itemVt.type)); std::copy( (char*)vVt.data(), (char*)vVt.data() + vVt.size(), itemVt.bytes.begin()); io::saveItems(name, {itemMt, itemVt}); } void Adam::resetStats() { if(mt_) mt_->set(0.f); if(vt_) vt_->set(0.f); } Ptr<OptimizerBase> Optimizer(Ptr<Config> options) { float lrate = (float)options->get<double>("learn-rate"); // @TODO: should this be <float>? auto params = options->has("optimizer-params") ? options->get<std::vector<float>>("optimizer-params") : std::vector<float>({}); Ptr<ClipperBase> clipper = nullptr; float clipNorm = (float)options->get<double>("clip-norm"); // @TODO: should this be <float>? if(clipNorm > 0) clipper = Clipper<Norm>(clipNorm); auto opt = options->get<std::string>("optimizer"); if(opt == "sgd") { return Optimizer<Sgd>(lrate, clipper, params); } else if(opt == "adagrad") { return Optimizer<Adagrad>(lrate, clipper, params); } else if(opt == "adam") { return Optimizer<Adam>(lrate, clipper, params); } else { ABORT("Unknown optimizer: {}", opt); } } } // namespace marian <|endoftext|>
<commit_before>#include "directories.h" #include "logging.h" #include <algorithm> #include <unordered_set> #include "source.h" #include "terminal.h" #include "notebook.h" #include <iostream> //TODO: remove using namespace std; //TODO: remove namespace sigc { #ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun(std::declval<Functor&>(), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; #else SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE #endif } bool Directories::TreeStore::row_drop_possible_vfunc(const Gtk::TreeModel::Path& path, const Gtk::SelectionData& selection_data) const { return true; } bool Directories::TreeStore::drag_data_received_vfunc(const TreeModel::Path &path, const Gtk::SelectionData &selection_data) { auto &directories=Directories::get(); auto get_target_folder=[this, &directories](const TreeModel::Path &path) { if(path.size()==1) return directories.path; else { auto it=get_iter(path); if(it) { auto prev_path=path; prev_path.up(); it=get_iter(prev_path); if(it) return it->get_value(directories.column_record.path); } else { auto prev_path=path; prev_path.up(); if(prev_path.size()==1) return directories.path; else { prev_path.up(); it=get_iter(prev_path); if(it) return it->get_value(directories.column_record.path); } } } return boost::filesystem::path(); }; auto it=directories.get_selection()->get_selected(); if(it) { auto source_path=it->get_value(directories.column_record.path); auto target_path=get_target_folder(path); target_path/=source_path.filename(); if(source_path==target_path) return false; if(boost::filesystem::exists(target_path)) { Terminal::get().print("Error: Could not move file: "+target_path.string()+" already exists\n", true); return false; } boost::system::error_code ec; boost::filesystem::rename(source_path, target_path, ec); if(ec) { Terminal::get().print("Error: Could not move file: "+ec.message()+'\n', true); return false; } for(int c=0;c<Notebook::get().size();c++) { auto view=Notebook::get().get_view(c); if(view->file_path==source_path) { view->file_path=target_path; break; } } Directories::get().update(); directories.select(target_path); } return false; } bool Directories::TreeStore::drag_data_delete_vfunc (const Gtk::TreeModel::Path &path) { return false; } Directories::Directories() : Gtk::TreeView(), stop_update_thread(false) { this->set_enable_tree_lines(true); tree_store = TreeStore::create(); tree_store->set_column_types(column_record); set_model(tree_store); append_column("", column_record.name); auto renderer=dynamic_cast<Gtk::CellRendererText*>(get_column(0)->get_first_cell()); get_column(0)->add_attribute(renderer->property_foreground_rgba(), column_record.color); tree_store->set_sort_column(column_record.id, Gtk::SortType::SORT_ASCENDING); set_enable_search(true); //TODO: why does this not work in OS X? set_search_column(column_record.name); signal_row_activated().connect([this](const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* column){ auto iter = tree_store->get_iter(path); if (iter) { auto filesystem_path=iter->get_value(column_record.path); if(filesystem_path!="") { if (boost::filesystem::is_directory(boost::filesystem::path(filesystem_path))) { row_expanded(path) ? collapse_row(path) : expand_row(path, false); } else { if(on_row_activated) on_row_activated(filesystem_path); } } } }); signal_test_expand_row().connect([this](const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& path){ if(iter->children().begin()->get_value(column_record.path)=="") { update_mutex.lock(); add_path(iter->get_value(column_record.path), *iter); update_mutex.unlock(); } return false; }); signal_row_collapsed().connect([this](const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& path){ update_mutex.lock(); auto directory_str=iter->get_value(column_record.path).string(); for(auto it=last_write_times.begin();it!=last_write_times.end();) { if(directory_str==it->first.substr(0, directory_str.size())) it=last_write_times.erase(it); else it++; } update_mutex.unlock(); auto children=iter->children(); if(children) { while(children) { tree_store->erase(children.begin()); } auto child=tree_store->append(iter->children()); child->set_value(column_record.name, std::string("(empty)")); Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); child->set_value(column_record.color, rgba); } }); update_thread=std::thread([this](){ while(!stop_update_thread) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); update_mutex.lock(); if(update_paths.size()==0) { for(auto it=last_write_times.begin();it!=last_write_times.end();) { boost::system::error_code ec; auto last_write_time=boost::filesystem::last_write_time(it->first, ec); if(!ec) { if(it->second.second<last_write_time) { update_paths.emplace_back(it->first); } it++; } else it=last_write_times.erase(it); } if(update_paths.size()>0) { dispatcher.post([this] { update_mutex.lock(); for(auto &path: update_paths) { if(last_write_times.count(path)>0) add_path(path, last_write_times.at(path).first); } update_paths.clear(); update_mutex.unlock(); }); } } update_mutex.unlock(); } }); enable_model_drag_source(); enable_model_drag_dest(); menu_item_delete.set_label("Delete"); menu_item_delete.signal_activate().connect([this] { std::cout << "delete " << menu_popup_row_path << std::endl; }); menu.append(menu_item_delete); menu.show_all(); menu.accelerate(*this); } Directories::~Directories() { stop_update_thread=true; update_thread.join(); dispatcher.disconnect(); } void Directories::open(const boost::filesystem::path& dir_path) { JDEBUG("start"); if(dir_path.empty()) return; tree_store->clear(); update_mutex.lock(); last_write_times.clear(); update_paths.clear(); update_mutex.unlock(); //TODO: report that set_title does not handle '_' correctly? auto title=dir_path.filename().string(); size_t pos=0; while((pos=title.find('_', pos))!=std::string::npos) { title.replace(pos, 1, "__"); pos+=2; } get_column(0)->set_title(title); update_mutex.lock(); add_path(dir_path, Gtk::TreeModel::Row()); update_mutex.unlock(); path=dir_path; JDEBUG("end"); } void Directories::update() { JDEBUG("start"); update_mutex.lock(); for(auto &last_write_time: last_write_times) { add_path(last_write_time.first, last_write_time.second.first); } update_mutex.unlock(); JDEBUG("end"); } void Directories::select(const boost::filesystem::path &select_path) { JDEBUG("start"); if(path=="") return; if(select_path.generic_string().substr(0, path.generic_string().size()+1)!=path.generic_string()+'/') return; std::list<boost::filesystem::path> paths; boost::filesystem::path parent_path; if(boost::filesystem::is_directory(select_path)) parent_path=select_path; else parent_path=select_path.parent_path(); paths.emplace_front(parent_path); while(parent_path!=path) { parent_path=parent_path.parent_path(); paths.emplace_front(parent_path); } for(auto &a_path: paths) { tree_store->foreach_iter([this, &a_path](const Gtk::TreeModel::iterator& iter){ if(iter->get_value(column_record.path)==a_path) { update_mutex.lock(); add_path(a_path, *iter); update_mutex.unlock(); return true; } return false; }); } tree_store->foreach_iter([this, &select_path](const Gtk::TreeModel::iterator& iter){ if(iter->get_value(column_record.path)==select_path) { auto tree_path=Gtk::TreePath(iter); expand_to_path(tree_path); set_cursor(tree_path); return true; } return false; }); JDEBUG("end"); } bool Directories::on_button_press_event(GdkEventButton* event) { if(event->type==GDK_BUTTON_PRESS && event->button==3) { Gtk::TreeModel::Path path; if(get_path_at_pos(static_cast<int>(event->x), static_cast<int>(event->y), path)) { menu_popup_row_path=get_model()->get_iter(path)->get_value(column_record.path); menu.popup(event->button, event->time); return true; } } return Gtk::TreeView::on_button_press_event(event); } void Directories::add_path(const boost::filesystem::path& dir_path, const Gtk::TreeModel::Row &parent) { boost::system::error_code ec; auto last_write_time=boost::filesystem::last_write_time(dir_path, ec); if(ec) return; last_write_times[dir_path.string()]={parent, last_write_time}; std::unique_ptr<Gtk::TreeNodeChildren> children; //Gtk::TreeNodeChildren is missing default constructor... if(parent) children=std::unique_ptr<Gtk::TreeNodeChildren>(new Gtk::TreeNodeChildren(parent.children())); else children=std::unique_ptr<Gtk::TreeNodeChildren>(new Gtk::TreeNodeChildren(tree_store->children())); if(*children) { if(children->begin()->get_value(column_record.path)=="") tree_store->erase(children->begin()); } std::unordered_set<std::string> not_deleted; boost::filesystem::directory_iterator end_it; for(boost::filesystem::directory_iterator it(dir_path);it!=end_it;it++) { auto filename=it->path().filename().string(); bool already_added=false; if(*children) { for(auto &child: *children) { if(child->get_value(column_record.name)==filename) { not_deleted.emplace(filename); already_added=true; break; } } } if(!already_added) { auto child = tree_store->append(*children); not_deleted.emplace(filename); child->set_value(column_record.name, filename); child->set_value(column_record.path, it->path()); if (boost::filesystem::is_directory(it->path())) { child->set_value(column_record.id, "a"+filename); auto grandchild=tree_store->append(child->children()); grandchild->set_value(column_record.name, std::string("(empty)")); Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); grandchild->set_value(column_record.color, rgba); } else { child->set_value(column_record.id, "b"+filename); auto language=Source::guess_language(it->path().filename()); if(!language) { Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); child->set_value(column_record.color, rgba); } } } } if(*children) { for(auto it=children->begin();it!=children->end();) { if(not_deleted.count(it->get_value(column_record.name))==0) { it=tree_store->erase(it); } else it++; } } if(!*children) { auto child=tree_store->append(*children); child->set_value(column_record.name, std::string("(empty)")); Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); child->set_value(column_record.color, rgba); } } <commit_msg>Added right click delete in directory view<commit_after>#include "directories.h" #include "logging.h" #include <algorithm> #include <unordered_set> #include "source.h" #include "terminal.h" #include "notebook.h" #include "filesystem.h" #include <iostream> //TODO: remove using namespace std; //TODO: remove namespace sigc { #ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun(std::declval<Functor&>(), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; #else SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE #endif } bool Directories::TreeStore::row_drop_possible_vfunc(const Gtk::TreeModel::Path& path, const Gtk::SelectionData& selection_data) const { return true; } bool Directories::TreeStore::drag_data_received_vfunc(const TreeModel::Path &path, const Gtk::SelectionData &selection_data) { auto &directories=Directories::get(); auto get_target_folder=[this, &directories](const TreeModel::Path &path) { if(path.size()==1) return directories.path; else { auto it=get_iter(path); if(it) { auto prev_path=path; prev_path.up(); it=get_iter(prev_path); if(it) return it->get_value(directories.column_record.path); } else { auto prev_path=path; prev_path.up(); if(prev_path.size()==1) return directories.path; else { prev_path.up(); it=get_iter(prev_path); if(it) return it->get_value(directories.column_record.path); } } } return boost::filesystem::path(); }; auto it=directories.get_selection()->get_selected(); if(it) { auto source_path=it->get_value(directories.column_record.path); auto target_path=get_target_folder(path); target_path/=source_path.filename(); if(source_path==target_path) return false; if(boost::filesystem::exists(target_path)) { Terminal::get().print("Error: Could not move file: "+target_path.string()+" already exists\n", true); return false; } boost::system::error_code ec; boost::filesystem::rename(source_path, target_path, ec); if(ec) { Terminal::get().print("Error: Could not move file: "+ec.message()+'\n', true); return false; } for(int c=0;c<Notebook::get().size();c++) { auto view=Notebook::get().get_view(c); if(view->file_path==source_path) { view->file_path=target_path; break; } } Directories::get().update(); directories.select(target_path); } return false; } bool Directories::TreeStore::drag_data_delete_vfunc (const Gtk::TreeModel::Path &path) { return false; } Directories::Directories() : Gtk::TreeView(), stop_update_thread(false) { this->set_enable_tree_lines(true); tree_store = TreeStore::create(); tree_store->set_column_types(column_record); set_model(tree_store); append_column("", column_record.name); auto renderer=dynamic_cast<Gtk::CellRendererText*>(get_column(0)->get_first_cell()); get_column(0)->add_attribute(renderer->property_foreground_rgba(), column_record.color); tree_store->set_sort_column(column_record.id, Gtk::SortType::SORT_ASCENDING); set_enable_search(true); //TODO: why does this not work in OS X? set_search_column(column_record.name); signal_row_activated().connect([this](const Gtk::TreeModel::Path& path, Gtk::TreeViewColumn* column){ auto iter = tree_store->get_iter(path); if (iter) { auto filesystem_path=iter->get_value(column_record.path); if(filesystem_path!="") { if (boost::filesystem::is_directory(boost::filesystem::path(filesystem_path))) { row_expanded(path) ? collapse_row(path) : expand_row(path, false); } else { if(on_row_activated) on_row_activated(filesystem_path); } } } }); signal_test_expand_row().connect([this](const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& path){ if(iter->children().begin()->get_value(column_record.path)=="") { update_mutex.lock(); add_path(iter->get_value(column_record.path), *iter); update_mutex.unlock(); } return false; }); signal_row_collapsed().connect([this](const Gtk::TreeModel::iterator& iter, const Gtk::TreeModel::Path& path){ update_mutex.lock(); auto directory_str=iter->get_value(column_record.path).string(); for(auto it=last_write_times.begin();it!=last_write_times.end();) { if(directory_str==it->first.substr(0, directory_str.size())) it=last_write_times.erase(it); else it++; } update_mutex.unlock(); auto children=iter->children(); if(children) { while(children) { tree_store->erase(children.begin()); } auto child=tree_store->append(iter->children()); child->set_value(column_record.name, std::string("(empty)")); Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); child->set_value(column_record.color, rgba); } }); update_thread=std::thread([this](){ while(!stop_update_thread) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); update_mutex.lock(); if(update_paths.size()==0) { for(auto it=last_write_times.begin();it!=last_write_times.end();) { boost::system::error_code ec; auto last_write_time=boost::filesystem::last_write_time(it->first, ec); if(!ec) { if(it->second.second<last_write_time) { update_paths.emplace_back(it->first); } it++; } else it=last_write_times.erase(it); } if(update_paths.size()>0) { dispatcher.post([this] { update_mutex.lock(); for(auto &path: update_paths) { if(last_write_times.count(path)>0) add_path(path, last_write_times.at(path).first); } update_paths.clear(); update_mutex.unlock(); }); } } update_mutex.unlock(); } }); enable_model_drag_source(); enable_model_drag_dest(); menu_item_delete.set_label("Delete"); menu_item_delete.signal_activate().connect([this] { if(menu_popup_row_path.empty()) return; Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Delete!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO); dialog.set_default_response(Gtk::RESPONSE_NO); dialog.set_secondary_text("Are you sure you want to delete "+menu_popup_row_path.string()+"?"); int result = dialog.run(); if(result==Gtk::RESPONSE_YES) { bool is_directory=boost::filesystem::is_directory(menu_popup_row_path); boost::system::error_code ec; boost::filesystem::remove_all(menu_popup_row_path, ec); if(ec) Terminal::get().print("Error: could not delete "+menu_popup_row_path.string()+": "+ec.message()+"\n", true); else { update(); for(int c=0;c<Notebook::get().size();c++) { auto view=Notebook::get().get_view(c); if(is_directory) { if(filesystem::file_in_path(view->file_path, menu_popup_row_path)) view->get_buffer()->set_modified(); } else if(view->file_path==menu_popup_row_path) view->get_buffer()->set_modified(); } } } }); menu.append(menu_item_delete); menu.show_all(); menu.accelerate(*this); } Directories::~Directories() { stop_update_thread=true; update_thread.join(); dispatcher.disconnect(); } void Directories::open(const boost::filesystem::path& dir_path) { JDEBUG("start"); if(dir_path.empty()) return; tree_store->clear(); update_mutex.lock(); last_write_times.clear(); update_paths.clear(); update_mutex.unlock(); //TODO: report that set_title does not handle '_' correctly? auto title=dir_path.filename().string(); size_t pos=0; while((pos=title.find('_', pos))!=std::string::npos) { title.replace(pos, 1, "__"); pos+=2; } get_column(0)->set_title(title); update_mutex.lock(); add_path(dir_path, Gtk::TreeModel::Row()); update_mutex.unlock(); path=dir_path; JDEBUG("end"); } void Directories::update() { JDEBUG("start"); update_mutex.lock(); for(auto &last_write_time: last_write_times) { add_path(last_write_time.first, last_write_time.second.first); } update_mutex.unlock(); JDEBUG("end"); } void Directories::select(const boost::filesystem::path &select_path) { JDEBUG("start"); if(path=="") return; if(select_path.generic_string().substr(0, path.generic_string().size()+1)!=path.generic_string()+'/') return; std::list<boost::filesystem::path> paths; boost::filesystem::path parent_path; if(boost::filesystem::is_directory(select_path)) parent_path=select_path; else parent_path=select_path.parent_path(); paths.emplace_front(parent_path); while(parent_path!=path) { parent_path=parent_path.parent_path(); paths.emplace_front(parent_path); } for(auto &a_path: paths) { tree_store->foreach_iter([this, &a_path](const Gtk::TreeModel::iterator& iter){ if(iter->get_value(column_record.path)==a_path) { update_mutex.lock(); add_path(a_path, *iter); update_mutex.unlock(); return true; } return false; }); } tree_store->foreach_iter([this, &select_path](const Gtk::TreeModel::iterator& iter){ if(iter->get_value(column_record.path)==select_path) { auto tree_path=Gtk::TreePath(iter); expand_to_path(tree_path); set_cursor(tree_path); return true; } return false; }); JDEBUG("end"); } bool Directories::on_button_press_event(GdkEventButton* event) { if(event->type==GDK_BUTTON_PRESS && event->button==3) { Gtk::TreeModel::Path path; if(get_path_at_pos(static_cast<int>(event->x), static_cast<int>(event->y), path)) { menu_popup_row_path=get_model()->get_iter(path)->get_value(column_record.path); menu.popup(event->button, event->time); return true; } } return Gtk::TreeView::on_button_press_event(event); } void Directories::add_path(const boost::filesystem::path& dir_path, const Gtk::TreeModel::Row &parent) { boost::system::error_code ec; auto last_write_time=boost::filesystem::last_write_time(dir_path, ec); if(ec) return; last_write_times[dir_path.string()]={parent, last_write_time}; std::unique_ptr<Gtk::TreeNodeChildren> children; //Gtk::TreeNodeChildren is missing default constructor... if(parent) children=std::unique_ptr<Gtk::TreeNodeChildren>(new Gtk::TreeNodeChildren(parent.children())); else children=std::unique_ptr<Gtk::TreeNodeChildren>(new Gtk::TreeNodeChildren(tree_store->children())); if(*children) { if(children->begin()->get_value(column_record.path)=="") tree_store->erase(children->begin()); } std::unordered_set<std::string> not_deleted; boost::filesystem::directory_iterator end_it; for(boost::filesystem::directory_iterator it(dir_path);it!=end_it;it++) { auto filename=it->path().filename().string(); bool already_added=false; if(*children) { for(auto &child: *children) { if(child->get_value(column_record.name)==filename) { not_deleted.emplace(filename); already_added=true; break; } } } if(!already_added) { auto child = tree_store->append(*children); not_deleted.emplace(filename); child->set_value(column_record.name, filename); child->set_value(column_record.path, it->path()); if (boost::filesystem::is_directory(it->path())) { child->set_value(column_record.id, "a"+filename); auto grandchild=tree_store->append(child->children()); grandchild->set_value(column_record.name, std::string("(empty)")); Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); grandchild->set_value(column_record.color, rgba); } else { child->set_value(column_record.id, "b"+filename); auto language=Source::guess_language(it->path().filename()); if(!language) { Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); child->set_value(column_record.color, rgba); } } } } if(*children) { for(auto it=children->begin();it!=children->end();) { if(not_deleted.count(it->get_value(column_record.name))==0) { it=tree_store->erase(it); } else it++; } } if(!*children) { auto child=tree_store->append(*children); child->set_value(column_record.name, std::string("(empty)")); Gdk::RGBA rgba; rgba.set_rgba(0.5, 0.5, 0.5); child->set_value(column_record.color, rgba); } } <|endoftext|>
<commit_before>#include <metaSMT/frontend/QF_BV.hpp> #include <metaSMT/API/Comment.hpp> #include <boost/test/unit_test.hpp> // lazy headers using namespace metaSMT; using namespace logic; using namespace logic::QF_BV; namespace proto = boost::proto; BOOST_FIXTURE_TEST_SUITE(annotate_t, Solver_Fixture ) BOOST_AUTO_TEST_CASE( comment1 ) { predicate x = new_variable(); assertion( ctx, True); comment( ctx, "jetzt kommt eine variable"); assertion( ctx, x); comment( ctx, "jetzt kommt solve"); BOOST_REQUIRE( solve(ctx) ); } BOOST_AUTO_TEST_SUITE_END() //lazy_t // vim: ft=cpp:ts=2:sw=2:expandtab <commit_msg>added a test case for variable naming in test_annotate<commit_after>#include <metaSMT/frontend/QF_BV.hpp> #include <metaSMT/API/Comment.hpp> #include <metaSMT/API/SymbolTable.hpp> #include <boost/test/unit_test.hpp> // lazy headers using namespace metaSMT; using namespace logic; using namespace logic::QF_BV; namespace proto = boost::proto; struct Lookup { std::map<unsigned, std::string> map_; std::string operator()(unsigned id) { return map_[id]; } void insert(predicate p, std::string const &name) { map_.insert(std::make_pair(boost::proto::value(p).id, name)); } }; BOOST_FIXTURE_TEST_SUITE(annotate_t, Solver_Fixture ) BOOST_AUTO_TEST_CASE( comment1 ) { predicate x = new_variable(); assertion( ctx, True); comment( ctx, "jetzt kommt eine variable"); assertion( ctx, x); comment( ctx, "jetzt kommt solve"); BOOST_REQUIRE( solve(ctx) ); } BOOST_AUTO_TEST_CASE( symbol_table ) { Lookup lookup; predicate x = new_variable(); lookup.insert(x, "x"); set_symbol_table( ctx, lookup); assertion( ctx, x); BOOST_REQUIRE( solve(ctx) ); } BOOST_AUTO_TEST_SUITE_END() //lazy_t // vim: ft=cpp:ts=2:sw=2:expandtab <|endoftext|>
<commit_before>// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/translator/TranslatorGLSL.h" #include "angle_gl.h" #include "compiler/translator/BuiltInFunctionEmulatorGLSL.h" #include "compiler/translator/EmulatePrecision.h" #include "compiler/translator/ExtensionGLSL.h" #include "compiler/translator/OutputGLSL.h" #include "compiler/translator/VersionGLSL.h" TranslatorGLSL::TranslatorGLSL(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output) : TCompiler(type, spec, output) { } void TranslatorGLSL::initBuiltInFunctionEmulator(BuiltInFunctionEmulator *emu, int compileOptions) { if (compileOptions & SH_EMULATE_BUILT_IN_FUNCTIONS) { InitBuiltInFunctionEmulatorForGLSLWorkarounds(emu, getShaderType()); } int targetGLSLVersion = ShaderOutputTypeToGLSLVersion(getOutputType()); InitBuiltInFunctionEmulatorForGLSLMissingFunctions(emu, getShaderType(), targetGLSLVersion); } void TranslatorGLSL::translate(TIntermNode *root, int compileOptions) { TInfoSinkBase& sink = getInfoSink().obj; // Write GLSL version. writeVersion(root); writePragma(); // Write extension behaviour as needed writeExtensionBehavior(root); bool precisionEmulation = getResources().WEBGL_debug_shader_precision && getPragma().debugShaderPrecision; if (precisionEmulation) { EmulatePrecision emulatePrecision(getSymbolTable(), getShaderVersion()); root->traverse(&emulatePrecision); emulatePrecision.updateTree(); emulatePrecision.writeEmulationHelpers(sink, getOutputType()); } // Write emulated built-in functions if needed. if (!getBuiltInFunctionEmulator().IsOutputEmpty()) { sink << "// BEGIN: Generated code for built-in function emulation\n\n"; sink << "#define webgl_emu_precision\n\n"; getBuiltInFunctionEmulator().OutputEmulatedFunctions(sink); sink << "// END: Generated code for built-in function emulation\n\n"; } // Write array bounds clamping emulation if needed. getArrayBoundsClamper().OutputClampingFunctionDefinition(sink); // Declare gl_FragColor and glFragData as webgl_FragColor and webgl_FragData // if it's core profile shaders and they are used. if (getShaderType() == GL_FRAGMENT_SHADER) { const bool mayHaveESSL1SecondaryOutputs = IsExtensionEnabled(getExtensionBehavior(), "GL_EXT_blend_func_extended") && getShaderVersion() == 100; const bool declareGLFragmentOutputs = IsGLSL130OrNewer(getOutputType()); bool hasGLFragColor = false; bool hasGLFragData = false; bool hasGLSecondaryFragColor = false; bool hasGLSecondaryFragData = false; for (const auto &outputVar : outputVariables) { if (declareGLFragmentOutputs) { if (outputVar.name == "gl_FragColor") { ASSERT(!hasGLFragColor); hasGLFragColor = true; continue; } else if (outputVar.name == "gl_FragData") { ASSERT(!hasGLFragData); hasGLFragData = true; continue; } } if (mayHaveESSL1SecondaryOutputs) { if (outputVar.name == "gl_SecondaryFragColorEXT") { ASSERT(!hasGLSecondaryFragColor); hasGLSecondaryFragColor = true; continue; } else if (outputVar.name == "gl_SecondaryFragDataEXT") { ASSERT(!hasGLSecondaryFragData); hasGLSecondaryFragData = true; continue; } } } ASSERT(!((hasGLFragColor || hasGLSecondaryFragColor) && (hasGLFragData || hasGLSecondaryFragData))); if (hasGLFragColor) { sink << "out vec4 webgl_FragColor;\n"; } if (hasGLFragData) { sink << "out vec4 webgl_FragData[gl_MaxDrawBuffers];\n"; } if (hasGLSecondaryFragColor) { sink << "out vec4 angle_SecondaryFragColor;\n"; } if (hasGLSecondaryFragData) { sink << "out vec4 angle_SecondaryFragData[" << getResources().MaxDualSourceDrawBuffers << "];\n"; } } // Write translated shader. TOutputGLSL outputGLSL(sink, getArrayIndexClampingStrategy(), getHashFunction(), getNameMap(), getSymbolTable(), getShaderVersion(), getOutputType()); root->traverse(&outputGLSL); } void TranslatorGLSL::writeVersion(TIntermNode *root) { TVersionGLSL versionGLSL(getShaderType(), getPragma(), getOutputType()); root->traverse(&versionGLSL); int version = versionGLSL.getVersion(); // We need to write version directive only if it is greater than 110. // If there is no version directive in the shader, 110 is implied. if (version > 110) { TInfoSinkBase& sink = getInfoSink().obj; sink << "#version " << version << "\n"; } } void TranslatorGLSL::writeExtensionBehavior(TIntermNode *root) { TInfoSinkBase& sink = getInfoSink().obj; const TExtensionBehavior& extBehavior = getExtensionBehavior(); for (const auto &iter : extBehavior) { if (iter.second == EBhUndefined) { continue; } // For GLSL output, we don't need to emit most extensions explicitly, // but some we need to translate. if (iter.first == "GL_EXT_shader_texture_lod") { sink << "#extension GL_ARB_shader_texture_lod : " << getBehaviorString(iter.second) << "\n"; } if (iter.first == "GL_EXT_draw_buffers") { sink << "#extension GL_ARB_draw_buffers : " << getBehaviorString(iter.second) << "\n"; } } // GLSL ES 3 explicit location qualifiers need to use an extension before GLSL 330 if (getShaderVersion() >= 300 && getOutputType() < SH_GLSL_330_CORE_OUTPUT) { sink << "#extension GL_ARB_explicit_attrib_location : require\n"; } TExtensionGLSL extensionGLSL(getOutputType()); root->traverse(&extensionGLSL); for (const auto &ext : extensionGLSL.getEnabledExtensions()) { sink << "#extension " << ext << " : enable\n"; } for (const auto &ext : extensionGLSL.getRequiredExtensions()) { sink << "#extension " << ext << " : require\n"; } } <commit_msg>Don't emit shader_texture_lod and draw_buffers extensions in core profile shader.<commit_after>// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/translator/TranslatorGLSL.h" #include "angle_gl.h" #include "compiler/translator/BuiltInFunctionEmulatorGLSL.h" #include "compiler/translator/EmulatePrecision.h" #include "compiler/translator/ExtensionGLSL.h" #include "compiler/translator/OutputGLSL.h" #include "compiler/translator/VersionGLSL.h" TranslatorGLSL::TranslatorGLSL(sh::GLenum type, ShShaderSpec spec, ShShaderOutput output) : TCompiler(type, spec, output) { } void TranslatorGLSL::initBuiltInFunctionEmulator(BuiltInFunctionEmulator *emu, int compileOptions) { if (compileOptions & SH_EMULATE_BUILT_IN_FUNCTIONS) { InitBuiltInFunctionEmulatorForGLSLWorkarounds(emu, getShaderType()); } int targetGLSLVersion = ShaderOutputTypeToGLSLVersion(getOutputType()); InitBuiltInFunctionEmulatorForGLSLMissingFunctions(emu, getShaderType(), targetGLSLVersion); } void TranslatorGLSL::translate(TIntermNode *root, int compileOptions) { TInfoSinkBase& sink = getInfoSink().obj; // Write GLSL version. writeVersion(root); writePragma(); // Write extension behaviour as needed writeExtensionBehavior(root); bool precisionEmulation = getResources().WEBGL_debug_shader_precision && getPragma().debugShaderPrecision; if (precisionEmulation) { EmulatePrecision emulatePrecision(getSymbolTable(), getShaderVersion()); root->traverse(&emulatePrecision); emulatePrecision.updateTree(); emulatePrecision.writeEmulationHelpers(sink, getOutputType()); } // Write emulated built-in functions if needed. if (!getBuiltInFunctionEmulator().IsOutputEmpty()) { sink << "// BEGIN: Generated code for built-in function emulation\n\n"; sink << "#define webgl_emu_precision\n\n"; getBuiltInFunctionEmulator().OutputEmulatedFunctions(sink); sink << "// END: Generated code for built-in function emulation\n\n"; } // Write array bounds clamping emulation if needed. getArrayBoundsClamper().OutputClampingFunctionDefinition(sink); // Declare gl_FragColor and glFragData as webgl_FragColor and webgl_FragData // if it's core profile shaders and they are used. if (getShaderType() == GL_FRAGMENT_SHADER) { const bool mayHaveESSL1SecondaryOutputs = IsExtensionEnabled(getExtensionBehavior(), "GL_EXT_blend_func_extended") && getShaderVersion() == 100; const bool declareGLFragmentOutputs = IsGLSL130OrNewer(getOutputType()); bool hasGLFragColor = false; bool hasGLFragData = false; bool hasGLSecondaryFragColor = false; bool hasGLSecondaryFragData = false; for (const auto &outputVar : outputVariables) { if (declareGLFragmentOutputs) { if (outputVar.name == "gl_FragColor") { ASSERT(!hasGLFragColor); hasGLFragColor = true; continue; } else if (outputVar.name == "gl_FragData") { ASSERT(!hasGLFragData); hasGLFragData = true; continue; } } if (mayHaveESSL1SecondaryOutputs) { if (outputVar.name == "gl_SecondaryFragColorEXT") { ASSERT(!hasGLSecondaryFragColor); hasGLSecondaryFragColor = true; continue; } else if (outputVar.name == "gl_SecondaryFragDataEXT") { ASSERT(!hasGLSecondaryFragData); hasGLSecondaryFragData = true; continue; } } } ASSERT(!((hasGLFragColor || hasGLSecondaryFragColor) && (hasGLFragData || hasGLSecondaryFragData))); if (hasGLFragColor) { sink << "out vec4 webgl_FragColor;\n"; } if (hasGLFragData) { sink << "out vec4 webgl_FragData[gl_MaxDrawBuffers];\n"; } if (hasGLSecondaryFragColor) { sink << "out vec4 angle_SecondaryFragColor;\n"; } if (hasGLSecondaryFragData) { sink << "out vec4 angle_SecondaryFragData[" << getResources().MaxDualSourceDrawBuffers << "];\n"; } } // Write translated shader. TOutputGLSL outputGLSL(sink, getArrayIndexClampingStrategy(), getHashFunction(), getNameMap(), getSymbolTable(), getShaderVersion(), getOutputType()); root->traverse(&outputGLSL); } void TranslatorGLSL::writeVersion(TIntermNode *root) { TVersionGLSL versionGLSL(getShaderType(), getPragma(), getOutputType()); root->traverse(&versionGLSL); int version = versionGLSL.getVersion(); // We need to write version directive only if it is greater than 110. // If there is no version directive in the shader, 110 is implied. if (version > 110) { TInfoSinkBase& sink = getInfoSink().obj; sink << "#version " << version << "\n"; } } void TranslatorGLSL::writeExtensionBehavior(TIntermNode *root) { TInfoSinkBase& sink = getInfoSink().obj; const TExtensionBehavior& extBehavior = getExtensionBehavior(); for (const auto &iter : extBehavior) { if (iter.second == EBhUndefined) { continue; } if (getOutputType() == SH_GLSL_COMPATIBILITY_OUTPUT) { // For GLSL output, we don't need to emit most extensions explicitly, // but some we need to translate in GL compatibility profile. if (iter.first == "GL_EXT_shader_texture_lod") { sink << "#extension GL_ARB_shader_texture_lod : " << getBehaviorString(iter.second) << "\n"; } if (iter.first == "GL_EXT_draw_buffers") { sink << "#extension GL_ARB_draw_buffers : " << getBehaviorString(iter.second) << "\n"; } } } // GLSL ES 3 explicit location qualifiers need to use an extension before GLSL 330 if (getShaderVersion() >= 300 && getOutputType() < SH_GLSL_330_CORE_OUTPUT) { sink << "#extension GL_ARB_explicit_attrib_location : require\n"; } TExtensionGLSL extensionGLSL(getOutputType()); root->traverse(&extensionGLSL); for (const auto &ext : extensionGLSL.getEnabledExtensions()) { sink << "#extension " << ext << " : enable\n"; } for (const auto &ext : extensionGLSL.getRequiredExtensions()) { sink << "#extension " << ext << " : require\n"; } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // query_to_operator_transformer.cpp // // Identification: src/optimizer/query_to_operator_transformer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cmath> #include "expression/expression_util.h" #include "optimizer/operator_expression.h" #include "optimizer/operators.h" #include "optimizer/query_node_visitor.h" #include "optimizer/query_to_operator_transformer.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" #include "parser/statements.h" #include "catalog/catalog.h" #include "catalog/manager.h" using std::vector; using std::shared_ptr; namespace peloton { namespace optimizer { std::shared_ptr<OperatorExpression> QueryToOperatorTransformer::ConvertToOpExpression(parser::SQLStatement *op) { output_expr = nullptr; op->Accept(this); return output_expr; } void QueryToOperatorTransformer::Visit(const parser::SelectStatement *op) { auto upper_expr = output_expr; if (op->where_clause != nullptr) { SingleTablePredicates where_predicates; util::ExtractPredicates(op->where_clause, where_predicates, join_predicates_); // Remove join predicates in the where clause if (!join_predicates_.empty()) { // Discard the const qualifier to update the where clause. // The select statement can only be updated in this way. This is a hack. ((parser::SelectStatement *)op) ->UpdateWhereClause(util::CombinePredicates(where_predicates)); } else { for (auto expr : where_predicates) delete expr; } } if (op->from_table != nullptr) { // SELECT with FROM op->from_table->Accept(this); if (op->group_by != nullptr) { // Make copies of groupby columns vector<shared_ptr<expression::AbstractExpression>> group_by_cols; for (auto col : *op->group_by->columns) group_by_cols.emplace_back(col->Copy()); auto group_by = std::make_shared<OperatorExpression>( LogicalGroupBy::make(move(group_by_cols), op->group_by->having)); group_by->PushChild(output_expr); output_expr = group_by; } else { // Check plain aggregation bool has_aggregation = false; bool has_other_exprs = false; for (auto expr : *op->getSelectList()) { vector<shared_ptr<expression::AggregateExpression>> aggr_exprs; expression::ExpressionUtil::GetAggregateExprs(aggr_exprs, expr); if (aggr_exprs.size() > 0) has_aggregation = true; else has_other_exprs = true; } // Syntax error when there are mixture of aggregation and other exprs // when group by is absent if (has_aggregation && has_other_exprs) throw SyntaxException( "Non aggregation expression must appear in the GROUP BY " "clause or be used in an aggregate function"); // Plain aggregation else if (has_aggregation && !has_other_exprs) { auto aggregate = std::make_shared<OperatorExpression>(LogicalAggregate::make()); aggregate->PushChild(output_expr); output_expr = aggregate; } } } else { // SELECT without FROM output_expr = std::make_shared<OperatorExpression>(LogicalGet::make()); } // Update output_expr if upper_expr exists if (upper_expr != nullptr) { upper_expr->PushChild(output_expr); output_expr = upper_expr; } } void QueryToOperatorTransformer::Visit(const parser::JoinDefinition *node) { // Get left operator node->left->Accept(this); auto left_expr = output_expr; auto left_table_alias_set = table_alias_set_; table_alias_set_.clear(); // Get right operator node->right->Accept(this); auto right_expr = output_expr; util::SetUnion(table_alias_set_, left_table_alias_set); // Construct join operator std::shared_ptr<OperatorExpression> join_expr; switch (node->type) { case JoinType::INNER: { if (node->condition != nullptr) { // Add join condition into join predicates std::unordered_set<std::string> join_condition_table_alias_set; expression::ExpressionUtil::GenerateTableAliasSet( node->condition, join_condition_table_alias_set); join_predicates_.emplace_back( MultiTableExpression(node->condition->Copy(), join_condition_table_alias_set)); } join_expr = std::make_shared<OperatorExpression>( LogicalInnerJoin::make( util::ConstructJoinPredicate(table_alias_set_, join_predicates_))); break; } case JoinType::OUTER: { join_expr = std::make_shared<OperatorExpression>( LogicalOuterJoin::make(node->condition->Copy())); break; } case JoinType::LEFT: { join_expr = std::make_shared<OperatorExpression>( LogicalLeftJoin::make(node->condition->Copy())); break; } case JoinType::RIGHT: { join_expr = std::make_shared<OperatorExpression>( LogicalRightJoin::make(node->condition->Copy())); break; } case JoinType::SEMI: { join_expr = std::make_shared<OperatorExpression>( LogicalSemiJoin::make(node->condition->Copy())); break; } default: throw Exception("Join type invalid"); } join_expr->PushChild(left_expr); join_expr->PushChild(right_expr); output_expr = join_expr; } void QueryToOperatorTransformer::Visit(const parser::TableRef *node) { // Nested select. Not supported in the current executors if (node->select != nullptr) { throw NotImplementedException("Not support joins"); node->select->Accept(this); } // Join else if (node->join != nullptr) { node->join->Accept(this); } // Multiple tables else if (node->list != nullptr && node->list->size() > 1) { node->list->at(0)->Accept(this); auto left_expr = output_expr; node->list->at(1)->Accept(this); auto right_expr = output_expr; auto join_expr = std::make_shared<OperatorExpression>( LogicalInnerJoin::make( util::ConstructJoinPredicate(table_alias_set_, join_predicates_))); join_expr->PushChild(left_expr); join_expr->PushChild(right_expr); for (size_t i=2; i<node->list->size(); i++) { node->list->at(i)->Accept(this); auto old_join_expr = join_expr; join_expr = std::make_shared<OperatorExpression>( LogicalInnerJoin::make( util::ConstructJoinPredicate(table_alias_set_, join_predicates_))); join_expr->PushChild(old_join_expr); join_expr->PushChild(output_expr); } output_expr = join_expr; } // Single table else { if (node->list != nullptr && node->list->size() == 1) node = node->list->at(0); storage::DataTable *target_table = catalog::Catalog::GetInstance()->GetTableWithName( node->GetDatabaseName(), node->GetTableName()); // Update table alias map table_alias_set_.insert(StringUtil::Lower(std::string(node->GetTableAlias()))); // Construct logical operator auto get_expr = std::make_shared<OperatorExpression>( LogicalGet::make(target_table, node->GetTableAlias())); output_expr = get_expr; } } void QueryToOperatorTransformer::Visit(const parser::GroupByDescription *) {} void QueryToOperatorTransformer::Visit(const parser::OrderDescription *) {} void QueryToOperatorTransformer::Visit(const parser::LimitDescription *) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::CreateStatement *op) {} void QueryToOperatorTransformer::Visit(const parser::InsertStatement *op) { storage::DataTable *target_table = catalog::Catalog::GetInstance()->GetTableWithName(op->GetDatabaseName(), op->GetTableName()); auto insert_expr = std::make_shared<OperatorExpression>( LogicalInsert::make(target_table, op->columns, op->insert_values)); output_expr = insert_expr; } void QueryToOperatorTransformer::Visit(const parser::DeleteStatement *op) { auto target_table = catalog::Catalog::GetInstance()->GetTableWithName( op->GetDatabaseName(), op->GetTableName()); auto table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(target_table, op->GetTableName())); auto delete_expr = std::make_shared<OperatorExpression>(LogicalDelete::make(target_table)); delete_expr->PushChild(table_scan); output_expr = delete_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::DropStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::PrepareStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::ExecuteStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::TransactionStatement *op) {} void QueryToOperatorTransformer::Visit(const parser::UpdateStatement *op) { auto target_table = catalog::Catalog::GetInstance()->GetTableWithName( op->table->GetDatabaseName(), op->table->GetTableName()); auto update_expr = std::make_shared<OperatorExpression>( LogicalUpdate::make(target_table, *op->updates)); auto table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(target_table, op->table->GetTableName(), true)); update_expr->PushChild(table_scan); output_expr = update_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::CopyStatement *op) {} } /* namespace optimizer */ } /* namespace peloton */ <commit_msg>Minor fix<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // query_to_operator_transformer.cpp // // Identification: src/optimizer/query_to_operator_transformer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cmath> #include "expression/expression_util.h" #include "optimizer/operator_expression.h" #include "optimizer/operators.h" #include "optimizer/query_node_visitor.h" #include "optimizer/query_to_operator_transformer.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" #include "parser/statements.h" #include "catalog/catalog.h" #include "catalog/manager.h" using std::vector; using std::shared_ptr; namespace peloton { namespace optimizer { std::shared_ptr<OperatorExpression> QueryToOperatorTransformer::ConvertToOpExpression(parser::SQLStatement *op) { output_expr = nullptr; op->Accept(this); return output_expr; } void QueryToOperatorTransformer::Visit(const parser::SelectStatement *op) { auto upper_expr = output_expr; if (op->where_clause != nullptr) { SingleTablePredicates where_predicates; util::ExtractPredicates(op->where_clause, where_predicates, join_predicates_); // Remove join predicates in the where clause if (!join_predicates_.empty()) { // Discard the const qualifier to update the where clause. // The select statement can only be updated in this way. This is a hack. ((parser::SelectStatement *)op) ->UpdateWhereClause(util::CombinePredicates(where_predicates)); } else { for (auto expr : where_predicates) delete expr; } } if (op->from_table != nullptr) { // SELECT with FROM op->from_table->Accept(this); if (op->group_by != nullptr) { // Make copies of groupby columns vector<shared_ptr<expression::AbstractExpression>> group_by_cols; for (auto col : *op->group_by->columns) group_by_cols.emplace_back(col->Copy()); auto group_by = std::make_shared<OperatorExpression>( LogicalGroupBy::make(move(group_by_cols), op->group_by->having)); group_by->PushChild(output_expr); output_expr = group_by; } else { // Check plain aggregation bool has_aggregation = false; bool has_other_exprs = false; for (auto expr : *op->getSelectList()) { vector<shared_ptr<expression::AggregateExpression>> aggr_exprs; expression::ExpressionUtil::GetAggregateExprs(aggr_exprs, expr); if (aggr_exprs.size() > 0) has_aggregation = true; else has_other_exprs = true; } // Syntax error when there are mixture of aggregation and other exprs // when group by is absent if (has_aggregation && has_other_exprs) throw SyntaxException( "Non aggregation expression must appear in the GROUP BY " "clause or be used in an aggregate function"); // Plain aggregation else if (has_aggregation && !has_other_exprs) { auto aggregate = std::make_shared<OperatorExpression>(LogicalAggregate::make()); aggregate->PushChild(output_expr); output_expr = aggregate; } } } else { // SELECT without FROM output_expr = std::make_shared<OperatorExpression>(LogicalGet::make()); } // Update output_expr if upper_expr exists if (upper_expr != nullptr) { upper_expr->PushChild(output_expr); output_expr = upper_expr; } } void QueryToOperatorTransformer::Visit(const parser::JoinDefinition *node) { // Get left operator node->left->Accept(this); auto left_expr = output_expr; auto left_table_alias_set = table_alias_set_; table_alias_set_.clear(); // Get right operator node->right->Accept(this); auto right_expr = output_expr; util::SetUnion(table_alias_set_, left_table_alias_set); // Construct join operator std::shared_ptr<OperatorExpression> join_expr; switch (node->type) { case JoinType::INNER: { if (node->condition != nullptr) { // Add join condition into join predicates std::unordered_set<std::string> join_condition_table_alias_set; expression::ExpressionUtil::GenerateTableAliasSet( node->condition, join_condition_table_alias_set); join_predicates_.emplace_back( MultiTableExpression(node->condition->Copy(), join_condition_table_alias_set)); } join_expr = std::make_shared<OperatorExpression>( LogicalInnerJoin::make( util::ConstructJoinPredicate(table_alias_set_, join_predicates_))); break; } case JoinType::OUTER: { join_expr = std::make_shared<OperatorExpression>( LogicalOuterJoin::make(node->condition->Copy())); break; } case JoinType::LEFT: { join_expr = std::make_shared<OperatorExpression>( LogicalLeftJoin::make(node->condition->Copy())); break; } case JoinType::RIGHT: { join_expr = std::make_shared<OperatorExpression>( LogicalRightJoin::make(node->condition->Copy())); break; } case JoinType::SEMI: { join_expr = std::make_shared<OperatorExpression>( LogicalSemiJoin::make(node->condition->Copy())); break; } default: throw Exception("Join type invalid"); } join_expr->PushChild(left_expr); join_expr->PushChild(right_expr); output_expr = join_expr; } void QueryToOperatorTransformer::Visit(const parser::TableRef *node) { // Nested select. Not supported in the current executors if (node->select != nullptr) { throw NotImplementedException("Not support joins"); node->select->Accept(this); } // Join else if (node->join != nullptr) { node->join->Accept(this); } // Multiple tables else if (node->list != nullptr && node->list->size() > 1) { node->list->at(0)->Accept(this); auto left_expr = output_expr; auto left_table_alias_set = table_alias_set_; table_alias_set_.clear(); node->list->at(1)->Accept(this); auto right_expr = output_expr; util::SetUnion(table_alias_set_, left_table_alias_set); auto join_expr = std::make_shared<OperatorExpression>( LogicalInnerJoin::make( util::ConstructJoinPredicate(table_alias_set_, join_predicates_))); join_expr->PushChild(left_expr); join_expr->PushChild(right_expr); for (size_t i=2; i<node->list->size(); i++) { node->list->at(i)->Accept(this); auto old_join_expr = join_expr; join_expr = std::make_shared<OperatorExpression>( LogicalInnerJoin::make( util::ConstructJoinPredicate(table_alias_set_, join_predicates_))); join_expr->PushChild(old_join_expr); join_expr->PushChild(output_expr); } output_expr = join_expr; } // Single table else { if (node->list != nullptr && node->list->size() == 1) node = node->list->at(0); storage::DataTable *target_table = catalog::Catalog::GetInstance()->GetTableWithName( node->GetDatabaseName(), node->GetTableName()); // Update table alias map table_alias_set_.insert(StringUtil::Lower(std::string(node->GetTableAlias()))); // Construct logical operator auto get_expr = std::make_shared<OperatorExpression>( LogicalGet::make(target_table, node->GetTableAlias())); output_expr = get_expr; } } void QueryToOperatorTransformer::Visit(const parser::GroupByDescription *) {} void QueryToOperatorTransformer::Visit(const parser::OrderDescription *) {} void QueryToOperatorTransformer::Visit(const parser::LimitDescription *) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::CreateStatement *op) {} void QueryToOperatorTransformer::Visit(const parser::InsertStatement *op) { storage::DataTable *target_table = catalog::Catalog::GetInstance()->GetTableWithName(op->GetDatabaseName(), op->GetTableName()); auto insert_expr = std::make_shared<OperatorExpression>( LogicalInsert::make(target_table, op->columns, op->insert_values)); output_expr = insert_expr; } void QueryToOperatorTransformer::Visit(const parser::DeleteStatement *op) { auto target_table = catalog::Catalog::GetInstance()->GetTableWithName( op->GetDatabaseName(), op->GetTableName()); auto table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(target_table, op->GetTableName())); auto delete_expr = std::make_shared<OperatorExpression>(LogicalDelete::make(target_table)); delete_expr->PushChild(table_scan); output_expr = delete_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::DropStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::PrepareStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::ExecuteStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::TransactionStatement *op) {} void QueryToOperatorTransformer::Visit(const parser::UpdateStatement *op) { auto target_table = catalog::Catalog::GetInstance()->GetTableWithName( op->table->GetDatabaseName(), op->table->GetTableName()); auto update_expr = std::make_shared<OperatorExpression>( LogicalUpdate::make(target_table, *op->updates)); auto table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(target_table, op->table->GetTableName(), true)); update_expr->PushChild(table_scan); output_expr = update_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE const parser::CopyStatement *op) {} } /* namespace optimizer */ } /* namespace peloton */ <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // query_to_operator_transformer.cpp // // Identification: src/optimizer/query_to_operator_transformer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cmath> #include "settings/settings_manager.h" #include "catalog/database_catalog.h" #include "expression/expression_util.h" #include "expression/subquery_expression.h" #include "optimizer/operator_expression.h" #include "optimizer/operators.h" #include "optimizer/query_node_visitor.h" #include "optimizer/query_to_operator_transformer.h" #include "planner/seq_scan_plan.h" #include "parser/statements.h" #include "catalog/manager.h" #include "common/exception.h" using std::vector; using std::shared_ptr; namespace peloton { namespace optimizer { QueryToOperatorTransformer::QueryToOperatorTransformer( concurrency::TransactionContext *txn) : txn_(txn), get_id(0), enable_predicate_push_down_(settings::SettingsManager::GetBool( settings::SettingId::predicate_push_down)) {} std::shared_ptr<OperatorExpression> QueryToOperatorTransformer::ConvertToOpExpression(parser::SQLStatement *op) { output_expr_ = nullptr; op->Accept(this); return output_expr_; } void QueryToOperatorTransformer::Visit(parser::SelectStatement *op) { // We do not visit the select list of a base table because the column // information is derived before the plan generation, at this step we // don't need to derive that auto pre_predicates = std::move(predicates_); auto pre_depth = depth_; depth_ = op->depth; if (op->from_table != nullptr) { // SELECT with FROM op->from_table->Accept(this); } else { // SELECT without FROM output_expr_ = std::make_shared<OperatorExpression>(LogicalGet::make()); } if (op->where_clause != nullptr) { CollectPredicates(op->where_clause.get()); } if (!predicates_.empty()) { auto filter_expr = std::make_shared<OperatorExpression>(LogicalFilter::make(predicates_)); filter_expr->PushChild(output_expr_); output_expr_ = filter_expr; } if (RequireAggregation(op)) { // Plain aggregation std::shared_ptr<OperatorExpression> agg_expr; if (op->group_by == nullptr) { agg_expr = std::make_shared<OperatorExpression>( LogicalAggregateAndGroupBy::make()); } else { size_t num_group_by_cols = op->group_by->columns.size(); auto group_by_cols = std::vector<std::shared_ptr<expression::AbstractExpression>>( num_group_by_cols); for (size_t i = 0; i < num_group_by_cols; i++) { group_by_cols[i] = std::shared_ptr<expression::AbstractExpression>( op->group_by->columns[i]->Copy()); } std::vector<AnnotatedExpression> having; if (op->group_by->having != nullptr) { util::ExtractPredicates(op->group_by->having.get(), having); } agg_expr = std::make_shared<OperatorExpression>( LogicalAggregateAndGroupBy::make(group_by_cols, having)); } agg_expr->PushChild(output_expr_); output_expr_ = agg_expr; } if (op->select_distinct) { auto distinct_expr = std::make_shared<OperatorExpression>(LogicalDistinct::make()); distinct_expr->PushChild(output_expr_); output_expr_ = distinct_expr; } if (op->limit != nullptr) { auto limit_expr = std::make_shared<OperatorExpression>( LogicalLimit::make(op->limit->offset, op->limit->limit)); limit_expr->PushChild(output_expr_); output_expr_ = limit_expr; } predicates_ = std::move(pre_predicates); depth_ = pre_depth; } void QueryToOperatorTransformer::Visit(parser::JoinDefinition *node) { // Get left operator node->left->Accept(this); auto left_expr = output_expr_; // Get right operator node->right->Accept(this); auto right_expr = output_expr_; // Construct join operator std::shared_ptr<OperatorExpression> join_expr; switch (node->type) { case JoinType::INNER: { CollectPredicates(node->condition.get()); join_expr = std::make_shared<OperatorExpression>(LogicalInnerJoin::make()); break; } case JoinType::OUTER: { join_expr = std::make_shared<OperatorExpression>( LogicalOuterJoin::make(node->condition->Copy())); break; } case JoinType::LEFT: { join_expr = std::make_shared<OperatorExpression>( LogicalLeftJoin::make(node->condition->Copy())); break; } case JoinType::RIGHT: { join_expr = std::make_shared<OperatorExpression>( LogicalRightJoin::make(node->condition->Copy())); break; } case JoinType::SEMI: { join_expr = std::make_shared<OperatorExpression>( LogicalSemiJoin::make(node->condition->Copy())); break; } default: throw Exception("Join type invalid"); } join_expr->PushChild(left_expr); join_expr->PushChild(right_expr); output_expr_ = join_expr; } void QueryToOperatorTransformer::Visit(parser::TableRef *node) { if (node->select != nullptr) { // Store previous context // Construct query derived table predicates // i.e. the mapping from column name to the underlying expression in the // sub-query. This is needed to generate input/output information for // subqueries auto table_alias = StringUtil::Lower(node->GetTableAlias()); auto alias_to_expr_map = util::ConstructSelectElementMap(node->select->select_list); node->select->Accept(this); auto alias = StringUtil::Lower(node->GetTableAlias()); auto child_expr = output_expr_; output_expr_ = std::make_shared<OperatorExpression>(LogicalQueryDerivedGet::make( GetAndIncreaseGetId(), alias, alias_to_expr_map)); output_expr_->PushChild(child_expr); } // Explicit Join else if (node->join != nullptr) { node->join->Accept(this); } // Multiple tables (Implicit Join) else if (node->list.size() > 1) { // Create a join operator between the first two tables node->list.at(0)->Accept(this); auto prev_expr = output_expr_; // Build a left deep join tree for (size_t i = 1; i < node->list.size(); i++) { node->list.at(i)->Accept(this); auto join_expr = std::make_shared<OperatorExpression>(LogicalInnerJoin::make()); join_expr->PushChild(prev_expr); join_expr->PushChild(output_expr_); PL_ASSERT(join_expr->Children().size() == 2); prev_expr = join_expr; } output_expr_ = prev_expr; } // Single table else { if (node->list.size() == 1) node = node->list.at(0).get(); std::shared_ptr<catalog::TableCatalogObject> target_table = catalog::Catalog::GetInstance()->GetTableObject( node->GetDatabaseName(), node->GetTableName(), txn_); std::string table_alias = StringUtil::Lower(std::string(node->GetTableAlias())); output_expr_ = std::make_shared<OperatorExpression>(LogicalGet::make( GetAndIncreaseGetId(), {}, target_table, node->GetTableAlias())); } } void QueryToOperatorTransformer::Visit(parser::GroupByDescription *) {} void QueryToOperatorTransformer::Visit(parser::OrderDescription *) {} void QueryToOperatorTransformer::Visit(parser::LimitDescription *) {} void QueryToOperatorTransformer::Visit(parser::CreateFunctionStatement *) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::CreateStatement *op) {} void QueryToOperatorTransformer::Visit(parser::InsertStatement *op) { std::shared_ptr<catalog::TableCatalogObject> target_table = catalog::Catalog::GetInstance() ->GetDatabaseObject(op->GetDatabaseName(), txn_) ->GetTableObject(op->GetTableName()); if (op->type == InsertType::SELECT) { auto insert_expr = std::make_shared<OperatorExpression>( LogicalInsertSelect::make(target_table)); op->select->Accept(this); insert_expr->PushChild(output_expr_); output_expr_ = insert_expr; } else { auto insert_expr = std::make_shared<OperatorExpression>( LogicalInsert::make(target_table, &op->columns, &op->insert_values)); output_expr_ = insert_expr; } } void QueryToOperatorTransformer::Visit(parser::DeleteStatement *op) { auto target_table = catalog::Catalog::GetInstance() ->GetDatabaseObject(op->GetDatabaseName(), txn_) ->GetTableObject(op->GetTableName()); std::shared_ptr<OperatorExpression> table_scan; if (op->expr != nullptr) { std::vector<AnnotatedExpression> predicates; util::ExtractPredicates(op->expr.get(), predicates); table_scan = std::make_shared<OperatorExpression>(LogicalGet::make( GetAndIncreaseGetId(), predicates, target_table, op->GetTableName())); } else table_scan = std::make_shared<OperatorExpression>(LogicalGet::make( GetAndIncreaseGetId(), {}, target_table, op->GetTableName())); auto delete_expr = std::make_shared<OperatorExpression>(LogicalDelete::make(target_table)); delete_expr->PushChild(table_scan); output_expr_ = delete_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::DropStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::PrepareStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::ExecuteStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::TransactionStatement *op) {} void QueryToOperatorTransformer::Visit(parser::UpdateStatement *op) { auto target_table = catalog::Catalog::GetInstance() ->GetDatabaseObject(op->table->GetDatabaseName(), txn_) ->GetTableObject(op->table->GetTableName()); std::shared_ptr<OperatorExpression> table_scan; auto update_expr = std::make_shared<OperatorExpression>( LogicalUpdate::make(target_table, &op->updates)); if (op->where != nullptr) { std::vector<AnnotatedExpression> predicates; util::ExtractPredicates(op->where.get(), predicates); table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(GetAndIncreaseGetId(), predicates, target_table, op->table->GetTableName(), true)); } else table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(GetAndIncreaseGetId(), {}, target_table, op->table->GetTableName(), true)); update_expr->PushChild(table_scan); output_expr_ = update_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::CopyStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::AnalyzeStatement *op) {} void QueryToOperatorTransformer::Visit(expression::ComparisonExpression *expr) { auto expr_type = expr->GetExpressionType(); if (expr->GetExpressionType() == ExpressionType::COMPARE_IN) { std::vector<expression::AbstractExpression *> select_list; if (GenerateSubquerytree(expr->GetModifiableChild(1), select_list) == true) { if (select_list.size() != 1) { throw Exception("Array in predicates not supported"); } // Set the right child as the output of the subquery expr->SetChild(1, select_list.at(0)->Copy()); expr->SetExpressionType(ExpressionType::COMPARE_EQUAL); } } else if (expr_type == ExpressionType::COMPARE_EQUAL || expr_type == ExpressionType::COMPARE_GREATERTHAN || expr_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO || expr_type == ExpressionType::COMPARE_LESSTHAN || expr_type == ExpressionType::COMPARE_LESSTHANOREQUALTO) { std::vector<expression::AbstractExpression *> select_list; if (GenerateSubquerytree(expr->GetModifiableChild(0), select_list, true) == true) { if (select_list.size() != 1) { throw Exception("Array in predicates not supported"); } // Set the left child as the output of the subquery expr->SetChild(0, select_list.at(0)->Copy()); } select_list.clear(); if (GenerateSubquerytree(expr->GetModifiableChild(1), select_list, true) == true) { if (select_list.size() != 1) { throw Exception("Array in predicates not supported"); } // Set the right child as the output of the subquery expr->SetChild(1, select_list.at(0)->Copy()); } } expr->AcceptChildren(this); } void QueryToOperatorTransformer::Visit(expression::OperatorExpression *expr) { if (expr->GetExpressionType() == ExpressionType::OPERATOR_EXISTS) { std::vector<expression::AbstractExpression *> select_list; if (GenerateSubquerytree(expr->GetModifiableChild(0), select_list) == true) { PL_ASSERT(!select_list.empty()); // Set the right child as the output of the subquery expr->SetExpressionType(ExpressionType::OPERATOR_IS_NOT_NULL); expr->SetChild(0, select_list.at(0)->Copy()); } } expr->AcceptChildren(this); } bool QueryToOperatorTransformer::RequireAggregation( const parser::SelectStatement *op) { if (op->group_by != nullptr) { return true; } // Check plain aggregation bool has_aggregation = false; bool has_other_exprs = false; for (auto &expr : op->getSelectList()) { std::vector<expression::AggregateExpression *> aggr_exprs; expression::ExpressionUtil::GetAggregateExprs(aggr_exprs, expr.get()); if (!aggr_exprs.empty()) { has_aggregation = true; } else { has_other_exprs = true; } } // TODO: Should be handled in the binder // Syntax error when there are mixture of aggregation and other exprs // when group by is absent if (has_aggregation && has_other_exprs) { throw SyntaxException( "Non aggregation expression must appear in the GROUP BY " "clause or be used in an aggregate function"); } return has_aggregation; } void QueryToOperatorTransformer::CollectPredicates( expression::AbstractExpression *expr) { expr->Accept(this); util::ExtractPredicates(expr, predicates_); } bool QueryToOperatorTransformer::GenerateSubquerytree( expression::AbstractExpression *expr, std::vector<expression::AbstractExpression *> &select_list, bool single_join) { if (expr->GetExpressionType() != ExpressionType::ROW_SUBQUERY) { return false; } auto subquery_expr = dynamic_cast<expression::SubqueryExpression *>(expr); auto sub_select = subquery_expr->GetSubSelect(); for (auto &ele : sub_select->select_list) { select_list.push_back(ele.get()); } // Construct join std::shared_ptr<OperatorExpression> op_expr; if (single_join) { op_expr = std::make_shared<OperatorExpression>(LogicalSingleJoin::make()); } else { op_expr = std::make_shared<OperatorExpression>(LogicalMarkJoin::make()); } // Push previous output op_expr->PushChild(output_expr_); sub_select->Accept(this); // Push subquery output op_expr->PushChild(output_expr_); output_expr_ = op_expr; return true; } } // namespace optimizer } // namespace peloton <commit_msg>Remove superfluous include<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // query_to_operator_transformer.cpp // // Identification: src/optimizer/query_to_operator_transformer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cmath> #include "settings/settings_manager.h" #include "catalog/database_catalog.h" #include "expression/expression_util.h" #include "expression/subquery_expression.h" #include "optimizer/operator_expression.h" #include "optimizer/operators.h" #include "optimizer/query_node_visitor.h" #include "optimizer/query_to_operator_transformer.h" #include "planner/seq_scan_plan.h" #include "parser/statements.h" #include "catalog/manager.h" using std::vector; using std::shared_ptr; namespace peloton { namespace optimizer { QueryToOperatorTransformer::QueryToOperatorTransformer( concurrency::TransactionContext *txn) : txn_(txn), get_id(0), enable_predicate_push_down_(settings::SettingsManager::GetBool( settings::SettingId::predicate_push_down)) {} std::shared_ptr<OperatorExpression> QueryToOperatorTransformer::ConvertToOpExpression(parser::SQLStatement *op) { output_expr_ = nullptr; op->Accept(this); return output_expr_; } void QueryToOperatorTransformer::Visit(parser::SelectStatement *op) { // We do not visit the select list of a base table because the column // information is derived before the plan generation, at this step we // don't need to derive that auto pre_predicates = std::move(predicates_); auto pre_depth = depth_; depth_ = op->depth; if (op->from_table != nullptr) { // SELECT with FROM op->from_table->Accept(this); } else { // SELECT without FROM output_expr_ = std::make_shared<OperatorExpression>(LogicalGet::make()); } if (op->where_clause != nullptr) { CollectPredicates(op->where_clause.get()); } if (!predicates_.empty()) { auto filter_expr = std::make_shared<OperatorExpression>(LogicalFilter::make(predicates_)); filter_expr->PushChild(output_expr_); output_expr_ = filter_expr; } if (RequireAggregation(op)) { // Plain aggregation std::shared_ptr<OperatorExpression> agg_expr; if (op->group_by == nullptr) { agg_expr = std::make_shared<OperatorExpression>( LogicalAggregateAndGroupBy::make()); } else { size_t num_group_by_cols = op->group_by->columns.size(); auto group_by_cols = std::vector<std::shared_ptr<expression::AbstractExpression>>( num_group_by_cols); for (size_t i = 0; i < num_group_by_cols; i++) { group_by_cols[i] = std::shared_ptr<expression::AbstractExpression>( op->group_by->columns[i]->Copy()); } std::vector<AnnotatedExpression> having; if (op->group_by->having != nullptr) { util::ExtractPredicates(op->group_by->having.get(), having); } agg_expr = std::make_shared<OperatorExpression>( LogicalAggregateAndGroupBy::make(group_by_cols, having)); } agg_expr->PushChild(output_expr_); output_expr_ = agg_expr; } if (op->select_distinct) { auto distinct_expr = std::make_shared<OperatorExpression>(LogicalDistinct::make()); distinct_expr->PushChild(output_expr_); output_expr_ = distinct_expr; } if (op->limit != nullptr) { auto limit_expr = std::make_shared<OperatorExpression>( LogicalLimit::make(op->limit->offset, op->limit->limit)); limit_expr->PushChild(output_expr_); output_expr_ = limit_expr; } predicates_ = std::move(pre_predicates); depth_ = pre_depth; } void QueryToOperatorTransformer::Visit(parser::JoinDefinition *node) { // Get left operator node->left->Accept(this); auto left_expr = output_expr_; // Get right operator node->right->Accept(this); auto right_expr = output_expr_; // Construct join operator std::shared_ptr<OperatorExpression> join_expr; switch (node->type) { case JoinType::INNER: { CollectPredicates(node->condition.get()); join_expr = std::make_shared<OperatorExpression>(LogicalInnerJoin::make()); break; } case JoinType::OUTER: { join_expr = std::make_shared<OperatorExpression>( LogicalOuterJoin::make(node->condition->Copy())); break; } case JoinType::LEFT: { join_expr = std::make_shared<OperatorExpression>( LogicalLeftJoin::make(node->condition->Copy())); break; } case JoinType::RIGHT: { join_expr = std::make_shared<OperatorExpression>( LogicalRightJoin::make(node->condition->Copy())); break; } case JoinType::SEMI: { join_expr = std::make_shared<OperatorExpression>( LogicalSemiJoin::make(node->condition->Copy())); break; } default: throw Exception("Join type invalid"); } join_expr->PushChild(left_expr); join_expr->PushChild(right_expr); output_expr_ = join_expr; } void QueryToOperatorTransformer::Visit(parser::TableRef *node) { if (node->select != nullptr) { // Store previous context // Construct query derived table predicates // i.e. the mapping from column name to the underlying expression in the // sub-query. This is needed to generate input/output information for // subqueries auto table_alias = StringUtil::Lower(node->GetTableAlias()); auto alias_to_expr_map = util::ConstructSelectElementMap(node->select->select_list); node->select->Accept(this); auto alias = StringUtil::Lower(node->GetTableAlias()); auto child_expr = output_expr_; output_expr_ = std::make_shared<OperatorExpression>(LogicalQueryDerivedGet::make( GetAndIncreaseGetId(), alias, alias_to_expr_map)); output_expr_->PushChild(child_expr); } // Explicit Join else if (node->join != nullptr) { node->join->Accept(this); } // Multiple tables (Implicit Join) else if (node->list.size() > 1) { // Create a join operator between the first two tables node->list.at(0)->Accept(this); auto prev_expr = output_expr_; // Build a left deep join tree for (size_t i = 1; i < node->list.size(); i++) { node->list.at(i)->Accept(this); auto join_expr = std::make_shared<OperatorExpression>(LogicalInnerJoin::make()); join_expr->PushChild(prev_expr); join_expr->PushChild(output_expr_); PL_ASSERT(join_expr->Children().size() == 2); prev_expr = join_expr; } output_expr_ = prev_expr; } // Single table else { if (node->list.size() == 1) node = node->list.at(0).get(); std::shared_ptr<catalog::TableCatalogObject> target_table = catalog::Catalog::GetInstance()->GetTableObject( node->GetDatabaseName(), node->GetTableName(), txn_); std::string table_alias = StringUtil::Lower(std::string(node->GetTableAlias())); output_expr_ = std::make_shared<OperatorExpression>(LogicalGet::make( GetAndIncreaseGetId(), {}, target_table, node->GetTableAlias())); } } void QueryToOperatorTransformer::Visit(parser::GroupByDescription *) {} void QueryToOperatorTransformer::Visit(parser::OrderDescription *) {} void QueryToOperatorTransformer::Visit(parser::LimitDescription *) {} void QueryToOperatorTransformer::Visit(parser::CreateFunctionStatement *) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::CreateStatement *op) {} void QueryToOperatorTransformer::Visit(parser::InsertStatement *op) { std::shared_ptr<catalog::TableCatalogObject> target_table = catalog::Catalog::GetInstance() ->GetDatabaseObject(op->GetDatabaseName(), txn_) ->GetTableObject(op->GetTableName()); if (op->type == InsertType::SELECT) { auto insert_expr = std::make_shared<OperatorExpression>( LogicalInsertSelect::make(target_table)); op->select->Accept(this); insert_expr->PushChild(output_expr_); output_expr_ = insert_expr; } else { auto insert_expr = std::make_shared<OperatorExpression>( LogicalInsert::make(target_table, &op->columns, &op->insert_values)); output_expr_ = insert_expr; } } void QueryToOperatorTransformer::Visit(parser::DeleteStatement *op) { auto target_table = catalog::Catalog::GetInstance() ->GetDatabaseObject(op->GetDatabaseName(), txn_) ->GetTableObject(op->GetTableName()); std::shared_ptr<OperatorExpression> table_scan; if (op->expr != nullptr) { std::vector<AnnotatedExpression> predicates; util::ExtractPredicates(op->expr.get(), predicates); table_scan = std::make_shared<OperatorExpression>(LogicalGet::make( GetAndIncreaseGetId(), predicates, target_table, op->GetTableName())); } else table_scan = std::make_shared<OperatorExpression>(LogicalGet::make( GetAndIncreaseGetId(), {}, target_table, op->GetTableName())); auto delete_expr = std::make_shared<OperatorExpression>(LogicalDelete::make(target_table)); delete_expr->PushChild(table_scan); output_expr_ = delete_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::DropStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::PrepareStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::ExecuteStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::TransactionStatement *op) {} void QueryToOperatorTransformer::Visit(parser::UpdateStatement *op) { auto target_table = catalog::Catalog::GetInstance() ->GetDatabaseObject(op->table->GetDatabaseName(), txn_) ->GetTableObject(op->table->GetTableName()); std::shared_ptr<OperatorExpression> table_scan; auto update_expr = std::make_shared<OperatorExpression>( LogicalUpdate::make(target_table, &op->updates)); if (op->where != nullptr) { std::vector<AnnotatedExpression> predicates; util::ExtractPredicates(op->where.get(), predicates); table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(GetAndIncreaseGetId(), predicates, target_table, op->table->GetTableName(), true)); } else table_scan = std::make_shared<OperatorExpression>( LogicalGet::make(GetAndIncreaseGetId(), {}, target_table, op->table->GetTableName(), true)); update_expr->PushChild(table_scan); output_expr_ = update_expr; } void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::CopyStatement *op) {} void QueryToOperatorTransformer::Visit( UNUSED_ATTRIBUTE parser::AnalyzeStatement *op) {} void QueryToOperatorTransformer::Visit(expression::ComparisonExpression *expr) { auto expr_type = expr->GetExpressionType(); if (expr->GetExpressionType() == ExpressionType::COMPARE_IN) { std::vector<expression::AbstractExpression *> select_list; if (GenerateSubquerytree(expr->GetModifiableChild(1), select_list) == true) { if (select_list.size() != 1) { throw Exception("Array in predicates not supported"); } // Set the right child as the output of the subquery expr->SetChild(1, select_list.at(0)->Copy()); expr->SetExpressionType(ExpressionType::COMPARE_EQUAL); } } else if (expr_type == ExpressionType::COMPARE_EQUAL || expr_type == ExpressionType::COMPARE_GREATERTHAN || expr_type == ExpressionType::COMPARE_GREATERTHANOREQUALTO || expr_type == ExpressionType::COMPARE_LESSTHAN || expr_type == ExpressionType::COMPARE_LESSTHANOREQUALTO) { std::vector<expression::AbstractExpression *> select_list; if (GenerateSubquerytree(expr->GetModifiableChild(0), select_list, true) == true) { if (select_list.size() != 1) { throw Exception("Array in predicates not supported"); } // Set the left child as the output of the subquery expr->SetChild(0, select_list.at(0)->Copy()); } select_list.clear(); if (GenerateSubquerytree(expr->GetModifiableChild(1), select_list, true) == true) { if (select_list.size() != 1) { throw Exception("Array in predicates not supported"); } // Set the right child as the output of the subquery expr->SetChild(1, select_list.at(0)->Copy()); } } expr->AcceptChildren(this); } void QueryToOperatorTransformer::Visit(expression::OperatorExpression *expr) { if (expr->GetExpressionType() == ExpressionType::OPERATOR_EXISTS) { std::vector<expression::AbstractExpression *> select_list; if (GenerateSubquerytree(expr->GetModifiableChild(0), select_list) == true) { PL_ASSERT(!select_list.empty()); // Set the right child as the output of the subquery expr->SetExpressionType(ExpressionType::OPERATOR_IS_NOT_NULL); expr->SetChild(0, select_list.at(0)->Copy()); } } expr->AcceptChildren(this); } bool QueryToOperatorTransformer::RequireAggregation( const parser::SelectStatement *op) { if (op->group_by != nullptr) { return true; } // Check plain aggregation bool has_aggregation = false; bool has_other_exprs = false; for (auto &expr : op->getSelectList()) { std::vector<expression::AggregateExpression *> aggr_exprs; expression::ExpressionUtil::GetAggregateExprs(aggr_exprs, expr.get()); if (!aggr_exprs.empty()) { has_aggregation = true; } else { has_other_exprs = true; } } // TODO: Should be handled in the binder // Syntax error when there are mixture of aggregation and other exprs // when group by is absent if (has_aggregation && has_other_exprs) { throw SyntaxException( "Non aggregation expression must appear in the GROUP BY " "clause or be used in an aggregate function"); } return has_aggregation; } void QueryToOperatorTransformer::CollectPredicates( expression::AbstractExpression *expr) { expr->Accept(this); util::ExtractPredicates(expr, predicates_); } bool QueryToOperatorTransformer::GenerateSubquerytree( expression::AbstractExpression *expr, std::vector<expression::AbstractExpression *> &select_list, bool single_join) { if (expr->GetExpressionType() != ExpressionType::ROW_SUBQUERY) { return false; } auto subquery_expr = dynamic_cast<expression::SubqueryExpression *>(expr); auto sub_select = subquery_expr->GetSubSelect(); for (auto &ele : sub_select->select_list) { select_list.push_back(ele.get()); } // Construct join std::shared_ptr<OperatorExpression> op_expr; if (single_join) { op_expr = std::make_shared<OperatorExpression>(LogicalSingleJoin::make()); } else { op_expr = std::make_shared<OperatorExpression>(LogicalMarkJoin::make()); } // Push previous output op_expr->PushChild(output_expr_); sub_select->Accept(this); // Push subquery output op_expr->PushChild(output_expr_); output_expr_ = op_expr; return true; } } // namespace optimizer } // namespace peloton <|endoftext|>
<commit_before>/* * validator.cpp * cpds * * Copyright (c) 2016 Hannes Friederich. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "cpds/validator.hpp" #include "cpds/node.hpp" #include "cpds/exception.hpp" #include <iostream> namespace cpds { // enforce local linkage namespace { // accepts nodes that match the type void vType(const Node& node, const Validator& validator) { if (node.type() != validator.type()) { throw TypeException(node); } } // accepts all maps bool vAllMaps(const Node& /*node*/) { return true; } // integer range validator void vIntRange(const Node& node, const Validator& validator) { IntRange range = validator.intRange(); Int val = node.intValue(); if (val < range.first || val > range.second) { throw IntRangeException(range.first, range.second, val, node); } } // floating point range validator void vFloatRange(const Node& node, const Validator& validator) { FloatRange range = validator.floatRange(); Float val = node.floatValue(); if (val < range.first || val > range.second) { throw FloatRangeException(range.first, range.second, val, node); } } // sequence validator void vSequence(const Node& node, const Validator& validator) { const ValidatorVector& validators = validator.seqValidators(); if (validators.empty()) { return; // nothing to validate against } for (const Node& child : node.sequence()) { // any of the validators must succeed bool success = false; for (const Validator& vld : validators) { try { vld.validate(child); success = true; break; } catch (...) { } } if (!success) { throw ValidationException("sequence child failed to validate", child); } } } // map validator void vMap(const Node& node, const Validator& validator) { const MapGroupVector& groups = validator.mapGroups(); if (groups.empty()) { return; // nothing to validate against } bool enabled = false; // at least one group must be enabled for (const MapGroup& group : groups) { if (group.isEnabled(node)) { group.validate(node); enabled = true; } } if (enabled == false) { throw ValidationException("map does not match any validation group", node); } } } // unnamed namespace // // Validator implementation // Validator::Validator(NodeType type, ValidationFcn validation_fcn) : type_(type) , fcn_(validation_fcn) { aux_data_.int_range_ = nullptr; } Validator::Validator(IntRange int_range) : type_(NodeType::Integer) , fcn_(vIntRange) { aux_data_.int_range_ = new IntRange(int_range); } Validator::Validator(FloatRange float_range) : type_(NodeType::FloatingPoint) , fcn_(vFloatRange) { aux_data_.float_range_ = new FloatRange(float_range); } Validator::Validator(ValidatorVector seq_validators) : type_(NodeType::Sequence) , fcn_(vSequence) { aux_data_.seq_validators_ = new ValidatorVector(std::move(seq_validators)); } Validator::Validator(MapGroupVector map_groups) : type_(NodeType::Map) , fcn_(vMap) { aux_data_.map_groups_ = new MapGroupVector(std::move(map_groups)); } Validator::Validator(const Validator& other) : type_(other.type_) , fcn_(other.fcn_) , aux_data_() { switch (type_) { case NodeType::Integer: if (other.aux_data_.int_range_ != nullptr) { aux_data_.int_range_ = new IntRange(*other.aux_data_.int_range_); } break; case NodeType::FloatingPoint: if (other.aux_data_.float_range_ != nullptr) { aux_data_.float_range_ = new FloatRange(*other.aux_data_.float_range_); } break; case NodeType::Sequence: aux_data_.seq_validators_ = new ValidatorVector(*other.aux_data_.seq_validators_); break; case NodeType::Map: aux_data_.map_groups_ = new MapGroupVector(*other.aux_data_.map_groups_); break; default: break; } } Validator::Validator(Validator&& other) noexcept : type_(other.type_) , fcn_(other.fcn_) , aux_data_(other.aux_data_) { other.type_ = NodeType::Null; other.aux_data_.int_range_ = nullptr; } Validator& Validator::operator=(Validator other) noexcept { swap(other); return *this; } Validator::~Validator() { switch (type_) { case NodeType::Integer: delete aux_data_.int_range_; break; case NodeType::FloatingPoint: delete aux_data_.float_range_; break; case NodeType::Sequence: delete aux_data_.seq_validators_; break; case NodeType::Map: delete aux_data_.map_groups_; break; default: break; } } void Validator::validate(const Node& node) const { fcn_(node, *this); } const IntRange& Validator::intRange() const { checkType(NodeType::Integer); if (aux_data_.int_range_ == nullptr) { throw TypeException(String("API error: missing integer range")); } return *aux_data_.int_range_; } const FloatRange& Validator::floatRange() const { checkType(NodeType::FloatingPoint); if (aux_data_.float_range_ == nullptr) { throw TypeException(String("API error: missing float range")); } return *aux_data_.float_range_; } const ValidatorVector& Validator::seqValidators() const { checkType(NodeType::Sequence); return *aux_data_.seq_validators_; } const MapGroupVector& Validator::mapGroups() const { checkType(NodeType::Map); return *aux_data_.map_groups_; } void Validator::swap(Validator& other) noexcept { std::swap(type_, other.type_); std::swap(fcn_, other.fcn_); std::swap(aux_data_, other.aux_data_); } void Validator::checkType(NodeType type) const { if (type_ != type) { throw TypeException(String("API error: validator type mismatch")); } } // // NullType implementation // NullType::NullType() : Validator(NodeType::Null, vType) { } // // BooleanType implementation // BooleanType::BooleanType() : Validator(NodeType::Boolean, vType) { } BooleanType::BooleanType(ValidationFcn validation_fcn) : Validator(NodeType::Boolean, validation_fcn) { } // // IntegerType implementation // IntegerType::IntegerType() : Validator(NodeType::Integer, vType) { } IntegerType::IntegerType(Int min, Int max) : Validator(std::make_pair(min, max)) { } IntegerType::IntegerType(ValidationFcn validation_fcn) : Validator(NodeType::Integer, validation_fcn) { } // // FloatingPointType implementation // FloatingPointType::FloatingPointType() : Validator(NodeType::FloatingPoint, vType) { } FloatingPointType::FloatingPointType(Float min, Float max) : Validator(std::make_pair(min, max)) { } FloatingPointType::FloatingPointType(ValidationFcn validation_fcn) : Validator(NodeType::FloatingPoint, validation_fcn) { } // // StringType implementation // StringType::StringType() : Validator(NodeType::String, vType) { } StringType::StringType(ValidationFcn validation_fcn) : Validator(NodeType::String, validation_fcn) { } // // SequenceType implementation // SequenceType::SequenceType() : Validator(ValidatorVector()) { } SequenceType::SequenceType(Validator child_validator) : Validator(ValidatorVector({child_validator})) { } SequenceType::SequenceType(ValidatorVector child_types) : Validator(std::move(child_types)) { } SequenceType::SequenceType(ValidationFcn validation_fcn) : Validator(NodeType::Sequence, validation_fcn) { } // // MapType implementation // MapType::MapType() : Validator(MapGroupVector()) { } MapType::MapType(MapGroup group) : MapType(MapGroupVector{ group }) { } MapType::MapType(MapGroupVector groups) : Validator(std::move(groups)) { } // // MapEntryType implementation // MapEntryType::MapEntryType(String key, Validator validator, Requiredness requiredness) : key_(std::move(key)) , validator_(std::move(validator)) , requiredness_(requiredness) { } void MapEntryType::validate(const Node& node) const { Map::const_iterator iter = node.find(key_); if (iter == node.end()) { if (requiredness_ == Optional) { return; } throw ValidationException("required key not present", node); } validator_.validate(iter->second); } // // MapGroup implementation // MapGroup::MapGroup(MapEntryTypeVector entries, Closedness closedness) : MapGroup(std::move(entries), closedness, vAllMaps) { } MapGroup::MapGroup(MapEntryTypeVector entries, Closedness closedness, GroupEnableFcn enable_fcn) : entries_(std::move(entries)) , closedness_(closedness) , enable_fcn_(enable_fcn) { } bool MapGroup::isEnabled(const Node& node) const { return enable_fcn_(node); } void MapGroup::validate(const Node& node) const { for (const MapEntryType& entry : entries_) { entry.validate(node); } // ensure there are no other entries if (closedness_ == AllowMoreEntries) { return; } const Map& map = node.map(); for (const MapEntry& entry : map) { const String& key = entry.first; bool found = false; for (const MapEntryType& type : entries_) { if (type.key() == key) { found = true; break; } } // entry type loop if (!found) { throw ValidationException("extra key present in map", node); } } // map loop } } // namespace cpds <commit_msg>cleanup<commit_after>/* * validator.cpp * cpds * * Copyright (c) 2016 Hannes Friederich. * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "cpds/validator.hpp" #include "cpds/node.hpp" #include "cpds/exception.hpp" #include <iostream> namespace cpds { // enforce local linkage namespace { // accepts nodes that match the type void vType(const Node& node, const Validator& validator) { if (node.type() != validator.type()) { throw TypeException(node); } } // accepts all maps bool vAllMaps(const Node& /*node*/) { return true; } // integer range validator void vIntRange(const Node& node, const Validator& validator) { IntRange range = validator.intRange(); Int val = node.intValue(); if (val < range.first || val > range.second) { throw IntRangeException(range.first, range.second, val, node); } } // floating point range validator void vFloatRange(const Node& node, const Validator& validator) { FloatRange range = validator.floatRange(); Float val = node.floatValue(); if (val < range.first || val > range.second) { throw FloatRangeException(range.first, range.second, val, node); } } // sequence validator void vSequence(const Node& node, const Validator& validator) { const ValidatorVector& validators = validator.seqValidators(); if (validators.empty()) { return; // nothing to validate against } for (const Node& child : node.sequence()) { // any of the validators must succeed bool success = false; for (const Validator& vld : validators) { try { vld.validate(child); success = true; break; } catch (...) { } } if (!success) { throw ValidationException("sequence child failed to validate", child); } } } // map validator void vMap(const Node& node, const Validator& validator) { const MapGroupVector& groups = validator.mapGroups(); if (groups.empty()) { return; // nothing to validate against } bool enabled = false; // at least one group must be enabled for (const MapGroup& group : groups) { if (group.isEnabled(node)) { group.validate(node); enabled = true; } } if (enabled == false) { throw ValidationException("map does not match any validation group", node); } } } // unnamed namespace // // Validator implementation // Validator::Validator(NodeType type, ValidationFcn validation_fcn) : type_(type) , fcn_(validation_fcn) { aux_data_.int_range_ = nullptr; } Validator::Validator(IntRange int_range) : type_(NodeType::Integer) , fcn_(vIntRange) { aux_data_.int_range_ = new IntRange(int_range); } Validator::Validator(FloatRange float_range) : type_(NodeType::FloatingPoint) , fcn_(vFloatRange) { aux_data_.float_range_ = new FloatRange(float_range); } Validator::Validator(ValidatorVector seq_validators) : type_(NodeType::Sequence) , fcn_(vSequence) { aux_data_.seq_validators_ = new ValidatorVector(std::move(seq_validators)); } Validator::Validator(MapGroupVector map_groups) : type_(NodeType::Map) , fcn_(vMap) { aux_data_.map_groups_ = new MapGroupVector(std::move(map_groups)); } Validator::Validator(const Validator& other) : type_(other.type_) , fcn_(other.fcn_) , aux_data_() { switch (type_) { case NodeType::Integer: if (other.aux_data_.int_range_ != nullptr) { aux_data_.int_range_ = new IntRange(*other.aux_data_.int_range_); } break; case NodeType::FloatingPoint: if (other.aux_data_.float_range_ != nullptr) { aux_data_.float_range_ = new FloatRange(*other.aux_data_.float_range_); } break; case NodeType::Sequence: aux_data_.seq_validators_ = new ValidatorVector(*other.aux_data_.seq_validators_); break; case NodeType::Map: aux_data_.map_groups_ = new MapGroupVector(*other.aux_data_.map_groups_); break; default: break; } } Validator::Validator(Validator&& other) noexcept : type_(other.type_) , fcn_(other.fcn_) , aux_data_(other.aux_data_) { other.type_ = NodeType::Null; other.aux_data_.int_range_ = nullptr; } Validator& Validator::operator=(Validator other) noexcept { swap(other); return *this; } Validator::~Validator() { switch (type_) { case NodeType::Integer: delete aux_data_.int_range_; break; case NodeType::FloatingPoint: delete aux_data_.float_range_; break; case NodeType::Sequence: delete aux_data_.seq_validators_; break; case NodeType::Map: delete aux_data_.map_groups_; break; default: break; } } void Validator::validate(const Node& node) const { fcn_(node, *this); } const IntRange& Validator::intRange() const { checkType(NodeType::Integer); if (aux_data_.int_range_ == nullptr) { throw TypeException("API error: missing integer range"); } return *aux_data_.int_range_; } const FloatRange& Validator::floatRange() const { checkType(NodeType::FloatingPoint); if (aux_data_.float_range_ == nullptr) { throw TypeException("API error: missing float range"); } return *aux_data_.float_range_; } const ValidatorVector& Validator::seqValidators() const { checkType(NodeType::Sequence); return *aux_data_.seq_validators_; } const MapGroupVector& Validator::mapGroups() const { checkType(NodeType::Map); return *aux_data_.map_groups_; } void Validator::swap(Validator& other) noexcept { std::swap(type_, other.type_); std::swap(fcn_, other.fcn_); std::swap(aux_data_, other.aux_data_); } void Validator::checkType(NodeType type) const { if (type_ != type) { throw TypeException("API error: validator type mismatch"); } } // // NullType implementation // NullType::NullType() : Validator(NodeType::Null, vType) { } // // BooleanType implementation // BooleanType::BooleanType() : Validator(NodeType::Boolean, vType) { } BooleanType::BooleanType(ValidationFcn validation_fcn) : Validator(NodeType::Boolean, validation_fcn) { } // // IntegerType implementation // IntegerType::IntegerType() : Validator(NodeType::Integer, vType) { } IntegerType::IntegerType(Int min, Int max) : Validator(std::make_pair(min, max)) { } IntegerType::IntegerType(ValidationFcn validation_fcn) : Validator(NodeType::Integer, validation_fcn) { } // // FloatingPointType implementation // FloatingPointType::FloatingPointType() : Validator(NodeType::FloatingPoint, vType) { } FloatingPointType::FloatingPointType(Float min, Float max) : Validator(std::make_pair(min, max)) { } FloatingPointType::FloatingPointType(ValidationFcn validation_fcn) : Validator(NodeType::FloatingPoint, validation_fcn) { } // // StringType implementation // StringType::StringType() : Validator(NodeType::String, vType) { } StringType::StringType(ValidationFcn validation_fcn) : Validator(NodeType::String, validation_fcn) { } // // SequenceType implementation // SequenceType::SequenceType() : Validator(ValidatorVector()) { } SequenceType::SequenceType(Validator child_validator) : Validator(ValidatorVector({child_validator})) { } SequenceType::SequenceType(ValidatorVector child_types) : Validator(std::move(child_types)) { } SequenceType::SequenceType(ValidationFcn validation_fcn) : Validator(NodeType::Sequence, validation_fcn) { } // // MapType implementation // MapType::MapType() : Validator(MapGroupVector()) { } MapType::MapType(MapGroup group) : MapType(MapGroupVector{ group }) { } MapType::MapType(MapGroupVector groups) : Validator(std::move(groups)) { } // // MapEntryType implementation // MapEntryType::MapEntryType(String key, Validator validator, Requiredness requiredness) : key_(std::move(key)) , validator_(std::move(validator)) , requiredness_(requiredness) { } void MapEntryType::validate(const Node& node) const { Map::const_iterator iter = node.find(key_); if (iter == node.end()) { if (requiredness_ == Optional) { return; } throw ValidationException("required key not present", node); } validator_.validate(iter->second); } // // MapGroup implementation // MapGroup::MapGroup(MapEntryTypeVector entries, Closedness closedness) : MapGroup(std::move(entries), closedness, vAllMaps) { } MapGroup::MapGroup(MapEntryTypeVector entries, Closedness closedness, GroupEnableFcn enable_fcn) : entries_(std::move(entries)) , closedness_(closedness) , enable_fcn_(enable_fcn) { } bool MapGroup::isEnabled(const Node& node) const { return enable_fcn_(node); } void MapGroup::validate(const Node& node) const { for (const MapEntryType& entry : entries_) { entry.validate(node); } // ensure there are no other entries if (closedness_ == AllowMoreEntries) { return; } const Map& map = node.map(); for (const MapEntry& entry : map) { const String& key = entry.first; bool found = false; for (const MapEntryType& type : entries_) { if (type.key() == key) { found = true; break; } } // entry type loop if (!found) { throw ValidationException("extra key present in map", node); } } // map loop } } // namespace cpds <|endoftext|>
<commit_before> #include <WiFiClientSecure.h> #include <base64.h> #include <Arduino.h> #define MODULE_NAME "email_send" #include "email_send.h" #include "logger.h" #define FSTR bool read_response(WiFiClientSecure* client, char* buffer, int buffer_len, const char* endmarker, const char* exp_response, const char* log_string ) { int buffer_offset = 0; bool line_change_found = false; int endmarker_len = strlen(endmarker); int delay_loop_max = EMAIL_SEND_TIMEOUT_MS/10; int delay_loop = 0; // make sure we start with 0 sized string memset( buffer, 0x00, buffer_len ); while ( ( line_change_found == false ) && (delay_loop < delay_loop_max )) { int avail = client->available(); if (avail == 0) { delay(10); delay_loop += 1; continue; } int to_read = min( avail, (buffer_len - buffer_offset)); int red = client->read( (uint8_t*)(buffer + buffer_offset), to_read ); buffer[ buffer_offset + red ] = 0; int search_start = max( 0, buffer_offset - endmarker_len ); if ( strstr( buffer + search_start , endmarker ) != NULL ) { line_change_found = true; } buffer_offset += red; } // Uncomment this if you want to see the full response always // Serial.println(buffer); if ( buffer_offset < 3 || buffer_offset >= EMAIL_SEND_MAX_SIZE ) { LOG_ERROR("Send failed (len) at '%s'", log_string ); LOG_ERROR("Got: '%s'", buffer ); return false; } if ( strncmp( buffer, exp_response, strlen(exp_response) ) != 0 ) { LOG_ERROR("Send failed (content) at '%s'", log_string ); LOG_ERROR("Got: '%s'", buffer ); return false; } return true; } bool email_send_raw( const Config_email* settings, const char* receiver, const char* subject, const char* message, char* buffer, WiFiClientSecure* client ) { LOG_INFO( "Sending email via '%s:%d'", settings->server_host, settings->server_port ); if (!client->connect( settings->server_host, settings->server_port)) { LOG_ERROR("Send failed on connect to server"); return false; } if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("220"), FSTR("Handshake") ) == false ) return false; sprintf( buffer, FSTR("EHLO %s"), client->localIP().toString().c_str() ); client->println(buffer); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n\n", FSTR("250"), FSTR("Ehlo") ) == false ) return false; sprintf( buffer, FSTR("AUTH LOGIN") ); client->println(buffer); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("334"), FSTR("login") ) == false ) return false; base64 encoder; client->println( encoder.encode( settings->login ) ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("334"), FSTR("login_user") ) == false ) return false; client->println( encoder.encode( settings->password ) ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("235"), FSTR("login_pass") ) == false ) return false; LOG_INFO("Login ok"); sprintf( buffer, FSTR("MAIL FROM: <%s>"), settings->login ); client->println( buffer ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("250"), FSTR("mail_from") ) == false ) return false; sprintf( buffer, FSTR("RCPT TO: <%s>"), receiver ); client->println( buffer ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("250"), FSTR("mail_to") ) == false ) return false; client->println( FSTR("DATA") ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("354"), FSTR("data") ) == false ) return false; sprintf( buffer, FSTR("From: <%s>\nTo: <%s>\nSubject: %s\r\n\n%s\r\n.\r\nQUIT"), settings->login, receiver, subject, message ); client->println( buffer ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("250"), FSTR("quit") ) == false ) return false; return true; } bool email_send( const Config_email* settings, const char* receiver, const char* subject, const char* message ) { char* buffer = (char*)malloc( EMAIL_SEND_MAX_SIZE ); WiFiClientSecure* client = new WiFiClientSecure(); bool ret = false; if ( client == NULL || buffer == NULL ) { LOG_ERROR("Out of memory!"); } else { client->setTimeout(EMAIL_SEND_TIMEOUT_MS); ret = email_send_raw( settings, receiver, subject, message, buffer, client ); client->stop(); } delete( client ); free(buffer); return ret; }<commit_msg>FIX: Do not give errors on email send, since that will trigger email send<commit_after> #include <WiFiClientSecure.h> #include <base64.h> #include <Arduino.h> #define MODULE_NAME "email_send" #include "email_send.h" #include "logger.h" #define FSTR bool read_response(WiFiClientSecure* client, char* buffer, int buffer_len, const char* endmarker, const char* exp_response, const char* log_string ) { int buffer_offset = 0; bool line_change_found = false; int endmarker_len = strlen(endmarker); int delay_loop_max = EMAIL_SEND_TIMEOUT_MS/10; int delay_loop = 0; // make sure we start with 0 sized string memset( buffer, 0x00, buffer_len ); while ( ( line_change_found == false ) && (delay_loop < delay_loop_max )) { int avail = client->available(); if (avail == 0) { delay(10); delay_loop += 1; continue; } int to_read = min( avail, (buffer_len - buffer_offset)); int red = client->read( (uint8_t*)(buffer + buffer_offset), to_read ); buffer[ buffer_offset + red ] = 0; int search_start = max( 0, buffer_offset - endmarker_len ); if ( strstr( buffer + search_start , endmarker ) != NULL ) { line_change_found = true; } buffer_offset += red; } // Uncomment this if you want to see the full response always // Serial.println(buffer); if ( buffer_offset < 3 || buffer_offset >= EMAIL_SEND_MAX_SIZE ) { LOG_WARN("Send failed (len) at '%s'", log_string ); LOG_WARN("Got: '%s'", buffer ); return false; } if ( strncmp( buffer, exp_response, strlen(exp_response) ) != 0 ) { LOG_WARN("Send failed (content) at '%s'", log_string ); LOG_WARN("Got: '%s'", buffer ); return false; } return true; } bool email_send_raw( const Config_email* settings, const char* receiver, const char* subject, const char* message, char* buffer, WiFiClientSecure* client ) { LOG_INFO( "Sending email via '%s:%d'", settings->server_host, settings->server_port ); if (!client->connect( settings->server_host, settings->server_port)) { LOG_WARN("Send failed on connect to server"); return false; } if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("220"), FSTR("Handshake") ) == false ) return false; sprintf( buffer, FSTR("EHLO %s"), client->localIP().toString().c_str() ); client->println(buffer); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n\n", FSTR("250"), FSTR("Ehlo") ) == false ) return false; sprintf( buffer, FSTR("AUTH LOGIN") ); client->println(buffer); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("334"), FSTR("login") ) == false ) return false; base64 encoder; client->println( encoder.encode( settings->login ) ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("334"), FSTR("login_user") ) == false ) return false; client->println( encoder.encode( settings->password ) ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("235"), FSTR("login_pass") ) == false ) return false; LOG_INFO("Login ok"); sprintf( buffer, FSTR("MAIL FROM: <%s>"), settings->login ); client->println( buffer ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("250"), FSTR("mail_from") ) == false ) return false; sprintf( buffer, FSTR("RCPT TO: <%s>"), receiver ); client->println( buffer ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("250"), FSTR("mail_to") ) == false ) return false; client->println( FSTR("DATA") ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("354"), FSTR("data") ) == false ) return false; sprintf( buffer, FSTR("From: <%s>\nTo: <%s>\nSubject: %s\r\n\n%s\r\n.\r\nQUIT"), settings->login, receiver, subject, message ); client->println( buffer ); if( read_response( client, buffer, EMAIL_SEND_MAX_SIZE, "\n", FSTR("250"), FSTR("quit") ) == false ) return false; return true; } bool email_send( const Config_email* settings, const char* receiver, const char* subject, const char* message ) { char* buffer = (char*)malloc( EMAIL_SEND_MAX_SIZE ); WiFiClientSecure* client = new WiFiClientSecure(); bool ret = false; if ( client == NULL || buffer == NULL ) { LOG_WARN("Out of memory!"); } else { client->setTimeout(EMAIL_SEND_TIMEOUT_MS); ret = email_send_raw( settings, receiver, subject, message, buffer, client ); client->stop(); } delete( client ); free(buffer); return ret; }<|endoftext|>
<commit_before>// Copyright (C) 2005-2009 by Jukka Korpela // Copyright (C) 2009-2013 by David Hoerl // Copyright (C) 2013 by Martin Moene // // 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 "eng_format.hpp" #include <iomanip> #include <sstream> #include <float.h> #include <math.h> #include <stdlib.h> /* * Note: using fabs() and other math functions in global namespace for * best compiler coverage. */ /* * Note: micro, , may not work everywhere, so you can define a glyph yourself: */ #ifndef ENG_FORMAT_MICRO_GLYPH # define ENG_FORMAT_MICRO_GLYPH "" #endif /* * Note: if not using signed at the computation of prefix_end below, * VC2010 -Wall issues a warning about unsigned and addition overflow. * Hence the cast to signed int here. */ #define ENG_FORMAT_DIMENSION_OF(a) ( static_cast<int>( sizeof(a) / sizeof(0[a]) ) ) eng_prefixed_t eng_prefixed; eng_exponential_t eng_exponential; namespace { char const * const prefixes[/*exp*/][2][9] = { { { "", "m", ENG_FORMAT_MICRO_GLYPH , "n", "p", "f", "a", "z", "y", }, { "", "k", "M", "G", "T", "P", "E", "Z", "Y", }, }, { { "e0", "e-3", "e-6", "e-9", "e-12", "e-15", "e-18", "e-21", "e-24", }, { "e0", "e3", "e6", "e9", "e12", "e15", "e18", "e21", "e24", }, }, }; const int prefix_count = ENG_FORMAT_DIMENSION_OF( prefixes[false][false] ); int sign( int const value ) { return value == 0 ? +1 : value / abs( value ); } int precision( double const scaled, int const digits ) { // MSVC6 requires -2 * DBL_EPSILON; //g++ 4.8.1: ok with -1 * DBL_EPSILON return digits - log10( fabs( scaled ) ) - 2 * DBL_EPSILON; } std::string prefix_or_exponent( bool const exponential, int const degree ) { return std::string( exponential ? "" : " " ) + prefixes[ exponential ][ sign(degree) > 0 ][ abs( degree ) ]; } std::string exponent( int const degree ) { std::ostringstream os; os << "e" << 3 * degree; return os.str(); } #if defined( _MSC_VER ) template <typename T> long lrint( T const x ) { return static_cast<long>( floor( x + ( x > 0 ) ? 0.5 : -0.5 ) ); } #endif /* * engineering to exponent notation conversion. */ std::string engineering_to_exponent( std::string text ); } // anonymous namespace /** * convert real number to prefixed or exponential notation, optionally followed by a unit. */ std::string to_engineering_string( double const value, int const digits, bool exponential, std::string const unit /*= ""*/ ) { const int degree = static_cast<int>( floor( log10( fabs( value ) ) / 3) ); std::string factor; if ( abs( degree ) < prefix_count ) { factor = prefix_or_exponent( exponential, degree ); } else { exponential = true; factor = exponent( degree ); } std::ostringstream os; const double scaled = value * pow( 1000, -degree ); const std::string space = exponential && unit.length() ? " ":""; os << std::fixed << std::setprecision( precision( scaled, digits ) ) << scaled << factor << space << unit; return os.str(); } /** * convert the output of to_engineering_string() into a double. */ double from_engineering_string( std::string const text ) { return strtod( engineering_to_exponent( text ).c_str(), NULL ); } /** * step a value by the smallest possible increment. */ std::string step_engineering_string( std::string const text, int digits, bool const exponential, bool const positive ) { const double value = from_engineering_string( text ); if ( digits < 3 ) { digits = 3; } // correctly round to desired precision const int expof10 = lrint( floor( log10( value ) ) ); const int power = expof10 + 1 - digits; const double inc = pow( 10.0, power ) * ( positive ? +1 : -1 ); const double ret = value + inc; return to_engineering_string( ret, digits, exponential ); } namespace { /* * "k" => "1e3" */ std::string prefix_to_exponent( std::string const pfx ) { for ( int i = 0; i < 2; ++i ) { for( int k = 0; k < prefix_count; ++k ) { if ( pfx == prefixes[0][i][k] ) { return prefixes[1][i][k] ; } } } return ""; } /* * Convert engineering presentation to presentation with exponent. * * The engineering presentation should not contain a unit, as the first letter * is interpreted as an SI prefix, e.g. "1 T" is 1e12, not 1 (Tesla). * * "1.23 M" => 1.23e+6 * "1.23 kPa" => 1.23e+3 (ok, but not recommended) * "1.23 Pa" => 1.23e+12 (not what's intended!) */ std::string engineering_to_exponent( std::string const text ) { std::string::size_type pos = text.find( ' ' ); if ( std::string::npos == pos ) { return text; } const std::string magnitude = text.substr( 0, pos ); const std::string prefix = text.substr( pos + 1, 1 ); return magnitude + prefix_to_exponent( prefix ); } } // anonymous namespace // end of file <commit_msg>Fix several errors<commit_after>// Copyright (C) 2005-2009 by Jukka Korpela // Copyright (C) 2009-2013 by David Hoerl // Copyright (C) 2013 by Martin Moene // // 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 "eng_format.hpp" #include <iomanip> #include <limits> #include <sstream> #include <float.h> #include <math.h> #include <stdlib.h> /* * Note: using fabs() and other math functions in global namespace for * best compiler coverage. */ /* * Note: micro, , may not work everywhere, so you can define a glyph yourself: */ #ifndef ENG_FORMAT_MICRO_GLYPH # define ENG_FORMAT_MICRO_GLYPH "" #endif /* * Note: if not using signed at the computation of prefix_end below, * VC2010 -Wall issues a warning about unsigned and addition overflow. * Hence the cast to signed int here. */ #define ENG_FORMAT_DIMENSION_OF(a) ( static_cast<int>( sizeof(a) / sizeof(0[a]) ) ) eng_prefixed_t eng_prefixed; eng_exponential_t eng_exponential; namespace { char const * const prefixes[/*exp*/][2][9] = { { { "", "m", ENG_FORMAT_MICRO_GLYPH , "n", "p", "f", "a", "z", "y", }, { "", "k", "M", "G", "T", "P", "E", "Z", "Y", }, }, { { "e0", "e-3", "e-6", "e-9", "e-12", "e-15", "e-18", "e-21", "e-24", }, { "e0", "e3", "e6", "e9", "e12", "e15", "e18", "e21", "e24", }, }, }; const int prefix_count = ENG_FORMAT_DIMENSION_OF( prefixes[false][false] ); #if defined( _MSC_VER ) template <typename T> long lrint( T const x ) { return static_cast<long>( floor( x + ( x > 0 ) ? 0.5 : -0.5 ) ); } #endif int sign( int const value ) { return value == 0 ? +1 : value / abs( value ); } bool is_zero( double const value ) { #if __cpluplus >= 201103L return FP_ZERO == std::fpclassify( value ); #else // deliberately compare literally: return 0.0 == value; #endif } long degree_of( double const value ) { return is_zero( value ) ? 0 : lrint( floor( log10( fabs( value ) ) / 3) ); } int precision( double const scaled, int const digits ) { // MSVC6 requires -2 * DBL_EPSILON; // g++ 4.8.1: ok with -1 * DBL_EPSILON return is_zero( scaled ) ? digits - 1 : digits - log10( fabs( scaled ) ) - DBL_EPSILON; // return digits - log10( fabs( scaled ) ) ; } std::string prefix_or_exponent( bool const exponential, int const degree ) { return std::string( exponential || 0 == degree ? "" : " " ) + prefixes[ exponential ][ sign(degree) > 0 ][ abs( degree ) ]; } std::string exponent( int const degree ) { std::ostringstream os; os << "e" << 3 * degree; return os.str(); } /* * engineering to exponent notation conversion. */ std::string engineering_to_exponent( std::string text ); } // anonymous namespace /** * convert real number to prefixed or exponential notation, optionally followed by a unit. */ std::string to_engineering_string( double const value, int const digits, bool exponential, std::string const unit /*= ""*/ ) { const int degree = degree_of( value ); std::string factor; if ( abs( degree ) < prefix_count ) { factor = prefix_or_exponent( exponential, degree ); } else { exponential = true; factor = exponent( degree ); } std::ostringstream os; const double scaled = value * pow( 1000, -degree ); const std::string space = exponential && unit.length() ? " ":""; os << std::fixed << std::setprecision( precision( scaled, digits ) ) << scaled << factor << space << unit; return os.str(); } /** * convert the output of to_engineering_string() into a double. */ double from_engineering_string( std::string const text ) { return strtod( engineering_to_exponent( text ).c_str(), NULL ); } /** * step a value by the smallest possible increment. */ std::string step_engineering_string( std::string const text, int digits, bool const exponential, bool const positive ) { const double value = from_engineering_string( text ); if ( digits < 3 ) { digits = 3; } // correctly round to desired precision const int expof10 = is_zero(value) ? 0 : lrint( floor( log10( value ) ) ); const int power = expof10 + 1 - digits; const double inc = pow( 10.0, power ) * ( positive ? +1 : -1 ); const double ret = value + inc; return to_engineering_string( ret, digits, exponential ); } namespace { /* * "k" => "1e3" */ std::string prefix_to_exponent( std::string const pfx ) { for ( int i = 0; i < 2; ++i ) { for( int k = 0; k < prefix_count; ++k ) { if ( pfx == prefixes[0][i][k] ) { return prefixes[1][i][k] ; } } } return ""; } /* * Convert engineering presentation to presentation with exponent. * * The engineering presentation should not contain a unit, as the first letter * is interpreted as an SI prefix, e.g. "1 T" is 1e12, not 1 (Tesla). * * "1.23 M" => 1.23e+6 * "1.23 kPa" => 1.23e+3 (ok, but not recommended) * "1.23 Pa" => 1.23e+12 (not what's intended!) */ std::string engineering_to_exponent( std::string const text ) { std::string::size_type pos = text.find( ' ' ); if ( std::string::npos == pos ) { return text; } const std::string magnitude = text.substr( 0, pos ); const std::string prefix = text.substr( pos + 1, 1 ); return magnitude + prefix_to_exponent( prefix ); } } // anonymous namespace // end of file <|endoftext|>
<commit_before>// // msgf_amp_pipe.cpp // ToneGenerator // // Created by 長谷部 雅彦 on 2013/12/08. // Copyright (c) 2013年 長谷部 雅彦. All rights reserved. // #include "msgf_amp_pipe.h" #include "msgf_audio_buffer.h" #include "msgf_instrument.h" #include "msgf_part.h" using namespace msgf; //--------------------------------------------------------- // Initialize //--------------------------------------------------------- AmpPipe::AmpPipe( Note& parent ): _parentNote(parent), _targetVol(0), _realVol(0) { _cbInst = new AegPCallBack( this ); _eg = new Eg2segment( *_cbInst, parent, false ); _am = new Lfo(); } //--------------------------------------------------------- AmpPipe::~AmpPipe( void ) { delete _cbInst; delete _eg; delete _am; } //--------------------------------------------------------- void AmpPipe::init( void ) { clearDacCounter(); // LFO Settings only for Amplitude _am->setWave(LFO_TRI); _am->setDirection(LFO_LOWER); _am->setCoef(); _am->start(); _amd = static_cast<double>(getVoicePrm(VP_LFO_AMD))/AMP_PRM_MAX; _startNcEgDac = -1; } //--------------------------------------------------------- void AmpPipe::changeNote( bool chgNote ) { _startNcEgDac = _dacCounter; _changeNote = chgNote; } //--------------------------------------------------------- // Calculate Note Change EG //--------------------------------------------------------- double AmpPipe::calcNcEg( double amp ) { if ( _startNcEgDac == -1 ) return amp; long counterDiff = _dacCounter - _startNcEgDac; double minLvl = static_cast<double>(getVoicePrm(VP_MINLVL))/10000; int upDcnt, minlvlDcnt, downDcnt; if ( _changeNote == true ){ upDcnt = getVoicePrm(VP_UP_DCNT); minlvlDcnt = getVoicePrm(VP_MINLVL_DCNT); downDcnt = getVoicePrm(VP_DOWN_DCNT); } else { // if Same Note upDcnt = 500; minlvlDcnt = 0; downDcnt = 1500; } if ( counterDiff > upDcnt + minlvlDcnt + downDcnt ){ _startNcEgDac = -1; return amp; } else if ( counterDiff > minlvlDcnt + downDcnt ){ // Level Up double tpdf = (counterDiff - minlvlDcnt - downDcnt)*((1-minLvl)/upDcnt); if ( tpdf > 1-minLvl ) return amp; else return amp*(minLvl + tpdf); } else if ( counterDiff > downDcnt ){ return amp*minLvl; } else if ( counterDiff > 0 ){ // Level Down return amp*(1 - counterDiff*((1-minLvl)/downDcnt)); } return amp; } //--------------------------------------------------------- // Calculate MIDI Volume //--------------------------------------------------------- double AmpPipe::calcMidiVolume( double amp ) { Part* pt = _parentNote.getInstrument()->getPart(); Uint8 midiVal = pt->getCc7(); amp = (amp*midiVal)/127; midiVal = pt->getCc11(); amp = (amp*midiVal)/127; return amp; } //--------------------------------------------------------- // Interporate Volume //--------------------------------------------------------- const double DEEMED_SAME_VOLUME = 1.0001; const double VOLUME_ITP_RATE = 0.01; // /1Dac //--------------------------------------------------------- void AmpPipe::interporateVolume( void ) { if (( _targetVol*DEEMED_SAME_VOLUME >= _realVol ) && ( _targetVol/DEEMED_SAME_VOLUME <= _realVol )){ _realVol = _targetVol; } else { if ( _targetVol > _realVol ){ _realVol = _realVol + (_targetVol-_realVol)*VOLUME_ITP_RATE; } else { _realVol = _realVol - (_realVol-_targetVol)*VOLUME_ITP_RATE; } } } //--------------------------------------------------------- // Process Function //--------------------------------------------------------- void AmpPipe::process( TgAudioBuffer& buf ) { // check Event _eg->periodicOnceEveryProcess(); // get LFO pattern double* lfoBuf = new double[buf.bufferSize()]; _am->process( buf.bufferSize(), lfoBuf ); double processVol = getVoicePrm(VP_VOLUME); processVol = calcMidiVolume(processVol); // write Buffer for ( int i=0; i<buf.bufferSize(); i++ ){ // Check AEG Segment _eg->periodicOnceEveryDac(_dacCounter); // calc real amplitude double tempAmp = _eg->calcEgLevel(); // LFO tempAmp = (_amd*lfoBuf[i]+1)*tempAmp; // Note Change EG tempAmp = calcNcEg( tempAmp ); // calculate Volume _targetVol = tempAmp * (processVol/AMP_PRM_MAX); // volume interporate interporateVolume(); // reflect volume to buffer buf.mulAudioBuffer( i, _realVol*_realVol ); _dacCounter++; } delete[] lfoBuf; } <commit_msg>補間のパラメータ変更<commit_after>// // msgf_amp_pipe.cpp // ToneGenerator // // Created by 長谷部 雅彦 on 2013/12/08. // Copyright (c) 2013年 長谷部 雅彦. All rights reserved. // #include "msgf_amp_pipe.h" #include "msgf_audio_buffer.h" #include "msgf_instrument.h" #include "msgf_part.h" using namespace msgf; //--------------------------------------------------------- // Initialize //--------------------------------------------------------- AmpPipe::AmpPipe( Note& parent ): _parentNote(parent), _targetVol(0), _realVol(0) { _cbInst = new AegPCallBack( this ); _eg = new Eg2segment( *_cbInst, parent, false ); _am = new Lfo(); } //--------------------------------------------------------- AmpPipe::~AmpPipe( void ) { delete _cbInst; delete _eg; delete _am; } //--------------------------------------------------------- void AmpPipe::init( void ) { clearDacCounter(); // LFO Settings only for Amplitude _am->setWave(LFO_TRI); _am->setDirection(LFO_LOWER); _am->setCoef(); _am->start(); _amd = static_cast<double>(getVoicePrm(VP_LFO_AMD))/AMP_PRM_MAX; _startNcEgDac = -1; } //--------------------------------------------------------- void AmpPipe::changeNote( bool chgNote ) { _startNcEgDac = _dacCounter; _changeNote = chgNote; } //--------------------------------------------------------- // Calculate Note Change EG //--------------------------------------------------------- double AmpPipe::calcNcEg( double amp ) { if ( _startNcEgDac == -1 ) return amp; long counterDiff = _dacCounter - _startNcEgDac; double minLvl = static_cast<double>(getVoicePrm(VP_MINLVL))/10000; int upDcnt, minlvlDcnt, downDcnt; if ( _changeNote == true ){ upDcnt = getVoicePrm(VP_UP_DCNT); minlvlDcnt = getVoicePrm(VP_MINLVL_DCNT); downDcnt = getVoicePrm(VP_DOWN_DCNT); } else { // if Same Note upDcnt = 500; minlvlDcnt = 0; downDcnt = 1500; } if ( counterDiff > upDcnt + minlvlDcnt + downDcnt ){ _startNcEgDac = -1; return amp; } else if ( counterDiff > minlvlDcnt + downDcnt ){ // Level Up double tpdf = (counterDiff - minlvlDcnt - downDcnt)*((1-minLvl)/upDcnt); if ( tpdf > 1-minLvl ) return amp; else return amp*(minLvl + tpdf); } else if ( counterDiff > downDcnt ){ return amp*minLvl; } else if ( counterDiff > 0 ){ // Level Down return amp*(1 - counterDiff*((1-minLvl)/downDcnt)); } return amp; } //--------------------------------------------------------- // Calculate MIDI Volume //--------------------------------------------------------- double AmpPipe::calcMidiVolume( double amp ) { Part* pt = _parentNote.getInstrument()->getPart(); Uint8 midiVal = pt->getCc7(); amp = (amp*midiVal)/127; midiVal = pt->getCc11(); amp = (amp*midiVal)/127; return amp; } //--------------------------------------------------------- // Interporate Volume //--------------------------------------------------------- const double DEEMED_SAME_VOLUME = 1.0001; const double VOLUME_ITP_RATE = 0.001; // /1Dac //--------------------------------------------------------- void AmpPipe::interporateVolume( void ) { if (( _targetVol*DEEMED_SAME_VOLUME >= _realVol ) && ( _targetVol/DEEMED_SAME_VOLUME <= _realVol )){ _realVol = _targetVol; } else { if ( _targetVol > _realVol ){ _realVol = _realVol + (_targetVol-_realVol)*VOLUME_ITP_RATE; } else { _realVol = _realVol - (_realVol-_targetVol)*VOLUME_ITP_RATE; } } } //--------------------------------------------------------- // Process Function //--------------------------------------------------------- void AmpPipe::process( TgAudioBuffer& buf ) { // check Event _eg->periodicOnceEveryProcess(); // get LFO pattern double* lfoBuf = new double[buf.bufferSize()]; _am->process( buf.bufferSize(), lfoBuf ); double processVol = getVoicePrm(VP_VOLUME); processVol = calcMidiVolume(processVol); // write Buffer for ( int i=0; i<buf.bufferSize(); i++ ){ // Check AEG Segment _eg->periodicOnceEveryDac(_dacCounter); // calc real amplitude double tempAmp = _eg->calcEgLevel(); // LFO tempAmp = (_amd*lfoBuf[i]+1)*tempAmp; // Note Change EG tempAmp = calcNcEg( tempAmp ); // calculate Volume _targetVol = tempAmp * (processVol/AMP_PRM_MAX); // volume interporate interporateVolume(); // reflect volume to buffer buf.mulAudioBuffer( i, _realVol*_realVol ); _dacCounter++; } delete[] lfoBuf; } <|endoftext|>
<commit_before>// // EigenJS.cpp // ~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_COMPLEX_HPP #define EIGENJS_COMPLEX_HPP #include <node.h> #include <v8.h> #include <nan.h> #include <complex> #include <sstream> namespace EigenJS { template <typename ValueType> class Complex : public node::ObjectWrap { typedef ValueType element_type; typedef std::complex<element_type> complex_type; public: static void Init(v8::Handle<v8::Object> exports) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New); tpl->SetClassName(NanNew("Complex")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "abs", abs); NODE_SET_PROTOTYPE_METHOD(tpl, "arg", arg); NODE_SET_PROTOTYPE_METHOD(tpl, "norm", norm); NODE_SET_PROTOTYPE_METHOD(tpl, "conj", conj); NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString); v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate(); proto->SetAccessor(NanNew("real"), get_real, set_real); proto->SetAccessor(NanNew("imag"), get_imag, set_imag); NanAssignPersistent(constructor, tpl->GetFunction()); exports->Set(NanNew("Complex"), tpl->GetFunction()); NanAssignPersistent(function_template, tpl); } static NAN_METHOD(abs) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::abs(obj->complex_))); } static NAN_METHOD(arg) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::arg(obj->complex_))); } static NAN_METHOD(norm) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::norm(obj->complex_))); } static NAN_METHOD(conj) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); const complex_type& c = std::conj(obj->complex_); const element_type& real = c.real(); const element_type& imag = c.imag(); NanScope(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(real) , NanNew<v8::Number>(imag) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } static NAN_METHOD(toString) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); std::ostringstream result; result << obj->complex_; NanReturnValue(NanNew(result.str().c_str())); NanReturnUndefined(); } static NAN_GETTER(get_real) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.real())); } static NAN_SETTER(set_real) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( value->NumberValue() , obj->complex_.imag() ); } } static NAN_GETTER(get_imag) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.imag())); } static NAN_SETTER(set_imag) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( obj->complex_.real() , value->NumberValue() ); } } private: Complex(const element_type& real, const element_type& imag) : complex_(real, imag) {} ~Complex() {} static NAN_METHOD(New) { NanScope(); if (args.Length() < 2) { NanThrowError("Tried creating complex without real and imag arguments"); NanReturnUndefined(); } if (args.IsConstructCall()) { const element_type& real = args[0]->NumberValue(); const element_type& imag = args[1]->NumberValue(); Complex* obj = new Complex(real, imag); obj->Wrap(args.This()); NanReturnValue(args.This()); } else { v8::Local<v8::Function> ctr = NanNew(constructor); v8::Local<v8::Value> argv[] = {args[0], args[1]}; NanReturnValue( ctr->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ) ); } } private: static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; private: complex_type complex_; }; template<typename ValueType> v8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template; template<typename ValueType> v8::Persistent<v8::Function> Complex<ValueType>::constructor; } // namespace EigenJS #endif // EIGENJS_COMPLEX_HPP <commit_msg>src: added class method 'Complex.polar()'<commit_after>// // EigenJS.cpp // ~~~~~~~~~~~ // // Copyright (c) 2014 Rick Yang (rick68 at gmail dot com) // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // #ifndef EIGENJS_COMPLEX_HPP #define EIGENJS_COMPLEX_HPP #include <node.h> #include <v8.h> #include <nan.h> #include <complex> #include <sstream> namespace EigenJS { template <typename ValueType> class Complex : public node::ObjectWrap { typedef ValueType element_type; typedef std::complex<element_type> complex_type; public: static void Init(v8::Handle<v8::Object> exports) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New); tpl->SetClassName(NanNew("Complex")); tpl->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(tpl, "abs", abs); NODE_SET_PROTOTYPE_METHOD(tpl, "arg", arg); NODE_SET_PROTOTYPE_METHOD(tpl, "norm", norm); NODE_SET_PROTOTYPE_METHOD(tpl, "conj", conj); NODE_SET_METHOD(tpl, "polar", polar); NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString); v8::Local<v8::ObjectTemplate> proto = tpl->PrototypeTemplate(); proto->SetAccessor(NanNew("real"), get_real, set_real); proto->SetAccessor(NanNew("imag"), get_imag, set_imag); NanAssignPersistent(constructor, tpl->GetFunction()); exports->Set(NanNew("Complex"), tpl->GetFunction()); NanAssignPersistent(function_template, tpl); } static NAN_METHOD(abs) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::abs(obj->complex_))); } static NAN_METHOD(arg) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::arg(obj->complex_))); } static NAN_METHOD(norm) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); NanReturnValue(NanNew(std::norm(obj->complex_))); } static NAN_METHOD(conj) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); const complex_type& c = std::conj(obj->complex_); const element_type& real = c.real(); const element_type& imag = c.imag(); NanScope(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(real) , NanNew<v8::Number>(imag) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } static NAN_METHOD(polar) { NanScope(); if (args.Length() == 2 && args[0]->IsNumber() && args[1]->IsNumber()) { const element_type& rho = args[0]->NumberValue(); const element_type& theta = args[1]->NumberValue(); v8::Local<v8::Function> ctor = NanNew(constructor); v8::Local<v8::Value> argv[] = { NanNew<v8::Number>(rho) , NanNew<v8::Number>(theta) }; v8::Local<v8::Object> new_complex = ctor->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ); NanReturnValue(new_complex); } NanReturnUndefined(); } static NAN_METHOD(toString) { const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanScope(); std::ostringstream result; result << obj->complex_; NanReturnValue(NanNew(result.str().c_str())); NanReturnUndefined(); } static NAN_GETTER(get_real) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.real())); } static NAN_SETTER(set_real) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( value->NumberValue() , obj->complex_.imag() ); } } static NAN_GETTER(get_imag) { NanScope(); if (!NanGetInternalFieldPointer(args.This(), 0)) NanReturnValue(args.This()); const Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); NanReturnValue(NanNew(obj->complex_.imag())); } static NAN_SETTER(set_imag) { if (value->IsNumber()) { Complex* obj = node::ObjectWrap::Unwrap<Complex>(args.This()); obj->complex_ = complex_type( obj->complex_.real() , value->NumberValue() ); } } private: Complex(const element_type& real, const element_type& imag) : complex_(real, imag) {} ~Complex() {} static NAN_METHOD(New) { NanScope(); if (args.Length() < 2) { NanThrowError("Tried creating complex without real and imag arguments"); NanReturnUndefined(); } if (args.IsConstructCall()) { const element_type& real = args[0]->NumberValue(); const element_type& imag = args[1]->NumberValue(); Complex* obj = new Complex(real, imag); obj->Wrap(args.This()); NanReturnValue(args.This()); } else { v8::Local<v8::Function> ctr = NanNew(constructor); v8::Local<v8::Value> argv[] = {args[0], args[1]}; NanReturnValue( ctr->NewInstance( sizeof(argv) / sizeof(v8::Local<v8::Value>) , argv ) ); } } private: static v8::Persistent<v8::FunctionTemplate> function_template; static v8::Persistent<v8::Function> constructor; private: complex_type complex_; }; template<typename ValueType> v8::Persistent<v8::FunctionTemplate> Complex<ValueType>::function_template; template<typename ValueType> v8::Persistent<v8::Function> Complex<ValueType>::constructor; } // namespace EigenJS #endif // EIGENJS_COMPLEX_HPP <|endoftext|>
<commit_before>#include <JsonBox/Convert.h> #include <sstream> #define MASKBITS 0x3F //00111111 #define MASK1BYTE 0x80 //10000000 #define MASK2BYTES 0xC0 //11000000 #define MASK3BYTES 0xE0 //11100000 #define MASK4BYTES 0xF0 //11110000 #define MASK5BYTES 0xF8 //11111000 #define MASK6BYTES 0xFC //11111100 namespace JsonBox { std::string Convert::encodeToUTF8(const String32& utf32String) { std::stringstream result; for(String32::const_iterator i = utf32String.begin() ; i < utf32String.end(); ++i) { // 0xxxxxxx if(*i < 0x80) { result << static_cast<char>(*i); } // 110xxxxx 10xxxxxx else if(*i < 0x800) { result << static_cast<char>(MASK2BYTES | (*i >> 6)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 1110xxxx 10xxxxxx 10xxxxxx else if(*i < 0x10000) { result << static_cast<char>(MASK3BYTES | (*i >> 12)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else if(*i < 0x200000) { result << static_cast<char>(MASK4BYTES | (*i >> 18)); result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx else if(*i < 0x4000000) { result << static_cast<char>(MASK5BYTES | (*i >> 24)); result << static_cast<char>(MASK1BYTE | (*i >> 18 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx else if(*i < 0x8000000) { result << static_cast<char>(MASK6BYTES | (*i >> 30)); result << static_cast<char>(MASK1BYTE | (*i >> 18 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } } return result.str(); } String32 Convert::decodeUTF8(const std::string& utf8String) { std::basic_stringstream<int32_t> result; int32_t tmpUnicodeChar; for(std::string::const_iterator i = utf8String.begin() ; i < utf8String.end();) { // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx if((*i & MASK6BYTES) == MASK6BYTES) { tmpUnicodeChar = ((*i & 0x01) << 30) | ((*(i + 1) & MASKBITS) << 24) | ((*(i + 2) & MASKBITS) << 18) | ((*(i + 3) & MASKBITS) << 12) | ((*(i + 4) & MASKBITS) << 6) | (*(i + 5) & MASKBITS); i += 6; } // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx else if((*i & MASK5BYTES) == MASK5BYTES) { tmpUnicodeChar = ((*i & 0x03) << 24) | ((*(i + 1) & MASKBITS) << 18) | ((*(i + 2) & MASKBITS) << 12) | ((*(i + 3) & MASKBITS) << 6) | (*(i + 4) & MASKBITS); i += 5; } // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else if((*i & MASK4BYTES) == MASK4BYTES) { tmpUnicodeChar = ((*i & 0x07) << 18) | ((*(i + 1) & MASKBITS) << 12) | ((*(i + 2) & MASKBITS) << 6) | (*(i + 3) & MASKBITS); i += 4; } // 1110xxxx 10xxxxxx 10xxxxxx else if((*i & MASK3BYTES) == MASK3BYTES) { tmpUnicodeChar = ((*i & 0x0F) << 12) | ((*(i + 1) & MASKBITS) << 6) | (*(i + 2) & MASKBITS); i += 3; } // 110xxxxx 10xxxxxx else if((*i & MASK2BYTES) == MASK2BYTES) { tmpUnicodeChar = ((*i & 0x1F) << 6) | (*(i + 1) & MASKBITS); i += 2; } // 0xxxxxxx else { // if(*i < MASK1BYTE) tmpUnicodeChar = *i; i += 1; } result << tmpUnicodeChar; } return result.str(); } } <commit_msg>fix the convert.cpp not work with vs2010<commit_after>#include <JsonBox/Convert.h> #include <sstream> #define MASKBITS 0x3F //00111111 #define MASK1BYTE 0x80 //10000000 #define MASK2BYTES 0xC0 //11000000 #define MASK3BYTES 0xE0 //11100000 #define MASK4BYTES 0xF0 //11110000 #define MASK5BYTES 0xF8 //11111000 #define MASK6BYTES 0xFC //11111100 namespace JsonBox { std::string Convert::encodeToUTF8(const String32& utf32String) { std::stringstream result; for(String32::const_iterator i = utf32String.begin() ; i < utf32String.end(); ++i) { // 0xxxxxxx if(*i < 0x80) { result << static_cast<char>(*i); } // 110xxxxx 10xxxxxx else if(*i < 0x800) { result << static_cast<char>(MASK2BYTES | (*i >> 6)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 1110xxxx 10xxxxxx 10xxxxxx else if(*i < 0x10000) { result << static_cast<char>(MASK3BYTES | (*i >> 12)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else if(*i < 0x200000) { result << static_cast<char>(MASK4BYTES | (*i >> 18)); result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx else if(*i < 0x4000000) { result << static_cast<char>(MASK5BYTES | (*i >> 24)); result << static_cast<char>(MASK1BYTE | (*i >> 18 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx else if(*i < 0x8000000) { result << static_cast<char>(MASK6BYTES | (*i >> 30)); result << static_cast<char>(MASK1BYTE | (*i >> 18 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 12 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i >> 6 & MASKBITS)); result << static_cast<char>(MASK1BYTE | (*i & MASKBITS)); } } return result.str(); } String32 Convert::decodeUTF8(const std::string& utf8String) { std::basic_string<int> result; int32_t tmpUnicodeChar; for(std::string::const_iterator i = utf8String.begin() ; i < utf8String.end();) { // 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx if((*i & MASK6BYTES) == MASK6BYTES) { tmpUnicodeChar = ((*i & 0x01) << 30) | ((*(i + 1) & MASKBITS) << 24) | ((*(i + 2) & MASKBITS) << 18) | ((*(i + 3) & MASKBITS) << 12) | ((*(i + 4) & MASKBITS) << 6) | (*(i + 5) & MASKBITS); i += 6; } // 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx else if((*i & MASK5BYTES) == MASK5BYTES) { tmpUnicodeChar = ((*i & 0x03) << 24) | ((*(i + 1) & MASKBITS) << 18) | ((*(i + 2) & MASKBITS) << 12) | ((*(i + 3) & MASKBITS) << 6) | (*(i + 4) & MASKBITS); i += 5; } // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx else if((*i & MASK4BYTES) == MASK4BYTES) { tmpUnicodeChar = ((*i & 0x07) << 18) | ((*(i + 1) & MASKBITS) << 12) | ((*(i + 2) & MASKBITS) << 6) | (*(i + 3) & MASKBITS); i += 4; } // 1110xxxx 10xxxxxx 10xxxxxx else if((*i & MASK3BYTES) == MASK3BYTES) { tmpUnicodeChar = ((*i & 0x0F) << 12) | ((*(i + 1) & MASKBITS) << 6) | (*(i + 2) & MASKBITS); i += 3; } // 110xxxxx 10xxxxxx else if((*i & MASK2BYTES) == MASK2BYTES) { tmpUnicodeChar = ((*i & 0x1F) << 6) | (*(i + 1) & MASKBITS); i += 2; } // 0xxxxxxx else { // if(*i < MASK1BYTE) tmpUnicodeChar = *i; i += 1; } result += std::basic_string<int>(1, tmpUnicodeChar); } return result; } } <|endoftext|>
<commit_before>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2007-2008 Vojtech Franc * Written (W) 2007-2008 Soeren Sonnenburg * Copyright (C) 2007-2008 Fraunhofer Institute FIRST and Max-Planck-Society */ #include "features/Labels.h" #include "lib/Mathematics.h" #include "lib/Time.h" #include "base/Parallel.h" #include "classifier/LinearClassifier.h" #include "classifier/svm/SVMOcas.h" #include "classifier/svm/libocas.h" #include "features/DotFeatures.h" #include "features/Labels.h" CSVMOcas::CSVMOcas(E_SVM_TYPE type) : CLinearClassifier(), use_bias(true), bufsize(3000), C1(1), C2(1), epsilon(1e-3), method(type) { w=NULL; old_w=NULL; } CSVMOcas::CSVMOcas( float64_t C, CDotFeatures* traindat, CLabels* trainlab) : CLinearClassifier(), use_bias(true), bufsize(3000), C1(C), C2(C), epsilon(1e-3) { w=NULL; old_w=NULL; method=SVM_OCAS; set_features(traindat); set_labels(trainlab); } CSVMOcas::~CSVMOcas() { } bool CSVMOcas::train() { SG_INFO("C=%f, epsilon=%f, bufsize=%d\n", get_C1(), get_epsilon(), bufsize); ASSERT(labels); ASSERT(get_features()); ASSERT(labels->is_two_class_labeling()); int32_t num_train_labels=0; lab=labels->get_labels(num_train_labels); w_dim=features->get_dim_feature_space(); int32_t num_vec=features->get_num_vectors(); ASSERT(num_vec==num_train_labels); ASSERT(num_vec>0); delete[] w; w=new float64_t[w_dim]; memset(w, 0, w_dim*sizeof(float64_t)); delete[] old_w; old_w=new float64_t[w_dim]; memset(old_w, 0, w_dim*sizeof(float64_t)); bias=0; tmp_a_buf=new float64_t[w_dim]; cp_value=new float64_t*[bufsize]; cp_index=new uint32_t*[bufsize]; cp_nz_dims=new uint32_t[bufsize]; float64_t TolAbs=0; float64_t QPBound=0; int32_t Method=0; if (method == SVM_OCAS) Method = 1; ocas_return_value_T result = svm_ocas_solver( get_C1(), num_vec, get_epsilon(), TolAbs, QPBound, bufsize, Method, &CSVMOcas::compute_W, &CSVMOcas::update_W, &CSVMOcas::add_new_cut, &CSVMOcas::compute_output, &CSVMOcas::sort, this); SG_INFO("Ocas Converged after %d iterations\n" "==================================\n" "timing statistics:\n" "output_time: %f s\n" "sort_time: %f s\n" "add_time: %f s\n" "w_time: %f s\n" "solver_time %f s\n" "ocas_time %f s\n\n", result.nIter, result.output_time, result.sort_time, result.add_time, result.w_time, result.solver_time, result.ocas_time); delete[] tmp_a_buf; uint32_t num_cut_planes = result.nCutPlanes; for (uint32_t i=0; i<num_cut_planes; i++) { delete[] cp_value[i]; delete[] cp_index[i]; } delete[] cp_value; cp_value=NULL; delete[] cp_index; cp_index=NULL; delete[] cp_nz_dims; cp_nz_dims=NULL; delete[] lab; lab=NULL; delete[] old_w; old_w=NULL; return true; } /*---------------------------------------------------------------------------------- sq_norm_W = sparse_update_W( t ) does the following: W = oldW*(1-t) + t*W; sq_norm_W = W'*W; ---------------------------------------------------------------------------------*/ float64_t CSVMOcas::update_W( float64_t t, void* ptr ) { float64_t sq_norm_W = 0; CSVMOcas* o = (CSVMOcas*) ptr; uint32_t nDim = (uint32_t) o->w_dim; float64_t* W=o->w; float64_t* oldW=o->old_w; for(uint32_t j=0; j <nDim; j++) { W[j] = oldW[j]*(1-t) + t*W[j]; sq_norm_W += W[j]*W[j]; } return( sq_norm_W ); } /*---------------------------------------------------------------------------------- sparse_add_new_cut( new_col_H, new_cut, cut_length, nSel ) does the following: new_a = sum(data_X(:,find(new_cut ~=0 )),2); new_col_H = [sparse_A(:,1:nSel)'*new_a ; new_a'*new_a]; sparse_A(:,nSel+1) = new_a; ---------------------------------------------------------------------------------*/ void CSVMOcas::add_new_cut( float64_t *new_col_H, uint32_t *new_cut, uint32_t cut_length, uint32_t nSel, void* ptr) { CSVMOcas* o = (CSVMOcas*) ptr; CDotFeatures* f = o->get_features(); uint32_t nDim=(uint32_t) o->w_dim; float64_t* y = o->lab; float64_t** c_val = o->cp_value; uint32_t** c_idx = o->cp_index; uint32_t* c_nzd = o->cp_nz_dims; float64_t sq_norm_a; uint32_t i, j, nz_dims; /* temporary vector */ float64_t* new_a = o->tmp_a_buf; memset(new_a, 0, sizeof(float64_t)*nDim); for(i=0; i < cut_length; i++) f->add_to_dense_vec(y[new_cut[i]], new_cut[i], new_a, nDim); /* compute new_a'*new_a and count number of non-zerou dimensions */ nz_dims = 0; sq_norm_a = 0; for(j=0; j < nDim; j++ ) { if(new_a[j] != 0) { nz_dims++; sq_norm_a += new_a[j]*new_a[j]; } } /* sparsify new_a and insert it to the last column of sparse_A */ c_nzd[nSel] = nz_dims; if(nz_dims > 0) { c_idx[nSel]=new uint32_t[nz_dims]; c_val[nSel]=new float64_t[nz_dims]; uint32_t idx=0; for(j=0; j < nDim; j++ ) { if(new_a[j] != 0) { c_idx[nSel][idx] = j; c_val[nSel][idx++] = new_a[j]; } } } new_col_H[nSel] = sq_norm_a; for(i=0; i < nSel; i++) { float64_t tmp = 0; for(j=0; j < c_nzd[i]; j++) tmp += new_a[c_idx[i][j]]*c_val[i][j]; new_col_H[i] = tmp; } //CMath::display_vector(new_col_H, nSel+1, "new_col_H"); //CMath::display_vector((int32_t*) c_idx[nSel], (int32_t) nz_dims, "c_idx"); //CMath::display_vector((float64_t*) c_val[nSel], nz_dims, "c_val"); } void CSVMOcas::sort(float64_t* vals, uint32_t* idx, uint32_t size) { CMath::qsort_index(vals, idx, size); } /*---------------------------------------------------------------------- sparse_compute_output( output ) does the follwing: output = data_X'*W; ----------------------------------------------------------------------*/ void CSVMOcas::compute_output(float64_t *output, void* ptr) { CSVMOcas* o = (CSVMOcas*) ptr; CDotFeatures* f=o->get_features(); int32_t nData=f->get_num_vectors(); float64_t* y = o->lab; f->dense_dot_range(output, 0, nData, y, o->w, o->w_dim, 0.0); //CMath::display_vector(o->w, o->w_dim, "w"); //CMath::display_vector(output, nData, "out"); } /*---------------------------------------------------------------------- sq_norm_W = compute_W( alpha, nSel ) does the following: oldW = W; W = sparse_A(:,1:nSel)'*alpha; sq_norm_W = W'*W; dp_WoldW = W'*oldW'; ----------------------------------------------------------------------*/ void CSVMOcas::compute_W( float64_t *sq_norm_W, float64_t *dp_WoldW, float64_t *alpha, uint32_t nSel, void* ptr ) { CSVMOcas* o = (CSVMOcas*) ptr; uint32_t nDim= (uint32_t) o->w_dim; CMath::swap(o->w, o->old_w); float64_t* W=o->w; float64_t* oldW=o->old_w; memset(W, 0, sizeof(float64_t)*nDim); float64_t** c_val = o->cp_value; uint32_t** c_idx = o->cp_index; uint32_t* c_nzd = o->cp_nz_dims; for(uint32_t i=0; i<nSel; i++) { uint32_t nz_dims = c_nzd[i]; if(nz_dims > 0 && alpha[i] > 0) { for(uint32_t j=0; j < nz_dims; j++) W[c_idx[i][j]] += alpha[i]*c_val[i][j]; } } *sq_norm_W = CMath::dot(W,W, nDim); *dp_WoldW = CMath::dot(W,oldW, nDim);; //SG_PRINT("nSel=%d sq_norm_W=%f dp_WoldW=%f\n", nSel, *sq_norm_W, *dp_WoldW); } <commit_msg>bias 1<commit_after>/* * 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 3 of the License, or * (at your option) any later version. * * Written (W) 2007-2008 Vojtech Franc * Written (W) 2007-2008 Soeren Sonnenburg * Copyright (C) 2007-2008 Fraunhofer Institute FIRST and Max-Planck-Society */ #include "features/Labels.h" #include "lib/Mathematics.h" #include "lib/Time.h" #include "base/Parallel.h" #include "classifier/LinearClassifier.h" #include "classifier/svm/SVMOcas.h" #include "classifier/svm/libocas.h" #include "features/DotFeatures.h" #include "features/Labels.h" CSVMOcas::CSVMOcas(E_SVM_TYPE type) : CLinearClassifier(), use_bias(true), bufsize(3000), C1(1), C2(1), epsilon(1e-3), method(type) { w=NULL; old_w=NULL; } CSVMOcas::CSVMOcas( float64_t C, CDotFeatures* traindat, CLabels* trainlab) : CLinearClassifier(), use_bias(true), bufsize(3000), C1(C), C2(C), epsilon(1e-3) { w=NULL; old_w=NULL; method=SVM_OCAS; set_features(traindat); set_labels(trainlab); } CSVMOcas::~CSVMOcas() { } bool CSVMOcas::train() { SG_INFO("C=%f, epsilon=%f, bufsize=%d\n", get_C1(), get_epsilon(), bufsize); ASSERT(labels); ASSERT(get_features()); ASSERT(labels->is_two_class_labeling()); int32_t num_train_labels=0; lab=labels->get_labels(num_train_labels); w_dim=features->get_dim_feature_space(); int32_t num_vec=features->get_num_vectors(); ASSERT(num_vec==num_train_labels); ASSERT(num_vec>0); delete[] w; w=new float64_t[w_dim]; memset(w, 0, w_dim*sizeof(float64_t)); delete[] old_w; old_w=new float64_t[w_dim]; memset(old_w, 0, w_dim*sizeof(float64_t)); bias=0; tmp_a_buf=new float64_t[w_dim]; cp_value=new float64_t*[bufsize]; cp_index=new uint32_t*[bufsize]; cp_nz_dims=new uint32_t[bufsize]; float64_t TolAbs=0; float64_t QPBound=0; int32_t Method=0; if (method == SVM_OCAS) Method = 1; ocas_return_value_T result = svm_ocas_solver( get_C1(), num_vec, get_epsilon(), TolAbs, QPBound, bufsize, Method, &CSVMOcas::compute_W, &CSVMOcas::update_W, &CSVMOcas::add_new_cut, &CSVMOcas::compute_output, &CSVMOcas::sort, this); SG_INFO("Ocas Converged after %d iterations\n" "==================================\n" "timing statistics:\n" "output_time: %f s\n" "sort_time: %f s\n" "add_time: %f s\n" "w_time: %f s\n" "solver_time %f s\n" "ocas_time %f s\n\n", result.nIter, result.output_time, result.sort_time, result.add_time, result.w_time, result.solver_time, result.ocas_time); delete[] tmp_a_buf; uint32_t num_cut_planes = result.nCutPlanes; for (uint32_t i=0; i<num_cut_planes; i++) { delete[] cp_value[i]; delete[] cp_index[i]; } delete[] cp_value; cp_value=NULL; delete[] cp_index; cp_index=NULL; delete[] cp_nz_dims; cp_nz_dims=NULL; delete[] lab; lab=NULL; delete[] old_w; old_w=NULL; return true; } /*---------------------------------------------------------------------------------- sq_norm_W = sparse_update_W( t ) does the following: W = oldW*(1-t) + t*W; sq_norm_W = W'*W; ---------------------------------------------------------------------------------*/ float64_t CSVMOcas::update_W( float64_t t, void* ptr ) { float64_t sq_norm_W = 0; CSVMOcas* o = (CSVMOcas*) ptr; uint32_t nDim = (uint32_t) o->w_dim; float64_t* W=o->w; float64_t* oldW=o->old_w; for(uint32_t j=0; j <nDim; j++) { W[j] = oldW[j]*(1-t) + t*W[j]; sq_norm_W += W[j]*W[j]; } return( sq_norm_W ); } /*---------------------------------------------------------------------------------- sparse_add_new_cut( new_col_H, new_cut, cut_length, nSel ) does the following: new_a = sum(data_X(:,find(new_cut ~=0 )),2); new_col_H = [sparse_A(:,1:nSel)'*new_a ; new_a'*new_a]; sparse_A(:,nSel+1) = new_a; ---------------------------------------------------------------------------------*/ void CSVMOcas::add_new_cut( float64_t *new_col_H, uint32_t *new_cut, uint32_t cut_length, uint32_t nSel, void* ptr) { CSVMOcas* o = (CSVMOcas*) ptr; CDotFeatures* f = o->get_features(); uint32_t nDim=(uint32_t) o->w_dim; float64_t* y = o->lab; float64_t** c_val = o->cp_value; uint32_t** c_idx = o->cp_index; uint32_t* c_nzd = o->cp_nz_dims; float64_t sq_norm_a; uint32_t i, j, nz_dims; /* temporary vector */ float64_t* new_a = o->tmp_a_buf; memset(new_a, 0, sizeof(float64_t)*nDim); for(i=0; i < cut_length; i++) f->add_to_dense_vec(y[new_cut[i]], new_cut[i], new_a, nDim); /* compute new_a'*new_a and count number of non-zerou dimensions */ nz_dims = 0; sq_norm_a = 0; for(j=0; j < nDim; j++ ) { if(new_a[j] != 0) { nz_dims++; sq_norm_a += new_a[j]*new_a[j]; } } /* sparsify new_a and insert it to the last column of sparse_A */ c_nzd[nSel] = nz_dims; if(nz_dims > 0) { c_idx[nSel]=new uint32_t[nz_dims]; c_val[nSel]=new float64_t[nz_dims]; uint32_t idx=0; for(j=0; j < nDim; j++ ) { if(new_a[j] != 0) { c_idx[nSel][idx] = j; c_val[nSel][idx++] = new_a[j]; } } } new_col_H[nSel] = sq_norm_a; for(i=0; i < nSel; i++) { float64_t tmp = 0; for(j=0; j < c_nzd[i]; j++) tmp += new_a[c_idx[i][j]]*c_val[i][j]; new_col_H[i] = tmp; } //CMath::display_vector(new_col_H, nSel+1, "new_col_H"); //CMath::display_vector((int32_t*) c_idx[nSel], (int32_t) nz_dims, "c_idx"); //CMath::display_vector((float64_t*) c_val[nSel], nz_dims, "c_val"); } void CSVMOcas::sort(float64_t* vals, uint32_t* idx, uint32_t size) { CMath::qsort_index(vals, idx, size); } /*---------------------------------------------------------------------- sparse_compute_output( output ) does the follwing: output = data_X'*W; ----------------------------------------------------------------------*/ void CSVMOcas::compute_output(float64_t *output, void* ptr) { CSVMOcas* o = (CSVMOcas*) ptr; CDotFeatures* f=o->get_features(); int32_t nData=f->get_num_vectors(); float64_t* y = o->lab; for (int32_t i=0; i<nData; i++) output[i]=y[i]; f->dense_dot_range(output, 0, nData, y, o->w, o->w_dim, 0.0); //CMath::display_vector(o->w, o->w_dim, "w"); //CMath::display_vector(output, nData, "out"); } /*---------------------------------------------------------------------- sq_norm_W = compute_W( alpha, nSel ) does the following: oldW = W; W = sparse_A(:,1:nSel)'*alpha; sq_norm_W = W'*W; dp_WoldW = W'*oldW'; ----------------------------------------------------------------------*/ void CSVMOcas::compute_W( float64_t *sq_norm_W, float64_t *dp_WoldW, float64_t *alpha, uint32_t nSel, void* ptr ) { CSVMOcas* o = (CSVMOcas*) ptr; uint32_t nDim= (uint32_t) o->w_dim; CMath::swap(o->w, o->old_w); float64_t* W=o->w; float64_t* oldW=o->old_w; memset(W, 0, sizeof(float64_t)*nDim); float64_t** c_val = o->cp_value; uint32_t** c_idx = o->cp_index; uint32_t* c_nzd = o->cp_nz_dims; for(uint32_t i=0; i<nSel; i++) { uint32_t nz_dims = c_nzd[i]; if(nz_dims > 0 && alpha[i] > 0) { for(uint32_t j=0; j < nz_dims; j++) W[c_idx[i][j]] += alpha[i]*c_val[i][j]; } } *sq_norm_W = CMath::dot(W,W, nDim); *dp_WoldW = CMath::dot(W,oldW, nDim);; //SG_PRINT("nSel=%d sq_norm_W=%f dp_WoldW=%f\n", nSel, *sq_norm_W, *dp_WoldW); } <|endoftext|>
<commit_before>#pragma once #include "core/enum.hh" #include "bytes.hh" #include "gc_clock.hh" #include "tombstone.hh" namespace sstables { // Some in-disk structures have an associated integer (of varying sizes) that // represents how large they are. They can be a byte-length, in the case of a // string, number of elements, in the case of an array, etc. // // For those elements, we encapsulate the underlying type in an outter // structure that embeds how large is the in-disk size. It is a lot more // convenient to embed it in the size than explicitly writing it in the parser. // This way, we don't need to encode this information in multiple places at // once - it is already part of the type. template <typename Size> struct disk_string { bytes value; explicit operator bytes_view() const { return value; } }; template <typename Size> struct disk_string_view { bytes_view value; }; template <typename Size, typename Members> struct disk_array { static_assert(std::is_integral<Size>::value, "Length type must be convertible to integer"); std::vector<Members> elements; }; template <typename Size, typename Key, typename Value> struct disk_hash { std::unordered_map<Key, Value, std::hash<Key>> map; }; struct option { disk_string<uint16_t> key; disk_string<uint16_t> value; template <typename Describer> future<> describe_type(Describer f) { return f(key, value); } }; struct filter { uint32_t hashes; disk_array<uint32_t, uint64_t> buckets; template <typename Describer> future<> describe_type(Describer f) { return f(hashes, buckets); } }; struct index_entry { disk_string<uint16_t> key; uint64_t position; disk_string<uint32_t> promoted_index; explicit operator bytes_view() const { return bytes_view(key); } }; struct summary_entry { bytes key; uint64_t position; explicit operator bytes_view() const { return key; } bool operator==(const summary_entry& x) const { return position == x.position && key == x.key; } }; // Note: Sampling level is present in versions ka and higher. We ATM only support la, // so it's always there. But we need to make this conditional if we ever want to support // other formats (unlikely) struct summary_la { struct header { // The minimum possible amount of indexes per group (sampling level) uint32_t min_index_interval; // The number of entries in the Summary File uint32_t size; // The memory to be consumed to map the whole Summary into memory. uint64_t memory_size; // The actual sampling level. uint32_t sampling_level; // The number of entries the Summary *would* have if the sampling // level would be equal to min_index_interval. uint32_t size_at_full_sampling; } header; // The position in the Summary file for each of the indexes. // NOTE1 that its actual size is determined by the "size" parameter, not // by its preceding size_at_full_sampling // NOTE2: They are laid out in *MEMORY* order, not BE. // NOTE3: The sizes in this array represent positions in the memory stream, // not the file. The memory stream effectively begins after the header, // so every position here has to be added of sizeof(header). std::vector<uint32_t> positions; std::vector<summary_entry> entries; disk_string<uint32_t> first_key; disk_string<uint32_t> last_key; // NOTE4: There is a structure written by Cassandra into the end of the Summary // file, after the field last_key, that we haven't understand yet, but we know // that its content isn't related to the summary itself. // The structure is basically as follow: // struct { disk_string<uint16_t>; uint32_t; uint64_t; disk_string<uint16_t>; } // Another interesting fact about this structure is that it is apparently always // filled with the same data. It's too early to judge that the data is useless. // However, it was tested that Cassandra loads successfully a Summary file with // this structure removed from it. Anyway, let's pay attention to it. }; using summary = summary_la; struct estimated_histogram { struct eh_elem { uint64_t offset; uint64_t bucket; template <typename Describer> future<> describe_type(Describer f) { return f(offset, bucket); } }; disk_array<uint32_t, eh_elem> elements; template <typename Describer> future<> describe_type(Describer f) { return f(elements); } }; struct replay_position { uint64_t segment; uint32_t position; template <typename Describer> future<> describe_type(Describer f) { return f(segment, position); } }; struct streaming_histogram { uint32_t max_bin_size; disk_hash<uint32_t, double, uint64_t> hash; template <typename Describer> future<> describe_type(Describer f) { return f(max_bin_size, hash); } }; struct metadata { }; struct validation_metadata : public metadata { disk_string<uint16_t> partitioner; double filter_chance; template <typename Describer> future<> describe_type(Describer f) { return f(partitioner, filter_chance); } }; struct compaction_metadata : public metadata { disk_array<uint32_t, uint32_t> ancestors; disk_array<uint32_t, uint8_t> cardinality; template <typename Describer> future<> describe_type(Describer f) { return f(ancestors, cardinality); } }; struct la_stats_metadata : public metadata { estimated_histogram estimated_row_size; estimated_histogram estimated_column_count; replay_position position; uint64_t min_timestamp; uint64_t max_timestamp; uint32_t max_local_deletion_time; double compression_ratio; streaming_histogram estimated_tombstone_drop_time; uint32_t sstable_level; uint64_t repaired_at; disk_array<uint32_t, disk_string<uint16_t>> min_column_names; disk_array<uint32_t, disk_string<uint16_t>> max_column_names; bool has_legacy_counter_shards; template <typename Describer> future<> describe_type(Describer f) { return f( estimated_row_size, estimated_column_count, position, min_timestamp, max_timestamp, max_local_deletion_time, compression_ratio, estimated_tombstone_drop_time, sstable_level, repaired_at, min_column_names, max_column_names, has_legacy_counter_shards ); } }; using stats_metadata = la_stats_metadata; // Numbers are found on disk, so they do matter. Also, setting their sizes of // that of an uint32_t is a bit wasteful, but it simplifies the code a lot // since we can now still use a strongly typed enum without introducing a // notion of "disk-size" vs "memory-size". enum class metadata_type : uint32_t { Validation = 0, Compaction = 1, Stats = 2, }; } namespace std { template <> struct hash<sstables::metadata_type> : enum_hash<sstables::metadata_type> {}; } namespace sstables { struct statistics { disk_hash<uint32_t, metadata_type, uint32_t> hash; std::unordered_map<metadata_type, std::unique_ptr<metadata>> contents; }; struct deletion_time { int32_t local_deletion_time; int64_t marked_for_delete_at; template <typename Describer> future<> describe_type(Describer f) { return f(local_deletion_time, marked_for_delete_at); } bool live() const { return (local_deletion_time == std::numeric_limits<int32_t>::max()) && (marked_for_delete_at == std::numeric_limits<int64_t>::min()); } explicit operator tombstone() { return tombstone(marked_for_delete_at, gc_clock::time_point(gc_clock::duration(local_deletion_time))); } }; enum class column_mask : uint8_t { none = 0x0, deletion = 0x01, expiration = 0x02, counter = 0x04, counter_update = 0x08, range_tombstone = 0x10, }; inline column_mask operator&(column_mask m1, column_mask m2) { return column_mask(static_cast<uint8_t>(m1) & static_cast<uint8_t>(m2)); } inline column_mask operator|(column_mask m1, column_mask m2) { return column_mask(static_cast<uint8_t>(m1) | static_cast<uint8_t>(m2)); } } <commit_msg>sstables: add convenience constructors for filter type<commit_after>#pragma once #include "core/enum.hh" #include "bytes.hh" #include "gc_clock.hh" #include "tombstone.hh" namespace sstables { // Some in-disk structures have an associated integer (of varying sizes) that // represents how large they are. They can be a byte-length, in the case of a // string, number of elements, in the case of an array, etc. // // For those elements, we encapsulate the underlying type in an outter // structure that embeds how large is the in-disk size. It is a lot more // convenient to embed it in the size than explicitly writing it in the parser. // This way, we don't need to encode this information in multiple places at // once - it is already part of the type. template <typename Size> struct disk_string { bytes value; explicit operator bytes_view() const { return value; } }; template <typename Size> struct disk_string_view { bytes_view value; }; template <typename Size, typename Members> struct disk_array { static_assert(std::is_integral<Size>::value, "Length type must be convertible to integer"); std::vector<Members> elements; }; template <typename Size, typename Key, typename Value> struct disk_hash { std::unordered_map<Key, Value, std::hash<Key>> map; }; struct option { disk_string<uint16_t> key; disk_string<uint16_t> value; template <typename Describer> future<> describe_type(Describer f) { return f(key, value); } }; struct filter { uint32_t hashes; disk_array<uint32_t, uint64_t> buckets; template <typename Describer> future<> describe_type(Describer f) { return f(hashes, buckets); } // Create an always positive filter if nothing else is specified. filter() : hashes(0), buckets({}) {} explicit filter(int hashes, std::vector<uint64_t> buckets) : hashes(hashes), buckets({std::move(buckets)}) {} }; struct index_entry { disk_string<uint16_t> key; uint64_t position; disk_string<uint32_t> promoted_index; explicit operator bytes_view() const { return bytes_view(key); } }; struct summary_entry { bytes key; uint64_t position; explicit operator bytes_view() const { return key; } bool operator==(const summary_entry& x) const { return position == x.position && key == x.key; } }; // Note: Sampling level is present in versions ka and higher. We ATM only support la, // so it's always there. But we need to make this conditional if we ever want to support // other formats (unlikely) struct summary_la { struct header { // The minimum possible amount of indexes per group (sampling level) uint32_t min_index_interval; // The number of entries in the Summary File uint32_t size; // The memory to be consumed to map the whole Summary into memory. uint64_t memory_size; // The actual sampling level. uint32_t sampling_level; // The number of entries the Summary *would* have if the sampling // level would be equal to min_index_interval. uint32_t size_at_full_sampling; } header; // The position in the Summary file for each of the indexes. // NOTE1 that its actual size is determined by the "size" parameter, not // by its preceding size_at_full_sampling // NOTE2: They are laid out in *MEMORY* order, not BE. // NOTE3: The sizes in this array represent positions in the memory stream, // not the file. The memory stream effectively begins after the header, // so every position here has to be added of sizeof(header). std::vector<uint32_t> positions; std::vector<summary_entry> entries; disk_string<uint32_t> first_key; disk_string<uint32_t> last_key; // NOTE4: There is a structure written by Cassandra into the end of the Summary // file, after the field last_key, that we haven't understand yet, but we know // that its content isn't related to the summary itself. // The structure is basically as follow: // struct { disk_string<uint16_t>; uint32_t; uint64_t; disk_string<uint16_t>; } // Another interesting fact about this structure is that it is apparently always // filled with the same data. It's too early to judge that the data is useless. // However, it was tested that Cassandra loads successfully a Summary file with // this structure removed from it. Anyway, let's pay attention to it. }; using summary = summary_la; struct estimated_histogram { struct eh_elem { uint64_t offset; uint64_t bucket; template <typename Describer> future<> describe_type(Describer f) { return f(offset, bucket); } }; disk_array<uint32_t, eh_elem> elements; template <typename Describer> future<> describe_type(Describer f) { return f(elements); } }; struct replay_position { uint64_t segment; uint32_t position; template <typename Describer> future<> describe_type(Describer f) { return f(segment, position); } }; struct streaming_histogram { uint32_t max_bin_size; disk_hash<uint32_t, double, uint64_t> hash; template <typename Describer> future<> describe_type(Describer f) { return f(max_bin_size, hash); } }; struct metadata { }; struct validation_metadata : public metadata { disk_string<uint16_t> partitioner; double filter_chance; template <typename Describer> future<> describe_type(Describer f) { return f(partitioner, filter_chance); } }; struct compaction_metadata : public metadata { disk_array<uint32_t, uint32_t> ancestors; disk_array<uint32_t, uint8_t> cardinality; template <typename Describer> future<> describe_type(Describer f) { return f(ancestors, cardinality); } }; struct la_stats_metadata : public metadata { estimated_histogram estimated_row_size; estimated_histogram estimated_column_count; replay_position position; uint64_t min_timestamp; uint64_t max_timestamp; uint32_t max_local_deletion_time; double compression_ratio; streaming_histogram estimated_tombstone_drop_time; uint32_t sstable_level; uint64_t repaired_at; disk_array<uint32_t, disk_string<uint16_t>> min_column_names; disk_array<uint32_t, disk_string<uint16_t>> max_column_names; bool has_legacy_counter_shards; template <typename Describer> future<> describe_type(Describer f) { return f( estimated_row_size, estimated_column_count, position, min_timestamp, max_timestamp, max_local_deletion_time, compression_ratio, estimated_tombstone_drop_time, sstable_level, repaired_at, min_column_names, max_column_names, has_legacy_counter_shards ); } }; using stats_metadata = la_stats_metadata; // Numbers are found on disk, so they do matter. Also, setting their sizes of // that of an uint32_t is a bit wasteful, but it simplifies the code a lot // since we can now still use a strongly typed enum without introducing a // notion of "disk-size" vs "memory-size". enum class metadata_type : uint32_t { Validation = 0, Compaction = 1, Stats = 2, }; } namespace std { template <> struct hash<sstables::metadata_type> : enum_hash<sstables::metadata_type> {}; } namespace sstables { struct statistics { disk_hash<uint32_t, metadata_type, uint32_t> hash; std::unordered_map<metadata_type, std::unique_ptr<metadata>> contents; }; struct deletion_time { int32_t local_deletion_time; int64_t marked_for_delete_at; template <typename Describer> future<> describe_type(Describer f) { return f(local_deletion_time, marked_for_delete_at); } bool live() const { return (local_deletion_time == std::numeric_limits<int32_t>::max()) && (marked_for_delete_at == std::numeric_limits<int64_t>::min()); } explicit operator tombstone() { return tombstone(marked_for_delete_at, gc_clock::time_point(gc_clock::duration(local_deletion_time))); } }; enum class column_mask : uint8_t { none = 0x0, deletion = 0x01, expiration = 0x02, counter = 0x04, counter_update = 0x08, range_tombstone = 0x10, }; inline column_mask operator&(column_mask m1, column_mask m2) { return column_mask(static_cast<uint8_t>(m1) & static_cast<uint8_t>(m2)); } inline column_mask operator|(column_mask m1, column_mask m2) { return column_mask(static_cast<uint8_t>(m1) | static_cast<uint8_t>(m2)); } } <|endoftext|>
<commit_before> #include "../../expat/escape_xml.h" #include "../frontend/basic_formats.h" #include "output_popup.h" #include <cmath> #include <fstream> bool Tag_Filter::matches(const std::vector< std::pair< std::string, std::string > >* tags) const { if (!tags) return false; for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) { if (it->first == key && condition.matches(it->second)) return straight; } return !straight; } std::string link_if_any(const std::vector< std::pair< std::string, std::string > >& tags) { std::string link; for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("www.") != std::string::npos) link = "http://" + it->second; } for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("http://") != std::string::npos) link = it->second; } for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("https://") != std::string::npos) link = it->second; } return link; } std::string title_if_any(const std::string& link, const std::string& title_key, const std::vector< std::pair< std::string, std::string > >& tags) { std::string title; for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->first == title_key) { if (link != "") title += "<a href=\"" + link + "\" target=\"_blank\">"; title += "<strong>" + it->second + "</strong>"; if (link != "") title += "</a>"; title += "<br/>\n"; break; } } return title; } void Category_Filter::set_title(const std::string& title) { output = "\n<h2>" + title + "</h2>"; } void Category_Filter::set_title_key(const std::string& title_key_) { title_key = title_key_; } template< typename TSkel > std::string elem_type() { return ""; } template< > std::string elem_type< Node_Skeleton >() { return "Node"; } template< > std::string elem_type< Way_Skeleton >() { return "Way"; } template< > std::string elem_type< Relation_Skeleton >() { return "Relation"; } template< typename TSkel > std::string print(const std::string& title_key, const TSkel& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::string link = tags ? link_if_any(*tags) : ""; std::string result = "\n<p>" + (tags ? title_if_any(link, title_key, *tags) : ""); if (result == "\n<p>") { if (link != "") result += "<a href=\"" + link + "\" target=\"_blank\">"; std::ostringstream out; out<<skel.id.val(); result += "<strong>" + elem_type< TSkel >() + " " + out.str() + "</strong>"; if (link != "") result += "</a>"; result += "<br/>\n"; } if (tags) { for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) result += it->first + ": " + it->second + "<br/>\n"; } return result + "<p/>\n"; } bool Category_Filter::consider(const Node_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) { std::vector< Tag_Filter* >::const_iterator it = it_conj->begin(); for (; it != it_conj->end(); ++it) { if ((*it)->matches(tags)) break; } if (it != it_conj->end()) break; } if (it_conj != filter_disjunction.end()) output += print(title_key, skel, tags); return it_conj == filter_disjunction.end(); } bool Category_Filter::consider(const Way_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) { std::vector< Tag_Filter* >::const_iterator it = it_conj->begin(); for (; it != it_conj->end(); ++it) { if ((*it)->matches(tags)) break; } if (it != it_conj->end()) break; } if (it_conj != filter_disjunction.end()) output += print(title_key, skel, tags); return it_conj == filter_disjunction.end(); } bool Category_Filter::consider(const Relation_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) { std::vector< Tag_Filter* >::const_iterator it = it_conj->begin(); for (; it != it_conj->end(); ++it) { if ((*it)->matches(tags)) break; } if (it != it_conj->end()) break; } if (it_conj != filter_disjunction.end()) output += print(title_key, skel, tags); return it_conj == filter_disjunction.end(); } bool Output_Popup::write_http_headers() { std::cout<<"Content-type: text/html; charset=utf-8\n"; return true; } void Output_Popup::write_payload_header (const std::string& db_dir_, const std::string& timestamp_, const std::string& area_timestamp_) { std::cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n" "<head>\n" " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n" " <title>OSM3S Response</title>\n" "</head>\n" "<body>\n"; } void Output_Popup::display_remark(const std::string& text) { //TODO } void Output_Popup::display_error(const std::string& text) { //TODO } void Output_Popup::write_footer() { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) std::cout<<(*it)->result(); std::cout<<"\n</body>\n</html>\n"; } void Output_Popup::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, const std::vector< std::pair< std::string, std::string > >* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) { if ((*it)->consider(skel, tags)) return; } } void Output_Popup::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, const std::vector< std::pair< std::string, std::string > >* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) { if ((*it)->consider(skel, tags)) return; } } void Output_Popup::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, const std::vector< std::pair< std::string, std::string > >* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) { if ((*it)->consider(skel, tags)) return; } } void Output_Popup::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, Output_Mode mode) { // Intentionally empty } <commit_msg>Fixed further bug in out:popup<commit_after> #include "../../expat/escape_xml.h" #include "../frontend/basic_formats.h" #include "output_popup.h" #include <cmath> #include <fstream> bool Tag_Filter::matches(const std::vector< std::pair< std::string, std::string > >* tags) const { if (!tags) return false; for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) { if (it->first == key && condition.matches(it->second)) return straight; } return !straight; } std::string link_if_any(const std::vector< std::pair< std::string, std::string > >& tags) { std::string link; for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("www.") != std::string::npos) link = "http://" + it->second; } for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("http://") != std::string::npos) link = it->second; } for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->second.find("https://") != std::string::npos) link = it->second; } return link; } std::string title_if_any(const std::string& link, const std::string& title_key, const std::vector< std::pair< std::string, std::string > >& tags) { std::string title; for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags.begin(); it != tags.end(); ++it) { if (it->first == title_key) { if (link != "") title += "<a href=\"" + link + "\" target=\"_blank\">"; title += "<strong>" + it->second + "</strong>"; if (link != "") title += "</a>"; title += "<br/>\n"; break; } } return title; } void Category_Filter::set_title(const std::string& title) { output = "\n<h2>" + title + "</h2>"; } void Category_Filter::set_title_key(const std::string& title_key_) { title_key = title_key_; } template< typename TSkel > std::string elem_type() { return ""; } template< > std::string elem_type< Node_Skeleton >() { return "Node"; } template< > std::string elem_type< Way_Skeleton >() { return "Way"; } template< > std::string elem_type< Relation_Skeleton >() { return "Relation"; } template< typename TSkel > std::string print(const std::string& title_key, const TSkel& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::string link = tags ? link_if_any(*tags) : ""; std::string result = "\n<p>" + (tags ? title_if_any(link, title_key, *tags) : ""); if (result == "\n<p>") { if (link != "") result += "<a href=\"" + link + "\" target=\"_blank\">"; std::ostringstream out; out<<skel.id.val(); result += "<strong>" + elem_type< TSkel >() + " " + out.str() + "</strong>"; if (link != "") result += "</a>"; result += "<br/>\n"; } if (tags) { for (std::vector< std::pair< std::string, std::string > >::const_iterator it = tags->begin(); it != tags->end(); ++it) result += it->first + ": " + it->second + "<br/>\n"; } return result + "<p/>\n"; } bool Category_Filter::consider(const Node_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) { std::vector< Tag_Filter* >::const_iterator it = it_conj->begin(); for (; it != it_conj->end(); ++it) { if ((*it)->matches(tags)) break; } if (it != it_conj->end()) break; } if (it_conj != filter_disjunction.end()) output += print(title_key, skel, tags); return it_conj != filter_disjunction.end(); } bool Category_Filter::consider(const Way_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) { std::vector< Tag_Filter* >::const_iterator it = it_conj->begin(); for (; it != it_conj->end(); ++it) { if ((*it)->matches(tags)) break; } if (it != it_conj->end()) break; } if (it_conj != filter_disjunction.end()) output += print(title_key, skel, tags); return it_conj != filter_disjunction.end(); } bool Category_Filter::consider(const Relation_Skeleton& skel, const std::vector< std::pair< std::string, std::string > >* tags) { std::vector< std::vector< Tag_Filter* > >::const_iterator it_conj = filter_disjunction.begin(); for (; it_conj != filter_disjunction.end(); ++it_conj) { std::vector< Tag_Filter* >::const_iterator it = it_conj->begin(); for (; it != it_conj->end(); ++it) { if ((*it)->matches(tags)) break; } if (it != it_conj->end()) break; } if (it_conj != filter_disjunction.end()) output += print(title_key, skel, tags); return it_conj != filter_disjunction.end(); } bool Output_Popup::write_http_headers() { std::cout<<"Content-type: text/html; charset=utf-8\n"; return true; } void Output_Popup::write_payload_header (const std::string& db_dir_, const std::string& timestamp_, const std::string& area_timestamp_) { std::cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n" "<head>\n" " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n" " <title>OSM3S Response</title>\n" "</head>\n" "<body>\n"; } void Output_Popup::display_remark(const std::string& text) { //TODO } void Output_Popup::display_error(const std::string& text) { //TODO } void Output_Popup::write_footer() { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) std::cout<<(*it)->result(); std::cout<<"\n</body>\n</html>\n"; } void Output_Popup::print_item(const Node_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Node_Skeleton* new_skel, const Opaque_Geometry* new_geometry, const std::vector< std::pair< std::string, std::string > >* new_tags, const OSM_Element_Metadata_Skeleton< Node::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) { if ((*it)->consider(skel, tags)) return; } } void Output_Popup::print_item(const Way_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* meta, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Way_Skeleton* new_skel, const Opaque_Geometry* new_geometry, const std::vector< std::pair< std::string, std::string > >* new_tags, const OSM_Element_Metadata_Skeleton< Way::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) { if ((*it)->consider(skel, tags)) return; } } void Output_Popup::print_item(const Relation_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* meta, const std::map< uint32, std::string >* roles, const std::map< uint32, std::string >* users, Output_Mode mode, const Feature_Action& action, const Relation_Skeleton* new_skel, const Opaque_Geometry* new_geometry, const std::vector< std::pair< std::string, std::string > >* new_tags, const OSM_Element_Metadata_Skeleton< Relation::Id_Type >* new_meta) { for (std::vector< Category_Filter* >::iterator it = categories.begin(); it != categories.end(); ++it) { if ((*it)->consider(skel, tags)) return; } } void Output_Popup::print_item(const Derived_Skeleton& skel, const Opaque_Geometry& geometry, const std::vector< std::pair< std::string, std::string > >* tags, Output_Mode mode) { // Intentionally empty } <|endoftext|>
<commit_before>/** * @file calcOpticalFlowPyrLK.cpp * @brief mex interface for calcOpticalFlowPyrLK * @author Kota Yamaguchi * @date 2011 */ #include "mexopencv.hpp" using namespace std; using namespace cv; /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { // Check the number of arguments if (nrhs<3 || ((nrhs%2)!=1) || nlhs>3) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); // Argument vector vector<MxArray> rhs(prhs,prhs+nrhs); Mat prevImg(rhs[0].toMat(CV_8U)), nextImg(rhs[1].toMat(CV_8U)); vector<Point2f> prevPts(rhs[2].toVector<Point2f>()), nextPts; Size winSize=Size(15,15); int maxLevel=3; TermCriteria criteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01); double derivLambda=0.5; int flags=0; for (int i=3; i<nrhs; i+=2) { string key = rhs[i].toString(); if (key=="InitialFlow") { vector<MxArray> _nextPts(rhs[i+1].toVector<MxArray>()); nextPts.reserve(_nextPts.size()); for (vector<MxArray>::iterator it=_nextPts.begin();it<_nextPts.end();++it) nextPts.push_back((*it).toPoint_<float>()); flags = OPTFLOW_USE_INITIAL_FLOW; } else if (key=="WinSize") winSize = rhs[i+1].toSize(); else if (key=="MaxLevel") maxLevel = rhs[i+1].toInt(); else if (key=="Criteria") criteria = rhs[i+1].toTermCriteria(); else if (key=="DerivLambda") derivLambda = rhs[i+1].toDouble(); else mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option"); } // Process vector<uchar> status(prevPts.size()); vector<float> err(prevPts.size()); calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel, criteria, derivLambda, flags); plhs[0] = MxArray(nextPts); if (nlhs>1) plhs[1] = MxArray(Mat(status)); if (nlhs>2) plhs[2] = MxArray(Mat(err)); } <commit_msg>Updated calcOpticalFlowPyrLK API to 2.4.x<commit_after>/** * @file calcOpticalFlowPyrLK.cpp * @brief mex interface for calcOpticalFlowPyrLK * @author Kota Yamaguchi * @date 2011 */ #include "mexopencv.hpp" using namespace std; using namespace cv; /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { // Check the number of arguments if (nrhs<3 || ((nrhs%2)!=1) || nlhs>3) mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments"); // Argument vector vector<MxArray> rhs(prhs,prhs+nrhs); Mat prevImg(rhs[0].toMat(CV_8U)), nextImg(rhs[1].toMat(CV_8U)); vector<Point2f> prevPts(rhs[2].toVector<Point2f>()), nextPts; Size winSize=Size(21,21); int maxLevel=3; TermCriteria criteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01); int flags=0; double minEigThreshold=1e-4; for (int i=3; i<nrhs; i+=2) { string key = rhs[i].toString(); if (key=="InitialFlow") { vector<MxArray> _nextPts(rhs[i+1].toVector<MxArray>()); nextPts.reserve(_nextPts.size()); for (vector<MxArray>::iterator it=_nextPts.begin();it<_nextPts.end();++it) nextPts.push_back((*it).toPoint_<float>()); flags = OPTFLOW_USE_INITIAL_FLOW; } else if (key=="WinSize") winSize = rhs[i+1].toSize(); else if (key=="MaxLevel") maxLevel = rhs[i+1].toInt(); else if (key=="Criteria") criteria = rhs[i+1].toTermCriteria(); else if (key=="MinEigThreshold") minEigThreshold = rhs[i+1].toDouble(); else mexErrMsgIdAndTxt("mexopencv:error","Unrecognized option"); } // Process vector<uchar> status(prevPts.size()); vector<float> err(prevPts.size()); calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel, criteria, flags, minEigThreshold); plhs[0] = MxArray(nextPts); if (nlhs>1) plhs[1] = MxArray(Mat(status)); if (nlhs>2) plhs[2] = MxArray(Mat(err)); } <|endoftext|>
<commit_before>#include <signal.h> #ifndef NDEBUG # include <sys/resource.h> #endif #include <syslog.h> #include <cassert> #include <iostream> #include <fstream> #include <stdexcept> #include <iterator> #include <algorithm> #include <sys/wait.h> #include <autosprintf.h> #include "eyekinfig.h" #include "eyetil.h" #include "eyefiworker.h" #ifdef HAVE_SQLITE # include "iiidb.h" #endif eyefiworker::eyefiworker() : eyefiService(SOAP_IO_STORE|SOAP_IO_KEEPALIVE) { bind_flags = SO_REUSEADDR; max_keep_alive = 0; socket_flags = #if defined(MSG_NOSIGNAL) MSG_NOSIGNAL #elif defined(SO_NOSIGPIPE) SO_NOSIGPIPE #else #error Something is wrong with sigpipe prevention on the platform #endif ; } eyefiworker::~eyefiworker() { } int eyefiworker::run(int bindport) { #ifdef HAVE_SQLITE sqlite3_initialize(); #endif if(!soap_valid_socket(bind(0,bindport,64))) throw std::runtime_error("failed to bind()"); signal(SIGCHLD,SIG_IGN); while(true) { if(!soap_valid_socket(accept())) throw std::runtime_error("failed to accept()"); pid_t p = fork(); if(p<0) throw std::runtime_error("failed to fork()"); if(!p) { recv_timeout = 600; send_timeout = 120; (void)serve(); soap_destroy(this); soap_end(this); soap_done(this); #ifndef NDEBUG struct rusage ru; if(getrusage(RUSAGE_SELF,&ru)) { syslog(LOG_NOTICE,"Failed to getrusage(): %d",errno); }else{ syslog(LOG_INFO,"maxrss: %ld\n",ru.ru_maxrss); } #endif /* NDEBUG */ throw throwable_exit(0); } close(socket); socket = SOAP_INVALID_SOCKET; } } static binary_t session_nonce; #ifdef HAVE_SQLITE static struct { std::string filesignature; long filesize; std::string filename; inline void reset() { filesignature.erase(); filename.erase(); filesize=0; } inline void set(const std::string n,const std::string sig,long siz) { filename = n; filesignature = sig; filesize = siz; } inline bool is(const std::string n,const std::string sig,long siz) { return filesize==siz && filename==n && filesignature==sig; } } already; #endif /* HAVE_SQLITE */ static bool detached_child() { pid_t p = fork(); if(p<0) { syslog(LOG_ERR,"Failed to fork away for hook execution"); _exit(-1); } if(!p) { setsid(); for(int i=getdtablesize();i>=0;--i) close(i); int i=open("/dev/null",O_RDWR); assert(i==0); i = dup(i); assert(i==1); i = dup(i); assert(i==2); return true; } return false; } static int E(eyefiworker* efs,const char *c,const std::exception& e) { efs->keep_alive=0; syslog(LOG_ERR,"error while processing %s: %s",c,e.what()); return soap_sender_fault(efs,gnu::autosprintf("error processing %s",c),0); } int eyefiworker::StartSession( std::string macaddress,std::string cnonce, int transfermode,long transfermodetimestamp, struct rns__StartSessionResponse &r ) try { syslog(LOG_INFO, "StartSession request from %s with cnonce=%s, transfermode=%d, transfermodetimestamp=%ld", macaddress.c_str(), cnonce.c_str(), transfermode, transfermodetimestamp ); eyekinfig_t eyekinfig(macaddress); r.credential = binary_t(macaddress+cnonce+eyekinfig.get_upload_key()).md5().hex(); r.snonce = session_nonce.make_nonce().hex(); r.transfermode=transfermode; r.transfermodetimestamp=transfermodetimestamp; r.upsyncallowed=false; std::string cmd = eyekinfig.get_on_start_session(); if(!cmd.empty()) { if(detached_child()) { putenv( gnu::autosprintf("EYEFI_MACADDRESS=%s",macaddress.c_str()) ); putenv( gnu::autosprintf("EYEFI_TRANSFERMODE=%d",transfermode) ); putenv( gnu::autosprintf("EYEFI_TRANSFERMODETIMESTAMP=%ld",transfermodetimestamp) ); char *argv[] = { (char*)"/bin/sh", (char*)"-c", (char*)cmd.c_str(), 0 }; execv("/bin/sh",argv); syslog(LOG_ERR,"Failed to execute '%s'",cmd.c_str()); _exit(-1); } } return SOAP_OK; }catch(const std::exception& e) { return E(this,"StartSession",e); } int eyefiworker::GetPhotoStatus( std::string credential, std::string macaddress, std::string filename, long filesize, std::string filesignature, int flags, struct rns__GetPhotoStatusResponse &r ) try { syslog(LOG_INFO, "GetPhotoStatus request from %s with credential=%s, filename=%s, filesize=%ld, filesignature=%s, flags=%d; session nonce=%s", macaddress.c_str(), credential.c_str(), filename.c_str(), filesize, filesignature.c_str(), flags, session_nonce.hex().c_str() ); eyekinfig_t eyekinfig(macaddress); std::string computed_credential = binary_t(macaddress+eyekinfig.get_upload_key()+session_nonce.hex()).md5().hex(); #ifndef NDEBUG syslog(LOG_DEBUG, " computed credential=%s", computed_credential.c_str()); #endif if (credential != computed_credential) throw std::runtime_error("card authentication failed"); #ifdef HAVE_SQLITE iiidb_t D(eyekinfig); seclude::stmt_t S = D.prepare( "SELECT fileid FROM photo" " WHERE mac=:mac AND filename=:filename" " AND filesize=:filesize AND filesignature=:filesignature" ).bind(":mac",macaddress) .bind(":filename",filename).bind(":filesize",filesize) .bind(":filesignature",filesignature); if(!S.step()) { r.fileid = 1; r.offset = 0; }else{ r.fileid = S.column<long>(0); r.offset = filesize; already.set(filename,filesignature,filesize); } #else /* HAVE_SQLITE */ r.fileid=1, r.offset=0; #endif /* HAVE_SQLITE */ return SOAP_OK; }catch(const std::exception& e) { return E(this,"GetPhotoStatus",e); } int eyefiworker::MarkLastPhotoInRoll( std::string macaddress, int mergedelta, struct rns__MarkLastPhotoInRollResponse&/* r */ ) try { syslog(LOG_INFO, "MarkLastPhotoInRoll request from %s with mergedelta=%d", macaddress.c_str(), mergedelta ); std::string cmd = eyekinfig_t(macaddress).get_on_mark_last_photo_in_roll(); if(!cmd.empty()) { if(detached_child()) { putenv( gnu::autosprintf("EYEFI_MACADDRESS=%s",macaddress.c_str()) ); putenv( gnu::autosprintf("EYEFI_MERGEDELTA=%d",mergedelta) ); char *argv[] = { (char*)"/bin/sh", (char*)"-c", (char*)cmd.c_str(), 0 }; execv("/bin/sh",argv); syslog(LOG_ERR,"Failed to execute '%s'",cmd.c_str()); _exit(-1); } } keep_alive = 0; return SOAP_OK; }catch(const std::exception& e) { return E(this,"MarkLastPhotoInRoll",e); } int eyefiworker::UploadPhoto( int fileid, std::string macaddress, std::string filename, long filesize, std::string filesignature, std::string encryption, int flags, struct rns__UploadPhotoResponse& r ) try { syslog(LOG_INFO, "UploadPhoto request from %s with fileid=%d, filename=%s, filesize=%ld," " filesignature=%s, encryption=%s, flags=%04X", macaddress.c_str(), fileid, filename.c_str(), filesize, filesignature.c_str(), encryption.c_str(), flags ); std::string::size_type fnl=filename.length(); if(fnl<sizeof(".tar") || strncmp(filename.c_str()+fnl-sizeof(".tar")+sizeof(""),".tar",sizeof(".tar"))) throw std::runtime_error(gnu::autosprintf("honestly, I expected the tarball coming here, not '%s'",filename.c_str())); std::string the_file(filename,0,fnl-sizeof(".tar")+sizeof("")); std::string the_log = the_file+".log"; eyekinfig_t eyekinfig(macaddress); umask(eyekinfig.get_umask()); std::string td = eyekinfig.get_targetdir(); tmpdir_t indir(td+"/.incoming.XXXXXX"); std::string tf,lf; binary_t digest, idigest; #ifdef HAVE_SQLITE bool beenthere = false; #endif for(soap_multipart::iterator i=mime.begin(),ie=mime.end();i!=ie;++i) { #ifndef NDEBUG syslog(LOG_DEBUG, " MIME attachment with id=%s, type=%s, size=%ld", (*i).id, (*i).type, (long)(*i).size ); #endif if((*i).id && !strcmp((*i).id,"INTEGRITYDIGEST")) { std::string idigestr((*i).ptr,(*i).size); #ifndef NDEBUG syslog(LOG_DEBUG, " INTEGRITYDIGEST=%s", idigestr.c_str()); #endif idigest.from_hex(idigestr); } if( (*i).id && !strcmp((*i).id,"FILENAME") ) { assert( (*i).type && !strcmp((*i).type,"application/x-tar") ); #ifdef III_SAVE_TARS std::string tarfile = indir.get_file(filename); { std::ofstream(tarfile.c_str(),std::ios::out|std::ios::binary).write((*i).ptr,(*i).size); } #endif if(!tf.empty()) throw std::runtime_error("already seen tarball"); if(!digest.empty()) throw std::runtime_error("already have integrity digest"); digest = integrity_digest((*i).ptr,(*i).size,eyekinfig.get_upload_key()); #ifndef NDEBUG syslog(LOG_DEBUG," computed integrity digest=%s", digest.hex().c_str()); #endif #ifdef HAVE_SQLITE if(!(*i).size) { if(!already.is(filename,filesignature,filesize)) throw std::runtime_error("got zero-length upload for unknown file"); beenthere = true; continue; } #endif tarchive_t a((*i).ptr,(*i).size); while(a.read_next_header()) { std::string ep = a.entry_pathname(), f = indir.get_file(ep); if(ep==the_file) tf = f; else if(ep==the_log) lf = f; else continue; int fd=open(f.c_str(),O_CREAT|O_WRONLY,0666); if(fd<0) throw std::runtime_error(gnu::autosprintf("failed to create output file '%s'",f.c_str())); if(!a.read_data_into_fd(fd)) throw std::runtime_error(gnu::autosprintf("failed to untar file into '%s'",f.c_str())); close(fd); } } } #ifdef HAVE_SQLITE if(beenthere) { r.success=true; return SOAP_OK; } #endif if(tf.empty()) throw std::runtime_error("haven't seen THE file"); if(digest!=idigest) throw std::runtime_error("integrity digest verification failed"); std::string::size_type ls = tf.rfind('/'); // XXX: actually, lack of '/' signifies error here std::string tbn = (ls==std::string::npos)?tf:tf.substr(ls+1); ls = lf.rfind('/'); std::string lbn = (ls==std::string::npos)?lf:lf.substr(ls+1); std::string ttf,tlf; bool success = false; for(int i=0;i<32767;++i) { const char *fmt = i ? "%1$s/(%3$05d)%2$s" : "%1$s/%2$s"; ttf = (const char*)gnu::autosprintf(fmt,td.c_str(),tbn.c_str(),i); if(!lf.empty()) tlf = (const char*)gnu::autosprintf(fmt,td.c_str(),lbn.c_str(),i); if( (!link(tf.c_str(),ttf.c_str())) && (lf.empty() || !link(lf.c_str(),tlf.c_str())) ) { unlink(tf.c_str()); if(!lf.empty()) unlink(lf.c_str()); success=true; break; } } std::string cmd = eyekinfig.get_on_upload_photo(); if(success) { #ifdef HAVE_SQLITE { iiidb_t D(eyekinfig); D.prepare( "INSERT INTO photo" " (ctime,mac,fileid,filename,filesize,filesignature,encryption,flags)" " VALUES" " (:ctime,:mac,:fileid,:filename,:filesize,:filesignature,:encryption,:flags)" ).bind(":ctime",time(0)) .bind(":mac",macaddress) .bind(":fileid",fileid).bind(":filename",filename) .bind(":filesize",filesize).bind(":filesignature",filesignature) .bind(":encryption",encryption).bind(":flags",flags) .step(); } #endif /* HAVE_SQLITE */ if((!cmd.empty()) && detached_child()) { putenv( gnu::autosprintf("EYEFI_UPLOADED_ORIG=%s",tbn.c_str()) ); putenv( gnu::autosprintf("EYEFI_MACADDRESS=%s",macaddress.c_str()) ); putenv( gnu::autosprintf("EYEFI_UPLOADED=%s",ttf.c_str()) ); if(!lf.empty()) putenv( gnu::autosprintf("EYEFI_LOG=%s",tlf.c_str()) ); char *argv[] = { (char*)"/bin/sh", (char*)"-c", (char*)cmd.c_str(), 0 }; execv("/bin/sh",argv); syslog(LOG_ERR,"Failed to execute '%s'",cmd.c_str()); _exit(-1); } } r.success = true; return SOAP_OK; }catch(const std::exception& e) { return E(this,"UploadPhoto",e); } <commit_msg>moved sqlite initialization<commit_after>#include <signal.h> #ifndef NDEBUG # include <sys/resource.h> #endif #include <syslog.h> #include <cassert> #include <iostream> #include <fstream> #include <stdexcept> #include <iterator> #include <algorithm> #include <sys/wait.h> #include <autosprintf.h> #include "eyekinfig.h" #include "eyetil.h" #include "eyefiworker.h" #ifdef HAVE_SQLITE # include "iiidb.h" #endif eyefiworker::eyefiworker() : eyefiService(SOAP_IO_STORE|SOAP_IO_KEEPALIVE) { bind_flags = SO_REUSEADDR; max_keep_alive = 0; socket_flags = #if defined(MSG_NOSIGNAL) MSG_NOSIGNAL #elif defined(SO_NOSIGPIPE) SO_NOSIGPIPE #else #error Something is wrong with sigpipe prevention on the platform #endif ; #ifdef HAVE_SQLITE sqlite3_initialize(); #endif } eyefiworker::~eyefiworker() { } int eyefiworker::run(int bindport) { if(!soap_valid_socket(bind(0,bindport,64))) throw std::runtime_error("failed to bind()"); signal(SIGCHLD,SIG_IGN); while(true) { if(!soap_valid_socket(accept())) throw std::runtime_error("failed to accept()"); pid_t p = fork(); if(p<0) throw std::runtime_error("failed to fork()"); if(!p) { recv_timeout = 600; send_timeout = 120; (void)serve(); soap_destroy(this); soap_end(this); soap_done(this); #ifndef NDEBUG struct rusage ru; if(getrusage(RUSAGE_SELF,&ru)) { syslog(LOG_NOTICE,"Failed to getrusage(): %d",errno); }else{ syslog(LOG_INFO,"maxrss: %ld\n",ru.ru_maxrss); } #endif /* NDEBUG */ throw throwable_exit(0); } close(socket); socket = SOAP_INVALID_SOCKET; } } static binary_t session_nonce; #ifdef HAVE_SQLITE static struct { std::string filesignature; long filesize; std::string filename; inline void reset() { filesignature.erase(); filename.erase(); filesize=0; } inline void set(const std::string n,const std::string sig,long siz) { filename = n; filesignature = sig; filesize = siz; } inline bool is(const std::string n,const std::string sig,long siz) { return filesize==siz && filename==n && filesignature==sig; } } already; #endif /* HAVE_SQLITE */ static bool detached_child() { pid_t p = fork(); if(p<0) { syslog(LOG_ERR,"Failed to fork away for hook execution"); _exit(-1); } if(!p) { setsid(); for(int i=getdtablesize();i>=0;--i) close(i); int i=open("/dev/null",O_RDWR); assert(i==0); i = dup(i); assert(i==1); i = dup(i); assert(i==2); return true; } return false; } static int E(eyefiworker* efs,const char *c,const std::exception& e) { efs->keep_alive=0; syslog(LOG_ERR,"error while processing %s: %s",c,e.what()); return soap_sender_fault(efs,gnu::autosprintf("error processing %s",c),0); } int eyefiworker::StartSession( std::string macaddress,std::string cnonce, int transfermode,long transfermodetimestamp, struct rns__StartSessionResponse &r ) try { syslog(LOG_INFO, "StartSession request from %s with cnonce=%s, transfermode=%d, transfermodetimestamp=%ld", macaddress.c_str(), cnonce.c_str(), transfermode, transfermodetimestamp ); eyekinfig_t eyekinfig(macaddress); r.credential = binary_t(macaddress+cnonce+eyekinfig.get_upload_key()).md5().hex(); r.snonce = session_nonce.make_nonce().hex(); r.transfermode=transfermode; r.transfermodetimestamp=transfermodetimestamp; r.upsyncallowed=false; std::string cmd = eyekinfig.get_on_start_session(); if(!cmd.empty()) { if(detached_child()) { putenv( gnu::autosprintf("EYEFI_MACADDRESS=%s",macaddress.c_str()) ); putenv( gnu::autosprintf("EYEFI_TRANSFERMODE=%d",transfermode) ); putenv( gnu::autosprintf("EYEFI_TRANSFERMODETIMESTAMP=%ld",transfermodetimestamp) ); char *argv[] = { (char*)"/bin/sh", (char*)"-c", (char*)cmd.c_str(), 0 }; execv("/bin/sh",argv); syslog(LOG_ERR,"Failed to execute '%s'",cmd.c_str()); _exit(-1); } } return SOAP_OK; }catch(const std::exception& e) { return E(this,"StartSession",e); } int eyefiworker::GetPhotoStatus( std::string credential, std::string macaddress, std::string filename, long filesize, std::string filesignature, int flags, struct rns__GetPhotoStatusResponse &r ) try { syslog(LOG_INFO, "GetPhotoStatus request from %s with credential=%s, filename=%s, filesize=%ld, filesignature=%s, flags=%d; session nonce=%s", macaddress.c_str(), credential.c_str(), filename.c_str(), filesize, filesignature.c_str(), flags, session_nonce.hex().c_str() ); eyekinfig_t eyekinfig(macaddress); std::string computed_credential = binary_t(macaddress+eyekinfig.get_upload_key()+session_nonce.hex()).md5().hex(); #ifndef NDEBUG syslog(LOG_DEBUG, " computed credential=%s", computed_credential.c_str()); #endif if (credential != computed_credential) throw std::runtime_error("card authentication failed"); #ifdef HAVE_SQLITE iiidb_t D(eyekinfig); seclude::stmt_t S = D.prepare( "SELECT fileid FROM photo" " WHERE mac=:mac AND filename=:filename" " AND filesize=:filesize AND filesignature=:filesignature" ).bind(":mac",macaddress) .bind(":filename",filename).bind(":filesize",filesize) .bind(":filesignature",filesignature); if(!S.step()) { r.fileid = 1; r.offset = 0; }else{ r.fileid = S.column<long>(0); r.offset = filesize; already.set(filename,filesignature,filesize); } #else /* HAVE_SQLITE */ r.fileid=1, r.offset=0; #endif /* HAVE_SQLITE */ return SOAP_OK; }catch(const std::exception& e) { return E(this,"GetPhotoStatus",e); } int eyefiworker::MarkLastPhotoInRoll( std::string macaddress, int mergedelta, struct rns__MarkLastPhotoInRollResponse&/* r */ ) try { syslog(LOG_INFO, "MarkLastPhotoInRoll request from %s with mergedelta=%d", macaddress.c_str(), mergedelta ); std::string cmd = eyekinfig_t(macaddress).get_on_mark_last_photo_in_roll(); if(!cmd.empty()) { if(detached_child()) { putenv( gnu::autosprintf("EYEFI_MACADDRESS=%s",macaddress.c_str()) ); putenv( gnu::autosprintf("EYEFI_MERGEDELTA=%d",mergedelta) ); char *argv[] = { (char*)"/bin/sh", (char*)"-c", (char*)cmd.c_str(), 0 }; execv("/bin/sh",argv); syslog(LOG_ERR,"Failed to execute '%s'",cmd.c_str()); _exit(-1); } } keep_alive = 0; return SOAP_OK; }catch(const std::exception& e) { return E(this,"MarkLastPhotoInRoll",e); } int eyefiworker::UploadPhoto( int fileid, std::string macaddress, std::string filename, long filesize, std::string filesignature, std::string encryption, int flags, struct rns__UploadPhotoResponse& r ) try { syslog(LOG_INFO, "UploadPhoto request from %s with fileid=%d, filename=%s, filesize=%ld," " filesignature=%s, encryption=%s, flags=%04X", macaddress.c_str(), fileid, filename.c_str(), filesize, filesignature.c_str(), encryption.c_str(), flags ); std::string::size_type fnl=filename.length(); if(fnl<sizeof(".tar") || strncmp(filename.c_str()+fnl-sizeof(".tar")+sizeof(""),".tar",sizeof(".tar"))) throw std::runtime_error(gnu::autosprintf("honestly, I expected the tarball coming here, not '%s'",filename.c_str())); std::string the_file(filename,0,fnl-sizeof(".tar")+sizeof("")); std::string the_log = the_file+".log"; eyekinfig_t eyekinfig(macaddress); umask(eyekinfig.get_umask()); std::string td = eyekinfig.get_targetdir(); tmpdir_t indir(td+"/.incoming.XXXXXX"); std::string tf,lf; binary_t digest, idigest; #ifdef HAVE_SQLITE bool beenthere = false; #endif for(soap_multipart::iterator i=mime.begin(),ie=mime.end();i!=ie;++i) { #ifndef NDEBUG syslog(LOG_DEBUG, " MIME attachment with id=%s, type=%s, size=%ld", (*i).id, (*i).type, (long)(*i).size ); #endif if((*i).id && !strcmp((*i).id,"INTEGRITYDIGEST")) { std::string idigestr((*i).ptr,(*i).size); #ifndef NDEBUG syslog(LOG_DEBUG, " INTEGRITYDIGEST=%s", idigestr.c_str()); #endif idigest.from_hex(idigestr); } if( (*i).id && !strcmp((*i).id,"FILENAME") ) { assert( (*i).type && !strcmp((*i).type,"application/x-tar") ); #ifdef III_SAVE_TARS std::string tarfile = indir.get_file(filename); { std::ofstream(tarfile.c_str(),std::ios::out|std::ios::binary).write((*i).ptr,(*i).size); } #endif if(!tf.empty()) throw std::runtime_error("already seen tarball"); if(!digest.empty()) throw std::runtime_error("already have integrity digest"); digest = integrity_digest((*i).ptr,(*i).size,eyekinfig.get_upload_key()); #ifndef NDEBUG syslog(LOG_DEBUG," computed integrity digest=%s", digest.hex().c_str()); #endif #ifdef HAVE_SQLITE if(!(*i).size) { if(!already.is(filename,filesignature,filesize)) throw std::runtime_error("got zero-length upload for unknown file"); beenthere = true; continue; } #endif tarchive_t a((*i).ptr,(*i).size); while(a.read_next_header()) { std::string ep = a.entry_pathname(), f = indir.get_file(ep); if(ep==the_file) tf = f; else if(ep==the_log) lf = f; else continue; int fd=open(f.c_str(),O_CREAT|O_WRONLY,0666); if(fd<0) throw std::runtime_error(gnu::autosprintf("failed to create output file '%s'",f.c_str())); if(!a.read_data_into_fd(fd)) throw std::runtime_error(gnu::autosprintf("failed to untar file into '%s'",f.c_str())); close(fd); } } } #ifdef HAVE_SQLITE if(beenthere) { r.success=true; return SOAP_OK; } #endif if(tf.empty()) throw std::runtime_error("haven't seen THE file"); if(digest!=idigest) throw std::runtime_error("integrity digest verification failed"); std::string::size_type ls = tf.rfind('/'); // XXX: actually, lack of '/' signifies error here std::string tbn = (ls==std::string::npos)?tf:tf.substr(ls+1); ls = lf.rfind('/'); std::string lbn = (ls==std::string::npos)?lf:lf.substr(ls+1); std::string ttf,tlf; bool success = false; for(int i=0;i<32767;++i) { const char *fmt = i ? "%1$s/(%3$05d)%2$s" : "%1$s/%2$s"; ttf = (const char*)gnu::autosprintf(fmt,td.c_str(),tbn.c_str(),i); if(!lf.empty()) tlf = (const char*)gnu::autosprintf(fmt,td.c_str(),lbn.c_str(),i); if( (!link(tf.c_str(),ttf.c_str())) && (lf.empty() || !link(lf.c_str(),tlf.c_str())) ) { unlink(tf.c_str()); if(!lf.empty()) unlink(lf.c_str()); success=true; break; } } std::string cmd = eyekinfig.get_on_upload_photo(); if(success) { #ifdef HAVE_SQLITE { iiidb_t D(eyekinfig); D.prepare( "INSERT INTO photo" " (ctime,mac,fileid,filename,filesize,filesignature,encryption,flags)" " VALUES" " (:ctime,:mac,:fileid,:filename,:filesize,:filesignature,:encryption,:flags)" ).bind(":ctime",time(0)) .bind(":mac",macaddress) .bind(":fileid",fileid).bind(":filename",filename) .bind(":filesize",filesize).bind(":filesignature",filesignature) .bind(":encryption",encryption).bind(":flags",flags) .step(); } #endif /* HAVE_SQLITE */ if((!cmd.empty()) && detached_child()) { putenv( gnu::autosprintf("EYEFI_UPLOADED_ORIG=%s",tbn.c_str()) ); putenv( gnu::autosprintf("EYEFI_MACADDRESS=%s",macaddress.c_str()) ); putenv( gnu::autosprintf("EYEFI_UPLOADED=%s",ttf.c_str()) ); if(!lf.empty()) putenv( gnu::autosprintf("EYEFI_LOG=%s",tlf.c_str()) ); char *argv[] = { (char*)"/bin/sh", (char*)"-c", (char*)cmd.c_str(), 0 }; execv("/bin/sh",argv); syslog(LOG_ERR,"Failed to execute '%s'",cmd.c_str()); _exit(-1); } } r.success = true; return SOAP_OK; }catch(const std::exception& e) { return E(this,"UploadPhoto",e); } <|endoftext|>
<commit_before>#include <windows.h> #include <winsock.h> #include <string> using std::string; #include <iostream> using std::cout; using std::endl; using std::cin; namespace rsa { const int WSVERS = MAKEWORD(2, 0); auto make_remote_address(char* arr[]) -> struct sockaddr_in { struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_addr.s_addr = inet_addr(arr[1]); //IP address address.sin_port = htons((u_short)atoi(arr[2]));//Port number address.sin_family = AF_INET; return address; } auto handle_user_input(int arguments_count) -> void { if (arguments_count != 3) { cout << "USAGE: client IP-address port" << endl; exit(1); } } auto setup_win_sock_api(WORD version_required) -> WSADATA { WSADATA wsadata; if (WSAStartup(WSVERS, &wsadata) != 0) { WSACleanup(); cout << "WSAStartup failed\n"; exit(1); } return wsadata; } //return the string received auto receive(SOCKET s) -> string { auto received = string(); //receive char by char, end on an LF, ignore CR's for (auto ch = char(0); true; /* */) { if (0 >= recv(s, &ch, 1, 0)) { cout << "recv failed\n"; exit(1); } if (ch == '\n') break; else if (ch == '\r') continue; else received.push_back(ch); } return received; } }//namespace rsa auto main(int argc, char *argv[]) -> int { rsa::handle_user_input(argc); auto wsa_data = rsa::setup_win_sock_api(rsa::WSVERS); auto remoteaddr = rsa::make_remote_address(argv); //CREATE CLIENT'S SOCKET auto s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { cout << "socket failed\n"; exit(1); } //CONNECT if (connect(s, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr)) != 0) { cout << "connect failed\n"; exit(1); } for (auto send_buffer = string{}; cin >> send_buffer; /* */) { if (send_buffer == ".") break; else send_buffer += "\r\n"; //SEND auto bytes_sent = send(s, send_buffer.c_str(), send_buffer.size(), 0); if (bytes_sent < 0) { cout << "send failed\n"; exit(1); } //receive cout << rsa::receive(s) << endl; } closesocket(s); return 0; }<commit_msg> modified: client/client.cpp<commit_after>#include <windows.h> #include <winsock.h> #include <string> using std::string; #include <iostream> using std::cout; using std::endl; using std::cin; namespace rsa { const int WSVERS = MAKEWORD(2, 0); auto make_remote_address(char* arr[]) -> sockaddr_in { struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_addr.s_addr = inet_addr(arr[1]); //IP address address.sin_port = htons((u_short)atoi(arr[2]));//Port number address.sin_family = AF_INET; return address; } auto handle_user_input(int arguments_count) -> void { if (arguments_count != 3) { cout << "USAGE: client IP-address port" << endl; exit(1); } } auto setup_win_sock_api(WORD version_required) -> WSADATA { WSADATA wsadata; if (WSAStartup(WSVERS, &wsadata) != 0) { WSACleanup(); cout << "WSAStartup failed\n"; exit(1); } return wsadata; } //return the string received auto receive(SOCKET s) -> string { auto received = string(); //receive char by char, end on an LF, ignore CR's for (auto ch = char(0); true; /* */) { if (0 >= recv(s, &ch, 1, 0)) { cout << "recv failed\n"; exit(1); } if (ch == '\n') break; else if (ch == '\r') continue; else received.push_back(ch); } return received; } }//namespace rsa auto main(int argc, char *argv[]) -> int { rsa::handle_user_input(argc); auto wsa_data = rsa::setup_win_sock_api(rsa::WSVERS); auto remoteaddr = rsa::make_remote_address(argv); //CREATE CLIENT'S SOCKET auto s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { cout << "socket failed\n"; exit(1); } //CONNECT if (connect(s, (struct sockaddr *)&remoteaddr, sizeof(remoteaddr)) != 0) { cout << "connect failed\n"; exit(1); } for (auto send_buffer = string{}; cin >> send_buffer; /* */) { if (send_buffer == ".") break; else send_buffer += "\r\n"; //SEND auto bytes_sent = send(s, send_buffer.c_str(), send_buffer.size(), 0); if (bytes_sent < 0) { cout << "send failed\n"; exit(1); } //receive cout << rsa::receive(s) << endl; } closesocket(s); return 0; }<|endoftext|>
<commit_before>#include <windows.h> #include <winsock.h> #include <string> using std::string; #include <iostream> using std::cout; using std::endl; using std::cin; namespace as3 { const int WSVERS = MAKEWORD(2, 0); class Socket { public: explicit Socket(SOCKET s) : socket_{ s } {} Socket(int address_family, int type, int protocol) : socket_{ ::socket(address_family, type, protocol) } {} auto get() const -> SOCKET { return socket_; } auto is_failed() const -> bool { return socket_ < 0; } ~Socket(){ ::closesocket(socket_); } private: const SOCKET socket_; }; auto make_remote_address(char* arr[]) -> sockaddr_in { struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_addr.s_addr = inet_addr(arr[1]); //IP address address.sin_port = htons((u_short)atoi(arr[2]));//Port number address.sin_family = AF_INET; return address; } auto handle_user_input(int arguments_count) -> void { if (arguments_count != 3) { cout << "USAGE: client IP-address port" << endl; exit(1); } } auto setup_win_sock_api(WORD version_required) -> WSADATA { WSADATA wsadata; if (WSAStartup(WSVERS, &wsadata) != 0) { WSACleanup(); cout << "WSAStartup failed\n"; exit(1); } return wsadata; } auto connect(as3::Socket const& s, sockaddr_in const& remote_addr) -> void { if (0 != ::connect(s.get(), (sockaddr*)&remote_addr, sizeof(remote_addr))) { cout << "connect failed\n"; exit(1); } } //return the string received auto receive(SOCKET s) -> string { auto received = string(); for (auto ch = char(0); true; /* */)//receive char by char, end on an LF, ignore CR's { if (0 >= recv(s, &ch, 1, 0)) { cout << "recv failed\n"; exit(1); } if (ch == '\n') break; else if (ch == '\r') continue; else received.push_back(ch); } return received; } auto send(SOCKET sock, string const& send_buffer) -> void { auto bytes_sent = ::send(sock, send_buffer.c_str(), send_buffer.size(), 0); if (bytes_sent < 0) { cout << "send failed\n"; exit(1); } } }//namespace rsa auto main(int argc, char *argv[]) -> int { //handle arugments as3::handle_user_input(argc); //init auto wsa_data = as3::setup_win_sock_api(as3::WSVERS); auto remote_addr = as3::make_remote_address(argv); auto sock = as3::Socket{ AF_INET, SOCK_STREAM, 0 }; //connect as3::connect(sock, remote_addr); for (auto input = string{}; cin >> input && input != "."; /* */) { as3::send(sock.get(), input + "\r\n"); cout << as3::receive(sock.get()) << endl; } return 0; }<commit_msg>use traditinal way to construct socket and add detele<commit_after>#include <windows.h> #include <winsock.h> #include <string> using std::string; #include <iostream> using std::cout; using std::endl; using std::cin; namespace as3 { const int WSVERS = MAKEWORD(2, 0); class Socket { public: explicit Socket(SOCKET s) : socket_{ s } {} Socket(int address_family, int type, int protocol) : socket_{ ::socket(address_family, type, protocol) } {} auto get() const -> SOCKET { return socket_; } auto is_failed() const -> bool { return socket_ < 0; } ~Socket(){ ::closesocket(socket_); } Socket(Socket const&) = delete; Socket(Socket &&) = delete; Socket& operator=(Socket const&) = delete; Socket& operator=(Socket &&) = delete; private: const SOCKET socket_; }; auto make_remote_address(char* arr[]) -> sockaddr_in { struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_addr.s_addr = inet_addr(arr[1]); //IP address address.sin_port = htons((u_short)atoi(arr[2]));//Port number address.sin_family = AF_INET; return address; } auto handle_user_input(int arguments_count) -> void { if (arguments_count != 3) { cout << "USAGE: client IP-address port" << endl; exit(1); } } auto setup_win_sock_api(WORD version_required) -> WSADATA { WSADATA wsadata; if (WSAStartup(WSVERS, &wsadata) != 0) { WSACleanup(); cout << "WSAStartup failed\n"; exit(1); } return wsadata; } auto connect(as3::Socket const& s, sockaddr_in const& remote_addr) -> void { if (0 != ::connect(s.get(), (sockaddr*)&remote_addr, sizeof(remote_addr))) { cout << "connect failed\n"; exit(1); } } //return the string received auto receive(SOCKET s) -> string { auto received = string(); for (auto ch = char(0); true; /* */)//receive char by char, end on an LF, ignore CR's { if (0 >= recv(s, &ch, 1, 0)) { cout << "recv failed\n"; exit(1); } if (ch == '\n') break; else if (ch == '\r') continue; else received.push_back(ch); } return received; } auto send(SOCKET sock, string const& send_buffer) -> void { auto bytes_sent = ::send(sock, send_buffer.c_str(), send_buffer.size(), 0); if (bytes_sent < 0) { cout << "send failed\n"; exit(1); } } }//namespace rsa auto main(int argc, char *argv[]) -> int { //handle arugments as3::handle_user_input(argc); //init auto wsa_data = as3::setup_win_sock_api(as3::WSVERS); auto remote_addr = as3::make_remote_address(argv); as3::Socket sock{ AF_INET, SOCK_STREAM, 0 }; //connect as3::connect(sock, remote_addr); for (auto input = string{}; cin >> input && input != "."; /* */) { as3::send(sock.get(), input + "\r\n"); cout << as3::receive(sock.get()) << endl; } return 0; }<|endoftext|>
<commit_before>/* Copyright 2012 Joe Hermaszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Joe Hermaszewski. */ #include "generic_value.hpp" #include <cassert> #include <string> #include <utility> #include <vector> #include <compiler/code_generator.hpp> #include <engine/types.hpp> #include <engine/internal/type_properties.hpp> namespace JoeLang { namespace Compiler { GenericValue::GenericValue() :m_Type( Type::UNKNOWN ) { } GenericValue::GenericValue( const GenericValue& g ) :m_Type( Type::UNKNOWN ) { *this = g; } GenericValue::GenericValue( Type type ) :m_Type( type ) { switch( m_Type ) { case Type::STRING: new(&m_StringValue) std::string; break; case Type::ARRAY: new(&m_ArrayValue) std::vector<GenericValue>; break; default: break; } } const GenericValue& GenericValue::operator = ( const GenericValue& g ) { FreeData(); switch( g.m_Type ) { case Type::UNKNOWN: break; case Type::BOOL: m_BoolValue = g.m_BoolValue; break; case Type::I8: m_I8Value = g.m_I8Value; break; case Type::I16: m_I16Value = g.m_I16Value; break; case Type::I32: m_I32Value = g.m_I32Value; break; case Type::I64: m_I64Value = g.m_I64Value; break; case Type::U8: m_U8Value = g.m_U8Value; break; case Type::U16: m_U16Value = g.m_U16Value; break; case Type::U32: m_U32Value = g.m_U32Value; break; case Type::U64: m_U64Value = g.m_U64Value; break; case Type::FLOAT: m_FloatValue = g.m_FloatValue; break; case Type::FLOAT4: m_Float4Value = g.m_Float4Value; break; case Type::DOUBLE: m_DoubleValue = g.m_DoubleValue; break; case Type::STRING: new(&m_StringValue) std::string; m_StringValue = g.m_StringValue; break; case Type::ARRAY: new(&m_ArrayValue) std::vector<GenericValue>; m_ArrayValue = g.m_ArrayValue; break; default: assert( false && "Assigning from GenericValue with an unhandled Type" ); break; } m_Type = g.m_Type; return *this; } GenericValue::GenericValue( jl_bool bool_value ) :m_Type( Type::BOOL ) ,m_BoolValue( bool_value ) { } GenericValue::GenericValue( jl_i8 i8_value ) :m_Type( Type::I8 ) ,m_I8Value( i8_value ) { } GenericValue::GenericValue( jl_i16 i16_value ) :m_Type( Type::I16 ) ,m_I16Value( i16_value ) { } GenericValue::GenericValue( jl_i32 i32_value ) :m_Type( Type::I32 ) ,m_I32Value( i32_value ) { } GenericValue::GenericValue( jl_i64 i64_value ) :m_Type( Type::I64 ) ,m_I64Value( i64_value ) { } GenericValue::GenericValue( jl_u8 u8_value ) :m_Type( Type::U8 ) ,m_U8Value( u8_value ) { } GenericValue::GenericValue( jl_u16 u16_value ) :m_Type( Type::U16 ) ,m_U16Value( u16_value ) { } GenericValue::GenericValue( jl_u32 u32_value ) :m_Type( Type::U32 ) ,m_U32Value( u32_value ) { } GenericValue::GenericValue( jl_u64 u64_value ) :m_Type( Type::U64 ) ,m_U64Value( u64_value ) { } GenericValue::GenericValue( jl_float float_value ) :m_Type( Type::FLOAT ) ,m_FloatValue( float_value ) { } GenericValue::GenericValue( jl_float4 float4_value ) :m_Type( Type::FLOAT4 ) ,m_Float4Value( float4_value ) { } GenericValue::GenericValue( jl_double double_value ) :m_Type( Type::DOUBLE ) ,m_DoubleValue( double_value ) { } GenericValue::GenericValue( jl_string&& string_value ) :m_Type( Type::STRING ) ,m_StringValue( reinterpret_cast<const char*>(string_value.data), string_value.size ) { delete[] string_value.data; string_value.size = 0; string_value.data = nullptr; } GenericValue::GenericValue( std::string string_value ) :m_Type( Type::STRING ) ,m_StringValue( std::move(string_value) ) { } GenericValue::GenericValue( std::vector<GenericValue> array_value ) :m_Type( Type::ARRAY ) ,m_ArrayValue( std::move(array_value) ) { #ifndef NDEBUG assert( !m_ArrayValue.empty() && "GenericValue given an empty array value" ); /// TODO verify that the values are of the same extents and types #endif } GenericValue::~GenericValue() { FreeData(); } llvm::Constant* GenericValue::CodeGen( CodeGenerator& code_gen ) const { switch( m_Type ) { case Type::BOOL: return code_gen.CreateInteger( m_BoolValue, Type::BOOL ); case Type::I8: return code_gen.CreateInteger( m_I8Value, Type::I8 ); case Type::I16: return code_gen.CreateInteger( m_I16Value, Type::I16 ); case Type::I32: return code_gen.CreateInteger( m_I32Value, Type::I32 ); case Type::I64: return code_gen.CreateInteger( m_I64Value, Type::I64 ); case Type::U8: return code_gen.CreateInteger( m_U8Value, Type::U8 ); case Type::U16: return code_gen.CreateInteger( m_U16Value, Type::U16 ); case Type::U32: return code_gen.CreateInteger( m_U32Value, Type::U32 ); case Type::U64: return code_gen.CreateInteger( m_U64Value, Type::U64 ); case Type::FLOAT: return code_gen.CreateFloating( m_FloatValue, Type::FLOAT ); case Type::FLOAT4: { std::vector<double> values( &m_Float4Value[0], &m_Float4Value[0]+4 ); return code_gen.CreateFloatingVector( values, Type::FLOAT4 ); } case Type::DOUBLE: return code_gen.CreateFloating( m_DoubleValue, Type::DOUBLE ); case Type::STRING: return code_gen.CreateString( m_StringValue ); case Type::ARRAY: return code_gen.CreateArray( m_ArrayValue ); default: assert( false && "Trying to codegen an unhandled type" ); } return nullptr; } Type GenericValue::GetType() const { return m_Type; } Type GenericValue::GetUnderlyingType() const { if( m_Type == Type::ARRAY ) { assert( !m_ArrayValue.empty() && "Trying to get the underlying type of an empty array " "genericvalue" ); return m_ArrayValue[0].GetUnderlyingType(); } return m_Type; } std::vector<unsigned> GenericValue::GetArrayExtents() const { if( m_Type == Type::ARRAY ) { assert( !m_ArrayValue.empty() && "Trying to get the array extents of an empty array " "genericvalue" ); std::vector<unsigned> ret = { static_cast<unsigned>( m_ArrayValue.size() ) }; const std::vector<unsigned>& sub_extents = m_ArrayValue[0].GetArrayExtents(); ret.insert( ret.end(), sub_extents.begin(), sub_extents.end() ); return ret; } return {}; } jl_bool GenericValue::GetBool() const { assert( m_Type == Type::BOOL && "Trying to get the bool value from a non-bool GenericValue" ); return m_BoolValue; } jl_i8 GenericValue::GetI8() const { assert( m_Type == Type::I8 && "Trying to get the i8 value from a non-i8 GenericValue" ); return m_I8Value; } jl_i16 GenericValue::GetI16() const { assert( m_Type == Type::I16 && "Trying to get the i16 value from a non-i16 GenericValue" ); return m_I16Value; } jl_i32 GenericValue::GetI32() const { assert( m_Type == Type::I32 && "Trying to get the i32 value from a non-i32 GenericValue" ); return m_I32Value; } jl_i64 GenericValue::GetI64() const { assert( m_Type == Type::I64 && "Trying to get the i64 value from a non-i64 GenericValue" ); return m_I64Value; } jl_u8 GenericValue::GetU8() const { assert( m_Type == Type::U8 && "Trying to get the u8 value from a non-u8 GenericValue" ); return m_U8Value; } jl_u16 GenericValue::GetU16() const { assert( m_Type == Type::U16 && "Trying to get the u16 value from a non-u16 GenericValue" ); return m_U16Value; } jl_u32 GenericValue::GetU32() const { assert( m_Type == Type::U32 && "Trying to get the u32 value from a non-u32 GenericValue" ); return m_U32Value; } jl_u64 GenericValue::GetU64() const { assert( m_Type == Type::U64 && "Trying to get the u64 value from a non-u64 GenericValue" ); return m_U64Value; } jl_float GenericValue::GetFloat() const { assert( m_Type == Type::FLOAT && "Trying to get the float value from a non-float GenericValue" ); return m_FloatValue; } jl_float4 GenericValue::GetFloat4() const { assert( m_Type == Type::FLOAT4 && "Trying to get the float4 value from a non-float GenericValue" ); return m_Float4Value; } jl_double GenericValue::GetDouble() const { assert( m_Type == Type::DOUBLE && "Trying to get the double value from a non-double GenericValue" ); return m_DoubleValue; } const std::string& GenericValue::GetString() const { assert( m_Type == Type::STRING && "Trying to get the string value from a non-string GenericValue" ); return m_StringValue; } const std::vector<GenericValue>& GenericValue::GetArray() const { assert( m_Type == Type::ARRAY && "Trying to get the array value from a non-array GenericValue" ); return m_ArrayValue; } void GenericValue::FreeData() { using std::string; using std::vector; switch( m_Type ) { case Type::ARRAY: m_ArrayValue.~vector(); break; case Type::STRING: m_StringValue.~string(); break; default: break; } m_Type = Type::UNKNOWN; } } // namespace Compiler } // namespace JoeLang <commit_msg>[+] Checking array values<commit_after>/* Copyright 2012 Joe Hermaszewski. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Joe Hermaszewski. */ #include "generic_value.hpp" #include <cassert> #include <string> #include <utility> #include <vector> #include <compiler/code_generator.hpp> #include <engine/types.hpp> #include <engine/internal/type_properties.hpp> namespace JoeLang { namespace Compiler { GenericValue::GenericValue() :m_Type( Type::UNKNOWN ) { } GenericValue::GenericValue( const GenericValue& g ) :m_Type( Type::UNKNOWN ) { *this = g; } GenericValue::GenericValue( Type type ) :m_Type( type ) { switch( m_Type ) { case Type::STRING: new(&m_StringValue) std::string; break; case Type::ARRAY: new(&m_ArrayValue) std::vector<GenericValue>; break; default: break; } } const GenericValue& GenericValue::operator = ( const GenericValue& g ) { FreeData(); switch( g.m_Type ) { case Type::UNKNOWN: break; case Type::BOOL: m_BoolValue = g.m_BoolValue; break; case Type::I8: m_I8Value = g.m_I8Value; break; case Type::I16: m_I16Value = g.m_I16Value; break; case Type::I32: m_I32Value = g.m_I32Value; break; case Type::I64: m_I64Value = g.m_I64Value; break; case Type::U8: m_U8Value = g.m_U8Value; break; case Type::U16: m_U16Value = g.m_U16Value; break; case Type::U32: m_U32Value = g.m_U32Value; break; case Type::U64: m_U64Value = g.m_U64Value; break; case Type::FLOAT: m_FloatValue = g.m_FloatValue; break; case Type::FLOAT4: m_Float4Value = g.m_Float4Value; break; case Type::DOUBLE: m_DoubleValue = g.m_DoubleValue; break; case Type::STRING: new(&m_StringValue) std::string; m_StringValue = g.m_StringValue; break; case Type::ARRAY: new(&m_ArrayValue) std::vector<GenericValue>; m_ArrayValue = g.m_ArrayValue; break; default: assert( false && "Assigning from GenericValue with an unhandled Type" ); break; } m_Type = g.m_Type; return *this; } GenericValue::GenericValue( jl_bool bool_value ) :m_Type( Type::BOOL ) ,m_BoolValue( bool_value ) { } GenericValue::GenericValue( jl_i8 i8_value ) :m_Type( Type::I8 ) ,m_I8Value( i8_value ) { } GenericValue::GenericValue( jl_i16 i16_value ) :m_Type( Type::I16 ) ,m_I16Value( i16_value ) { } GenericValue::GenericValue( jl_i32 i32_value ) :m_Type( Type::I32 ) ,m_I32Value( i32_value ) { } GenericValue::GenericValue( jl_i64 i64_value ) :m_Type( Type::I64 ) ,m_I64Value( i64_value ) { } GenericValue::GenericValue( jl_u8 u8_value ) :m_Type( Type::U8 ) ,m_U8Value( u8_value ) { } GenericValue::GenericValue( jl_u16 u16_value ) :m_Type( Type::U16 ) ,m_U16Value( u16_value ) { } GenericValue::GenericValue( jl_u32 u32_value ) :m_Type( Type::U32 ) ,m_U32Value( u32_value ) { } GenericValue::GenericValue( jl_u64 u64_value ) :m_Type( Type::U64 ) ,m_U64Value( u64_value ) { } GenericValue::GenericValue( jl_float float_value ) :m_Type( Type::FLOAT ) ,m_FloatValue( float_value ) { } GenericValue::GenericValue( jl_float4 float4_value ) :m_Type( Type::FLOAT4 ) ,m_Float4Value( float4_value ) { } GenericValue::GenericValue( jl_double double_value ) :m_Type( Type::DOUBLE ) ,m_DoubleValue( double_value ) { } GenericValue::GenericValue( jl_string&& string_value ) :m_Type( Type::STRING ) ,m_StringValue( reinterpret_cast<const char*>(string_value.data), string_value.size ) { delete[] string_value.data; string_value.size = 0; string_value.data = nullptr; } GenericValue::GenericValue( std::string string_value ) :m_Type( Type::STRING ) ,m_StringValue( std::move(string_value) ) { } GenericValue::GenericValue( std::vector<GenericValue> array_value ) :m_Type( Type::ARRAY ) ,m_ArrayValue( std::move(array_value) ) { #ifndef NDEBUG assert( !m_ArrayValue.empty() && "GenericValue given an empty array value" ); const std::vector<unsigned>& extents = m_ArrayValue[0].GetArrayExtents(); Type underlying_type = m_ArrayValue[0].GetUnderlyingType(); for( unsigned i = 1; i < m_ArrayValue.size(); ++i ) { assert( underlying_type == m_ArrayValue[i].GetUnderlyingType() && "Array genericvalue created with mismatched types" ); assert( extents == m_ArrayValue[i].GetArrayExtents() && "Array genericvalue created with mismatched array extents" ); } #endif } GenericValue::~GenericValue() { FreeData(); } llvm::Constant* GenericValue::CodeGen( CodeGenerator& code_gen ) const { switch( m_Type ) { case Type::BOOL: return code_gen.CreateInteger( m_BoolValue, Type::BOOL ); case Type::I8: return code_gen.CreateInteger( m_I8Value, Type::I8 ); case Type::I16: return code_gen.CreateInteger( m_I16Value, Type::I16 ); case Type::I32: return code_gen.CreateInteger( m_I32Value, Type::I32 ); case Type::I64: return code_gen.CreateInteger( m_I64Value, Type::I64 ); case Type::U8: return code_gen.CreateInteger( m_U8Value, Type::U8 ); case Type::U16: return code_gen.CreateInteger( m_U16Value, Type::U16 ); case Type::U32: return code_gen.CreateInteger( m_U32Value, Type::U32 ); case Type::U64: return code_gen.CreateInteger( m_U64Value, Type::U64 ); case Type::FLOAT: return code_gen.CreateFloating( m_FloatValue, Type::FLOAT ); case Type::FLOAT4: { std::vector<double> values( &m_Float4Value[0], &m_Float4Value[0]+4 ); return code_gen.CreateFloatingVector( values, Type::FLOAT4 ); } case Type::DOUBLE: return code_gen.CreateFloating( m_DoubleValue, Type::DOUBLE ); case Type::STRING: return code_gen.CreateString( m_StringValue ); case Type::ARRAY: return code_gen.CreateArray( m_ArrayValue ); default: assert( false && "Trying to codegen an unhandled type" ); } return nullptr; } Type GenericValue::GetType() const { return m_Type; } Type GenericValue::GetUnderlyingType() const { if( m_Type == Type::ARRAY ) { assert( !m_ArrayValue.empty() && "Trying to get the underlying type of an empty array " "genericvalue" ); return m_ArrayValue[0].GetUnderlyingType(); } return m_Type; } std::vector<unsigned> GenericValue::GetArrayExtents() const { if( m_Type == Type::ARRAY ) { assert( !m_ArrayValue.empty() && "Trying to get the array extents of an empty array " "genericvalue" ); std::vector<unsigned> ret = { static_cast<unsigned>( m_ArrayValue.size() ) }; const std::vector<unsigned>& sub_extents = m_ArrayValue[0].GetArrayExtents(); ret.insert( ret.end(), sub_extents.begin(), sub_extents.end() ); return ret; } return {}; } jl_bool GenericValue::GetBool() const { assert( m_Type == Type::BOOL && "Trying to get the bool value from a non-bool GenericValue" ); return m_BoolValue; } jl_i8 GenericValue::GetI8() const { assert( m_Type == Type::I8 && "Trying to get the i8 value from a non-i8 GenericValue" ); return m_I8Value; } jl_i16 GenericValue::GetI16() const { assert( m_Type == Type::I16 && "Trying to get the i16 value from a non-i16 GenericValue" ); return m_I16Value; } jl_i32 GenericValue::GetI32() const { assert( m_Type == Type::I32 && "Trying to get the i32 value from a non-i32 GenericValue" ); return m_I32Value; } jl_i64 GenericValue::GetI64() const { assert( m_Type == Type::I64 && "Trying to get the i64 value from a non-i64 GenericValue" ); return m_I64Value; } jl_u8 GenericValue::GetU8() const { assert( m_Type == Type::U8 && "Trying to get the u8 value from a non-u8 GenericValue" ); return m_U8Value; } jl_u16 GenericValue::GetU16() const { assert( m_Type == Type::U16 && "Trying to get the u16 value from a non-u16 GenericValue" ); return m_U16Value; } jl_u32 GenericValue::GetU32() const { assert( m_Type == Type::U32 && "Trying to get the u32 value from a non-u32 GenericValue" ); return m_U32Value; } jl_u64 GenericValue::GetU64() const { assert( m_Type == Type::U64 && "Trying to get the u64 value from a non-u64 GenericValue" ); return m_U64Value; } jl_float GenericValue::GetFloat() const { assert( m_Type == Type::FLOAT && "Trying to get the float value from a non-float GenericValue" ); return m_FloatValue; } jl_float4 GenericValue::GetFloat4() const { assert( m_Type == Type::FLOAT4 && "Trying to get the float4 value from a non-float GenericValue" ); return m_Float4Value; } jl_double GenericValue::GetDouble() const { assert( m_Type == Type::DOUBLE && "Trying to get the double value from a non-double GenericValue" ); return m_DoubleValue; } const std::string& GenericValue::GetString() const { assert( m_Type == Type::STRING && "Trying to get the string value from a non-string GenericValue" ); return m_StringValue; } const std::vector<GenericValue>& GenericValue::GetArray() const { assert( m_Type == Type::ARRAY && "Trying to get the array value from a non-array GenericValue" ); return m_ArrayValue; } void GenericValue::FreeData() { using std::string; using std::vector; switch( m_Type ) { case Type::ARRAY: m_ArrayValue.~vector(); break; case Type::STRING: m_StringValue.~string(); break; default: break; } m_Type = Type::UNKNOWN; } } // namespace Compiler } // namespace JoeLang <|endoftext|>
<commit_before>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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 * FOUNDATION 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 "Stock.hxx" #include "Error.hxx" #include "stock/MapStock.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "child_stock.hxx" #include "spawn/Prepared.hxx" #include "spawn/ChildOptions.hxx" #include "spawn/JailParams.hxx" #include "spawn/JailConfig.hxx" #include "pool/tpool.hxx" #include "pool/StringBuilder.hxx" #include "AllocatorPtr.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "io/UniqueFileDescriptor.hxx" #include "io/Logger.hxx" #include "util/ConstBuffer.hxx" #include "util/RuntimeError.hxx" #include "util/Exception.hxx" #include "util/StringFormat.hxx" #include <string> #include <assert.h> #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #ifdef __linux #include <sched.h> #endif struct FcgiStock final : StockClass, ChildStockClass { StockMap hstock; ChildStock child_stock; FcgiStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor _log_socket) noexcept; ~FcgiStock() { /* this one must be cleared before #child_stock; FadeAll() calls ClearIdle(), so this method is the best match for what we want to do (though a kludge) */ hstock.FadeAll(); } EventLoop &GetEventLoop() { return hstock.GetEventLoop(); } SocketDescriptor GetLogSocket() const noexcept { return child_stock.GetLogSocket(); } void FadeAll() { hstock.FadeAll(); child_stock.GetStockMap().FadeAll(); } void FadeTag(const char *tag); /* virtual methods from class StockClass */ void Create(CreateStockItem c, void *info, struct pool &caller_pool, CancellablePointer &cancel_ptr) override; /* virtual methods from class ChildStockClass */ const char *GetChildTag(void *info) const noexcept override; void PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) override; }; struct FcgiChildParams { const char *executable_path; ConstBuffer<const char *> args; const ChildOptions &options; FcgiChildParams(const char *_executable_path, ConstBuffer<const char *> _args, const ChildOptions &_options) :executable_path(_executable_path), args(_args), options(_options) {} const char *GetStockKey(struct pool &pool) const; }; struct FcgiConnection final : StockItem { const LLogger logger; std::string jail_home_directory; JailConfig jail_config; StockItem *child = nullptr; UniqueSocketDescriptor fd; SocketEvent event; TimerEvent idle_timeout_event; /** * Is this a fresh connection to the FastCGI child process? */ bool fresh = true; /** * Shall the FastCGI child process be killed? */ bool kill = false; /** * Was the current request aborted by the fcgi_client caller? */ bool aborted = false; explicit FcgiConnection(EventLoop &event_loop, CreateStockItem c) :StockItem(c), logger(GetStockName()), event(event_loop, BIND_THIS_METHOD(OnSocketEvent)), idle_timeout_event(c.stock.GetEventLoop(), BIND_THIS_METHOD(OnIdleTimeout)) {} ~FcgiConnection() override; gcc_pure const char *GetTag() const { assert(child != nullptr); return child_stock_item_get_tag(*child); } void SetSite(const char *site) noexcept { child_stock_item_set_site(*child, site); } void SetUri(const char *uri) noexcept { child_stock_item_set_uri(*child, uri); } /* virtual methods from class StockItem */ bool Borrow() noexcept override; bool Release() noexcept override; private: void OnSocketEvent(unsigned events); void OnIdleTimeout() noexcept; }; const char * FcgiChildParams::GetStockKey(struct pool &pool) const { PoolStringBuilder<256> b; b.push_back(executable_path); for (auto i : args) { b.push_back(" "); b.push_back(i); } for (auto i : options.env) { b.push_back("$"); b.push_back(i); } char options_buffer[16384]; b.emplace_back(options_buffer, options.MakeId(options_buffer)); return b(pool); } /* * libevent callback * */ void FcgiConnection::OnSocketEvent(unsigned) { char buffer; ssize_t nbytes = fd.Read(&buffer, sizeof(buffer)); if (nbytes < 0) logger(2, "error on idle FastCGI connection: ", strerror(errno)); else if (nbytes > 0) logger(2, "unexpected data from idle FastCGI connection"); InvokeIdleDisconnect(); } inline void FcgiConnection::OnIdleTimeout() noexcept { InvokeIdleDisconnect(); } /* * child_stock class * */ const char * FcgiStock::GetChildTag(void *info) const noexcept { const auto &params = *(const FcgiChildParams *)info; return params.options.tag; } void FcgiStock::PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) { auto &params = *(FcgiChildParams *)info; const ChildOptions &options = params.options; p.SetStdin(std::move(fd)); /* the FastCGI protocol defines a channel for stderr, so we could close its "real" stderr here, but many FastCGI applications don't use the FastCGI protocol to send error messages, so we just keep it open */ UniqueFileDescriptor null_fd; if (null_fd.Open("/dev/null", O_WRONLY)) p.SetStdout(std::move(null_fd)); p.Append(params.executable_path); for (auto i : params.args) p.Append(i); options.CopyTo(p, true, nullptr); } /* * stock class * */ void FcgiStock::Create(CreateStockItem c, void *info, struct pool &caller_pool, gcc_unused CancellablePointer &cancel_ptr) { FcgiChildParams *params = (FcgiChildParams *)info; assert(params != nullptr); assert(params->executable_path != nullptr); auto *connection = new FcgiConnection(GetEventLoop(), c); const ChildOptions &options = params->options; if (options.jail != nullptr && options.jail->enabled) { connection->jail_home_directory = options.jail->home_directory; if (!connection->jail_config.Load("/etc/cm4all/jailcgi/jail.conf")) { delete connection; throw FcgiClientError("Failed to load /etc/cm4all/jailcgi/jail.conf"); } } const char *key = c.GetStockName(); try { connection->child = child_stock.GetStockMap().GetNow(caller_pool, key, params); } catch (...) { delete connection; std::throw_with_nested(FcgiClientError(StringFormat<256>("Failed to start FastCGI server '%s'", key))); } try { connection->fd = child_stock_item_connect(*connection->child); } catch (...) { connection->kill = true; delete connection; std::throw_with_nested(FcgiClientError(StringFormat<256>("Failed to connect to FastCGI server '%s'", key))); } connection->event.Open(connection->fd); connection->InvokeCreateSuccess(); } bool FcgiConnection::Borrow() noexcept { /* check the connection status before using it, just in case the FastCGI server has decided to close the connection before fcgi_connection_event_callback() got invoked */ char buffer; ssize_t nbytes = fd.Read(&buffer, sizeof(buffer)); if (nbytes > 0) { logger(2, "unexpected data from idle FastCGI connection"); return false; } else if (nbytes == 0) { /* connection closed (not worth a log message) */ return false; } else if (errno != EAGAIN) { logger(2, "error on idle FastCGI connection: ", strerror(errno)); return false; } event.Cancel(); idle_timeout_event.Cancel(); aborted = false; return true; } bool FcgiConnection::Release() noexcept { fresh = false; event.ScheduleRead(); idle_timeout_event.Schedule(std::chrono::minutes(6)); return true; } FcgiConnection::~FcgiConnection() { if (fd.IsDefined()) { event.Cancel(); fd.Close(); } if (fresh && aborted) /* the fcgi_client caller has aborted the request before the first response on a fresh connection was received: better kill the child process, it may be failing on us completely */ kill = true; if (child != nullptr) child->Put(kill); } /* * interface * */ inline FcgiStock::FcgiStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor _log_socket) noexcept :hstock(event_loop, *this, limit, max_idle), child_stock(event_loop, spawn_service, *this, _log_socket, limit, max_idle) {} void FcgiStock::FadeTag(const char *tag) { assert(tag != nullptr); hstock.FadeIf([tag](const StockItem &item){ const auto &connection = (const FcgiConnection &)item; const char *tag2 = connection.GetTag(); return tag2 != nullptr && strcmp(tag, tag2) == 0; }); child_stock.FadeTag(tag); } FcgiStock * fcgi_stock_new(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket) { return new FcgiStock(limit, max_idle, event_loop, spawn_service, log_socket); } void fcgi_stock_free(FcgiStock *fcgi_stock) { delete fcgi_stock; } SocketDescriptor fcgi_stock_get_log_socket(const FcgiStock &fs) noexcept { return fs.GetLogSocket(); } void fcgi_stock_fade_all(FcgiStock &fs) { fs.FadeAll(); } void fcgi_stock_fade_tag(FcgiStock &fs, const char *tag) { fs.FadeTag(tag); } StockItem * fcgi_stock_get(FcgiStock *fcgi_stock, const ChildOptions &options, const char *executable_path, ConstBuffer<const char *> args) { const AutoRewindPool auto_rewind(*tpool); auto params = NewFromPool<FcgiChildParams>(*tpool, executable_path, args, options); return fcgi_stock->hstock.GetNow(*tpool, params->GetStockKey(*tpool), params); } int fcgi_stock_item_get_domain(gcc_unused const StockItem &item) { return AF_LOCAL; } void fcgi_stock_item_set_site(StockItem &item, const char *site) noexcept { auto &connection = (FcgiConnection &)item; connection.SetSite(site); } void fcgi_stock_item_set_uri(StockItem &item, const char *uri) noexcept { auto &connection = (FcgiConnection &)item; connection.SetUri(uri); } SocketDescriptor fcgi_stock_item_get(const StockItem &item) { const auto *connection = (const FcgiConnection *)&item; assert(connection->fd.IsDefined()); return connection->fd; } const char * fcgi_stock_translate_path(const StockItem &item, const char *path, AllocatorPtr alloc) { const auto *connection = (const FcgiConnection *)&item; if (connection->jail_home_directory.empty()) /* no JailCGI - application's namespace is the same as ours, no translation needed */ return path; const char *jailed = connection->jail_config.TranslatePath(path, connection->jail_home_directory.c_str(), alloc); return jailed != nullptr ? jailed : path; } void fcgi_stock_aborted(StockItem &item) { auto *connection = (FcgiConnection *)&item; connection->aborted = true; } <commit_msg>fcgi/stock: add `noexcept`<commit_after>/* * Copyright 2007-2018 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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 * FOUNDATION 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 "Stock.hxx" #include "Error.hxx" #include "stock/MapStock.hxx" #include "stock/Stock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "child_stock.hxx" #include "spawn/Prepared.hxx" #include "spawn/ChildOptions.hxx" #include "spawn/JailParams.hxx" #include "spawn/JailConfig.hxx" #include "pool/tpool.hxx" #include "pool/StringBuilder.hxx" #include "AllocatorPtr.hxx" #include "event/SocketEvent.hxx" #include "event/TimerEvent.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "io/UniqueFileDescriptor.hxx" #include "io/Logger.hxx" #include "util/ConstBuffer.hxx" #include "util/RuntimeError.hxx" #include "util/Exception.hxx" #include "util/StringFormat.hxx" #include <string> #include <assert.h> #include <sys/socket.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #ifdef __linux #include <sched.h> #endif struct FcgiStock final : StockClass, ChildStockClass { StockMap hstock; ChildStock child_stock; FcgiStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor _log_socket) noexcept; ~FcgiStock() { /* this one must be cleared before #child_stock; FadeAll() calls ClearIdle(), so this method is the best match for what we want to do (though a kludge) */ hstock.FadeAll(); } EventLoop &GetEventLoop() { return hstock.GetEventLoop(); } SocketDescriptor GetLogSocket() const noexcept { return child_stock.GetLogSocket(); } void FadeAll() { hstock.FadeAll(); child_stock.GetStockMap().FadeAll(); } void FadeTag(const char *tag); /* virtual methods from class StockClass */ void Create(CreateStockItem c, void *info, struct pool &caller_pool, CancellablePointer &cancel_ptr) override; /* virtual methods from class ChildStockClass */ const char *GetChildTag(void *info) const noexcept override; void PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) override; }; struct FcgiChildParams { const char *executable_path; ConstBuffer<const char *> args; const ChildOptions &options; FcgiChildParams(const char *_executable_path, ConstBuffer<const char *> _args, const ChildOptions &_options) :executable_path(_executable_path), args(_args), options(_options) {} const char *GetStockKey(struct pool &pool) const; }; struct FcgiConnection final : StockItem { const LLogger logger; std::string jail_home_directory; JailConfig jail_config; StockItem *child = nullptr; UniqueSocketDescriptor fd; SocketEvent event; TimerEvent idle_timeout_event; /** * Is this a fresh connection to the FastCGI child process? */ bool fresh = true; /** * Shall the FastCGI child process be killed? */ bool kill = false; /** * Was the current request aborted by the fcgi_client caller? */ bool aborted = false; explicit FcgiConnection(EventLoop &event_loop, CreateStockItem c) noexcept :StockItem(c), logger(GetStockName()), event(event_loop, BIND_THIS_METHOD(OnSocketEvent)), idle_timeout_event(c.stock.GetEventLoop(), BIND_THIS_METHOD(OnIdleTimeout)) {} ~FcgiConnection() noexcept override; gcc_pure const char *GetTag() const { assert(child != nullptr); return child_stock_item_get_tag(*child); } void SetSite(const char *site) noexcept { child_stock_item_set_site(*child, site); } void SetUri(const char *uri) noexcept { child_stock_item_set_uri(*child, uri); } /* virtual methods from class StockItem */ bool Borrow() noexcept override; bool Release() noexcept override; private: void OnSocketEvent(unsigned events) noexcept; void OnIdleTimeout() noexcept; }; const char * FcgiChildParams::GetStockKey(struct pool &pool) const { PoolStringBuilder<256> b; b.push_back(executable_path); for (auto i : args) { b.push_back(" "); b.push_back(i); } for (auto i : options.env) { b.push_back("$"); b.push_back(i); } char options_buffer[16384]; b.emplace_back(options_buffer, options.MakeId(options_buffer)); return b(pool); } /* * libevent callback * */ void FcgiConnection::OnSocketEvent(unsigned) noexcept { char buffer; ssize_t nbytes = fd.Read(&buffer, sizeof(buffer)); if (nbytes < 0) logger(2, "error on idle FastCGI connection: ", strerror(errno)); else if (nbytes > 0) logger(2, "unexpected data from idle FastCGI connection"); InvokeIdleDisconnect(); } inline void FcgiConnection::OnIdleTimeout() noexcept { InvokeIdleDisconnect(); } /* * child_stock class * */ const char * FcgiStock::GetChildTag(void *info) const noexcept { const auto &params = *(const FcgiChildParams *)info; return params.options.tag; } void FcgiStock::PrepareChild(void *info, UniqueSocketDescriptor &&fd, PreparedChildProcess &p) { auto &params = *(FcgiChildParams *)info; const ChildOptions &options = params.options; p.SetStdin(std::move(fd)); /* the FastCGI protocol defines a channel for stderr, so we could close its "real" stderr here, but many FastCGI applications don't use the FastCGI protocol to send error messages, so we just keep it open */ UniqueFileDescriptor null_fd; if (null_fd.Open("/dev/null", O_WRONLY)) p.SetStdout(std::move(null_fd)); p.Append(params.executable_path); for (auto i : params.args) p.Append(i); options.CopyTo(p, true, nullptr); } /* * stock class * */ void FcgiStock::Create(CreateStockItem c, void *info, struct pool &caller_pool, gcc_unused CancellablePointer &cancel_ptr) { FcgiChildParams *params = (FcgiChildParams *)info; assert(params != nullptr); assert(params->executable_path != nullptr); auto *connection = new FcgiConnection(GetEventLoop(), c); const ChildOptions &options = params->options; if (options.jail != nullptr && options.jail->enabled) { connection->jail_home_directory = options.jail->home_directory; if (!connection->jail_config.Load("/etc/cm4all/jailcgi/jail.conf")) { delete connection; throw FcgiClientError("Failed to load /etc/cm4all/jailcgi/jail.conf"); } } const char *key = c.GetStockName(); try { connection->child = child_stock.GetStockMap().GetNow(caller_pool, key, params); } catch (...) { delete connection; std::throw_with_nested(FcgiClientError(StringFormat<256>("Failed to start FastCGI server '%s'", key))); } try { connection->fd = child_stock_item_connect(*connection->child); } catch (...) { connection->kill = true; delete connection; std::throw_with_nested(FcgiClientError(StringFormat<256>("Failed to connect to FastCGI server '%s'", key))); } connection->event.Open(connection->fd); connection->InvokeCreateSuccess(); } bool FcgiConnection::Borrow() noexcept { /* check the connection status before using it, just in case the FastCGI server has decided to close the connection before fcgi_connection_event_callback() got invoked */ char buffer; ssize_t nbytes = fd.Read(&buffer, sizeof(buffer)); if (nbytes > 0) { logger(2, "unexpected data from idle FastCGI connection"); return false; } else if (nbytes == 0) { /* connection closed (not worth a log message) */ return false; } else if (errno != EAGAIN) { logger(2, "error on idle FastCGI connection: ", strerror(errno)); return false; } event.Cancel(); idle_timeout_event.Cancel(); aborted = false; return true; } bool FcgiConnection::Release() noexcept { fresh = false; event.ScheduleRead(); idle_timeout_event.Schedule(std::chrono::minutes(6)); return true; } FcgiConnection::~FcgiConnection() noexcept { if (fd.IsDefined()) { event.Cancel(); fd.Close(); } if (fresh && aborted) /* the fcgi_client caller has aborted the request before the first response on a fresh connection was received: better kill the child process, it may be failing on us completely */ kill = true; if (child != nullptr) child->Put(kill); } /* * interface * */ inline FcgiStock::FcgiStock(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor _log_socket) noexcept :hstock(event_loop, *this, limit, max_idle), child_stock(event_loop, spawn_service, *this, _log_socket, limit, max_idle) {} void FcgiStock::FadeTag(const char *tag) { assert(tag != nullptr); hstock.FadeIf([tag](const StockItem &item){ const auto &connection = (const FcgiConnection &)item; const char *tag2 = connection.GetTag(); return tag2 != nullptr && strcmp(tag, tag2) == 0; }); child_stock.FadeTag(tag); } FcgiStock * fcgi_stock_new(unsigned limit, unsigned max_idle, EventLoop &event_loop, SpawnService &spawn_service, SocketDescriptor log_socket) { return new FcgiStock(limit, max_idle, event_loop, spawn_service, log_socket); } void fcgi_stock_free(FcgiStock *fcgi_stock) { delete fcgi_stock; } SocketDescriptor fcgi_stock_get_log_socket(const FcgiStock &fs) noexcept { return fs.GetLogSocket(); } void fcgi_stock_fade_all(FcgiStock &fs) { fs.FadeAll(); } void fcgi_stock_fade_tag(FcgiStock &fs, const char *tag) { fs.FadeTag(tag); } StockItem * fcgi_stock_get(FcgiStock *fcgi_stock, const ChildOptions &options, const char *executable_path, ConstBuffer<const char *> args) { const AutoRewindPool auto_rewind(*tpool); auto params = NewFromPool<FcgiChildParams>(*tpool, executable_path, args, options); return fcgi_stock->hstock.GetNow(*tpool, params->GetStockKey(*tpool), params); } int fcgi_stock_item_get_domain(gcc_unused const StockItem &item) { return AF_LOCAL; } void fcgi_stock_item_set_site(StockItem &item, const char *site) noexcept { auto &connection = (FcgiConnection &)item; connection.SetSite(site); } void fcgi_stock_item_set_uri(StockItem &item, const char *uri) noexcept { auto &connection = (FcgiConnection &)item; connection.SetUri(uri); } SocketDescriptor fcgi_stock_item_get(const StockItem &item) { const auto *connection = (const FcgiConnection *)&item; assert(connection->fd.IsDefined()); return connection->fd; } const char * fcgi_stock_translate_path(const StockItem &item, const char *path, AllocatorPtr alloc) { const auto *connection = (const FcgiConnection *)&item; if (connection->jail_home_directory.empty()) /* no JailCGI - application's namespace is the same as ours, no translation needed */ return path; const char *jailed = connection->jail_config.TranslatePath(path, connection->jail_home_directory.c_str(), alloc); return jailed != nullptr ? jailed : path; } void fcgi_stock_aborted(StockItem &item) { auto *connection = (FcgiConnection *)&item; connection->aborted = true; } <|endoftext|>
<commit_before>#include "filesystem.hpp" #include "logger.hpp" #include "string_util.hpp" #include "SDL.h" #include "oddlib/stream.hpp" #include "oddlib/cdromfilesystem.hpp" #include <algorithm> #include <fstream> #include "jsonxx/jsonxx.h" #include "imgui/imgui.h" #ifdef _WIN32 const char kDirSeperator = '\\'; #else const char kDirSeperator = '/'; #endif static std::string GetFilePath(const std::string& basePath, const std::string& fileName) { std::string fullFileName; if (string_util::ends_with(basePath, std::string(1, kDirSeperator))) { fullFileName = basePath + fileName; } else { fullFileName = basePath + kDirSeperator + fileName; } return fullFileName; } static bool FileExists(const std::string& fileName) { std::ifstream fileStream; fileStream.open(fileName, std::ios::in | std::ios::binary | std::ios::ate); if (fileStream) { LOG_INFO("File: " << fileName << " found"); return true; } LOG_WARNING("File: " << fileName << " not found"); return false; } FileSystem::Directory::Directory(const std::string& path, int priority) : IResourcePathAbstraction(path, priority) { } std::unique_ptr<Oddlib::IStream> FileSystem::Directory::Open(const std::string& fileName) { const auto fullFileName = GetFilePath(Path(), fileName); return std::make_unique<Oddlib::Stream>(fullFileName); } bool FileSystem::Directory::Exists(const std::string& fileName) const { const auto fullFileName = GetFilePath(Path(), fileName); return FileExists(fullFileName); } FileSystem::RawCdImagePath::RawCdImagePath(const std::string& path, int priority) : IResourcePathAbstraction(path, priority) { mCdImage = std::make_unique<RawCdImage>(path); mCdImage->LogTree(); } std::unique_ptr<Oddlib::IStream> FileSystem::RawCdImagePath::Open(const std::string& fileName) { return mCdImage->ReadFile(fileName, true); } bool FileSystem::RawCdImagePath::Exists(const std::string& fileName) const { return mCdImage->FileExists(fileName); } FileSystem::FileSystem() { } FileSystem::~FileSystem() { } bool FileSystem::Init() { InitBasePath(); InitResourcePaths(); return true; } void FileSystem::AddResourcePath(const std::string& path, int priority) { mResourcePaths.emplace_back(MakeResourcePath(path, priority)); std::sort(mResourcePaths.begin(), mResourcePaths.end(), [](const std::unique_ptr<IResourcePathAbstraction>& lhs, const std::unique_ptr<IResourcePathAbstraction>& rhs) { return lhs->Priority() < rhs->Priority(); }); } bool FileSystem::Exists(const std::string& name) const { return FileExists(GetFilePath(mBasePath,name)); } std::unique_ptr<Oddlib::IStream> FileSystem::OpenResource(const std::string& name) { LOG_INFO("Opening resource: " << name); if (mResourcePaths.empty()) { throw Oddlib::Exception("No resource paths configured"); } // Look in each resource path by priority for (auto& resourceLocation : mResourcePaths) { if (resourceLocation->Exists(name)) { return resourceLocation->Open(name); } } throw Oddlib::Exception("Missing resource"); } void FileSystem::DebugUi() { ImGui::Begin("Resource paths", nullptr, ImGuiWindowFlags_NoCollapse); static int idx = 0; static std::vector<const char*> items; items.resize(mResourcePaths.size()); for (size_t i=0; i<items.size(); i++) { items[i] = mResourcePaths[i]->Path().c_str(); } ImGui::PushItemWidth(-1); ImGui::ListBox("", &idx, items.data(), static_cast<int>(items.size()), static_cast<int>(items.size())); /* TODO: Allow edits ImGui::Button("Delete selected"); ImGui::Button("Add"); */ ImGui::End(); } std::unique_ptr<FileSystem::IResourcePathAbstraction> FileSystem::MakeResourcePath(std::string path, int priority) { TRACE_ENTRYEXIT; if (string_util::ends_with(path, ".bin", true)) { LOG_INFO("Adding CD image: " << path); return std::make_unique<FileSystem::RawCdImagePath>(path, priority); } LOG_INFO("Adding directory: " << path); return std::make_unique<FileSystem::Directory>(path, priority); } std::unique_ptr<Oddlib::IStream> FileSystem::Open(const std::string& name) { const auto fileName = GetFilePath(mBasePath, name); LOG_INFO("Opening file: " << fileName); return std::make_unique<Oddlib::Stream>(fileName); } void FileSystem::InitBasePath() { char* pBasePath = SDL_GetBasePath(); if (pBasePath) { mBasePath = std::string(pBasePath); SDL_free(pBasePath); // If it looks like we're running from the IDE/dev build then attempt to fix up the path to the correct location to save // manually setting the correct working directory. const bool bIsDebugPath = string_util::contains(mBasePath, "/alive/bin/") || string_util::contains(mBasePath, "\\alive\\bin\\"); if (bIsDebugPath) { if (string_util::contains(mBasePath, "/alive/bin/")) { LOG_WARNING("We appear to be running from the IDE (Linux) - fixing up basePath to be ../"); mBasePath += "../"; } else { LOG_WARNING("We appear to be running from the IDE (Win32) - fixing up basePath to be ../"); mBasePath += "..\\..\\"; } } } else { mBasePath = "." + kDirSeperator; LOG_ERROR("SDL_GetBasePath failed, falling back to ." << kDirSeperator); } LOG_INFO("basePath is " << mBasePath); } void FileSystem::InitResourcePaths() { TRACE_ENTRYEXIT; auto stream = Open("data/resource_paths.json"); const std::string jsonFileContents = stream->LoadAllToString(); jsonxx::Object rootJsonObject; rootJsonObject.parse(jsonFileContents); if (rootJsonObject.has<jsonxx::Array>("ResourcePaths")) { const jsonxx::Array& resourcePaths = rootJsonObject.get<jsonxx::Array>("ResourcePaths"); for (size_t i = 0; i < resourcePaths.size(); i++) { const jsonxx::Object& pathAndPriority = resourcePaths.get<jsonxx::Object>(i); const auto& path = pathAndPriority.get<jsonxx::String>("path"); const auto& priority = pathAndPriority.get<jsonxx::Number>("priority"); AddResourcePath(path,static_cast<int>(priority)); } } } <commit_msg>handle case when cd image isnt found<commit_after>#include "filesystem.hpp" #include "logger.hpp" #include "string_util.hpp" #include "SDL.h" #include "oddlib/stream.hpp" #include "oddlib/cdromfilesystem.hpp" #include <algorithm> #include <fstream> #include "jsonxx/jsonxx.h" #include "imgui/imgui.h" #ifdef _WIN32 const char kDirSeperator = '\\'; #else const char kDirSeperator = '/'; #endif static std::string GetFilePath(const std::string& basePath, const std::string& fileName) { std::string fullFileName; if (string_util::ends_with(basePath, std::string(1, kDirSeperator))) { fullFileName = basePath + fileName; } else { fullFileName = basePath + kDirSeperator + fileName; } return fullFileName; } static bool FileExists(const std::string& fileName) { std::ifstream fileStream; fileStream.open(fileName, std::ios::in | std::ios::binary | std::ios::ate); if (fileStream) { LOG_INFO("File: " << fileName << " found"); return true; } LOG_WARNING("File: " << fileName << " not found"); return false; } FileSystem::Directory::Directory(const std::string& path, int priority) : IResourcePathAbstraction(path, priority) { } std::unique_ptr<Oddlib::IStream> FileSystem::Directory::Open(const std::string& fileName) { const auto fullFileName = GetFilePath(Path(), fileName); return std::make_unique<Oddlib::Stream>(fullFileName); } bool FileSystem::Directory::Exists(const std::string& fileName) const { const auto fullFileName = GetFilePath(Path(), fileName); return FileExists(fullFileName); } FileSystem::RawCdImagePath::RawCdImagePath(const std::string& path, int priority) : IResourcePathAbstraction(path, priority) { mCdImage = std::make_unique<RawCdImage>(path); mCdImage->LogTree(); } std::unique_ptr<Oddlib::IStream> FileSystem::RawCdImagePath::Open(const std::string& fileName) { return mCdImage->ReadFile(fileName, true); } bool FileSystem::RawCdImagePath::Exists(const std::string& fileName) const { return mCdImage->FileExists(fileName); } FileSystem::FileSystem() { } FileSystem::~FileSystem() { } bool FileSystem::Init() { InitBasePath(); InitResourcePaths(); return true; } void FileSystem::AddResourcePath(const std::string& path, int priority) { try { mResourcePaths.emplace_back(MakeResourcePath(path, priority)); std::sort(mResourcePaths.begin(), mResourcePaths.end(), [](const std::unique_ptr<IResourcePathAbstraction>& lhs, const std::unique_ptr<IResourcePathAbstraction>& rhs) { return lhs->Priority() < rhs->Priority(); }); } catch (const Oddlib::Exception& ex) { LOG_ERROR("Failed to add resource path: " << path << " with priority: " << priority << " err: " << ex.what()); } } bool FileSystem::Exists(const std::string& name) const { return FileExists(GetFilePath(mBasePath,name)); } std::unique_ptr<Oddlib::IStream> FileSystem::OpenResource(const std::string& name) { LOG_INFO("Opening resource: " << name); if (mResourcePaths.empty()) { throw Oddlib::Exception("No resource paths configured"); } // Look in each resource path by priority for (auto& resourceLocation : mResourcePaths) { if (resourceLocation->Exists(name)) { return resourceLocation->Open(name); } } throw Oddlib::Exception("Missing resource"); } void FileSystem::DebugUi() { ImGui::Begin("Resource paths", nullptr, ImGuiWindowFlags_NoCollapse); static int idx = 0; static std::vector<const char*> items; items.resize(mResourcePaths.size()); for (size_t i=0; i<items.size(); i++) { items[i] = mResourcePaths[i]->Path().c_str(); } ImGui::PushItemWidth(-1); ImGui::ListBox("", &idx, items.data(), static_cast<int>(items.size()), static_cast<int>(items.size())); /* TODO: Allow edits ImGui::Button("Delete selected"); ImGui::Button("Add"); */ ImGui::End(); } std::unique_ptr<FileSystem::IResourcePathAbstraction> FileSystem::MakeResourcePath(std::string path, int priority) { TRACE_ENTRYEXIT; if (string_util::ends_with(path, ".bin", true)) { LOG_INFO("Adding CD image: " << path); return std::make_unique<FileSystem::RawCdImagePath>(path, priority); } LOG_INFO("Adding directory: " << path); return std::make_unique<FileSystem::Directory>(path, priority); } std::unique_ptr<Oddlib::IStream> FileSystem::Open(const std::string& name) { const auto fileName = GetFilePath(mBasePath, name); LOG_INFO("Opening file: " << fileName); return std::make_unique<Oddlib::Stream>(fileName); } void FileSystem::InitBasePath() { char* pBasePath = SDL_GetBasePath(); if (pBasePath) { mBasePath = std::string(pBasePath); SDL_free(pBasePath); // If it looks like we're running from the IDE/dev build then attempt to fix up the path to the correct location to save // manually setting the correct working directory. const bool bIsDebugPath = string_util::contains(mBasePath, "/alive/bin/") || string_util::contains(mBasePath, "\\alive\\bin\\"); if (bIsDebugPath) { if (string_util::contains(mBasePath, "/alive/bin/")) { LOG_WARNING("We appear to be running from the IDE (Linux) - fixing up basePath to be ../"); mBasePath += "../"; } else { LOG_WARNING("We appear to be running from the IDE (Win32) - fixing up basePath to be ../"); mBasePath += "..\\..\\"; } } } else { mBasePath = "." + kDirSeperator; LOG_ERROR("SDL_GetBasePath failed, falling back to ." << kDirSeperator); } LOG_INFO("basePath is " << mBasePath); } void FileSystem::InitResourcePaths() { TRACE_ENTRYEXIT; auto stream = Open("data/resource_paths.json"); const std::string jsonFileContents = stream->LoadAllToString(); jsonxx::Object rootJsonObject; rootJsonObject.parse(jsonFileContents); if (rootJsonObject.has<jsonxx::Array>("ResourcePaths")) { const jsonxx::Array& resourcePaths = rootJsonObject.get<jsonxx::Array>("ResourcePaths"); for (size_t i = 0; i < resourcePaths.size(); i++) { const jsonxx::Object& pathAndPriority = resourcePaths.get<jsonxx::Object>(i); const auto& path = pathAndPriority.get<jsonxx::String>("path"); const auto& priority = pathAndPriority.get<jsonxx::Number>("priority"); AddResourcePath(path,static_cast<int>(priority)); } } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 1999-2016 Vaclav Slavik * * 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 "fileviewer.h" #include <wx/filename.h> #include <wx/log.h> #include <wx/button.h> #include <wx/panel.h> #include <wx/stattext.h> #include <wx/choice.h> #include <wx/config.h> #include <wx/sizer.h> #include <wx/settings.h> #include <wx/listctrl.h> #include <wx/fontenum.h> #include <wx/ffile.h> #include <wx/utils.h> #include <wx/stc/stc.h> #include "customcontrols.h" #include "hidpi.h" #include "utility.h" #include "unicode_helpers.h" namespace { #ifdef __WXOSX__ const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE | wxFRAME_TOOL_WINDOW; #else const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE; #endif } // anonymous namespace FileViewer *FileViewer::ms_instance = nullptr; FileViewer *FileViewer::GetAndActivate() { if (!ms_instance) ms_instance = new FileViewer(nullptr); ms_instance->Show(); ms_instance->Raise(); return ms_instance; } FileViewer::FileViewer(wxWindow*) : wxFrame(nullptr, wxID_ANY, _("Source file"), wxDefaultPosition, wxDefaultSize, FRAME_STYLE) { SetName("fileviewer"); wxPanel *panel = new wxPanel(this, -1); wxSizer *sizer = new wxBoxSizer(wxVERTICAL); panel->SetSizer(sizer); #ifdef __WXOSX__ panel->SetWindowVariant(wxWINDOW_VARIANT_SMALL); #endif wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(barsizer, wxSizerFlags().Expand().PXBorderAll()); barsizer->Add(new wxStaticText(panel, wxID_ANY, _("Source file occurrence:")), wxSizerFlags().Center().PXBorder(wxRIGHT)); m_file = new wxChoice(panel, wxID_ANY); barsizer->Add(m_file, wxSizerFlags(1).Center()); m_openInEditor = new wxButton(panel, wxID_ANY, MSW_OR_OTHER(_("Open in editor"), _("Open in Editor"))); barsizer->Add(m_openInEditor, wxSizerFlags().Center().Border(wxLEFT, PX(10))); m_text = new wxStyledTextCtrl(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_THEME); SetupTextCtrl(); sizer->Add(m_text, 1, wxEXPAND); m_error = new wxStaticText(panel, wxID_ANY, ""); m_error->SetForegroundColour(ExplanationLabel::GetTextColor()); m_error->SetFont(m_error->GetFont().Larger().Larger()); sizer->Add(m_error, wxSizerFlags(1).Center().Border(wxTOP|wxBOTTOM, PX(80))); RestoreWindowState(this, wxSize(PX(600), PX(400))); wxSizer *topsizer = new wxBoxSizer(wxVERTICAL); topsizer->Add(panel, wxSizerFlags(1).Expand()); SetSizer(topsizer); // avoid flicker with these initial settings: m_file->Disable(); sizer->Hide(m_error); sizer->Hide(m_text); Layout(); m_file->Bind(wxEVT_CHOICE, &FileViewer::OnChoice, this); m_openInEditor->Bind(wxEVT_BUTTON, &FileViewer::OnEditFile, this); #ifdef __WXOSX__ wxAcceleratorEntry entries[] = { { wxACCEL_CMD, 'W', wxID_CLOSE } }; wxAcceleratorTable accel(WXSIZEOF(entries), entries); SetAcceleratorTable(accel); Bind(wxEVT_MENU, [=](wxCommandEvent&){ Destroy(); }, wxID_CLOSE); #endif } FileViewer::~FileViewer() { ms_instance = nullptr; SaveWindowState(this); } void FileViewer::SetupTextCtrl() { wxStyledTextCtrl& t = *m_text; wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); #ifdef __WXGTK__ font.SetFaceName("monospace"); #else static const char *s_monospaced_fonts[] = { #ifdef __WXMSW__ "Consolas", "Lucida Console", #endif #ifdef __WXOSX__ "Menlo", "Monaco", #endif NULL }; for ( const char **f = s_monospaced_fonts; *f; ++f ) { if ( wxFontEnumerator::IsValidFacename(*f) ) { font.SetFaceName(*f); break; } } #endif // style used: wxString fontspec = wxString::Format("face:%s,size:%d", font.GetFaceName().c_str(), #ifdef __WXOSX__ font.GetPointSize() - 1 #else font.GetPointSize() #endif ); const wxString DEFAULT = fontspec + ",fore:black,back:white"; const wxString STRING = fontspec + ",bold,fore:#882d21"; const wxString COMMENT = fontspec + ",fore:#487e18"; const wxString KEYWORD = fontspec + ",fore:#2f00f9"; const wxString LINENUMBERS = fontspec + ",fore:#5d8bab"; // current line marker t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0)); // set fonts t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT); t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS); // line numbers margin size: t.SetMarginType(0, wxSTC_MARGIN_NUMBER); t.SetMarginWidth(0, t.TextWidth(wxSTC_STYLE_LINENUMBER, "9999 ")); t.SetMarginWidth(1, 0); t.SetMarginWidth(2, 3); // set syntax highlighting styling t.StyleSetSpec(wxSTC_C_STRING, STRING); t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_P_STRING, STRING); t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT); t.StyleSetSpec(wxSTC_LUA_STRING, STRING); t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING); t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING); t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING); t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_PAS_STRING, STRING); t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT); t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT); } int FileViewer::GetLexer(const wxString& ext) { struct LexerInfo { const char *ext; int lexer; }; static const LexerInfo s_lexer[] = { { "c", wxSTC_LEX_CPP }, { "cpp", wxSTC_LEX_CPP }, { "cc", wxSTC_LEX_CPP }, { "cxx", wxSTC_LEX_CPP }, { "h", wxSTC_LEX_CPP }, { "hxx", wxSTC_LEX_CPP }, { "hpp", wxSTC_LEX_CPP }, { "py", wxSTC_LEX_PYTHON }, { "htm", wxSTC_LEX_HTML }, { "html", wxSTC_LEX_HTML }, { "php", wxSTC_LEX_PHPSCRIPT }, { "xml", wxSTC_LEX_XML }, { "pas", wxSTC_LEX_PASCAL }, { NULL, -1 } }; wxString e = ext.Lower(); for ( const LexerInfo *i = s_lexer; i->ext; ++i ) { if ( e == wxString::FromAscii(i->ext) ) return i->lexer; } return wxSTC_LEX_NULL; } wxFileName FileViewer::GetFilename(wxString ref) const { if ( ref.length() >= 3 && ref[1] == _T(':') && (ref[2] == _T('\\') || ref[2] == _T('/')) ) { // This is an absolute Windows path (c:\foo... or c:/foo...); fix // the latter case. ref.Replace("/", "\\"); } wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX; wxFileName filename(ref.BeforeLast(_T(':')), pathfmt); if ( filename.IsRelative() ) { wxFileName relative(filename); wxString basePath(m_basePath); // Sometimes, the path in source reference is not relative to the PO // file's location, but is relative to e.g. the root directory. See // https://code.djangoproject.com/ticket/13936 for exhaustive // discussion with plenty of examples. // // Deal with this by trying parent directories of m_basePath too. So if // a file named project/locales/cs/foo.po has a reference to src/main.c, // try not only project/locales/cs/src/main.c, but also // project/locales/src/main.c and project/src/main.c etc. while ( !basePath.empty() ) { filename = relative; filename.MakeAbsolute(basePath); if ( filename.FileExists() ) { break; // good, found the file } else { // remove the last path component size_t last = basePath.find_last_of("\\/"); if ( last == wxString::npos ) break; else basePath.erase(last); } } } return filename; } void FileViewer::ShowReferences(CatalogPtr catalog, CatalogItemPtr item, int defaultReference) { m_basePath = catalog->GetSourcesBasePath(); if (m_basePath.empty()) m_basePath = wxPathOnly(catalog->GetFileName()); m_references = item->GetReferences(); m_file->Clear(); m_file->Enable(m_references.size() > 1); if (m_references.empty()) { ShowError(_("No references for the selected item.")); } else { for (auto& r: m_references) m_file->Append(bidi::platform_mark_direction(r)); m_file->SetSelection(defaultReference); SelectReference(m_references[defaultReference]); } } void FileViewer::SelectReference(const wxString& ref) { const wxFileName filename = GetFilename(ref); wxFFile file; wxString data; if ( !filename.IsFileReadable() || !file.Open(filename.GetFullPath()) || !file.ReadAll(&data, wxConvAuto()) ) { ShowError(wxString::Format(_("Error opening file %s!"), filename.GetFullPath())); m_openInEditor->Disable(); return; } m_openInEditor->Enable(); m_error->GetContainingSizer()->Hide(m_error); m_text->GetContainingSizer()->Show(m_text); Layout(); // support GNOME's xml2po's extension to references in the form of // filename:line(xml_node): wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('(')); long linenum; if (!linenumStr.ToLong(&linenum)) linenum = 0; m_text->SetReadOnly(false); m_text->SetValue(data); m_text->SetReadOnly(true); m_text->MarkerDeleteAll(1); m_text->MarkerAdd((int)linenum - 1, 1); // Center the highlighted line: int lineHeight = m_text->TextHeight((int)linenum); int linesInWnd = m_text->GetSize().y / lineHeight; m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2)); } void FileViewer::ShowError(const wxString& msg) { m_error->SetLabel(msg); m_error->GetContainingSizer()->Show(m_error); m_text->GetContainingSizer()->Hide(m_text); Layout(); } void FileViewer::OnChoice(wxCommandEvent &event) { SelectReference(m_references[event.GetSelection()]); } void FileViewer::OnEditFile(wxCommandEvent&) { wxLaunchDefaultApplication(GetFilename(m_file->GetStringSelection()).GetFullPath()); } <commit_msg>Fix Open in Editor button in some cases on Windows<commit_after>/* * This file is part of Poedit (https://poedit.net) * * Copyright (C) 1999-2016 Vaclav Slavik * * 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 "fileviewer.h" #include <wx/filename.h> #include <wx/log.h> #include <wx/button.h> #include <wx/panel.h> #include <wx/stattext.h> #include <wx/choice.h> #include <wx/config.h> #include <wx/sizer.h> #include <wx/settings.h> #include <wx/listctrl.h> #include <wx/fontenum.h> #include <wx/ffile.h> #include <wx/utils.h> #include <wx/stc/stc.h> #include "customcontrols.h" #include "hidpi.h" #include "utility.h" #include "unicode_helpers.h" namespace { #ifdef __WXOSX__ const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE | wxFRAME_TOOL_WINDOW; #else const int FRAME_STYLE = wxDEFAULT_FRAME_STYLE; #endif } // anonymous namespace FileViewer *FileViewer::ms_instance = nullptr; FileViewer *FileViewer::GetAndActivate() { if (!ms_instance) ms_instance = new FileViewer(nullptr); ms_instance->Show(); ms_instance->Raise(); return ms_instance; } FileViewer::FileViewer(wxWindow*) : wxFrame(nullptr, wxID_ANY, _("Source file"), wxDefaultPosition, wxDefaultSize, FRAME_STYLE) { SetName("fileviewer"); wxPanel *panel = new wxPanel(this, -1); wxSizer *sizer = new wxBoxSizer(wxVERTICAL); panel->SetSizer(sizer); #ifdef __WXOSX__ panel->SetWindowVariant(wxWINDOW_VARIANT_SMALL); #endif wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(barsizer, wxSizerFlags().Expand().PXBorderAll()); barsizer->Add(new wxStaticText(panel, wxID_ANY, _("Source file occurrence:")), wxSizerFlags().Center().PXBorder(wxRIGHT)); m_file = new wxChoice(panel, wxID_ANY); barsizer->Add(m_file, wxSizerFlags(1).Center()); m_openInEditor = new wxButton(panel, wxID_ANY, MSW_OR_OTHER(_("Open in editor"), _("Open in Editor"))); barsizer->Add(m_openInEditor, wxSizerFlags().Center().Border(wxLEFT, PX(10))); m_text = new wxStyledTextCtrl(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxBORDER_THEME); SetupTextCtrl(); sizer->Add(m_text, 1, wxEXPAND); m_error = new wxStaticText(panel, wxID_ANY, ""); m_error->SetForegroundColour(ExplanationLabel::GetTextColor()); m_error->SetFont(m_error->GetFont().Larger().Larger()); sizer->Add(m_error, wxSizerFlags(1).Center().Border(wxTOP|wxBOTTOM, PX(80))); RestoreWindowState(this, wxSize(PX(600), PX(400))); wxSizer *topsizer = new wxBoxSizer(wxVERTICAL); topsizer->Add(panel, wxSizerFlags(1).Expand()); SetSizer(topsizer); // avoid flicker with these initial settings: m_file->Disable(); sizer->Hide(m_error); sizer->Hide(m_text); Layout(); m_file->Bind(wxEVT_CHOICE, &FileViewer::OnChoice, this); m_openInEditor->Bind(wxEVT_BUTTON, &FileViewer::OnEditFile, this); #ifdef __WXOSX__ wxAcceleratorEntry entries[] = { { wxACCEL_CMD, 'W', wxID_CLOSE } }; wxAcceleratorTable accel(WXSIZEOF(entries), entries); SetAcceleratorTable(accel); Bind(wxEVT_MENU, [=](wxCommandEvent&){ Destroy(); }, wxID_CLOSE); #endif } FileViewer::~FileViewer() { ms_instance = nullptr; SaveWindowState(this); } void FileViewer::SetupTextCtrl() { wxStyledTextCtrl& t = *m_text; wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); #ifdef __WXGTK__ font.SetFaceName("monospace"); #else static const char *s_monospaced_fonts[] = { #ifdef __WXMSW__ "Consolas", "Lucida Console", #endif #ifdef __WXOSX__ "Menlo", "Monaco", #endif NULL }; for ( const char **f = s_monospaced_fonts; *f; ++f ) { if ( wxFontEnumerator::IsValidFacename(*f) ) { font.SetFaceName(*f); break; } } #endif // style used: wxString fontspec = wxString::Format("face:%s,size:%d", font.GetFaceName().c_str(), #ifdef __WXOSX__ font.GetPointSize() - 1 #else font.GetPointSize() #endif ); const wxString DEFAULT = fontspec + ",fore:black,back:white"; const wxString STRING = fontspec + ",bold,fore:#882d21"; const wxString COMMENT = fontspec + ",fore:#487e18"; const wxString KEYWORD = fontspec + ",fore:#2f00f9"; const wxString LINENUMBERS = fontspec + ",fore:#5d8bab"; // current line marker t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0)); // set fonts t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT); t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS); // line numbers margin size: t.SetMarginType(0, wxSTC_MARGIN_NUMBER); t.SetMarginWidth(0, t.TextWidth(wxSTC_STYLE_LINENUMBER, "9999 ")); t.SetMarginWidth(1, 0); t.SetMarginWidth(2, 3); // set syntax highlighting styling t.StyleSetSpec(wxSTC_C_STRING, STRING); t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_P_STRING, STRING); t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT); t.StyleSetSpec(wxSTC_LUA_STRING, STRING); t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING); t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING); t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING); t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT); t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_PAS_STRING, STRING); t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT); t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT); t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT); } int FileViewer::GetLexer(const wxString& ext) { struct LexerInfo { const char *ext; int lexer; }; static const LexerInfo s_lexer[] = { { "c", wxSTC_LEX_CPP }, { "cpp", wxSTC_LEX_CPP }, { "cc", wxSTC_LEX_CPP }, { "cxx", wxSTC_LEX_CPP }, { "h", wxSTC_LEX_CPP }, { "hxx", wxSTC_LEX_CPP }, { "hpp", wxSTC_LEX_CPP }, { "py", wxSTC_LEX_PYTHON }, { "htm", wxSTC_LEX_HTML }, { "html", wxSTC_LEX_HTML }, { "php", wxSTC_LEX_PHPSCRIPT }, { "xml", wxSTC_LEX_XML }, { "pas", wxSTC_LEX_PASCAL }, { NULL, -1 } }; wxString e = ext.Lower(); for ( const LexerInfo *i = s_lexer; i->ext; ++i ) { if ( e == wxString::FromAscii(i->ext) ) return i->lexer; } return wxSTC_LEX_NULL; } wxFileName FileViewer::GetFilename(wxString ref) const { if ( ref.length() >= 3 && ref[1] == _T(':') && (ref[2] == _T('\\') || ref[2] == _T('/')) ) { // This is an absolute Windows path (c:\foo... or c:/foo...); fix // the latter case. ref.Replace("/", "\\"); } wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX; wxFileName filename(ref.BeforeLast(_T(':')), pathfmt); if ( filename.IsRelative() ) { wxFileName relative(filename); wxString basePath(m_basePath); // Sometimes, the path in source reference is not relative to the PO // file's location, but is relative to e.g. the root directory. See // https://code.djangoproject.com/ticket/13936 for exhaustive // discussion with plenty of examples. // // Deal with this by trying parent directories of m_basePath too. So if // a file named project/locales/cs/foo.po has a reference to src/main.c, // try not only project/locales/cs/src/main.c, but also // project/locales/src/main.c and project/src/main.c etc. while ( !basePath.empty() ) { filename = relative; filename.MakeAbsolute(basePath); if ( filename.FileExists() ) { return filename; // good, found the file } else { // remove the last path component size_t last = basePath.find_last_of("\\/"); if ( last == wxString::npos ) break; else basePath.erase(last); } } } return wxFileName(); // invalid } void FileViewer::ShowReferences(CatalogPtr catalog, CatalogItemPtr item, int defaultReference) { m_basePath = catalog->GetSourcesBasePath(); if (m_basePath.empty()) m_basePath = wxPathOnly(catalog->GetFileName()); m_references = item->GetReferences(); m_file->Clear(); m_file->Enable(m_references.size() > 1); if (m_references.empty()) { ShowError(_("No references for the selected item.")); } else { for (auto& r: m_references) m_file->Append(bidi::platform_mark_direction(r)); m_file->SetSelection(defaultReference); SelectReference(m_references[defaultReference]); } } void FileViewer::SelectReference(const wxString& ref) { const wxFileName filename = GetFilename(ref); if (!filename.IsOk()) { ShowError(wxString::Format(_("Error opening file %s!"), filename.GetFullPath())); m_openInEditor->Disable(); return; } wxFFile file; wxString data; if ( !filename.IsFileReadable() || !file.Open(filename.GetFullPath()) || !file.ReadAll(&data, wxConvAuto()) ) { ShowError(wxString::Format(_("Error opening file %s!"), filename.GetFullPath())); m_openInEditor->Disable(); return; } m_openInEditor->Enable(); m_error->GetContainingSizer()->Hide(m_error); m_text->GetContainingSizer()->Show(m_text); Layout(); // support GNOME's xml2po's extension to references in the form of // filename:line(xml_node): wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('(')); long linenum; if (!linenumStr.ToLong(&linenum)) linenum = 0; m_text->SetReadOnly(false); m_text->SetValue(data); m_text->SetReadOnly(true); m_text->MarkerDeleteAll(1); m_text->MarkerAdd((int)linenum - 1, 1); // Center the highlighted line: int lineHeight = m_text->TextHeight((int)linenum); int linesInWnd = m_text->GetSize().y / lineHeight; m_text->ScrollToLine(wxMax(0, (int)linenum - linesInWnd/2)); } void FileViewer::ShowError(const wxString& msg) { m_error->SetLabel(msg); m_error->GetContainingSizer()->Show(m_error); m_text->GetContainingSizer()->Hide(m_text); Layout(); } void FileViewer::OnChoice(wxCommandEvent &event) { SelectReference(m_references[event.GetSelection()]); } void FileViewer::OnEditFile(wxCommandEvent&) { wxFileName filename = GetFilename(bidi::strip_control_chars(m_file->GetStringSelection())); if (filename.IsOk()) wxLaunchDefaultApplication(filename.GetFullPath()); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: FeatEdge.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "FeatEdge.hh" #include "vlMath.hh" #include "Polygon.hh" #include "FNormals.hh" // Description: // Construct object with feature angle = 30; all types of edges extracted // and colored. vlFeatureEdges::vlFeatureEdges() { this->FeatureAngle = 30.0; this->BoundaryEdges = 1; this->FeatureEdges = 1; this->NonManifoldEdges = 1; this->Coloring = 1; } // Generate feature edges for mesh void vlFeatureEdges::Execute() { vlFloatPoints *newPts; vlFloatScalars *newScalars; vlCellArray *newLines; vlPolyData Mesh; int i, j, numNei, cellId; int numBEdges, numNonManifoldEdges, numFedges; float scalar, n[3], *x1, *x2, cosAngle; vlMath math; vlPolygon poly; int lineIds[2]; int npts, *pts; vlCellArray *inPolys; vlFloatNormals *polyNormals; int numPts, nei; vlIdList neighbors(MAX_CELL_SIZE); int p1, p2; vlPolyData *input=(vlPolyData *)this->Input; vlDebugMacro(<<"Executing feature edges"); this->Initialize(); // // Check input // if (!(numPts=input->GetNumberOfPoints()) ) { vlErrorMacro(<<"No input data!"); return; } // build cell structure. Only operate with polygons. Mesh.SetPoints(input->GetPoints()); inPolys = input->GetPolys(); Mesh.SetPolys(inPolys); Mesh.BuildLinks(); // // Allocate storage for lines/points // newPts = new vlFloatPoints(numPts/10,numPts); // arbitrary allocations size newScalars = new vlFloatScalars(numPts/10,numPts); newLines = new vlCellArray(numPts/10); // // Loop over all polygons generating boundary, non-manifold, and feature edges // if (this->BoundaryEdges || this->NonManifoldEdges || this->FeatureEdges) { if ( this->FeatureEdges ) { polyNormals = new vlFloatNormals(inPolys->GetNumberOfCells()); for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); cellId++) { poly.ComputeNormal(input->GetPoints(),npts,pts,n); polyNormals->InsertNormal(cellId,n); } cosAngle = cos ((double) math.DegreesToRadians() * this->FeatureAngle); } numBEdges = numNonManifoldEdges = numFedges = 0; for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); cellId++) { for (i=0; i < npts; i++) { p1 = pts[i]; p2 = pts[(i+1)%npts]; Mesh.GetCellEdgeNeighbors(cellId,p1,p2,neighbors); if ( (numNei=neighbors.GetNumberOfIds()) < 1 && this->BoundaryEdges ) { numBEdges++; scalar = 0.0; } else if ( numNei > 1 && this->NonManifoldEdges ) { // check to make sure that this edge hasn't been created before for (j=0; j < numNei; j++) if ( neighbors.GetId(j) < cellId ) break; if ( j >= numNei ) { numNonManifoldEdges++; scalar = 0.33333; } } else if ( numNei == 1 && (nei=neighbors.GetId(0)) > cellId ) { if ( math.Dot(polyNormals->GetNormal(nei),polyNormals->GetNormal(cellId)) <= cosAngle ) { numFedges++; scalar = 0.66667; } else { continue; } } x1 = Mesh.GetPoint(p1); x2 = Mesh.GetPoint(p2); lineIds[0] = newPts->InsertNextPoint(x1); lineIds[1] = newPts->InsertNextPoint(x2); newLines->InsertNextCell(2,lineIds); newScalars->InsertScalar(lineIds[0], scalar); newScalars->InsertScalar(lineIds[1], scalar); } } vlDebugMacro(<<"Created " << numBEdges << " boundary edges, " << numNonManifoldEdges << " non-manifold edges, " << numFedges << " feature edges"); if ( this->FeatureEdges ) delete polyNormals; } // // Update ourselves. // this->SetPoints(newPts); this->SetLines(newLines); if ( this->Coloring ) this->PointData.SetScalars(newScalars); else delete newScalars; } void vlFeatureEdges::PrintSelf(ostream& os, vlIndent indent) { vlPolyToPolyFilter::PrintSelf(os,indent); os << indent << "Feature Angle: " << this->FeatureAngle << "\n"; os << indent << "BoundaryEdges: " << (this->BoundaryEdges ? "On\n" : "Off\n"); os << indent << "FeatureEdges: " << (this->FeatureEdges ? "On\n" : "Off\n"); os << indent << "Non-Manifold Edges: " << (this->NonManifoldEdges ? "On\n" : "Off\n"); os << indent << "Coloring: " << (this->Coloring ? "On\n" : "Off\n"); } <commit_msg>ERR: Logic problems with continue statements<commit_after>/*========================================================================= Program: Visualization Library Module: FeatEdge.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "FeatEdge.hh" #include "vlMath.hh" #include "Polygon.hh" #include "FNormals.hh" // Description: // Construct object with feature angle = 30; all types of edges extracted // and colored. vlFeatureEdges::vlFeatureEdges() { this->FeatureAngle = 30.0; this->BoundaryEdges = 1; this->FeatureEdges = 1; this->NonManifoldEdges = 1; this->Coloring = 1; } // Generate feature edges for mesh void vlFeatureEdges::Execute() { vlPolyData *input=(vlPolyData *)this->Input; vlPoints *inPts; vlFloatPoints *newPts; vlFloatScalars *newScalars; vlCellArray *newLines; vlPolyData Mesh; int i, j, numNei, cellId; int numBEdges, numNonManifoldEdges, numFedges; float scalar, n[3], *x1, *x2, cosAngle; vlMath math; vlPolygon poly; int lineIds[2]; int npts, *pts; vlCellArray *inPolys; vlFloatNormals *polyNormals; int numPts, nei; vlIdList neighbors(MAX_CELL_SIZE); int p1, p2; vlDebugMacro(<<"Executing feature edges"); this->Initialize(); // // Check input // if ( (numPts=input->GetNumberOfPoints()) < 1 || (inPts=input->GetPoints()) == NULL || (inPolys=input->GetPolys()) == NULL ) { vlErrorMacro(<<"No input data!"); return; } if ( !this->BoundaryEdges && !this->NonManifoldEdges && !this->FeatureEdges) { vlWarningMacro(<<"All edge types turned off!"); return; } // build cell structure. Only operate with polygons. Mesh.SetPoints(inPts); Mesh.SetPolys(inPolys); Mesh.BuildLinks(); // // Allocate storage for lines/points // newPts = new vlFloatPoints(numPts/10,numPts); // arbitrary allocations size newScalars = new vlFloatScalars(numPts/10,numPts); newLines = new vlCellArray(numPts/10); // // Loop over all polygons generating boundary, non-manifold, and feature edges // if ( this->FeatureEdges ) { polyNormals = new vlFloatNormals(inPolys->GetNumberOfCells()); for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); cellId++) { poly.ComputeNormal(inPts,npts,pts,n); polyNormals->InsertNormal(cellId,n); } cosAngle = cos ((double) math.DegreesToRadians() * this->FeatureAngle); } numBEdges = numNonManifoldEdges = numFedges = 0; for (cellId=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); cellId++) { for (i=0; i < npts; i++) { p1 = pts[i]; p2 = pts[(i+1)%npts]; Mesh.GetCellEdgeNeighbors(cellId,p1,p2,neighbors); if ( this->BoundaryEdges && (numNei=neighbors.GetNumberOfIds()) < 1 ) { numBEdges++; scalar = 0.0; } else if ( this->NonManifoldEdges && numNei > 1 ) { // check to make sure that this edge hasn't been created before for (j=0; j < numNei; j++) if ( neighbors.GetId(j) < cellId ) break; if ( j >= numNei ) { numNonManifoldEdges++; scalar = 0.33333; } else continue; } else if ( this->FeatureEdges && numNei == 1 && (nei=neighbors.GetId(0)) > cellId ) { if ( math.Dot(polyNormals->GetNormal(nei),polyNormals->GetNormal(cellId)) <= cosAngle ) { numFedges++; scalar = 0.66667; } else continue; } else continue; // Add edge to output x1 = Mesh.GetPoint(p1); x2 = Mesh.GetPoint(p2); lineIds[0] = newPts->InsertNextPoint(x1); lineIds[1] = newPts->InsertNextPoint(x2); newLines->InsertNextCell(2,lineIds); newScalars->InsertScalar(lineIds[0], scalar); newScalars->InsertScalar(lineIds[1], scalar); } } vlDebugMacro(<<"Created " << numBEdges << " boundary edges, " << numNonManifoldEdges << " non-manifold edges, " << numFedges << " feature edges"); // // Update ourselves. // if ( this->FeatureEdges ) delete polyNormals; this->SetPoints(newPts); this->SetLines(newLines); if ( this->Coloring ) this->PointData.SetScalars(newScalars); else delete newScalars; } void vlFeatureEdges::PrintSelf(ostream& os, vlIndent indent) { vlPolyToPolyFilter::PrintSelf(os,indent); os << indent << "Feature Angle: " << this->FeatureAngle << "\n"; os << indent << "BoundaryEdges: " << (this->BoundaryEdges ? "On\n" : "Off\n"); os << indent << "FeatureEdges: " << (this->FeatureEdges ? "On\n" : "Off\n"); os << indent << "Non-Manifold Edges: " << (this->NonManifoldEdges ? "On\n" : "Off\n"); os << indent << "Coloring: " << (this->Coloring ? "On\n" : "Off\n"); } <|endoftext|>
<commit_before>#include "NTClient.h" using namespace std; NTClient::NTClient(int interval, double _accuracy) { typeIntervalMS = interval; accuracy = _accuracy; hasError = false; firstConnect = true; connected = false; lessonLen = 0; lidx = 0; log = new NTLogger("(Not logged in)"); } NTClient::~NTClient() { delete log; if (wsh != nullptr) { delete wsh; wsh = nullptr; } } bool NTClient::login(string username, string password) { log->type(LOG_HTTP); log->wr("Logging into the NitroType account...\n"); log->setUsername(username); uname = username; pword = password; bool ret = true; string data = string("username="); data += uname; data += "&password="; data += pword; data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT); shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8"); if (res) { bool foundLoginCookie = false; for (int i = 0; i < res->cookies.size(); ++i) { string cookie = res->cookies.at(i); addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie)); if (cookie.find("ntuserrem=") == 0) { foundLoginCookie = true; token = Utils::extractCValue(cookie); log->type(LOG_HTTP); log->wr("Resolved ntuserrem login token.\n"); // addCookie("ntuserrem", token); } } if (!foundLoginCookie) { ret = false; cout << "Unable to locate the login cookie. Maybe try a different account?\n"; } } else { ret = false; cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n"; } bool success = getPrimusSID(); if (!success) return false; return ret; } bool NTClient::connect() { wsh = new Hub(); time_t tnow = time(0); rawCookieStr = Utils::stringifyCookies(&cookies); stringstream uristream; uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1"; string wsURI = uristream.str(); log->type(LOG_CONN); log->wr("Attempting to open a WebSocket on NitroType realtime server...\n"); if (firstConnect) { addListeners(); } // cout << "Cookies: " << rawCookieStr << endl << endl; // Create override headers SMap customHeaders; customHeaders["Cookie"] = rawCookieStr; customHeaders["Origin"] = "https://www.nitrotype.com"; customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36"; // customHeaders["Host"] = "realtime1.nitrotype.com"; wsh->connect(wsURI, (void*)this, customHeaders, 7000); // wsh->connect(wsURI); if (firstConnect) { wsh->run(); firstConnect = false; } return true; } void NTClient::addCookie(string key, string val) { SPair sp = SPair(key, val); cookies.push_back(sp); } bool NTClient::getPrimusSID() { time_t tnow = time(0); log->type(LOG_HTTP); log->wr("Resolving Primus SID...\n"); rawCookieStr = Utils::stringifyCookies(&cookies); stringstream squery; squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1"; string queryStr = squery.str(); httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT); string path = NT_PRIMUS_ENDPOINT + queryStr; shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str()); if (res) { json jres = json::parse(res->body.substr(4, res->body.length())); primusSid = jres["sid"]; log->type(LOG_HTTP); log->wr("Resolved Primus SID successfully.\n"); // addCookie("io", primusSid); } else { cout << "Error retrieving primus handshake data.\n"; return false; } return true; } string NTClient::getJoinPacket(int avgSpeed) { stringstream ss; ss << "4{\"stream\":\"race\",\"msg\":\"join\",\"payload\":{\"debugging\":false,\"avgSpeed\":" << avgSpeed << ",\"forceEarlyPlace\":true,\"track\":\"desert\",\"music\":\"city_nights\"}}"; return ss.str(); } void NTClient::addListeners() { assert(wsh != nullptr); wsh->onError([this](void* udata) { cout << "Failed to connect to WebSocket server." << endl; hasError = true; }); wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) { log->type(LOG_CONN); log->wr("Established a WebSocket connection with the realtime server.\n"); onConnection(wsocket, req); }); wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) { log->type(LOG_CONN); log->wr("Disconnected from the realtime server.\n"); onDisconnection(wsocket, code, msg, len); }); wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) { onMessage(ws, msg, len, opCode); }); } void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) { cout << "Disconn message: " << string(msg, len) << endl; cout << "Disconn code: " << code << endl; } void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) { // Uncomment to dump all raw JSON packets // cout << "Recieved json data:" << endl << j->dump(4) << endl; if (j->operator[]("msg") == "setup") { log->type(LOG_RACE); log->wr("I joined a new race.\n"); } else if (j->operator[]("msg") == "joined") { string joinedName = j->operator[]("payload")["profile"]["username"]; string dispName; try { dispName = j->operator[]("payload")["profile"]["displayName"]; } catch (const exception& e) { dispName = "[None]"; } log->type(LOG_RACE); if (joinedName == "bot") { log->wr("Bot user '"); log->wrs(dispName); log->wrs("' joined the race.\n"); } else { log->wr("Human user '"); log->wrs(joinedName); log->wrs("' joined the race.\n"); } } else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") { log->type(LOG_RACE); log->wr("The race has started.\n"); lesson = j->operator[]("payload")["l"]; lessonLen = lesson.length(); lidx = 0; this_thread::sleep_for(chrono::milliseconds(50)); type(ws); } } void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) { if (opCode != OpCode::TEXT) { cout << "The realtime server did not send a text packet for some reason, ignoring.\n"; return; } string smsg = string(msg, len); if (smsg == "3probe") { // Response to initial connection probe ws->send("5", OpCode::TEXT); // Join packet this_thread::sleep_for(chrono::seconds(1)); string joinTo = getJoinPacket(20); // 20 WPM just to test ws->send(joinTo.c_str(), OpCode::TEXT); } else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') { string rawJData = smsg.substr(1, smsg.length()); json jdata; try { jdata = json::parse(rawJData); } catch (const exception& e) { // Some error parsing real race data, something must be wrong cout << "There was an issue parsing server data: " << e.what() << endl; return; } handleData(ws, &jdata); } else { cout << "Recieved unknown WebSocket message: '" << smsg << "'\n"; } } void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) { // Send a probe, which is required for connection wsocket->send("2probe", OpCode::TEXT); } void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, bool isRight) { json p = { {"stream", "race"}, {"msg", "update"}, {"payload", {}} }; if (isRight) { p["payload"]["t"] = idx; } else { p["payload"]["e"] = idx; } string packet = "4" + p.dump(); ws->send(packet.c_str(), OpCode::TEXT); } void NTClient::type(WebSocket<CLIENT>* ws) { if (lidx > lessonLen) { // All characters have been typed return; } int low = typeIntervalMS - 10; int high = typeIntervalMS + 10; bool isRight = Utils::randBool(accuracy); if (low < 10) { low = 10; } sendTypePacket(ws, lidx, isRight); lidx++; int sleepFor = Utils::randInt(low, high); this_thread::sleep_for(chrono::milliseconds(sleepFor)); type(ws); // Call the function until the lesson has been "typed" }<commit_msg>Typing debug ingo<commit_after>#include "NTClient.h" using namespace std; NTClient::NTClient(int interval, double _accuracy) { typeIntervalMS = interval; accuracy = _accuracy; hasError = false; firstConnect = true; connected = false; lessonLen = 0; lidx = 0; log = new NTLogger("(Not logged in)"); } NTClient::~NTClient() { delete log; if (wsh != nullptr) { delete wsh; wsh = nullptr; } } bool NTClient::login(string username, string password) { log->type(LOG_HTTP); log->wr("Logging into the NitroType account...\n"); log->setUsername(username); uname = username; pword = password; bool ret = true; string data = string("username="); data += uname; data += "&password="; data += pword; data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT); shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8"); if (res) { bool foundLoginCookie = false; for (int i = 0; i < res->cookies.size(); ++i) { string cookie = res->cookies.at(i); addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie)); if (cookie.find("ntuserrem=") == 0) { foundLoginCookie = true; token = Utils::extractCValue(cookie); log->type(LOG_HTTP); log->wr("Resolved ntuserrem login token.\n"); // addCookie("ntuserrem", token); } } if (!foundLoginCookie) { ret = false; cout << "Unable to locate the login cookie. Maybe try a different account?\n"; } } else { ret = false; cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n"; } bool success = getPrimusSID(); if (!success) return false; return ret; } bool NTClient::connect() { wsh = new Hub(); time_t tnow = time(0); rawCookieStr = Utils::stringifyCookies(&cookies); stringstream uristream; uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1"; string wsURI = uristream.str(); log->type(LOG_CONN); log->wr("Attempting to open a WebSocket on NitroType realtime server...\n"); if (firstConnect) { addListeners(); } // cout << "Cookies: " << rawCookieStr << endl << endl; // Create override headers SMap customHeaders; customHeaders["Cookie"] = rawCookieStr; customHeaders["Origin"] = "https://www.nitrotype.com"; customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36"; // customHeaders["Host"] = "realtime1.nitrotype.com"; wsh->connect(wsURI, (void*)this, customHeaders, 7000); // wsh->connect(wsURI); if (firstConnect) { wsh->run(); firstConnect = false; } return true; } void NTClient::addCookie(string key, string val) { SPair sp = SPair(key, val); cookies.push_back(sp); } bool NTClient::getPrimusSID() { time_t tnow = time(0); log->type(LOG_HTTP); log->wr("Resolving Primus SID...\n"); rawCookieStr = Utils::stringifyCookies(&cookies); stringstream squery; squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1"; string queryStr = squery.str(); httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT); string path = NT_PRIMUS_ENDPOINT + queryStr; shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str()); if (res) { json jres = json::parse(res->body.substr(4, res->body.length())); primusSid = jres["sid"]; log->type(LOG_HTTP); log->wr("Resolved Primus SID successfully.\n"); // addCookie("io", primusSid); } else { cout << "Error retrieving primus handshake data.\n"; return false; } return true; } string NTClient::getJoinPacket(int avgSpeed) { stringstream ss; ss << "4{\"stream\":\"race\",\"msg\":\"join\",\"payload\":{\"debugging\":false,\"avgSpeed\":" << avgSpeed << ",\"forceEarlyPlace\":true,\"track\":\"desert\",\"music\":\"city_nights\"}}"; return ss.str(); } void NTClient::addListeners() { assert(wsh != nullptr); wsh->onError([this](void* udata) { cout << "Failed to connect to WebSocket server." << endl; hasError = true; }); wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) { log->type(LOG_CONN); log->wr("Established a WebSocket connection with the realtime server.\n"); onConnection(wsocket, req); }); wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) { log->type(LOG_CONN); log->wr("Disconnected from the realtime server.\n"); onDisconnection(wsocket, code, msg, len); }); wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) { onMessage(ws, msg, len, opCode); }); } void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) { cout << "Disconn message: " << string(msg, len) << endl; cout << "Disconn code: " << code << endl; } void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) { // Uncomment to dump all raw JSON packets // cout << "Recieved json data:" << endl << j->dump(4) << endl; if (j->operator[]("msg") == "setup") { log->type(LOG_RACE); log->wr("I joined a new race.\n"); } else if (j->operator[]("msg") == "joined") { string joinedName = j->operator[]("payload")["profile"]["username"]; string dispName; try { dispName = j->operator[]("payload")["profile"]["displayName"]; } catch (const exception& e) { dispName = "[None]"; } log->type(LOG_RACE); if (joinedName == "bot") { log->wr("Bot user '"); log->wrs(dispName); log->wrs("' joined the race.\n"); } else { log->wr("Human user '"); log->wrs(joinedName); log->wrs("' joined the race.\n"); } } else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") { log->type(LOG_RACE); log->wr("The race has started.\n"); lesson = j->operator[]("payload")["l"]; lessonLen = lesson.length(); lidx = 0; this_thread::sleep_for(chrono::milliseconds(50)); type(ws); } } void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) { if (opCode != OpCode::TEXT) { cout << "The realtime server did not send a text packet for some reason, ignoring.\n"; return; } string smsg = string(msg, len); if (smsg == "3probe") { // Response to initial connection probe ws->send("5", OpCode::TEXT); // Join packet this_thread::sleep_for(chrono::seconds(1)); string joinTo = getJoinPacket(20); // 20 WPM just to test ws->send(joinTo.c_str(), OpCode::TEXT); } else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') { string rawJData = smsg.substr(1, smsg.length()); json jdata; try { jdata = json::parse(rawJData); } catch (const exception& e) { // Some error parsing real race data, something must be wrong cout << "There was an issue parsing server data: " << e.what() << endl; return; } handleData(ws, &jdata); } else { cout << "Recieved unknown WebSocket message: '" << smsg << "'\n"; } } void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) { // Send a probe, which is required for connection wsocket->send("2probe", OpCode::TEXT); } void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, bool isRight) { json p = { {"stream", "race"}, {"msg", "update"}, {"payload", {}} }; if (isRight) { p["payload"]["t"] = idx; } else { p["payload"]["e"] = idx; } string packet = "4" + p.dump(); ws->send(packet.c_str(), OpCode::TEXT); } void NTClient::type(WebSocket<CLIENT>* ws) { if (lidx > lessonLen) { // All characters have been typed return; } int low = typeIntervalMS - 10; int high = typeIntervalMS + 10; bool isRight = Utils::randBool(accuracy); int sleepFor = Utils::randInt(low, high); if (low < 10) { low = 10; } cout << "Typing with index: " << lidx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl; sendTypePacket(ws, lidx, isRight); lidx++; this_thread::sleep_for(chrono::milliseconds(sleepFor)); type(ws); // Call the function until the lesson has been "typed" }<|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2014. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "Options.hpp" #include "cxxopts.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; cxxopts::Options options("eddic", " source.eddi"); void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<std::string>()->default_value("100"), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<std::string>()->implicit_value("0")->default_value("2"), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; po::options_description backend("Backend options"); backend.add_options() ("log", po::value<std::string>()->default_value("0"), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", po::value<std::string>(), "Input file") ; all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); options.add_options("General") ("h,help", "Generate this help message") ("S,assembly", "Generate only the assembly") ("k,keep", "Keep the assembly file") ("version", "Print the version of eddic") ("o,output", "Set the name of the executable", cxxopts::value<std::string>()->default_value("a.out")) ("g,debug", "Add debugging symbols") ("template-depth", "Define the maximum template depth", cxxopts::value<std::string>()->default_value("100")) ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; options.add_options("Display") ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; options.add_options("Optimization") ("O,Opt", "Define the optimization level", cxxopts::value<std::string>()->implicit_value("0")->default_value("2")) ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; options.add_options("Backend") ("log", "Define the logging", cxxopts::value<std::string>()->default_value("0")) ("q,quiet", "Do not print anything") ("v,verbose", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", "Input file", cxxopts::value<std::string>()) ; add_trigger("warning-all", {"warning-unused", "warning-cast", "warning-effects", "warning-includes"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); add_trigger("__3", {"funroll-loops", "fcomplete-peel-loops", "funswitch-loops"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].as<std::string>(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = "0"; } else if(options.count("O1")){ configuration->values["Opt"].value = "1"; } else if(options.count("O2")){ configuration->values["Opt"].value = "2"; } else if(options.count("O3")){ configuration->values["Opt"].value = "3"; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } if(configuration->option_int_value("Opt") >= 3){ trigger_childs(configuration, triggers["__3"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Invalid command line options: Multiple occurrences of " << e.get_option_name() << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return values[option_name].value; } int Configuration::option_int_value(const std::string& option_name){ return boost::lexical_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; std::cout << options.help({"General", "Display", "Optimization"}) << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.2.3" << std::endl; } <commit_msg>Clean<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2014. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "Options.hpp" #include "cxxopts.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; cxxopts::Options options("eddic", " source.eddi"); void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<std::string>()->default_value("100"), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<std::string>()->implicit_value("0")->default_value("2"), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; po::options_description backend("Backend options"); backend.add_options() ("log", po::value<std::string>()->default_value("0"), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", po::value<std::string>(), "Input file") ; all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); options.add_options("General") ("h,help", "Generate this help message") ("S,assembly", "Generate only the assembly") ("k,keep", "Keep the assembly file") ("version", "Print the version of eddic") ("o,output", "Set the name of the executable", cxxopts::value<std::string>()->default_value("a.out")) ("g,debug", "Add debugging symbols") ("template-depth", "Define the maximum template depth", cxxopts::value<std::string>()->default_value("100")) ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts") ("warning-effects", "Warn about statements without effect") ("warning-includes", "Warn about useless includes") ; options.add_options("Display") ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)") ; options.add_options("Optimization") ("O,Opt", "Define the optimization level", cxxopts::value<std::string>()->implicit_value("0")->default_value("2")) ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations improving the speed but do imply a space tradeoff.") ("O3", "Enable all optimizations improving the speed but can increase the size of the program.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining") ("funroll-loops", "Enable Loop Unrolling") ("fcomplete-peel-loops", "Enable Complete Loop Peeling") ; options.add_options("Backend") ("log", "Define the logging", cxxopts::value<std::string>()->default_value("0")) ("q,quiet", "Do not print anything") ("v,verbose", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("time", "Activate the timing system") ("stats", "Activate the statistics system") ("input", "Input file", cxxopts::value<std::string>()) ; add_trigger("warning-all", {"warning-unused", "warning-cast", "warning-effects", "warning-includes"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); add_trigger("__3", {"funroll-loops", "fcomplete-peel-loops", "funswitch-loops"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].as<std::string>(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = "0"; } else if(options.count("O1")){ configuration->values["Opt"].value = "1"; } else if(options.count("O2")){ configuration->values["Opt"].value = "2"; } else if(options.count("O3")){ configuration->values["Opt"].value = "3"; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } if(configuration->option_int_value("Opt") >= 3){ trigger_childs(configuration, triggers["__3"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options: " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Invalid command line options: Multiple occurrences of " << e.get_option_name() << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return values[option_name].value; } int Configuration::option_int_value(const std::string& option_name){ return boost::lexical_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; std::cout << options.help({"General", "Display", "Optimization"}) << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.2.3" << std::endl; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // Licensed to Qualys, Inc. (QUALYS) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // QUALYS licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// @file /// @brief IronBee - UUID Test Functions /// /// @author Brian Rectanus <[email protected]> ////////////////////////////////////////////////////////////////////////////// #include "ironbee_config_auto.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" #define TESTING #include "util/uuid.c" struct testval { const char *str; ib_status_t ret; ib_uuid_t val; }; static struct testval uuidstr[] = { { "01234567-89ab-cdef-0123-456789abcdef", IB_OK, { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef } }, { "01234567-89ab-cdef-0123-456789abcdef ", IB_EINVAL, { 0 } }, { " 01234567-89ab-cdef-0123-456789abcdef", IB_EINVAL, { 0 } }, { " 01234567-89ab-cdef-0123-456789abcdef ", IB_EINVAL, { 0 } }, { "0123456789abcdef0123456789abcdef", IB_EINVAL, { 0 } }, { "1234", IB_EINVAL, { 0 } }, { "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", IB_EINVAL, { 0 } }, { "0123456789abcdef0123456789abcdex", IB_EINVAL, { 0 } }, { "0123456789abcdef0123456789abcdxf", IB_EINVAL, { 0 } }, { "0123456789abcdef0123456789abcdefxxx", IB_EINVAL, { 0 } }, { "xxx0123456789abcdef0123456789abcdef", IB_EINVAL, { 0 } }, { "xxx0123456789abcdef0123456789abcdefxxx", IB_EINVAL, { 0 } }, { NULL, IB_OK, { 0 } } }; /* -- Tests -- */ /// @test Test util uuid library - ib_uuid_ascii_to_bin() TEST(TestIBUtilUUID, test_field_create) { struct testval *rec; ib_uuid_t uuid; ib_status_t rc; for (rec = &uuidstr[0];rec->str != NULL; ++rec) { ib_uuid_t uuid = { 0 }; rc = ib_uuid_ascii_to_bin(&uuid, rec->str); ASSERT_TRUE(rc == rec->ret) << "ib_uuid_ascii_to_bin() failed - bad return code: " << rec->str; if (rc == IB_OK) { ASSERT_TRUE(memcmp(&rec->val, &uuid, 16) == 0) << "ib_uuid_ascii_to_bin() failed: " << rec->str << " - wrong binary value"; } } } <commit_msg>test/test_util_uuid.cc: Fix warnings.<commit_after>////////////////////////////////////////////////////////////////////////////// // Licensed to Qualys, Inc. (QUALYS) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // QUALYS licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// /// @file /// @brief IronBee - UUID Test Functions /// /// @author Brian Rectanus <[email protected]> ////////////////////////////////////////////////////////////////////////////// #include "ironbee_config_auto.h" #include "gtest/gtest.h" #include "gtest/gtest-spi.h" #define TESTING #include "util/uuid.c" struct testval { const char *str; ib_status_t ret; ib_uuid_t val; }; static struct testval uuidstr[] = { { "01234567-89ab-cdef-0123-456789abcdef", IB_OK, { { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef } } }, { "01234567-89ab-cdef-0123-456789abcdef ", IB_EINVAL, { { 0 } } }, { " 01234567-89ab-cdef-0123-456789abcdef", IB_EINVAL, { { 0 } } }, { " 01234567-89ab-cdef-0123-456789abcdef ", IB_EINVAL, { { 0 } } }, { "0123456789abcdef0123456789abcdef", IB_EINVAL, { { 0 } } }, { "1234", IB_EINVAL, { { 0 } } }, { "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", IB_EINVAL, { { 0 } } }, { "0123456789abcdef0123456789abcdex", IB_EINVAL, { { 0 } } }, { "0123456789abcdef0123456789abcdxf", IB_EINVAL, { { 0 } } }, { "0123456789abcdef0123456789abcdefxxx", IB_EINVAL, { { 0 } } }, { "xxx0123456789abcdef0123456789abcdef", IB_EINVAL, { { 0 } } }, { "xxx0123456789abcdef0123456789abcdefxxx", IB_EINVAL, { { 0 } } }, { NULL, IB_OK, { { 0 } } } }; /* -- Tests -- */ /// @test Test util uuid library - ib_uuid_ascii_to_bin() TEST(TestIBUtilUUID, test_field_create) { struct testval *rec; ib_status_t rc; for (rec = &uuidstr[0];rec->str != NULL; ++rec) { ib_uuid_t uuid = { { 0 } }; rc = ib_uuid_ascii_to_bin(&uuid, rec->str); ASSERT_TRUE(rc == rec->ret) << "ib_uuid_ascii_to_bin() failed - bad return code: " << rec->str; if (rc == IB_OK) { ASSERT_TRUE(memcmp(&rec->val, &uuid, 16) == 0) << "ib_uuid_ascii_to_bin() failed: " << rec->str << " - wrong binary value"; } } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "assert.hpp" #include "Options.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<int>()->default_value(100), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts"); po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)"); po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<int>()->implicit_value(0)->default_value(2), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations. This can be slow for big programs.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining"); po::options_description backend("Backend options"); backend.add_options() ("log", po::value<int>()->default_value(0), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("input", po::value<std::string>(), "Input file"); all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); add_trigger("warning-all", {"warning-unused", "warning-cast"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].value(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = 0; } else if(options.count("O1")){ configuration->values["Opt"].value = 1; } else if(options.count("O2")){ configuration->values["Opt"].value = 2; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Only one file can be compiled" << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return boost::any_cast<std::string>(values[option_name].value); } int Configuration::option_int_value(const std::string& option_name){ return boost::any_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.1.4" << std::endl; } <commit_msg>Add option to activate the timing system<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <string> #include <iostream> #include <vector> #include <atomic> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include "assert.hpp" #include "Options.hpp" using namespace eddic; namespace po = boost::program_options; namespace { std::pair<std::string, std::string> numeric_parser(const std::string& s){ if (s.find("-32") == 0) { return make_pair("32", std::string("true")); } else if (s.find("-64") == 0) { return make_pair("64", std::string("true")); } else { return make_pair(std::string(), std::string()); } } std::atomic<bool> description_flag; po::options_description visible("Usage : eddic [options] source.eddi"); po::options_description all("Usage : eddic [options] source.eddi"); std::unordered_map<std::string, std::vector<std::string>> triggers; void add_trigger(const std::string& option, const std::vector<std::string>& childs){ triggers[option] = childs; } void init_descriptions(){ po::options_description general("General options"); general.add_options() ("help,h", "Generate this help message") ("assembly,S", "Generate only the assembly") ("keep,k", "Keep the assembly file") ("version", "Print the version of eddic") ("output,o", po::value<std::string>()->default_value("a.out"), "Set the name of the executable") ("debug,g", "Add debugging symbols") ("template-depth", po::value<int>()->default_value(100), "Define the maximum template depth") ("32", "Force the compilation for 32 bits platform") ("64", "Force the compilation for 64 bits platform") ("warning-all", "Enable all the warning messages") ("warning-unused", "Warn about unused variables, parameters and functions") ("warning-cast", "Warn about useless casts"); po::options_description display("Display options"); display.add_options() ("ast", "Print the Abstract Syntax Tree representation of the source") ("ast-raw", "Print the Abstract Syntax Tree representation of the source coming directly from the parser before any pass is run on the AST. ") ("ast-only", "Only print the Abstract Syntax Tree representation of the source (do not continue compilation after printing)") ("mtac", "Print the medium-level Three Address Code representation of the source") ("mtac-opt", "Print the medium-level Three Address Code representation of the source before any optimization has been performed") ("mtac-only", "Only print the medium-level Three Address Code representation of the source (do not continue compilation after printing)") ("ltac-pre", "Print the low-level Three Address Code representation of the source before allocation of registers") ("ltac-alloc", "Print the low-level Three Address Code representation of the source before optimization") ("ltac", "Print the final low-level Three Address Code representation of the source") ("ltac-only", "Only print the low-level Three Address Code representation of the source (do not continue compilation after printing)"); po::options_description optimization("Optimization options"); optimization.add_options() ("Opt,O", po::value<int>()->implicit_value(0)->default_value(2), "Define the optimization level") ("O0", "Disable all optimizations") ("O1", "Enable low-level optimizations") ("O2", "Enable all optimizations. This can be slow for big programs.") ("fglobal-optimization", "Enable optimizer engine") ("fparameter-allocation", "Enable parameter allocation in register") ("fpeephole-optimization", "Enable peephole optimizer") ("fomit-frame-pointer", "Omit frame pointer from functions") ("finline-functions", "Enable inlining") ("fno-inline-functions", "Disable inlining"); po::options_description backend("Backend options"); backend.add_options() ("log", po::value<int>()->default_value(0), "Define the logging") ("quiet,q", "Do not print anything") ("verbose,v", "Make the compiler verbose") ("single-threaded", "Disable the multi-threaded optimization") ("timing", "Activate timing system") ("input", po::value<std::string>(), "Input file"); all.add(general).add(display).add(optimization).add(backend); visible.add(general).add(display).add(optimization); add_trigger("warning-all", {"warning-unused", "warning-cast"}); //Special triggers for optimization levels add_trigger("__1", {"fpeephole-optimization"}); add_trigger("__2", {"fglobal-optimization", "fomit-frame-pointer", "fparameter-allocation", "finline-functions"}); } inline void trigger_childs(std::shared_ptr<Configuration> configuration, const std::vector<std::string>& childs){ for(auto& child : childs){ configuration->values[child].defined = true; configuration->values[child].value = std::string("true"); } } } //end of anonymous namespace std::shared_ptr<Configuration> eddic::parseOptions(int argc, const char* argv[]) { //Create a new configuration auto configuration = std::make_shared<Configuration>(); try { //Only if the description has not been already defined if(!description_flag.load()){ bool old_value = description_flag.load(); if(description_flag.compare_exchange_strong(old_value, true)){ init_descriptions(); } } //Add the option of the input file po::positional_options_description p; p.add("input", -1); //Create a new set of options po::variables_map options; //Parse the command line options po::store(po::command_line_parser(argc, argv).options(all).extra_parser(numeric_parser).positional(p).run(), options); po::notify(options); //Transfer the options in the eddic configuration for(auto& option : all.options()){ ConfigValue value; if(options.count(option->long_name())){ value.defined = true; value.value = options[option->long_name()].value(); } else { value.defined = false; value.value = std::string("false"); } configuration->values[option->long_name()] = value; } if(options.count("O0") + options.count("O1") + options.count("O2") > 1){ std::cout << "Invalid command line options : only one optimization level should be set" << std::endl; return nullptr; } if(options.count("64") && options.count("32")){ std::cout << "Invalid command line options : a compilation cannot be both 32 and 64 bits" << std::endl; return nullptr; } //Update optimization level based on special switches if(options.count("O0")){ configuration->values["Opt"].value = 0; } else if(options.count("O1")){ configuration->values["Opt"].value = 1; } else if(options.count("O2")){ configuration->values["Opt"].value = 2; } //Triggers dependent options for(auto& trigger : triggers){ if(configuration->option_defined(trigger.first)){ trigger_childs(configuration, trigger.second); } } if(configuration->option_int_value("Opt") >= 1){ trigger_childs(configuration, triggers["__1"]); } if(configuration->option_int_value("Opt") >= 2){ trigger_childs(configuration, triggers["__2"]); } } catch (const po::ambiguous_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::unknown_option& e) { std::cout << "Invalid command line options : " << e.what() << std::endl; return nullptr; } catch (const po::multiple_occurrences& e) { std::cout << "Only one file can be compiled" << std::endl; return nullptr; } return configuration; } bool Configuration::option_defined(const std::string& option_name){ return values[option_name].defined; } std::string Configuration::option_value(const std::string& option_name){ return boost::any_cast<std::string>(values[option_name].value); } int Configuration::option_int_value(const std::string& option_name){ return boost::any_cast<int>(values[option_name].value); } void eddic::print_help(){ std::cout << visible << std::endl; } void eddic::print_version(){ std::cout << "eddic version 1.1.4" << std::endl; } <|endoftext|>
<commit_before>#include "src/holy_thread.h" #include "src/pink_epoll.h" #include "src/pink_item.h" #include "include/pink_conn.h" namespace pink { HolyThread::HolyThread(int port, ConnFactory *conn_factory, int cron_interval) : ServerThread::ServerThread(port, cron_interval), conn_factory_(conn_factory) { pthread_rwlock_init(&rwlock_, NULL); } HolyThread::HolyThread(const std::string& bind_ip, int port, ConnFactory *conn_factory, int cron_interval) : ServerThread::ServerThread(bind_ip, port, cron_interval), conn_factory_(conn_factory) { pthread_rwlock_init(&rwlock_, NULL); } HolyThread::HolyThread(const std::set<std::string>& bind_ips, int port, ConnFactory *conn_factory, int cron_interval) : ServerThread::ServerThread(bind_ips, port, cron_interval), conn_factory_(conn_factory) { pthread_rwlock_init(&rwlock_, NULL); } HolyThread::~HolyThread() { Cleanup(); } void HolyThread::HandleNewConn(const int connfd, const std::string &ip_port) { PinkConn *tc = conn_factory_->NewPinkConn(connfd, ip_port, this); tc->SetNonblock(); { RWLock l(&rwlock_, true); conns_[connfd] = tc; } pink_epoll_->PinkAddEvent(connfd, EPOLLIN); } void HolyThread::HandleConnEvent(PinkFiredEvent *pfe) { if (pfe == NULL) { return; } PinkConn *in_conn = NULL; int should_close = 0; std::map<int, PinkConn *>::iterator iter; { RWLock l(&rwlock_, false); if ((iter = conns_.find(pfe->fd)) == conns_.end()) { pink_epoll_->PinkDelEvent(pfe->fd); return; } } if (pfe->mask & EPOLLIN) { in_conn = iter->second; ReadStatus getRes = in_conn->GetRequest(); struct timeval now; gettimeofday(&now, NULL); in_conn->set_last_interaction(now); if (getRes != kReadAll && getRes != kReadHalf) { // kReadError kReadClose kFullError kParseError should_close = 1; } else if (in_conn->is_reply()) { pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLOUT); } else { return; } } if (pfe->mask & EPOLLOUT) { in_conn = iter->second; WriteStatus write_status = in_conn->SendReply(); if (write_status == kWriteAll) { in_conn->set_is_reply(false); pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); } else if (write_status == kWriteHalf) { return; } else if (write_status == kWriteError) { should_close = 1; } } if ((pfe->mask & EPOLLERR) || (pfe->mask & EPOLLHUP) || should_close) { log_info("close pfe fd here"); pink_epoll_->PinkDelEvent(pfe->fd); close(pfe->fd); delete(in_conn); in_conn = NULL; RWLock l(&rwlock_, true); conns_.erase(pfe->fd); } } // clean conns void HolyThread::Cleanup() { RWLock l(&rwlock_, true); PinkConn *in_conn; std::map<int, PinkConn *>::iterator iter = conns_.begin(); for (; iter != conns_.end(); iter++) { close(iter->first); in_conn = iter->second; delete in_conn; } } extern ServerThread *NewHolyThread(int port, ConnFactory *conn_factory, int cron_interval) { return new HolyThread(port, conn_factory, cron_interval); } extern ServerThread *NewHolyThread(const std::string &bind_ip, int port, ConnFactory *conn_factory, int cron_interval) { return new HolyThread(bind_ip, port, conn_factory, cron_interval); } extern ServerThread *NewHolyThread(const std::set<std::string>& bind_ips, int port, ConnFactory *conn_factory, int cron_interval) { return new HolyThread(bind_ips, port, conn_factory, cron_interval); } }; // namespace pink <commit_msg>fix delete null pointer when there is only EPOLLERR or EPOLLHUP event<commit_after>#include "src/holy_thread.h" #include "src/pink_epoll.h" #include "src/pink_item.h" #include "include/pink_conn.h" namespace pink { HolyThread::HolyThread(int port, ConnFactory *conn_factory, int cron_interval) : ServerThread::ServerThread(port, cron_interval), conn_factory_(conn_factory) { pthread_rwlock_init(&rwlock_, NULL); } HolyThread::HolyThread(const std::string& bind_ip, int port, ConnFactory *conn_factory, int cron_interval) : ServerThread::ServerThread(bind_ip, port, cron_interval), conn_factory_(conn_factory) { pthread_rwlock_init(&rwlock_, NULL); } HolyThread::HolyThread(const std::set<std::string>& bind_ips, int port, ConnFactory *conn_factory, int cron_interval) : ServerThread::ServerThread(bind_ips, port, cron_interval), conn_factory_(conn_factory) { pthread_rwlock_init(&rwlock_, NULL); } HolyThread::~HolyThread() { Cleanup(); } void HolyThread::HandleNewConn(const int connfd, const std::string &ip_port) { PinkConn *tc = conn_factory_->NewPinkConn(connfd, ip_port, this); tc->SetNonblock(); { RWLock l(&rwlock_, true); conns_[connfd] = tc; } pink_epoll_->PinkAddEvent(connfd, EPOLLIN); } void HolyThread::HandleConnEvent(PinkFiredEvent *pfe) { if (pfe == NULL) { return; } PinkConn *in_conn = NULL; int should_close = 0; std::map<int, PinkConn *>::iterator iter; { RWLock l(&rwlock_, false); if ((iter = conns_.find(pfe->fd)) == conns_.end()) { pink_epoll_->PinkDelEvent(pfe->fd); return; } } in_conn = iter->second; if (pfe->mask & EPOLLIN) { ReadStatus getRes = in_conn->GetRequest(); struct timeval now; gettimeofday(&now, NULL); in_conn->set_last_interaction(now); if (getRes != kReadAll && getRes != kReadHalf) { // kReadError kReadClose kFullError kParseError should_close = 1; } else if (in_conn->is_reply()) { pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLOUT); } else { return; } } if (pfe->mask & EPOLLOUT) { WriteStatus write_status = in_conn->SendReply(); if (write_status == kWriteAll) { in_conn->set_is_reply(false); pink_epoll_->PinkModEvent(pfe->fd, 0, EPOLLIN); } else if (write_status == kWriteHalf) { return; } else if (write_status == kWriteError) { should_close = 1; } } if ((pfe->mask & EPOLLERR) || (pfe->mask & EPOLLHUP) || should_close) { log_info("close pfe fd here"); pink_epoll_->PinkDelEvent(pfe->fd); close(pfe->fd); delete(in_conn); in_conn = NULL; RWLock l(&rwlock_, true); conns_.erase(pfe->fd); } } // clean conns void HolyThread::Cleanup() { RWLock l(&rwlock_, true); PinkConn *in_conn; std::map<int, PinkConn *>::iterator iter = conns_.begin(); for (; iter != conns_.end(); iter++) { close(iter->first); in_conn = iter->second; delete in_conn; } } extern ServerThread *NewHolyThread(int port, ConnFactory *conn_factory, int cron_interval) { return new HolyThread(port, conn_factory, cron_interval); } extern ServerThread *NewHolyThread(const std::string &bind_ip, int port, ConnFactory *conn_factory, int cron_interval) { return new HolyThread(bind_ip, port, conn_factory, cron_interval); } extern ServerThread *NewHolyThread(const std::set<std::string>& bind_ips, int port, ConnFactory *conn_factory, int cron_interval) { return new HolyThread(bind_ips, port, conn_factory, cron_interval); } }; // namespace pink <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "TestSuite.h" int TestSuite_Main(int argc, char *argv[]) { ::llbc::LLBC_Startup(); ::llbc::LLBC_ITestCase *test = NULL; /* Common module testcases. */ test = LLBC_New0(TestCase_Com_Version); // test = LLBC_New0(TestCase_Com_DataType); // test = LLBC_New0(TestCase_Com_Endian); // test = LLBC_New0(TestCase_Com_Stream); // test = LLBC_New0(TestCase_Com_Error); // test = LLBC_New0(TestCase_Com_Compiler); // test = LLBC_New0(TestCase_Com_RTTI); /* Core module testcases. */ // test = LLBC_New0(TestCase_Core_OS_Symbol); // test = LLBC_New0(TestCase_Core_OS_Thread); // test = LLBC_New0(TestCase_Core_OS_Console); // test = LLBC_New0(TestCase_Core_Algo_RingBuffer); // test = LLBC_New0(TestCase_Core_Bundle); // test = LLBC_New0(TestCase_Core_Utils_Text); // test = LLBC_New0(TestCase_Core_Utils_Debug); // test = LLBC_New0(TestCase_Core_Utils_Algorithm); // test = LLBC_New0(TestCase_Core_Utils_Delegate); // test = LLBC_New0(TestCase_Core_Utils_MD5); // test = LLBC_New0(TestCase_Core_Utils_Base64); // test = LLBC_New0(TestCase_Core_Utils_Misc); // test = LLBC_New0(TestCase_Core_Utils_Network); // test = LLBC_New0(TestCase_Core_Helper_StlHelper); // test = LLBC_New0(TestCase_Core_File_File); // test = LLBC_New0(TestCase_Core_File_Directory); // test = LLBC_New0(TestCase_Core_VariantTest); test = LLBC_New0(TestCase_Core_Config_Ini); // test = LLBC_New0(TestCase_Core_Time_Time); // test = LLBC_New0(TestCase_Core_Event); // test = LLBC_New0(TestCase_Core_Config_Property); // test = LLBC_New0(TestCase_Core_Thread_Lock); // test = LLBC_New0(TestCase_Core_Thread_RWLock); // test = LLBC_New0(TestCase_Core_Thread_Guard); // test = LLBC_New0(TestCase_Core_Thread_CV); // test = LLBC_New0(TestCase_Core_Thread_Semaphore); // test = LLBC_New0(TestCase_Core_Thread_Tls); // test = LLBC_New0(TestCase_Core_Thread_ThreadMgr); // test = LLBC_New0(TestCase_Core_Thread_Task); // test = LLBC_New0(TestCase_Core_Random); // test = LLBC_New0(TestCase_Core_Log); // test = LLBC_New0(TestCase_Core_Entity); // test = LLBC_New0(TestCase_Core_Transcoder); // test = LLBC_New0(TestCase_Core_Library); // test = LLBC_New0(TestCase_ObjBase_Object); // test = LLBC_New0(TestCase_ObjBase_Array); // test = LLBC_New0(TestCase_ObjBase_Dictionary); // test = LLBC_New0(TestCase_Core_ObjectPool); // test = LLBC_New0(TestCase_Core_Recycle); /* Communication module testcases. */ // test = LLBC_New0(TestCase_Comm_EventInSvc); // test = LLBC_New0(TestCase_Comm_Timer); // test = LLBC_New0(TestCase_Comm_PacketOp); // test = LLBC_New0(TestCase_Comm_ReleasePool); // test = LLBC_New0(TestCase_Comm_Facade); // test = LLBC_New0(TestCase_Comm_SvcBase); // test = LLBC_New0(TestCase_Comm_SvcFps); // test = LLBC_New0(TestCase_Comm_SvcStartStop); // test = LLBC_New0(TestCase_Comm_Svc); // test = LLBC_New0(TestCase_Comm_SendBytes); // test = LLBC_New0(TestCase_Comm_Multicast); // test = LLBC_New0(TestCase_Comm_ExternalDriveSvc); // test = LLBC_New0(TestCase_Comm_LazyTask); // test = LLBC_New0(TestCase_Comm_ProtoStackCtrl); // test = LLBC_New0(TestCase_App_AppTest); int ret = LLBC_FAILED; if (test) { ret = test->Run(argc, argv); LLBC_Delete(test); } else { LLBC_PrintLine("Not specific any testcase to run!"); } ::llbc::LLBC_Cleanup(); return ret; } <commit_msg>Block Ini test case code run.<commit_after>// The MIT License (MIT) // Copyright (c) 2013 lailongwei<[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "TestSuite.h" int TestSuite_Main(int argc, char *argv[]) { ::llbc::LLBC_Startup(); ::llbc::LLBC_ITestCase *test = NULL; /* Common module testcases. */ test = LLBC_New0(TestCase_Com_Version); // test = LLBC_New0(TestCase_Com_DataType); // test = LLBC_New0(TestCase_Com_Endian); // test = LLBC_New0(TestCase_Com_Stream); // test = LLBC_New0(TestCase_Com_Error); // test = LLBC_New0(TestCase_Com_Compiler); // test = LLBC_New0(TestCase_Com_RTTI); /* Core module testcases. */ // test = LLBC_New0(TestCase_Core_OS_Symbol); // test = LLBC_New0(TestCase_Core_OS_Thread); // test = LLBC_New0(TestCase_Core_OS_Console); // test = LLBC_New0(TestCase_Core_Algo_RingBuffer); // test = LLBC_New0(TestCase_Core_Bundle); // test = LLBC_New0(TestCase_Core_Utils_Text); // test = LLBC_New0(TestCase_Core_Utils_Debug); // test = LLBC_New0(TestCase_Core_Utils_Algorithm); // test = LLBC_New0(TestCase_Core_Utils_Delegate); // test = LLBC_New0(TestCase_Core_Utils_MD5); // test = LLBC_New0(TestCase_Core_Utils_Base64); // test = LLBC_New0(TestCase_Core_Utils_Misc); // test = LLBC_New0(TestCase_Core_Utils_Network); // test = LLBC_New0(TestCase_Core_Helper_StlHelper); // test = LLBC_New0(TestCase_Core_File_File); // test = LLBC_New0(TestCase_Core_File_Directory); // test = LLBC_New0(TestCase_Core_VariantTest); // test = LLBC_New0(TestCase_Core_Config_Ini); // test = LLBC_New0(TestCase_Core_Time_Time); // test = LLBC_New0(TestCase_Core_Event); // test = LLBC_New0(TestCase_Core_Config_Property); // test = LLBC_New0(TestCase_Core_Thread_Lock); // test = LLBC_New0(TestCase_Core_Thread_RWLock); // test = LLBC_New0(TestCase_Core_Thread_Guard); // test = LLBC_New0(TestCase_Core_Thread_CV); // test = LLBC_New0(TestCase_Core_Thread_Semaphore); // test = LLBC_New0(TestCase_Core_Thread_Tls); // test = LLBC_New0(TestCase_Core_Thread_ThreadMgr); // test = LLBC_New0(TestCase_Core_Thread_Task); // test = LLBC_New0(TestCase_Core_Random); // test = LLBC_New0(TestCase_Core_Log); // test = LLBC_New0(TestCase_Core_Entity); // test = LLBC_New0(TestCase_Core_Transcoder); // test = LLBC_New0(TestCase_Core_Library); // test = LLBC_New0(TestCase_ObjBase_Object); // test = LLBC_New0(TestCase_ObjBase_Array); // test = LLBC_New0(TestCase_ObjBase_Dictionary); // test = LLBC_New0(TestCase_Core_ObjectPool); // test = LLBC_New0(TestCase_Core_Recycle); /* Communication module testcases. */ // test = LLBC_New0(TestCase_Comm_EventInSvc); // test = LLBC_New0(TestCase_Comm_Timer); // test = LLBC_New0(TestCase_Comm_PacketOp); // test = LLBC_New0(TestCase_Comm_ReleasePool); // test = LLBC_New0(TestCase_Comm_Facade); // test = LLBC_New0(TestCase_Comm_SvcBase); // test = LLBC_New0(TestCase_Comm_SvcFps); // test = LLBC_New0(TestCase_Comm_SvcStartStop); // test = LLBC_New0(TestCase_Comm_Svc); // test = LLBC_New0(TestCase_Comm_SendBytes); // test = LLBC_New0(TestCase_Comm_Multicast); // test = LLBC_New0(TestCase_Comm_ExternalDriveSvc); // test = LLBC_New0(TestCase_Comm_LazyTask); // test = LLBC_New0(TestCase_Comm_ProtoStackCtrl); // test = LLBC_New0(TestCase_App_AppTest); int ret = LLBC_FAILED; if (test) { ret = test->Run(argc, argv); LLBC_Delete(test); } else { LLBC_PrintLine("Not specific any testcase to run!"); } ::llbc::LLBC_Cleanup(); return ret; } <|endoftext|>
<commit_before>/* * mapping_data.cc * * Created on: Mar 19, 2015 * Author: isovic */ #include "mapping_data.h" MappingData::MappingData() { bins.clear(); intermediate_mappings.clear(); final_mapping_ptrs.clear(); bin_size = -1; num_seeds_over_limit = 0; num_seeds_with_no_hits = 0; num_seeds_errors = 0; num_similar_mappings = 0; num_same_mappings = 0; avg_covered_bases_of_all_mappings = 0; std_covered_bases_of_all_mappings = 0; median_covered_bases_of_all_mappings = 0; iteration = 0; unmapped_reason = std::string(""); num_region_iterations = 0; mapping_quality = 0; metagen_alignment_score = 0; time_region_selection = 0.0; time_mapping = 0.0; time_alignment = 0.0; time_region_seed_lookup = 0.0; time_region_hitsort = 0.0; time_region_conversion = 0.0; time_region_alloc = 0.0; time_region_counting = 0.0; } MappingData::~MappingData() { vertices.Clear(); bins.clear(); for (int64_t i = 0; i < intermediate_mappings.size(); i++) { if (intermediate_mappings[i]) delete intermediate_mappings[i]; intermediate_mappings[i] = NULL; } intermediate_mappings.clear(); unmapped_reason = std::string(""); num_region_iterations = 0; mapping_quality = 0; metagen_alignment_score = 0; } bool MappingData::IsMapped() { for (int32_t i=0; i<final_mapping_ptrs.size(); i++) { if (final_mapping_ptrs[i]->IsMapped() == true) { return true; }; } return false; } bool MappingData::IsAligned() { for (int32_t i=0; i<final_mapping_ptrs.size(); i++) { if (final_mapping_ptrs[i]->IsAligned() == true) { return true; }; } return false; } std::string MappingData::VerboseMappingDataToString_(const std::vector<PathGraphEntry *> *mapping_data, const Index *index, const SingleSequence *read) const { std::stringstream ss; int64_t reference_length = index->get_data_length(); int64_t read_length = read->get_data_length(); ss << "-----------------------\n"; ss << "--- num_entries = " << mapping_data->size() << "\n"; ss << "--- read id = " << read->get_sequence_absolute_id() << "\n"; ss << "--- read name = " << read->get_header() << "\n"; ss << "--- read_length = " << read_length << "\n"; ss << "--- reference_length = " << reference_length << "\n"; for (int64_t i = (mapping_data->size() - 1); i >= 0; i--) { // ss << "--- [" << i << "] "; ss << "[" << i << "/" << mapping_data->size() << "] "; int64_t start_location = 0, start_location_raw = 0; ss << "local_score_id = " << mapping_data->at(i)->get_mapping_data().local_score_id; ss << "\n ° " << mapping_data->at(i)->VerboseToString(); ss << "\n ° r_id = " << mapping_data->at(i)->get_region_data().reference_id << ", fwd_r_id = " << (mapping_data->at(i)->get_region_data().reference_id % index->get_num_sequences_forward()) << ", region_index = " << mapping_data->at(i)->get_region_data().region_index; ss << "\n ° \"" << index->get_headers()[mapping_data->at(i)->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; int64_t relative_position = 0; int64_t absolute_position = 0; SeqOrientation orientation = kForward; int64_t reference_id = index->RawPositionConverter(start_location, 0, &absolute_position, &relative_position, &orientation); int64_t reference_start; index->RawPositionConverter(mapping_data->at(i)->get_mapping_data().ref_coords.start, 0, &absolute_position, &reference_start, &orientation); int64_t reference_end; index->RawPositionConverter(mapping_data->at(i)->get_mapping_data().ref_coords.end, 0, &absolute_position, &reference_end, &orientation); for (int64_t j = 0; j < mapping_data->at(i)->get_alignments().size(); j++) { ss << "\n ° Alignment " << j << " / " << mapping_data->at(i)->get_alignments().size(); ss << "\n ° r_id = " << mapping_data->at(i)->get_region_data().reference_id << ", region_index = " << mapping_data->at(i)->get_region_data().region_index << ", region_votes = " << mapping_data->at(i)->get_region_data().region_votes << ", position = " << relative_position << ", r1[" << reference_start << ", " << reference_end << "], " << ((orientation == kForward) ? "forward" : "reverse"); ss << ", sam_NM = " << mapping_data->at(i)->get_alignments()[j].edit_distance << ", sam_AS = " << mapping_data->at(i)->get_alignments()[j].alignment_score << ", sam_evalue = " << mapping_data->at(i)->get_alignments()[j].evalue << ", sam_pos = " << mapping_data->at(i)->get_alignments()[j].ref_start << ", sam_mapq = " << ((int64_t) mapping_data->at(i)->get_alignments()[j].mapping_quality) << ", relative_position = " << relative_position; ss << "\n ° r_len = " << index->get_reference_lengths()[mapping_data->at(i)->get_region_data().reference_id] << ", l1_l = " << mapping_data->at(i)->get_l1_data().l1_l << ", match_rate = " << ((float) mapping_data->at(i)->get_alignments()[j].num_eq_ops) / ((float) read->get_sequence_length()) << ", error_rate = " << ((float) mapping_data->at(i)->get_alignments()[j].num_x_ops + mapping_data->at(i)->get_alignments()[j].num_d_ops + mapping_data->at(i)->get_alignments()[j].num_i_ops) / ((float) read->get_sequence_length()); ss << "\n ° \"" << index->get_headers()[mapping_data->at(i)->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; } ss << "\n-----------"; if (i == 0) { ss << "\n"; } ss << "\n"; } return ss.str(); } std::string MappingData::VerboseFinalMappingsToString(const Index *index, const SingleSequence *read) const { return VerboseMappingDataToString_(&final_mapping_ptrs, index, read); // std::stringstream ss; // // int64_t reference_length = index->get_data_length(); // int64_t read_length = read->get_data_length(); // // ss << "-----------------------\n"; // ss << "--- num_entries = " << final_mapping_ptrs.size() << "\n"; // ss << "--- read id = " << read->get_sequence_absolute_id() << "\n"; // ss << "--- read name = " << read->get_header() << "\n"; // ss << "--- read_length = " << read_length << "\n"; // ss << "--- reference_length = " << reference_length << "\n"; // // for (int64_t i = (final_mapping_ptrs.size() - 1); i >= 0; i--) { //// ss << "--- [" << i << "] "; // ss << "[" << i << "/" << final_mapping_ptrs.size() << "] "; // int64_t start_location = 0, start_location_raw = 0; // // ss << "local_score_id = " << final_mapping_ptrs[i]->get_mapping_data().local_score_id; // ss << "\n ° " << final_mapping_ptrs[i]->VerboseToString(); // // int64_t relative_position = 0; // int64_t absolute_position = 0; // SeqOrientation orientation = kForward; // int64_t reference_id = index->RawPositionConverter(start_location, 0, &absolute_position, &relative_position, &orientation); // // int64_t reference_start; // index->RawPositionConverter(final_mapping_ptrs[i]->get_mapping_data().ref_coords.start, 0, &absolute_position, &reference_start, &orientation); // int64_t reference_end; // index->RawPositionConverter(final_mapping_ptrs[i]->get_mapping_data().ref_coords.end, 0, &absolute_position, &reference_end, &orientation); // // ss << "\n ° r_id = " << final_mapping_ptrs[i]->get_region_data().reference_id << ", region_index = " << final_mapping_ptrs[i]->get_region_data().region_index << ", region_votes = " << final_mapping_ptrs[i]->get_region_data().region_votes << ", position = " << relative_position << ", r1[" << reference_start << ", " << reference_end << "], " << ((orientation == kForward) ? "forward" : "reverse"); // ss << ", sam_NM = " << final_mapping_ptrs[i]->get_alignment_primary().edit_distance << ", sam_AS = " << final_mapping_ptrs[i]->get_alignment_primary().alignment_score << ", sam_pos = " << final_mapping_ptrs[i]->get_alignment_primary().pos_start << ", sam_mapq = " << ((int64_t) final_mapping_ptrs[i]->get_alignment_primary().mapping_quality) << ", relative_position = " << relative_position; // ss << "\n ° l1_l = " << final_mapping_ptrs[i]->get_l1_data().l1_l << ", match_rate = " << ((float) final_mapping_ptrs[i]->get_alignment_primary().num_eq_ops) / ((float) read->get_sequence_length()); // ss << "\n ° \"" << index->get_headers()[final_mapping_ptrs[i]->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; // ss << "\n-----------"; // if (i == 0) { // ss << "\n"; // } // ss << "\n"; // } // // return ss.str(); } std::string MappingData::VerboseIntermediateMappingsToString(const Index *index, const SingleSequence *read) const { return VerboseMappingDataToString_(&intermediate_mappings, index, read); // std::stringstream ss; // // int64_t reference_length = index->get_data_length(); // int64_t readlength = read->get_data_length(); // // ss << "-----------------------\n"; // ss << "--- num_entries = " << intermediate_mappings.size() << "\n"; // ss << "--- readlength = " << readlength << "\n"; // ss << "--- reference_length = " << reference_length << "\n"; // // for (int64_t i = (intermediate_mappings.size() - 1); i >= 0; i--) { //// ss << "--- [" << i << "] "; // ss << "[" << i << "/" << intermediate_mappings.size() << "] "; // int64_t start_location = 0, start_location_raw = 0; // // ss << intermediate_mappings[i]->VerboseToString(); // // int64_t relative_position = 0; // int64_t absolute_position = 0; // SeqOrientation orientation = kForward; // int64_t reference_id = index->RawPositionConverter(start_location, 0, &absolute_position, &relative_position, &orientation); // // int64_t reference_start; // index->RawPositionConverter(intermediate_mappings[i]->get_mapping_data().ref_coords.start, 0, &absolute_position, &reference_start, &orientation); // // int64_t reference_end; // index->RawPositionConverter(intermediate_mappings[i]->get_mapping_data().ref_coords.end, 0, &absolute_position, &reference_end, &orientation); // // ss << "\n r_id = " << intermediate_mappings[i]->get_region_data().reference_id << ", region_index = " << intermediate_mappings[i]->get_region_data().region_index << ", region_votes = " << intermediate_mappings[i]->get_region_data().region_votes << ", position = " << relative_position << ", r1[" << reference_start << ", " << reference_end << "], " << ((orientation == kForward) ? "forward" : "reverse"); // // reference_id = index->RawPositionConverter(start_location_raw, 0, &absolute_position, &relative_position, &orientation); // uint64_t position = index->get_reference_starting_pos()[reference_id] + relative_position; // // ss << ", sam_NM = " << intermediate_mappings[i]->get_alignment_primary().edit_distance << ", sam_AS = " << intermediate_mappings[i]->get_alignment_primary().alignment_score << ", sam_pos = " << intermediate_mappings[i]->get_alignment_primary().pos_start << ", sam_mapq = " << ((int64_t) intermediate_mappings[i]->get_alignment_primary().mapping_quality) << ", relative_position = " << relative_position; // // ss << "\n \"" << index->get_headers()[intermediate_mappings[i]->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; // ss << "\n-----------"; // // if (i == 0) { // ss << "\n"; // } // // ss << "\n"; // } // // return ss.str(); } <commit_msg>Minor modifications to the debug output.<commit_after>/* * mapping_data.cc * * Created on: Mar 19, 2015 * Author: isovic */ #include "mapping_data.h" MappingData::MappingData() { bins.clear(); intermediate_mappings.clear(); final_mapping_ptrs.clear(); bin_size = -1; num_seeds_over_limit = 0; num_seeds_with_no_hits = 0; num_seeds_errors = 0; num_similar_mappings = 0; num_same_mappings = 0; avg_covered_bases_of_all_mappings = 0; std_covered_bases_of_all_mappings = 0; median_covered_bases_of_all_mappings = 0; iteration = 0; unmapped_reason = std::string(""); num_region_iterations = 0; mapping_quality = 0; metagen_alignment_score = 0; time_region_selection = 0.0; time_mapping = 0.0; time_alignment = 0.0; time_region_seed_lookup = 0.0; time_region_hitsort = 0.0; time_region_conversion = 0.0; time_region_alloc = 0.0; time_region_counting = 0.0; } MappingData::~MappingData() { vertices.Clear(); bins.clear(); for (int64_t i = 0; i < intermediate_mappings.size(); i++) { if (intermediate_mappings[i]) delete intermediate_mappings[i]; intermediate_mappings[i] = NULL; } intermediate_mappings.clear(); unmapped_reason = std::string(""); num_region_iterations = 0; mapping_quality = 0; metagen_alignment_score = 0; } bool MappingData::IsMapped() { for (int32_t i=0; i<final_mapping_ptrs.size(); i++) { if (final_mapping_ptrs[i]->IsMapped() == true) { return true; }; } return false; } bool MappingData::IsAligned() { for (int32_t i=0; i<final_mapping_ptrs.size(); i++) { if (final_mapping_ptrs[i]->IsAligned() == true) { return true; }; } return false; } std::string MappingData::VerboseMappingDataToString_(const std::vector<PathGraphEntry *> *mapping_data, const Index *index, const SingleSequence *read) const { std::stringstream ss; int64_t reference_length = index->get_data_length(); int64_t read_length = read->get_data_length(); ss << "-----------------------\n"; ss << "--- num_entries = " << mapping_data->size() << "\n"; ss << "--- read id = " << read->get_sequence_absolute_id() << "\n"; ss << "--- read name = " << read->get_header() << "\n"; ss << "--- read_length = " << read_length << "\n"; ss << "--- reference_length = " << reference_length << "\n"; for (int64_t i = (mapping_data->size() - 1); i >= 0; i--) { // ss << "--- [" << i << "] "; ss << "[" << i << "/" << mapping_data->size() << "] "; int64_t start_location = 0, start_location_raw = 0; ss << "local_score_id = " << mapping_data->at(i)->get_mapping_data().local_score_id; ss << "\n ° " << mapping_data->at(i)->VerboseToString(); ss << "\n ° r_id = " << mapping_data->at(i)->get_region_data().reference_id << ", fwd_r_id = " << (mapping_data->at(i)->get_region_data().reference_id % index->get_num_sequences_forward()) << ", region_index = " << mapping_data->at(i)->get_region_data().region_index; ss << "\n ° \"" << index->get_headers()[mapping_data->at(i)->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; int64_t relative_position = 0; int64_t absolute_position = 0; SeqOrientation orientation = kForward; int64_t reference_id = index->RawPositionConverter(start_location, 0, &absolute_position, &relative_position, &orientation); int64_t reference_start; index->RawPositionConverter(mapping_data->at(i)->get_mapping_data().ref_coords.start, 0, &absolute_position, &reference_start, &orientation); int64_t reference_end; index->RawPositionConverter(mapping_data->at(i)->get_mapping_data().ref_coords.end, 0, &absolute_position, &reference_end, &orientation); for (int64_t j = 0; j < mapping_data->at(i)->get_alignments().size(); j++) { ss << "\n ° Alignment " << j << " / " << mapping_data->at(i)->get_alignments().size(); ss << "\n ° r_id = " << mapping_data->at(i)->get_region_data().reference_id << ", region_index = " << mapping_data->at(i)->get_region_data().region_index << ", region_votes = " << mapping_data->at(i)->get_region_data().region_votes << ", position = " << relative_position << ", r1[" << reference_start << ", " << reference_end << "], " << ((orientation == kForward) ? "forward" : "reverse"); ss << ", sam_NM = " << mapping_data->at(i)->get_alignments()[j].edit_distance << ", sam_AS = " << mapping_data->at(i)->get_alignments()[j].alignment_score << ", sam_evalue = " << mapping_data->at(i)->get_alignments()[j].evalue << ", sam_pos = " << mapping_data->at(i)->get_alignments()[j].ref_start << ", sam_mapq = " << ((int64_t) mapping_data->at(i)->get_alignments()[j].mapping_quality) << ", relative_position = " << relative_position; ss << "\n ° r_len = " << index->get_reference_lengths()[mapping_data->at(i)->get_region_data().reference_id] << ", l1_l = " << mapping_data->at(i)->get_l1_data().l1_l << ", match_rate = " << ((float) mapping_data->at(i)->get_alignments()[j].num_eq_ops) / ((float) mapping_data->at(i)->get_alignments()[j].nonclipped_length) << ", error_rate = " << ((float) mapping_data->at(i)->get_alignments()[j].num_x_ops + mapping_data->at(i)->get_alignments()[j].num_d_ops + mapping_data->at(i)->get_alignments()[j].num_i_ops) / ((float) mapping_data->at(i)->get_alignments()[j].nonclipped_length) << " (X: = " << ((float) mapping_data->at(i)->get_alignments()[j].num_x_ops) / ((float) mapping_data->at(i)->get_alignments()[j].nonclipped_length) << ", I = " << ((float) mapping_data->at(i)->get_alignments()[j].num_i_ops) / ((float) mapping_data->at(i)->get_alignments()[j].nonclipped_length) << ", D: = " << ((float) mapping_data->at(i)->get_alignments()[j].num_d_ops) / ((float) mapping_data->at(i)->get_alignments()[j].nonclipped_length) << ")"; ss << "\n ° \"" << index->get_headers()[mapping_data->at(i)->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; } ss << "\n-----------"; if (i == 0) { ss << "\n"; } ss << "\n"; } return ss.str(); } std::string MappingData::VerboseFinalMappingsToString(const Index *index, const SingleSequence *read) const { return VerboseMappingDataToString_(&final_mapping_ptrs, index, read); // std::stringstream ss; // // int64_t reference_length = index->get_data_length(); // int64_t read_length = read->get_data_length(); // // ss << "-----------------------\n"; // ss << "--- num_entries = " << final_mapping_ptrs.size() << "\n"; // ss << "--- read id = " << read->get_sequence_absolute_id() << "\n"; // ss << "--- read name = " << read->get_header() << "\n"; // ss << "--- read_length = " << read_length << "\n"; // ss << "--- reference_length = " << reference_length << "\n"; // // for (int64_t i = (final_mapping_ptrs.size() - 1); i >= 0; i--) { //// ss << "--- [" << i << "] "; // ss << "[" << i << "/" << final_mapping_ptrs.size() << "] "; // int64_t start_location = 0, start_location_raw = 0; // // ss << "local_score_id = " << final_mapping_ptrs[i]->get_mapping_data().local_score_id; // ss << "\n ° " << final_mapping_ptrs[i]->VerboseToString(); // // int64_t relative_position = 0; // int64_t absolute_position = 0; // SeqOrientation orientation = kForward; // int64_t reference_id = index->RawPositionConverter(start_location, 0, &absolute_position, &relative_position, &orientation); // // int64_t reference_start; // index->RawPositionConverter(final_mapping_ptrs[i]->get_mapping_data().ref_coords.start, 0, &absolute_position, &reference_start, &orientation); // int64_t reference_end; // index->RawPositionConverter(final_mapping_ptrs[i]->get_mapping_data().ref_coords.end, 0, &absolute_position, &reference_end, &orientation); // // ss << "\n ° r_id = " << final_mapping_ptrs[i]->get_region_data().reference_id << ", region_index = " << final_mapping_ptrs[i]->get_region_data().region_index << ", region_votes = " << final_mapping_ptrs[i]->get_region_data().region_votes << ", position = " << relative_position << ", r1[" << reference_start << ", " << reference_end << "], " << ((orientation == kForward) ? "forward" : "reverse"); // ss << ", sam_NM = " << final_mapping_ptrs[i]->get_alignment_primary().edit_distance << ", sam_AS = " << final_mapping_ptrs[i]->get_alignment_primary().alignment_score << ", sam_pos = " << final_mapping_ptrs[i]->get_alignment_primary().pos_start << ", sam_mapq = " << ((int64_t) final_mapping_ptrs[i]->get_alignment_primary().mapping_quality) << ", relative_position = " << relative_position; // ss << "\n ° l1_l = " << final_mapping_ptrs[i]->get_l1_data().l1_l << ", match_rate = " << ((float) final_mapping_ptrs[i]->get_alignment_primary().num_eq_ops) / ((float) read->get_sequence_length()); // ss << "\n ° \"" << index->get_headers()[final_mapping_ptrs[i]->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; // ss << "\n-----------"; // if (i == 0) { // ss << "\n"; // } // ss << "\n"; // } // // return ss.str(); } std::string MappingData::VerboseIntermediateMappingsToString(const Index *index, const SingleSequence *read) const { return VerboseMappingDataToString_(&intermediate_mappings, index, read); // std::stringstream ss; // // int64_t reference_length = index->get_data_length(); // int64_t readlength = read->get_data_length(); // // ss << "-----------------------\n"; // ss << "--- num_entries = " << intermediate_mappings.size() << "\n"; // ss << "--- readlength = " << readlength << "\n"; // ss << "--- reference_length = " << reference_length << "\n"; // // for (int64_t i = (intermediate_mappings.size() - 1); i >= 0; i--) { //// ss << "--- [" << i << "] "; // ss << "[" << i << "/" << intermediate_mappings.size() << "] "; // int64_t start_location = 0, start_location_raw = 0; // // ss << intermediate_mappings[i]->VerboseToString(); // // int64_t relative_position = 0; // int64_t absolute_position = 0; // SeqOrientation orientation = kForward; // int64_t reference_id = index->RawPositionConverter(start_location, 0, &absolute_position, &relative_position, &orientation); // // int64_t reference_start; // index->RawPositionConverter(intermediate_mappings[i]->get_mapping_data().ref_coords.start, 0, &absolute_position, &reference_start, &orientation); // // int64_t reference_end; // index->RawPositionConverter(intermediate_mappings[i]->get_mapping_data().ref_coords.end, 0, &absolute_position, &reference_end, &orientation); // // ss << "\n r_id = " << intermediate_mappings[i]->get_region_data().reference_id << ", region_index = " << intermediate_mappings[i]->get_region_data().region_index << ", region_votes = " << intermediate_mappings[i]->get_region_data().region_votes << ", position = " << relative_position << ", r1[" << reference_start << ", " << reference_end << "], " << ((orientation == kForward) ? "forward" : "reverse"); // // reference_id = index->RawPositionConverter(start_location_raw, 0, &absolute_position, &relative_position, &orientation); // uint64_t position = index->get_reference_starting_pos()[reference_id] + relative_position; // // ss << ", sam_NM = " << intermediate_mappings[i]->get_alignment_primary().edit_distance << ", sam_AS = " << intermediate_mappings[i]->get_alignment_primary().alignment_score << ", sam_pos = " << intermediate_mappings[i]->get_alignment_primary().pos_start << ", sam_mapq = " << ((int64_t) intermediate_mappings[i]->get_alignment_primary().mapping_quality) << ", relative_position = " << relative_position; // // ss << "\n \"" << index->get_headers()[intermediate_mappings[i]->get_region_data().reference_id % index->get_num_sequences_forward()] << "\""; // ss << "\n-----------"; // // if (i == 0) { // ss << "\n"; // } // // ss << "\n"; // } // // return ss.str(); } <|endoftext|>
<commit_before>#include "Preheat.h" namespace cura { void Preheat::setConfig(const MeshGroup& meshgroup) { for (int extruder_nr = 0; extruder_nr < meshgroup.getExtruderCount(); extruder_nr++) { assert(meshgroup.getExtruderTrain(extruder_nr) != nullptr); const ExtruderTrain& extruder_train = *meshgroup.getExtruderTrain(extruder_nr); config_per_extruder.emplace_back(); Config& config = config_per_extruder.back(); double machine_nozzle_cool_down_speed = extruder_train.getSettingInSeconds("machine_nozzle_cool_down_speed"); double machine_nozzle_heat_up_speed = extruder_train.getSettingInSeconds("machine_nozzle_heat_up_speed"); double material_extrusion_cool_down_speed = extruder_train.getSettingInSeconds("material_extrusion_cool_down_speed"); assert(material_extrusion_cool_down_speed < machine_nozzle_heat_up_speed && "The extrusion cooldown speed must be smaller than the heat up speed; otherwise the printing temperature cannot be reached!"); config.time_to_cooldown_1_degree[0] = 1.0 / machine_nozzle_cool_down_speed; config.time_to_heatup_1_degree[0] = 1.0 / machine_nozzle_heat_up_speed; config.time_to_cooldown_1_degree[1] = 1.0 / (machine_nozzle_cool_down_speed + material_extrusion_cool_down_speed); config.time_to_heatup_1_degree[1] = 1.0 / (machine_nozzle_heat_up_speed - material_extrusion_cool_down_speed); config.standby_temp = extruder_train.getSettingInSeconds("material_standby_temperature"); config.min_time_window = extruder_train.getSettingInSeconds("machine_min_cool_heat_time_window"); config.material_print_temperature = extruder_train.getSettingInDegreeCelsius("material_print_temperature"); config.material_print_temperature_layer_0 = extruder_train.getSettingInDegreeCelsius("material_print_temperature_layer_0"); config.material_initial_print_temperature = extruder_train.getSettingInDegreeCelsius("material_initial_print_temperature"); config.material_final_print_temperature = extruder_train.getSettingInDegreeCelsius("material_final_print_temperature"); config.flow_dependent_temperature = extruder_train.getSettingBoolean("material_flow_dependent_temperature"); config.flow_temp_graph = extruder_train.getSettingAsFlowTempGraph("material_flow_temp_graph"); // [[0.1,180],[20,230]] } } double Preheat::getTimeToGoFromTempToTemp(int extruder, double temp_before, double temp_after, bool during_printing) { Config& config = config_per_extruder[extruder]; double time; if (temp_after > temp_before) { time = (temp_after - temp_before) * config.time_to_heatup_1_degree[during_printing]; } else { time = (temp_before - temp_after) * config.time_to_cooldown_1_degree[during_printing]; } return std::max(0.0, time); } double Preheat::getTemp(unsigned int extruder, double flow, bool is_initial_layer) { if (is_initial_layer && config_per_extruder[extruder].material_print_temperature_layer_0 != 0) { return config_per_extruder[extruder].material_print_temperature_layer_0; } return config_per_extruder[extruder].flow_temp_graph.getTemp(flow, config_per_extruder[extruder].material_print_temperature, config_per_extruder[extruder].flow_dependent_temperature); } Preheat::WarmUpResult Preheat::getWarmUpPointAfterCoolDown(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { WarmUpResult result; const Config& config = config_per_extruder[extruder]; double time_to_cooldown_1_degree = config.time_to_cooldown_1_degree[during_printing]; double time_to_heatup_1_degree = config.time_to_heatup_1_degree[during_printing]; result.total_time_window = time_window; // ,temp_end // / . // ,temp_start / . // \ ' ' ' ' '/ ' ' '> outer_temp . // \________/ . // "-> temp_mid // ^^^^^^^^^^ // limited_time_window double outer_temp; double limited_time_window; if (temp_start < temp_end) { // extra time needed during heating double extra_heatup_time = (temp_end - temp_start) * time_to_heatup_1_degree; result.heating_time = extra_heatup_time; limited_time_window = time_window - extra_heatup_time; outer_temp = temp_start; if (limited_time_window < 0.0) { result.heating_time = 0.0; result.lowest_temperature = temp_start; return result; } } else { double extra_cooldown_time = (temp_start - temp_end) * time_to_cooldown_1_degree; result.heating_time = 0; limited_time_window = time_window - extra_cooldown_time; outer_temp = temp_end; if (limited_time_window < 0.0) { result.heating_time = 0.0; result.lowest_temperature = temp_end; return result; } } double time_ratio_cooldown_heatup = time_to_cooldown_1_degree / time_to_heatup_1_degree; double time_to_heat_from_standby_to_print_temp = getTimeToGoFromTempToTemp(extruder, temp_mid, outer_temp, during_printing); double time_needed_to_reach_standby_temp = time_to_heat_from_standby_to_print_temp * (1.0 + time_ratio_cooldown_heatup); if (time_needed_to_reach_standby_temp < limited_time_window) { result.heating_time += time_to_heat_from_standby_to_print_temp; result.lowest_temperature = temp_mid; } else { result.heating_time += limited_time_window * time_to_heatup_1_degree / (time_to_cooldown_1_degree + time_to_heatup_1_degree); result.lowest_temperature = std::max(temp_mid, temp_end - result.heating_time / time_to_heatup_1_degree); } if (result.heating_time > time_window || result.heating_time < 0.0) { logWarning("getWarmUpPointAfterCoolDown returns result outside of the time window!"); } return result; } Preheat::CoolDownResult Preheat::getCoolDownPointAfterWarmUp(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { CoolDownResult result; const Config& config = config_per_extruder[extruder]; double time_to_cooldown_1_degree = config.time_to_cooldown_1_degree[during_printing]; double time_to_heatup_1_degree = config.time_to_heatup_1_degree[during_printing]; assert(temp_start != -1 && temp_mid != -1 && temp_end != -1 && "temperatures must be initialized!"); result.total_time_window = time_window; // limited_time_window // :^^^^^^^^^^^^: // : ________. : . . .> temp_mid // : / \ : . // :/ . . . . .\:. . .> outer_temp . // ^temp_start \ . // \ . // ^temp_end double outer_temp; double limited_time_window; if (temp_start < temp_end) { // extra time needed during heating double extra_heatup_time = (temp_end - temp_start) * time_to_heatup_1_degree; result.cooling_time = 0; limited_time_window = time_window - extra_heatup_time; outer_temp = temp_start; if (limited_time_window < 0.0) { result.cooling_time = 0.0; result.highest_temperature = temp_end; return result; } } else { double extra_cooldown_time = (temp_start - temp_end) * time_to_cooldown_1_degree; result.cooling_time = extra_cooldown_time; limited_time_window = time_window - extra_cooldown_time; outer_temp = temp_end; if (limited_time_window < 0.0) { result.cooling_time = 0.0; result.highest_temperature = temp_start; return result; } } double time_ratio_cooldown_heatup = time_to_cooldown_1_degree / time_to_heatup_1_degree; double cool_down_time = getTimeToGoFromTempToTemp(extruder, temp_mid, outer_temp, during_printing); double time_needed_to_reach_temp1 = cool_down_time * (1.0 + time_ratio_cooldown_heatup); if (time_needed_to_reach_temp1 < limited_time_window) { result.cooling_time += cool_down_time; result.highest_temperature = temp_mid; } else { result.cooling_time += limited_time_window * time_to_heatup_1_degree / (time_to_cooldown_1_degree + time_to_heatup_1_degree); result.highest_temperature = std::min(temp_mid, temp_end + result.cooling_time / time_to_cooldown_1_degree); } if (result.cooling_time > time_window || result.cooling_time < 0.0) { logWarning("getCoolDownPointAfterWarmUp returns result outside of the time window!"); } return result; } }//namespace cura <commit_msg>fix: getCoolDownPointAfterWarmUp outer_temp was switched (CURA-1932)<commit_after>#include "Preheat.h" namespace cura { void Preheat::setConfig(const MeshGroup& meshgroup) { for (int extruder_nr = 0; extruder_nr < meshgroup.getExtruderCount(); extruder_nr++) { assert(meshgroup.getExtruderTrain(extruder_nr) != nullptr); const ExtruderTrain& extruder_train = *meshgroup.getExtruderTrain(extruder_nr); config_per_extruder.emplace_back(); Config& config = config_per_extruder.back(); double machine_nozzle_cool_down_speed = extruder_train.getSettingInSeconds("machine_nozzle_cool_down_speed"); double machine_nozzle_heat_up_speed = extruder_train.getSettingInSeconds("machine_nozzle_heat_up_speed"); double material_extrusion_cool_down_speed = extruder_train.getSettingInSeconds("material_extrusion_cool_down_speed"); assert(material_extrusion_cool_down_speed < machine_nozzle_heat_up_speed && "The extrusion cooldown speed must be smaller than the heat up speed; otherwise the printing temperature cannot be reached!"); config.time_to_cooldown_1_degree[0] = 1.0 / machine_nozzle_cool_down_speed; config.time_to_heatup_1_degree[0] = 1.0 / machine_nozzle_heat_up_speed; config.time_to_cooldown_1_degree[1] = 1.0 / (machine_nozzle_cool_down_speed + material_extrusion_cool_down_speed); config.time_to_heatup_1_degree[1] = 1.0 / (machine_nozzle_heat_up_speed - material_extrusion_cool_down_speed); config.standby_temp = extruder_train.getSettingInSeconds("material_standby_temperature"); config.min_time_window = extruder_train.getSettingInSeconds("machine_min_cool_heat_time_window"); config.material_print_temperature = extruder_train.getSettingInDegreeCelsius("material_print_temperature"); config.material_print_temperature_layer_0 = extruder_train.getSettingInDegreeCelsius("material_print_temperature_layer_0"); config.material_initial_print_temperature = extruder_train.getSettingInDegreeCelsius("material_initial_print_temperature"); config.material_final_print_temperature = extruder_train.getSettingInDegreeCelsius("material_final_print_temperature"); config.flow_dependent_temperature = extruder_train.getSettingBoolean("material_flow_dependent_temperature"); config.flow_temp_graph = extruder_train.getSettingAsFlowTempGraph("material_flow_temp_graph"); // [[0.1,180],[20,230]] } } double Preheat::getTimeToGoFromTempToTemp(int extruder, double temp_before, double temp_after, bool during_printing) { Config& config = config_per_extruder[extruder]; double time; if (temp_after > temp_before) { time = (temp_after - temp_before) * config.time_to_heatup_1_degree[during_printing]; } else { time = (temp_before - temp_after) * config.time_to_cooldown_1_degree[during_printing]; } return std::max(0.0, time); } double Preheat::getTemp(unsigned int extruder, double flow, bool is_initial_layer) { if (is_initial_layer && config_per_extruder[extruder].material_print_temperature_layer_0 != 0) { return config_per_extruder[extruder].material_print_temperature_layer_0; } return config_per_extruder[extruder].flow_temp_graph.getTemp(flow, config_per_extruder[extruder].material_print_temperature, config_per_extruder[extruder].flow_dependent_temperature); } Preheat::WarmUpResult Preheat::getWarmUpPointAfterCoolDown(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { WarmUpResult result; const Config& config = config_per_extruder[extruder]; double time_to_cooldown_1_degree = config.time_to_cooldown_1_degree[during_printing]; double time_to_heatup_1_degree = config.time_to_heatup_1_degree[during_printing]; result.total_time_window = time_window; // ,temp_end // / . // ,temp_start / . // \ ' ' ' ' '/ ' ' '> outer_temp . // \________/ . // "-> temp_mid // ^^^^^^^^^^ // limited_time_window double outer_temp; double limited_time_window; if (temp_start < temp_end) { // extra time needed during heating double extra_heatup_time = (temp_end - temp_start) * time_to_heatup_1_degree; result.heating_time = extra_heatup_time; limited_time_window = time_window - extra_heatup_time; outer_temp = temp_start; if (limited_time_window < 0.0) { result.heating_time = 0.0; result.lowest_temperature = temp_start; return result; } } else { double extra_cooldown_time = (temp_start - temp_end) * time_to_cooldown_1_degree; result.heating_time = 0; limited_time_window = time_window - extra_cooldown_time; outer_temp = temp_end; if (limited_time_window < 0.0) { result.heating_time = 0.0; result.lowest_temperature = temp_end; return result; } } double time_ratio_cooldown_heatup = time_to_cooldown_1_degree / time_to_heatup_1_degree; double time_to_heat_from_standby_to_print_temp = getTimeToGoFromTempToTemp(extruder, temp_mid, outer_temp, during_printing); double time_needed_to_reach_standby_temp = time_to_heat_from_standby_to_print_temp * (1.0 + time_ratio_cooldown_heatup); if (time_needed_to_reach_standby_temp < limited_time_window) { result.heating_time += time_to_heat_from_standby_to_print_temp; result.lowest_temperature = temp_mid; } else { result.heating_time += limited_time_window * time_to_heatup_1_degree / (time_to_cooldown_1_degree + time_to_heatup_1_degree); result.lowest_temperature = std::max(temp_mid, temp_end - result.heating_time / time_to_heatup_1_degree); } if (result.heating_time > time_window || result.heating_time < 0.0) { logWarning("getWarmUpPointAfterCoolDown returns result outside of the time window!"); } return result; } Preheat::CoolDownResult Preheat::getCoolDownPointAfterWarmUp(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { CoolDownResult result; const Config& config = config_per_extruder[extruder]; double time_to_cooldown_1_degree = config.time_to_cooldown_1_degree[during_printing]; double time_to_heatup_1_degree = config.time_to_heatup_1_degree[during_printing]; assert(temp_start != -1 && temp_mid != -1 && temp_end != -1 && "temperatures must be initialized!"); result.total_time_window = time_window; // limited_time_window // :^^^^^^^^^^^^: // : ________. : . . .> temp_mid // : / \ : . // :/ . . . . .\:. . .> outer_temp . // ^temp_start \ . // \ . // ^temp_end double outer_temp; double limited_time_window; if (temp_start < temp_end) { // extra time needed during heating double extra_heatup_time = (temp_end - temp_start) * time_to_heatup_1_degree; result.cooling_time = 0; limited_time_window = time_window - extra_heatup_time; outer_temp = temp_end; if (limited_time_window < 0.0) { result.cooling_time = 0.0; result.highest_temperature = temp_end; return result; } } else { double extra_cooldown_time = (temp_start - temp_end) * time_to_cooldown_1_degree; result.cooling_time = extra_cooldown_time; limited_time_window = time_window - extra_cooldown_time; outer_temp = temp_start; if (limited_time_window < 0.0) { result.cooling_time = 0.0; result.highest_temperature = temp_start; return result; } } double time_ratio_cooldown_heatup = time_to_cooldown_1_degree / time_to_heatup_1_degree; double cool_down_time = getTimeToGoFromTempToTemp(extruder, temp_mid, outer_temp, during_printing); double time_needed_to_reach_temp1 = cool_down_time * (1.0 + time_ratio_cooldown_heatup); if (time_needed_to_reach_temp1 < limited_time_window) { result.cooling_time += cool_down_time; result.highest_temperature = temp_mid; } else { result.cooling_time += limited_time_window * time_to_heatup_1_degree / (time_to_cooldown_1_degree + time_to_heatup_1_degree); result.highest_temperature = std::min(temp_mid, temp_end + result.cooling_time / time_to_cooldown_1_degree); } if (result.cooling_time > time_window || result.cooling_time < 0.0) { logWarning("getCoolDownPointAfterWarmUp returns result outside of the time window!"); } return result; } }//namespace cura <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * Copyright (C) 2011, 2012, 2013 Christoph Redl * * This file is part of dlvhex. * * dlvhex is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * dlvhex is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file Printer.cpp * @author Peter Schueller * @date * * @brief Printer classes for printing objects stored in registry given registry and ID. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex2/Printer.h" #include "dlvhex2/Registry.h" #include <cassert> DLVHEX_NAMESPACE_BEGIN void Printer::printmany(const std::vector<ID>& ids, const std::string& separator) { std::vector<ID>::const_iterator it = ids.begin(); if( it != ids.end() ) { print(*it); it++; while( it != ids.end() ) { out << separator; print(*it); it++; } } } namespace { bool isInfixBuiltin(IDAddress id) { return id <= ID::TERM_BUILTIN_DIV; } } void RawPrinter::print(ID id) { switch(id.kind & ID::MAINKIND_MASK) { case ID::MAINKIND_LITERAL: if(id.isNaf()) out << "not "; // continue with atom here! case ID::MAINKIND_ATOM: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_ATOM_ORDINARYG: out << registry->ogatoms.getByID(id).text; break; case ID::SUBKIND_ATOM_ORDINARYN: out << registry->onatoms.getByID(id).text; break; case ID::SUBKIND_ATOM_BUILTIN: { const BuiltinAtom& atom = registry->batoms.getByID(id); assert(atom.tuple.size() > 1); assert(atom.tuple[0].isBuiltinTerm()); if( isInfixBuiltin(atom.tuple[0].address) ) { if( atom.tuple.size() == 3 ) { // things like A < B print(atom.tuple[1]); out << " "; print(atom.tuple[0]); out << " "; print(atom.tuple[2]); } else { // things like A = B * C assert(atom.tuple.size() == 4); // for ternary builtins of the form (A = B * C) tuple contains // in this order: <*, B, C, A> print(atom.tuple[3]); out << " = "; print(atom.tuple[1]); out << " "; print(atom.tuple[0]); out << " "; print(atom.tuple[2]); } } else { print(atom.tuple[0]); out << "("; Tuple::const_iterator it = atom.tuple.begin() + 1; print(*it); it++; for(; it != atom.tuple.end(); ++it) { out << ","; print(*it); } out << ")"; } } break; case ID::SUBKIND_ATOM_AGGREGATE: { const AggregateAtom& atom = registry->aatoms.getByID(id); assert(atom.tuple.size() == 5); // left operator (if any) if( atom.tuple[0] != ID_FAIL ) { assert(atom.tuple[1] != ID_FAIL); print(atom.tuple[0]); out << " "; print(atom.tuple[1]); out << " "; } else { assert(atom.tuple[1] == ID_FAIL); } // aggregate predicate assert(atom.tuple[2] != ID_FAIL); // aggregation function print(atom.tuple[2]); out << " { "; // variables printmany(atom.variables, ","); out << " : "; // body printmany(atom.literals, ","); out << " }"; // right operator (if any) if( atom.tuple[3] != ID_FAIL ) { assert(atom.tuple[4] != ID_FAIL); out << " "; print(atom.tuple[3]); out << " "; print(atom.tuple[4]); } else { assert(atom.tuple[4] == ID_FAIL); } } break; case ID::SUBKIND_ATOM_EXTERNAL: { const ExternalAtom& atom = registry->eatoms.getByID(id); out << "&"; print(atom.predicate); out << "["; printmany(atom.inputs,","); out << "]("; printmany(atom.tuple,","); out << ")"; } break; case ID::SUBKIND_ATOM_MODULE: { const ModuleAtom& atom = registry->matoms.getByID(id); out << "@"; print(atom.predicate); out << "["; printmany(atom.inputs,","); out << "]::"; print(atom.outputAtom); } break; default: assert(false); } break; case ID::MAINKIND_TERM: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_TERM_VARIABLE: out << (id.isAnonymousVariable() ? "_" : "") << registry->terms.getByID(id).symbol; break; case ID::SUBKIND_TERM_CONSTANT: case ID::SUBKIND_TERM_NESTED: out << registry->terms.getByID(id).symbol; break; case ID::SUBKIND_TERM_PREDICATE: out << registry->preds.getByID(id).symbol; break; case ID::SUBKIND_TERM_INTEGER: out << id.address; break; case ID::SUBKIND_TERM_BUILTIN: out << ID::stringFromBuiltinTerm(id.address); break; default: assert(false); } break; case ID::MAINKIND_RULE: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_RULE_REGULAR: { const Rule& r = registry->rules.getByID(id); printmany(r.head, " v "); if( !r.body.empty() ) { out << " :- "; printmany(r.body, ", "); } out << "."; } break; case ID::SUBKIND_RULE_CONSTRAINT: { out << ":- "; const Rule& r = registry->rules.getByID(id); printmany(r.body, ", "); out << "."; } break; case ID::SUBKIND_RULE_WEAKCONSTRAINT: { out << ":~ "; const Rule& r = registry->rules.getByID(id); printmany(r.body, ", "); out << ". ["; print(r.weight); out << ":"; print(r.level); out << "]"; } break; case ID::SUBKIND_RULE_WEIGHT: { const Rule& r = registry->rules.getByID(id); printmany(r.head, " v "); if( !r.body.empty() ) { out << " :- "; out << r.bound.address << " "; for (int i = 0; i < r.body.size(); ++i){ out << (i > 0 ? ", " : ""); print(r.body[i]); out << "=" << r.bodyWeightVector[i].address; } } out << "."; } break; default: assert(false); } break; default: assert(false); } } // remove the prefix // from m0___p1__q(a) to q(a) std::string RawPrinter::removeModulePrefix(const std::string& text) { std::string result; if (text.find(MODULEINSTSEPARATOR) == std::string::npos) { result = text; } else { result = text.substr(text.find(MODULEINSTSEPARATOR)+3); } return result.substr(result.find(MODULEPREFIXSEPARATOR)+2); } void RawPrinter::printWithoutPrefix(ID id) { switch(id.kind & ID::MAINKIND_MASK) { case ID::MAINKIND_ATOM: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_ATOM_ORDINARYG: out << removeModulePrefix(registry->ogatoms.getByID(id).text); break; default: assert(false); } break; default: assert(false); } } DLVHEX_NAMESPACE_END <commit_msg>implement complete support sets for query answering over ASP programs<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * Copyright (C) 2011, 2012, 2013 Christoph Redl * * This file is part of dlvhex. * * dlvhex is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * dlvhex is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file Printer.cpp * @author Peter Schueller * @date * * @brief Printer classes for printing objects stored in registry given registry and ID. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex2/Printer.h" #include "dlvhex2/Registry.h" #include <cassert> DLVHEX_NAMESPACE_BEGIN void Printer::printmany(const std::vector<ID>& ids, const std::string& separator) { std::vector<ID>::const_iterator it = ids.begin(); if( it != ids.end() ) { print(*it); it++; while( it != ids.end() ) { out << separator; print(*it); it++; } } } namespace { bool isInfixBuiltin(IDAddress id) { return id <= ID::TERM_BUILTIN_DIV; } } void RawPrinter::print(ID id) { switch(id.kind & ID::MAINKIND_MASK) { case ID::MAINKIND_LITERAL: if(id.isNaf()) out << "not "; // continue with atom here! case ID::MAINKIND_ATOM: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_ATOM_ORDINARYG: out << registry->ogatoms.getByID(id).text; break; case ID::SUBKIND_ATOM_ORDINARYN: out << registry->onatoms.getByID(id).text; break; case ID::SUBKIND_ATOM_BUILTIN: { const BuiltinAtom& atom = registry->batoms.getByID(id); assert(atom.tuple.size() > 1); assert(atom.tuple[0].isBuiltinTerm()); if( isInfixBuiltin(atom.tuple[0].address) ) { if( atom.tuple.size() == 3 ) { // things like A < B print(atom.tuple[1]); out << " "; print(atom.tuple[0]); out << " "; print(atom.tuple[2]); } else { // things like A = B * C assert(atom.tuple.size() == 4); // for ternary builtins of the form (A = B * C) tuple contains // in this order: <*, B, C, A> print(atom.tuple[3]); out << " = "; print(atom.tuple[1]); out << " "; print(atom.tuple[0]); out << " "; print(atom.tuple[2]); } } else { print(atom.tuple[0]); out << "("; Tuple::const_iterator it = atom.tuple.begin() + 1; print(*it); it++; for(; it != atom.tuple.end(); ++it) { out << ","; print(*it); } out << ")"; } } break; case ID::SUBKIND_ATOM_AGGREGATE: { const AggregateAtom& atom = registry->aatoms.getByID(id); assert(atom.tuple.size() == 5); // left operator (if any) if( atom.tuple[0] != ID_FAIL ) { assert(atom.tuple[1] != ID_FAIL); print(atom.tuple[0]); out << " "; print(atom.tuple[1]); out << " "; } else { assert(atom.tuple[1] == ID_FAIL); } // aggregate predicate assert(atom.tuple[2] != ID_FAIL); // aggregation function print(atom.tuple[2]); out << " { "; // variables printmany(atom.variables, ","); out << " : "; // body printmany(atom.literals, ","); out << " }"; // right operator (if any) if( atom.tuple[3] != ID_FAIL ) { assert(atom.tuple[4] != ID_FAIL); out << " "; print(atom.tuple[3]); out << " "; print(atom.tuple[4]); } else { assert(atom.tuple[4] == ID_FAIL); } } break; case ID::SUBKIND_ATOM_EXTERNAL: { const ExternalAtom& atom = registry->eatoms.getByID(id); out << "&"; print(atom.predicate); out << "["; printmany(atom.inputs,","); out << "]("; printmany(atom.tuple,","); out << ")"; } break; case ID::SUBKIND_ATOM_MODULE: { const ModuleAtom& atom = registry->matoms.getByID(id); out << "@"; print(atom.predicate); out << "["; printmany(atom.inputs,","); out << "]::"; print(atom.outputAtom); } break; default: assert(false); } break; case ID::MAINKIND_TERM: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_TERM_VARIABLE: out << /*(id.isAnonymousVariable() ? "_" : "") <<*/ registry->terms.getByID(id).symbol; break; case ID::SUBKIND_TERM_CONSTANT: case ID::SUBKIND_TERM_NESTED: out << registry->terms.getByID(id).symbol; break; case ID::SUBKIND_TERM_PREDICATE: out << registry->preds.getByID(id).symbol; break; case ID::SUBKIND_TERM_INTEGER: out << id.address; break; case ID::SUBKIND_TERM_BUILTIN: out << ID::stringFromBuiltinTerm(id.address); break; default: assert(false); } break; case ID::MAINKIND_RULE: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_RULE_REGULAR: { const Rule& r = registry->rules.getByID(id); printmany(r.head, " v "); if( !r.body.empty() ) { out << " :- "; printmany(r.body, ", "); } out << "."; } break; case ID::SUBKIND_RULE_CONSTRAINT: { out << ":- "; const Rule& r = registry->rules.getByID(id); printmany(r.body, ", "); out << "."; } break; case ID::SUBKIND_RULE_WEAKCONSTRAINT: { out << ":~ "; const Rule& r = registry->rules.getByID(id); printmany(r.body, ", "); out << ". ["; print(r.weight); out << ":"; print(r.level); out << "]"; } break; case ID::SUBKIND_RULE_WEIGHT: { const Rule& r = registry->rules.getByID(id); printmany(r.head, " v "); if( !r.body.empty() ) { out << " :- "; out << r.bound.address << " "; for (int i = 0; i < r.body.size(); ++i){ out << (i > 0 ? ", " : ""); print(r.body[i]); out << "=" << r.bodyWeightVector[i].address; } } out << "."; } break; default: assert(false); } break; default: assert(false); } } // remove the prefix // from m0___p1__q(a) to q(a) std::string RawPrinter::removeModulePrefix(const std::string& text) { std::string result; if (text.find(MODULEINSTSEPARATOR) == std::string::npos) { result = text; } else { result = text.substr(text.find(MODULEINSTSEPARATOR)+3); } return result.substr(result.find(MODULEPREFIXSEPARATOR)+2); } void RawPrinter::printWithoutPrefix(ID id) { switch(id.kind & ID::MAINKIND_MASK) { case ID::MAINKIND_ATOM: switch(id.kind & ID::SUBKIND_MASK) { case ID::SUBKIND_ATOM_ORDINARYG: out << removeModulePrefix(registry->ogatoms.getByID(id).text); break; default: assert(false); } break; default: assert(false); } } DLVHEX_NAMESPACE_END <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 Gabriel Corona 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 <cstring> #include <string> #include <fstream> #include <iostream> #include <regex> #include <sys/mman.h> #include "unjit.hpp" namespace unjit { Process::Process(pid_t pid) : pid_(pid) { } Process::~Process() { } void Process::load_vm_maps() { vmas_.clear(); std::string filename = std::string("/proc/") + std::to_string(this->pid_) + std::string("/maps"); std::regex map_regex( // Start-end: "^([0-9a-f]+)-([0-9a-f]+)" // Flags: " ([r-])([w-])([x-])([p-])" // Offset: " ([0-9a-f]+)" // Device (major/minor): " [0-9a-f]+:[0-9a-f]+" // icode: " [0-9]*" // File name: " *([^ ]*)$" ); std::ifstream file(filename); std::string line; std::smatch match; while (getline(file, line)) { if (!std::regex_search(line, match, map_regex)) continue; Vma vma; vma.start = strtoll(match[1].str().c_str(), nullptr, 16); vma.end = strtoll(match[2].str().c_str(), nullptr, 16); vma.prot = 0; if (match[3].str()[0] == 'r') vma.prot |= PROT_READ; if (match[4].str()[0] == 'w') vma.prot |= PROT_WRITE; if (match[5].str()[0] == 'x') vma.prot |= PROT_EXEC; if (match[6].str()[0] == 'p') vma.flags = MAP_PRIVATE; else vma.flags = MAP_SHARED; vma.offset = strtoll(match[7].str().c_str(), nullptr, 16); vma.name = match[8]; this->vmas_.push_back(std::move(vma)); } } void Process::load_modules() { this->areas_.clear(); size_t n = this->vmas_.size(); for (size_t i = 0; i != n; ++ i) { Vma const& vma = this->vmas_[i]; if (vma.name.empty() || vma.name[0] == '[') continue; // Find the end of the module: do { ++i; } while (i != n && this->vmas_[i].name == vma.name); if (this->vmas_[i].name.empty() && i != n) ++i; std::uint64_t end = this->vmas_[i - 1].end; std::shared_ptr<Module> module = load_module(vma.name); ModuleArea area; area.start = vma.start; area.end = end; area.module = std::move(module); this->areas_.push_back(std::move(area)); } } void Process::load_map_file() { std::string filename = std::string("/tmp/perf-") + std::to_string(this->pid_) + std::string(".map"); this->load_map_file(filename); } void Process::load_map_file(std::string const& map_file) { std::ifstream file(map_file); size_t size = 256; std::string line; while (getline(file, line)) { Symbol symbol; int name_index; if (sscanf(line.c_str(), "%" SCNx64 " %" SCNx64 "%n", &symbol.value, &symbol.size, &name_index) == 2) { while (name_index < line.size() && line[name_index] == ' ') ++name_index; symbol.name = std::string(line.c_str() + name_index); this->jit_symbols_[symbol.value] = std::move(symbol); } } } const char* Process::lookup_symbol(std::uint64_t ReferenceValue) { { auto i = this->jit_symbols_.find(ReferenceValue); if (i != this->jit_symbols_.end()) return i->second.name.c_str(); } unjit::ModuleArea const* area = this->find_module_area(ReferenceValue); if (area) { std::uint64_t relative_address = area->module->absolute_address ? ReferenceValue : ReferenceValue - area->start; auto i = area->module->symbols.find(relative_address); if (i != this->jit_symbols_.end()) return i->second.name.c_str(); } return NULL; } } <commit_msg>Accept space char in filenames in /proc/$pid/maps<commit_after>/* The MIT License (MIT) Copyright (c) 2015 Gabriel Corona 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 <cstring> #include <string> #include <fstream> #include <iostream> #include <regex> #include <sys/mman.h> #include "unjit.hpp" namespace unjit { Process::Process(pid_t pid) : pid_(pid) { } Process::~Process() { } void Process::load_vm_maps() { vmas_.clear(); std::string filename = std::string("/proc/") + std::to_string(this->pid_) + std::string("/maps"); std::regex map_regex( // Start-end: "^([0-9a-f]+)-([0-9a-f]+)" // Flags: " ([r-])([w-])([x-])([p-])" // Offset: " ([0-9a-f]+)" // Device (major/minor): " [0-9a-f]+:[0-9a-f]+" // icode: " [0-9]*" // File name: " *(.*)$" ); std::ifstream file(filename); std::string line; std::smatch match; while (getline(file, line)) { if (!std::regex_search(line, match, map_regex)) continue; Vma vma; vma.start = strtoll(match[1].str().c_str(), nullptr, 16); vma.end = strtoll(match[2].str().c_str(), nullptr, 16); vma.prot = 0; if (match[3].str()[0] == 'r') vma.prot |= PROT_READ; if (match[4].str()[0] == 'w') vma.prot |= PROT_WRITE; if (match[5].str()[0] == 'x') vma.prot |= PROT_EXEC; if (match[6].str()[0] == 'p') vma.flags = MAP_PRIVATE; else vma.flags = MAP_SHARED; vma.offset = strtoll(match[7].str().c_str(), nullptr, 16); vma.name = match[8]; this->vmas_.push_back(std::move(vma)); } } void Process::load_modules() { this->areas_.clear(); size_t n = this->vmas_.size(); for (size_t i = 0; i != n; ++ i) { Vma const& vma = this->vmas_[i]; if (vma.name.empty() || vma.name[0] == '[') continue; // Find the end of the module: do { ++i; } while (i != n && this->vmas_[i].name == vma.name); if (this->vmas_[i].name.empty() && i != n) ++i; std::uint64_t end = this->vmas_[i - 1].end; std::shared_ptr<Module> module = load_module(vma.name); ModuleArea area; area.start = vma.start; area.end = end; area.module = std::move(module); this->areas_.push_back(std::move(area)); } } void Process::load_map_file() { std::string filename = std::string("/tmp/perf-") + std::to_string(this->pid_) + std::string(".map"); this->load_map_file(filename); } void Process::load_map_file(std::string const& map_file) { std::ifstream file(map_file); size_t size = 256; std::string line; while (getline(file, line)) { Symbol symbol; int name_index; if (sscanf(line.c_str(), "%" SCNx64 " %" SCNx64 "%n", &symbol.value, &symbol.size, &name_index) == 2) { while (name_index < line.size() && line[name_index] == ' ') ++name_index; symbol.name = std::string(line.c_str() + name_index); this->jit_symbols_[symbol.value] = std::move(symbol); } } } const char* Process::lookup_symbol(std::uint64_t ReferenceValue) { { auto i = this->jit_symbols_.find(ReferenceValue); if (i != this->jit_symbols_.end()) return i->second.name.c_str(); } unjit::ModuleArea const* area = this->find_module_area(ReferenceValue); if (area) { std::uint64_t relative_address = area->module->absolute_address ? ReferenceValue : ReferenceValue - area->start; auto i = area->module->symbols.find(relative_address); if (i != this->jit_symbols_.end()) return i->second.name.c_str(); } return NULL; } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, 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 the Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <planning_request_adapter/planning_request_adapter.h> #include <planning_models/conversions.h> #include <trajectory_processing/trajectory_tools.h> #include <pluginlib/class_list_macros.h> #include <ros/ros.h> namespace default_planner_request_adapters { class FixStartStateCollision : public planning_request_adapter::PlanningRequestAdapter { public: static const std::string DT_PARAM_NAME; static const std::string JIGGLE_PARAM_NAME; static const std::string ATTEMPTS_PARAM_NAME; FixStartStateCollision(void) : planning_request_adapter::PlanningRequestAdapter(), nh_("~") { if (!nh_.getParam(DT_PARAM_NAME, max_dt_offset_)) { max_dt_offset_ = 0.5; ROS_INFO_STREAM("Param '" << DT_PARAM_NAME << "' was not set. Using default value: " << max_dt_offset_); } else ROS_INFO_STREAM("Param '" << DT_PARAM_NAME << "' was set to " << max_dt_offset_); if (!nh_.getParam(JIGGLE_PARAM_NAME, jiggle_fraction_)) { jiggle_fraction_ = 0.02; ROS_INFO_STREAM("Param '" << JIGGLE_PARAM_NAME << "' was not set. Using default value: " << jiggle_fraction_); } else ROS_INFO_STREAM("Param '" << JIGGLE_PARAM_NAME << "' was set to " << jiggle_fraction_); if (!nh_.getParam(ATTEMPTS_PARAM_NAME, sampling_attempts_)) { sampling_attempts_ = 100; ROS_INFO_STREAM("Param '" << ATTEMPTS_PARAM_NAME << "' was not set. Using default value: " << sampling_attempts_); } else { if (sampling_attempts_ < 1) { sampling_attempts_ = 1; ROS_WARN_STREAM("Param '" << ATTEMPTS_PARAM_NAME << "' needs to be at least 1."); } ROS_INFO_STREAM("Param '" << ATTEMPTS_PARAM_NAME << "' was set to " << sampling_attempts_); } } virtual std::string getDescription(void) const { return "Fix Start State In Collision"; } virtual bool adaptAndPlan(const planning_request_adapter::PlannerFn &planner, const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res, std::vector<std::size_t> &added_path_index) const { ROS_DEBUG("Running '%s'", getDescription().c_str()); // get the specified start state planning_models::KinematicState start_state = planning_scene->getCurrentState(); planning_models::robotStateToKinematicState(*planning_scene->getTransforms(), req.motion_plan_request.start_state, start_state); collision_detection::CollisionRequest creq; creq.group_name = req.motion_plan_request.group_name; collision_detection::CollisionResult cres; planning_scene->checkCollision(creq, cres, start_state); if (cres.collision) { if (creq.group_name.empty()) ROS_INFO("Start state appears to be in collision"); else ROS_INFO_STREAM("Start state appears to be in collision with respect to group " << creq.group_name); planning_models::KinematicState prefix_state = start_state; random_numbers::RandomNumberGenerator rng; const std::vector<planning_models::KinematicState::JointState*> &jstates = planning_scene->getKinematicModel()->hasJointModelGroup(req.motion_plan_request.group_name) ? start_state.getJointStateGroup(req.motion_plan_request.group_name)->getJointStateVector() : start_state.getJointStateVector(); bool found = false; for (int c = 0 ; !found && c < sampling_attempts_ ; ++c) { for (std::size_t i = 0 ; !found && i < jstates.size() ; ++i) { std::vector<double> sampled_variable_values; const std::vector<double> &original_values = prefix_state.getJointState(jstates[i]->getName())->getVariableValues(); jstates[i]->getJointModel()->getRandomValuesNearBy(rng, sampled_variable_values, jstates[i]->getVariableBounds(), original_values, jstates[i]->getJointModel()->getMaximumExtent() * jiggle_fraction_); jstates[i]->setVariableValues(sampled_variable_values); start_state.updateLinkTransforms(); std::cout << "State distance: " << prefix_state.distance(start_state) << std::endl; collision_detection::CollisionResult cres; planning_scene->checkCollision(creq, cres, start_state); if (!cres.collision) { found = true; ROS_INFO("Found a valid state near the start state at distance %lf after %d attempts", prefix_state.distance(start_state), c); } } } if (found) { moveit_msgs::GetMotionPlan::Request req2 = req; planning_models::kinematicStateToRobotState(start_state, req2.motion_plan_request.start_state); bool solved = planner(planning_scene, req2, res); planning_models::kinematicStateToRobotState(prefix_state, res.trajectory_start); if (solved) { // heuristically decide a duration offset for the trajectory (induced by the additional point added as a prefix to the computed trajectory) double d = std::min(max_dt_offset_, trajectory_processing::averageSegmentDuration(res.trajectory)); trajectory_processing::addPrefixState(prefix_state, res.trajectory, d, planning_scene->getTransforms()); added_path_index.push_back(0); } return solved; } else { ROS_WARN("Unable to find a valid state nearby the start state (using jiggle fraction of %lf and %u sampling attempts). Passing the original planning request to the planner.", jiggle_fraction_, sampling_attempts_); return planner(planning_scene, req, res); } } else { if (creq.group_name.empty()) ROS_DEBUG("Start state is valid"); else ROS_DEBUG_STREAM("Start state is valid with respect to group " << creq.group_name); return planner(planning_scene, req, res); } } private: ros::NodeHandle nh_; double max_dt_offset_; double jiggle_fraction_; int sampling_attempts_; }; const std::string FixStartStateCollision::DT_PARAM_NAME = "start_state_max_dt"; const std::string FixStartStateCollision::JIGGLE_PARAM_NAME = "jiggle_fraction"; const std::string FixStartStateCollision::ATTEMPTS_PARAM_NAME = "max_sampling_attempts"; } PLUGINLIB_DECLARE_CLASS(default_planner_request_adapters, FixStartStateCollision, default_planner_request_adapters::FixStartStateCollision, planning_request_adapter::PlanningRequestAdapter); <commit_msg>remove superfluous output<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, 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 the Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <planning_request_adapter/planning_request_adapter.h> #include <planning_models/conversions.h> #include <trajectory_processing/trajectory_tools.h> #include <pluginlib/class_list_macros.h> #include <ros/ros.h> namespace default_planner_request_adapters { class FixStartStateCollision : public planning_request_adapter::PlanningRequestAdapter { public: static const std::string DT_PARAM_NAME; static const std::string JIGGLE_PARAM_NAME; static const std::string ATTEMPTS_PARAM_NAME; FixStartStateCollision(void) : planning_request_adapter::PlanningRequestAdapter(), nh_("~") { if (!nh_.getParam(DT_PARAM_NAME, max_dt_offset_)) { max_dt_offset_ = 0.5; ROS_INFO_STREAM("Param '" << DT_PARAM_NAME << "' was not set. Using default value: " << max_dt_offset_); } else ROS_INFO_STREAM("Param '" << DT_PARAM_NAME << "' was set to " << max_dt_offset_); if (!nh_.getParam(JIGGLE_PARAM_NAME, jiggle_fraction_)) { jiggle_fraction_ = 0.02; ROS_INFO_STREAM("Param '" << JIGGLE_PARAM_NAME << "' was not set. Using default value: " << jiggle_fraction_); } else ROS_INFO_STREAM("Param '" << JIGGLE_PARAM_NAME << "' was set to " << jiggle_fraction_); if (!nh_.getParam(ATTEMPTS_PARAM_NAME, sampling_attempts_)) { sampling_attempts_ = 100; ROS_INFO_STREAM("Param '" << ATTEMPTS_PARAM_NAME << "' was not set. Using default value: " << sampling_attempts_); } else { if (sampling_attempts_ < 1) { sampling_attempts_ = 1; ROS_WARN_STREAM("Param '" << ATTEMPTS_PARAM_NAME << "' needs to be at least 1."); } ROS_INFO_STREAM("Param '" << ATTEMPTS_PARAM_NAME << "' was set to " << sampling_attempts_); } } virtual std::string getDescription(void) const { return "Fix Start State In Collision"; } virtual bool adaptAndPlan(const planning_request_adapter::PlannerFn &planner, const planning_scene::PlanningSceneConstPtr& planning_scene, const moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res, std::vector<std::size_t> &added_path_index) const { ROS_DEBUG("Running '%s'", getDescription().c_str()); // get the specified start state planning_models::KinematicState start_state = planning_scene->getCurrentState(); planning_models::robotStateToKinematicState(*planning_scene->getTransforms(), req.motion_plan_request.start_state, start_state); collision_detection::CollisionRequest creq; creq.group_name = req.motion_plan_request.group_name; collision_detection::CollisionResult cres; planning_scene->checkCollision(creq, cres, start_state); if (cres.collision) { if (creq.group_name.empty()) ROS_INFO("Start state appears to be in collision"); else ROS_INFO_STREAM("Start state appears to be in collision with respect to group " << creq.group_name); planning_models::KinematicState prefix_state = start_state; random_numbers::RandomNumberGenerator rng; const std::vector<planning_models::KinematicState::JointState*> &jstates = planning_scene->getKinematicModel()->hasJointModelGroup(req.motion_plan_request.group_name) ? start_state.getJointStateGroup(req.motion_plan_request.group_name)->getJointStateVector() : start_state.getJointStateVector(); bool found = false; for (int c = 0 ; !found && c < sampling_attempts_ ; ++c) { for (std::size_t i = 0 ; !found && i < jstates.size() ; ++i) { std::vector<double> sampled_variable_values; const std::vector<double> &original_values = prefix_state.getJointState(jstates[i]->getName())->getVariableValues(); jstates[i]->getJointModel()->getRandomValuesNearBy(rng, sampled_variable_values, jstates[i]->getVariableBounds(), original_values, jstates[i]->getJointModel()->getMaximumExtent() * jiggle_fraction_); jstates[i]->setVariableValues(sampled_variable_values); start_state.updateLinkTransforms(); collision_detection::CollisionResult cres; planning_scene->checkCollision(creq, cres, start_state); if (!cres.collision) { found = true; ROS_INFO("Found a valid state near the start state at distance %lf after %d attempts", prefix_state.distance(start_state), c); } } } if (found) { moveit_msgs::GetMotionPlan::Request req2 = req; planning_models::kinematicStateToRobotState(start_state, req2.motion_plan_request.start_state); bool solved = planner(planning_scene, req2, res); planning_models::kinematicStateToRobotState(prefix_state, res.trajectory_start); if (solved) { // heuristically decide a duration offset for the trajectory (induced by the additional point added as a prefix to the computed trajectory) double d = std::min(max_dt_offset_, trajectory_processing::averageSegmentDuration(res.trajectory)); trajectory_processing::addPrefixState(prefix_state, res.trajectory, d, planning_scene->getTransforms()); added_path_index.push_back(0); } return solved; } else { ROS_WARN("Unable to find a valid state nearby the start state (using jiggle fraction of %lf and %u sampling attempts). Passing the original planning request to the planner.", jiggle_fraction_, sampling_attempts_); return planner(planning_scene, req, res); } } else { if (creq.group_name.empty()) ROS_DEBUG("Start state is valid"); else ROS_DEBUG_STREAM("Start state is valid with respect to group " << creq.group_name); return planner(planning_scene, req, res); } } private: ros::NodeHandle nh_; double max_dt_offset_; double jiggle_fraction_; int sampling_attempts_; }; const std::string FixStartStateCollision::DT_PARAM_NAME = "start_state_max_dt"; const std::string FixStartStateCollision::JIGGLE_PARAM_NAME = "jiggle_fraction"; const std::string FixStartStateCollision::ATTEMPTS_PARAM_NAME = "max_sampling_attempts"; } PLUGINLIB_DECLARE_CLASS(default_planner_request_adapters, FixStartStateCollision, default_planner_request_adapters::FixStartStateCollision, planning_request_adapter::PlanningRequestAdapter); <|endoftext|>
<commit_before>/* * Copyright (c) 2016, The OpenThread Authors. * 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 the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes macros for validating runtime conditions. */ #ifndef CODE_UTILS_HPP_ #define CODE_UTILS_HPP_ #include "openthread-core-config.h" #include <stdbool.h> #include "utils/static_assert.hpp" /** * This macro calculates the number of elements in an array. * * @param[in] aArray Name of the array variable. * * @returns Number of elements in the array. * */ #define OT_ARRAY_LENGTH(aArray) (sizeof(aArray) / sizeof(aArray[0])) /** * This macro returns a pointer to end of a given array (pointing to the past-the-end element). * * Note that the past-the-end element is a theoretical element that would follow the last element in the array. It does * not point to an actual element in array, and thus should not be dereferenced. * * @param[in] Name of the array variable * * @returns Pointer to the past-the-end element. * */ #define OT_ARRAY_END(aArray) (&aArray[OT_ARRAY_LENGTH(aArray)]) /** * This macro returns a pointer aligned by @p aAlignment. * * @param[in] aPointer A pointer to contiguous space. * @param[in] aAlignment The desired alignment. * * @returns The aligned pointer. * */ #define OT_ALIGN(aPointer, aAlignment) \ ((void *)(((uintptr_t)(aPointer) + (aAlignment)-1UL) & ~((uintptr_t)(aAlignment)-1UL))) // Calculates the aligned variable size. #define OT_ALIGNED_VAR_SIZE(size, align_type) (((size) + (sizeof(align_type) - 1)) / sizeof(align_type)) // Allocate the structure using "raw" storage. #define OT_DEFINE_ALIGNED_VAR(name, size, align_type) \ align_type name[(((size) + (sizeof(align_type) - 1)) / sizeof(align_type))] /** * This macro checks for the specified status, which is expected to commonly be successful, and branches to the local * label 'exit' if the status is unsuccessful. * * @param[in] aStatus A scalar status to be evaluated against zero (0). * */ #define SuccessOrExit(aStatus) \ do \ { \ if ((aStatus) != 0) \ { \ goto exit; \ } \ } while (false) /** * This macro checks for the specified condition, which is expected to commonly be true, and both executes @a ... and * branches to the local label 'exit' if the condition is false. * * @param[in] aCondition A Boolean expression to be evaluated. * @param[in] ... An expression or block to execute when the assertion fails. * */ #define VerifyOrExit(aCondition, ...) \ do \ { \ if (!(aCondition)) \ { \ __VA_ARGS__; \ goto exit; \ } \ } while (false) /** * This macro unconditionally executes @a ... and branches to the local label 'exit'. * * @note The use of this interface implies neither success nor failure for the overall exit status of the enclosing * function body. * * @param[in] ... An optional expression or block to execute when the assertion fails. * */ #define ExitNow(...) \ do \ { \ __VA_ARGS__; \ goto exit; \ } while (false) /* * This macro executes the `statement` and ignores the return value. * * This is primarily used to indicate the intention of developer that the return value of a function/method can be * safely ignored. * * @param[in] aStatement The function/method to execute. * */ #define IgnoreReturnValue(aStatement) \ do \ { \ if (aStatement) \ { \ } \ } while (false) #endif // CODE_UTILS_HPP_ <commit_msg>[code-utils] update comments (#4367)<commit_after>/* * Copyright (c) 2016, The OpenThread Authors. * 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 the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes macros for validating runtime conditions. */ #ifndef CODE_UTILS_HPP_ #define CODE_UTILS_HPP_ #include "openthread-core-config.h" #include <stdbool.h> #include "utils/static_assert.hpp" /** * This macro calculates the number of elements in an array. * * @param[in] aArray Name of the array variable. * * @returns Number of elements in the array. * */ #define OT_ARRAY_LENGTH(aArray) (sizeof(aArray) / sizeof(aArray[0])) /** * This macro returns a pointer to end of a given array (pointing to the past-the-end element). * * Note that the past-the-end element is a theoretical element that would follow the last element in the array. It does * not point to an actual element in array, and thus should not be dereferenced. * * @param[in] Name of the array variable * * @returns Pointer to the past-the-end element. * */ #define OT_ARRAY_END(aArray) (&aArray[OT_ARRAY_LENGTH(aArray)]) /** * This macro returns a pointer aligned by @p aAlignment. * * @param[in] aPointer A pointer to contiguous space. * @param[in] aAlignment The desired alignment. * * @returns The aligned pointer. * */ #define OT_ALIGN(aPointer, aAlignment) \ ((void *)(((uintptr_t)(aPointer) + (aAlignment)-1UL) & ~((uintptr_t)(aAlignment)-1UL))) // Calculates the aligned variable size. #define OT_ALIGNED_VAR_SIZE(size, align_type) (((size) + (sizeof(align_type) - 1)) / sizeof(align_type)) // Allocate the structure using "raw" storage. #define OT_DEFINE_ALIGNED_VAR(name, size, align_type) \ align_type name[(((size) + (sizeof(align_type) - 1)) / sizeof(align_type))] /** * This macro checks for the specified status, which is expected to commonly be successful, and branches to the local * label 'exit' if the status is unsuccessful. * * @param[in] aStatus A scalar status to be evaluated against zero (0). * */ #define SuccessOrExit(aStatus) \ do \ { \ if ((aStatus) != 0) \ { \ goto exit; \ } \ } while (false) /** * This macro checks for the specified condition, which is expected to commonly be true, and both executes @a ... and * branches to the local label 'exit' if the condition is false. * * @param[in] aCondition A Boolean expression to be evaluated. * @param[in] ... An expression or block to execute when the assertion fails. * */ #define VerifyOrExit(aCondition, ...) \ do \ { \ if (!(aCondition)) \ { \ __VA_ARGS__; \ goto exit; \ } \ } while (false) /** * This macro unconditionally executes @a ... and branches to the local label 'exit'. * * @note The use of this interface implies neither success nor failure for the overall exit status of the enclosing * function body. * * @param[in] ... An optional expression or block to execute when the assertion fails. * */ #define ExitNow(...) \ do \ { \ __VA_ARGS__; \ goto exit; \ } while (false) /* * This macro executes the `statement` and ignores the return value. * * This is primarily used to indicate the intention of developer that the return value of a function/method can be * safely ignored. * * @param[in] aStatement The function/method to execute. * */ #define IgnoreReturnValue(aStatement) \ do \ { \ if (aStatement) \ { \ } \ } while (false) #endif // CODE_UTILS_HPP_ <|endoftext|>
<commit_before>/* ************************************************************************************ * * ftFluidFlow * * Created by Matthias Oostrik on 03/16.14. * Copyright 2014 http://www.MatthiasOostrik.com All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones: * * Mark J Harris: Various online sources * * Patricio Gonzalez Vivo (http://www.patriciogonzalezvivo.com): ofxFluid * * ************************************************************************************ */ #include "ftFluidFlow.h" namespace flowTools { ftFluidFlow::ftFluidFlow(){ parameters.setName("fluid"); parameters.add(speed.set("speed", .5, 0, 1)); parameters.add(numJacobiIterations.set("iterations", 40, 1, 100)); parameters.add(viscosity.set("viscosity", 0.0, 0, 1)); parameters.add(vorticity.set("vorticity", 0.0, 0.0, 1)); dissipationParameters.setName("dissipation"); dissipationParameters.add(dissipationVel.set("velocity",0.0015, 0, 0.025)); dissipationParameters.add(dissipationDen.set("density", 0.0015, 0, 0.025)); dissipationParameters.add(dissipationPrs.set("pressure",0.025, 0, 0.1)); parameters.add(dissipationParameters); // smokeBuoyancyParameters.setName("smoke buoyancy"); // smokeBuoyancyParameters.add(smokeSigma.set("buoyancy", 0.5, 0.0, 1.0)); // smokeBuoyancyParameters.add(smokeWeight.set("weight", 0.05, 0.0, 1.0)); // smokeBuoyancyParameters.add(ambientTemperature.set("ambient temperature", 0.75, 0.0, 1.0)); // smokeBuoyancyParameters.add(gravity.set("gravity", ofDefaultVec2(0., -0.980665), ofDefaultVec2(-1, -1), ofDefaultVec2(1, 1))); // parameters.add(smokeBuoyancyParameters); } //-------------------------------------------------------------- void ftFluidFlow::setup(int _flowWidth, int _flowHeight, int _densityWidth, int _densityHeight) { simulationWidth = _flowWidth; simulationHeight = _flowHeight; densityWidth = _densityWidth; densityHeight = _densityHeight; ftFlow::allocate(simulationWidth, simulationHeight, GL_RG32F, densityWidth, densityHeight, GL_RGBA32F); visualizationField.setup(simulationWidth, simulationHeight); temperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(temperatureFbo); pressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(pressureFbo); obstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8); ftUtil::zero(obstacleFbo); obstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGB32F); ftUtil::zero(obstacleOffsetFbo); divergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F); ftUtil::zero(divergenceFbo); smokeBuoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(smokeBuoyancyFbo); vorticityVelocityFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); vorticityConfinementFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); } //-------------------------------------------------------------- void ftFluidFlow::update(float _deltaTime){ float timeStep = _deltaTime * speed.get() * simulationWidth; ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftPingPongFbo& velocityFbo = inputFbo; ftPingPongFbo& densityFbo = outputFbo; // ADVECT velocityFbo.swap(); advectShader.update(velocityFbo, velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), timeStep, 1.0 - dissipationVel.get()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // ADD FORCES: DIFFUSE if (viscosity.get() > 0.0) { for (int i = 0; i < numJacobiIterations.get(); i++) { velocityFbo.swap(); diffuseShader.update(velocityFbo, velocityFbo.getBackTexture(), viscosity.get()); } velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: VORTEX CONFINEMENT if (vorticity.get() > 0.0) { vorticityVelocityShader.update(vorticityVelocityFbo, velocityFbo.getTexture()); vorticityConfinementShader.update(vorticityConfinementFbo, vorticityVelocityFbo.getTexture(), timeStep, vorticity.get()); addVelocity(vorticityConfinementFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: SMOKE BUOYANCY // if (smokeSigma.get() > 0.0 && smokeWeight.get() > 0.0 ) { // temperatureFbo.swap(); // advectShader.update(temperatureFbo, temperatureFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); // temperatureFbo.swap(); // clampLengthShader.update(temperatureFbo, temperatureFbo.getBackTexture(), 2.0, 1.0); // temperatureFbo.swap(); // applyObstacleShader.update(temperatureFbo, temperatureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // ftUtil::zero(smokeBuoyancyFbo); // smokeBuoyancyShader.update(smokeBuoyancyFbo, temperatureFbo.getTexture(), densityFbo.getTexture(), ambientTemperature.get(), timeStep, smokeSigma.get(), smokeWeight.get(), gravity.get()); // addVelocity(smokeBuoyancyFbo.getTexture()); // velocityFbo.swap(); // applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // } // else { // ftUtil::zero(temperatureFbo); // } // PRESSURE: DIVERGENCE ftUtil::zero(divergenceFbo); divergenceShader.update(divergenceFbo, velocityFbo.getTexture()); // PRESSURE: JACOBI // ftUtil::zero(pressureFbo); pressureFbo.swap(); multiplyForceShader.update(pressureFbo, pressureFbo.getBackTexture(), 1.0 - dissipationPrs.get()); for (int i = 0; i < numJacobiIterations.get(); i++) { pressureFbo.swap(); jacobiShader.update(pressureFbo, pressureFbo.getBackTexture(), divergenceFbo.getTexture()); } pressureFbo.swap(); applyObstacleShader.update(pressureFbo, pressureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // PRESSURE: SUBSTRACT GRADIENT velocityFbo.swap(); substractGradientShader.update(velocityFbo, velocityFbo.getBackTexture(), pressureFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // DENSITY: densityFbo.swap(); advectShader.update(densityFbo, densityFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); densityFbo.swap(); clampLengthShader.update(densityFbo, densityFbo.getBackTexture(), sqrt(3), 1.0); densityFbo.swap(); applyObstacleShader.update(densityFbo, densityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) { switch (_type) { case FT_VELOCITY: setVelocity(_tex); break; case FT_DENSITY: setDensity(_tex); break; case FT_TEMPERATURE: setTemperature(_tex); break; case FT_PRESSURE: setPressure(_tex); break; case FT_OBSTACLE: setObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) { switch (_type) { case FT_VELOCITY: addVelocity(_tex, _strength); break; case FT_DENSITY: addDensity(_tex, _strength); break; case FT_TEMPERATURE: addTemperature(_tex, _strength); break; case FT_PRESSURE: addPressure(_tex, _strength); break; case FT_OBSTACLE: addObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::setObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftUtil::zero(obstacleFbo); addBooleanShader.update(obstacleFbo, obstacleFbo.getBackTexture(), _tex); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::addObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); obstacleFbo.swap(); addBooleanShader.update(obstacleFbo, obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::reset() { ftFlow::reset(); ftUtil::zero(pressureFbo); ftUtil::zero(temperatureFbo); ftUtil::zero(obstacleFbo); advectShader = ftAdvectShader(); diffuseShader = ftDiffuseShader(); divergenceShader = ftDivergenceShader(); jacobiShader = ftJacobiShader(); substractGradientShader = ftSubstractGradientShader(); obstacleOffsetShader = ftObstacleOffsetShader(); applyObstacleShader = ftApplyObstacleShader(); } } <commit_msg>obstacle setup fix<commit_after>/* ************************************************************************************ * * ftFluidFlow * * Created by Matthias Oostrik on 03/16.14. * Copyright 2014 http://www.MatthiasOostrik.com All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones: * * Mark J Harris: Various online sources * * Patricio Gonzalez Vivo (http://www.patriciogonzalezvivo.com): ofxFluid * * ************************************************************************************ */ #include "ftFluidFlow.h" namespace flowTools { ftFluidFlow::ftFluidFlow(){ parameters.setName("fluid"); parameters.add(speed.set("speed", .5, 0, 1)); parameters.add(numJacobiIterations.set("iterations", 40, 1, 100)); parameters.add(viscosity.set("viscosity", 0.0, 0, 1)); parameters.add(vorticity.set("vorticity", 0.0, 0.0, 1)); dissipationParameters.setName("dissipation"); dissipationParameters.add(dissipationVel.set("velocity",0.0015, 0, 0.025)); dissipationParameters.add(dissipationDen.set("density", 0.0015, 0, 0.025)); dissipationParameters.add(dissipationPrs.set("pressure",0.025, 0, 0.1)); parameters.add(dissipationParameters); // smokeBuoyancyParameters.setName("smoke buoyancy"); // smokeBuoyancyParameters.add(smokeSigma.set("buoyancy", 0.5, 0.0, 1.0)); // smokeBuoyancyParameters.add(smokeWeight.set("weight", 0.05, 0.0, 1.0)); // smokeBuoyancyParameters.add(ambientTemperature.set("ambient temperature", 0.75, 0.0, 1.0)); // smokeBuoyancyParameters.add(gravity.set("gravity", ofDefaultVec2(0., -0.980665), ofDefaultVec2(-1, -1), ofDefaultVec2(1, 1))); // parameters.add(smokeBuoyancyParameters); } //-------------------------------------------------------------- void ftFluidFlow::setup(int _flowWidth, int _flowHeight, int _densityWidth, int _densityHeight) { simulationWidth = _flowWidth; simulationHeight = _flowHeight; densityWidth = _densityWidth; densityHeight = _densityHeight; ftFlow::allocate(simulationWidth, simulationHeight, GL_RG32F, densityWidth, densityHeight, GL_RGBA32F); visualizationField.setup(simulationWidth, simulationHeight); temperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(temperatureFbo); pressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(pressureFbo); obstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8); ftUtil::zero(obstacleFbo); obstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGB32F); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); divergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F); ftUtil::zero(divergenceFbo); smokeBuoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(smokeBuoyancyFbo); vorticityVelocityFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); vorticityConfinementFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(pressureFbo); } //-------------------------------------------------------------- void ftFluidFlow::update(float _deltaTime){ float timeStep = _deltaTime * speed.get() * simulationWidth; ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftPingPongFbo& velocityFbo = inputFbo; ftPingPongFbo& densityFbo = outputFbo; // ADVECT velocityFbo.swap(); advectShader.update(velocityFbo, velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), timeStep, 1.0 - dissipationVel.get()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // ADD FORCES: DIFFUSE if (viscosity.get() > 0.0) { for (int i = 0; i < numJacobiIterations.get(); i++) { velocityFbo.swap(); diffuseShader.update(velocityFbo, velocityFbo.getBackTexture(), viscosity.get()); } velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: VORTEX CONFINEMENT if (vorticity.get() > 0.0) { vorticityVelocityShader.update(vorticityVelocityFbo, velocityFbo.getTexture()); vorticityConfinementShader.update(vorticityConfinementFbo, vorticityVelocityFbo.getTexture(), timeStep, vorticity.get()); addVelocity(vorticityConfinementFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); } // ADD FORCES: SMOKE BUOYANCY // if (smokeSigma.get() > 0.0 && smokeWeight.get() > 0.0 ) { // temperatureFbo.swap(); // advectShader.update(temperatureFbo, temperatureFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); // temperatureFbo.swap(); // clampLengthShader.update(temperatureFbo, temperatureFbo.getBackTexture(), 2.0, 1.0); // temperatureFbo.swap(); // applyObstacleShader.update(temperatureFbo, temperatureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // ftUtil::zero(smokeBuoyancyFbo); // smokeBuoyancyShader.update(smokeBuoyancyFbo, temperatureFbo.getTexture(), densityFbo.getTexture(), ambientTemperature.get(), timeStep, smokeSigma.get(), smokeWeight.get(), gravity.get()); // addVelocity(smokeBuoyancyFbo.getTexture()); // velocityFbo.swap(); // applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // } // else { // ftUtil::zero(temperatureFbo); // } // PRESSURE: DIVERGENCE ftUtil::zero(divergenceFbo); divergenceShader.update(divergenceFbo, velocityFbo.getTexture()); // PRESSURE: JACOBI // ftUtil::zero(pressureFbo); pressureFbo.swap(); multiplyForceShader.update(pressureFbo, pressureFbo.getBackTexture(), 1.0 - dissipationPrs.get()); for (int i = 0; i < numJacobiIterations.get(); i++) { pressureFbo.swap(); jacobiShader.update(pressureFbo, pressureFbo.getBackTexture(), divergenceFbo.getTexture()); } pressureFbo.swap(); applyObstacleShader.update(pressureFbo, pressureFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); // PRESSURE: SUBSTRACT GRADIENT velocityFbo.swap(); substractGradientShader.update(velocityFbo, velocityFbo.getBackTexture(), pressureFbo.getTexture()); velocityFbo.swap(); applyObstacleShader.update(velocityFbo, velocityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), -1.0); // DENSITY: densityFbo.swap(); advectShader.update(densityFbo, densityFbo.getBackTexture(), velocityFbo.getTexture(), timeStep, 1.0 - dissipationDen.get()); densityFbo.swap(); clampLengthShader.update(densityFbo, densityFbo.getBackTexture(), sqrt(3), 1.0); densityFbo.swap(); applyObstacleShader.update(densityFbo, densityFbo.getBackTexture(), obstacleOffsetFbo.getTexture(), 1.0); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) { switch (_type) { case FT_VELOCITY: setVelocity(_tex); break; case FT_DENSITY: setDensity(_tex); break; case FT_TEMPERATURE: setTemperature(_tex); break; case FT_PRESSURE: setPressure(_tex); break; case FT_OBSTACLE: setObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) { switch (_type) { case FT_VELOCITY: addVelocity(_tex, _strength); break; case FT_DENSITY: addDensity(_tex, _strength); break; case FT_TEMPERATURE: addTemperature(_tex, _strength); break; case FT_PRESSURE: addPressure(_tex, _strength); break; case FT_OBSTACLE: addObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::setObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftUtil::zero(obstacleFbo); addBooleanShader.update(obstacleFbo, obstacleFbo.getBackTexture(), _tex); ftUtil::zero(obstacleOffsetFbo); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::addObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); obstacleFbo.swap(); addBooleanShader.update(obstacleFbo, obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::reset() { ftFlow::reset(); ftUtil::zero(pressureFbo); ftUtil::zero(temperatureFbo); ftUtil::zero(obstacleFbo); advectShader = ftAdvectShader(); diffuseShader = ftDiffuseShader(); divergenceShader = ftDivergenceShader(); jacobiShader = ftJacobiShader(); substractGradientShader = ftSubstractGradientShader(); obstacleOffsetShader = ftObstacleOffsetShader(); applyObstacleShader = ftApplyObstacleShader(); } } <|endoftext|>
<commit_before>/* ************************************************************************************ * * ftFluidFlow * * Created by Matthias Oostrik on 03/16.14. * Copyright 2014 http://www.MatthiasOostrik.com All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones: * * Mark J Harris: Various online sources * * Patricio Gonzalez Vivo (http://www.patriciogonzalezvivo.com): ofxFluid * * ************************************************************************************ */ #include "ftFluidFlow.h" namespace flowTools { ftFluidFlow::ftFluidFlow(){ parameters.setName("fluid"); parameters.add(speed.set("speed" , 0.3, 0.0, 1.0)); dissipationParameters.setName("dissipation"); dissipationParameters.add(dissipationVel.set("velocity" , 0.1, 0.0, 1.0)); dissipationParameters.add(dissipationDen.set("density" , 0.1, 0.0, 1.0)); dissipationParameters.add(dissipationTmp.set("temperature" , 0.1, 0.0, 1.0)); dissipationParameters.add(dissipationPrs.set("pressure" , 0.1, 0.0, 1.0)); parameters.add(dissipationParameters); viscosityParameters.setName("viscosity"); viscosityParameters.add(viscosityVel.set("velocity" , 0.5, 0.0, 1.0)); viscosityParameters.add(viscosityDen.set("density" , 0.0, 0.0, 1.0)); viscosityParameters.add(viscosityTmp.set("temperature" , 0.0, 0.0, 1.0)); parameters.add(viscosityParameters); parameters.add(vorticity.set("vorticity" , 1.0, 0.0, 1.0)); buoyancyParameters.setName("smoke buoyancy"); buoyancyParameters.add(buoyancySigma.set("buoyancy" , 0.6, 0.0, 1.0)); buoyancyParameters.add(buoyancyWeight.set("weight" , 0.2, 0.0, 1.0)); buoyancyParameters.add(buoyancyAmbientTemperature.set("ambient temperature", 0.2, 0.0, 1.0)); parameters.add(buoyancyParameters); numJacobiIterationsProjection = 40; numJacobiIterationsDiffuse = 20; gridScale = 1; } //-------------------------------------------------------------- void ftFluidFlow::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) { allocate(_simulationWidth, _simulationHeight, GL_RG32F, _densityWidth, _densityHeight, GL_RGBA32F); } //-------------------------------------------------------------- void ftFluidFlow::allocate(int _simulationWidth, int _simulationHeight, GLint _simulationInternalFormat, int _densityWidth, int _densityHeight, GLint _densityInternalFormat) { simulationWidth = _simulationWidth; simulationHeight = _simulationHeight; densityWidth = _densityWidth; densityHeight = _densityHeight; ftFlow::allocate(simulationWidth, simulationHeight, _simulationInternalFormat, densityWidth, densityHeight, _densityInternalFormat); visualizationField.setup(simulationWidth, simulationHeight); temperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(temperatureFbo); pressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(pressureFbo); divergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F); ftUtil::zero(divergenceFbo); vorticityCurlFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(vorticityCurlFbo); vorticityForceFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(vorticityForceFbo); buoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(buoyancyFbo); obstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8); ftUtil::zero(obstacleFbo); obstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGBA8); ftUtil::zero(obstacleOffsetFbo); initObstacle(); } //-------------------------------------------------------------- void ftFluidFlow::update(float _deltaTime){ float timeStep = _deltaTime * speed.get() * 100; ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftPingPongFbo& velocityFbo = inputFbo; ftPingPongFbo& densityFbo = outputFbo; // ADVECT & DISSEPATE float vDis = 1.0 - _deltaTime * dissipationVel.get(); velocityFbo.swap(); advectShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), obstacleFbo.getTexture(), timeStep, gridScale, vDis); float dDis = 1.0 - _deltaTime * dissipationDen.get(); densityFbo.swap(); advectShader.update(densityFbo.get(), densityFbo.getBackTexture(), velocityFbo.getTexture(), obstacleFbo.getTexture(), timeStep, gridScale, dDis); float tDis = 1.0 - _deltaTime * dissipationTmp.get(); temperatureFbo.swap(); advectShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), velocityFbo.getTexture(), obstacleFbo.getTexture(), timeStep, gridScale, tDis); float pDis = 1.0 - dissipationPrs.get(); pressureFbo.swap(); multiplyForceShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), pDis); // DIFFUSE if (viscosityVel.get() > 0.0) { float vDif = timeStep * viscosityVel.get(); for (int i = 0; i < numJacobiIterationsDiffuse; i++) { velocityFbo.swap(); jacobiDiffusionShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), vDif, gridScale); } } if (viscosityDen.get() > 0.0) { float dDif = timeStep * viscosityDen.get(); for (int i = 0; i < numJacobiIterationsDiffuse; i++) { densityFbo.swap(); jacobiDiffusionShader.update(densityFbo.get(), densityFbo.getBackTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), dDif, gridScale); } } if (viscosityTmp.get() > 0.0) { float tDif = timeStep * viscosityTmp.get(); for (int i = 0; i < numJacobiIterationsDiffuse; i++) { temperatureFbo.swap(); jacobiDiffusionShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), tDif, gridScale); } } // VORTEX CONFINEMENT if (vorticity.get() > 0.0) { vorticityCurlShader.update(vorticityCurlFbo, velocityFbo.getTexture(), obstacleFbo.getTexture(), gridScale); vorticityForceShader.update(vorticityForceFbo, vorticityCurlFbo.getTexture(), timeStep, gridScale, vorticity.get()); addVelocity(vorticityForceFbo.getTexture()); } // BUOYANCY if (buoyancySigma.get() > 0.0 && buoyancyWeight.get() > 0.0 ) { buoyancyShader.update(buoyancyFbo, velocityFbo.getTexture(), temperatureFbo.getTexture(), densityFbo.getTexture(), timeStep, buoyancyAmbientTemperature, buoyancySigma.get(), buoyancyWeight.get()); addVelocity(buoyancyFbo.getTexture()); } // PRESSURE: DIVERGENCE divergenceShader.update(divergenceFbo, velocityFbo.getTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), gridScale); // PRESSURE: JACOBI for (int i = 0; i < numJacobiIterationsProjection; i++) { pressureFbo.swap(); jacobiPressureShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), divergenceFbo.getTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), gridScale); } // PRESSURE: GRADIENT velocityFbo.swap(); gradientShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), pressureFbo.getTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), gridScale); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) { switch (_type) { case FT_VELOCITY: setVelocity(_tex); break; case FT_DENSITY: setDensity(_tex); break; case FT_TEMPERATURE: setTemperature(_tex); break; case FT_PRESSURE: setPressure(_tex); break; case FT_OBSTACLE: setObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) { switch (_type) { case FT_VELOCITY: addVelocity(_tex, _strength); break; case FT_DENSITY: addDensity(_tex, _strength); break; case FT_TEMPERATURE: addTemperature(_tex, _strength); break; case FT_PRESSURE: addPressure(_tex, _strength); break; case FT_OBSTACLE: addObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::initObstacle(){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftUtil::one(obstacleFbo); obstacleFbo.begin(); ofSetColor(0,0,0,255); int borderSize = 1; ofDrawRectangle(borderSize, borderSize, obstacleFbo.getWidth()-borderSize*2, obstacleFbo.getHeight()-borderSize*2); obstacleFbo.end(); ofPopStyle(); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); } //-------------------------------------------------------------- void ftFluidFlow::setObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); initObstacle(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::addObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); obstacleFbo.swap(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::reset() { ftFlow::reset(); ftUtil::zero(pressureFbo); ftUtil::zero(temperatureFbo); ftUtil::zero(divergenceFbo); ftUtil::zero(vorticityCurlFbo); ftUtil::zero(buoyancyFbo); initObstacle(); advectShader = ftAdvectShader(); buoyancyShader = ftBuoyancyShader(); divergenceShader = ftDivergenceShader(); gradientShader = ftGradientShader(); jacobiDiffusionShader = ftJacobiDiffusionShader(); obstacleOffsetShader = ftObstacleOffsetShader(); vorticityCurlShader = ftVorticityCurlShader(); vorticityForceShader = ftVorticityForceShader(); } } <commit_msg>cleanup<commit_after>/* ************************************************************************************ * * ftFluidFlow * * Created by Matthias Oostrik on 03/16.14. * Copyright 2014 http://www.MatthiasOostrik.com All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The Fluid shaders are adapted from various sources. Unfortunately I can't remember all, but the most important ones: * * Mark J Harris: Various online sources * * Patricio Gonzalez Vivo (http://www.patriciogonzalezvivo.com): ofxFluid * * ************************************************************************************ */ #include "ftFluidFlow.h" namespace flowTools { ftFluidFlow::ftFluidFlow(){ parameters.setName("fluid"); parameters.add(speed.set("speed" , 0.3, 0.0, 1.0)); dissipationParameters.setName("dissipation"); dissipationParameters.add(dissipationVel.set("velocity" , 0.1, 0.0, 1.0)); dissipationParameters.add(dissipationDen.set("density" , 0.1, 0.0, 1.0)); dissipationParameters.add(dissipationTmp.set("temperature" , 0.1, 0.0, 1.0)); dissipationParameters.add(dissipationPrs.set("pressure" , 0.1, 0.0, 1.0)); parameters.add(dissipationParameters); viscosityParameters.setName("viscosity"); viscosityParameters.add(viscosityVel.set("velocity" , 0.5, 0.0, 1.0)); viscosityParameters.add(viscosityDen.set("density" , 0.0, 0.0, 1.0)); viscosityParameters.add(viscosityTmp.set("temperature" , 0.0, 0.0, 1.0)); parameters.add(viscosityParameters); parameters.add(vorticity.set("vorticity" , 1.0, 0.0, 1.0)); buoyancyParameters.setName("smoke buoyancy"); buoyancyParameters.add(buoyancySigma.set("buoyancy" , 0.6, 0.0, 1.0)); buoyancyParameters.add(buoyancyWeight.set("weight" , 0.2, 0.0, 1.0)); buoyancyParameters.add(buoyancyAmbientTemperature.set("ambient temperature", 0.2, 0.0, 1.0)); parameters.add(buoyancyParameters); numJacobiIterationsProjection = 40; numJacobiIterationsDiffuse = 20; gridScale = 1; } //-------------------------------------------------------------- void ftFluidFlow::setup(int _simulationWidth, int _simulationHeight, int _densityWidth, int _densityHeight) { allocate(_simulationWidth, _simulationHeight, GL_RG32F, _densityWidth, _densityHeight, GL_RGBA32F); } //-------------------------------------------------------------- void ftFluidFlow::allocate(int _simulationWidth, int _simulationHeight, GLint _simulationInternalFormat, int _densityWidth, int _densityHeight, GLint _densityInternalFormat) { simulationWidth = _simulationWidth; simulationHeight = _simulationHeight; densityWidth = _densityWidth; densityHeight = _densityHeight; ftFlow::allocate(simulationWidth, simulationHeight, _simulationInternalFormat, densityWidth, densityHeight, _densityInternalFormat); visualizationField.setup(simulationWidth, simulationHeight); temperatureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(temperatureFbo); pressureFbo.allocate(simulationWidth,simulationHeight,GL_R32F); ftUtil::zero(pressureFbo); divergenceFbo.allocate(simulationWidth, simulationHeight, GL_R32F); ftUtil::zero(divergenceFbo); vorticityCurlFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(vorticityCurlFbo); vorticityForceFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(vorticityForceFbo); buoyancyFbo.allocate(simulationWidth, simulationHeight, GL_RG32F); ftUtil::zero(buoyancyFbo); obstacleFbo.allocate(simulationWidth, simulationHeight, GL_R8); ftUtil::zero(obstacleFbo); obstacleOffsetFbo.allocate(simulationWidth, simulationHeight, GL_RGBA8); ftUtil::zero(obstacleOffsetFbo); initObstacle(); } //-------------------------------------------------------------- void ftFluidFlow::update(float _deltaTime){ float timeStep = _deltaTime * speed.get() * 100; ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftPingPongFbo& velocityFbo = inputFbo; ftPingPongFbo& densityFbo = outputFbo; // ADVECT & DISSEPATE float vDis = 1.0 - _deltaTime * dissipationVel.get(); velocityFbo.swap(); advectShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), velocityFbo.getBackTexture(), obstacleFbo.getTexture(), timeStep, gridScale, vDis); float dDis = 1.0 - _deltaTime * dissipationDen.get(); densityFbo.swap(); advectShader.update(densityFbo.get(), densityFbo.getBackTexture(), velocityFbo.getTexture(), obstacleFbo.getTexture(), timeStep, gridScale, dDis); float tDis = 1.0 - _deltaTime * dissipationTmp.get(); temperatureFbo.swap(); advectShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), velocityFbo.getTexture(), obstacleFbo.getTexture(), timeStep, gridScale, tDis); float pDis = 1.0 - dissipationPrs.get(); pressureFbo.swap(); multiplyForceShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), pDis); // DIFFUSE if (viscosityVel.get() > 0.0) { float vDif = timeStep * viscosityVel.get(); for (int i = 0; i < numJacobiIterationsDiffuse; i++) { velocityFbo.swap(); jacobiDiffusionShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), vDif, gridScale); } } if (viscosityDen.get() > 0.0) { float dDif = timeStep * viscosityDen.get(); for (int i = 0; i < numJacobiIterationsDiffuse; i++) { densityFbo.swap(); jacobiDiffusionShader.update(densityFbo.get(), densityFbo.getBackTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), dDif, gridScale); } } if (viscosityTmp.get() > 0.0) { float tDif = timeStep * viscosityTmp.get(); for (int i = 0; i < numJacobiIterationsDiffuse; i++) { temperatureFbo.swap(); jacobiDiffusionShader.update(temperatureFbo.get(), temperatureFbo.getBackTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), tDif, gridScale); } } // VORTEX CONFINEMENT if (vorticity.get() > 0.0) { vorticityCurlShader.update(vorticityCurlFbo, velocityFbo.getTexture(), obstacleFbo.getTexture(), gridScale); vorticityForceShader.update(vorticityForceFbo, vorticityCurlFbo.getTexture(), timeStep, gridScale, vorticity.get()); addVelocity(vorticityForceFbo.getTexture()); } // BUOYANCY if (buoyancySigma.get() > 0.0 && buoyancyWeight.get() > 0.0 ) { buoyancyShader.update(buoyancyFbo, velocityFbo.getTexture(), temperatureFbo.getTexture(), densityFbo.getTexture(), timeStep, buoyancyAmbientTemperature, buoyancySigma.get(), buoyancyWeight.get()); addVelocity(buoyancyFbo.getTexture()); } // PRESSURE: DIVERGENCE divergenceShader.update(divergenceFbo, velocityFbo.getTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), gridScale); // PRESSURE: JACOBI for (int i = 0; i < numJacobiIterationsProjection; i++) { pressureFbo.swap(); jacobiPressureShader.update(pressureFbo.get(), pressureFbo.getBackTexture(), divergenceFbo.getTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), gridScale); } // PRESSURE: GRADIENT velocityFbo.swap(); gradientShader.update(velocityFbo.get(), velocityFbo.getBackTexture(), pressureFbo.getTexture(), obstacleFbo.getTexture(), obstacleOffsetFbo.getTexture(), gridScale); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::setFlow(flowTools::ftFlowForceType _type, ofTexture &_tex) { switch (_type) { case FT_VELOCITY: setVelocity(_tex); break; case FT_DENSITY: setDensity(_tex); break; case FT_TEMPERATURE: setTemperature(_tex); break; case FT_PRESSURE: setPressure(_tex); break; case FT_OBSTACLE: setObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::addFlow(flowTools::ftFlowForceType _type, ofTexture &_tex, float _strength) { switch (_type) { case FT_VELOCITY: addVelocity(_tex, _strength); break; case FT_DENSITY: addDensity(_tex, _strength); break; case FT_TEMPERATURE: addTemperature(_tex, _strength); break; case FT_PRESSURE: addPressure(_tex, _strength); break; case FT_OBSTACLE: addObstacle(_tex); break; default: ofLogWarning("ftFluidFlow: addFlow") << "no method to add flow of type " << _type; break; } } //-------------------------------------------------------------- void ftFluidFlow::initObstacle(){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); ftUtil::one(obstacleFbo); obstacleFbo.begin(); ofSetColor(0,0,0,255); int borderSize = 1; ofDrawRectangle(borderSize, borderSize, obstacleFbo.getWidth()-borderSize*2, obstacleFbo.getHeight()-borderSize*2); obstacleFbo.end(); ofPopStyle(); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); } //-------------------------------------------------------------- void ftFluidFlow::setObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); initObstacle(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::addObstacle(ofTexture & _tex){ ofPushStyle(); ofEnableBlendMode(OF_BLENDMODE_DISABLED); obstacleFbo.swap(); addBooleanShader.update(obstacleFbo.get(), obstacleFbo.getBackTexture(), _tex); obstacleOffsetShader.update(obstacleOffsetFbo, obstacleFbo.getTexture()); ofPopStyle(); } //-------------------------------------------------------------- void ftFluidFlow::reset() { ftFlow::reset(); ftUtil::zero(pressureFbo); ftUtil::zero(temperatureFbo); ftUtil::zero(divergenceFbo); ftUtil::zero(vorticityCurlFbo); ftUtil::zero(buoyancyFbo); initObstacle(); } } <|endoftext|>
<commit_before>/* RLTK (RogueLike Tool Kit) 1.00 * Copyright (c) 2016-Present, Bracket Productions. * Licensed under the LGPL - see LICENSE file. * * Example 7: Advanced GUI with retained-mode GUI elements and an owner-draw background. */ // You need to include the RLTK header #include "../../rltk/rltk.hpp" #include <sstream> #include <iomanip> // For convenience, import the whole rltk namespace. You may not want to do this // in larger projects, to avoid naming collisions. using namespace rltk; using namespace rltk::colors; constexpr int BACKDROP_LAYER = 1; void resize_bg(layer_t * l, int w, int h) { // Use the whole window l->w = w; l->h = h; } void draw_bg(layer_t * l, sf::RenderWindow &window) { sf::Texture * bg = get_texture("backdrop"); sf::Sprite backdrop(*bg); window.draw(backdrop); } // Tick is called every frame. The parameter specifies how many ms have elapsed // since the last time it was called. void tick(double duration_ms) { } // Your main function int main() { // This time, we're using a full initialization: width, height, window title, and "false" meaning we don't // want an automatically generated root console. This is necessary when you want to use the complex layout // functions. init(config_advanced("../assets")); // We're going to be using a bitmap, so we need to load it. The library makes this easy: register_texture("../assets/background_image.png", "backdrop"); // Now we add an owner-draw background layer. "Owner-draw" means that it the library will ask it to // draw itself with a call-back function. gui->add_owner_layer(BACKDROP_LAYER, 0, 0, 1024, 768, resize_bg, draw_bg); // Main loop - calls the 'tick' function you defined for each frame. run(tick); return 0; } <commit_msg>Its not retained controls yet, but it looks nice - console window over backdrop.<commit_after>/* RLTK (RogueLike Tool Kit) 1.00 * Copyright (c) 2016-Present, Bracket Productions. * Licensed under the LGPL - see LICENSE file. * * Example 7: Advanced GUI with retained-mode GUI elements and an owner-draw background. */ // You need to include the RLTK header #include "../../rltk/rltk.hpp" #include <sstream> #include <iomanip> // For convenience, import the whole rltk namespace. You may not want to do this // in larger projects, to avoid naming collisions. using namespace rltk; using namespace rltk::colors; constexpr int BACKDROP_LAYER = 1; constexpr int LOG_LAYER = 2; void resize_bg(layer_t * l, int w, int h) { // Use the whole window l->w = w; l->h = h; } void draw_bg(layer_t * l, sf::RenderWindow &window) { sf::Texture * bg = get_texture("backdrop"); sf::Sprite backdrop(*bg); window.draw(backdrop); } void resize_log(layer_t * l, int w, int h) { // Simply set the width to the whole window width, and the whole window minus 16 pixels (for the heading) l->w = w - 160; l->h = h - 32; // If the log window would take up the whole screen, hide it if (l->w < 0) { l->console->visible = false; } else { l->console->visible = true; } l->x = w - 160; } // Tick is called every frame. The parameter specifies how many ms have elapsed // since the last time it was called. void tick(double duration_ms) { term(LOG_LAYER)->clear(vchar{' ', WHITE, DARKEST_GREEN}); term(LOG_LAYER)->box(DARKEST_GREEN, BLACK); term(LOG_LAYER)->print(1,1, "Log Entry", LIGHT_GREEN, DARKEST_GREEN); term(LOG_LAYER)->print(1,2, "More text!", LIGHT_GREEN, DARKEST_GREEN); term(LOG_LAYER)->print(1,3, "Even more...", LIGHT_GREEN, DARKEST_GREEN); term(LOG_LAYER)->print(1,4, "... goes here", LIGHT_GREEN, DARKEST_GREEN); std::stringstream ss; ss << std::setiosflags(std::ios::fixed) << std::setprecision(0) << (1000.0/duration_ms) << " FPS"; term(LOG_LAYER)->print(1,6, ss.str(), WHITE, DARKEST_GREEN); } // Your main function int main() { // This time, we're using a full initialization: width, height, window title, and "false" meaning we don't // want an automatically generated root console. This is necessary when you want to use the complex layout // functions. init(config_advanced("../assets")); // We're going to be using a bitmap, so we need to load it. The library makes this easy: register_texture("../assets/background_image.png", "backdrop"); // Now we add an owner-draw background layer. "Owner-draw" means that it the library will ask it to // draw itself with a call-back function. gui->add_owner_layer(BACKDROP_LAYER, 0, 0, 1024, 768, resize_bg, draw_bg); gui->add_layer(LOG_LAYER, 864, 32, 160, 768-32, "8x16", resize_log); term(LOG_LAYER)->set_alpha(196); // Make the overlay translucent // Main loop - calls the 'tick' function you defined for each frame. run(tick); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2011 Chris Pickel <[email protected]> // // This file is part of librezin, a free software project. You can redistribute it and/or modify // it under the terms of the MIT License. #include <rezin/pict.hpp> #include <stdint.h> #include <vector> #include <rezin/clut.hpp> #include <rezin/image.hpp> #include <rezin/primitives.hpp> using sfz::BytesSlice; using sfz::Exception; using sfz::ReadSource; using sfz::WriteTarget; using sfz::format; using sfz::hex; using sfz::range; using sfz::read; using sfz::scoped_ptr; using std::vector; namespace rezin { struct Picture::Rep { Rect bounds; scoped_ptr<RasterImage> image; }; namespace { struct PackBitsRectOp { PixMap pix_map; ColorTable clut; Rect src_rect; Rect dst_rect; int16_t mode; scoped_ptr<RasterImage> image; void draw(Picture::Rep& rep) { RectImage mask(dst_rect, AlphaColor(0, 0, 0)); TranslatedImage src(*image, dst_rect.left - src_rect.left, dst_rect.top - src_rect.top); rep.image->src(src, mask); } }; void read_from(ReadSource in, PackBitsRectOp& op) { read(in, op.pix_map); read(in, op.clut); read(in, op.src_rect); read(in, op.dst_rect); read(in, op.mode); if (op.mode != 0) { throw Exception("only source compositing is supported"); } op.pix_map.read_packed_image(in, op.clut, op.image); } struct DirectBitsRectOp { AddressedPixMap pix_map; Rect src_rect; Rect dst_rect; int16_t mode; scoped_ptr<RasterImage> image; void draw(Picture::Rep& rep) { RectImage mask(dst_rect, AlphaColor(0, 0, 0)); TranslatedImage src(*image, dst_rect.left - src_rect.left, dst_rect.top - src_rect.top); rep.image->src(src, mask); } }; void read_from(ReadSource in, DirectBitsRectOp& op) { read(in, op.pix_map); read(in, op.src_rect); read(in, op.dst_rect); read(in, op.mode); if (op.mode != 0) { throw Exception("only source compositing is supported"); } op.pix_map.read_direct_image(in, op.image); } struct Header { Rect bounds; }; enum { HEADER_VERSION_2 = 0xffff, HEADER_VERSION_2_EXTENDED = 0xfffe, }; void read_from(ReadSource in, Header& header) { uint16_t version = read<uint16_t>(in); if (version == HEADER_VERSION_2) { in.shift(2); // reserved header.bounds.left = read<uint32_t>(in) / 65536; header.bounds.top = read<uint32_t>(in) / 65536; header.bounds.right = read<uint32_t>(in) / 65536; header.bounds.bottom = read<uint32_t>(in) / 65536; in.shift(4); // reserved } else if (version == HEADER_VERSION_2_EXTENDED) { in.shift(2); // reserved if (read<uint32_t>(in) != 0x00480000) { throw Exception("horizontal resolution != 72 dpi"); } if (read<uint32_t>(in) != 0x00480000) { throw Exception("vertical resolution != 72 dpi"); } read(in, header.bounds); in.shift(2); // reserved } else { throw Exception("only version 2 'PICT' resources are supported"); } } enum { NOOP_V2 = 0x0000, CLIP_V2 = 0x0001, DEFAULT_HILITE_V2 = 0x001e, PACK_BITS_RECT_V2 = 0x0098, DIRECT_BITS_RECT_V2 = 0x009a, LONG_COMMENT_V2 = 0x00a1, HEADER_OP_V2 = 0x0c00, END_V2 = 0x00ff, }; void read_version_2_pict(ReadSource in, Picture& pict) { if (read<uint16_t>(in) != HEADER_OP_V2) { throw Exception("expected header of version 2 'PICT' resource"); } Header header = {pict.rep->bounds}; read(in, header); if (pict.rep->bounds != header.bounds) { throw Exception("PICT resource must fill bounds"); } while (true) { const uint16_t op = read<uint16_t>(in); switch (op) { case NOOP_V2: case DEFAULT_HILITE_V2: { break; } case CLIP_V2: { if (read<uint16_t>(in) != 0x000a) { throw Exception("only rectangular clip regions are supported"); } if (read<Rect>(in) != pict.rep->bounds) { throw Exception("PICT clip must fill bounds"); } break; } case PACK_BITS_RECT_V2: { PackBitsRectOp op; read(in, op); op.draw(*pict.rep); break; } case DIRECT_BITS_RECT_V2: { DirectBitsRectOp op; read(in, op); op.draw(*pict.rep); break; } case LONG_COMMENT_V2: { in.shift(2); in.shift(read<uint16_t>(in)); break; } case END_V2: { goto end_pict_v2; } default: { throw Exception(format("unsupported op ${0} in 'PICT' resource", hex(op, 4))); } } } end_pict_v2: ; } enum { NOOP_V1 = 0x00, PIC_VERSION_V1 = 0x11, }; void read_version_1_pict(ReadSource in, Picture& pict) { while (!in.empty()) { const uint8_t op = read<uint8_t>(in); switch (op) { case NOOP_V1: { break; } case PIC_VERSION_V1: { if (read<uint8_t>(in) != 0x02) { throw Exception("only version 2 'PICT' resources are supported"); } if (read<uint8_t>(in) != 0xff) { throw Exception("expected end of version 1 'PICT' resource"); } read_version_2_pict(in, pict); break; } default: { throw Exception(format("unsupported op ${0} in 'PICT' resource", hex(op, 2))); } } } } } // namespace Picture::Picture(BytesSlice in): rep(new Rep) { in.shift(2); // Ignore size of 'PICT' resource. read(in, rep->bounds); rep->image.reset(new RasterImage(rep->bounds)); read_version_1_pict(in, *this); } Picture::~Picture() { } PngPicture png(const Picture& pict) { PngPicture result = {pict}; return result; } void write_to(WriteTarget out, PngPicture png_pict) { const Picture::Rep& rep = *png_pict.pict.rep; write(out, png(*rep.image)); } } // namespace rezin <commit_msg>Support ShortComment ops.<commit_after>// Copyright (c) 2011 Chris Pickel <[email protected]> // // This file is part of librezin, a free software project. You can redistribute it and/or modify // it under the terms of the MIT License. #include <rezin/pict.hpp> #include <stdint.h> #include <vector> #include <rezin/clut.hpp> #include <rezin/image.hpp> #include <rezin/primitives.hpp> using sfz::BytesSlice; using sfz::Exception; using sfz::ReadSource; using sfz::WriteTarget; using sfz::format; using sfz::hex; using sfz::range; using sfz::read; using sfz::scoped_ptr; using std::vector; namespace rezin { struct Picture::Rep { Rect bounds; scoped_ptr<RasterImage> image; }; namespace { struct PackBitsRectOp { PixMap pix_map; ColorTable clut; Rect src_rect; Rect dst_rect; int16_t mode; scoped_ptr<RasterImage> image; void draw(Picture::Rep& rep) { RectImage mask(dst_rect, AlphaColor(0, 0, 0)); TranslatedImage src(*image, dst_rect.left - src_rect.left, dst_rect.top - src_rect.top); rep.image->src(src, mask); } }; void read_from(ReadSource in, PackBitsRectOp& op) { read(in, op.pix_map); read(in, op.clut); read(in, op.src_rect); read(in, op.dst_rect); read(in, op.mode); if (op.mode != 0) { throw Exception("only source compositing is supported"); } op.pix_map.read_packed_image(in, op.clut, op.image); } struct DirectBitsRectOp { AddressedPixMap pix_map; Rect src_rect; Rect dst_rect; int16_t mode; scoped_ptr<RasterImage> image; void draw(Picture::Rep& rep) { RectImage mask(dst_rect, AlphaColor(0, 0, 0)); TranslatedImage src(*image, dst_rect.left - src_rect.left, dst_rect.top - src_rect.top); rep.image->src(src, mask); } }; void read_from(ReadSource in, DirectBitsRectOp& op) { read(in, op.pix_map); read(in, op.src_rect); read(in, op.dst_rect); read(in, op.mode); if (op.mode != 0) { throw Exception("only source compositing is supported"); } op.pix_map.read_direct_image(in, op.image); } struct Header { Rect bounds; }; enum { HEADER_VERSION_2 = 0xffff, HEADER_VERSION_2_EXTENDED = 0xfffe, }; void read_from(ReadSource in, Header& header) { uint16_t version = read<uint16_t>(in); if (version == HEADER_VERSION_2) { in.shift(2); // reserved header.bounds.left = read<uint32_t>(in) / 65536; header.bounds.top = read<uint32_t>(in) / 65536; header.bounds.right = read<uint32_t>(in) / 65536; header.bounds.bottom = read<uint32_t>(in) / 65536; in.shift(4); // reserved } else if (version == HEADER_VERSION_2_EXTENDED) { in.shift(2); // reserved if (read<uint32_t>(in) != 0x00480000) { throw Exception("horizontal resolution != 72 dpi"); } if (read<uint32_t>(in) != 0x00480000) { throw Exception("vertical resolution != 72 dpi"); } read(in, header.bounds); in.shift(2); // reserved } else { throw Exception("only version 2 'PICT' resources are supported"); } } enum { NOOP_V2 = 0x0000, CLIP_V2 = 0x0001, DEFAULT_HILITE_V2 = 0x001e, PACK_BITS_RECT_V2 = 0x0098, DIRECT_BITS_RECT_V2 = 0x009a, SHORT_COMMENT_V2 = 0x00a0, LONG_COMMENT_V2 = 0x00a1, HEADER_OP_V2 = 0x0c00, END_V2 = 0x00ff, }; void read_version_2_pict(ReadSource in, Picture& pict) { if (read<uint16_t>(in) != HEADER_OP_V2) { throw Exception("expected header of version 2 'PICT' resource"); } Header header = {pict.rep->bounds}; read(in, header); if (pict.rep->bounds != header.bounds) { throw Exception("PICT resource must fill bounds"); } while (true) { const uint16_t op = read<uint16_t>(in); switch (op) { case NOOP_V2: case DEFAULT_HILITE_V2: { break; } case CLIP_V2: { if (read<uint16_t>(in) != 0x000a) { throw Exception("only rectangular clip regions are supported"); } if (read<Rect>(in) != pict.rep->bounds) { throw Exception("PICT clip must fill bounds"); } break; } case PACK_BITS_RECT_V2: { PackBitsRectOp op; read(in, op); op.draw(*pict.rep); break; } case DIRECT_BITS_RECT_V2: { DirectBitsRectOp op; read(in, op); op.draw(*pict.rep); break; } case SHORT_COMMENT_V2: { in.shift(2); break; } case LONG_COMMENT_V2: { in.shift(2); in.shift(read<uint16_t>(in)); break; } case END_V2: { goto end_pict_v2; } default: { throw Exception(format("unsupported op ${0} in 'PICT' resource", hex(op, 4))); } } } end_pict_v2: ; } enum { NOOP_V1 = 0x00, PIC_VERSION_V1 = 0x11, }; void read_version_1_pict(ReadSource in, Picture& pict) { while (!in.empty()) { const uint8_t op = read<uint8_t>(in); switch (op) { case NOOP_V1: { break; } case PIC_VERSION_V1: { if (read<uint8_t>(in) != 0x02) { throw Exception("only version 2 'PICT' resources are supported"); } if (read<uint8_t>(in) != 0xff) { throw Exception("expected end of version 1 'PICT' resource"); } read_version_2_pict(in, pict); break; } default: { throw Exception(format("unsupported op ${0} in 'PICT' resource", hex(op, 2))); } } } } } // namespace Picture::Picture(BytesSlice in): rep(new Rep) { in.shift(2); // Ignore size of 'PICT' resource. read(in, rep->bounds); rep->image.reset(new RasterImage(rep->bounds)); read_version_1_pict(in, *this); } Picture::~Picture() { } PngPicture png(const Picture& pict) { PngPicture result = {pict}; return result; } void write_to(WriteTarget out, PngPicture png_pict) { const Picture::Rep& rep = *png_pict.pict.rep; write(out, png(*rep.image)); } } // namespace rezin <|endoftext|>
<commit_before>// // Bareflank Hypervisor // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <[email protected]> // Author: Brendan Kerrigan <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <gsl/gsl> #include <debug.h> extern "C" bool __attribute__((weak)) __vmxon(void *ptr) { (void) ptr; bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called" << bfendl; abort(); } extern "C" bool __attribute__((weak)) __vmxoff(void) noexcept { bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called" << bfendl; abort(); } extern "C" bool __attribute__((weak)) __vmclear(void *ptr) noexcept { (void) ptr; bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called" << bfendl; abort(); } extern "C" bool __attribute__((weak)) __vmptrld(void *ptr) noexcept { (void) ptr; bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called" << bfendl; abort(); } extern "C" bool __attribute__((weak)) __vmptrst(void *ptr) noexcept { (void) ptr; bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called" << bfendl; abort(); } extern "C" bool __attribute__((weak)) __vmwrite(uint64_t field, uint64_t value) noexcept { bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called with: " << bfendl; bferror << " - field: " << view_as_pointer(field) << '\n'; bferror << " - value: " << view_as_pointer(value) << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmread(uint64_t field, uint64_t *value) noexcept { (void) value; bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called with: " << bfendl; bferror << " - field: " << view_as_pointer(field) << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmlaunch(void) noexcept { bferror << static_cast<const char *>(__PRETTY_FUNCTION__) << " called" << bfendl; abort(); } <commit_msg>Remvoe __PRETTY_FUNCTION__ (#286)<commit_after>// // Bareflank Hypervisor // // Copyright (C) 2015 Assured Information Security, Inc. // Author: Rian Quinn <[email protected]> // Author: Brendan Kerrigan <[email protected]> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <gsl/gsl> #include <debug.h> extern "C" bool __attribute__((weak)) __vmxon(void *ptr) { (void) ptr; std::cerr << __FUNC__ << " called" << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmxoff(void) noexcept { std::cerr << __FUNC__ << " called" << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmclear(void *ptr) noexcept { (void) ptr; std::cerr << __FUNC__ << " called" << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmptrld(void *ptr) noexcept { (void) ptr; std::cerr << __FUNC__ << " called" << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmptrst(void *ptr) noexcept { (void) ptr; std::cerr << __FUNC__ << " called" << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmwrite(uint64_t field, uint64_t value) noexcept { std::cerr << __FUNC__ << " called with: " << '\n'; std::cerr << " - field: " << view_as_pointer(field) << '\n'; std::cerr << " - value: " << view_as_pointer(value) << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmread(uint64_t field, uint64_t *value) noexcept { (void) value; std::cerr << __FUNC__ << " called with: " << '\n'; std::cerr << " - field: " << view_as_pointer(field) << '\n'; abort(); } extern "C" bool __attribute__((weak)) __vmlaunch(void) noexcept { std::cerr << __FUNC__ << " called" << '\n'; abort(); } <|endoftext|>
<commit_before>/* * Copyright 2015 WebAssembly Community Group participants * * 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. */ // // Locals-related optimizations // // This "sinks" set_locals, pushing them to the next get_local where possible, // and removing the set if there are no gets remaining (the latter is // particularly useful in ssa mode, but not only). // // After this pass, some locals may be completely unused. reorder-locals // can get rid of those (the operation is trivial there after it sorts by use // frequency). #include <wasm.h> #include <wasm-traversal.h> #include <pass.h> #include <ast_utils.h> namespace wasm { struct SimplifyLocals : public WalkerPass<LinearExecutionWalker<SimplifyLocals>> { bool isFunctionParallel() { return true; } struct SinkableInfo { Expression** item; EffectAnalyzer effects; SinkableInfo(Expression** item) : item(item) { effects.walk(*item); } }; // locals in current linear execution trace, which we try to sink std::map<Index, SinkableInfo> sinkables; bool sunk; // local => # of get_locals for it std::map<Index, int> numGetLocals; // for each set_local, its origin pointer std::map<SetLocal*, Expression**> setLocalOrigins; void noteNonLinear() { sinkables.clear(); } void visitGetLocal(GetLocal *curr) { auto found = sinkables.find(curr->index); if (found != sinkables.end()) { // sink it, and nop the origin TODO: clean up nops replaceCurrent(*found->second.item); // reuse the getlocal that is dying *found->second.item = curr; ExpressionManipulator::nop(curr); sinkables.erase(found); sunk = true; } else { numGetLocals[curr->index]++; } } void visitSetLocal(SetLocal *curr) { // if we are a potentially-sinkable thing, forget it - this // write overrides the last TODO: optimizable // TODO: if no get_locals left, can remove the set as well (== expressionizer in emscripten optimizer) auto found = sinkables.find(curr->index); if (found != sinkables.end()) { sinkables.erase(found); } } void checkInvalidations(EffectAnalyzer& effects) { // TODO: this is O(bad) std::vector<Index> invalidated; for (auto& sinkable : sinkables) { if (effects.invalidates(sinkable.second.effects)) { invalidated.push_back(sinkable.first); } } for (auto index : invalidated) { sinkables.erase(index); } } static void visitPre(SimplifyLocals* self, Expression** currp) { Expression* curr = *currp; EffectAnalyzer effects; if (effects.checkPre(curr)) { self->checkInvalidations(effects); } } static void visitPost(SimplifyLocals* self, Expression** currp) { Expression* curr = *currp; EffectAnalyzer effects; if (effects.checkPost(curr)) { self->checkInvalidations(effects); } // noting origins in the post means it happens after a // get_local was replaced by a set_local in a sinking // operation, so we track those movements properly. if (curr->is<SetLocal>()) { self->setLocalOrigins[curr->cast<SetLocal>()] = currp; } } static void tryMarkSinkable(SimplifyLocals* self, Expression** currp) { auto* curr = (*currp)->dynCast<SetLocal>(); if (curr) { Index index = curr->index; assert(self->sinkables.count(index) == 0); self->sinkables.emplace(std::make_pair(index, SinkableInfo(currp))); } } // override scan to add a pre and a post check task to all nodes static void scan(SimplifyLocals* self, Expression** currp) { self->pushTask(visitPost, currp); auto* curr = *currp; if (curr->is<Block>()) { // special-case blocks, by marking their children as locals. // TODO sink from elsewhere? (need to make sure value is not used) self->pushTask(SimplifyLocals::doNoteNonLinear, currp); auto& list = curr->cast<Block>()->list; int size = list.size(); // we can't sink the last element, as it might be a return value; // and anyhow, control flow is nonlinear at the end of the block so // it would be invalidated. for (int i = size - 1; i >= 0; i--) { if (i < size - 1) { self->pushTask(tryMarkSinkable, &list[i]); } self->pushTask(scan, &list[i]); } } else { WalkerPass<LinearExecutionWalker<SimplifyLocals>>::scan(self, currp); } self->pushTask(visitPre, currp); } void walk(Expression*& root) { // multiple passes may be required per function, consider this: // x = load // y = store // c(x, y) // the load cannot cross the store, but y can be sunk, after which so can x do { sunk = false; // main operation WalkerPass<LinearExecutionWalker<SimplifyLocals>>::walk(root); // after optimizing a function, we can see if we have set_locals // for a local with no remaining gets, in which case, we can // remove the set. std::vector<SetLocal*> optimizables; for (auto pair : setLocalOrigins) { SetLocal* curr = pair.first; if (numGetLocals[curr->index] == 0) { // no gets, can remove the set and leave just the value optimizables.push_back(curr); } } for (auto* curr : optimizables) { Expression** origin = setLocalOrigins[curr]; *origin = curr->value; // nested set_values need to be handled properly. // consider (set_local x (set_local y (..)), where both can be // reduced to their values, and we might do it in either // order. if (curr->value->is<SetLocal>()) { setLocalOrigins[curr->value->cast<SetLocal>()] = origin; } } // clean up numGetLocals.clear(); setLocalOrigins.clear(); sinkables.clear(); } while (sunk); } }; static RegisterPass<SimplifyLocals> registerPass("simplify-locals", "miscellaneous locals-related optimizations"); } // namespace wasm <commit_msg>use a vector for get_local counts in SimplifyLocals (#356)<commit_after>/* * Copyright 2015 WebAssembly Community Group participants * * 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. */ // // Locals-related optimizations // // This "sinks" set_locals, pushing them to the next get_local where possible, // and removing the set if there are no gets remaining (the latter is // particularly useful in ssa mode, but not only). // // After this pass, some locals may be completely unused. reorder-locals // can get rid of those (the operation is trivial there after it sorts by use // frequency). #include <wasm.h> #include <wasm-traversal.h> #include <pass.h> #include <ast_utils.h> namespace wasm { struct SimplifyLocals : public WalkerPass<LinearExecutionWalker<SimplifyLocals>> { bool isFunctionParallel() { return true; } struct SinkableInfo { Expression** item; EffectAnalyzer effects; SinkableInfo(Expression** item) : item(item) { effects.walk(*item); } }; // locals in current linear execution trace, which we try to sink std::map<Index, SinkableInfo> sinkables; bool sunk; // local => # of get_locals for it std::vector<int> numGetLocals; // for each set_local, its origin pointer std::map<SetLocal*, Expression**> setLocalOrigins; void noteNonLinear() { sinkables.clear(); } void visitGetLocal(GetLocal *curr) { auto found = sinkables.find(curr->index); if (found != sinkables.end()) { // sink it, and nop the origin TODO: clean up nops replaceCurrent(*found->second.item); // reuse the getlocal that is dying *found->second.item = curr; ExpressionManipulator::nop(curr); sinkables.erase(found); sunk = true; } else { numGetLocals[curr->index]++; } } void visitSetLocal(SetLocal *curr) { // if we are a potentially-sinkable thing, forget it - this // write overrides the last TODO: optimizable // TODO: if no get_locals left, can remove the set as well (== expressionizer in emscripten optimizer) auto found = sinkables.find(curr->index); if (found != sinkables.end()) { sinkables.erase(found); } } void checkInvalidations(EffectAnalyzer& effects) { // TODO: this is O(bad) std::vector<Index> invalidated; for (auto& sinkable : sinkables) { if (effects.invalidates(sinkable.second.effects)) { invalidated.push_back(sinkable.first); } } for (auto index : invalidated) { sinkables.erase(index); } } static void visitPre(SimplifyLocals* self, Expression** currp) { Expression* curr = *currp; EffectAnalyzer effects; if (effects.checkPre(curr)) { self->checkInvalidations(effects); } } static void visitPost(SimplifyLocals* self, Expression** currp) { Expression* curr = *currp; EffectAnalyzer effects; if (effects.checkPost(curr)) { self->checkInvalidations(effects); } // noting origins in the post means it happens after a // get_local was replaced by a set_local in a sinking // operation, so we track those movements properly. if (curr->is<SetLocal>()) { self->setLocalOrigins[curr->cast<SetLocal>()] = currp; } } static void tryMarkSinkable(SimplifyLocals* self, Expression** currp) { auto* curr = (*currp)->dynCast<SetLocal>(); if (curr) { Index index = curr->index; assert(self->sinkables.count(index) == 0); self->sinkables.emplace(std::make_pair(index, SinkableInfo(currp))); } } // override scan to add a pre and a post check task to all nodes static void scan(SimplifyLocals* self, Expression** currp) { self->pushTask(visitPost, currp); auto* curr = *currp; if (curr->is<Block>()) { // special-case blocks, by marking their children as locals. // TODO sink from elsewhere? (need to make sure value is not used) self->pushTask(SimplifyLocals::doNoteNonLinear, currp); auto& list = curr->cast<Block>()->list; int size = list.size(); // we can't sink the last element, as it might be a return value; // and anyhow, control flow is nonlinear at the end of the block so // it would be invalidated. for (int i = size - 1; i >= 0; i--) { if (i < size - 1) { self->pushTask(tryMarkSinkable, &list[i]); } self->pushTask(scan, &list[i]); } } else { WalkerPass<LinearExecutionWalker<SimplifyLocals>>::scan(self, currp); } self->pushTask(visitPre, currp); } void walk(Expression*& root) { // multiple passes may be required per function, consider this: // x = load // y = store // c(x, y) // the load cannot cross the store, but y can be sunk, after which so can x do { numGetLocals.resize(getFunction()->getNumLocals()); sunk = false; // main operation WalkerPass<LinearExecutionWalker<SimplifyLocals>>::walk(root); // after optimizing a function, we can see if we have set_locals // for a local with no remaining gets, in which case, we can // remove the set. std::vector<SetLocal*> optimizables; for (auto pair : setLocalOrigins) { SetLocal* curr = pair.first; if (numGetLocals[curr->index] == 0) { // no gets, can remove the set and leave just the value optimizables.push_back(curr); } } for (auto* curr : optimizables) { Expression** origin = setLocalOrigins[curr]; *origin = curr->value; // nested set_values need to be handled properly. // consider (set_local x (set_local y (..)), where both can be // reduced to their values, and we might do it in either // order. if (curr->value->is<SetLocal>()) { setLocalOrigins[curr->value->cast<SetLocal>()] = origin; } } // clean up numGetLocals.clear(); setLocalOrigins.clear(); sinkables.clear(); } while (sunk); } }; static RegisterPass<SimplifyLocals> registerPass("simplify-locals", "miscellaneous locals-related optimizations"); } // namespace wasm <|endoftext|>
<commit_before>/* * XCFun, an arbitrary order exchange-correlation library * Copyright (C) 2018 Ulf Ekström and contributors. * * This file is part of XCFun. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * For information on the complete list of contributors to the * XCFun library, see: <https://xcfun.readthedocs.io/> */ #include <cmath> #include <cstdlib> #include <iostream> #include <XCFun/xcfun.h> // This example contains calls to C++ interface routines that are needed to // "talk to" the xcfun library and demonstrates how to use them. // We will compute the kernel for an unpolarized system using total density and // the gradient components as the variables. These are linear in the density // matrix, which helps the code using the results from xcfun. // we consider only one grid point const int num_grid_points = 1; // we will use XC_N_NX_NY_NZ // N: density // NX: x-gradient of the density // NY: y-gradient of the density // NZ: z-gradient of the density const int num_density_variables = 4; // forward declare function double derivative(xcfun_t * fun, int vector_length, double density[][num_density_variables][num_grid_points]); int main(int, char **) { // print some info and copyright about the library // please always include this info in your code std::cout << xcfun_splash() << std::endl; // create a new functional // we need this for interacting with the library auto fun = xcfun_new(); { // in this example we use PBE std::cout << "Setting up PBE" << std::endl; auto ierr = xcfun_set(fun, "pbe", 1.0); if (ierr) std::cout << "functional name not recognized" << std::endl; } //---------------------------------------------------------------------------- // in the first example we compute the XC energy ("order 0 derivative") { const auto order = 0; // XC_CONTRACTED here has nothing to do with contracted basis sets // it means we will evaluated in the XC_CONTRACTED mode and internally // contract functional derivatives with the density taylor expansion // in other words: we will not have to explicitly assemble/contract partial // derivatives outside of XCFun auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; auto vector_length = 1 << order; // bit shift to get power of two: 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // n density[0][1][i] = 2.0; // nabla_x n density[0][2][i] = 3.0; // nabla_y n density[0][3][i] = 4.0; // nabla_z n } auto res = derivative(fun, vector_length, density); std::cout << "The XC energy density is " << res << std::endl; // compare with reference auto diff = std::abs(-0.86494159400066051 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we will compute the first derivatives ('potential') // and contract them with the first order densities { const auto order = 1; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; auto vector_length = 1 << order; // bit shift to get power of two: 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // n zeroth order density[0][1][i] = 2.0; // nabla_x n zeroth order density[0][2][i] = 3.0; // nabla_y n zeroth order density[0][3][i] = 4.0; // nabla_z n zeroth order density[1][0][i] = 5.0; // n first order density[1][1][i] = 6.0; // nabla_x n first order density[1][2][i] = 7.0; // nabla_y n first order density[1][3][i] = 8.0; // nabla_z n first order } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(-5.1509916226154067 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we will compute a particular partial derivative // within order = 1 // we do this with a trick: we set the perturbed density for // the density variable of interest to 1, and set other perturbed // densities to 0 { const auto order = 1; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; const auto vector_length = 1 << order; // bit shift to get 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // n zeroth order density[0][1][i] = 2.0; // nabla_x n zeroth order density[0][2][i] = 3.0; // nabla_y n zeroth order density[0][3][i] = 4.0; // nabla_z n zeroth order density[1][0][i] = 0.0; density[1][1][i] = 0.0; density[1][2][i] = 1.0; // we differentiate wrt this variable density[1][3][i] = 0.0; } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(-0.013470456737102541 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we try 2nd order { const auto order = 2; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; const auto vector_length = 1 << order; // bit shift to get 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // zeroth order density[0][1][i] = 2.0; // zeroth order density[0][2][i] = 3.0; // zeroth order density[0][3][i] = 4.0; // zeroth order density[1][0][i] = 5.0; // first order density[1][1][i] = 6.0; // first order density[1][2][i] = 7.0; // first order density[1][3][i] = 8.0; // first order density[2][0][i] = 5.0; // first order density[2][1][i] = 6.0; // first order density[2][2][i] = 7.0; // first order density[2][3][i] = 8.0; // first order density[3][0][i] = 0.0; // second order density[3][1][i] = 0.0; // second order density[3][2][i] = 0.0; // second order density[3][3][i] = 0.0; // second order } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(-9.4927931153398468 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we try 3nd order, contracted with perturbed densities { const auto order = 3; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; auto vector_length = 1 << order; // bit shift to get power of two: 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // zeroth order density[0][1][i] = 2.0; // zeroth order density[0][2][i] = 3.0; // zeroth order density[0][3][i] = 4.0; // zeroth order density[1][0][i] = 5.0; // first order (1) density[1][1][i] = 6.0; // first order (1) density[1][2][i] = 7.0; // first order (1) density[1][3][i] = 8.0; // first order (1) density[2][0][i] = 9.0; // first order (2) density[2][1][i] = 10.0; // first order (2) density[2][2][i] = 11.0; // first order (2) density[2][3][i] = 12.0; // first order (2) density[3][0][i] = 5.0; // second order (depending on (1) and (2)) density[3][1][i] = 6.0; // second order (depending on (1) and (2)) density[3][2][i] = 7.0; // second order (depending on (1) and (2)) density[3][3][i] = 8.0; // second order (depending on (1) and (2)) density[4][0][i] = 9.0; // first order (3) density[4][1][i] = 10.0; // first order (3) density[4][2][i] = 11.0; // first order (3) density[4][3][i] = 12.0; // first order (3) density[5][0][i] = 5.0; // second order (depending on (1) and (3)) density[5][1][i] = 6.0; // second order (depending on (1) and (3)) density[5][2][i] = 7.0; // second order (depending on (1) and (3)) density[5][3][i] = 8.0; // second order (depending on (1) and (3)) density[6][0][i] = 9.0; // second order (depending on (2) and (3)) density[6][1][i] = 10.0; // second order (depending on (2) and (3)) density[6][2][i] = 11.0; // second order (depending on (2) and (3)) density[6][3][i] = 12.0; // second order (depending on (2) and (3)) density[7][0][i] = 0.0; // third order (depending on (1), (2) and (3)) density[7][1][i] = 0.0; // third order (depending on (1), (2) and (3)) density[7][2][i] = 0.0; // third order (depending on (1), (2) and (3)) density[7][3][i] = 0.0; // third order (depending on (1), (2) and (3)) } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(47.091223089835331 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // we are done and can release the memory xcfun_delete(fun); std::cout << "Kernel test has ended properly!" << std::endl; return EXIT_SUCCESS; } // computes the derivative and takes care of offsetting double derivative(xcfun_t * fun, int vector_length, double density[][num_density_variables][num_grid_points]) { double inp_array[vector_length * num_density_variables]; double out_array[num_grid_points][vector_length]; // put the densities into the right places // along the input array for (auto i = 0; i < num_grid_points; i++) { auto n = 0; for (auto j = 0; j < num_density_variables; j++) { for (auto k = 0; k < vector_length; k++) { inp_array[n++] = density[k][j][i]; } } xcfun_eval(fun, inp_array, out_array[i]); } // The output_array holds a Taylor series expansion // and we pick here one particular element out of this array. return out_array[0][vector_length - 1]; } <commit_msg>Fix C++ example<commit_after>/* * XCFun, an arbitrary order exchange-correlation library * Copyright (C) 2018 Ulf Ekström and contributors. * * This file is part of XCFun. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * For information on the complete list of contributors to the * XCFun library, see: <https://xcfun.readthedocs.io/> */ #include <array> #include <cmath> #include <cstdlib> #include <iostream> #include <vector> #include <XCFun/xcfun.h> // This example contains calls to C++ interface routines that are needed to // "talk to" the xcfun library and demonstrates how to use them. // We will compute the kernel for an unpolarized system using total density and // the gradient components as the variables. These are linear in the density // matrix, which helps the code using the results from xcfun. // we consider only one grid point const int num_grid_points = 1; // we will use XC_N_NX_NY_NZ // N: density // NX: x-gradient of the density // NY: y-gradient of the density // NZ: z-gradient of the density const int num_density_variables = 4; // forward declare function double derivative(xcfun_t * fun, int vector_length, double density[][num_density_variables][num_grid_points]); int main(int, char **) { // print some info and copyright about the library // please always include this info in your code std::cout << xcfun_splash() << std::endl; // create a new functional // we need this for interacting with the library auto fun = xcfun_new(); { // in this example we use PBE std::cout << "Setting up PBE" << std::endl; auto ierr = xcfun_set(fun, "pbe", 1.0); if (ierr) std::cout << "functional name not recognized" << std::endl; } //---------------------------------------------------------------------------- // in the first example we compute the XC energy ("order 0 derivative") { constexpr auto order = 0; // XC_CONTRACTED here has nothing to do with contracted basis sets // it means we will evaluated in the XC_CONTRACTED mode and internally // contract functional derivatives with the density taylor expansion // in other words: we will not have to explicitly assemble/contract partial // derivatives outside of XCFun auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; constexpr auto vector_length = 1 << order; // bit shift to get power of two: 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // n density[0][1][i] = 2.0; // nabla_x n density[0][2][i] = 3.0; // nabla_y n density[0][3][i] = 4.0; // nabla_z n } auto res = derivative(fun, vector_length, density); std::cout << "The XC energy density is " << res << std::endl; // compare with reference auto diff = std::abs(-0.86494159400066051 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we will compute the first derivatives ('potential') // and contract them with the first order densities { constexpr auto order = 1; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; constexpr auto vector_length = 1 << order; // bit shift to get power of two: 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // n zeroth order density[0][1][i] = 2.0; // nabla_x n zeroth order density[0][2][i] = 3.0; // nabla_y n zeroth order density[0][3][i] = 4.0; // nabla_z n zeroth order density[1][0][i] = 5.0; // n first order density[1][1][i] = 6.0; // nabla_x n first order density[1][2][i] = 7.0; // nabla_y n first order density[1][3][i] = 8.0; // nabla_z n first order } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(-5.1509916226154067 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we will compute a particular partial derivative // within order = 1 // we do this with a trick: we set the perturbed density for // the density variable of interest to 1, and set other perturbed // densities to 0 { constexpr auto order = 1; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; constexpr auto vector_length = 1 << order; // bit shift to get 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // n zeroth order density[0][1][i] = 2.0; // nabla_x n zeroth order density[0][2][i] = 3.0; // nabla_y n zeroth order density[0][3][i] = 4.0; // nabla_z n zeroth order density[1][0][i] = 0.0; density[1][1][i] = 0.0; density[1][2][i] = 1.0; // we differentiate wrt this variable density[1][3][i] = 0.0; } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(-0.013470456737102541 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we try 2nd order { constexpr auto order = 2; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; constexpr auto vector_length = 1 << order; // bit shift to get 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // zeroth order density[0][1][i] = 2.0; // zeroth order density[0][2][i] = 3.0; // zeroth order density[0][3][i] = 4.0; // zeroth order density[1][0][i] = 5.0; // first order density[1][1][i] = 6.0; // first order density[1][2][i] = 7.0; // first order density[1][3][i] = 8.0; // first order density[2][0][i] = 5.0; // first order density[2][1][i] = 6.0; // first order density[2][2][i] = 7.0; // first order density[2][3][i] = 8.0; // first order density[3][0][i] = 0.0; // second order density[3][1][i] = 0.0; // second order density[3][2][i] = 0.0; // second order density[3][3][i] = 0.0; // second order } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(-9.4927931153398468 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // now we try 3nd order, contracted with perturbed densities { constexpr auto order = 3; auto ierr = xcfun_eval_setup(fun, XC_N_NX_NY_NZ, XC_CONTRACTED, order); if (ierr) std::cout << "xcfun_eval_setup failed" << std::endl; constexpr auto vector_length = 1 << order; // bit shift to get power of two: 2**order double density[vector_length][num_density_variables][num_grid_points]; for (auto i = 0; i < num_grid_points; i++) { // we use fantasy values here density[0][0][i] = 1.0; // zeroth order density[0][1][i] = 2.0; // zeroth order density[0][2][i] = 3.0; // zeroth order density[0][3][i] = 4.0; // zeroth order density[1][0][i] = 5.0; // first order (1) density[1][1][i] = 6.0; // first order (1) density[1][2][i] = 7.0; // first order (1) density[1][3][i] = 8.0; // first order (1) density[2][0][i] = 9.0; // first order (2) density[2][1][i] = 10.0; // first order (2) density[2][2][i] = 11.0; // first order (2) density[2][3][i] = 12.0; // first order (2) density[3][0][i] = 5.0; // second order (depending on (1) and (2)) density[3][1][i] = 6.0; // second order (depending on (1) and (2)) density[3][2][i] = 7.0; // second order (depending on (1) and (2)) density[3][3][i] = 8.0; // second order (depending on (1) and (2)) density[4][0][i] = 9.0; // first order (3) density[4][1][i] = 10.0; // first order (3) density[4][2][i] = 11.0; // first order (3) density[4][3][i] = 12.0; // first order (3) density[5][0][i] = 5.0; // second order (depending on (1) and (3)) density[5][1][i] = 6.0; // second order (depending on (1) and (3)) density[5][2][i] = 7.0; // second order (depending on (1) and (3)) density[5][3][i] = 8.0; // second order (depending on (1) and (3)) density[6][0][i] = 9.0; // second order (depending on (2) and (3)) density[6][1][i] = 10.0; // second order (depending on (2) and (3)) density[6][2][i] = 11.0; // second order (depending on (2) and (3)) density[6][3][i] = 12.0; // second order (depending on (2) and (3)) density[7][0][i] = 0.0; // third order (depending on (1), (2) and (3)) density[7][1][i] = 0.0; // third order (depending on (1), (2) and (3)) density[7][2][i] = 0.0; // third order (depending on (1), (2) and (3)) density[7][3][i] = 0.0; // third order (depending on (1), (2) and (3)) } auto res = derivative(fun, vector_length, density); // compare with reference auto diff = std::abs(47.091223089835331 - res); if (diff > 1.0e-6) std::cout << "derivatives do not match reference numbers" << std::endl; } //---------------------------------------------------------------------------- // we are done and can release the memory xcfun_delete(fun); std::cout << "Kernel test has ended properly!" << std::endl; return EXIT_SUCCESS; } // computes the derivative and takes care of offsetting double derivative(xcfun_t * fun, int vector_length, double density[][num_density_variables][num_grid_points]) { std::vector<double> inp_array(vector_length * num_density_variables, 0.0); std::array<std::vector<double>, num_grid_points> out_array{ std::vector<double>(vector_length, 0.0)}; // put the densities into the right places // along the input array for (auto i = 0; i < num_grid_points; i++) { auto n = 0; for (auto j = 0; j < num_density_variables; j++) { for (auto k = 0; k < vector_length; k++) { inp_array[n++] = density[k][j][i]; } } xcfun_eval(fun, inp_array.data(), out_array[i].data()); } // The output_array holds a Taylor series expansion // and we pick here one particular element out of this array. return out_array[0][vector_length - 1]; } <|endoftext|>
<commit_before>#include <jpl-tags/fiducial_stereo.h> #include <opencv2/opencv.hpp> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/multisense/images_t.hpp> #include <lcmtypes/bot_core/image_t.hpp> #include <lcmtypes/drc/tag_detection_t.hpp> #include <lcmtypes/drc/tag_detection_list_t.hpp> #include <bot_core/camtrans.h> #include <bot_param/param_util.h> #include <zlib.h> struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; BotCamTrans* mCamTransLeft; BotCamTrans* mCamTransRight; fiducial_detector_t* mDetector; fiducial_stereo_t* mStereoDetector; double mStereoBaseline; Eigen::Matrix3d mCalibLeft; Eigen::Matrix3d mCalibLeftInv; std::string mCameraChannel; std::string mTagChannel; bool mRunStereoAlgorithm; State() { mDetector = NULL; mStereoDetector = NULL; mCamTransLeft = NULL; mCamTransRight = NULL; mCameraChannel = "CAMERA"; mTagChannel = "JPL_TAGS"; mRunStereoAlgorithm = true; } ~State() { if (mDetector != NULL) fiducial_detector_free(mDetector); if (mStereoDetector != NULL) fiducial_stereo_free(mStereoDetector); } void populate(BotCamTrans* iCam, fiducial_stereo_cam_model_t& oCam) { oCam.cols = bot_camtrans_get_width(iCam); oCam.rows = bot_camtrans_get_height(iCam); oCam.focal_length_x = bot_camtrans_get_focal_length_x(iCam); oCam.focal_length_y = bot_camtrans_get_focal_length_y(iCam); oCam.image_center_x = bot_camtrans_get_principal_x(iCam); oCam.image_center_y = bot_camtrans_get_principal_y(iCam); } void populate(BotCamTrans* iCam, Eigen::Matrix3d& oK) { oK(0,0) = bot_camtrans_get_focal_length_x(iCam); oK(1,1) = bot_camtrans_get_focal_length_y(iCam); oK(0,2) = bot_camtrans_get_principal_x(iCam); oK(1,2) = bot_camtrans_get_principal_y(iCam); oK(0,1) = bot_camtrans_get_skew(iCam); } void copyTransform(const Eigen::Isometry3d& iTransform, double oTransform[4][4]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { oTransform[i][j] = iTransform(i,j); } } } void setup() { mBotWrapper.reset(new drc::BotWrapper()); mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm())); mLcmWrapper->get()->subscribe(mCameraChannel, &State::onCamera, this); mDetector = fiducial_detector_alloc(); fiducial_detector_init(mDetector); fiducial_params_t params; fiducial_detector_get_params(mDetector, &params); // TODO: can set parameters here if desired //params.search_size = 40; // image search radius in pixels //params.min_viewing_angle = 20; // angle of view of fiducial in degrees //params.dist_thresh = 0.05; // max allowed distance in meters between initial and estimated fiducial positions fiducial_detector_set_params(mDetector, &params); mStereoDetector = fiducial_stereo_alloc(); fiducial_stereo_init(mStereoDetector); // populate camera data fiducial_stereo_cam_model_t leftModel, rightModel; mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_LEFT").c_str()); mCamTransRight = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_RIGHT").c_str()); populate(mCamTransLeft, leftModel); populate(mCamTransRight, rightModel); copyTransform(Eigen::Isometry3d::Identity(), leftModel.transform); copyTransform(Eigen::Isometry3d::Identity(), leftModel.inv_transform); Eigen::Isometry3d rightToLeft; mBotWrapper->getTransform(mCameraChannel + "_RIGHT", mCameraChannel + "_LEFT", rightToLeft); copyTransform(rightToLeft, rightModel.transform); copyTransform(rightToLeft.inverse(), rightModel.inv_transform); // set detector camera models fiducial_detector_set_camera_models(mDetector, &leftModel); fiducial_stereo_set_camera_models(mStereoDetector, &leftModel, &rightModel); // set internal values for stereo depth computation populate(mCamTransLeft, mCalibLeft); mCalibLeftInv = mCalibLeft.inverse(); mStereoBaseline = rightToLeft.translation().norm(); } void start() { mLcmWrapper->startHandleThread(true); } bool decodeImages(const multisense::images_t* iMessage, cv::Mat& oLeft, cv::Mat& oRight, cv::Mat& oDisp) { bot_core::image_t* leftImage = NULL; bot_core::image_t* rightImage = NULL; bot_core::image_t* dispImage = NULL; // grab image pointers for (int i = 0; i < iMessage->n_images; ++i) { switch (iMessage->image_types[i]) { case multisense::images_t::LEFT: leftImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::RIGHT: rightImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::DISPARITY_ZIPPED: case multisense::images_t::DISPARITY: dispImage = (bot_core::image_t*)(&iMessage->images[i]); break; default: break; } } // decode left image if (leftImage == NULL) { std::cout << "error: no left image available!" << std::endl; return false; } oLeft = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(leftImage->data), -1) : cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data()); if (oLeft.channels() < 3) cv::cvtColor(oLeft, oLeft, CV_GRAY2RGB); // decode right image if necessary for stereo algorithm if (mRunStereoAlgorithm) { if (rightImage == NULL) { std::cout << "error: no right image available!" << std::endl; return false; } oRight = rightImage->pixelformat == rightImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(rightImage->data), -1) : cv::Mat(rightImage->height, rightImage->width, CV_8UC1, rightImage->data.data()); if (oRight.channels() < 3) cv::cvtColor(oRight, oRight, CV_GRAY2RGB); } // otherwise decode disparity; we will compute depth from left image only else { if (dispImage == NULL) { std::cout << "error: no disparity image available!" << std::endl; return false; } int numPix = dispImage->width*dispImage->height; if ((int)dispImage->data.size() != numPix*2) { std::vector<uint8_t> buf(numPix*2); unsigned long len = buf.size(); uncompress(buf.data(), &len, dispImage->data.data(), dispImage->data.size()); oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, buf.data()); } else { oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, dispImage->data.data()); } } return true; } void onCamera(const lcm::ReceiveBuffer* iBuffer, const std::string& iChannel, const multisense::images_t* iMessage) { std::cout << "GOT IMAGE " << std::endl; // grab camera pose Eigen::Isometry3d cameraToLocal, localToCamera; mBotWrapper->getTransform(mCameraChannel + "_LEFT", "local", cameraToLocal, iMessage->utime); localToCamera = cameraToLocal.inverse(); cv::Mat left, right, disp; if (!decodeImages(iMessage, left, right, disp)) return; // set up tag detections message drc::tag_detection_list_t msg; msg.utime = iMessage->utime; msg.num_detections = 0; // TODO: initialize with number of tags from config int numTags = 1; for (int i = 0; i < numTags; ++i) { // TODO: populate from config id int tagId = i; fiducial_pose_t poseInit, poseFinal; // TODO: populate initial pose wrt left cam using fk and config location // can also initialize with previous pose (tracking) poseInit = fiducial_pose_ident(); poseInit.pos.z = 1; poseInit.rot = fiducial_rot_from_rpy(0,2*M_PI/2,0); fiducial_detector_error_t status; if (mRunStereoAlgorithm) { float leftScore(0), rightScore(0); status = fiducial_stereo_process(mStereoDetector, left.data, right.data, left.cols, left.rows, left.channels(), poseInit, &poseFinal, &leftScore, &rightScore, false); } else { float score = 0; status = fiducial_detector_match_subpixel(mDetector, left.data, left.cols, left.rows, left.channels(), poseInit, &score); if (status == FIDUCIAL_DETECTOR_OK) { float x = mDetector->fiducial_location.x; float y = mDetector->fiducial_location.y; int xInt(x), yInt(y); if ((xInt < 0) || (yInt < 0) || (xInt >= disp.cols-1) || (yInt >= disp.rows-1)) { status = FIDUCIAL_DETECTOR_ERR; } else { // interpolate disparity float xFrac(x-xInt), yFrac(y-yInt); int d00 = disp.at<uint16_t>(xInt, yInt); int d10 = disp.at<uint16_t>(xInt+1, yInt); int d01 = disp.at<uint16_t>(xInt, yInt+1); int d11 = disp.at<uint16_t>(xInt+1, yInt+1); float d = (1-xFrac)*(1-yFrac)*d00 + xFrac*(1-yFrac)*d10 + (1-xFrac)*yFrac*d01 + xFrac*yFrac*d11; // compute depth and 3d point float z = mStereoBaseline*mCalibLeft(0,0) / d; Eigen::Vector3d pos = z*mCalibLeftInv*Eigen::Vector3d(x,y,1); poseFinal.pos.x = pos[0]; poseFinal.pos.y = pos[1]; poseFinal.pos.z = pos[2]; // TODO: what about orientation? } } } if (status == FIDUCIAL_DETECTOR_OK) { // populate this tag detection message drc::tag_detection_t detection; detection.utime = msg.utime; detection.id = tagId; // put tag into local frame Eigen::Vector3d pos(poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z); pos = cameraToLocal*pos; for (int k = 0; k < 3; ++k) detection.pos[k] = pos[k]; Eigen::Quaterniond q(poseFinal.rot.u, poseFinal.rot.x, poseFinal.rot.y, poseFinal.rot.z); q = cameraToLocal.rotation()*q; detection.orientation[0] = q.w(); detection.orientation[1] = q.x(); detection.orientation[2] = q.y(); detection.orientation[3] = q.z(); // find pixel position of tag double p[] = {poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z}; double pix[3]; bot_camtrans_project_point(mCamTransLeft, p, pix); detection.cxy[0] = pix[0]; detection.cxy[1] = pix[1]; // four corners are irrelevant; set them all to tag center for (int k = 0; k < 4; ++k) { for (int m = 0; m < 2; ++m) detection.p[k][m] = pix[m]; } // add this detection to list msg.detections.push_back(detection); msg.num_detections = msg.detections.size(); std::cout << "PROCESSED " << status << std::endl; std::cout << "POSE: " << poseFinal.pos.x << " " << poseFinal.pos.y << " " << poseFinal.pos.z << std::endl; } else { std::cout << "warning: could not detect tag " << tagId << std::endl; } } mLcmWrapper->get()->publish(mTagChannel, &msg); } }; int main(const int iArgc, const char** iArgv) { State state; state.setup(); state.start(); return -1; } <commit_msg>added command line options, validated single-image + disparity method<commit_after>#include <jpl-tags/fiducial_stereo.h> #include <opencv2/opencv.hpp> #include <drc_utils/LcmWrapper.hpp> #include <drc_utils/BotWrapper.hpp> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/multisense/images_t.hpp> #include <lcmtypes/bot_core/image_t.hpp> #include <lcmtypes/drc/tag_detection_t.hpp> #include <lcmtypes/drc/tag_detection_list_t.hpp> #include <bot_core/camtrans.h> #include <bot_param/param_util.h> #include <zlib.h> #include <chrono> #include <ConciseArgs> struct TagInfo { int64_t mId; // unique id std::string mLink; // link coordinate frame name Eigen::Isometry3d mLinkPose; // with respect to link Eigen::Isometry3d mCurPose; // tracked pose in local frame bool mTracked; TagInfo() { mId = 0; mLinkPose = Eigen::Isometry3d::Identity(); mCurPose = Eigen::Isometry3d::Identity(); mTracked = false; } }; struct State { drc::BotWrapper::Ptr mBotWrapper; drc::LcmWrapper::Ptr mLcmWrapper; BotCamTrans* mCamTransLeft; BotCamTrans* mCamTransRight; fiducial_detector_t* mDetector; fiducial_stereo_t* mStereoDetector; double mStereoBaseline; Eigen::Matrix3d mCalibLeft; Eigen::Matrix3d mCalibLeftInv; std::vector<TagInfo> mTags; std::string mCameraChannel; std::string mTagChannel; bool mRunStereoAlgorithm; bool mDoTracking; State() { mDetector = NULL; mStereoDetector = NULL; mCamTransLeft = NULL; mCamTransRight = NULL; mCameraChannel = "CAMERA"; mTagChannel = "JPL_TAGS"; mRunStereoAlgorithm = true; mDoTracking = true; } ~State() { if (mDetector != NULL) fiducial_detector_free(mDetector); if (mStereoDetector != NULL) fiducial_stereo_free(mStereoDetector); } void populate(BotCamTrans* iCam, fiducial_stereo_cam_model_t& oCam) { oCam.cols = bot_camtrans_get_width(iCam); oCam.rows = bot_camtrans_get_height(iCam); oCam.focal_length_x = bot_camtrans_get_focal_length_x(iCam); oCam.focal_length_y = bot_camtrans_get_focal_length_y(iCam); oCam.image_center_x = bot_camtrans_get_principal_x(iCam); oCam.image_center_y = bot_camtrans_get_principal_y(iCam); } void populate(BotCamTrans* iCam, Eigen::Matrix3d& oK) { oK = Eigen::Matrix3d::Identity(); oK(0,0) = bot_camtrans_get_focal_length_x(iCam); oK(1,1) = bot_camtrans_get_focal_length_y(iCam); oK(0,2) = bot_camtrans_get_principal_x(iCam); oK(1,2) = bot_camtrans_get_principal_y(iCam); oK(0,1) = bot_camtrans_get_skew(iCam); } void copyTransform(const Eigen::Isometry3d& iTransform, double oTransform[4][4]) { for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { oTransform[i][j] = iTransform(i,j); } } } void setup() { mBotWrapper.reset(new drc::BotWrapper()); mLcmWrapper.reset(new drc::LcmWrapper(mBotWrapper->getLcm())); mLcmWrapper->get()->subscribe(mCameraChannel, &State::onCamera, this); mDetector = fiducial_detector_alloc(); fiducial_detector_init(mDetector); fiducial_params_t params; fiducial_detector_get_params(mDetector, &params); // TODO: can set parameters here if desired //params.search_size = 40; // image search radius in pixels //params.min_viewing_angle = 20; // angle of view of fiducial in degrees //params.dist_thresh = 0.05; // max allowed distance in meters between initial and estimated fiducial positions fiducial_detector_set_params(mDetector, &params); mStereoDetector = fiducial_stereo_alloc(); fiducial_stereo_init(mStereoDetector); // populate camera data fiducial_stereo_cam_model_t leftModel, rightModel; mCamTransLeft = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_LEFT").c_str()); mCamTransRight = bot_param_get_new_camtrans(mBotWrapper->getBotParam(), (mCameraChannel + "_RIGHT").c_str()); populate(mCamTransLeft, leftModel); populate(mCamTransRight, rightModel); copyTransform(Eigen::Isometry3d::Identity(), leftModel.transform); copyTransform(Eigen::Isometry3d::Identity(), leftModel.inv_transform); Eigen::Isometry3d rightToLeft; mBotWrapper->getTransform(mCameraChannel + "_RIGHT", mCameraChannel + "_LEFT", rightToLeft); copyTransform(rightToLeft, rightModel.transform); copyTransform(rightToLeft.inverse(), rightModel.inv_transform); // set detector camera models fiducial_detector_set_camera_models(mDetector, &leftModel); fiducial_stereo_set_camera_models(mStereoDetector, &leftModel, &rightModel); // set internal values for stereo depth computation populate(mCamTransLeft, mCalibLeft); mCalibLeftInv = mCalibLeft.inverse(); mStereoBaseline = rightToLeft.translation().norm(); // populate tag data from config // TODO: this is temporary mTags.clear(); for (int i = 0; i < 1; ++i) { TagInfo tag; tag.mId = 99; mTags.push_back(tag); } } void start() { mLcmWrapper->startHandleThread(true); } bool decodeImages(const multisense::images_t* iMessage, cv::Mat& oLeft, cv::Mat& oRight, cv::Mat& oDisp) { bot_core::image_t* leftImage = NULL; bot_core::image_t* rightImage = NULL; bot_core::image_t* dispImage = NULL; // grab image pointers for (int i = 0; i < iMessage->n_images; ++i) { switch (iMessage->image_types[i]) { case multisense::images_t::LEFT: leftImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::RIGHT: rightImage = (bot_core::image_t*)(&iMessage->images[i]); break; case multisense::images_t::DISPARITY_ZIPPED: case multisense::images_t::DISPARITY: dispImage = (bot_core::image_t*)(&iMessage->images[i]); break; default: break; } } // decode left image if (leftImage == NULL) { std::cout << "error: no left image available!" << std::endl; return false; } oLeft = leftImage->pixelformat == leftImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(leftImage->data), -1) : cv::Mat(leftImage->height, leftImage->width, CV_8UC1, leftImage->data.data()); if (oLeft.channels() < 3) cv::cvtColor(oLeft, oLeft, CV_GRAY2RGB); // decode right image if necessary for stereo algorithm if (mRunStereoAlgorithm) { if (rightImage == NULL) { std::cout << "error: no right image available!" << std::endl; return false; } oRight = rightImage->pixelformat == rightImage->PIXEL_FORMAT_MJPEG ? cv::imdecode(cv::Mat(rightImage->data), -1) : cv::Mat(rightImage->height, rightImage->width, CV_8UC1, rightImage->data.data()); if (oRight.channels() < 3) cv::cvtColor(oRight, oRight, CV_GRAY2RGB); } // otherwise decode disparity; we will compute depth from left image only else { if (dispImage == NULL) { std::cout << "error: no disparity image available!" << std::endl; return false; } int numPix = dispImage->width*dispImage->height; if ((int)dispImage->data.size() != numPix*2) { std::vector<uint8_t> buf(numPix*2); unsigned long len = buf.size(); uncompress(buf.data(), &len, dispImage->data.data(), dispImage->data.size()); oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, buf.data()).clone(); } else { oDisp = cv::Mat(dispImage->height, dispImage->width, CV_16UC1, dispImage->data.data()).clone(); } } return true; } void onCamera(const lcm::ReceiveBuffer* iBuffer, const std::string& iChannel, const multisense::images_t* iMessage) { auto t1 = std::chrono::high_resolution_clock::now(); // grab camera pose Eigen::Isometry3d cameraToLocal, localToCamera; mBotWrapper->getTransform(mCameraChannel + "_LEFT", "local", cameraToLocal, iMessage->utime); localToCamera = cameraToLocal.inverse(); // decode images cv::Mat left, right, disp; if (!decodeImages(iMessage, left, right, disp)) return; // set up tag detections message drc::tag_detection_list_t msg; msg.utime = iMessage->utime; msg.num_detections = 0; for (int i = 0; i < (int)mTags.size(); ++i) { // initialize pose fiducial_pose_t poseInit, poseFinal; poseInit = fiducial_pose_ident(); // use previous tracked position if available if (mDoTracking && mTags[i].mTracked) { Eigen::Isometry3d pose = localToCamera*mTags[i].mCurPose; poseInit.pos.x = pose.translation()[0]; poseInit.pos.y = pose.translation()[1]; poseInit.pos.z = pose.translation()[2]; Eigen::Quaterniond q(pose.rotation()); poseInit.rot.u = q.w(); poseInit.rot.x = q.x(); poseInit.rot.y = q.y(); poseInit.rot.z = q.z(); } // TODO: use fk wrt left cam else { // TOOD: this is temp poseInit.pos.x = 0.028; poseInit.pos.y = 0.002; poseInit.pos.z = 0.56; poseInit.rot = fiducial_rot_from_rpy(0,2*M_PI/2,0); } mTags[i].mTracked = false; fiducial_detector_error_t status; // run stereo detector if (mRunStereoAlgorithm) { float leftScore(0), rightScore(0); status = fiducial_stereo_process(mStereoDetector, left.data, right.data, left.cols, left.rows, left.channels(), poseInit, &poseFinal, &leftScore, &rightScore, false); } // run mono detector and use disparity to infer 3d else { float score = 0; status = fiducial_detector_match_subpixel(mDetector, left.data, left.cols, left.rows, left.channels(), poseInit, &score); if (status == FIDUCIAL_DETECTOR_OK) { float x = mDetector->fiducial_location.x; float y = mDetector->fiducial_location.y; int xInt(x), yInt(y); if ((xInt < 0) || (yInt < 0) || (xInt >= disp.cols-1) || (yInt >= disp.rows-1)) { status = FIDUCIAL_DETECTOR_ERR; } else { // interpolate disparity float xFrac(x-xInt), yFrac(y-yInt); int d00 = disp.at<uint16_t>(yInt, xInt); int d10 = disp.at<uint16_t>(yInt, xInt+1); int d01 = disp.at<uint16_t>(yInt+1, xInt); int d11 = disp.at<uint16_t>(yInt+1, xInt+1); float d = (1-xFrac)*(1-yFrac)*d00 + xFrac*(1-yFrac)*d10 + (1-xFrac)*yFrac*d01 + xFrac*yFrac*d11; // compute depth and 3d point float z = 16*mStereoBaseline*mCalibLeft(0,0) / d; Eigen::Vector3d pos = z*mCalibLeftInv*Eigen::Vector3d(x,y,1); poseFinal.pos.x = pos[0]; poseFinal.pos.y = pos[1]; poseFinal.pos.z = pos[2]; poseFinal.rot = poseInit.rot; // TODO: fill in correct orientation } } } if (status == FIDUCIAL_DETECTOR_OK) { // populate this tag detection message drc::tag_detection_t detection; detection.utime = msg.utime; detection.id = mTags[i].mId; // put tag into local frame Eigen::Vector3d pos(poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z); pos = cameraToLocal*pos; for (int k = 0; k < 3; ++k) detection.pos[k] = pos[k]; Eigen::Quaterniond q(poseFinal.rot.u, poseFinal.rot.x, poseFinal.rot.y, poseFinal.rot.z); q = cameraToLocal.rotation()*q; detection.orientation[0] = q.w(); detection.orientation[1] = q.x(); detection.orientation[2] = q.y(); detection.orientation[3] = q.z(); // find pixel position of tag double p[] = {poseFinal.pos.x, poseFinal.pos.y, poseFinal.pos.z}; double pix[3]; bot_camtrans_project_point(mCamTransLeft, p, pix); detection.cxy[0] = pix[0]; detection.cxy[1] = pix[1]; // four corners are irrelevant; set them all to tag center for (int k = 0; k < 4; ++k) { for (int m = 0; m < 2; ++m) detection.p[k][m] = pix[m]; } // add this detection to list msg.detections.push_back(detection); msg.num_detections = msg.detections.size(); // tracked successfully mTags[i].mCurPose.linear() = q.matrix(); mTags[i].mCurPose.translation() = pos; mTags[i].mTracked = true; } else { std::cout << "warning: could not detect tag " << mTags[i].mId << std::endl; } } mLcmWrapper->get()->publish(mTagChannel, &msg); auto t2 = std::chrono::high_resolution_clock::now(); auto dt = std::chrono::duration_cast<std::chrono::microseconds>(t2-t1); std::cout << "PROCESSED IN " << dt.count()/1e6 << " SEC" << std::endl; } }; int main(const int iArgc, const char** iArgv) { State state; ConciseArgs opt(iArgc, (char**)iArgv); opt.add(state.mCameraChannel, "c", "camera_channel", "channel containing stereo image data"); opt.add(state.mTagChannel, "d", "detection_channel", "channel on which to publish tag detections"); opt.add(state.mRunStereoAlgorithm, "s", "stereo", "whether to run stereo-based detector"); opt.add(state.mDoTracking, "t", "tracking", "whether to use previous detection to initialize current detection"); opt.parse(); state.setup(); state.start(); return -1; } <|endoftext|>
<commit_before>#include "ImageResizer.hpp" #include "FAST/Data/Image.hpp" namespace fast { void ImageResizer::setWidth(int width) { if(width <= 0) throw Exception("Width must be larger than 0."); mSize.x() = width; } void ImageResizer::setHeight(int height) { if(height <= 0) throw Exception("Height must be larger than 0."); mSize.y() = height; } void ImageResizer::setDepth(int depth) { if(depth <= 0) throw Exception("Depth must be larger than 0."); mSize.z() = depth; } void ImageResizer::setSize(VectorXi size) { setWidth(size.x()); setHeight(size.y()); if(size.size() > 2) setDepth(size.z()); } void ImageResizer::setPreserveAspectRatio(bool preserve) { mPreserveAspectRatio = preserve; } ImageResizer::ImageResizer() { createInputPort<Image>(0); createOutputPort<Image>(0); createOpenCLProgram(Config::getKernelSourcePath() + "Algorithms/ImageResizer/ImageResizer.cl"); mSize = Vector3i::Zero(); mPreserveAspectRatio = false; } void ImageResizer::execute() { Image::pointer input = getInputData<Image>(); Image::pointer output = getOutputData<Image>(); if(mSize.x() <= 0 || mSize.y() <= 0) throw Exception("Desired size must be provided to ImageResizer"); // Initialize output image if(input->getDimensions() == 2) { output->create( mSize.x(), mSize.y(), input->getDataType(), input->getNrOfComponents() ); } else { if(mSize.z() == 0) throw Exception("Desired size must be provided to ImageResizer"); output->create( mSize.cast<uint>(), input->getDataType(), input->getNrOfComponents() ); } if(getMainDevice()->isHost()) { throw Exception("Not implemented yet."); } else { OpenCLDevice::pointer device = OpenCLDevice::pointer(getMainDevice()); cl::Program program = getOpenCLProgram(device, ""); cl::Kernel kernel; OpenCLImageAccess::pointer inputAccess = input->getOpenCLImageAccess(ACCESS_READ, device); if(input->getDimensions() == 2) { if(mPreserveAspectRatio) { float scale = (float)output->getWidth() / input->getWidth(); output->setSpacing(scale*input->getSpacing()); int newHeight = (int)round(input->getHeight()*scale); kernel = cl::Kernel(program, "resize2DpreserveAspect"); kernel.setArg(2, newHeight); } else { kernel = cl::Kernel(program, "resize2D"); } OpenCLImageAccess::pointer outputAccess = output->getOpenCLImageAccess(ACCESS_READ_WRITE, device); kernel.setArg(0, *inputAccess->get2DImage()); kernel.setArg(1, *outputAccess->get2DImage()); } else { throw Exception("Not implemented yet."); /* kernel = cl::Kernel(program, "gradient3D"); kernel.setArg(0, *inputAccess->get3DImage()); if(device->isWritingTo3DTexturesSupported()) { OpenCLImageAccess::pointer outputAccess = output->getOpenCLImageAccess(ACCESS_READ_WRITE, device); kernel.setArg(1, *outputAccess->get3DImage()); } else { // If device does not support writing to 3D textures, use a buffer instead OpenCLBufferAccess::pointer outputAccess = output->getOpenCLBufferAccess(ACCESS_READ_WRITE, device); kernel.setArg(1, *outputAccess->get()); } */ } device->getCommandQueue().enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(output->getWidth(), output->getHeight(), output->getDepth()), cl::NullRange ); } } } <commit_msg>fixing spacing in ImageResizer<commit_after>#include "ImageResizer.hpp" #include "FAST/Data/Image.hpp" namespace fast { void ImageResizer::setWidth(int width) { if(width <= 0) throw Exception("Width must be larger than 0."); mSize.x() = width; } void ImageResizer::setHeight(int height) { if(height <= 0) throw Exception("Height must be larger than 0."); mSize.y() = height; } void ImageResizer::setDepth(int depth) { if(depth <= 0) throw Exception("Depth must be larger than 0."); mSize.z() = depth; } void ImageResizer::setSize(VectorXi size) { setWidth(size.x()); setHeight(size.y()); if(size.size() > 2) setDepth(size.z()); } void ImageResizer::setPreserveAspectRatio(bool preserve) { mPreserveAspectRatio = preserve; } ImageResizer::ImageResizer() { createInputPort<Image>(0); createOutputPort<Image>(0); createOpenCLProgram(Config::getKernelSourcePath() + "Algorithms/ImageResizer/ImageResizer.cl"); mSize = Vector3i::Zero(); mPreserveAspectRatio = false; } void ImageResizer::execute() { Image::pointer input = getInputData<Image>(); Image::pointer output = getOutputData<Image>(); if(mSize.x() <= 0 || mSize.y() <= 0) throw Exception("Desired size must be provided to ImageResizer"); // Initialize output image if(input->getDimensions() == 2) { output->create( mSize.x(), mSize.y(), input->getDataType(), input->getNrOfComponents() ); } else { if(mSize.z() == 0) throw Exception("Desired size must be provided to ImageResizer"); output->create( mSize.cast<uint>(), input->getDataType(), input->getNrOfComponents() ); } if(getMainDevice()->isHost()) { throw Exception("Not implemented yet."); } else { OpenCLDevice::pointer device = OpenCLDevice::pointer(getMainDevice()); cl::Program program = getOpenCLProgram(device, ""); cl::Kernel kernel; OpenCLImageAccess::pointer inputAccess = input->getOpenCLImageAccess(ACCESS_READ, device); if(input->getDimensions() == 2) { if(mPreserveAspectRatio) { float scale = (float)output->getWidth() / input->getWidth(); output->setSpacing(scale*input->getSpacing()); int newHeight = (int)round(input->getHeight()*scale); kernel = cl::Kernel(program, "resize2DpreserveAspect"); kernel.setArg(2, newHeight); } else { output->setSpacing(Vector3f( input->getSpacing().x()*((float)input->getWidth()/output->getWidth()), input->getSpacing().y()*((float)input->getHeight()/output->getHeight()), 1.0f )); kernel = cl::Kernel(program, "resize2D"); } OpenCLImageAccess::pointer outputAccess = output->getOpenCLImageAccess(ACCESS_READ_WRITE, device); kernel.setArg(0, *inputAccess->get2DImage()); kernel.setArg(1, *outputAccess->get2DImage()); } else { throw Exception("Not implemented yet."); /* kernel = cl::Kernel(program, "gradient3D"); kernel.setArg(0, *inputAccess->get3DImage()); if(device->isWritingTo3DTexturesSupported()) { OpenCLImageAccess::pointer outputAccess = output->getOpenCLImageAccess(ACCESS_READ_WRITE, device); kernel.setArg(1, *outputAccess->get3DImage()); } else { // If device does not support writing to 3D textures, use a buffer instead OpenCLBufferAccess::pointer outputAccess = output->getOpenCLBufferAccess(ACCESS_READ_WRITE, device); kernel.setArg(1, *outputAccess->get()); } */ } device->getCommandQueue().enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(output->getWidth(), output->getHeight(), output->getDepth()), cl::NullRange ); } } } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "common/Common.h" #include <cstdarg> // for va_end, va_list, va_start #include <cstdio> // for printf, vprintf // #define _DEBUG namespace rawspeed { #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && !defined(_DEBUG) void __attribute__((const))) writeLog(DEBUG_PRIO priority, const char* format, ...) { // When fuzzing, any output is really undesirable. } #else void writeLog(DEBUG_PRIO priority, const char* format, ...) { #ifndef _DEBUG if (priority < DEBUG_PRIO_INFO) #endif // _DEBUG fprintf(stdout, "%s", "RawSpeed:"); va_list args; va_start(args, format); #ifndef _DEBUG if (priority < DEBUG_PRIO_INFO) #endif // _DEBUG vfprintf(stdout, format, args); va_end(args); #ifndef _DEBUG if (priority < DEBUG_PRIO_INFO) #endif // _DEBUG fprintf(stdout, "%s", "\n"); } #endif } // namespace rawspeed <commit_msg>writeLog(): ugh, drop extra errneous ')'<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "common/Common.h" #include <cstdarg> // for va_end, va_list, va_start #include <cstdio> // for printf, vprintf // #define _DEBUG namespace rawspeed { #if defined(FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION) && !defined(_DEBUG) void __attribute__((const)) writeLog(DEBUG_PRIO priority, const char* format, ...) { // When fuzzing, any output is really undesirable. } #else void writeLog(DEBUG_PRIO priority, const char* format, ...) { #ifndef _DEBUG if (priority < DEBUG_PRIO_INFO) #endif // _DEBUG fprintf(stdout, "%s", "RawSpeed:"); va_list args; va_start(args, format); #ifndef _DEBUG if (priority < DEBUG_PRIO_INFO) #endif // _DEBUG vfprintf(stdout, format, args); va_end(args); #ifndef _DEBUG if (priority < DEBUG_PRIO_INFO) #endif // _DEBUG fprintf(stdout, "%s", "\n"); } #endif } // namespace rawspeed <|endoftext|>
<commit_before>#include "Zenderer/CoreGraphics/VertexArray.hpp" using namespace zen::gfxcore; CVertexArray::CVertexArray(const GLenum type) : CGLSubsystem("Vertex Array"), m_icount(0), m_vcount(0), m_vao(0), m_vbo(0), m_ibo(0), m_type(type) { m_vaoIndices.clear(); m_vaoVertices.clear(); } CVertexArray::~CVertexArray() { this->Destroy(); } bool CVertexArray::Init() { if(m_init) this->Destroy(); // Bad GL version. if(!glGenVertexArrays) return false; GL(glGenVertexArrays(1, &m_vao)); GL(glGenBuffers(1, &m_vbo)); GL(glGenBuffers(1, &m_ibo)); ZEN_ASSERT(m_vao != 0); ZEN_ASSERT(m_vbo != 0); ZEN_ASSERT(m_ibo != 0); return (m_init = true); } bool CVertexArray::Destroy() { if(!m_init) return true; ZEN_ASSERT(m_vao != 0); ZEN_ASSERT(m_vbo != 0); ZEN_ASSERT(m_ibo != 0); glDeleteVertexArrays(1, &m_vao); glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ibo); return true; } bool CVertexArray::Bind() { if(!m_init) return false; GL(glBindVertexArray(m_vao)); GL(glEnableVertexAttribArray(0)); // Enable shader attribute 0 GL(glEnableVertexAttribArray(1)); GL(glEnableVertexAttribArray(2)); GL(glBindBuffer(GL_ARRAY_BUFFER, m_vbo)); GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo)); return true; } bool CVertexArray::Unbind() { if(!m_init) return false; GL(glBindBuffer(GL_ARRAY_BUFFER, 0)); GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); GL(glBindVertexArray(0)); return true; } index_t CVertexArray::AddData(const DrawBatch& D) { ZEN_ASSERTM(D.vcount > 0, "no buffer vertices given"); ZEN_ASSERTM(D.icount > 0, "no buffer indices given"); m_vaoVertices.reserve(m_vaoVertices.size() + D.vcount); for(size_t v = 0; v < D.vcount; ++v) m_vaoVertices.push_back(D.Vertices[v]); size_t offset = m_vaoIndices.size(); m_vaoIndices.reserve(m_vaoIndices.size() + D.icount); for(size_t i = 0; i < D.icount; ++i) m_vaoIndices.push_back(D.Indices[i]); return offset + m_icount; } bool CVertexArray::Offload() { if(!this->Bind()) return false; if(this->Offloaded()) return false; // Check if there's existing data on the buffers. GLint bsize = 0; GL(glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize)); // There is! if(bsize > 0) { // Copy existing buffer data from GPU to local buffer. const vertex_t* const data = this->GetVerticesFromGPU(); vertex_t* tmp = new vertex_t[bsize / sizeof(vertex_t)]; memcpy(tmp, data, bsize); GL(glUnmapBuffer(GL_ARRAY_BUFFER)); // Allocate enough GPU space for all vertex data, new and old. // Pass the old data directly to it. GL(glBufferData(GL_ARRAY_BUFFER, bsize + (sizeof(vertex_t) * m_vaoVertices.size()), tmp, m_type)); // Pass the latest vertex data at the end of the existing data. GL(glBufferSubData(GL_ARRAY_BUFFER, bsize, sizeof(vertex_t) * m_vaoVertices.size(), &m_vaoVertices[0])); } // No existing buffer or vertices. else { // Allocate enough space for all vertices on GPU. GL(glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_t) * m_vaoVertices.size(), &m_vaoVertices[0], m_type)); } // Repeat process for index buffer. bsize = 0; GL(glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize)); if(bsize > 0) { // Copy from GPU to local buffer. const index_t* const data = this->GetIndicesFromGPU(); index_t* tmp = new index_t[bsize / sizeof(index_t)]; memcpy(tmp, data, bsize); GL(glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)); // Allocate enough GPU space for all vertex data, new and old. // Pass the old data directly to it. GL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, // IBO bsize + (sizeof(index_t) * m_vaoIndices.size()),// Size tmp, // Initial data m_type)); // Access type // Pass the latest vertex data at the end of the existing data. GL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, bsize, sizeof(index_t) * m_vaoIndices.size(), &m_vaoIndices[0])); } else { // No existing data, so we just write new stuff to the buffer. GL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_t) * m_vaoIndices.size(), &m_vaoIndices[0], m_type)); } // Vertices are arranged in memory like so: // // [ x, y, z, t, s, r, r, g, b, a ] // // (see the definition of vertex_t in Zenderer/CoreGraphics/OpenGL.hpp) // // Specify vertex position arrangement. // According to the diagram shown above, the vertex position // would start at index 0. GL(glVertexAttribPointer(0, /* Attribute index */ 3, /* Number of values */ GL_FLOAT, /* Type of value */ GL_FALSE, /* Normalized? */ sizeof(vertex_t), /* Size of field */ VBO_OFFSET(0, vertex_t, position))); /* Size of offset */ // Specify texture coordinate position arrangement. // According to the diagram, texture coordinates // start at index 3. GL(glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_t), VBO_OFFSET(0, vertex_t, tc))); // Specify the color arrangement, starting at index 4. GL(glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_t), VBO_OFFSET(0, vertex_t, color))); // We're done, clean up buffers. m_vcount += m_vaoVertices.size(); m_icount += m_vaoIndices.size(); m_vaoVertices.clear(); m_vaoIndices.clear(); return this->Unbind(); } const vertex_t* const CVertexArray::GetVerticesFromGPU() const { return (vertex_t*)GL(glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY)); } const index_t* const CVertexArray::GetIndicesFromGPU() const { return (index_t*)GL(glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY)); } size_t CVertexArray::GetVertexCount() const { return m_vcount; } size_t CVertexArray::GetIndexCount() const { return m_icount; } bool CVertexArray::Offloaded() const { return (m_vaoIndices.size() == 0 && m_vaoVertices.size() == 0); } <commit_msg>Restructured VAOs for best practices.<commit_after>#include "Zenderer/CoreGraphics/VertexArray.hpp" using namespace zen::gfxcore; CVertexArray::CVertexArray(const GLenum type) : CGLSubsystem("Vertex Array"), m_icount(0), m_vcount(0), m_vao(0), m_vbo(0), m_ibo(0), m_type(type) { m_vaoIndices.clear(); m_vaoVertices.clear(); } CVertexArray::~CVertexArray() { this->Destroy(); } bool CVertexArray::Init() { if(m_init) this->Destroy(); // Bad GL version. if(!glGenVertexArrays) return false; GL(glGenVertexArrays(1, &m_vao)); GL(glGenBuffers(1, &m_vbo)); GL(glGenBuffers(1, &m_ibo)); ZEN_ASSERT(m_vao != 0); ZEN_ASSERT(m_vbo != 0); ZEN_ASSERT(m_ibo != 0); return (m_init = true); } bool CVertexArray::Destroy() { if(!m_init) return true; ZEN_ASSERT(m_vao != 0); ZEN_ASSERT(m_vbo != 0); ZEN_ASSERT(m_ibo != 0); glDeleteVertexArrays(1, &m_vao); glDeleteBuffers(1, &m_vbo); glDeleteBuffers(1, &m_ibo); return true; } bool CVertexArray::Bind() const { if(!m_init) return false; GL(glBindVertexArray(m_vao)); return true; } bool CVertexArray::Unbind() const { if(!m_init) return false; GL(glBindVertexArray(0)); return true; } index_t CVertexArray::AddData(const DrawBatch& D) { ZEN_ASSERTM(D.vcount > 0, "no buffer vertices given"); ZEN_ASSERTM(D.icount > 0, "no buffer indices given"); m_vaoVertices.reserve(m_vaoVertices.size() + D.vcount); for(size_t v = 0; v < D.vcount; ++v) m_vaoVertices.push_back(D.Vertices[v]); size_t offset = m_vaoIndices.size(); m_vaoIndices.reserve(m_vaoIndices.size() + D.icount); for(size_t i = 0; i < D.icount; ++i) m_vaoIndices.push_back(D.Indices[i]); return offset + m_icount; } /// @see http://stackoverflow.com/questions/8923174/opengl-vao-best-practices bool CVertexArray::Offload() { if(!this->Bind()) return false; if(this->Offloaded()) return false; // Bind() only binds the VAO. We attach the VBO/IBO to it here. GL(glBindBuffer(GL_ARRAY_BUFFER, m_vbo)); GL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo)); // Check if there's existing data on the buffers. GLint bsize = 0; GL(glGetBufferParameteriv(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize)); // There is! if(bsize > 0) { // Copy existing buffer data from GPU to local buffer. const vertex_t* const data = this->GetVerticesFromGPU(); vertex_t* tmp = new vertex_t[bsize / sizeof(vertex_t)]; memcpy(tmp, data, bsize); GL(glUnmapBuffer(GL_ARRAY_BUFFER)); // Allocate enough GPU space for all vertex data, new and old. // Pass the old data directly to it. GL(glBufferData(GL_ARRAY_BUFFER, bsize + (sizeof(vertex_t) * m_vaoVertices.size()), tmp, m_type)); // Pass the latest vertex data at the end of the existing data. GL(glBufferSubData(GL_ARRAY_BUFFER, bsize, sizeof(vertex_t) * m_vaoVertices.size(), &m_vaoVertices[0])); } // No existing buffer or vertices. else { // Allocate enough space for all vertices on GPU. GL(glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_t) * m_vaoVertices.size(), &m_vaoVertices[0], m_type)); } // Repeat process for index buffer. bsize = 0; GL(glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &bsize)); if(bsize > 0) { // Copy from GPU to local buffer. const index_t* const data = this->GetIndicesFromGPU(); index_t* tmp = new index_t[bsize / sizeof(index_t)]; memcpy(tmp, data, bsize); GL(glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER)); // Allocate enough GPU space for all vertex data, new and old. // Pass the old data directly to it. GL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, // IBO bsize + (sizeof(index_t) * m_vaoIndices.size()),// Size tmp, // Initial data m_type)); // Access type // Pass the latest vertex data at the end of the existing data. GL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, bsize, sizeof(index_t) * m_vaoIndices.size(), &m_vaoIndices[0])); } else { // No existing data, so we just write new stuff to the buffer. GL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index_t) * m_vaoIndices.size(), &m_vaoIndices[0], m_type)); } // Vertices are arranged in memory like so: // // [ x, y, z, t, s, r, r, g, b, a ] // // (see the definition of vertex_t in Zenderer/CoreGraphics/OpenGL.hpp) // // Specify vertex position arrangement. // According to the diagram shown above, the vertex position // would start at index 0. GL(glVertexAttribPointer(0, /* Attribute index */ 3, /* Number of values */ GL_FLOAT, /* Type of value */ GL_FALSE, /* Normalized? */ sizeof(vertex_t), /* Size of field */ VBO_OFFSET(0, vertex_t, position))); /* Size of offset */ // Enable shader attribute 0 (position) GL(glEnableVertexAttribArray(0)); // Specify texture coordinate position arrangement. // According to the diagram, texture coordinates // start at index 3. GL(glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_t), VBO_OFFSET(0, vertex_t, tc))); GL(glEnableVertexAttribArray(1)); // Specify the color arrangement, starting at index 4. GL(glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(vertex_t), VBO_OFFSET(0, vertex_t, color))); GL(glEnableVertexAttribArray(2)); // We do not unbind our buffers as they stay attached to the VAO. // We're done, clean up buffers. m_vcount += m_vaoVertices.size(); m_icount += m_vaoIndices.size(); m_vaoVertices.clear(); m_vaoIndices.clear(); return this->Unbind(); } const vertex_t* const CVertexArray::GetVerticesFromGPU() const { return (vertex_t*)GL(glMapBuffer(GL_ARRAY_BUFFER, GL_READ_ONLY)); } const index_t* const CVertexArray::GetIndicesFromGPU() const { return (index_t*)GL(glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY)); } size_t CVertexArray::GetVertexCount() const { return m_vcount; } size_t CVertexArray::GetIndexCount() const { return m_icount; } bool CVertexArray::Offloaded() const { return (m_vaoIndices.size() == 0 && m_vaoVertices.size() == 0); } <|endoftext|>
<commit_before>#ifndef apparel_class_H #define apparel_class_H /* Classes for apparel */ #include <iostream> using namespace std; class apparel { public: string type; // apparel type int condition; // condition of equipment }; int main() { } #endif <commit_msg>no changes made<commit_after>#ifndef apparel_class_H #define apparel_class_H /* Classes for apparel */ #include <iostream> using namespace std; class apparel { public: string type; // apparel type int condition; // condition of equipment value 1-10 }; int main() { } #endif <|endoftext|>
<commit_before>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // 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. ////////////////////////////////////////////////////////////////////////////// #include "ShImage.hpp" #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <png.h> #include <sstream> #include "ShException.hpp" #include "ShError.hpp" #include "ShDebug.hpp" namespace SH { ShImage::ShImage() : m_width(0), m_height(0), m_elements(0), m_memory(0) { } ShImage::ShImage(int width, int height, int elements) : m_width(width), m_height(height), m_elements(elements), m_memory(new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT)) { } ShImage::ShImage(const ShImage& other) : m_width(other.m_width), m_height(other.m_height), m_elements(other.m_elements), m_memory(other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT) : 0) { if (m_memory) { std::memcpy(m_memory->hostStorage()->data(), other.m_memory->hostStorage()->data(), m_width * m_height * m_elements * sizeof(float)); } } ShImage::~ShImage() { } ShImage& ShImage::operator=(const ShImage& other) { m_width = other.m_width; m_height = other.m_height; m_elements = other.m_elements; m_memory = (other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT) : 0); std::memcpy(m_memory->hostStorage()->data(), other.m_memory->hostStorage()->data(), m_width * m_height * m_elements * sizeof(float)); return *this; } int ShImage::width() const { return m_width; } int ShImage::height() const { return m_height; } int ShImage::elements() const { return m_elements; } float ShImage::operator()(int x, int y, int i) const { SH_DEBUG_ASSERT(m_memory); return data()[m_elements * (m_width * y + x) + i]; } float& ShImage::operator()(int x, int y, int i) { return data()[m_elements * (m_width * y + x) + i]; } void ShImage::savePng(const std::string& filename, int inverse_alpha) { FILE* fout = std::fopen(filename.c_str(), "wb"); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); setjmp(png_ptr->jmpbuf); /* Setup PNG I/O */ png_init_io(png_ptr, fout); /* Optionally setup a callback to indicate when a row has been * written. */ /* Setup filtering. Use Paeth filtering */ png_set_filter(png_ptr, 0, PNG_FILTER_PAETH); /* Setup compression level. */ png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* Setup PNG header information and write it to the file */ int color_type; switch (m_elements) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3: color_type = PNG_COLOR_TYPE_RGB; break; case 4: color_type = PNG_COLOR_TYPE_RGBA; break; default: throw ShImageException("Invalid element size"); } png_set_IHDR(png_ptr, info_ptr, m_width, m_height, 8, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); // Actual writing png_byte* tempLine = (png_byte*)malloc(m_width * sizeof(png_byte) * m_elements); for(int i=0;i<m_height;i+=1){ for(int j=0;j<m_width;j+=1){ for(int k = 0;k<m_elements;k+=1) tempLine[m_elements*j+k] = static_cast<png_byte>((*this)(j, i, k)*255.0); // inverse alpha if(inverse_alpha && m_elements == 4) tempLine[m_elements*j+3] = 255 - tempLine[m_elements*j+3]; } png_write_row(png_ptr, tempLine); } // closing and freeing the structs png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); free(tempLine); fclose(fout); } void ShImage::loadPng(const std::string& filename) { // check that the file is a png file png_byte buf[8]; FILE* in = std::fopen(filename.c_str(), "rb"); if (!in) shError( ShImageException("Unable to open " + filename) ); for (int i = 0; i < 8; i++) { if (!(buf[i] = fgetc(in))) shError( ShImageException("Not a PNG file") ); } if (png_sig_cmp(buf, 0, 8)) shError( ShImageException("Not a PNG file") ); png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); // FIXME: use error handlers if (!png_ptr) shError( ShImageException("Error initialising libpng (png_ptr)") ); png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, 0, 0); shError( ShImageException("Error initialising libpng (info_ptr)") ); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, 0, 0); shError( ShImageException("Error initialising libpng (setjmp/lngjmp)") ); } // png_set_read_fn(png_ptr, reinterpret_cast<void*>(&in), my_istream_read_data); png_init_io(png_ptr, in); png_set_sig_bytes(png_ptr, 8); png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, 0); int bit_depth = png_get_bit_depth(png_ptr, info_ptr); if (bit_depth % 8) { png_destroy_read_struct(&png_ptr, 0, 0); std::ostringstream os; os << "Invalid bit elements " << bit_depth; shError( ShImageException(os.str()) ); } int colour_type = png_get_color_type(png_ptr, info_ptr); if (colour_type == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); colour_type = PNG_COLOR_TYPE_RGB; } if (colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { png_set_gray_1_2_4_to_8(png_ptr); } if (colour_type != PNG_COLOR_TYPE_RGB && colour_type != PNG_COLOR_TYPE_GRAY && colour_type != PNG_COLOR_TYPE_RGBA) { png_destroy_read_struct(&png_ptr, 0, 0); shError( ShImageException("Invalid colour type") ); } m_memory = 0; m_width = png_get_image_width(png_ptr, info_ptr); m_height = png_get_image_height(png_ptr, info_ptr); switch (colour_type) { case PNG_COLOR_TYPE_RGB: m_elements = 3; break; case PNG_COLOR_TYPE_RGBA: m_elements = 4; break; default: m_elements = 1; break; } png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr); m_memory = new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT); for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { for (int i = 0; i < m_elements; i++) { png_byte *row = row_pointers[y]; int index = m_elements * (y * m_width + x) + i; long element = 0; for (int j = bit_depth/8 - 1; j >= 0; j--) { element <<= 8; element += row[(x * m_elements + i) * bit_depth/8 + j]; } data()[index] = element / static_cast<float>((1 << bit_depth) - 1); } } } png_destroy_read_struct(&png_ptr, &info_ptr, 0); } void ShImage::savePng16(const std::string& filename, int inverse_alpha) { FILE* fout = std::fopen(filename.c_str(), "w"); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); setjmp(png_ptr->jmpbuf); /* Setup PNG I/O */ png_init_io(png_ptr, fout); /* Optionally setup a callback to indicate when a row has been * written. */ /* Setup filtering. Use Paeth filtering */ png_set_filter(png_ptr, 0, PNG_FILTER_PAETH); /* Setup compression level. */ png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* Setup PNG header information and write it to the file */ int color_type; switch (m_elements) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3: color_type = PNG_COLOR_TYPE_RGB; break; case 4: color_type = PNG_COLOR_TYPE_RGBA; break; default: throw ShImageException("Invalid element size"); } png_set_IHDR(png_ptr, info_ptr, m_width, m_height, 16, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); // Actual writing png_uint_16* tempLine = (png_uint_16*)malloc(m_width * sizeof(png_uint_16) * m_elements); for(int i=0;i<m_height;i+=1){ for(int j=0;j<m_width;j+=1){ for(int k = 0;k<m_elements;k+=1) tempLine[m_elements*j+k] = static_cast<png_uint_16>((*this)(j, i, k)*65535.0); // inverse alpha if(inverse_alpha && m_elements == 4) tempLine[m_elements*j+3] = 65535 - tempLine[m_elements*j+3]; } png_write_row(png_ptr, (png_byte*)tempLine); } // closing and freeing the structs png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); free(tempLine); fclose(fout); } ShImage ShImage::getNormalImage() { int w = width(); int h = height(); ShImage output_image(w,h,3); for (int j = 0; j < h; j++) { int jp1 = j + 1; if (jp1 >= h) jp1 = 0; int jm1 = (j - 1); if (jm1 < 0) jm1 = h - 1; for (int i = 0; i < w; i++) { int ip1 = i + 1; if (ip1 >= w) ip1 = 0; int im1 = (i - 1); if (im1 < 0) im1 = w - 1; float x, y, z; x = ((*this)(ip1,j,0) - (*this)(im1,j,0))/2.0f; output_image(i,j,0) = x/2.0f + 0.5f; y = ((*this)(i,jp1,0) - (*this)(i,jm1,0))/2.0f; output_image(i,j,1) = y/2.0f + 0.5f; z = x*x + y*y; z = (z > 1.0f) ? z = 0.0f : std::sqrt(1 - z); output_image(i,j,2) = z; } } return output_image; } const float* ShImage::data() const { if (!m_memory) return 0; return reinterpret_cast<const float*>(m_memory->hostStorage()->data()); } float* ShImage::data() { if (!m_memory) return 0; return reinterpret_cast<float*>(m_memory->hostStorage()->data()); } void ShImage::dirty() { if (!m_memory) return; m_memory->hostStorage()->dirty(); } ShMemoryPtr ShImage::memory() { return m_memory; } ShPointer<const ShMemory> ShImage::memory() const { return m_memory; } } <commit_msg>Work-around a compilation warning<commit_after>// Sh: A GPU metaprogramming language. // // Copyright 2003-2005 Serious Hack Inc. // // 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. ////////////////////////////////////////////////////////////////////////////// #include "ShImage.hpp" #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <png.h> #include <sstream> #include "ShException.hpp" #include "ShError.hpp" #include "ShDebug.hpp" namespace SH { ShImage::ShImage() : m_width(0), m_height(0), m_elements(0), m_memory(0) { } ShImage::ShImage(int width, int height, int elements) : m_width(width), m_height(height), m_elements(elements), m_memory(new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT)) { } ShImage::ShImage(const ShImage& other) : m_width(other.m_width), m_height(other.m_height), m_elements(other.m_elements), m_memory(other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT) : 0) { if (m_memory) { std::memcpy(m_memory->hostStorage()->data(), other.m_memory->hostStorage()->data(), m_width * m_height * m_elements * sizeof(float)); } } ShImage::~ShImage() { } ShImage& ShImage::operator=(const ShImage& other) { m_width = other.m_width; m_height = other.m_height; m_elements = other.m_elements; m_memory = (other.m_memory ? new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT) : 0); std::memcpy(m_memory->hostStorage()->data(), other.m_memory->hostStorage()->data(), m_width * m_height * m_elements * sizeof(float)); return *this; } int ShImage::width() const { return m_width; } int ShImage::height() const { return m_height; } int ShImage::elements() const { return m_elements; } float ShImage::operator()(int x, int y, int i) const { SH_DEBUG_ASSERT(m_memory); return data()[m_elements * (m_width * y + x) + i]; } float& ShImage::operator()(int x, int y, int i) { return data()[m_elements * (m_width * y + x) + i]; } void ShImage::savePng(const std::string& filename, int inverse_alpha) { FILE* fout = std::fopen(filename.c_str(), "wb"); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); setjmp(png_ptr->jmpbuf); /* Setup PNG I/O */ png_init_io(png_ptr, fout); /* Optionally setup a callback to indicate when a row has been * written. */ /* Setup filtering. Use Paeth filtering */ png_set_filter(png_ptr, 0, PNG_FILTER_PAETH); /* Setup compression level. */ png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* Setup PNG header information and write it to the file */ int color_type; switch (m_elements) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3: color_type = PNG_COLOR_TYPE_RGB; break; case 4: color_type = PNG_COLOR_TYPE_RGBA; break; default: throw ShImageException("Invalid element size"); } png_set_IHDR(png_ptr, info_ptr, m_width, m_height, 8, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); // Actual writing png_byte* tempLine = (png_byte*)malloc(m_width * sizeof(png_byte) * m_elements); for(int i=0;i<m_height;i+=1){ for(int j=0;j<m_width;j+=1){ for(int k = 0;k<m_elements;k+=1) tempLine[m_elements*j+k] = static_cast<png_byte>((*this)(j, i, k)*255.0); // inverse alpha if(inverse_alpha && m_elements == 4) tempLine[m_elements*j+3] = 255 - tempLine[m_elements*j+3]; } png_write_row(png_ptr, tempLine); } // closing and freeing the structs png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); free(tempLine); fclose(fout); } void ShImage::loadPng(const std::string& filename) { // check that the file is a png file png_byte buf[8]; FILE* in = std::fopen(filename.c_str(), "rb"); if (!in) shError( ShImageException("Unable to open " + filename) ); for (int i = 0; i < 8; i++) { if (!(buf[i] = fgetc(in))) shError( ShImageException("Not a PNG file") ); } if (png_sig_cmp(buf, 0, 8)) shError( ShImageException("Not a PNG file") ); png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); // FIXME: use error handlers if (!png_ptr) shError( ShImageException("Error initialising libpng (png_ptr)") ); png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, 0, 0); shError( ShImageException("Error initialising libpng (info_ptr)") ); } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, 0, 0); shError( ShImageException("Error initialising libpng (setjmp/lngjmp)") ); } // png_set_read_fn(png_ptr, reinterpret_cast<void*>(&in), my_istream_read_data); png_init_io(png_ptr, in); png_set_sig_bytes(png_ptr, 8); png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, 0); int bit_depth = png_get_bit_depth(png_ptr, info_ptr); if (bit_depth % 8) { png_destroy_read_struct(&png_ptr, 0, 0); std::ostringstream os; os << "Invalid bit elements " << bit_depth; shError( ShImageException(os.str()) ); } int colour_type = png_get_color_type(png_ptr, info_ptr); if (colour_type == PNG_COLOR_TYPE_PALETTE) { png_set_palette_to_rgb(png_ptr); colour_type = PNG_COLOR_TYPE_RGB; } if (colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) { png_set_gray_1_2_4_to_8(png_ptr); } if (colour_type != PNG_COLOR_TYPE_RGB && colour_type != PNG_COLOR_TYPE_GRAY && colour_type != PNG_COLOR_TYPE_RGBA) { png_destroy_read_struct(&png_ptr, 0, 0); shError( ShImageException("Invalid colour type") ); } m_memory = 0; m_width = png_get_image_width(png_ptr, info_ptr); m_height = png_get_image_height(png_ptr, info_ptr); switch (colour_type) { case PNG_COLOR_TYPE_RGB: m_elements = 3; break; case PNG_COLOR_TYPE_RGBA: m_elements = 4; break; default: m_elements = 1; break; } png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr); m_memory = new ShHostMemory(sizeof(float) * m_width * m_height * m_elements, SH_FLOAT); for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { for (int i = 0; i < m_elements; i++) { png_byte *row = row_pointers[y]; int index = m_elements * (y * m_width + x) + i; long element = 0; for (int j = bit_depth/8 - 1; j >= 0; j--) { element <<= 8; element += row[(x * m_elements + i) * bit_depth/8 + j]; } data()[index] = element / static_cast<float>((1 << bit_depth) - 1); } } } png_destroy_read_struct(&png_ptr, &info_ptr, 0); } void ShImage::savePng16(const std::string& filename, int inverse_alpha) { FILE* fout = std::fopen(filename.c_str(), "w"); png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); png_infop info_ptr = png_create_info_struct(png_ptr); setjmp(png_ptr->jmpbuf); /* Setup PNG I/O */ png_init_io(png_ptr, fout); /* Optionally setup a callback to indicate when a row has been * written. */ /* Setup filtering. Use Paeth filtering */ png_set_filter(png_ptr, 0, PNG_FILTER_PAETH); /* Setup compression level. */ png_set_compression_level(png_ptr, Z_BEST_COMPRESSION); /* Setup PNG header information and write it to the file */ int color_type; switch (m_elements) { case 1: color_type = PNG_COLOR_TYPE_GRAY; break; case 2: color_type = PNG_COLOR_TYPE_GRAY_ALPHA; break; case 3: color_type = PNG_COLOR_TYPE_RGB; break; case 4: color_type = PNG_COLOR_TYPE_RGBA; break; default: throw ShImageException("Invalid element size"); } png_set_IHDR(png_ptr, info_ptr, m_width, m_height, 16, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); png_write_info(png_ptr, info_ptr); // Actual writing png_uint_16* tempLine = (png_uint_16*)malloc(m_width * sizeof(png_uint_16) * m_elements); for(int i=0;i<m_height;i+=1){ for(int j=0;j<m_width;j+=1){ for(int k = 0;k<m_elements;k+=1) tempLine[m_elements*j+k] = static_cast<png_uint_16>((*this)(j, i, k)*65535.0); // inverse alpha if(inverse_alpha && m_elements == 4) tempLine[m_elements*j+3] = 65535 - tempLine[m_elements*j+3]; } png_write_row(png_ptr, (png_byte*)tempLine); } // closing and freeing the structs png_write_end(png_ptr, info_ptr); png_destroy_write_struct(&png_ptr, &info_ptr); free(tempLine); fclose(fout); } ShImage ShImage::getNormalImage() { int w = width(); int h = height(); ShImage output_image(w,h,3); for (int j = 0; j < h; j++) { int jp1 = j + 1; if (jp1 >= h) jp1 = 0; int jm1 = (j - 1); if (jm1 < 0) jm1 = h - 1; for (int i = 0; i < w; i++) { int ip1 = i + 1; if (ip1 >= w) ip1 = 0; int im1 = (i - 1); if (im1 < 0) im1 = w - 1; float x, y, z; x = ((*this)(ip1,j,0) - (*this)(im1,j,0))/2.0f; output_image(i,j,0) = x/2.0f + 0.5f; y = ((*this)(i,jp1,0) - (*this)(i,jm1,0))/2.0f; output_image(i,j,1) = y/2.0f + 0.5f; z = x*x + y*y; if (z < 1.0f) { z = std::sqrt(1 - z); } else { z = 0.0f; } output_image(i,j,2) = z; } } return output_image; } const float* ShImage::data() const { if (!m_memory) return 0; return reinterpret_cast<const float*>(m_memory->hostStorage()->data()); } float* ShImage::data() { if (!m_memory) return 0; return reinterpret_cast<float*>(m_memory->hostStorage()->data()); } void ShImage::dirty() { if (!m_memory) return; m_memory->hostStorage()->dirty(); } ShMemoryPtr ShImage::memory() { return m_memory; } ShPointer<const ShMemory> ShImage::memory() const { return m_memory; } } <|endoftext|>
<commit_before>/*************************************************************************** begin : Thu Apr 24 15:54:58 CEST 2003 copyright : (C) 2003 by Giuseppe Lipari email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef __JSONTRACE_HPP__ #define __JSONRACE_HPP__ #include <fstream> #include <iostream> #include <string> #include <baseexc.hpp> #include <basetype.hpp> #include <event.hpp> #include <particle.hpp> #include <trace.hpp> #include <rttask.hpp> #include <taskevt.hpp> namespace RTSim { class JSONTrace { protected: std::ofstream fd; bool first_event; void writeTaskEvent(const Task &tt, const std::string &evt_name); public: JSONTrace(const std::string& name); ~JSONTrace(); void probe(ArrEvt& e); void probe(EndEvt& e); void probe(SchedEvt& e); void probe(DeschedEvt& e); void probe(DeadEvt& e); void attachToTask(Task* t); }; } #endif <commit_msg>Modified wrong definition<commit_after>/*************************************************************************** begin : Thu Apr 24 15:54:58 CEST 2003 copyright : (C) 2003 by Giuseppe Lipari email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef __JSONTRACE_HPP__ #define __JSONTRACE_HPP__ #include <fstream> #include <iostream> #include <string> #include <baseexc.hpp> #include <basetype.hpp> #include <event.hpp> #include <particle.hpp> #include <trace.hpp> #include <rttask.hpp> #include <taskevt.hpp> namespace RTSim { class JSONTrace { protected: std::ofstream fd; bool first_event; void writeTaskEvent(const Task &tt, const std::string &evt_name); public: JSONTrace(const std::string& name); ~JSONTrace(); void probe(ArrEvt& e); void probe(EndEvt& e); void probe(SchedEvt& e); void probe(DeschedEvt& e); void probe(DeadEvt& e); void attachToTask(Task* t); }; } #endif <|endoftext|>
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "MainApp.h" const TCHAR* pszDefaulTime = _T("--:--"); const TCHAR* pszProgresssLoop[] = { /* 00 */ _T("Error: can not load progress script."), /* 01 */ _T("Error: can not find progress function."), /* 02 */ _T("Error: console line is too large for read buffer.") }; const TCHAR* pszConvertConsole[] = { /* 00 */ _T("Error: invalid format pipe configuration."), /* 01 */ _T("Error: can not create pipes for stderr."), /* 02 */ _T("Error: can not duplicate stderr pipe to prevent child process from closing the pipe."), /* 03 */ _T("Error: can not create command-line process (%d)."), /* 04 */ _T("Error: progress did not reach 100%."), /* 05 */ _T("Done") }; const TCHAR* pszConvertPipes[] = { /* 00 */ _T("Error: invalid format pipe configuration."), /* 01 */ _T("Error: can not create pipes for stdin."), /* 02 */ _T("Error: can not set stdin pipe inherit flag."), /* 03 */ _T("Error: can not create pipes for stdout."), /* 04 */ _T("Error: can not set stdout pipe inherit flag."), /* 05 */ _T("Error: can not create command-line process (%d)."), /* 06 */ _T("Error: can not create read thread."), /* 07 */ _T("Error: can not create write thread."), /* 08 */ _T("Error: progress did not reach 100%."), /* 09 */ _T("Error: can not create pipes for process connection."), /* 10 */ _T("Done") }; const TCHAR* pszConvertItem[] = { /* 00 */ _T("Error: can not find input file."), /* 01 */ _T("Error: can not find valid encoder by id."), /* 02 */ _T("Error: can not find encoder format preset."), /* 03 */ _T("Error: can not find valid decoder by extension."), /* 04 */ _T("Error: can not find decoder format preset."), /* 05 */ _T("Error: decoder output not supported by encoder."), /* 06 */ _T("Decoding..."), /* 07 */ _T("Error: can not find decoded file."), /* 08 */ _T("Error: exception thrown while converting file."), /* 09 */ _T("Encoding..."), /* 10 */ _T("Decoding..."), /* 11 */ _T("Processing..."), /* 12 */ _T("Error: can not find encoded file."), /* 13 */ _T("Error: exception thrown while converting file."), /* 14 */ _T("Unable to create output path!"), /* 15 */ _T("Output file already exists.") }; const TCHAR* pszWorkerContext[] = { /* 00 */ _T("Error"), /* 01 */ _T("Errors"), /* 02 */ _T("Processing item %d of %d (%d Done, %d %s)"), /* 03 */ _T("Processed %d of %d (%d Done, %d %s) in %s") }; const TCHAR* pszMainDialog[] = { /* 00 */ _T("Not Done"), /* 01 */ _T("Item"), /* 02 */ _T("Items"), /* 03 */ _T("No Items"), /* 04 */ _T("Recurse subdirectories"), /* 05 */ _T("Output path:"), /* 06 */ _T("Failed to load file!"), /* 07 */ _T("Failed to save file!"), /* 08 */ _T("Failed to allocate memory for filenames buffer!"), /* 09 */ _T("Select folder:"), /* 10 */ _T("Error while searching for language files!"), /* 11 */ _T("Error while searching for item files!"), /* 12 */ _T("Unable to create output path!"), /* 13 */ _T("Fatal error when creating thread!"), /* 14 */ _T("Invalid output path format!") }; const TCHAR* pszPresetsDialog[] = { /* 00 */ _T("ERROR"), /* 01 */ _T("Failed to load file!"), /* 02 */ _T("Failed to save file!"), /* 03 */ _T("Default") }; const TCHAR* pszFormatsDialog[] = { /* 00 */ _T("ERROR"), /* 01 */ _T("Failed to load file!"), /* 02 */ _T("Failed to save file!"), /* 03 */ _T("Format"), /* 04 */ _T("Default") }; const TCHAR* pszToolsDialog[] = { /* 00 */ _T("ERROR"), /* 01 */ _T("Failed to load file!"), /* 02 */ _T("Failed to save file!"), /* 03 */ _T("Tool") }; const TCHAR* pszFileDialogs[] = { /* 00 */ _T("All Files"), /* 01 */ _T("Xml Files"), /* 02 */ _T("Items Files"), /* 03 */ _T("Presets Files"), /* 04 */ _T("Formats Files"), /* 05 */ _T("Exe Files"), /* 06 */ _T("Progress Files"), /* 07 */ _T("Format Files"), /* 08 */ _T("Tools Files"), /* 09 */ _T("Tool Files") }; const TCHAR* pszDownloadStatus[] = { /* 00 */ _T("Finding resource..."), /* 01 */ _T("Connecting..."), /* 02 */ _T("Sending request..."), /* 03 */ _T("Mime type available"), /* 04 */ _T("Cache filename available"), /* 05 */ _T("Begin download"), /* 06 */ _T("End download"), /* 07 */ _T("Status code : ") }; const TCHAR* pszExtractStatus[] = { /* 00 */ _T("Failed to create unzip folder."), /* 01 */ _T("Unziped downloaded file."), /* 02 */ _T("Failed to unzip downloaded file.") }; <commit_msg>Add language strings<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "StdAfx.h" #include "MainApp.h" const TCHAR* pszDefaulTime = _T("--:--"); const TCHAR* pszProgresssLoop[] = { /* 00 */ _T("Error: can not load progress script."), /* 01 */ _T("Error: can not find progress function."), /* 02 */ _T("Error: console line is too large for read buffer.") }; const TCHAR* pszConvertConsole[] = { /* 00 */ _T("Error: invalid format pipe configuration."), /* 01 */ _T("Error: can not create pipes for stderr."), /* 02 */ _T("Error: can not duplicate stderr pipe to prevent child process from closing the pipe."), /* 03 */ _T("Error: can not create command-line process (%d)."), /* 04 */ _T("Error: progress did not reach 100%."), /* 05 */ _T("Done") }; const TCHAR* pszConvertPipes[] = { /* 00 */ _T("Error: invalid format pipe configuration."), /* 01 */ _T("Error: can not create pipes for stdin."), /* 02 */ _T("Error: can not set stdin pipe inherit flag."), /* 03 */ _T("Error: can not create pipes for stdout."), /* 04 */ _T("Error: can not set stdout pipe inherit flag."), /* 05 */ _T("Error: can not create command-line process (%d)."), /* 06 */ _T("Error: can not create read thread."), /* 07 */ _T("Error: can not create write thread."), /* 08 */ _T("Error: progress did not reach 100%."), /* 09 */ _T("Error: can not create pipes for process connection."), /* 10 */ _T("Done"), /* 11 */ _T("Error: can not create pipes for stderr."), /* 12 */ _T("Error: can not set stderr pipe inherit flag."), /* 13 */ _T("Error: can not create output thread.") }; const TCHAR* pszConvertItem[] = { /* 00 */ _T("Error: can not find input file."), /* 01 */ _T("Error: can not find valid encoder by id."), /* 02 */ _T("Error: can not find encoder format preset."), /* 03 */ _T("Error: can not find valid decoder by extension."), /* 04 */ _T("Error: can not find decoder format preset."), /* 05 */ _T("Error: decoder output not supported by encoder."), /* 06 */ _T("Decoding..."), /* 07 */ _T("Error: can not find decoded file."), /* 08 */ _T("Error: exception thrown while converting file."), /* 09 */ _T("Encoding..."), /* 10 */ _T("Decoding..."), /* 11 */ _T("Processing..."), /* 12 */ _T("Error: can not find encoded file."), /* 13 */ _T("Error: exception thrown while converting file."), /* 14 */ _T("Unable to create output path!"), /* 15 */ _T("Output file already exists.") }; const TCHAR* pszWorkerContext[] = { /* 00 */ _T("Error"), /* 01 */ _T("Errors"), /* 02 */ _T("Processing item %d of %d (%d Done, %d %s)"), /* 03 */ _T("Processed %d of %d (%d Done, %d %s) in %s") }; const TCHAR* pszMainDialog[] = { /* 00 */ _T("Not Done"), /* 01 */ _T("Item"), /* 02 */ _T("Items"), /* 03 */ _T("No Items"), /* 04 */ _T("Recurse subdirectories"), /* 05 */ _T("Output path:"), /* 06 */ _T("Failed to load file!"), /* 07 */ _T("Failed to save file!"), /* 08 */ _T("Failed to allocate memory for filenames buffer!"), /* 09 */ _T("Select folder:"), /* 10 */ _T("Error while searching for language files!"), /* 11 */ _T("Error while searching for item files!"), /* 12 */ _T("Unable to create output path!"), /* 13 */ _T("Fatal error when creating thread!"), /* 14 */ _T("Invalid output path format!") }; const TCHAR* pszPresetsDialog[] = { /* 00 */ _T("ERROR"), /* 01 */ _T("Failed to load file!"), /* 02 */ _T("Failed to save file!"), /* 03 */ _T("Default") }; const TCHAR* pszFormatsDialog[] = { /* 00 */ _T("ERROR"), /* 01 */ _T("Failed to load file!"), /* 02 */ _T("Failed to save file!"), /* 03 */ _T("Format"), /* 04 */ _T("Default") }; const TCHAR* pszToolsDialog[] = { /* 00 */ _T("ERROR"), /* 01 */ _T("Failed to load file!"), /* 02 */ _T("Failed to save file!"), /* 03 */ _T("Tool") }; const TCHAR* pszFileDialogs[] = { /* 00 */ _T("All Files"), /* 01 */ _T("Xml Files"), /* 02 */ _T("Items Files"), /* 03 */ _T("Presets Files"), /* 04 */ _T("Formats Files"), /* 05 */ _T("Exe Files"), /* 06 */ _T("Progress Files"), /* 07 */ _T("Format Files"), /* 08 */ _T("Tools Files"), /* 09 */ _T("Tool Files") }; const TCHAR* pszDownloadStatus[] = { /* 00 */ _T("Finding resource..."), /* 01 */ _T("Connecting..."), /* 02 */ _T("Sending request..."), /* 03 */ _T("Mime type available"), /* 04 */ _T("Cache filename available"), /* 05 */ _T("Begin download"), /* 06 */ _T("End download"), /* 07 */ _T("Status code : ") }; const TCHAR* pszExtractStatus[] = { /* 00 */ _T("Failed to create unzip folder."), /* 01 */ _T("Unziped downloaded file."), /* 02 */ _T("Failed to unzip downloaded file.") }; <|endoftext|>