hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
14504bcffa9e1671195dcc01e97e2fdefdd5cb2d
1,123
hpp
C++
03/minik/src/target_x86/x86_assembler.hpp
nokia-wroclaw/nokia-book
dd397958b5db039a2f53e555c2becfc419065264
[ "MIT" ]
104
2015-06-30T07:41:42.000Z
2022-02-28T08:56:37.000Z
03/minik/src/target_x86/x86_assembler.hpp
nokia-wroclaw/nokia-book
dd397958b5db039a2f53e555c2becfc419065264
[ "MIT" ]
null
null
null
03/minik/src/target_x86/x86_assembler.hpp
nokia-wroclaw/nokia-book
dd397958b5db039a2f53e555c2becfc419065264
[ "MIT" ]
22
2015-06-11T14:40:49.000Z
2021-12-27T19:13:11.000Z
#pragma once #include "ir/ir.hpp" #include "ir/symbol_table.hpp" enum class X86_Registers { EAX = 0, EBX = 1, ECX = 2, EDX = 3, ESI = 4, EDI = 5, EBP = 6, ESP = 7 }; struct X86_IrRegisters { static constexpr Ir::Argument EAX = Ir::Argument::PinnedHardRegister(int(X86_Registers::EAX)); static constexpr Ir::Argument EBX = Ir::Argument::PinnedHardRegister(int(X86_Registers::EBX)); static constexpr Ir::Argument ECX = Ir::Argument::PinnedHardRegister(int(X86_Registers::ECX)); static constexpr Ir::Argument EDX = Ir::Argument::PinnedHardRegister(int(X86_Registers::EDX)); static constexpr Ir::Argument ESI = Ir::Argument::PinnedHardRegister(int(X86_Registers::ESI)); static constexpr Ir::Argument EDI = Ir::Argument::PinnedHardRegister(int(X86_Registers::EDI)); static constexpr Ir::Argument EBP = Ir::Argument::PinnedSpecialHardRegister(int(X86_Registers::EBP)); static constexpr Ir::Argument ESP = Ir::Argument::PinnedSpecialHardRegister(int(X86_Registers::ESP)); }; class Assembler { public: std::string compile(const SymbolTable &symbolTable); };
31.194444
105
0.712378
nokia-wroclaw
145222f4a2d532f4a0c99e7e6175d206fc31aeba
2,187
cpp
C++
archived/VoIP/cs/VoipBackEnd/BackEndAudioHelpers.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,504
2019-05-07T06:56:42.000Z
2022-03-31T19:37:59.000Z
archived/VoIP/cs/VoipBackEnd/BackEndAudioHelpers.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
314
2019-05-08T16:56:30.000Z
2022-03-21T07:13:45.000Z
archived/VoIP/cs/VoipBackEnd/BackEndAudioHelpers.cpp
dujianxin/Windows-universal-samples
d4e95ff0ac408c5d4d980bb18d53fb2c6556a273
[ "MIT" ]
2,219
2019-05-07T00:47:26.000Z
2022-03-30T21:12:31.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "BackEndAudioHelpers.h" // release and zero out a possible NULL pointer. note this will // do the release on a temp copy to avoid reentrancy issues that can result from // callbacks durring the release template <class T> void SafeRelease(__deref_inout_opt T **ppT) { T *pTTemp = *ppT; // temp copy *ppT = nullptr; // zero the input if (pTTemp) { pTTemp->Release(); } } // Begin of audio helpers size_t inline GetWaveFormatSize(const WAVEFORMATEX& format) { return (sizeof WAVEFORMATEX) + (format.wFormatTag == WAVE_FORMAT_PCM ? 0 : format.cbSize); } void FillPcmFormat(WAVEFORMATEX& format, WORD wChannels, int nSampleRate, WORD wBits) { format.wFormatTag = WAVE_FORMAT_PCM; format.nChannels = wChannels; format.nSamplesPerSec = nSampleRate; format.wBitsPerSample = wBits; format.nBlockAlign = format.nChannels * (format.wBitsPerSample / 8); format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign; format.cbSize = 0; } size_t BytesFromDuration(int nDurationInMs, const WAVEFORMATEX& format) { return size_t(nDurationInMs * FLOAT(format.nAvgBytesPerSec) / 1000); } size_t SamplesFromDuration(int nDurationInMs, const WAVEFORMATEX& format) { return size_t(nDurationInMs * FLOAT(format.nSamplesPerSec) / 1000); } BOOL WaveFormatCompare(const WAVEFORMATEX& format1, const WAVEFORMATEX& format2) { size_t cbSizeFormat1 = GetWaveFormatSize(format1); size_t cbSizeFormat2 = GetWaveFormatSize(format2); return (cbSizeFormat1 == cbSizeFormat2) && (memcmp(&format1, &format2, cbSizeFormat1) == 0); } // End of audio helpers
34.714286
97
0.657979
dujianxin
1456e6459e974b66bbed916f106439036f953c94
4,402
cpp
C++
code/tools/popart-current1/src/networks/AncestralSeqNet.cpp
kibet-gilbert/co1_metaanalysis
1089cc03bc4dbabab543a8dadf49130d8e399665
[ "CC-BY-3.0" ]
1
2021-01-01T05:57:08.000Z
2021-01-01T05:57:08.000Z
code/tools/popart-current1/src/networks/AncestralSeqNet.cpp
kibet-gilbert/co1_metaanalysis
1089cc03bc4dbabab543a8dadf49130d8e399665
[ "CC-BY-3.0" ]
null
null
null
code/tools/popart-current1/src/networks/AncestralSeqNet.cpp
kibet-gilbert/co1_metaanalysis
1089cc03bc4dbabab543a8dadf49130d8e399665
[ "CC-BY-3.0" ]
1
2021-01-01T06:15:56.000Z
2021-01-01T06:15:56.000Z
#include "AncestralSeqNet.h" #include "NetworkError.h" #include <iostream> #include <map> #include <set> using namespace std; AncestralSeqNet::AncestralSeqNet(const vector <Sequence*> & seqvect, const vector<bool> & mask, unsigned epsilon, double alpha) : /*AbstractMSN(seqvect, mask, epsilon), */HapNet(seqvect, mask), _seqsComputed(false), _alpha(alpha) { } void AncestralSeqNet::computeGraph() { updateProgress(0); map<const string, Vertex*> seq2Vert; vector<unsigned> seqCount; vector<unsigned> edgeCount; for (unsigned i = 0; i < nseqs(); i++) { seq2Vert[seqSeq(i)] = newVertex(seqName(i), &seqSeq(i)); seqCount.push_back(0); } double progPerIter = 100./niter(); double prog; for (unsigned i = 0; i < niter(); i++) { const list<pair<const string, const string> > edgelist = sampleEdge(); // for each edge, check to see if sequences are new. If neither new, check to see if already adjacent list<pair<const string, const string> >::const_iterator edgeIt = edgelist.begin(); set<unsigned> verticesSeen; set<unsigned> edgesSeen; while (edgeIt != edgelist.end()) { string seqFrom(edgeIt->first); string seqTo(edgeIt->second); bool seqFromNew = false; bool seqToNew = false; Vertex *u, *v; map<const string, Vertex *>::iterator seqIt = seq2Vert.find(seqFrom); if (seqIt != seq2Vert.end()) { u = seqIt->second; verticesSeen.insert(u->index()); } else { u = newVertex(""); seq2Vert[seqFrom] = u; verticesSeen.insert(u->index()); seqFromNew = true; } seqIt = seq2Vert.find(seqTo); if (seqIt != seq2Vert.end()) { v = seqIt->second; verticesSeen.insert(v->index()); } else { v = newVertex(""); seq2Vert[seqTo] = v; verticesSeen.insert(v->index()); seqToNew = true; } if (seqToNew || seqFromNew) { double weight = pairwiseDistance(seqFrom, seqTo); Edge *e = newEdge(u, v, weight); edgesSeen.insert(e->index()); } else if (u != v && ! v->isAdjacent(u)) { double weight = pairwiseDistance(seqFrom, seqTo); Edge *e = newEdge(u, v, weight); edgesSeen.insert(e->index()); } else if (u != v) { const Edge *e = v->sharedEdge(u); edgesSeen.insert(e->index()); } ++edgeIt; } set<unsigned>::const_iterator idxIt = verticesSeen.begin(); while (idxIt != verticesSeen.end()) { if (*idxIt >= seqCount.size()) seqCount.resize(*idxIt + 1, 0); seqCount.at(*idxIt) += 1; ++idxIt; } idxIt = edgesSeen.begin(); while (idxIt != edgesSeen.end()) { if (*idxIt >= edgeCount.size()) edgeCount.resize(*idxIt + 1, 0); edgeCount.at(*idxIt) += 1; ++idxIt; } prog = (i + 1) * progPerIter; updateProgress(prog); } //cout << *(dynamic_cast<Graph*>(this)) << endl; priority_queue<pair<double, Edge*>, vector<pair<double, Edge*> >, greater<pair<double, Edge*> > > edgeQ; for (unsigned i = 0; i < edgeCount.size(); i++) { double edgeFreq = (double)edgeCount.at(i)/niter(); if (edgeFreq < _alpha) edgeQ.push(pair<double, Edge*>(edgeFreq, edge(i))); } while (! edgeQ.empty()) { Edge *e = edgeQ.top().second; double weight = e->weight(); Vertex *u = vertex(e->from()->index()); Vertex *v = vertex(e->to()->index()); //unsigned idx = e->index(); removeEdge(e->index()); if (! areConnected(u, v)) newEdge(u, v, weight); edgeQ.pop(); } for (unsigned i = seqCount.size(); i > nseqs(); i--) { if (vertex(i-1)->degree() <= 1) { removeVertex(i - 1); } } updateProgress(100); } void AncestralSeqNet::setDistance(unsigned dist, unsigned i, unsigned j) { unsigned totalCount = nseqs() + ancestorCount(); if (i >= totalCount || j >= totalCount) throw NetworkError("Invalid index."); _distances.at(i).at(j) = dist; } unsigned AncestralSeqNet::distance(unsigned i, unsigned j) const { unsigned totalCount = nseqs() + ancestorCount(); if (i >= totalCount || j >= totalCount) throw NetworkError("Invalid index."); return _distances.at(i).at(j); }
22.232323
128
0.57224
kibet-gilbert
1457c8bf087de1d2746c8dfc46da03537892a899
914
hpp
C++
shared_model/backend/protobuf/commands/proto_command.hpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
shared_model/backend/protobuf/commands/proto_command.hpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
shared_model/backend/protobuf/commands/proto_command.hpp
coderintherye/iroha
68509282851130c9818f21acef1ef28e53622315
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_SHARED_MODEL_PROTO_COMMAND_HPP #define IROHA_SHARED_MODEL_PROTO_COMMAND_HPP #include "interfaces/commands/command.hpp" #include "commands.pb.h" namespace shared_model { namespace proto { class Command final : public interface::Command { public: using TransportType = iroha::protocol::Command; Command(const Command &o); Command(Command &&o) noexcept; explicit Command(const TransportType &ref); explicit Command(TransportType &&ref); ~Command() override; const CommandVariantType &get() const override; protected: Command *clone() const override; private: struct Impl; std::unique_ptr<Impl> impl_; }; } // namespace proto } // namespace shared_model #endif // IROHA_SHARED_MODEL_PROTO_COMMAND_HPP
22.292683
53
0.696937
coderintherye
14615a1c0b433382482e1be95e9571a599fef25b
1,959
hpp
C++
src/pyprx/utilities/data_structures/tree_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
3
2021-05-31T11:28:03.000Z
2021-05-31T13:49:30.000Z
src/pyprx/utilities/data_structures/tree_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
1
2021-09-03T09:39:32.000Z
2021-12-10T22:17:56.000Z
src/pyprx/utilities/data_structures/tree_py.hpp
aravindsiv/ML4KP
064015a7545e1713cbcad3e79807b5cec0849f54
[ "MIT" ]
2
2021-09-03T09:17:45.000Z
2021-10-04T15:52:58.000Z
#include "prx/utilities/data_structures/tree.hpp" PRX_SETTER(tree_t, vertex_id_counter) PRX_GETTER(tree_t, vertex_id_counter) void pyprx_utilities_data_structures_tree_py() { class_<prx::tree_node_t, std::shared_ptr<prx::tree_node_t>, bases<prx::abstract_node_t>>("tree_node", init<>()) .def("get_parent", &prx::tree_node_t::get_parent) .def("get_index", &prx::tree_node_t::get_index) .def("get_parent_edge", &prx::tree_node_t::get_parent_edge) .def("get_children", &prx::tree_node_t::get_children, return_internal_reference<>()) ; class_<prx::tree_edge_t, std::shared_ptr<prx::tree_edge_t>, bases<prx::abstract_edge_t>, boost::noncopyable>("tree_edge", no_init) .def("__init__", make_constructor(&init_as_ptr<prx::tree_edge_t>, default_call_policies())) .def("get_index", &prx::tree_edge_t::get_index) .def("get_source", &prx::tree_edge_t::get_source) .def("get_target", &prx::tree_edge_t::get_target) ; class_<prx::tree_t, std::shared_ptr<prx::tree_t>>("tree", init<>()) .def("allocate_memory", &prx::tree_t::allocate_memory<prx::tree_node_t, prx::tree_edge_t>) .def("add_vertex", &prx::tree_t::add_vertex<prx::tree_node_t, prx::tree_edge_t>) .def("get_vertex_as", &prx::tree_t::get_vertex_as<prx::tree_node_t>) .def("get_edge_as", &prx::tree_t::get_edge_as<prx::tree_edge_t>) .def("num_vertices", &prx::tree_t::num_vertices) .def("num_edges", &prx::tree_t::num_edges) .def("is_leaf", &prx::tree_t::is_leaf) .def("edge", &prx::tree_t::edge) .def("add_edge", &prx::tree_t::add_edge) .def("add_safety_edge", &prx::tree_t::add_safety_edge) .def("get_depth", &prx::tree_t::get_depth) .def("remove_vertex", &prx::tree_t::remove_vertex) .def("purge", &prx::tree_t::purge) .def("clear", &prx::tree_t::clear) .def("transplant", &prx::tree_t::transplant) .add_property("vertex_id_counter", &get_tree_t_vertex_id_counter<unsigned>, &set_tree_t_vertex_id_counter<unsigned>) // .def("", &prx::tree_t::) ; }
47.780488
131
0.722818
aravindsiv
14615b5b73d4ba2cf77c592fdece8422a32c6dc2
300
cpp
C++
libraries/lib-components/ConfigInterface.cpp
IshoAntar/AudMonkey
c9180745529960b147b49f659c4295d7dffb888c
[ "CC-BY-3.0" ]
41
2021-07-07T13:22:16.000Z
2022-03-15T19:46:27.000Z
libraries/lib-components/ConfigInterface.cpp
BeaterTeam/Beater
e92b0b85986d51e40fcccb41fec61bd261fc52e6
[ "CC-BY-3.0" ]
41
2021-07-07T16:47:48.000Z
2022-02-23T03:43:25.000Z
libraries/lib-components/ConfigInterface.cpp
TheEvilSkeleton/AudMonkey
848d951c3d4acf2687a9c83ece71de5940d0546c
[ "CC-BY-3.0" ]
6
2021-07-07T09:39:48.000Z
2021-12-28T01:06:58.000Z
/********************************************************************** AudMonkey: A Digital Audio Editor @file ConfigInterface.cpp **********************************************************************/ #include "ConfigInterface.h" ConfigClientInterface::~ConfigClientInterface() = default;
27.272727
71
0.406667
IshoAntar
1464a693e0bf3899f6f9ecd6df73fdef4395e068
4,822
cpp
C++
src/common.cpp
EDM-Developers/fastEDM
9724bf609d09beae53a89ca5cbe52d407787dbf2
[ "MIT" ]
2
2021-04-27T00:21:57.000Z
2022-01-23T03:46:04.000Z
src/common.cpp
EDM-Developers/fastEDM
9724bf609d09beae53a89ca5cbe52d407787dbf2
[ "MIT" ]
null
null
null
src/common.cpp
EDM-Developers/fastEDM
9724bf609d09beae53a89ca5cbe52d407787dbf2
[ "MIT" ]
1
2021-09-17T17:14:07.000Z
2021-09-17T17:14:07.000Z
#include "common.h" #ifdef JSON void to_json(json& j, const Algorithm& a) { if (a == Algorithm::Simplex) { j = "Simplex"; } else { j = "SMap"; } } void from_json(const json& j, Algorithm& a) { if (j == "Simplex") { a = Algorithm::Simplex; } else { a = Algorithm::SMap; } } void to_json(json& j, const Distance& d) { if (d == Distance::MeanAbsoluteError) { j = "MeanAbsoluteError"; } else if (d == Distance::Euclidean) { j = "Euclidean"; } else { j = "Wasserstein"; } } void from_json(const json& j, Distance& d) { if (j == "MeanAbsoluteError") { d = Distance::MeanAbsoluteError; } else if (j == "Euclidean") { d = Distance::Euclidean; } else { d = Distance::Wasserstein; } } void to_json(json& j, const Metric& m) { if (m == Metric::Diff) { j = "Diff"; } else { j = "CheckSame"; } } void from_json(const json& j, Metric& m) { if (j == "Diff") { m = Metric::Diff; } else { m = Metric::CheckSame; } } void to_json(json& j, const Options& o) { j = json{ { "copredict", o.copredict }, { "forceCompute", o.forceCompute }, { "savePrediction", o.savePrediction }, { "saveSMAPCoeffs", o.saveSMAPCoeffs }, { "k", o.k }, { "nthreads", o.nthreads }, { "missingdistance", o.missingdistance }, { "panelMode", o.panelMode }, { "idw", o.idw }, { "thetas", o.thetas }, { "algorithm", o.algorithm }, { "taskNum", o.taskNum }, { "numTasks", o.numTasks }, { "configNum", o.configNum }, { "calcRhoMAE", o.calcRhoMAE }, { "aspectRatio", o.aspectRatio }, { "distance", o.distance }, { "metrics", o.metrics }, { "cmdLine", o.cmdLine } }; } void from_json(const json& j, Options& o) { j.at("copredict").get_to(o.copredict); j.at("forceCompute").get_to(o.forceCompute); j.at("savePrediction").get_to(o.savePrediction); j.at("saveSMAPCoeffs").get_to(o.saveSMAPCoeffs); j.at("k").get_to(o.k); j.at("nthreads").get_to(o.nthreads); j.at("missingdistance").get_to(o.missingdistance); j.at("panelMode").get_to(o.panelMode); j.at("idw").get_to(o.idw); j.at("thetas").get_to(o.thetas); j.at("algorithm").get_to(o.algorithm); j.at("taskNum").get_to(o.taskNum); j.at("numTasks").get_to(o.numTasks); j.at("configNum").get_to(o.configNum); j.at("calcRhoMAE").get_to(o.calcRhoMAE); j.at("aspectRatio").get_to(o.aspectRatio); j.at("distance").get_to(o.distance); j.at("metrics").get_to(o.metrics); j.at("cmdLine").get_to(o.cmdLine); } void to_json(json& j, const PredictionStats& s) { j = json{ { "mae", s.mae }, { "rho", s.rho } }; } void from_json(const json& j, PredictionStats& s) { j.at("mae").get_to(s.mae); j.at("rho").get_to(s.rho); } void to_json(json& j, const PredictionResult& p) { std::vector<double> predictionsVec, coeffsVec; if (p.predictions != nullptr) { predictionsVec = std::vector<double>(p.predictions.get(), p.predictions.get() + p.numThetas * p.numPredictions); } if (p.coeffs != nullptr) { coeffsVec = std::vector<double>(p.coeffs.get(), p.coeffs.get() + p.numPredictions * p.numCoeffCols); } j = json{ { "rc", p.rc }, { "numThetas", p.numThetas }, { "numPredictions", p.numPredictions }, { "numCoeffCols", p.numCoeffCols }, { "predictions", predictionsVec }, { "coeffs", coeffsVec }, { "stats", p.stats }, { "predictionRows", p.predictionRows }, { "kMin", p.kMin }, { "kMax", p.kMax }, { "cmdLine", p.cmdLine }, { "configNum", p.configNum } }; } void from_json(const json& j, PredictionResult& p) { j.at("rc").get_to(p.rc); j.at("numThetas").get_to(p.numThetas); j.at("numPredictions").get_to(p.numPredictions); j.at("numCoeffCols").get_to(p.numCoeffCols); j.at("predictionRows").get_to(p.predictionRows); j.at("stats").get_to(p.stats); j.at("kMin").get_to(p.kMin); j.at("kMax").get_to(p.kMax); j.at("cmdLine").get_to(p.cmdLine); j.at("configNum").get_to(p.configNum); // TODO: Test this coeffs/predictions loading works as expected std::vector<double> predictions = j.at("predictions"); if (predictions.size()) { p.predictions = std::make_unique<double[]>(predictions.size()); for (int i = 0; i < predictions.size(); i++) { p.predictions[i] = predictions[i]; } } else { p.predictions = nullptr; } std::vector<double> coeffs = j.at("coeffs"); if (coeffs.size()) { p.coeffs = std::make_unique<double[]>(coeffs.size()); for (int i = 0; i < coeffs.size(); i++) { p.coeffs[i] = coeffs[i]; } } else { p.coeffs = nullptr; } } #endif
26.938547
116
0.575695
EDM-Developers
14654be2919a8e5540b4da26a314d92537de6679
9,967
cpp
C++
src/manager.cpp
openbmc/bios-settings-mgr
29656f07b7e81c0bb13ca119b4c6ef62f5e79a18
[ "Apache-2.0" ]
1
2021-12-13T03:53:38.000Z
2021-12-13T03:53:38.000Z
src/manager.cpp
openbmc/bios-settings-mgr
29656f07b7e81c0bb13ca119b4c6ef62f5e79a18
[ "Apache-2.0" ]
2
2020-12-03T10:28:49.000Z
2022-03-02T05:47:32.000Z
src/manager.cpp
openbmc/bios-settings-mgr
29656f07b7e81c0bb13ca119b4c6ef62f5e79a18
[ "Apache-2.0" ]
1
2021-12-13T03:53:31.000Z
2021-12-13T03:53:31.000Z
/* // Copyright (c) 2020 Intel Corporation // // 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 "manager.hpp" #include "manager_serialize.hpp" #include "xyz/openbmc_project/BIOSConfig/Common/error.hpp" #include "xyz/openbmc_project/Common/error.hpp" #include <boost/asio.hpp> #include <phosphor-logging/elog-errors.hpp> #include <sdbusplus/asio/connection.hpp> #include <sdbusplus/asio/object_server.hpp> namespace bios_config { using namespace sdbusplus::xyz::openbmc_project::Common::Error; using namespace sdbusplus::xyz::openbmc_project::BIOSConfig::Common::Error; void Manager::setAttribute(AttributeName attribute, AttributeValue value) { auto pendingAttrs = Base::pendingAttributes(); auto iter = pendingAttrs.find(attribute); if (iter != pendingAttrs.end()) { std::get<1>(iter->second) = value; } else { Manager::PendingAttribute attributeValue; if (std::get_if<int64_t>(&value)) { std::get<0>(attributeValue) = AttributeType::Integer; } else { std::get<0>(attributeValue) = AttributeType::String; } std::get<1>(attributeValue) = value; pendingAttrs.emplace(attribute, attributeValue); } pendingAttributes(pendingAttrs); } Manager::AttributeDetails Manager::getAttribute(AttributeName attribute) { Manager::AttributeDetails value; auto table = Base::baseBIOSTable(); auto iter = table.find(attribute); if (iter != table.end()) { std::get<0>(value) = std::get<static_cast<uint8_t>(Index::attributeType)>(iter->second); std::get<1>(value) = std::get<static_cast<uint8_t>(Index::currentValue)>(iter->second); auto pending = Base::pendingAttributes(); auto pendingIter = pending.find(attribute); if (pendingIter != pending.end()) { std::get<2>(value) = std::get<1>(pendingIter->second); } else if (std::get_if<std::string>(&std::get<1>(value))) { std::get<2>(value) = std::string(); } } else { throw AttributeNotFound(); } return value; } Manager::BaseTable Manager::baseBIOSTable(BaseTable value) { pendingAttributes({}); auto baseTable = Base::baseBIOSTable(value, false); serialize(*this, biosFile); Base::resetBIOSSettings(Base::ResetFlag::NoAction); return baseTable; } Manager::PendingAttributes Manager::pendingAttributes(PendingAttributes value) { // Clear the pending attributes if (value.empty()) { auto pendingAttrs = Base::pendingAttributes({}, false); serialize(*this, biosFile); return pendingAttrs; } // Validate all the BIOS attributes before setting PendingAttributes BaseTable biosTable = Base::baseBIOSTable(); for (const auto& pair : value) { auto iter = biosTable.find(pair.first); // BIOS attribute not found in the BaseBIOSTable if (iter == biosTable.end()) { phosphor::logging::log<phosphor::logging::level::ERR>( "BIOS attribute not found in the BaseBIOSTable"); throw AttributeNotFound(); } auto attributeType = std::get<static_cast<uint8_t>(Index::attributeType)>(iter->second); if (attributeType != std::get<0>(pair.second)) { phosphor::logging::log<phosphor::logging::level::ERR>( "attributeType is not same with bios base table"); throw InvalidArgument(); } // Validate enumeration BIOS attributes if (attributeType == AttributeType::Enumeration) { // For enumeration the expected variant types is Enumeration if (std::get<1>(pair.second).index() == 0) { phosphor::logging::log<phosphor::logging::level::ERR>( "Enumeration property value is not enum"); throw InvalidArgument(); } const auto& attrValue = std::get<std::string>(std::get<1>(pair.second)); const auto& options = std::get<static_cast<uint8_t>(Index::options)>(iter->second); bool found = false; for (const auto& enumOptions : options) { if ((BoundType::OneOf == std::get<0>(enumOptions)) && (attrValue == std::get<std::string>(std::get<1>(enumOptions)))) { found = true; break; } } if (!found) { phosphor::logging::log<phosphor::logging::level::ERR>( "No valid attribute"); throw InvalidArgument(); } } if (attributeType == AttributeType::String) { // For enumeration the expected variant types is std::string if (std::get<1>(pair.second).index() == 0) { phosphor::logging::log<phosphor::logging::level::ERR>( "String property value is not string"); throw InvalidArgument(); } const auto& attrValue = std::get<std::string>(std::get<1>(pair.second)); const auto& options = std::get<static_cast<uint8_t>(Index::options)>(iter->second); auto optionsIterator = options.begin(); for (; optionsIterator != options.end(); ++optionsIterator) { if (std::get<1>(std::get<1>(*optionsIterator)) == attrValue) { break; } } if (optionsIterator == options.end()) { std::string error = attrValue + " is not a valid value for " + pair.first; phosphor::logging::log<phosphor::logging::level::ERR>( error.c_str()); throw InvalidArgument(); } } if (attributeType == AttributeType::Integer) { // For enumeration the expected variant types is Integer if (std::get<1>(pair.second).index() == 1) { phosphor::logging::log<phosphor::logging::level::ERR>( "Enumeration property value is not int"); throw InvalidArgument(); } const auto& attrValue = std::get<int64_t>(std::get<1>(pair.second)); const auto& options = std::get<static_cast<uint8_t>(Index::options)>(iter->second); int64_t lowerBound = 0; int64_t upperBound = 0; int64_t scalarIncrement = 0; for (const auto& integerOptions : options) { if (BoundType::LowerBound == std::get<0>(integerOptions)) { lowerBound = std::get<int64_t>(std::get<1>(integerOptions)); } else if (BoundType::UpperBound == std::get<0>(integerOptions)) { upperBound = std::get<int64_t>(std::get<1>(integerOptions)); } else if (BoundType::ScalarIncrement == std::get<0>(integerOptions)) { scalarIncrement = std::get<int64_t>(std::get<1>(integerOptions)); } } if ((attrValue < lowerBound) || (attrValue > upperBound)) { phosphor::logging::log<phosphor::logging::level::ERR>( "Integer, bound is invalid"); throw InvalidArgument(); } if (((std::abs(attrValue - lowerBound)) % scalarIncrement) != 0) { phosphor::logging::log<phosphor::logging::level::ERR>( "((std::abs(attrValue - lowerBound)) % scalarIncrement) != " "0"); throw InvalidArgument(); } } } PendingAttributes pendingAttribute = Base::pendingAttributes(); for (const auto& pair : value) { auto iter = pendingAttribute.find(pair.first); if (iter != pendingAttribute.end()) { iter = pendingAttribute.erase(iter); } pendingAttribute.emplace(std::make_pair(pair.first, pair.second)); } auto pendingAttrs = Base::pendingAttributes(pendingAttribute, false); serialize(*this, biosFile); return pendingAttrs; } Manager::Manager(sdbusplus::asio::object_server& objectServer, std::shared_ptr<sdbusplus::asio::connection>& systemBus) : sdbusplus::xyz::openbmc_project::BIOSConfig::server::Manager(*systemBus, objectPath), objServer(objectServer), systemBus(systemBus) { fs::path biosDir(BIOS_PERSIST_PATH); fs::create_directories(biosDir); biosFile = biosDir / biosPersistFile; deserialize(biosFile, *this); } } // namespace bios_config int main() { boost::asio::io_service io; auto systemBus = std::make_shared<sdbusplus::asio::connection>(io); systemBus->request_name(bios_config::service); sdbusplus::asio::object_server objectServer(systemBus); bios_config::Manager manager(objectServer, systemBus); io.run(); return 0; }
32.786184
80
0.562757
openbmc
14670a76bd33d6a34a71529f0856211c03120f06
36,873
cpp
C++
apps/camera-calib/camera_calib_guiMain.cpp
waltzrobotics/mrpt
540c52cebd4b7c31b104ebbeec369c800d73aa44
[ "BSD-3-Clause" ]
1
2019-05-08T18:58:54.000Z
2019-05-08T18:58:54.000Z
apps/camera-calib/camera_calib_guiMain.cpp
waltzrobotics/mrpt
540c52cebd4b7c31b104ebbeec369c800d73aa44
[ "BSD-3-Clause" ]
null
null
null
apps/camera-calib/camera_calib_guiMain.cpp
waltzrobotics/mrpt
540c52cebd4b7c31b104ebbeec369c800d73aa44
[ "BSD-3-Clause" ]
null
null
null
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ /*--------------------------------------------------------------- APPLICATION: Camera calibration GUI AUTHOR: Jose Luis Blanco, based on code from the OpenCV library. ---------------------------------------------------------------*/ #include "camera_calib_guiMain.h" #include "CDlgCalibWizardOnline.h" #include "CDlgPoseEst.h" //(*InternalHeaders(camera_calib_guiDialog) #include <wx/settings.h> #include <wx/font.h> #include <wx/intl.h> #include <wx/string.h> //*) #include <wx/filedlg.h> #include <wx/msgdlg.h> #include <wx/progdlg.h> #include <mrpt/gui/WxUtils.h> #include <mrpt/system/filesystem.h> #include <mrpt/opengl/CGridPlaneXY.h> #include <mrpt/opengl/stock_objects.h> #include <fstream> #include <iostream> #include <Eigen/Dense> #include <mrpt/vision/pnp_algos.h> using namespace mrpt; using namespace mrpt::math; using namespace mrpt::img; using namespace mrpt::vision; using namespace mrpt::gui; using namespace std; #include <mrpt/gui/CMyRedirector.h> #include <mrpt/gui/about_box.h> #define USE_EXTERNAL_STORAGE_IMGS 1 // VARIABLES ================================ TCalibrationImageList lst_images; // Here are all the images: file_name -> data mrpt::img::TCamera camera_params; // END VARIABLES ============================ #include "imgs/icono_main.xpm" #include "../wx-common/mrpt_logo.xpm" // A custom Art provider for customizing the icons: class MyArtProvider : public wxArtProvider { protected: wxBitmap CreateBitmap( const wxArtID& id, const wxArtClient& client, const wxSize& size) override; }; // CreateBitmap function wxBitmap MyArtProvider::CreateBitmap( const wxArtID& id, const wxArtClient& client, const wxSize& size) { if (id == wxART_MAKE_ART_ID(MAIN_ICON)) return wxBitmap(icono_main_xpm); if (id == wxART_MAKE_ART_ID(IMG_MRPT_LOGO)) return wxBitmap(mrpt_logo_xpm); // Any wxWidgets icons not implemented here // will be provided by the default art provider. return wxNullBitmap; } //(*IdInit(camera_calib_guiDialog) const long camera_calib_guiDialog::ID_BUTTON8 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON1 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON2 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON9 = wxNewId(); const long camera_calib_guiDialog::ID_LISTBOX1 = wxNewId(); const long camera_calib_guiDialog::ID_STATICTEXT5 = wxNewId(); const long camera_calib_guiDialog::ID_CHOICE1 = wxNewId(); const long camera_calib_guiDialog::ID_STATICTEXT1 = wxNewId(); const long camera_calib_guiDialog::ID_SPINCTRL1 = wxNewId(); const long camera_calib_guiDialog::ID_STATICTEXT2 = wxNewId(); const long camera_calib_guiDialog::ID_SPINCTRL2 = wxNewId(); const long camera_calib_guiDialog::ID_RADIOBOX1 = wxNewId(); const long camera_calib_guiDialog::ID_STATICTEXT3 = wxNewId(); const long camera_calib_guiDialog::ID_TEXTCTRL1 = wxNewId(); const long camera_calib_guiDialog::ID_STATICTEXT6 = wxNewId(); const long camera_calib_guiDialog::ID_TEXTCTRL3 = wxNewId(); const long camera_calib_guiDialog::ID_CHECKBOX1 = wxNewId(); const long camera_calib_guiDialog::ID_TEXTCTRL2 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON3 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON6 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON7 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON5 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON4 = wxNewId(); const long camera_calib_guiDialog::ID_CUSTOM2 = wxNewId(); const long camera_calib_guiDialog::ID_SCROLLEDWINDOW2 = wxNewId(); const long camera_calib_guiDialog::ID_PANEL2 = wxNewId(); const long camera_calib_guiDialog::ID_CUSTOM1 = wxNewId(); const long camera_calib_guiDialog::ID_SCROLLEDWINDOW3 = wxNewId(); const long camera_calib_guiDialog::ID_PANEL3 = wxNewId(); const long camera_calib_guiDialog::ID_XY_GLCANVAS = wxNewId(); const long camera_calib_guiDialog::ID_PANEL1 = wxNewId(); const long camera_calib_guiDialog::ID_NOTEBOOK1 = wxNewId(); const long camera_calib_guiDialog::ID_BUTTON10 = wxNewId(); //*) BEGIN_EVENT_TABLE(camera_calib_guiDialog, wxDialog) //(*EventTable(camera_calib_guiDialog) //*) END_EVENT_TABLE() camera_calib_guiDialog::camera_calib_guiDialog(wxWindow* parent, wxWindowID id) { // Load my custom icons: #if wxCHECK_VERSION(2, 8, 0) wxArtProvider::Push(new MyArtProvider); #else wxArtProvider::PushProvider(new MyArtProvider); #endif //(*Initialize(camera_calib_guiDialog) wxStaticBoxSizer* StaticBoxSizer2; wxFlexGridSizer* FlexGridSizer4; wxFlexGridSizer* FlexGridSizer16; wxStaticBoxSizer* StaticBoxSizer4; wxFlexGridSizer* FlexGridSizer10; wxFlexGridSizer* FlexGridSizer3; wxFlexGridSizer* FlexGridSizer5; wxFlexGridSizer* FlexGridSizer9; wxFlexGridSizer* FlexGridSizer2; wxFlexGridSizer* FlexGridSizer7; wxStaticBoxSizer* StaticBoxSizer3; wxFlexGridSizer* FlexGridSizer15; wxFlexGridSizer* FlexGridSizer18; wxFlexGridSizer* FlexGridSizer8; wxFlexGridSizer* FlexGridSizer13; wxFlexGridSizer* FlexGridSizer12; wxFlexGridSizer* FlexGridSizer6; wxStaticBoxSizer* StaticBoxSizer1; wxFlexGridSizer* FlexGridSizer1; wxFlexGridSizer* FlexGridSizer17; wxStaticBoxSizer* StaticBoxSizer5; Create( parent, id, _("Camera calibration GUI - Part of the MRPT project"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER | wxMAXIMIZE_BOX, _T("id")); FlexGridSizer1 = new wxFlexGridSizer(1, 2, 0, 0); FlexGridSizer1->AddGrowableCol(1); FlexGridSizer1->AddGrowableRow(0); FlexGridSizer2 = new wxFlexGridSizer(3, 1, 0, 0); FlexGridSizer2->AddGrowableCol(0); FlexGridSizer2->AddGrowableRow(0); FlexGridSizer2->AddGrowableRow(2); StaticBoxSizer1 = new wxStaticBoxSizer(wxHORIZONTAL, this, _("List of images")); FlexGridSizer4 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer4->AddGrowableCol(0); FlexGridSizer4->AddGrowableRow(1); FlexGridSizer5 = new wxFlexGridSizer(0, 4, 0, 0); btnCaptureNow = new wxButton( this, ID_BUTTON8, _("Grab now..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON8")); wxFont btnCaptureNowFont( wxDEFAULT, wxDEFAULT, wxFONTSTYLE_NORMAL, wxBOLD, false, wxEmptyString, wxFONTENCODING_DEFAULT); btnCaptureNow->SetFont(btnCaptureNowFont); FlexGridSizer5->Add( btnCaptureNow, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); btnPoseEstimateNow = new wxButton( this, ID_BUTTON10, _("Pose Est. now..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON10")); wxFont btnPoseEstimateNowFont( wxDEFAULT, wxDEFAULT, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_BOLD, false, wxEmptyString, wxFONTENCODING_DEFAULT); btnPoseEstimateNow->SetFont(btnPoseEstimateNowFont); FlexGridSizer5->Add( btnPoseEstimateNow, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); Button11 = new wxButton( this, ID_BUTTON1, _("Add image(s)..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1")); FlexGridSizer5->Add( Button11, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); Button22 = new wxButton( this, ID_BUTTON2, _("Clear all"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2")); FlexGridSizer5->Add( Button22, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); btnSaveImages = new wxButton( this, ID_BUTTON9, _("Save all..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON9")); btnSaveImages->Disable(); FlexGridSizer5->Add( btnSaveImages, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); FlexGridSizer4->Add( FlexGridSizer5, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 0); FlexGridSizer15 = new wxFlexGridSizer(1, 2, 0, 0); FlexGridSizer15->AddGrowableCol(0); FlexGridSizer15->AddGrowableRow(0); lbFiles = new wxListBox( this, ID_LISTBOX1, wxDefaultPosition, wxSize(294, 84), 0, nullptr, wxLB_ALWAYS_SB | wxVSCROLL | wxHSCROLL | wxALWAYS_SHOW_SB, wxDefaultValidator, _T("ID_LISTBOX1")); FlexGridSizer15->Add( lbFiles, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); FlexGridSizer16 = new wxFlexGridSizer(0, 1, 0, 0); StaticText5 = new wxStaticText( this, ID_STATICTEXT5, _("Zoom:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT5")); FlexGridSizer16->Add( StaticText5, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); cbZoom = new wxChoice( this, ID_CHOICE1, wxDefaultPosition, wxDefaultSize, 0, nullptr, 0, wxDefaultValidator, _T("ID_CHOICE1")); cbZoom->Append(_("25%")); cbZoom->Append(_("50%")); cbZoom->Append(_("75%")); cbZoom->SetSelection(cbZoom->Append(_("100%"))); cbZoom->Append(_("150%")); cbZoom->Append(_("200%")); cbZoom->Append(_("300%")); cbZoom->Append(_("400%")); cbZoom->Append(_("500%")); FlexGridSizer16->Add( cbZoom, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); FlexGridSizer15->Add( FlexGridSizer16, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer4->Add( FlexGridSizer15, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); StaticBoxSizer1->Add( FlexGridSizer4, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer2->Add( StaticBoxSizer1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2); StaticBoxSizer3 = new wxStaticBoxSizer( wxHORIZONTAL, this, _("Checkerboard detection parameters")); FlexGridSizer6 = new wxFlexGridSizer(2, 2, 0, 0); FlexGridSizer6->AddGrowableCol(0); FlexGridSizer6->AddGrowableCol(1); StaticBoxSizer4 = new wxStaticBoxSizer( wxHORIZONTAL, this, _("Number of inner corners: ")); FlexGridSizer17 = new wxFlexGridSizer(1, 4, 0, 0); StaticText1 = new wxStaticText( this, ID_STATICTEXT1, _("In X:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT1")); FlexGridSizer17->Add( StaticText1, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); edSizeX = new wxSpinCtrl( this, ID_SPINCTRL1, _T("9"), wxDefaultPosition, wxSize(50, -1), 0, 1, 200, 5, _T("ID_SPINCTRL1")); edSizeX->SetValue(_T("9")); FlexGridSizer17->Add( edSizeX, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); StaticText2 = new wxStaticText( this, ID_STATICTEXT2, _("In Y:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT2")); FlexGridSizer17->Add( StaticText2, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); edSizeY = new wxSpinCtrl( this, ID_SPINCTRL2, _T("6"), wxDefaultPosition, wxSize(50, -1), 0, 1, 200, 8, _T("ID_SPINCTRL2")); edSizeY->SetValue(_T("6")); FlexGridSizer17->Add( edSizeY, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer4->Add( FlexGridSizer17, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer6->Add( StaticBoxSizer4, 1, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, 2); wxString __wxRadioBoxChoices_1[2] = {_("OpenCV\'s default"), _("Scaramuzza et al.\'s")}; rbMethod = new wxRadioBox( this, ID_RADIOBOX1, _(" Detector method: "), wxDefaultPosition, wxDefaultSize, 2, __wxRadioBoxChoices_1, 1, 0, wxDefaultValidator, _T("ID_RADIOBOX1")); FlexGridSizer6->Add( rbMethod, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2); StaticBoxSizer5 = new wxStaticBoxSizer(wxHORIZONTAL, this, _(" Size of quads (in mm): ")); FlexGridSizer18 = new wxFlexGridSizer(1, 4, 0, 0); StaticText3 = new wxStaticText( this, ID_STATICTEXT3, _("In X:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT3")); FlexGridSizer18->Add( StaticText3, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); edLengthX = new wxTextCtrl( this, ID_TEXTCTRL1, _("25.0"), wxDefaultPosition, wxSize(40, -1), 0, wxDefaultValidator, _T("ID_TEXTCTRL1")); FlexGridSizer18->Add( edLengthX, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); StaticText6 = new wxStaticText( this, ID_STATICTEXT6, _("In Y:"), wxDefaultPosition, wxDefaultSize, 0, _T("ID_STATICTEXT6")); FlexGridSizer18->Add( StaticText6, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); edLengthY = new wxTextCtrl( this, ID_TEXTCTRL3, _("25.0"), wxDefaultPosition, wxSize(40, -1), 0, wxDefaultValidator, _T("ID_TEXTCTRL3")); FlexGridSizer18->Add( edLengthY, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer5->Add( FlexGridSizer18, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer6->Add( StaticBoxSizer5, 1, wxALL | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL, 2); cbNormalize = new wxCheckBox( this, ID_CHECKBOX1, _("Normalize image"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1")); cbNormalize->SetValue(true); FlexGridSizer6->Add( cbNormalize, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer3->Add( FlexGridSizer6, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer2->Add( StaticBoxSizer3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2); StaticBoxSizer2 = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Calibration")); FlexGridSizer7 = new wxFlexGridSizer(2, 1, 0, 0); FlexGridSizer7->AddGrowableCol(0); FlexGridSizer7->AddGrowableRow(0); FlexGridSizer9 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer9->AddGrowableCol(0); FlexGridSizer9->AddGrowableRow(0); txtLog = new wxTextCtrl( this, ID_TEXTCTRL2, _("(Calibration results)"), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE | wxTE_READONLY | wxHSCROLL | wxVSCROLL, wxDefaultValidator, _T("ID_TEXTCTRL2")); wxFont txtLogFont = wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT); if (!txtLogFont.Ok()) txtLogFont = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); txtLogFont.SetPointSize(9); txtLog->SetFont(txtLogFont); FlexGridSizer9->Add( txtLog, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); FlexGridSizer7->Add( FlexGridSizer9, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer8 = new wxFlexGridSizer(2, 3, 0, 0); FlexGridSizer8->AddGrowableCol(0); FlexGridSizer8->AddGrowableCol(1); btnRunCalib = new wxButton( this, ID_BUTTON3, _("Calibrate"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON3")); btnRunCalib->SetDefault(); wxFont btnRunCalibFont( wxDEFAULT, wxDEFAULT, wxFONTSTYLE_NORMAL, wxBOLD, false, wxEmptyString, wxFONTENCODING_DEFAULT); btnRunCalib->SetFont(btnRunCalibFont); FlexGridSizer8->Add( btnRunCalib, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); btnSave = new wxButton( this, ID_BUTTON6, _("Save matrices..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON6")); FlexGridSizer8->Add( btnSave, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); FlexGridSizer8->Add( -1, -1, 1, wxALL | wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL, 5); btnManualRect = new wxButton( this, ID_BUTTON7, _("Manual params..."), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON7")); FlexGridSizer8->Add( btnManualRect, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); btnAbout = new wxButton( this, ID_BUTTON5, _("About"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON5")); FlexGridSizer8->Add( btnAbout, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); btnClose = new wxButton( this, ID_BUTTON4, _("Quit"), wxDefaultPosition, wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON4")); FlexGridSizer8->Add( btnClose, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 5); FlexGridSizer7->Add( FlexGridSizer8, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); StaticBoxSizer2->Add( FlexGridSizer7, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer2->Add( StaticBoxSizer2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2); FlexGridSizer1->Add( FlexGridSizer2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); FlexGridSizer3 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer3->AddGrowableCol(0); FlexGridSizer3->AddGrowableRow(0); Notebook1 = new wxNotebook( this, ID_NOTEBOOK1, wxDefaultPosition, wxSize(719, 570), 0, _T("ID_NOTEBOOK1")); Panel2 = new wxPanel( Notebook1, ID_PANEL2, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL2")); FlexGridSizer13 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer13->AddGrowableCol(0); FlexGridSizer13->AddGrowableRow(0); ScrolledWindow2 = new wxScrolledWindow( Panel2, ID_SCROLLEDWINDOW2, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL, _T("ID_SCROLLEDWINDOW2")); FlexGridSizer11 = new wxFlexGridSizer(0, 1, 0, 0); FlexGridSizer11->AddGrowableCol(0); FlexGridSizer11->AddGrowableRow(0); bmpOriginal = new mrpt::gui::wxMRPTImageControl( ScrolledWindow2, ID_CUSTOM2, wxDefaultPosition.x, wxDefaultPosition.y, wxSize(640, 480).GetWidth(), wxSize(640, 480).GetHeight()); FlexGridSizer11->Add(bmpOriginal, 1, wxALL | wxALIGN_LEFT | wxALIGN_TOP, 0); ScrolledWindow2->SetSizer(FlexGridSizer11); FlexGridSizer11->Fit(ScrolledWindow2); FlexGridSizer11->SetSizeHints(ScrolledWindow2); FlexGridSizer13->Add( ScrolledWindow2, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); Panel2->SetSizer(FlexGridSizer13); FlexGridSizer13->Fit(Panel2); FlexGridSizer13->SetSizeHints(Panel2); Panel3 = new wxPanel( Notebook1, ID_PANEL3, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL3")); FlexGridSizer10 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer10->AddGrowableCol(0); FlexGridSizer10->AddGrowableRow(0); ScrolledWindow3 = new wxScrolledWindow( Panel3, ID_SCROLLEDWINDOW3, wxDefaultPosition, wxDefaultSize, wxHSCROLL | wxVSCROLL, _T("ID_SCROLLEDWINDOW3")); FlexGridSizer14 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer14->AddGrowableCol(0); FlexGridSizer14->AddGrowableRow(0); bmpRectified = new mrpt::gui::wxMRPTImageControl( ScrolledWindow3, ID_CUSTOM1, wxDefaultPosition.x, wxDefaultPosition.y, wxSize(640, 480).GetWidth(), wxSize(640, 480).GetHeight()); FlexGridSizer14->Add( bmpRectified, 1, wxALL | wxALIGN_LEFT | wxALIGN_TOP, 0); ScrolledWindow3->SetSizer(FlexGridSizer14); FlexGridSizer14->Fit(ScrolledWindow3); FlexGridSizer14->SetSizeHints(ScrolledWindow3); FlexGridSizer10->Add( ScrolledWindow3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); Panel3->SetSizer(FlexGridSizer10); FlexGridSizer10->Fit(Panel3); FlexGridSizer10->SetSizeHints(Panel3); Panel1 = new wxPanel( Notebook1, ID_PANEL1, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, _T("ID_PANEL1")); FlexGridSizer12 = new wxFlexGridSizer(1, 1, 0, 0); FlexGridSizer12->AddGrowableCol(0); FlexGridSizer12->AddGrowableRow(0); m_3Dview = new CMyGLCanvas( Panel1, ID_XY_GLCANVAS, wxDefaultPosition, wxSize(-1, 300), wxTAB_TRAVERSAL, _T("ID_XY_GLCANVAS")); FlexGridSizer12->Add( m_3Dview, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); Panel1->SetSizer(FlexGridSizer12); FlexGridSizer12->Fit(Panel1); FlexGridSizer12->SetSizeHints(Panel1); Notebook1->AddPage(Panel2, _("Original Image"), false); Notebook1->AddPage( Panel3, _("Rectified image and reprojected points"), true); Notebook1->AddPage(Panel1, _("3D view"), false); FlexGridSizer3->Add( Notebook1, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 2); FlexGridSizer1->Add( FlexGridSizer3, 1, wxALL | wxEXPAND | wxALIGN_LEFT | wxALIGN_TOP, 0); SetSizer(FlexGridSizer1); FlexGridSizer1->Fit(this); FlexGridSizer1->SetSizeHints(this); Connect( ID_BUTTON8, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnCaptureNowClick); Connect( ID_BUTTON1, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnAddImage); Connect( ID_BUTTON2, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnListClear); Connect( ID_BUTTON9, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnSaveImagesClick); Connect( ID_LISTBOX1, wxEVT_COMMAND_LISTBOX_SELECTED, (wxObjectEventFunction)&camera_calib_guiDialog::OnlbFilesSelect); Connect( ID_CHOICE1, wxEVT_COMMAND_CHOICE_SELECTED, (wxObjectEventFunction)&camera_calib_guiDialog::OncbZoomSelect); Connect( ID_BUTTON3, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnRunCalibClick); Connect( ID_BUTTON6, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnSaveClick); Connect( ID_BUTTON7, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnManualRectClick); Connect( ID_BUTTON5, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnAboutClick); Connect( ID_BUTTON4, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog::OnbtnCloseClick); Connect( ID_BUTTON10, wxEVT_COMMAND_BUTTON_CLICKED, (wxObjectEventFunction)&camera_calib_guiDialog:: OnbtnPoseEstimateNowClick); //*) camera_params.intrinsicParams(0, 0) = 0; // Indicate calib didn't run yet. wxIcon icon; icon.CopyFromBitmap(wxBitmap(wxImage(icono_main_xpm))); this->SetIcon(icon); this->show3Dview(); // Empty 3D scene Center(); this->SetTitle(format( "Camera calibration %s - Part of the MRPT project", CAMERA_CALIB_GUI_VERSION) .c_str()); Maximize(); } camera_calib_guiDialog::~camera_calib_guiDialog() { //(*Destroy(camera_calib_guiDialog) //*) this->clearListImages(); } // Ask the user for new files to add to the list: void camera_calib_guiDialog::OnAddImage(wxCommandEvent& event) { try { wxFileDialog dlg( this, _("Select image(s) to open"), _("."), _(""), _("Image files (*.bmp;*.png;*.jpg)|*.bmp;*.png;*.jpg|All files " "(*.*)|*.*"), wxFD_OPEN | wxFD_FILE_MUST_EXIST | wxFD_MULTIPLE | wxFD_PREVIEW); if (wxID_OK != dlg.ShowModal()) return; wxBusyCursor waitcur; wxArrayString files; dlg.GetPaths(files); wxProgressDialog progDia( wxT("Adding image files"), wxT("Processing..."), files.Count(), // range this, // parent wxPD_CAN_ABORT | wxPD_APP_MODAL | wxPD_SMOOTH | wxPD_AUTO_HIDE | wxPD_ELAPSED_TIME | wxPD_ESTIMATED_TIME | wxPD_REMAINING_TIME); wxTheApp->Yield(); // Let the app. process messages int counter_loops = 0; for (unsigned int i = 0; i < files.Count(); i++) { if (counter_loops++ % 5 == 0) { if (!progDia.Update(i)) break; wxTheApp->Yield(); // Let the app. process messages } const string fil = string(files[i].mb_str()); TImageCalibData dat; #if USE_EXTERNAL_STORAGE_IMGS // Optimization: Use external storage: // --------------------------------------- // string tmp_check = mrpt::system::getTempFileName()+".jpg"; // string tmp_rectified = mrpt::system::getTempFileName()+".jpg"; // dat.img_original.saveToFile(tmp_check); // dat.img_original.saveToFile(tmp_rectified); // mark all imgs. as external storage: dat.img_original.setExternalStorage(fil); // dat.img_checkboard.setExternalStorage(tmp_check); // dat.img_rectified.setExternalStorage(tmp_rectified); dat.img_original.unload(); // dat.img_checkboard.unload(); // dat.img_rectified.unload(); #else // All in memory: if (!dat.img_original.loadFromFile(fil)) { wxMessageBox( format("Error loading file: %s", fil.c_str()).c_str()), _("Error"); this->updateListOfImages(); return; } #endif lst_images[fil] = dat; } this->updateListOfImages(); } catch (const std::exception& e) { wxMessageBox( mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this); } } void camera_calib_guiDialog::clearListImages() { lst_images.clear(); } // Clear list of images. void camera_calib_guiDialog::OnListClear(wxCommandEvent& event) { this->clearListImages(); this->updateListOfImages(); } void camera_calib_guiDialog::OnbtnRunCalibClick(wxCommandEvent& event) { try { txtLog->Clear(); CMyRedirector redire(txtLog, true, 10); const unsigned int check_size_x = edSizeX->GetValue(); const unsigned int check_size_y = edSizeY->GetValue(); const double check_squares_length_X_meters = 0.001 * atof(string(edLengthX->GetValue().mb_str()).c_str()); const double check_squares_length_Y_meters = 0.001 * atof(string(edLengthY->GetValue().mb_str()).c_str()); const bool normalize_image = cbNormalize->GetValue(); const bool useScaramuzzaAlternativeDetector = rbMethod->GetSelection() == 1; wxBusyCursor waitcur; bool res = mrpt::vision::checkerBoardCameraCalibration( lst_images, check_size_x, check_size_y, check_squares_length_X_meters, check_squares_length_Y_meters, camera_params, normalize_image, nullptr /* MSE */, false /* skip draw */, useScaramuzzaAlternativeDetector); refreshDisplayedImage(); if (!res) wxMessageBox( _("Calibration finished with error: Please check the text log " "to see what's wrong"), _("Error")); if (res) show3Dview(); } catch (const std::exception& e) { wxMessageBox( mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this); } } void camera_calib_guiDialog::OnbtnCloseClick(wxCommandEvent&) { Close(); } void camera_calib_guiDialog::OnbtnAboutClick(wxCommandEvent&) { mrpt::gui::show_mrpt_about_box_wxWidgets(this, "camera-calib"); } // save matrices: void camera_calib_guiDialog::OnbtnSaveClick(wxCommandEvent& event) { if (camera_params.intrinsicParams(0, 0) == 0) { wxMessageBox(_("Run the calibration first"), _("Error")); return; } { wxFileDialog dlg( this, _("Save intrinsic parameters matrix"), _("."), _("intrinsic_matrix.txt"), _("Text files (*.txt)|*.txt|All files (*.*)|*.*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (wxID_OK != dlg.ShowModal()) return; camera_params.intrinsicParams.saveToTextFile( string(dlg.GetPath().mb_str())); } { wxFileDialog dlg( this, _("Save distortion parameters"), _("."), _("distortion_matrix.txt"), _("Text files (*.txt)|*.txt|All files (*.*)|*.*"), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (wxID_OK != dlg.ShowModal()) return; CMatrixDouble M(1, 5); for (unsigned i = 0; i < 5; i++) M(0, i) = camera_params.dist[i]; M.saveToTextFile(string(dlg.GetPath().mb_str())); } } // Update the listbox from lst_img_files void camera_calib_guiDialog::updateListOfImages() { lbFiles->Clear(); for (auto s = lst_images.begin(); s != lst_images.end(); ++s) lbFiles->Append(s->first.c_str()); btnSaveImages->Enable(!lst_images.empty()); refreshDisplayedImage(); } // Shows the image selected in the listbox: void camera_calib_guiDialog::refreshDisplayedImage() { try { if (!lbFiles->GetCount()) { // No images: return; } // Assure there's one selected: if (lbFiles->GetSelection() == wxNOT_FOUND) lbFiles->SetSelection(0); const string selFile = string(lbFiles->GetStringSelection().mb_str()); auto it = lst_images.find(selFile); if (it == lst_images.end()) return; // Zoom: const std::string strZoom = string(cbZoom->GetStringSelection().mb_str()); const double zoomVal = 0.01 * atof(strZoom.c_str()); ASSERT_(zoomVal > 0 && zoomVal < 30); TImageSize imgSizes(0, 0); // Generate the images on-the-fly: CImage imgOrgColor; it->second.img_original.colorImage(imgOrgColor); imgSizes = imgOrgColor.getSize(); // Rectify: CImage imgRect; if (camera_params.intrinsicParams(0, 0) == 0) { // Not calibrated yet: imgRect = imgOrgColor; imgRect.scaleImage( imgRect, imgSizes.x * zoomVal, imgSizes.y * zoomVal, IMG_INTERP_NN); } else { imgOrgColor.undistort(imgRect, camera_params); imgRect.scaleImage( imgRect, imgSizes.x * zoomVal, imgSizes.y * zoomVal, IMG_INTERP_NN); // Draw reprojected: for (auto& k : it->second.projectedPoints_undistorted) imgRect.drawCircle( zoomVal * k.x, zoomVal * k.y, 4, TColor(0, 255, 64)); imgRect.drawCircle(10, 10, 4, TColor(0, 255, 64)); imgRect.textOut(18, 4, "Reprojected corners", TColor::white()); } // Zoom images: imgOrgColor.scaleImage( imgOrgColor, imgSizes.x * zoomVal, imgSizes.y * zoomVal, IMG_INTERP_NN); imgSizes = imgOrgColor.getSize(); CImage imgCheck = imgOrgColor; // Draw the board: for (unsigned int k = 0; k < it->second.detected_corners.size(); k++) { imgCheck.cross( it->second.detected_corners[k].x * zoomVal, it->second.detected_corners[k].y * zoomVal, TColor::blue(), '+', 3); imgCheck.drawCircle( it->second.projectedPoints_distorted[k].x * zoomVal, it->second.projectedPoints_distorted[k].y * zoomVal, 4, TColor(0, 255, 64)); } imgCheck.drawCircle(10, 10, 4, TColor(0, 255, 64)); imgCheck.textOut(18, 4, "Reprojected corners", TColor::white()); imgCheck.cross(10, 30, TColor::blue(), '+', 3); imgCheck.textOut(18, 24, "Detected corners", TColor::white()); this->bmpOriginal->AssignImage(imgCheck); this->bmpRectified->AssignImage(imgRect); it->second.img_original.unload(); // Plot: this->bmpOriginal->SetMinSize(wxSize(imgSizes.x, imgSizes.y)); this->bmpOriginal->SetMaxSize(wxSize(imgSizes.x, imgSizes.y)); this->bmpOriginal->SetSize(imgSizes.x, imgSizes.y); this->bmpRectified->SetMinSize(wxSize(imgSizes.x, imgSizes.y)); this->bmpRectified->SetMaxSize(wxSize(imgSizes.x, imgSizes.y)); this->bmpRectified->SetSize(imgSizes.x, imgSizes.y); this->FlexGridSizer11->RecalcSizes(); this->FlexGridSizer14->RecalcSizes(); // this->ScrolledWindow2->SetVirtualSize(wxSize(imgSizes.x,imgSizes.y)); // this->ScrolledWindow3->SetVirtualSize(wxSize(imgSizes.x,imgSizes.y)); this->ScrolledWindow2->SetScrollbars(1, 1, imgSizes.x, imgSizes.y); this->ScrolledWindow3->SetScrollbars(1, 1, imgSizes.x, imgSizes.y); this->bmpOriginal->Refresh(false); this->bmpRectified->Refresh(false); } catch (const std::exception& e) { wxMessageBox( mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this); } } void camera_calib_guiDialog::OnlbFilesSelect(wxCommandEvent& event) { refreshDisplayedImage(); } void camera_calib_guiDialog::show3Dview() { mrpt::opengl::COpenGLScene::Ptr scene = mrpt::make_aligned_shared<mrpt::opengl::COpenGLScene>(); const unsigned int check_size_x = edSizeX->GetValue(); const unsigned int check_size_y = edSizeY->GetValue(); const double check_squares_length_X_meters = 0.001 * atof(string(edLengthX->GetValue().mb_str()).c_str()); const double check_squares_length_Y_meters = 0.001 * atof(string(edLengthY->GetValue().mb_str()).c_str()); if (!check_squares_length_X_meters || !check_squares_length_Y_meters) return; opengl::CGridPlaneXY::Ptr grid = mrpt::make_aligned_shared<opengl::CGridPlaneXY>( 0, check_size_x * check_squares_length_X_meters, 0, check_size_y * check_squares_length_Y_meters, 0, check_squares_length_X_meters); scene->insert(grid); for (auto& lst_image : lst_images) { if (!lst_image.second.detected_corners.empty()) { mrpt::opengl::CSetOfObjects::Ptr cor = mrpt::opengl::stock_objects::CornerXYZ(); cor->setName(mrpt::system::extractFileName(lst_image.first)); cor->enableShowName(true); cor->setScale(0.1f); cor->setPose(lst_image.second.reconstructed_camera_pose); scene->insert(cor); } } // scene->insert( mrpt::opengl::stock_objects::CornerXYZ() ); this->m_3Dview->setOpenGLSceneRef(scene); this->m_3Dview->Refresh(); } // Enter calib. params manually: void camera_calib_guiDialog::OnbtnManualRectClick(wxCommandEvent& event) { wxMessageBox( _("Please, enter calibration parameters manually next to overpass " "automatically obtained parameters."), _("Manual parameters")); wxString s; if (camera_params.intrinsicParams(0, 0) == 0) { wxMessageBox(_("Run the calibration first"), _("Error")); return; } s = wxGetTextFromUser( _("Focus length in X pixel size (fx):"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(0, 0)), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.intrinsicParams(0, 0))) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Focus length in Y pixel size (fy):"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(1, 1)), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.intrinsicParams(1, 1))) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Image center X (cx):"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(0, 2)), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.intrinsicParams(0, 2))) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Image center Y (cy):"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.intrinsicParams(1, 2)), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.intrinsicParams(1, 2))) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Distortion param p1:"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.dist[0]), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.dist[0])) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Distortion param p2:"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.dist[1]), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.dist[1])) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Distortion param k1:"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.dist[2]), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.dist[2])) { wxMessageBox(_("Invalid number")); return; } s = wxGetTextFromUser( _("Distortion param k2:"), _("Manual parameters"), wxString::Format(wxT("%.07f"), camera_params.dist[3]), this); if (s.IsEmpty()) return; if (!s.ToDouble(&camera_params.dist[3])) { wxMessageBox(_("Invalid number")); return; } refreshDisplayedImage(); } void camera_calib_guiDialog::OnbtnCaptureNowClick(wxCommandEvent& event) { CDlgCalibWizardOnline dlg(this); // Set pattern params: dlg.edLengthX->SetValue(this->edLengthX->GetValue()); dlg.edLengthY->SetValue(this->edLengthY->GetValue()); dlg.edSizeX->SetValue(this->edSizeX->GetValue()); dlg.edSizeY->SetValue(this->edSizeY->GetValue()); dlg.cbNormalize->SetValue(this->cbNormalize->GetValue()); // Run: dlg.ShowModal(); // Get params: this->edLengthX->SetValue(dlg.edLengthX->GetValue()); this->edLengthY->SetValue(dlg.edLengthY->GetValue()); this->edSizeX->SetValue(dlg.edSizeX->GetValue()); this->edSizeY->SetValue(dlg.edSizeY->GetValue()); this->cbNormalize->SetValue(dlg.cbNormalize->GetValue()); // Get images: lst_images = dlg.m_calibFrames; this->updateListOfImages(); } void camera_calib_guiDialog::OnbtnPoseEstimateNowClick(wxCommandEvent& event) { // Compute pose using PnP Algorithms toolkit CDlgPoseEst dlg(this); // Set pattern params: dlg.edLengthX->SetValue(this->edLengthX->GetValue()); dlg.edLengthY->SetValue(this->edLengthY->GetValue()); dlg.edSizeX->SetValue(this->edSizeX->GetValue()); dlg.edSizeY->SetValue(this->edSizeY->GetValue()); dlg.cbNormalize->SetValue(this->cbNormalize->GetValue()); // Run: dlg.ShowModal(); // Get params: this->edLengthX->SetValue(dlg.edLengthX->GetValue()); this->edLengthY->SetValue(dlg.edLengthY->GetValue()); this->edSizeX->SetValue(dlg.edSizeX->GetValue()); this->edSizeY->SetValue(dlg.edSizeY->GetValue()); this->cbNormalize->SetValue(dlg.cbNormalize->GetValue()); // Get images: lst_images = dlg.m_calibFrames; this->updateListOfImages(); } void camera_calib_guiDialog::OnbtnSaveImagesClick(wxCommandEvent& event) { try { if (lst_images.empty()) return; wxDirDialog dlg( this, _("Select the directory where to save the images"), _(".")); if (dlg.ShowModal() == wxID_OK) { string dir = string(dlg.GetPath().mb_str()); for (auto& lst_image : lst_images) lst_image.second.img_original.saveToFile( dir + string("/") + lst_image.first + string(".png")); } } catch (const std::exception& e) { wxMessageBox( mrpt::exception_to_str(e), _("Error"), wxICON_INFORMATION, this); } } void camera_calib_guiDialog::OncbZoomSelect(wxCommandEvent& event) { refreshDisplayedImage(); }
33.766484
80
0.724297
waltzrobotics
14721df9fd0e5d7acd839bd5ec78de00e0f0cdf3
2,125
cpp
C++
Chapter05-physics/005-forces/src/ofApp.cpp
jeffcrouse/ccof
d9c5773b9913209e3ff06a4777115d750487cb44
[ "MIT" ]
6
2017-09-27T14:13:44.000Z
2020-06-24T18:16:22.000Z
Chapter05-physics/005-forces/src/ofApp.cpp
jeffcrouse/ccof
d9c5773b9913209e3ff06a4777115d750487cb44
[ "MIT" ]
null
null
null
Chapter05-physics/005-forces/src/ofApp.cpp
jeffcrouse/ccof
d9c5773b9913209e3ff06a4777115d750487cb44
[ "MIT" ]
3
2017-10-27T20:33:33.000Z
2019-09-17T05:42:13.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetWindowShape(1280, 800); ofSetWindowTitle("forces"); ofSetFrameRate(60); ofBackground(255, 255, 255); ofEnableSmoothing(); ofSetCircleResolution(40); gravity.x = 0; gravity.y = 0.08; wind.x = -0.1; wind.y = 0; } //-------------------------------------------------------------- void ofApp::update(){ t.applyForce(gravity); t.applyForce(wind); // Make the Thing slow down as it passes through some "liquid" // Do this by applying a negative force // 1. Decide on a drag coeffecient (negative) // 2. Multiply it by the vel // 3. Apply the force // 4. update() t.update(); } //-------------------------------------------------------------- void ofApp::draw(){ t.draw(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ t.reset(); } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
22.606383
66
0.356706
jeffcrouse
1472cea6e1c8029ab939dffe9bc15a4f82236cf0
6,107
cc
C++
lib/Base64.cc
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
lib/Base64.cc
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
lib/Base64.cc
jojochuang/eventwave
6cb3a8569f12a9127bf326be3231123428cd754d
[ "BSD-3-Clause" ]
null
null
null
/* * Base64.cc : part of the Mace toolkit for building distributed systems * * Copyright (c) 2011, Charles Killian, Dejan Kostic, Ryan Braud, James W. Anderson, John Fisher-Ogden, Calvin Hubble, Duy Nguyen, Justin Burke, David Oppenheimer, Amin Vahdat, Adolfo Rodriguez, Sooraj Bhat * 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 names of the contributors, nor their associated universities * or organizations 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. * * ----END-OF-LEGAL-STUFF---- */ //********************************************************************* //* Base64 - a simple base64 encoder and decoder. //* //* Copyright (c) 1999, Bob Withers - bwit@pobox.com //* //* This code may be freely used for any purpose, either personal //* or commercial, provided the authors copyright notice remains //* intact. //* //* Enhancements by Stanley Yamane: //* o reverse lookup table for the decode function //* o reserve string buffer space in advance //* //* //* Reformated by James W. Anderson. Added isPrintable method. //********************************************************************* #include <ctype.h> #include "Base64.h" using std::string; const char Base64::fillchar = '='; const string::size_type Base64::np = string::npos; // 0000000000111111111122222222223333333333444444444455555555556666 // 0123456789012345678901234567890123456789012345678901234567890123 const string Base64::Base64Table("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); // Decode Table gives the index of any valid base64 character in the Base64 table // 65 == A, 97 == a, 48 == 0, 43 == +, 47 == / const string::size_type Base64::DecodeTable[] = //0 1 2 3 4 5 6 7 8 9 {np,np,np,np,np,np,np,np,np,np, // 0 - 9 np,np,np,np,np,np,np,np,np,np, //10 -19 np,np,np,np,np,np,np,np,np,np, //20 -29 np,np,np,np,np,np,np,np,np,np, //30 -39 np,np,np,62,np,np,np,63,52,53, //40 -49 54,55,56,57,58,59,60,61,np,np, //50 -59 np,np,np,np,np, 0, 1, 2, 3, 4, //60 -69 5, 6, 7, 8, 9,10,11,12,13,14, //70 -79 15,16,17,18,19,20,21,22,23,24, //80 -89 25,np,np,np,np,np,np,26,27,28, //90 -99 29,30,31,32,33,34,35,36,37,38, //100 -109 39,40,41,42,43,44,45,46,47,48, //110 -119 49,50,51,np,np,np,np,np,np,np, //120 -129 np,np,np,np,np,np,np,np,np,np, //130 -139 np,np,np,np,np,np,np,np,np,np, //140 -149 np,np,np,np,np,np,np,np,np,np, //150 -159 np,np,np,np,np,np,np,np,np,np, //160 -169 np,np,np,np,np,np,np,np,np,np, //170 -179 np,np,np,np,np,np,np,np,np,np, //180 -189 np,np,np,np,np,np,np,np,np,np, //190 -199 np,np,np,np,np,np,np,np,np,np, //200 -209 np,np,np,np,np,np,np,np,np,np, //210 -219 np,np,np,np,np,np,np,np,np,np, //220 -229 np,np,np,np,np,np,np,np,np,np, //230 -239 np,np,np,np,np,np,np,np,np,np, //240 -249 np,np,np,np,np,np //250 -256 }; string Base64::encode(const string& data) { string::size_type i; char c; string::size_type len = data.length(); string ret; ret.reserve(len * 2); for (i = 0; i < len; ++i) { c = (data[i] >> 2) & 0x3f; ret.append(1, Base64Table[c]); c = (data[i] << 4) & 0x3f; if (++i < len) c |= (data[i] >> 4) & 0x0f; ret.append(1, Base64Table[c]); if (i < len) { c = (data[i] << 2) & 0x3f; if (++i < len) c |= (data[i] >> 6) & 0x03; ret.append(1, Base64Table[c]); } else { ++i; ret.append(1, fillchar); } if (i < len) { c = data[i] & 0x3f; ret.append(1, Base64Table[c]); } else { ret.append(1, fillchar); } } return(ret); } // encode string Base64::decode(const string& data) { string::size_type i; char c; char c1; string::size_type len = data.length(); string ret; ret.reserve(len); for (i = 0; i < len; ++i) { c = (char) DecodeTable[(unsigned char)data[i]]; ++i; c1 = (char) DecodeTable[(unsigned char)data[i]]; c = (c << 2) | ((c1 >> 4) & 0x3); ret.append(1, c); if (++i < len) { c = data[i]; if (fillchar == c) break; c = (char) DecodeTable[(unsigned char)data[i]]; c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); ret.append(1, c1); } if (++i < len) { c1 = data[i]; if (fillchar == c1) break; c1 = (char) DecodeTable[(unsigned char)data[i]]; c = ((c << 6) & 0xc0) | c1; ret.append(1, c); } } return(ret); } // decode bool Base64::isPrintable(const string& s) { size_t i = 0; while (i < s.size() && (isprint(s[i]) || isspace(s[i]))) { i++; } return (i == s.size()); } // isPrintable
32.142105
206
0.602423
jojochuang
1474a1984a53c1d6cb08d767e15adf8abab34914
30,372
cpp
C++
library/src/blas2/rocblas_trsv.cpp
YvanMokwinski/rocBLAS
f02952487c7019cbde04c4ddcb596aaf71e51ec6
[ "MIT" ]
null
null
null
library/src/blas2/rocblas_trsv.cpp
YvanMokwinski/rocBLAS
f02952487c7019cbde04c4ddcb596aaf71e51ec6
[ "MIT" ]
1
2019-09-26T01:51:09.000Z
2019-09-26T18:09:56.000Z
library/src/blas2/rocblas_trsv.cpp
YvanMokwinski/rocBLAS
f02952487c7019cbde04c4ddcb596aaf71e51ec6
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2016-2019 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "../blas3/trtri_trsm.hpp" #include "handle.h" #include "logging.h" #include "rocblas.h" #include "rocblas_gemv.hpp" #include "utility.h" #include <algorithm> #include <cstdio> #include <tuple> namespace { using std::max; using std::min; constexpr rocblas_int NB_X = 1024; constexpr rocblas_int STRSV_BLOCK = 128; constexpr rocblas_int DTRSV_BLOCK = 128; template <typename T> constexpr T negative_one = -1; template <typename T> constexpr T zero = 0; template <typename T> constexpr T one = 1; template <typename T> __global__ void flip_vector_kernel(T* __restrict__ data, T* __restrict__ data_end, rocblas_int size, rocblas_int abs_incx) { ptrdiff_t tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(tx < size) { auto offset = tx * abs_incx; auto temp = data[offset]; data[offset] = data_end[-offset]; data_end[-offset] = temp; } } template <typename T> void flip_vector(rocblas_handle handle, T* data, rocblas_int m, rocblas_int abs_incx) { T* data_end = data + (m - 1) * abs_incx; rocblas_int size = (m + 1) / 2; rocblas_int blocksX = (size - 1) / NB_X + 1; dim3 grid = blocksX; dim3 threads = NB_X; hipLaunchKernelGGL(flip_vector_kernel, grid, threads, 0, handle->rocblas_stream, data, data_end, size, abs_incx); } template <typename T> __global__ void strided_vector_copy_kernel(T* __restrict__ dst, rocblas_int dst_incx, const T* __restrict__ src, rocblas_int src_incx, rocblas_int size) { ptrdiff_t tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(tx < size) dst[tx * dst_incx] = src[tx * src_incx]; } template <typename T> void strided_vector_copy(rocblas_handle handle, T* dst, rocblas_int dst_incx, T* src, rocblas_int src_incx, rocblas_int size) { rocblas_int blocksX = (size - 1) / NB_X + 1; dim3 grid = blocksX; dim3 threads = NB_X; hipLaunchKernelGGL(strided_vector_copy_kernel, grid, threads, 0, handle->rocblas_stream, dst, dst_incx, src, src_incx, size); } template <rocblas_int BLOCK, typename T> rocblas_status rocblas_trsv_left(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_int m, const T* A, rocblas_int lda, T* B, rocblas_int incx, const T* invA, T* X) { rocblas_int i, jb; if(transA == rocblas_operation_none) { if(uplo == rocblas_fill_lower) { // left, lower no-transpose jb = min(BLOCK, m); rocblas_gemv_template( handle, transA, jb, jb, &one<T>, invA, BLOCK, B, incx, &zero<T>, X, 1); if(BLOCK < m) { rocblas_gemv_template(handle, transA, m - BLOCK, BLOCK, &negative_one<T>, A + BLOCK, lda, X, 1, &one<T>, B + BLOCK * incx, incx); // remaining blocks for(i = BLOCK; i < m; i += BLOCK) { jb = min(m - i, BLOCK); rocblas_gemv_template(handle, transA, jb, jb, &one<T>, invA + i * BLOCK, BLOCK, B + i * incx, incx, &zero<T>, X + i, 1); if(i + BLOCK < m) rocblas_gemv_template(handle, transA, m - i - BLOCK, BLOCK, &negative_one<T>, A + i + BLOCK + i * lda, lda, X + i, 1, &one<T>, B + (i + BLOCK) * incx, incx); } } } else { // left, upper no-transpose jb = m % BLOCK == 0 ? BLOCK : m % BLOCK; i = m - jb; // if m=n=35=lda=ldb, BLOCK =32, then jb = 3, i = 32; {3, 35, 3, 32, 35, 35} rocblas_gemv_template(handle, transA, jb, jb, &one<T>, invA + i * BLOCK, BLOCK, B + i * incx, incx, &zero<T>, X + i, 1); if(i >= BLOCK) { rocblas_gemv_template(handle, transA, i, jb, &negative_one<T>, A + i * lda, lda, X + i, 1, &one<T>, B, incx); // remaining blocks for(i = m - jb - BLOCK; i >= 0; i -= BLOCK) { //{32, 35, 32, 32, 35, 35} rocblas_gemv_template(handle, transA, BLOCK, BLOCK, &one<T>, invA + i * BLOCK, BLOCK, B + i * incx, incx, &zero<T>, X + i, 1); if(i >= BLOCK) rocblas_gemv_template(handle, transA, i, BLOCK, &negative_one<T>, A + i * lda, lda, X + i, 1, &one<T>, B, incx); } } } } else { // transA == rocblas_operation_transpose || transA == rocblas_operation_conjugate_transpose if(uplo == rocblas_fill_lower) { // left, lower transpose jb = m % BLOCK == 0 ? BLOCK : m % BLOCK; i = m - jb; rocblas_gemv_template(handle, transA, jb, jb, &one<T>, invA + i * BLOCK, BLOCK, B + i * incx, incx, &zero<T>, X + i, 1); if(i - BLOCK >= 0) { rocblas_gemv_template(handle, transA, jb, i, &negative_one<T>, A + i, lda, X + i, 1, &one<T>, B, incx); // remaining blocks for(i = m - jb - BLOCK; i >= 0; i -= BLOCK) { rocblas_gemv_template(handle, transA, BLOCK, BLOCK, &one<T>, invA + i * BLOCK, BLOCK, B + i * incx, incx, &zero<T>, X + i, 1); if(i >= BLOCK) rocblas_gemv_template(handle, transA, BLOCK, i, &negative_one<T>, A + i, lda, X + i, 1, &one<T>, B, incx); } } } else { // left, upper transpose jb = min(BLOCK, m); rocblas_gemv_template( handle, transA, jb, jb, &one<T>, invA, BLOCK, B, incx, &zero<T>, X, 1); if(BLOCK < m) { rocblas_gemv_template(handle, transA, BLOCK, m - BLOCK, &negative_one<T>, A + BLOCK * lda, lda, X, 1, &one<T>, B + BLOCK * incx, incx); // remaining blocks for(i = BLOCK; i < m; i += BLOCK) { jb = min(m - i, BLOCK); rocblas_gemv_template(handle, transA, jb, jb, &one<T>, invA + i * BLOCK, BLOCK, B + i * incx, incx, &zero<T>, X + i, 1); if(i + BLOCK < m) rocblas_gemv_template(handle, transA, BLOCK, m - i - BLOCK, &negative_one<T>, A + i + (i + BLOCK) * lda, lda, X + i, 1, &one<T>, B + (i + BLOCK) * incx, incx); } } } } // transpose return rocblas_status_success; } template <rocblas_int BLOCK, typename T> rocblas_status special_trsv_template(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, const T* A, rocblas_int lda, T* B, ptrdiff_t incx, const T* invA, T* x_temp) { bool parity = (transA == rocblas_operation_none) ^ (uplo == rocblas_fill_lower); size_t R = m / BLOCK; for(size_t r = 0; r < R; r++) { size_t q = R - r; size_t j = parity ? q - 1 : r; // copy a BLOCK*n piece we are solving at a time strided_vector_copy<T>(handle, x_temp, 1, B + incx * j * BLOCK, incx, BLOCK); if(r) { rocblas_int M = BLOCK; rocblas_int N = BLOCK; const T* A_current; T* B_current = parity ? B + q * BLOCK * incx : B; if(transA == rocblas_operation_none) { N *= r; A_current = parity ? A + BLOCK * ((lda + 1) * q - 1) : A + N; } else { M *= r; A_current = parity ? A + BLOCK * ((lda + 1) * q - lda) : A + M * lda; } rocblas_gemv_template(handle, transA, M, N, &negative_one<T>, A_current, lda, B_current, incx, &one<T>, x_temp, 1); } rocblas_gemv_template(handle, transA, BLOCK, BLOCK, &one<T>, invA + j * BLOCK * BLOCK, BLOCK, x_temp, 1, &zero<T>, B + j * BLOCK * incx, incx); } return rocblas_status_success; } template <typename> constexpr char rocblas_trsv_name[] = "unknown"; template <> constexpr char rocblas_trsv_name<float>[] = "rocblas_strsv"; template <> constexpr char rocblas_trsv_name<double>[] = "rocblas_dtrsv"; template <rocblas_int BLOCK, typename T> rocblas_status rocblas_trsv_ex_impl(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, const T* A, rocblas_int lda, T* B, rocblas_int incx, const T* supplied_invA = nullptr, rocblas_int supplied_invA_size = 0) { if(!handle) return rocblas_status_invalid_handle; auto layer_mode = handle->layer_mode; if(layer_mode & rocblas_layer_mode_log_trace) log_trace(handle, rocblas_trsv_name<T>, uplo, transA, diag, m, A, lda, B, incx); if(layer_mode & (rocblas_layer_mode_log_bench | rocblas_layer_mode_log_profile)) { auto uplo_letter = rocblas_fill_letter(uplo); auto transA_letter = rocblas_transpose_letter(transA); auto diag_letter = rocblas_diag_letter(diag); if(layer_mode & rocblas_layer_mode_log_bench) { if(handle->pointer_mode == rocblas_pointer_mode_host) log_bench(handle, "./rocblas-bench -f trsv -r", rocblas_precision_string<T>, "--uplo", uplo_letter, "--transposeA", transA_letter, "--diag", diag_letter, "-m", m, "--lda", lda, "--incx", incx); } if(layer_mode & rocblas_layer_mode_log_profile) log_profile(handle, rocblas_trsv_name<T>, "uplo", uplo_letter, "transA", transA_letter, "diag", diag_letter, "M", m, "lda", lda, "incx", incx); } if(uplo != rocblas_fill_lower && uplo != rocblas_fill_upper) return rocblas_status_not_implemented; if(!A || !B) return rocblas_status_invalid_pointer; if(m < 0 || lda < m || lda < 1 || !incx) return rocblas_status_invalid_size; // quick return if possible. // return rocblas_status_size_unchanged if device memory size query if(!m) return handle->is_device_memory_size_query() ? rocblas_status_size_unchanged : rocblas_status_success; // Whether size is an exact multiple of blocksize const bool exact_blocks = (m % BLOCK) == 0; // perf_status indicates whether optimal performance is obtainable with available memory rocblas_status perf_status = rocblas_status_success; size_t invA_bytes = 0; size_t c_temp_bytes = 0; // For user-supplied invA, check to make sure size is large enough // If not large enough, indicate degraded performance and ignore supplied invA if(supplied_invA && supplied_invA_size / BLOCK < m) { static int msg = fputs("WARNING: TRSV invA_size argument is too small; invA argument " "is being ignored; TRSV performance is degraded\n", stderr); perf_status = rocblas_status_perf_degraded; supplied_invA = nullptr; } if(!supplied_invA) { // Only allocate bytes for invA if supplied_invA == nullptr or supplied_invA_size is too small invA_bytes = sizeof(T) * BLOCK * m; // When m < BLOCK, C is unnecessary for trtri c_temp_bytes = (m / BLOCK) * (sizeof(T) * (BLOCK / 2) * (BLOCK / 2)); // For the TRTRI last diagonal block we need remainder space if m % BLOCK != 0 if(!exact_blocks) { // TODO: Make this more accurate -- right now it's much larger than necessary size_t remainder_bytes = sizeof(T) * ROCBLAS_TRTRI_NB * BLOCK * 2; // C is the maximum of the temporary space needed for TRTRI c_temp_bytes = max(c_temp_bytes, remainder_bytes); } } // Temporary solution vector // If the special solver can be used, then only BLOCK words are needed instead of m words size_t x_temp_bytes = exact_blocks ? sizeof(T) * BLOCK : sizeof(T) * m; // X and C temporaries can share space, so the maximum size is allocated size_t x_c_temp_bytes = max(x_temp_bytes, c_temp_bytes); // If this is a device memory size query, set optimal size and return changed status if(handle->is_device_memory_size_query()) return handle->set_optimal_device_memory_size(x_c_temp_bytes, invA_bytes); // Attempt to allocate optimal memory size, returning error if failure auto mem = handle->device_malloc(x_c_temp_bytes, invA_bytes); if(!mem) return rocblas_status_memory_error; // Get pointers to allocated device memory // Note: Order of pointers in std::tie(...) must match order of sizes in handle->device_malloc(...) void* x_temp; void* invA; std::tie(x_temp, invA) = mem; // Temporarily switch to host pointer mode, restoring on return auto saved_pointer_mode = handle->push_pointer_mode(rocblas_pointer_mode_host); rocblas_status status = rocblas_status_success; if(supplied_invA) invA = const_cast<T*>(supplied_invA); else { // batched trtri invert diagonal part (BLOCK*BLOCK) of A into invA auto c_temp = x_temp; // Uses same memory as x_temp status = rocblas_trtri_trsm_template<BLOCK>( handle, (T*)c_temp, uplo, diag, m, A, lda, (T*)invA); if(status != rocblas_status_success) return status; } if(transA == rocblas_operation_conjugate_transpose) transA = rocblas_operation_transpose; // TODO: workaround to fix negative incx issue rocblas_int abs_incx = incx < 0 ? -incx : incx; if(incx < 0) flip_vector(handle, B, m, abs_incx); if(exact_blocks) { status = special_trsv_template<BLOCK>( handle, uplo, transA, diag, m, A, lda, B, abs_incx, (const T*)invA, (T*)x_temp); if(status != rocblas_status_success) return status; // TODO: workaround to fix negative incx issue if(incx < 0) flip_vector(handle, B, m, abs_incx); } else { status = rocblas_trsv_left<BLOCK>( handle, uplo, transA, m, A, lda, B, abs_incx, (const T*)invA, (T*)x_temp); if(status != rocblas_status_success) return status; // copy solution X into B // TODO: workaround to fix negative incx issue strided_vector_copy(handle, B, abs_incx, incx < 0 ? (T*)x_temp + m - 1 : (T*)x_temp, incx < 0 ? -1 : 1, m); } return perf_status; } } // namespace /* * =========================================================================== * C wrapper * =========================================================================== */ extern "C" { rocblas_status rocblas_strsv(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, const float* A, rocblas_int lda, float* x, rocblas_int incx) { return rocblas_trsv_ex_impl<STRSV_BLOCK>(handle, uplo, transA, diag, m, A, lda, x, incx); } rocblas_status rocblas_dtrsv(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, const double* A, rocblas_int lda, double* x, rocblas_int incx) { return rocblas_trsv_ex_impl<DTRSV_BLOCK>(handle, uplo, transA, diag, m, A, lda, x, incx); } rocblas_status rocblas_trsv_ex(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, const void* A, rocblas_int lda, void* x, rocblas_int incx, const void* invA, rocblas_int invA_size, rocblas_datatype compute_type) { switch(compute_type) { case rocblas_datatype_f64_r: return rocblas_trsv_ex_impl<DTRSV_BLOCK>(handle, uplo, transA, diag, m, static_cast<const double*>(A), lda, static_cast<double*>(x), incx, static_cast<const double*>(invA), invA_size); case rocblas_datatype_f32_r: return rocblas_trsv_ex_impl<STRSV_BLOCK>(handle, uplo, transA, diag, m, static_cast<const float*>(A), lda, static_cast<float*>(x), incx, static_cast<const float*>(invA), invA_size); default: return rocblas_status_not_implemented; } } } // extern "C"
41.892414
107
0.317859
YvanMokwinski
147944acc3cae01f608118077899da58bd2523ac
5,661
cpp
C++
libnd4j/include/ops/declarable/generic/parity_ops/batch_to_space_nd.cpp
steven-lang/deeplearning4j
979ef13c0b28565800fc651693102d7bd2bf52c9
[ "Apache-2.0" ]
1
2019-10-14T06:55:41.000Z
2019-10-14T06:55:41.000Z
libnd4j/include/ops/declarable/generic/parity_ops/batch_to_space_nd.cpp
steven-lang/deeplearning4j
979ef13c0b28565800fc651693102d7bd2bf52c9
[ "Apache-2.0" ]
null
null
null
libnd4j/include/ops/declarable/generic/parity_ops/batch_to_space_nd.cpp
steven-lang/deeplearning4j
979ef13c0b28565800fc651693102d7bd2bf52c9
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ /* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // // @author Yurii Shyrma (iuriish@yahoo.com) // #include <op_boilerplate.h> #if NOT_EXCLUDED(OP_batch_to_space_nd) #include <ops/declarable/headers/parity_ops.h> #include <ops/declarable/helpers/s_t_b.h> namespace nd4j { namespace ops { CUSTOM_OP_IMPL(batch_to_space_nd, 3, 1, false, 0, 0) { // 4D example, numOfSpatialDims = 2 - two spatial dimensions // [bS*blockShape[0]*blockShape[1], iH, iW, iC] is rearranged/permuted to [bS, iH*blockShape[0] - cropTop - cropBottom, iW*blockShape[1] - cropLeft - cropRight, iC] auto input = INPUT_VARIABLE(0); auto blockShape = INPUT_VARIABLE(1); auto crop = INPUT_VARIABLE(2); auto output = OUTPUT_VARIABLE(0); REQUIRE_TRUE(blockShape->rankOf() == 1, 0, "BatchToSpaceND: rank of blockShape array must be equal to one, but got %i instead !", blockShape->rankOf()); const uint numOfSpatialDims = blockShape->sizeAt(0); const auto product = blockShape->reduceNumber(nd4j::reduce::Prod).e<Nd4jLong>(0); REQUIRE_TRUE(input->sizeAt(0) % product == 0, 0, "BatchToSpaceND: first dimension of input array must be divisible by product of blockShape array elements (= %lld), but got first dimension equal to %i", product, input->sizeAt(0)); if(crop->sizeAt(0) != numOfSpatialDims || crop->sizeAt(1) != 2) { const std::string expectedCropShape = "[" + std::to_string(numOfSpatialDims) + ", 2]"; // [numOfSpatialDims, 2] REQUIRE_TRUE(false, 0, "BatchToSpaceND: operation expects padding shape to be %s, but got %s instead", expectedCropShape.c_str(), ShapeUtils::shapeAsString(crop).c_str()); } // FIXME - should we use this time-consuming validation ? for (uint i = 0; i < numOfSpatialDims; ++i) { const auto cropLeft = crop->e<uint>(i,0); const auto cropRight = crop->e<uint>(i,1); const auto outSpatialDim = input->sizeAt(i + 1) * blockShape->e<Nd4jLong>(i) - cropLeft - cropRight; REQUIRE_TRUE(outSpatialDim >= 0, 0, "BatchToSpaceND: crop left/right values are too big and cause negative output spatial dimension/dimensions !"); } helpers::batchToSpaceND(block.launchContext(), *input, *blockShape, *crop, *output); return Status::OK(); } //////////////////////////////////////////////////////////////////////////////// DECLARE_TYPES(batch_to_space_nd) { getOpDescriptor()->setAllowedInputTypes(0, nd4j::DataType::ANY) ->setAllowedInputTypes(1, {ALL_INTS}) ->setAllowedInputTypes(2, {ALL_INTS}) ->setSameMode(true); } //////////////////////////////////////////////////////////////////////////////// DECLARE_SHAPE_FN(batch_to_space_nd) { auto inputShapeInfo = inputShape->at(0); auto blockShapeInfo = inputShape->at(1); auto cropShapeInfo = inputShape->at(2); REQUIRE_TRUE(blockShapeInfo[0] == 1, 0, "BatchToSpaceND: rank of blockShape array must be equal to one, but got %i instead !", blockShapeInfo[0]); const auto product = INPUT_VARIABLE(1)->reduceNumber(nd4j::reduce::Prod).e<Nd4jLong>(0); REQUIRE_TRUE(inputShapeInfo[1] % product == 0, 0, "BatchToSpaceND: first dimension of input array must be divisible by product of blockShape array elements (= %lld), but got first dimension equal to %i", product, inputShapeInfo[1]); const auto numOfSpatialDims = blockShapeInfo[1]; if(cropShapeInfo[1] != numOfSpatialDims || cropShapeInfo[2] != 2) { const std::string expectedCropShape = "[" + std::to_string(numOfSpatialDims) + ", 2]"; // [numOfSpatialDims, 2] REQUIRE_TRUE(false, 0, "BatchToSpaceND: operation expects padding shape to be %s, but got %s instead", expectedCropShape.c_str(), ShapeUtils::shapeAsString(cropShapeInfo).c_str()); } std::vector<Nd4jLong> outShape(inputShapeInfo + 1, inputShapeInfo + 1 + inputShapeInfo[0]); outShape[0] /= product; for (uint i = 0; i < numOfSpatialDims; ++i) outShape[i + 1] = outShape[i + 1] * INPUT_VARIABLE(1)->e<Nd4jLong>(i) - INPUT_VARIABLE(2)->e<uint>(i,0) - INPUT_VARIABLE(2)->e<uint>(i,1); return SHAPELIST(ConstantShapeHelper::getInstance()->createShapeInfo(ArrayOptions::dataType(inputShapeInfo), 'c', outShape)); } } } #endif
45.288
236
0.651828
steven-lang
147e127c13187317ac47851a21174ffa72a59d4c
1,930
cpp
C++
Server/socketUtils.cpp
sylwow/Cards-against-the-world
36a842da3fdeeccc990b2b60c6e49ff0441597e5
[ "MIT" ]
null
null
null
Server/socketUtils.cpp
sylwow/Cards-against-the-world
36a842da3fdeeccc990b2b60c6e49ff0441597e5
[ "MIT" ]
null
null
null
Server/socketUtils.cpp
sylwow/Cards-against-the-world
36a842da3fdeeccc990b2b60c6e49ff0441597e5
[ "MIT" ]
null
null
null
#include "socketUtils.h" socketUtils::socketUtils() { } socketUtils::~socketUtils() { } void socketUtils::addMessagePrefix(char* pos, uint16_t nmb, char coding, char playerId) { pos[0] = coding; nmb = htons(nmb); memcpy(pos + 1, (char*)& nmb, 2); pos[3] = playerId; } uint16_t socketUtils::getMessagePrefix(char* pos, char& coding, char& playerId) { coding = pos[0]; playerId = pos[3]; uint16_t* ptr = (uint16_t*)(pos + 1); return ntohs(*ptr); } std::u32string socketUtils::decode(char* pos, int limit, int reserve) { std::u32string str; str.reserve(reserve); mbstate_t p{}; bool tillEnd = !limit; char32_t x; int length; for (int i = 0; i < limit || tillEnd; i++) { length = mbrtoc32(&x, pos + i * 4, 4, &p); if (!length && tillEnd) break; str.push_back(x); } return str; } int socketUtils::code(const std::u32string & string, char* pos) { mbstate_t p{}; int size = string.size(); if (size + 2 > LEN || !size) return 0;//error size_t length; int i; for (i = 0; i < size; i++) { clear(pos + i * 4); length = c32rtomb(pos + i * 4, string[i], &p); } clear(pos + i * 4); return (++i) * 4; } void socketUtils::codeCard(char* pos, uint16_t card) { card = htons(card); memcpy(pos, (char*)& card, 2); } void socketUtils::codeCards(char* pos, std::vector<uint16_t> & cards) { for (int i = 0; i < cards.size(); i++) codeCard(pos + i * 2, cards.at(i)); } uint16_t socketUtils::decodeCard(char* pos) { uint16_t* ptr = (uint16_t*)(pos); return ntohs(*ptr); } std::vector<int> socketUtils::decodeCards(char* pos, int len) { std::vector<int> cards; for (int i = 0; i < len; i++) { cards.push_back(decodeCard(pos + i * 2)); } return cards; } void socketUtils::codeAllCards(char * pos, std::vector<std::array<int, 2>>& cardPlayer) { for (int i = 0; i < cardPlayer.size(); i++) { codeCard(pos + i * 3, cardPlayer.at(i).at(0)); *(pos + (i * 3) + 2) = cardPlayer.at(i).at(1); } }
21.931818
89
0.622798
sylwow
147ebc77e69e696db438a86048421918a06a8e0e
2,223
cpp
C++
mil_common/ros_alarms/src/ros_alarms/alarm_proxy.cpp
RishiKumarRay/mil
f3746a91e68aac713e86b380cdda8852ba826170
[ "MIT" ]
27
2020-02-17T21:54:09.000Z
2022-03-18T17:49:23.000Z
mil_common/ros_alarms/src/ros_alarms/alarm_proxy.cpp
RishiKumarRay/mil
f3746a91e68aac713e86b380cdda8852ba826170
[ "MIT" ]
325
2019-09-11T14:13:56.000Z
2022-03-31T00:38:30.000Z
mil_common/ros_alarms/src/ros_alarms/alarm_proxy.cpp
RishiKumarRay/mil
f3746a91e68aac713e86b380cdda8852ba826170
[ "MIT" ]
24
2019-09-16T00:29:45.000Z
2022-03-06T10:56:38.000Z
/** * Author: David Soto * Date: Jan 16, 2017 */ #include <ros_alarms/alarm_proxy.hpp> using namespace std; namespace ros_alarms { AlarmProxy::AlarmProxy(string _alarm_name, bool _raised, string _node_name, string _problem, string _json, int _severity) { alarm_name = _alarm_name; raised = _raised; node_name = _node_name; problem_description = _problem; json_parameters = _json; severity = _severity; } AlarmProxy::AlarmProxy(string _alarm_name, bool _raised, string _problem, string _json, int _severity) { *this = AlarmProxy(_alarm_name, _raised, ros::this_node::getName(), _problem, _json, _severity); } AlarmProxy::AlarmProxy(ros_alarms::Alarm msg) { alarm_name = msg.alarm_name; raised = msg.raised; node_name = msg.node_name; problem_description = msg.problem_description; json_parameters = msg.parameters; severity = msg.severity; } Alarm AlarmProxy::as_msg() { ros_alarms::Alarm a; a.alarm_name = alarm_name; a.raised = raised; a.node_name = node_name; a.problem_description = problem_description; a.parameters = json_parameters; a.severity = severity; return a; } std::string AlarmProxy::str(bool full) const { std::stringstream repr; repr << "[alarm_name: " << alarm_name << ", status: " << (raised ? "raised" : "cleared"); if (raised) repr << ", severity: " << severity; if (full) { repr << ", node_name: " << (node_name.empty() ? "N/A" : node_name) << ", problem: " << (problem_description.empty() ? "N/A" : problem_description) << ", json_parameters: " << (json_parameters.empty() ? "N/A" : json_parameters); } repr << "]"; return repr.str(); } bool AlarmProxy::operator==(const AlarmProxy &other) const { if (alarm_name != other.alarm_name) return false; if (raised != other.raised) return false; if (node_name != other.node_name) return false; if (problem_description != other.problem_description) return false; // JSON parameters can be stripped off by the alarm server if they can't be // deserialized if(json_parameters != other.json_parameters) return false; if (severity != other.severity) return false; return true; } } // namespace ros_alarms
26.783133
106
0.683311
RishiKumarRay
14802d5e52e55151331428b93f76038bb810446a
1,288
cc
C++
Phase2Sim/src/PRIMSD.cc
uiowahep/Old
e52c4a67960028010904a1214f7d060c92f3da8c
[ "Apache-2.0" ]
null
null
null
Phase2Sim/src/PRIMSD.cc
uiowahep/Old
e52c4a67960028010904a1214f7d060c92f3da8c
[ "Apache-2.0" ]
null
null
null
Phase2Sim/src/PRIMSD.cc
uiowahep/Old
e52c4a67960028010904a1214f7d060c92f3da8c
[ "Apache-2.0" ]
null
null
null
#include "PRIMSD.hh" #include "G4UnitsTable.hh" #include "G4TrackStatus.hh" #include "G4VProcess.hh" using namespace CLHEP; // // Constructor // PRIMSD::PRIMSD(G4String name, RunParams runParams, int id, HGCReadoutModule *readout) : G4VSensitiveDetector(name), _runParams(runParams), _readout(readout) { // _readout = (HGCReadoutModule*)readout; G4cout << "### Setting up PRIMSD for id: " << id << " " << name << G4endl; _id = id; _readout->Book(id); } // // Destructor // PRIMSD::~PRIMSD() { } // // Pre Event TODO // void PRIMSD::Initialize(G4HCofThisEvent*) { _readout->BeginEvent(_id); } // // End of Event TODO // void PRIMSD::EndOfEvent(G4HCofThisEvent*) { _readout->FinishEvent(_id); } // // Process Hit // G4bool PRIMSD::ProcessHits(G4Step* aStep, G4TouchableHistory*) { // // Look at Primary Tracks only // if (aStep->GetTrack()->GetParentID() == 0) { PRIMHit aHit; aHit.pos = aStep->GetPreStepPoint()->GetPosition(); aHit.mom = aStep->GetPreStepPoint()->GetMomentum(); aHit.ene = aStep->GetPreStepPoint()->GetKineticEnergy(); aHit.name = aStep->GetTrack()->GetParticleDefinition()->GetParticleName(); aHit.id = aStep->GetTrack()->GetParticleDefinition()->GetPDGEncoding(); _readout->PushHit(aHit); } return true; }
14.976744
76
0.67236
uiowahep
1481c8692ad5a3d42770a9c7933c63cdd26738a1
529
hpp
C++
posix/subsystem/src/nl-socket.hpp
robertlipe/managarm
5e6173abb2f2b1c365e6774074380255bcccf3a5
[ "MIT" ]
null
null
null
posix/subsystem/src/nl-socket.hpp
robertlipe/managarm
5e6173abb2f2b1c365e6774074380255bcccf3a5
[ "MIT" ]
null
null
null
posix/subsystem/src/nl-socket.hpp
robertlipe/managarm
5e6173abb2f2b1c365e6774074380255bcccf3a5
[ "MIT" ]
null
null
null
#include "file.hpp" namespace nl_socket { // Configures the given netlink protocol. // TODO: Let this take a callback that is called on receive? void configure(int proto_idx, int num_groups); // Broadcasts a kernel message to the given netlink multicast group. void broadcast(int proto_idx, int grp_idx, std::string buffer); smarter::shared_ptr<File, FileHandle> createSocketFile(int proto_idx, bool nonBlock); std::array<smarter::shared_ptr<File, FileHandle>, 2> createSocketPair(int proto_idx); } // namespace nl_socket
29.388889
85
0.775047
robertlipe
1482d94626286d2fbe4bc5d9e97cadf7fe07c715
7,663
cpp
C++
GlobalIllumination/src/DemoMesh.cpp
raptoravis/voxelbasedgi
aaf2b02929edfaf72528c2f029696728c5f1d30f
[ "MIT" ]
null
null
null
GlobalIllumination/src/DemoMesh.cpp
raptoravis/voxelbasedgi
aaf2b02929edfaf72528c2f029696728c5f1d30f
[ "MIT" ]
null
null
null
GlobalIllumination/src/DemoMesh.cpp
raptoravis/voxelbasedgi
aaf2b02929edfaf72528c2f029696728c5f1d30f
[ "MIT" ]
null
null
null
#include <stdafx.h> #include <Demo.h> #include <GlobalIllum.h> #include <DemoMesh.h> void DemoMesh::Release() { SAFE_DELETE_PLIST(subMeshes); } bool DemoMesh::Load(const char *filename) { // cache pointer to GlobalIllum post-processor globalIllumPP = (GlobalIllum*)Demo::renderer->GetPostProcessor("GlobalIllum"); if (!globalIllumPP) return false; // load ".mesh" file strcpy(name, filename); char filePath[DEMO_MAX_FILEPATH]; if (!Demo::fileManager->GetFilePath(filename, filePath)) return false; FILE *file; fopen_s(&file, filePath, "rb"); if (!file) return false; // check idString char idString[5]; memset(idString, 0, 5); fread(idString, sizeof(char), 4, file); if (strcmp(idString, "DMSH") != 0) { fclose(file); return false; } // check version unsigned int version; fread(&version, sizeof(unsigned int), 1, file); if (version != CURRENT_DEMO_MESH_VERSION) { fclose(file); return false; } // get number of vertices unsigned int numVertices; fread(&numVertices, sizeof(unsigned int), 1, file); if (numVertices < 3) { fclose(file); return false; } // load vertices GeometryVertex *vertices = new GeometryVertex[numVertices]; if (!vertices) { fclose(file); return false; } fread(vertices, sizeof(GeometryVertex), numVertices, file); // create vertex layout for base pass VertexElementDesc vertexElementDescs[4] = { POSITION_ELEMENT, R32G32B32_FLOAT_EF, 0, TEXCOORDS_ELEMENT, R32G32_FLOAT_EF, 12, NORMAL_ELEMENT, R32G32B32_FLOAT_EF, 20, TANGENT_ELEMENT, R32G32B32A32_FLOAT_EF, 32 }; baseVertexLayout = Demo::renderer->CreateVertexLayout(vertexElementDescs, 4); if (!baseVertexLayout) return false; // create vertex layout for voxel grid generation gridVertexLayout = Demo::renderer->CreateVertexLayout(vertexElementDescs, 3); if (!gridVertexLayout) return false; // create vertex layout for shadow map generation shadowVertexLayout = Demo::renderer->CreateVertexLayout(vertexElementDescs, 1); if (!shadowVertexLayout) return false; // create vertex buffer vertexBuffer = Demo::renderer->CreateVertexBuffer(sizeof(GeometryVertex), numVertices, false); if (!vertexBuffer) { SAFE_DELETE_ARRAY(vertices); fclose(file); return false; } vertexBuffer->AddVertices(numVertices, (float*)vertices); vertexBuffer->Update(); SAFE_DELETE_ARRAY(vertices); // get number of indices unsigned int numIndices; fread(&numIndices, sizeof(unsigned int), 1, file); if (numIndices < 3) { fclose(file); return false; } // load indices unsigned int *indices = new unsigned int[numIndices]; if (!indices) { fclose(file); return false; } fread(indices, sizeof(unsigned int), numIndices, file); // create index-buffer indexBuffer = Demo::renderer->CreateIndexBuffer(numIndices, false); if (!indexBuffer) { SAFE_DELETE_ARRAY(indices); fclose(file); return false; } indexBuffer->AddIndices(numIndices, indices); indexBuffer->Update(); SAFE_DELETE_ARRAY(indices); // get number of sub-meshes unsigned int numSubMeshes; fread(&numSubMeshes, sizeof(unsigned int), 1, file); if (numSubMeshes < 1) { fclose(file); return false; } // load/ create sub-meshes for (unsigned int i = 0; i < numSubMeshes; i++) { DemoSubmesh *subMesh = new DemoSubmesh; if (!subMesh) { fclose(file); return false; } char materialName[256]; fread(materialName, sizeof(char), 256, file); subMesh->material = Demo::resourceManager->LoadMaterial(materialName); if (!subMesh->material) { fclose(file); SAFE_DELETE(subMesh); return false; } fread(&subMesh->firstIndex, sizeof(unsigned int), 1, file); fread(&subMesh->numIndices, sizeof(unsigned int), 1, file); subMeshes.AddElement(&subMesh); } fclose(file); uniformBuffer = Demo::renderer->CreateUniformBuffer(sizeof(Vector3)); if (!uniformBuffer) return false; // render into albedoGloss and normal render-target of GBuffers RtConfigDesc rtcDesc; rtcDesc.numColorBuffers = 2; rtcDesc.firstColorBufferIndex = 1; multiRTC = Demo::renderer->CreateRenderTargetConfig(rtcDesc); if (!multiRTC) return false; Update(); return true; } void DemoMesh::Update() { if (!performUpdate) return; uniformBuffer->Update(position); performUpdate = false; } void DemoMesh::SetPosition(const Vector3 &position) { if (this->position == position) return; this->position = position; performUpdate = true; } void DemoMesh::AddBaseSurfaces() { for (unsigned int i = 0; i < subMeshes.GetSize(); i++) { GpuCmd gpuCmd(DRAW_CM); gpuCmd.order = BASE_CO; gpuCmd.draw.renderTarget = Demo::renderer->GetRenderTarget(GBUFFERS_RT_ID); gpuCmd.draw.renderTargetConfig = multiRTC; gpuCmd.draw.primitiveType = TRIANGLES_PRIMITIVE; gpuCmd.draw.camera = Demo::renderer->GetCamera(MAIN_CAMERA_ID); gpuCmd.draw.vertexLayout = baseVertexLayout; gpuCmd.draw.vertexBuffer = vertexBuffer; gpuCmd.draw.indexBuffer = indexBuffer; gpuCmd.draw.firstIndex = subMeshes[i]->firstIndex; gpuCmd.draw.numElements = subMeshes[i]->numIndices; gpuCmd.draw.textures[COLOR_TEX_ID] = subMeshes[i]->material->colorTexture; gpuCmd.draw.samplers[COLOR_TEX_ID] = Demo::renderer->GetSampler(TRILINEAR_SAMPLER_ID); gpuCmd.draw.textures[NORMAL_TEX_ID] = subMeshes[i]->material->normalTexture; gpuCmd.draw.textures[SPECULAR_TEX_ID] = subMeshes[i]->material->specularTexture; gpuCmd.draw.rasterizerState = subMeshes[i]->material->rasterizerState; gpuCmd.draw.depthStencilState = subMeshes[i]->material->depthStencilState; gpuCmd.draw.blendState = subMeshes[i]->material->blendState; gpuCmd.draw.customUBs[0] = uniformBuffer; gpuCmd.draw.shader = subMeshes[i]->material->shader; Demo::renderer->AddGpuCmd(gpuCmd); } } void DemoMesh::AddGridSurfaces() { if (globalIllumPP->GetGlobalIllumMode() == DIRECT_ILLUM_ONLY_GIM) return; // add surfaces for generating voxel-grids for (unsigned int i = 0; i < 2; i++) { for (unsigned int j = 0; j < subMeshes.GetSize(); j++) { GpuCmd gpuCmd(DRAW_CM); gpuCmd.order = GRID_FILL_CO; gpuCmd.draw.vertexLayout = gridVertexLayout; gpuCmd.draw.vertexBuffer = vertexBuffer; gpuCmd.draw.indexBuffer = indexBuffer; gpuCmd.draw.primitiveType = TRIANGLES_PRIMITIVE; gpuCmd.draw.firstIndex = subMeshes[j]->firstIndex; gpuCmd.draw.numElements = subMeshes[j]->numIndices; gpuCmd.draw.textures[COLOR_TEX_ID] = subMeshes[j]->material->colorTexture; gpuCmd.draw.samplers[COLOR_TEX_ID] = Demo::renderer->GetSampler(TRILINEAR_SAMPLER_ID); gpuCmd.draw.customUBs[0] = uniformBuffer; globalIllumPP->SetupGridSurface(gpuCmd.draw, (gridTypes)i); Demo::renderer->AddGpuCmd(gpuCmd); } } } void DemoMesh::AddShadowMapSurfaces(unsigned int lightIndex) { for (unsigned int i = 0; i < subMeshes.GetSize(); i++) { GpuCmd gpuCmd(DRAW_CM); gpuCmd.order = SHADOW_CO; gpuCmd.draw.vertexLayout = shadowVertexLayout; gpuCmd.draw.vertexBuffer = vertexBuffer; gpuCmd.draw.indexBuffer = indexBuffer; gpuCmd.draw.primitiveType = TRIANGLES_PRIMITIVE; gpuCmd.draw.firstIndex = subMeshes[i]->firstIndex; gpuCmd.draw.numElements = subMeshes[i]->numIndices; gpuCmd.draw.customUBs[0] = uniformBuffer; Demo::renderer->GetLight(lightIndex)->SetupShadowMapSurface(gpuCmd.draw); Demo::renderer->AddGpuCmd(gpuCmd); } } void DemoMesh::AddSurfaces() { if (!active) return; Update(); AddBaseSurfaces(); AddGridSurfaces(); for (unsigned int i = 0; i < Demo::renderer->GetNumLights(); i++) { if ((!Demo::renderer->GetLight(i)->IsActive()) || (!Demo::renderer->GetLight(i)->HasShadow())) continue; AddShadowMapSurfaces(i); } }
27.367857
96
0.724129
raptoravis
148443f31e06c8ad291dbfd6383580d424ab1f1c
327
cpp
C++
LeetCode/974.subarray-sums-divisible-by-k.ac.cpp
Kresnt/AlgorithmTraining
3dec1e712f525b4f406fe669d97888f322dfca97
[ "MIT" ]
null
null
null
LeetCode/974.subarray-sums-divisible-by-k.ac.cpp
Kresnt/AlgorithmTraining
3dec1e712f525b4f406fe669d97888f322dfca97
[ "MIT" ]
null
null
null
LeetCode/974.subarray-sums-divisible-by-k.ac.cpp
Kresnt/AlgorithmTraining
3dec1e712f525b4f406fe669d97888f322dfca97
[ "MIT" ]
null
null
null
class Solution { public: int subarraysDivByK(vector<int>& A, int K) { const int maxm = 10000 + 7; const int n = A.size(); int c[maxm] = {0}; int ans = 0; c[0] = 1; for(int i = 0, l = 0; i < n; ++i) { l = (l + A[i] % K + K) % K; c[l]++; ans += c[l] - 1; } return ans; } };
19.235294
46
0.425076
Kresnt
148559db6a70da2bc408c303d4be7d6dd2ce1227
1,334
cpp
C++
Lamia/src/Systems/Systems.cpp
Alorafae/Lamia
bf2dd1cf7427fae8728abbb6a718a5223ab68caa
[ "MIT" ]
null
null
null
Lamia/src/Systems/Systems.cpp
Alorafae/Lamia
bf2dd1cf7427fae8728abbb6a718a5223ab68caa
[ "MIT" ]
null
null
null
Lamia/src/Systems/Systems.cpp
Alorafae/Lamia
bf2dd1cf7427fae8728abbb6a718a5223ab68caa
[ "MIT" ]
null
null
null
#include "Systems.h" using namespace LamiaSystems; static Systems* g_LamiaSystem; LAMIA_RESULT LamiaSystems::LamiaSystemsInit(void) { // initialize the system itself g_LamiaSystem = new Systems; // initialize our sub systems file, audio, graphics, etc bool ret = LamiaFileInit(); if (ret == false) return LAMIA_E_AUDIO_SYS; // this is setting our file system pointer lf in g_LamiaSystem g_LamiaSystem->SetFileSystemPtr(LamiaFileGetSystem()); //-- end audio ret = LamiaInputInit(); if (ret == false) return LAMIA_E_INPUT_SYS; g_LamiaSystem->SetInputSystemPtr(LamiaInputGetSystem()); return LAMIA_E_SUCCESS; } LAMIA_RESULT LamiaSystems::LamiaSystemsShutdown(void) { delete g_LamiaSystem; return LAMIA_E_SUCCESS; } Systems* const LamiaSystems::LamiaSystem(void) { return g_LamiaSystem; } Systems::Systems() { } Systems::~Systems() { } LamiaFile* const Systems::FileSystem(void) { return LFileSys; // should no longer be null anymore } LamiaInput * const LamiaSystems::Systems::InputSystem(void) { return LInputSys; } void LamiaSystems::Systems::SetFileSystemPtr(LamiaFile * fileSys) { LFileSys = fileSys; } void LamiaSystems::Systems::SetInputSystemPtr(LamiaInput * inputSys) { LInputSys = inputSys; }
18.788732
69
0.703898
Alorafae
14858075ad5c4397785b7819e088c436c4924844
26,689
cpp
C++
vbox/src/VBox/VMM/testcase/tstSSM.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/VMM/testcase/tstSSM.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
vbox/src/VBox/VMM/testcase/tstSSM.cpp
Nurzamal/rest_api_docker
a9cc01dfc235467d490d9663755b33ef6990bdd8
[ "MIT" ]
null
null
null
/* $Id: tstSSM.cpp 69111 2017-10-17 14:26:02Z vboxsync $ */ /** @file * Saved State Manager Testcase. */ /* * Copyright (C) 2006-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include <VBox/vmm/ssm.h> #include "VMInternal.h" /* createFakeVM */ #include <VBox/vmm/vm.h> #include <VBox/vmm/uvm.h> #include <VBox/vmm/mm.h> #include <VBox/vmm/stam.h> #include <VBox/log.h> #include <VBox/sup.h> #include <VBox/err.h> #include <VBox/param.h> #include <iprt/assert.h> #include <iprt/file.h> #include <iprt/initterm.h> #include <iprt/mem.h> #include <iprt/stream.h> #include <iprt/string.h> #include <iprt/time.h> #include <iprt/thread.h> #include <iprt/path.h> /********************************************************************************************************************************* * Defined Constants And Macros * *********************************************************************************************************************************/ #define TSTSSM_BIG_CONFIG 1 #ifdef TSTSSM_BIG_CONFIG # define TSTSSM_ITEM_SIZE (512*_1M) #else # define TSTSSM_ITEM_SIZE (5*_1M) #endif /********************************************************************************************************************************* * Global Variables * *********************************************************************************************************************************/ const uint8_t gabPage[PAGE_SIZE] = {0}; const char gachMem1[] = "sdfg\1asdfa\177hjkl;sdfghjkl;dfghjkl;dfghjkl;\0\0asdf;kjasdf;lkjasd;flkjasd;lfkjasd\0;lfk"; #ifdef TSTSSM_BIG_CONFIG uint8_t gabBigMem[_1M]; #else uint8_t gabBigMem[8*_1M]; #endif /** initializes gabBigMem with some non zero stuff. */ void initBigMem(void) { #if 0 uint32_t *puch = (uint32_t *)&gabBigMem[0]; uint32_t *puchEnd = (uint32_t *)&gabBigMem[sizeof(gabBigMem)]; uint32_t u32 = 0xdeadbeef; for (; puch < puchEnd; puch++) { *puch = u32; u32 += 19; u32 = (u32 << 1) | (u32 >> 31); } #else uint8_t *pb = &gabBigMem[0]; uint8_t *pbEnd = &gabBigMem[sizeof(gabBigMem)]; for (; pb < pbEnd; pb += 16) { char szTmp[17]; RTStrPrintf(szTmp, sizeof(szTmp), "aaaa%08Xzzzz", (uint32_t)(uintptr_t)pb); memcpy(pb, szTmp, 16); } /* add some zero pages */ memset(&gabBigMem[sizeof(gabBigMem) / 4], 0, PAGE_SIZE * 4); memset(&gabBigMem[sizeof(gabBigMem) / 4 * 3], 0, PAGE_SIZE * 4); #endif } /** * Execute state save operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. */ DECLCALLBACK(int) Item01Save(PVM pVM, PSSMHANDLE pSSM) { uint64_t u64Start = RTTimeNanoTS(); NOREF(pVM); /* * Test writing some memory block. */ int rc = SSMR3PutMem(pSSM, gachMem1, sizeof(gachMem1)); if (RT_FAILURE(rc)) { RTPrintf("Item01: #1 - SSMR3PutMem -> %Rrc\n", rc); return rc; } /* * Test writing a zeroterminated string. */ rc = SSMR3PutStrZ(pSSM, "String"); if (RT_FAILURE(rc)) { RTPrintf("Item01: #1 - SSMR3PutMem -> %Rrc\n", rc); return rc; } /* * Test the individual integer put functions to see that they all work. * (Testcases are also known as "The Land of The Ugly Code"...) */ #define ITEM(suff,bits, val) \ rc = SSMR3Put##suff(pSSM, val); \ if (RT_FAILURE(rc)) \ { \ RTPrintf("Item01: #" #suff " - SSMR3Put" #suff "(," #val ") -> %Rrc\n", rc); \ return rc; \ } /* copy & past with the load one! */ ITEM(U8, uint8_t, 0xff); ITEM(U8, uint8_t, 0x0); ITEM(U8, uint8_t, 1); ITEM(U8, uint8_t, 42); ITEM(U8, uint8_t, 230); ITEM(S8, int8_t, -128); ITEM(S8, int8_t, 127); ITEM(S8, int8_t, 12); ITEM(S8, int8_t, -76); ITEM(U16, uint16_t, 0xffff); ITEM(U16, uint16_t, 0x0); ITEM(S16, int16_t, 32767); ITEM(S16, int16_t, -32768); ITEM(U32, uint32_t, 4294967295U); ITEM(U32, uint32_t, 0); ITEM(U32, uint32_t, 42); ITEM(U32, uint32_t, 2342342344U); ITEM(S32, int32_t, -2147483647-1); ITEM(S32, int32_t, 2147483647); ITEM(S32, int32_t, 42); ITEM(S32, int32_t, 568459834); ITEM(S32, int32_t, -58758999); ITEM(U64, uint64_t, 18446744073709551615ULL); ITEM(U64, uint64_t, 0); ITEM(U64, uint64_t, 42); ITEM(U64, uint64_t, 593023944758394234ULL); ITEM(S64, int64_t, 9223372036854775807LL); ITEM(S64, int64_t, -9223372036854775807LL - 1); ITEM(S64, int64_t, 42); ITEM(S64, int64_t, 21398723459873LL); ITEM(S64, int64_t, -5848594593453453245LL); #undef ITEM uint64_t u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Saved 1st item in %'RI64 ns\n", u64Elapsed); return 0; } /** * Prepare state load operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. * @param uVersion The data layout version. * @param uPass The data pass. */ DECLCALLBACK(int) Item01Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass) { NOREF(pVM); NOREF(uPass); if (uVersion != 0) { RTPrintf("Item01: uVersion=%#x, expected 0\n", uVersion); return VERR_GENERAL_FAILURE; } /* * Load the memory block. */ char achTmp[sizeof(gachMem1)]; int rc = SSMR3GetMem(pSSM, achTmp, sizeof(gachMem1)); if (RT_FAILURE(rc)) { RTPrintf("Item01: #1 - SSMR3GetMem -> %Rrc\n", rc); return rc; } /* * Load the string. */ rc = SSMR3GetStrZ(pSSM, achTmp, sizeof(achTmp)); if (RT_FAILURE(rc)) { RTPrintf("Item01: #2 - SSMR3GetStrZ -> %Rrc\n", rc); return rc; } /* * Test the individual integer put functions to see that they all work. * (Testcases are also known as "The Land of The Ugly Code"...) */ #define ITEM(suff, type, val) \ do { \ type var = {0}; \ rc = SSMR3Get##suff(pSSM, &var); \ if (RT_FAILURE(rc)) \ { \ RTPrintf("Item01: #" #suff " - SSMR3Get" #suff "(," #val ") -> %Rrc\n", rc); \ return rc; \ } \ if (var != val) \ { \ RTPrintf("Item01: #" #suff " - SSMR3Get" #suff "(," #val ") -> %d returned wrong value!\n", rc); \ return VERR_GENERAL_FAILURE; \ } \ } while (0) /* copy & past with the load one! */ ITEM(U8, uint8_t, 0xff); ITEM(U8, uint8_t, 0x0); ITEM(U8, uint8_t, 1); ITEM(U8, uint8_t, 42); ITEM(U8, uint8_t, 230); ITEM(S8, int8_t, -128); ITEM(S8, int8_t, 127); ITEM(S8, int8_t, 12); ITEM(S8, int8_t, -76); ITEM(U16, uint16_t, 0xffff); ITEM(U16, uint16_t, 0x0); ITEM(S16, int16_t, 32767); ITEM(S16, int16_t, -32768); ITEM(U32, uint32_t, 4294967295U); ITEM(U32, uint32_t, 0); ITEM(U32, uint32_t, 42); ITEM(U32, uint32_t, 2342342344U); ITEM(S32, int32_t, -2147483647-1); ITEM(S32, int32_t, 2147483647); ITEM(S32, int32_t, 42); ITEM(S32, int32_t, 568459834); ITEM(S32, int32_t, -58758999); ITEM(U64, uint64_t, 18446744073709551615ULL); ITEM(U64, uint64_t, 0); ITEM(U64, uint64_t, 42); ITEM(U64, uint64_t, 593023944758394234ULL); ITEM(S64, int64_t, 9223372036854775807LL); ITEM(S64, int64_t, -9223372036854775807LL - 1); ITEM(S64, int64_t, 42); ITEM(S64, int64_t, 21398723459873LL); ITEM(S64, int64_t, -5848594593453453245LL); #undef ITEM return 0; } /** * Execute state save operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. */ DECLCALLBACK(int) Item02Save(PVM pVM, PSSMHANDLE pSSM) { NOREF(pVM); uint64_t u64Start = RTTimeNanoTS(); /* * Put the size. */ uint32_t cb = sizeof(gabBigMem); int rc = SSMR3PutU32(pSSM, cb); if (RT_FAILURE(rc)) { RTPrintf("Item02: PutU32 -> %Rrc\n", rc); return rc; } /* * Put 8MB of memory to the file in 3 chunks. */ uint8_t *pbMem = &gabBigMem[0]; uint32_t cbChunk = cb / 47; rc = SSMR3PutMem(pSSM, pbMem, cbChunk); if (RT_FAILURE(rc)) { RTPrintf("Item02: PutMem(,%p,%#x) -> %Rrc\n", pbMem, cbChunk, rc); return rc; } cb -= cbChunk; pbMem += cbChunk; /* next piece. */ cbChunk *= 19; rc = SSMR3PutMem(pSSM, pbMem, cbChunk); if (RT_FAILURE(rc)) { RTPrintf("Item02: PutMem(,%p,%#x) -> %Rrc\n", pbMem, cbChunk, rc); return rc; } cb -= cbChunk; pbMem += cbChunk; /* last piece. */ cbChunk = cb; rc = SSMR3PutMem(pSSM, pbMem, cbChunk); if (RT_FAILURE(rc)) { RTPrintf("Item02: PutMem(,%p,%#x) -> %Rrc\n", pbMem, cbChunk, rc); return rc; } uint64_t u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Saved 2nd item in %'RI64 ns\n", u64Elapsed); return 0; } /** * Prepare state load operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. * @param uVersion The data layout version. * @param uPass The data pass. */ DECLCALLBACK(int) Item02Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass) { NOREF(pVM); NOREF(uPass); if (uVersion != 0) { RTPrintf("Item02: uVersion=%#x, expected 0\n", uVersion); return VERR_GENERAL_FAILURE; } /* * Load the size. */ uint32_t cb; int rc = SSMR3GetU32(pSSM, &cb); if (RT_FAILURE(rc)) { RTPrintf("Item02: SSMR3GetU32 -> %Rrc\n", rc); return rc; } if (cb != sizeof(gabBigMem)) { RTPrintf("Item02: loaded size doesn't match the real thing. %#x != %#x\n", cb, sizeof(gabBigMem)); return VERR_GENERAL_FAILURE; } /* * Load the memory chunk by chunk. */ uint8_t *pbMem = &gabBigMem[0]; char achTmp[16383]; uint32_t cbChunk = sizeof(achTmp); while (cb > 0) { cbChunk -= 7; if (cbChunk < 64) cbChunk = sizeof(achTmp) - (cbChunk % 47); if (cbChunk > cb) cbChunk = cb; rc = SSMR3GetMem(pSSM, &achTmp[0], cbChunk); if (RT_FAILURE(rc)) { RTPrintf("Item02: SSMR3GetMem(,,%#x) -> %d offset %#x\n", cbChunk, rc, pbMem - &gabBigMem[0]); return rc; } if (memcmp(achTmp, pbMem, cbChunk)) { RTPrintf("Item02: compare failed. mem offset=%#x cbChunk=%#x\n", pbMem - &gabBigMem[0], cbChunk); return VERR_GENERAL_FAILURE; } /* next */ pbMem += cbChunk; cb -= cbChunk; } return 0; } /** * Execute state save operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. */ DECLCALLBACK(int) Item03Save(PVM pVM, PSSMHANDLE pSSM) { NOREF(pVM); uint64_t u64Start = RTTimeNanoTS(); /* * Put the size. */ uint32_t cb = TSTSSM_ITEM_SIZE; int rc = SSMR3PutU32(pSSM, cb); if (RT_FAILURE(rc)) { RTPrintf("Item03: PutU32 -> %Rrc\n", rc); return rc; } /* * Put 512 MB page by page. */ const uint8_t *pu8Org = &gabBigMem[0]; while (cb > 0) { rc = SSMR3PutMem(pSSM, pu8Org, PAGE_SIZE); if (RT_FAILURE(rc)) { RTPrintf("Item03: PutMem(,%p,%#x) -> %Rrc\n", pu8Org, PAGE_SIZE, rc); return rc; } /* next */ cb -= PAGE_SIZE; pu8Org += PAGE_SIZE; if (pu8Org >= &gabBigMem[sizeof(gabBigMem)]) pu8Org = &gabBigMem[0]; } uint64_t u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Saved 3rd item in %'RI64 ns\n", u64Elapsed); return 0; } /** * Prepare state load operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. * @param uVersion The data layout version. * @param uPass The data pass. */ DECLCALLBACK(int) Item03Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass) { NOREF(pVM); NOREF(uPass); if (uVersion != 123) { RTPrintf("Item03: uVersion=%#x, expected 123\n", uVersion); return VERR_GENERAL_FAILURE; } /* * Load the size. */ uint32_t cb; int rc = SSMR3GetU32(pSSM, &cb); if (RT_FAILURE(rc)) { RTPrintf("Item03: SSMR3GetU32 -> %Rrc\n", rc); return rc; } if (cb != TSTSSM_ITEM_SIZE) { RTPrintf("Item03: loaded size doesn't match the real thing. %#x != %#x\n", cb, TSTSSM_ITEM_SIZE); return VERR_GENERAL_FAILURE; } /* * Load the memory page by page. */ const uint8_t *pu8Org = &gabBigMem[0]; while (cb > 0) { char achPage[PAGE_SIZE]; rc = SSMR3GetMem(pSSM, &achPage[0], PAGE_SIZE); if (RT_FAILURE(rc)) { RTPrintf("Item03: SSMR3GetMem(,,%#x) -> %Rrc offset %#x\n", PAGE_SIZE, rc, TSTSSM_ITEM_SIZE - cb); return rc; } if (memcmp(achPage, pu8Org, PAGE_SIZE)) { RTPrintf("Item03: compare failed. mem offset=%#x\n", TSTSSM_ITEM_SIZE - cb); return VERR_GENERAL_FAILURE; } /* next */ cb -= PAGE_SIZE; pu8Org += PAGE_SIZE; if (pu8Org >= &gabBigMem[sizeof(gabBigMem)]) pu8Org = &gabBigMem[0]; } return 0; } /** * Execute state save operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. */ DECLCALLBACK(int) Item04Save(PVM pVM, PSSMHANDLE pSSM) { NOREF(pVM); uint64_t u64Start = RTTimeNanoTS(); /* * Put the size. */ uint32_t cb = 512*_1M; int rc = SSMR3PutU32(pSSM, cb); if (RT_FAILURE(rc)) { RTPrintf("Item04: PutU32 -> %Rrc\n", rc); return rc; } /* * Put 512 MB page by page. */ while (cb > 0) { rc = SSMR3PutMem(pSSM, gabPage, PAGE_SIZE); if (RT_FAILURE(rc)) { RTPrintf("Item04: PutMem(,%p,%#x) -> %Rrc\n", gabPage, PAGE_SIZE, rc); return rc; } /* next */ cb -= PAGE_SIZE; } uint64_t u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Saved 4th item in %'RI64 ns\n", u64Elapsed); return 0; } /** * Prepare state load operation. * * @returns VBox status code. * @param pVM The cross context VM handle. * @param pSSM SSM operation handle. * @param uVersion The data layout version. * @param uPass The data pass. */ DECLCALLBACK(int) Item04Load(PVM pVM, PSSMHANDLE pSSM, uint32_t uVersion, uint32_t uPass) { NOREF(pVM); NOREF(uPass); if (uVersion != 42) { RTPrintf("Item04: uVersion=%#x, expected 42\n", uVersion); return VERR_GENERAL_FAILURE; } /* * Load the size. */ uint32_t cb; int rc = SSMR3GetU32(pSSM, &cb); if (RT_FAILURE(rc)) { RTPrintf("Item04: SSMR3GetU32 -> %Rrc\n", rc); return rc; } if (cb != 512*_1M) { RTPrintf("Item04: loaded size doesn't match the real thing. %#x != %#x\n", cb, 512*_1M); return VERR_GENERAL_FAILURE; } /* * Load the memory page by page. */ while (cb > 0) { char achPage[PAGE_SIZE]; rc = SSMR3GetMem(pSSM, &achPage[0], PAGE_SIZE); if (RT_FAILURE(rc)) { RTPrintf("Item04: SSMR3GetMem(,,%#x) -> %Rrc offset %#x\n", PAGE_SIZE, rc, 512*_1M - cb); return rc; } if (memcmp(achPage, gabPage, PAGE_SIZE)) { RTPrintf("Item04: compare failed. mem offset=%#x\n", 512*_1M - cb); return VERR_GENERAL_FAILURE; } /* next */ cb -= PAGE_SIZE; } return 0; } /** * Creates a mockup VM structure for testing SSM. * * @returns 0 on success, 1 on failure. * @param ppVM Where to store Pointer to the VM. * * @todo Move this to VMM/VM since it's stuff done by several testcases. */ static int createFakeVM(PVM *ppVM) { /* * Allocate and init the UVM structure. */ PUVM pUVM = (PUVM)RTMemPageAllocZ(sizeof(*pUVM)); AssertReturn(pUVM, 1); pUVM->u32Magic = UVM_MAGIC; pUVM->vm.s.idxTLS = RTTlsAlloc(); int rc = RTTlsSet(pUVM->vm.s.idxTLS, &pUVM->aCpus[0]); if (RT_SUCCESS(rc)) { pUVM->aCpus[0].pUVM = pUVM; pUVM->aCpus[0].vm.s.NativeThreadEMT = RTThreadNativeSelf(); rc = STAMR3InitUVM(pUVM); if (RT_SUCCESS(rc)) { rc = MMR3InitUVM(pUVM); if (RT_SUCCESS(rc)) { /* * Allocate and init the VM structure. */ PVM pVM; rc = SUPR3PageAlloc((sizeof(*pVM) + PAGE_SIZE - 1) >> PAGE_SHIFT, (void **)&pVM); if (RT_SUCCESS(rc)) { pVM->enmVMState = VMSTATE_CREATED; pVM->pVMR3 = pVM; pVM->pUVM = pUVM; pVM->cCpus = 1; pVM->aCpus[0].pVMR3 = pVM; pVM->aCpus[0].hNativeThread = RTThreadNativeSelf(); pUVM->pVM = pVM; *ppVM = pVM; return 0; } RTPrintf("Fatal error: failed to allocated pages for the VM structure, rc=%Rrc\n", rc); } else RTPrintf("Fatal error: MMR3InitUVM failed, rc=%Rrc\n", rc); } else RTPrintf("Fatal error: SSMR3InitUVM failed, rc=%Rrc\n", rc); } else RTPrintf("Fatal error: RTTlsSet failed, rc=%Rrc\n", rc); *ppVM = NULL; return 1; } /** * Destroy the VM structure. * * @param pVM Pointer to the VM. * * @todo Move this to VMM/VM since it's stuff done by several testcases. */ static void destroyFakeVM(PVM pVM) { STAMR3TermUVM(pVM->pUVM); MMR3TermUVM(pVM->pUVM); } /** * Entry point. */ extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp) { RT_NOREF1(envp); /* * Init runtime and static data. */ RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB); RTPrintf("tstSSM: TESTING...\n"); initBigMem(); const char *pszFilename = "SSMTestSave#1"; /* * Create an fake VM structure and init SSM. */ int rc = SUPR3Init(NULL); if (RT_FAILURE(rc)) { RTPrintf("Fatal error: SUP Failure! rc=%Rrc\n", rc); return 1; } PVM pVM; if (createFakeVM(&pVM)) return 1; /* * Register a few callbacks. */ rc = SSMR3RegisterInternal(pVM, "SSM Testcase Data Item no.1 (all types)", 1, 0, 256, NULL, NULL, NULL, NULL, Item01Save, NULL, NULL, Item01Load, NULL); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Register #1 -> %Rrc\n", rc); return 1; } rc = SSMR3RegisterInternal(pVM, "SSM Testcase Data Item no.2 (rand mem)", 2, 0, _1M * 8, NULL, NULL, NULL, NULL, Item02Save, NULL, NULL, Item02Load, NULL); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Register #2 -> %Rrc\n", rc); return 1; } rc = SSMR3RegisterInternal(pVM, "SSM Testcase Data Item no.3 (big mem)", 0, 123, 512*_1M, NULL, NULL, NULL, NULL, Item03Save, NULL, NULL, Item03Load, NULL); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Register #3 -> %Rrc\n", rc); return 1; } rc = SSMR3RegisterInternal(pVM, "SSM Testcase Data Item no.4 (big zero mem)", 0, 42, 512*_1M, NULL, NULL, NULL, NULL, Item04Save, NULL, NULL, Item04Load, NULL); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Register #4 -> %Rrc\n", rc); return 1; } /* * Attempt a save. */ uint64_t u64Start = RTTimeNanoTS(); rc = SSMR3Save(pVM, pszFilename, NULL, NULL, SSMAFTER_DESTROY, NULL, NULL); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Save #1 -> %Rrc\n", rc); return 1; } uint64_t u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Saved in %'RI64 ns\n", u64Elapsed); RTFSOBJINFO Info; rc = RTPathQueryInfo(pszFilename, &Info, RTFSOBJATTRADD_NOTHING); if (RT_FAILURE(rc)) { RTPrintf("tstSSM: failed to query file size: %Rrc\n", rc); return 1; } RTPrintf("tstSSM: file size %'RI64 bytes\n", Info.cbObject); /* * Attempt a load. */ u64Start = RTTimeNanoTS(); rc = SSMR3Load(pVM, pszFilename, NULL /*pStreamOps*/, NULL /*pStreamOpsUser*/, SSMAFTER_RESUME, NULL /*pfnProgress*/, NULL /*pvProgressUser*/); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Load #1 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Loaded in %'RI64 ns\n", u64Elapsed); /* * Validate it. */ u64Start = RTTimeNanoTS(); rc = SSMR3ValidateFile(pszFilename, false /* fChecksumIt*/ ); if (RT_FAILURE(rc)) { RTPrintf("SSMR3ValidateFile #1 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Validated without checksumming in %'RI64 ns\n", u64Elapsed); u64Start = RTTimeNanoTS(); rc = SSMR3ValidateFile(pszFilename, true /* fChecksumIt */); if (RT_FAILURE(rc)) { RTPrintf("SSMR3ValidateFile #1 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Validated and checksummed in %'RI64 ns\n", u64Elapsed); /* * Open it and read. */ u64Start = RTTimeNanoTS(); PSSMHANDLE pSSM; rc = SSMR3Open(pszFilename, 0, &pSSM); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Open #1 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Opened in %'RI64 ns\n", u64Elapsed); /* negative */ u64Start = RTTimeNanoTS(); rc = SSMR3Seek(pSSM, "some unit that doesn't exist", 0, NULL); if (rc != VERR_SSM_UNIT_NOT_FOUND) { RTPrintf("SSMR3Seek #1 negative -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Failed seek in %'RI64 ns\n", u64Elapsed); /* another negative, now only the instance number isn't matching. */ rc = SSMR3Seek(pSSM, "SSM Testcase Data Item no.2 (rand mem)", 0, NULL); if (rc != VERR_SSM_UNIT_NOT_FOUND) { RTPrintf("SSMR3Seek #1 unit 2 -> %Rrc\n", rc); return 1; } /* 2nd unit */ rc = SSMR3Seek(pSSM, "SSM Testcase Data Item no.2 (rand mem)", 2, NULL); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Seek #1 unit 2 -> %Rrc [2]\n", rc); return 1; } uint32_t uVersion = 0xbadc0ded; rc = SSMR3Seek(pSSM, "SSM Testcase Data Item no.2 (rand mem)", 2, &uVersion); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Seek #1 unit 2 -> %Rrc [3]\n", rc); return 1; } u64Start = RTTimeNanoTS(); rc = Item02Load(NULL, pSSM, uVersion, SSM_PASS_FINAL); if (RT_FAILURE(rc)) { RTPrintf("Item02Load #1 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Loaded 2nd item in %'RI64 ns\n", u64Elapsed); /* 1st unit */ uVersion = 0xbadc0ded; rc = SSMR3Seek(pSSM, "SSM Testcase Data Item no.1 (all types)", 1, &uVersion); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Seek #1 unit 1 -> %Rrc\n", rc); return 1; } u64Start = RTTimeNanoTS(); rc = Item01Load(NULL, pSSM, uVersion, SSM_PASS_FINAL); if (RT_FAILURE(rc)) { RTPrintf("Item01Load #1 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Loaded 1st item in %'RI64 ns\n", u64Elapsed); /* 3st unit */ uVersion = 0xbadc0ded; rc = SSMR3Seek(pSSM, "SSM Testcase Data Item no.3 (big mem)", 0, &uVersion); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Seek #3 unit 1 -> %Rrc\n", rc); return 1; } u64Start = RTTimeNanoTS(); rc = Item03Load(NULL, pSSM, uVersion, SSM_PASS_FINAL); if (RT_FAILURE(rc)) { RTPrintf("Item01Load #3 -> %Rrc\n", rc); return 1; } u64Elapsed = RTTimeNanoTS() - u64Start; RTPrintf("tstSSM: Loaded 3rd item in %'RI64 ns\n", u64Elapsed); /* close */ rc = SSMR3Close(pSSM); if (RT_FAILURE(rc)) { RTPrintf("SSMR3Close #1 -> %Rrc\n", rc); return 1; } destroyFakeVM(pVM); /* delete */ RTFileDelete(pszFilename); RTPrintf("tstSSM: SUCCESS\n"); return 0; } #if !defined(VBOX_WITH_HARDENING) || !defined(RT_OS_WINDOWS) /** * Main entry point. */ int main(int argc, char **argv, char **envp) { return TrustedMain(argc, argv, envp); } #endif
28.064143
130
0.535839
Nurzamal
14859d765d2a4c7ce6aafacedef25ab335c77686
13,531
cpp
C++
common/contrib/QSsh/src/sshcryptofacility.cpp
cbtek/ClockNGo
4b23043a8b535059990e4eedb2c0f3a4fb079415
[ "MIT" ]
null
null
null
common/contrib/QSsh/src/sshcryptofacility.cpp
cbtek/ClockNGo
4b23043a8b535059990e4eedb2c0f3a4fb079415
[ "MIT" ]
null
null
null
common/contrib/QSsh/src/sshcryptofacility.cpp
cbtek/ClockNGo
4b23043a8b535059990e4eedb2c0f3a4fb079415
[ "MIT" ]
null
null
null
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "sshcryptofacility_p.h" #include "sshbotanconversions_p.h" #include "sshcapabilities_p.h" #include "sshexception_p.h" #include "sshkeyexchange_p.h" #include "sshkeypasswordretriever_p.h" #include "sshpacket_p.h" #include <botan/inc/botan.h> #include <QDebug> #include <QList> #include <string> using namespace Botan; namespace QSsh { namespace Internal { SshAbstractCryptoFacility::SshAbstractCryptoFacility() : m_cipherBlockSize(0), m_macLength(0) { } SshAbstractCryptoFacility::~SshAbstractCryptoFacility() {} void SshAbstractCryptoFacility::clearKeys() { m_cipherBlockSize = 0; m_macLength = 0; m_sessionId.clear(); m_pipe.reset(0); m_hMac.reset(0); } void SshAbstractCryptoFacility::recreateKeys(const SshKeyExchange &kex) { checkInvariant(); if (m_sessionId.isEmpty()) m_sessionId = kex.h(); Algorithm_Factory &af = global_state().algorithm_factory(); const std::string &cryptAlgo = botanCryptAlgoName(cryptAlgoName(kex)); BlockCipher * const cipher = af.prototype_block_cipher(cryptAlgo)->clone(); m_cipherBlockSize = cipher->block_size(); const QByteArray ivData = generateHash(kex, ivChar(), m_cipherBlockSize); const InitializationVector iv(convertByteArray(ivData), m_cipherBlockSize); const quint32 keySize = cipher->key_spec().maximum_keylength(); const QByteArray cryptKeyData = generateHash(kex, keyChar(), keySize); SymmetricKey cryptKey(convertByteArray(cryptKeyData), keySize); Keyed_Filter * const cipherMode = makeCipherMode(cipher, new Null_Padding, iv, cryptKey); m_pipe.reset(new Pipe(cipherMode)); m_macLength = botanHMacKeyLen(hMacAlgoName(kex)); const QByteArray hMacKeyData = generateHash(kex, macChar(), macLength()); SymmetricKey hMacKey(convertByteArray(hMacKeyData), macLength()); const HashFunction * const hMacProto = af.prototype_hash_function(botanHMacAlgoName(hMacAlgoName(kex))); m_hMac.reset(new HMAC(hMacProto->clone())); m_hMac->set_key(hMacKey); } void SshAbstractCryptoFacility::convert(QByteArray &data, quint32 offset, quint32 dataSize) const { Q_ASSERT(offset + dataSize <= static_cast<quint32>(data.size())); checkInvariant(); // Session id empty => No key exchange has happened yet. if (dataSize == 0 || m_sessionId.isEmpty()) return; if (dataSize % cipherBlockSize() != 0) { throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR, "Invalid packet size"); } m_pipe->process_msg(reinterpret_cast<const byte *>(data.constData()) + offset, dataSize); quint32 bytesRead = m_pipe->read(reinterpret_cast<byte *>(data.data()) + offset, dataSize, m_pipe->message_count() - 1); // Can't use Pipe::LAST_MESSAGE because of a VC bug. Q_ASSERT(bytesRead == dataSize); } QByteArray SshAbstractCryptoFacility::generateMac(const QByteArray &data, quint32 dataSize) const { return m_sessionId.isEmpty() ? QByteArray() : convertByteArray(m_hMac->process(reinterpret_cast<const byte *>(data.constData()), dataSize)); } QByteArray SshAbstractCryptoFacility::generateHash(const SshKeyExchange &kex, char c, quint32 length) { const QByteArray &k = kex.k(); const QByteArray &h = kex.h(); QByteArray data(k); data.append(h).append(c).append(m_sessionId); SecureVector<byte> key = kex.hash()->process(convertByteArray(data), data.size()); while (key.size() < length) { SecureVector<byte> tmpKey; tmpKey += SecureVector<byte>(convertByteArray(k), k.size()); tmpKey += SecureVector<byte>(convertByteArray(h), h.size()); tmpKey += key; key += kex.hash()->process(tmpKey); } return QByteArray(reinterpret_cast<const char *>(key.begin()), length); } void SshAbstractCryptoFacility::checkInvariant() const { Q_ASSERT(m_sessionId.isEmpty() == !m_pipe); } const QByteArray SshEncryptionFacility::PrivKeyFileStartLineRsa("-----BEGIN RSA PRIVATE KEY-----"); const QByteArray SshEncryptionFacility::PrivKeyFileStartLineDsa("-----BEGIN DSA PRIVATE KEY-----"); const QByteArray SshEncryptionFacility::PrivKeyFileEndLineRsa("-----END RSA PRIVATE KEY-----"); const QByteArray SshEncryptionFacility::PrivKeyFileEndLineDsa("-----END DSA PRIVATE KEY-----"); QByteArray SshEncryptionFacility::cryptAlgoName(const SshKeyExchange &kex) const { return kex.encryptionAlgo(); } QByteArray SshEncryptionFacility::hMacAlgoName(const SshKeyExchange &kex) const { return kex.hMacAlgoClientToServer(); } Keyed_Filter *SshEncryptionFacility::makeCipherMode(BlockCipher *cipher, BlockCipherModePaddingMethod *paddingMethod, const InitializationVector &iv, const SymmetricKey &key) { return new CBC_Encryption(cipher, paddingMethod, key, iv); } void SshEncryptionFacility::encrypt(QByteArray &data) const { convert(data, 0, data.size()); } void SshEncryptionFacility::createAuthenticationKey(const QByteArray &privKeyFileContents) { if (privKeyFileContents == m_cachedPrivKeyContents) return; #ifdef CREATOR_SSH_DEBUG qDebug("%s: Key not cached, reading", Q_FUNC_INFO); #endif QList<BigInt> pubKeyParams; QList<BigInt> allKeyParams; QString error1; QString error2; if (!createAuthenticationKeyFromPKCS8(privKeyFileContents, pubKeyParams, allKeyParams, error1) && !createAuthenticationKeyFromOpenSSL(privKeyFileContents, pubKeyParams, allKeyParams, error2)) { #ifdef CREATOR_SSH_DEBUG qDebug("%s: %s\n\t%s\n", Q_FUNC_INFO, qPrintable(error1), qPrintable(error2)); #endif throw SshClientException(SshKeyFileError, SSH_TR("Decoding of private key file failed: " "Format not understood.")); } foreach (const BigInt &b, allKeyParams) { if (b.is_zero()) { throw SshClientException(SshKeyFileError, SSH_TR("Decoding of private key file failed: Invalid zero parameter.")); } } m_authPubKeyBlob = AbstractSshPacket::encodeString(m_authKeyAlgoName); foreach (const BigInt &b, pubKeyParams) m_authPubKeyBlob += AbstractSshPacket::encodeMpInt(b); m_cachedPrivKeyContents = privKeyFileContents; } bool SshEncryptionFacility::createAuthenticationKeyFromPKCS8(const QByteArray &privKeyFileContents, QList<BigInt> &pubKeyParams, QList<BigInt> &allKeyParams, QString &error) { try { Pipe pipe; pipe.process_msg(convertByteArray(privKeyFileContents), privKeyFileContents.size()); Private_Key * const key = PKCS8::load_key(pipe, m_rng, SshKeyPasswordRetriever()); if (DSA_PrivateKey * const dsaKey = dynamic_cast<DSA_PrivateKey *>(key)) { m_authKeyAlgoName = SshCapabilities::PubKeyDss; m_authKey.reset(dsaKey); pubKeyParams << dsaKey->group_p() << dsaKey->group_q() << dsaKey->group_g() << dsaKey->get_y(); allKeyParams << pubKeyParams << dsaKey->get_x(); } else if (RSA_PrivateKey * const rsaKey = dynamic_cast<RSA_PrivateKey *>(key)) { m_authKeyAlgoName = SshCapabilities::PubKeyRsa; m_authKey.reset(rsaKey); pubKeyParams << rsaKey->get_e() << rsaKey->get_n(); allKeyParams << pubKeyParams << rsaKey->get_p() << rsaKey->get_q() << rsaKey->get_d(); } else { qWarning("%s: Unexpected code flow, expected success or exception.", Q_FUNC_INFO); return false; } } catch (const Botan::Exception &ex) { error = QLatin1String(ex.what()); return false; } catch (const Botan::Decoding_Error &ex) { error = QLatin1String(ex.what()); return false; } return true; } bool SshEncryptionFacility::createAuthenticationKeyFromOpenSSL(const QByteArray &privKeyFileContents, QList<BigInt> &pubKeyParams, QList<BigInt> &allKeyParams, QString &error) { try { bool syntaxOk = true; QList<QByteArray> lines = privKeyFileContents.split('\n'); while (lines.last().isEmpty()) lines.removeLast(); if (lines.count() < 3) { syntaxOk = false; } else if (lines.first() == PrivKeyFileStartLineRsa) { if (lines.last() != PrivKeyFileEndLineRsa) syntaxOk = false; else m_authKeyAlgoName = SshCapabilities::PubKeyRsa; } else if (lines.first() == PrivKeyFileStartLineDsa) { if (lines.last() != PrivKeyFileEndLineDsa) syntaxOk = false; else m_authKeyAlgoName = SshCapabilities::PubKeyDss; } else { syntaxOk = false; } if (!syntaxOk) { error = SSH_TR("Unexpected format."); return false; } QByteArray privateKeyBlob; for (int i = 1; i < lines.size() - 1; ++i) privateKeyBlob += lines.at(i); privateKeyBlob = QByteArray::fromBase64(privateKeyBlob); BER_Decoder decoder(convertByteArray(privateKeyBlob), privateKeyBlob.size()); BER_Decoder sequence = decoder.start_cons(SEQUENCE); size_t version; sequence.decode (version); if (version != 0) { error = SSH_TR("Key encoding has version %1, expected 0.").arg(version); return false; } if (m_authKeyAlgoName == SshCapabilities::PubKeyDss) { BigInt p, q, g, y, x; sequence.decode (p).decode (q).decode (g).decode (y).decode (x); DSA_PrivateKey * const dsaKey = new DSA_PrivateKey(m_rng, DL_Group(p, q, g), x); m_authKey.reset(dsaKey); pubKeyParams << p << q << g << y; allKeyParams << pubKeyParams << x; } else { BigInt p, q, e, d, n; sequence.decode(n).decode(e).decode(d).decode(p).decode(q); RSA_PrivateKey * const rsaKey = new RSA_PrivateKey(m_rng, p, q, e, d, n); m_authKey.reset(rsaKey); pubKeyParams << e << n; allKeyParams << pubKeyParams << p << q << d; } sequence.discard_remaining(); sequence.verify_end(); } catch (const Botan::Exception &ex) { error = QLatin1String(ex.what()); return false; } catch (const Botan::Decoding_Error &ex) { error = QLatin1String(ex.what()); return false; } return true; } QByteArray SshEncryptionFacility::authenticationAlgorithmName() const { Q_ASSERT(m_authKey); return m_authKeyAlgoName; } QByteArray SshEncryptionFacility::authenticationKeySignature(const QByteArray &data) const { Q_ASSERT(m_authKey); QScopedPointer<PK_Signer> signer(new PK_Signer(*m_authKey, botanEmsaAlgoName(m_authKeyAlgoName))); QByteArray dataToSign = AbstractSshPacket::encodeString(sessionId()) + data; QByteArray signature = convertByteArray(signer->sign_message(convertByteArray(dataToSign), dataToSign.size(), m_rng)); return AbstractSshPacket::encodeString(m_authKeyAlgoName) + AbstractSshPacket::encodeString(signature); } QByteArray SshEncryptionFacility::getRandomNumbers(int count) const { QByteArray data; data.resize(count); m_rng.randomize(convertByteArray(data), count); return data; } SshEncryptionFacility::~SshEncryptionFacility() {} QByteArray SshDecryptionFacility::cryptAlgoName(const SshKeyExchange &kex) const { return kex.decryptionAlgo(); } QByteArray SshDecryptionFacility::hMacAlgoName(const SshKeyExchange &kex) const { return kex.hMacAlgoServerToClient(); } Keyed_Filter *SshDecryptionFacility::makeCipherMode(BlockCipher *cipher, BlockCipherModePaddingMethod *paddingMethod, const InitializationVector &iv, const SymmetricKey &key) { return new CBC_Decryption(cipher, paddingMethod, key, iv); } void SshDecryptionFacility::decrypt(QByteArray &data, quint32 offset, quint32 dataSize) const { convert(data, offset, dataSize); #ifdef CREATOR_SSH_DEBUG qDebug("Decrypted data:"); const char * const start = data.constData() + offset; const char * const end = start + dataSize; for (const char *c = start; c < end; ++c) qDebug() << "'" << *c << "' (0x" << (static_cast<int>(*c) & 0xff) << ")"; #endif } } // namespace Internal } // namespace QSsh
35.421466
101
0.670313
cbtek
1485d7c5006627275475854ccbc9c159ce35259c
7,617
cc
C++
weblayer/browser/persistence/minimal_browser_persister_browsertest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
weblayer/browser/persistence/minimal_browser_persister_browsertest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
weblayer/browser/persistence/minimal_browser_persister_browsertest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/raw_ptr.h" #include "build/build_config.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "net/base/filename_util.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "weblayer/browser/browser_impl.h" #include "weblayer/browser/profile_impl.h" #include "weblayer/browser/tab_impl.h" #include "weblayer/public/navigation.h" #include "weblayer/public/navigation_controller.h" #include "weblayer/public/tab.h" #include "weblayer/shell/browser/shell.h" #include "weblayer/test/test_navigation_observer.h" #include "weblayer/test/weblayer_browser_test.h" #include "weblayer/test/weblayer_browser_test_utils.h" namespace weblayer { class MinimalBrowserPersisterTest : public WebLayerBrowserTest { public: MinimalBrowserPersisterTest() = default; ~MinimalBrowserPersisterTest() override = default; // WebLayerBrowserTest: void SetUpOnMainThread() override { WebLayerBrowserTest::SetUpOnMainThread(); ASSERT_TRUE(embedded_test_server()->Start()); browser_ = Browser::Create(GetProfile(), nullptr); tab_ = static_cast<TabImpl*>(browser_->CreateTab()); browser_->SetActiveTab(tab_); } void PostRunTestOnMainThread() override { tab_ = nullptr; browser_.reset(); WebLayerBrowserTest::PostRunTestOnMainThread(); } GURL url1() { return embedded_test_server()->GetURL("/simple_page.html"); } GURL url2() { return embedded_test_server()->GetURL("/simple_page2.html"); } // Persists the current state, then recreates the browser. See // BrowserImpl::GetMinimalPersistenceState() for details on // |max_size_in_bytes|, 0 means use the default value. void RecreateBrowserFromCurrentState( int max_number_of_navigations_per_tab = 0, int max_size_in_bytes = 0) { Browser::PersistenceInfo persistence_info; persistence_info.minimal_state = browser_impl()->GetMinimalPersistenceState( max_number_of_navigations_per_tab, max_size_in_bytes); tab_ = nullptr; browser_ = Browser::Create(GetProfile(), &persistence_info); // There is always at least one tab created (even if restore fails). ASSERT_GE(browser_->GetTabs().size(), 1u); tab_ = static_cast<TabImpl*>(browser_->GetTabs()[0]); } protected: BrowserImpl* browser_impl() { return static_cast<BrowserImpl*>(browser_.get()); } std::unique_ptr<Browser> browser_; raw_ptr<TabImpl> tab_ = nullptr; }; IN_PROC_BROWSER_TEST_F(MinimalBrowserPersisterTest, SingleTab) { NavigateAndWaitForCompletion(url1(), tab_); ASSERT_NO_FATAL_FAILURE(RecreateBrowserFromCurrentState()); EXPECT_EQ(tab_, browser_->GetActiveTab()); TestNavigationObserver observer( url1(), TestNavigationObserver::NavigationEvent::kCompletion, browser_->GetActiveTab()); observer.Wait(); EXPECT_EQ(1, tab_->GetNavigationController()->GetNavigationListSize()); } IN_PROC_BROWSER_TEST_F(MinimalBrowserPersisterTest, TwoTabs) { NavigateAndWaitForCompletion(url1(), tab_); Tab* tab2 = browser_->CreateTab(); NavigateAndWaitForCompletion(url2(), tab2); browser_->SetActiveTab(tab2); // Shutdown the service and run the assertions twice to ensure we handle // correctly storing state of tabs that need to be reloaded. for (int i = 0; i < 2; ++i) { ASSERT_NO_FATAL_FAILURE(RecreateBrowserFromCurrentState()); tab2 = nullptr; ASSERT_EQ(2u, browser_->GetTabs().size()) << "iteration " << i; tab2 = browser_->GetTabs()[1]; EXPECT_EQ(tab2, browser_->GetActiveTab()) << "iteration " << i; // The first tab shouldn't have loaded yet, as it's not active. EXPECT_TRUE(tab_->web_contents()->GetController().NeedsReload()) << "iteration " << i; EXPECT_EQ(1, tab2->GetNavigationController()->GetNavigationListSize()) << "iteration " << i; TestNavigationObserver observer( url2(), TestNavigationObserver::NavigationEvent::kCompletion, tab2); } } IN_PROC_BROWSER_TEST_F(MinimalBrowserPersisterTest, PendingSkipped) { NavigateAndWaitForCompletion(url1(), tab_); tab_->GetNavigationController()->Navigate(url2()); ASSERT_NO_FATAL_FAILURE(RecreateBrowserFromCurrentState()); EXPECT_EQ(tab_, browser_->GetActiveTab()); TestNavigationObserver observer( url1(), TestNavigationObserver::NavigationEvent::kCompletion, browser_->GetActiveTab()); observer.Wait(); ASSERT_EQ(1, tab_->GetNavigationController()->GetNavigationListSize()); } IN_PROC_BROWSER_TEST_F(MinimalBrowserPersisterTest, TwoNavs) { NavigateAndWaitForCompletion(url1(), tab_); NavigateAndWaitForCompletion(url2(), tab_); ASSERT_NO_FATAL_FAILURE(RecreateBrowserFromCurrentState()); TabImpl* restored_tab = tab_; EXPECT_EQ(restored_tab, browser_->GetActiveTab()); TestNavigationObserver observer( url2(), TestNavigationObserver::NavigationEvent::kCompletion, restored_tab); observer.Wait(); ASSERT_EQ(2, restored_tab->GetNavigationController()->GetNavigationListSize()); content::NavigationController& nav_controller = restored_tab->web_contents()->GetController(); EXPECT_EQ(1, nav_controller.GetCurrentEntryIndex()); EXPECT_EQ(url1(), nav_controller.GetEntryAtIndex(0)->GetURL()); EXPECT_EQ(url2(), nav_controller.GetEntryAtIndex(1)->GetURL()); } IN_PROC_BROWSER_TEST_F(MinimalBrowserPersisterTest, NavigationOverflow) { NavigateAndWaitForCompletion(url1(), tab_); NavigateAndWaitForCompletion(url2(), tab_); const GURL url3 = embedded_test_server()->GetURL("/simple_page3.html"); NavigateAndWaitForCompletion(url3, tab_); const GURL url4 = embedded_test_server()->GetURL("/simple_page4.html"); NavigateAndWaitForCompletion(url4, tab_); ASSERT_NO_FATAL_FAILURE(RecreateBrowserFromCurrentState(3)); // As a max of 3 navigations was specified, only the last three navigations // should be restored. TabImpl* restored_tab = tab_; EXPECT_EQ(restored_tab, browser_->GetActiveTab()); TestNavigationObserver observer( url4, TestNavigationObserver::NavigationEvent::kCompletion, restored_tab); observer.Wait(); ASSERT_EQ(3, restored_tab->GetNavigationController()->GetNavigationListSize()); content::NavigationController& nav_controller = restored_tab->web_contents()->GetController(); EXPECT_EQ(2, nav_controller.GetCurrentEntryIndex()); EXPECT_EQ(url2(), nav_controller.GetEntryAtIndex(0)->GetURL()); EXPECT_EQ(url3, nav_controller.GetEntryAtIndex(1)->GetURL()); EXPECT_EQ(url4, nav_controller.GetEntryAtIndex(2)->GetURL()); } // crbug.com/1240904: test is flaky on linux and win. #if defined(OS_LINUX) || defined(OS_WIN) #define MAYBE_Overflow DISABLED_Overflow #else #define MAYBE_Overflow Overflow #endif IN_PROC_BROWSER_TEST_F(MinimalBrowserPersisterTest, MAYBE_Overflow) { std::string url_string(2048, 'a'); const std::string data = "data:,"; url_string.replace(0, data.size(), data); NavigateAndWaitForCompletion(GURL(url_string), tab_); ASSERT_NO_FATAL_FAILURE(RecreateBrowserFromCurrentState(0, 2048)); TabImpl* restored_tab = tab_; EXPECT_EQ(restored_tab, browser_->GetActiveTab()); EXPECT_EQ(1, restored_tab->web_contents()->GetController().GetEntryCount()); EXPECT_TRUE(restored_tab->web_contents()->GetController().GetPendingEntry() == nullptr); } } // namespace weblayer
38.276382
80
0.753578
chromium
148619e5823c1dbced2f88975d7fe0f28e494288
3,002
cpp
C++
Frontend/GItems/Mini/RUBorderComponent.cpp
Gattic/gfxplusplus
f0c05a0f424fd65c8f7fd26ee0dee1802a033336
[ "MIT" ]
3
2020-02-12T23:22:45.000Z
2020-02-19T01:03:07.000Z
Frontend/GItems/Mini/RUBorderComponent.cpp
MeeseeksLookAtMe/gfxplusplus
f0c05a0f424fd65c8f7fd26ee0dee1802a033336
[ "MIT" ]
null
null
null
Frontend/GItems/Mini/RUBorderComponent.cpp
MeeseeksLookAtMe/gfxplusplus
f0c05a0f424fd65c8f7fd26ee0dee1802a033336
[ "MIT" ]
null
null
null
// Copyright 2020 Robert Carneiro, Derek Meer, Matthew Tabak, Eric Lujan // // 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 "RUBorderComponent.h" #include "../../Graphics/graphics.h" #include "../GItem.h" #include "../RUColors.h" RUBorderComponent::RUBorderComponent() { borderEnabled = false; borderWidth = 1; setBorderColor(RUColors::DEFAULT_COLOR_BORDER); } RUBorderComponent::RUBorderComponent(int newWidth) { borderEnabled = true; borderWidth = newWidth; setBorderColor(RUColors::DEFAULT_COLOR_BORDER); } RUBorderComponent::RUBorderComponent(SDL_Color newBorderColor) { borderEnabled = true; borderWidth = 1; setBorderColor(newBorderColor); } RUBorderComponent::RUBorderComponent(int newWidth, SDL_Color newBorderColor) { borderEnabled = true; borderWidth = newWidth; setBorderColor(newBorderColor); } RUBorderComponent::~RUBorderComponent() { borderEnabled = false; } bool RUBorderComponent::getBorderEnabled() const { return borderEnabled; } SDL_Color RUBorderComponent::getBorderColor() const { return borderColor; } int RUBorderComponent::getBorderWidth() const { return borderWidth; } void RUBorderComponent::toggleBorder(bool newBorder) { borderEnabled = newBorder; drawUpdate = true; } void RUBorderComponent::setBorderColor(SDL_Color newBorderColor) { borderColor = newBorderColor; } void RUBorderComponent::setBorderWidth(int newBorderWidth) { borderWidth = newBorderWidth; } void RUBorderComponent::updateBorderBackground(gfxpp* cGfx) { if (!borderEnabled) return; if (!((getWidth() > 0) && (getHeight() > 0))) return; for (int i = 0; i < borderWidth; ++i) { // draw the border SDL_Rect borderRect; borderRect.x = i; borderRect.y = i; borderRect.w = getWidth() - (borderWidth - 1); borderRect.h = getHeight() - (borderWidth - 1); SDL_SetRenderDrawColor(cGfx->getRenderer(), borderColor.r, borderColor.g, borderColor.b, borderColor.a); SDL_RenderDrawRect(cGfx->getRenderer(), &borderRect); } }
27.796296
100
0.758161
Gattic
1489b159b85c69900140ef57b2e9bac4b1010849
34,667
cpp
C++
ext/include/osgEarthDrivers/engine_osgterrain/OSGTileFactory.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
6
2015-09-26T15:33:41.000Z
2021-06-13T13:21:50.000Z
ext/include/osgEarthDrivers/engine_osgterrain/OSGTileFactory.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
null
null
null
ext/include/osgEarthDrivers/engine_osgterrain/OSGTileFactory.cpp
energonQuest/dtEarth
47b04bb272ec8781702dea46f5ee9a03d4a22196
[ "MIT" ]
5
2015-05-04T09:02:23.000Z
2019-06-17T11:34:12.000Z
/* -*-c++-*- */ /* osgEarth - Dynamic map generation toolkit for OpenSceneGraph * Copyright 2008-2013 Pelican Mapping * http://osgearth.org * * osgEarth 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include "OSGTileFactory" #include "TerrainNode" #include "StreamingTerrainNode" #include "FileLocationCallback" #include "TransparentLayer" #include <osgEarth/Map> #include <osgEarth/HeightFieldUtils> #include <osgEarth/Registry> #include <osgEarth/ImageUtils> #include <osgEarth/TileSource> #include <osg/Image> #include <osg/Notify> #include <osg/PagedLOD> #include <osg/ClusterCullingCallback> #include <osg/CoordinateSystemNode> #include <osgFX/MultiTextureControl> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <osgTerrain/Locator> #include <osgTerrain/GeometryTechnique> #include <OpenThreads/ReentrantMutex> #include <sstream> #include <stdlib.h> using namespace OpenThreads; using namespace osgEarth_engine_osgterrain; using namespace osgEarth; using namespace osgEarth::Drivers; #define LC "[OSGTileFactory] " /*****************************************************************************/ namespace { //TODO: get rid of this, and move it to the CustomTerrain CULL traversal....????? struct PopulateStreamingTileDataCallback : public osg::NodeCallback { PopulateStreamingTileDataCallback( const MapFrame& mapf ) : _mapf(mapf) { } void operator()( osg::Node* node, osg::NodeVisitor* nv ) { if ( nv->getVisitorType() == osg::NodeVisitor::CULL_VISITOR ) { if ( node->asGroup()->getNumChildren() > 0 ) { StreamingTile* tile = static_cast<StreamingTile*>( node->asGroup()->getChild(0) ); tile->servicePendingImageRequests( _mapf, nv->getFrameStamp()->getFrameNumber() ); } } traverse( node, nv ); } const MapFrame& _mapf; }; } /*****************************************************************************/ OSGTileFactory::OSGTileFactory(unsigned int engineId, const MapFrame& cull_thread_mapf, const OSGTerrainOptions& props ) : osg::Referenced( true ), _engineId( engineId ), _cull_thread_mapf( cull_thread_mapf ), _terrainOptions( props ) { LoadingPolicy::Mode mode = _terrainOptions.loadingPolicy()->mode().value(); } const OSGTerrainOptions& OSGTileFactory::getTerrainOptions() const { return _terrainOptions; } std::string OSGTileFactory::createURI( unsigned int id, const TileKey& key ) { std::stringstream ss; ss << key.str() << "." <<id<<".osgearth_osgterrain_tile"; std::string ssStr; ssStr = ss.str(); return ssStr; } // Make a MatrixTransform suitable for use with a Locator object based on the given extents. // Calling Locator::setTransformAsExtents doesn't work with OSG 2.6 due to the fact that the // _inverse member isn't updated properly. Calling Locator::setTransform works correctly. osg::Matrixd OSGTileFactory::getTransformFromExtents(double minX, double minY, double maxX, double maxY) const { osg::Matrixd transform; transform.set( maxX-minX, 0.0, 0.0, 0.0, 0.0, maxY-minY, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, minX, minY, 0.0, 1.0); return transform; } osg::Node* OSGTileFactory::createSubTiles( const MapFrame& mapf, TerrainNode* terrain, const TileKey& key, bool populateLayers ) { TileKey k0 = key.createChildKey(0); TileKey k1 = key.createChildKey(1); TileKey k2 = key.createChildKey(2); TileKey k3 = key.createChildKey(3); bool hasValidData = false; bool validData; bool fallback = false; osg::ref_ptr<osg::Node> q0 = createTile( mapf, terrain, k0, populateLayers, true, fallback, validData); if (!hasValidData && validData) hasValidData = true; osg::ref_ptr<osg::Node> q1 = createTile( mapf, terrain, k1, populateLayers, true, fallback, validData ); if (!hasValidData && validData) hasValidData = true; osg::ref_ptr<osg::Node> q2 = createTile( mapf, terrain, k2, populateLayers, true, fallback, validData ); if (!hasValidData && validData) hasValidData = true; osg::ref_ptr<osg::Node> q3 = createTile( mapf, terrain, k3, populateLayers, true, fallback, validData ); if (!hasValidData && validData) hasValidData = true; if (!hasValidData) { OE_DEBUG << LC << "Couldn't create any quadrants for " << key.str() << " time to stop subdividing!" << std::endl; return NULL; } osg::Group* tile_parent = new osg::Group(); fallback = true; //Fallback on tiles if we couldn't create any if (!q0.valid()) { q0 = createTile( mapf, terrain, k0, populateLayers, true, fallback, validData); } if (!q1.valid()) { q1 = createTile( mapf, terrain, k1, populateLayers, true, fallback, validData); } if (!q2.valid()) { q2 = createTile( mapf, terrain, k2, populateLayers, true, fallback, validData); } if (!q3.valid()) { q3 = createTile( mapf, terrain, k3, populateLayers, true, fallback, validData); } tile_parent->addChild( q0.get() ); tile_parent->addChild( q1.get() ); tile_parent->addChild( q2.get() ); tile_parent->addChild( q3.get() ); return tile_parent; } bool OSGTileFactory::createValidGeoImage(ImageLayer* layer, const TileKey& key, GeoImage& out_image, TileKey& out_actualTileKey, ProgressCallback* progress) { //TODO: Redo this to just grab images from the parent TerrainTiles //Try to create the image with the given key out_actualTileKey = key; while (out_actualTileKey.valid()) { if ( layer->isKeyValid(out_actualTileKey) ) { out_image = layer->createImage( out_actualTileKey, progress ); if ( out_image.valid() ) { return true; } } out_actualTileKey = out_actualTileKey.createParentKey(); } return false; } bool OSGTileFactory::hasMoreLevels( Map* map, const TileKey& key ) { //Threading::ScopedReadLock lock( map->getMapDataMutex() ); bool more_levels = false; ImageLayerVector imageLayers; map->getImageLayers( imageLayers ); for ( ImageLayerVector::const_iterator i = imageLayers.begin(); i != imageLayers.end(); i++ ) { const ImageLayerOptions& opt = i->get()->getImageLayerOptions(); if ( !opt.maxLevel().isSet() || key.getLevelOfDetail() < (unsigned int)*opt.maxLevel() ) { more_levels = true; break; } } if ( !more_levels ) { ElevationLayerVector elevLayers; map->getElevationLayers( elevLayers ); for( ElevationLayerVector::const_iterator j = elevLayers.begin(); j != elevLayers.end(); j++ ) { const ElevationLayerOptions& opt = j->get()->getElevationLayerOptions(); if ( !opt.maxLevel().isSet() || key.getLevelOfDetail() < (unsigned int)*opt.maxLevel() ) //if ( !j->get()->maxLevel().isSet() || key.getLevelOfDetail() < j->get()->maxLevel().get() ) { more_levels = true; break; } } } return more_levels; } osg::HeightField* OSGTileFactory::createEmptyHeightField( const TileKey& key, unsigned numCols, unsigned numRows ) { return HeightFieldUtils::createReferenceHeightField( key.getExtent(), numCols, numRows ); } void OSGTileFactory::addPlaceholderImageLayers(Tile* tile, Tile* ancestorTile ) { if ( !ancestorTile ) { //OE_NOTICE << "No ancestorTile for key " << key.str() << std::endl; return; } // Now if we have a valid ancestor tile, go through and make a temporary tile consisting only of // layers that exist in the new map layer image list as well. //int layer = 0; ColorLayersByUID colorLayers; ancestorTile->getCustomColorLayers( colorLayers ); tile->setCustomColorLayers( colorLayers ); } void OSGTileFactory::addPlaceholderHeightfieldLayer(StreamingTile* tile, StreamingTile* ancestorTile, GeoLocator* defaultLocator, const TileKey& key, const TileKey& ancestorKey) { osgTerrain::HeightFieldLayer* newHFLayer = 0L; if ( ancestorTile && ancestorKey.valid() ) { osg::ref_ptr<osgTerrain::HeightFieldLayer> ancestorLayer; { Threading::ScopedReadLock sharedLock( ancestorTile->getTileLayersMutex() ); ancestorLayer = dynamic_cast<osgTerrain::HeightFieldLayer*>(ancestorTile->getElevationLayer()); } if ( ancestorLayer.valid() ) { osg::ref_ptr<osg::HeightField> ancestorHF = ancestorLayer->getHeightField(); if ( ancestorHF.valid() ) { osg::HeightField* newHF = HeightFieldUtils::createSubSample( ancestorHF.get(), ancestorKey.getExtent(), key.getExtent()); newHFLayer = new osgTerrain::HeightFieldLayer( newHF ); newHFLayer->setLocator( defaultLocator ); // lock to set the elevation layerdata: { Threading::ScopedWriteLock exclusiveLock( tile->getTileLayersMutex() ); tile->setElevationLayer( newHFLayer ); tile->setElevationLOD( ancestorTile->getElevationLOD() ); } } } } // lock the tile to write the elevation data. { Threading::ScopedWriteLock exclusiveLock( tile->getTileLayersMutex() ); if ( !newHFLayer ) { newHFLayer = new osgTerrain::HeightFieldLayer(); newHFLayer->setHeightField( createEmptyHeightField( key, 8, 8 ) ); newHFLayer->setLocator( defaultLocator ); tile->setElevationLOD( -1 ); } if ( newHFLayer ) { tile->setElevationLayer( newHFLayer ); } } } osgTerrain::HeightFieldLayer* OSGTileFactory::createPlaceholderHeightfieldLayer(osg::HeightField* ancestorHF, const TileKey& ancestorKey, const TileKey& key, GeoLocator* keyLocator ) { osgTerrain::HeightFieldLayer* hfLayer = NULL; osg::HeightField* newHF = HeightFieldUtils::createSubSample( ancestorHF, ancestorKey.getExtent(), key.getExtent() ); newHF->setSkirtHeight( ancestorHF->getSkirtHeight() / 2.0 ); hfLayer = new osgTerrain::HeightFieldLayer( newHF ); hfLayer->setLocator( keyLocator ); return hfLayer; } osg::Node* OSGTileFactory::createTile(const MapFrame& mapf, TerrainNode* terrain, const TileKey& key, bool populateLayers, bool wrapInPagedLOD, bool fallback, bool& out_validData ) { if ( populateLayers ) { return createPopulatedTile( mapf, terrain, key, wrapInPagedLOD, fallback, out_validData); } else { //Placeholders always contain valid data out_validData = true; return createPlaceholderTile( mapf, static_cast<StreamingTerrainNode*>(terrain), key ); } } osg::Node* OSGTileFactory::createPlaceholderTile(const MapFrame& mapf, StreamingTerrainNode* terrain, const TileKey& key ) { // Start out by finding the nearest registered ancestor tile, since the placeholder is // going to be based on inherited data. Note- the ancestor may not be the immediate // parent, b/c the parent may or may not be in the scene graph. TileKey ancestorKey = key.createParentKey(); osg::ref_ptr<StreamingTile> ancestorTile; while( !ancestorTile.valid() && ancestorKey.valid() ) { terrain->getTile( ancestorKey.getTileId(), ancestorTile ); if ( !ancestorTile.valid() ) ancestorKey = ancestorKey.createParentKey(); } if ( !ancestorTile.valid() ) { OE_WARN << LC << "cannot find ancestor tile for (" << key.str() << ")" <<std::endl; return 0L; } OE_DEBUG << LC << "Creating placeholder for " << key.str() << std::endl; const MapInfo& mapInfo = mapf.getMapInfo(); bool hasElevation = mapf.elevationLayers().size() > 0; // Build a "placeholder" tile. double xmin, ymin, xmax, ymax; key.getExtent().getBounds( xmin, ymin, xmax, ymax ); // A locator will place the tile on the globe: osg::ref_ptr<GeoLocator> locator = GeoLocator::createForKey( key, mapInfo ); // The empty tile: StreamingTile* tile = new StreamingTile( key, locator.get(), terrain->getQuickReleaseGLObjects() ); tile->setTerrainTechnique( terrain->cloneTechnique() ); tile->setVerticalScale( _terrainOptions.verticalScale().value() ); tile->setDataVariance( osg::Object::DYNAMIC ); //tile->setLocator( locator.get() ); // Generate placeholder imagery and elevation layers. These "inherit" data from an // ancestor tile. { //Threading::ScopedReadLock parentLock( ancestorTile->getTileLayersMutex() ); addPlaceholderImageLayers ( tile, ancestorTile.get() ); addPlaceholderHeightfieldLayer( tile, ancestorTile.get(), locator.get(), key, ancestorKey ); } // calculate the switching distances: osg::BoundingSphere bs = tile->getBound(); double max_range = 1e10; double radius = bs.radius(); double min_range = radius * _terrainOptions.minTileRangeFactor().get(); // Set the skirt height of the heightfield osgTerrain::HeightFieldLayer* hfLayer = static_cast<osgTerrain::HeightFieldLayer*>(tile->getElevationLayer()); if (!hfLayer) { OE_WARN << LC << "Warning: Couldn't get hfLayer for " << key.str() << std::endl; } hfLayer->getHeightField()->setSkirtHeight(radius * _terrainOptions.heightFieldSkirtRatio().get() ); // In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees if ( mapInfo.isPlateCarre() && hfLayer->getHeightField() ) HeightFieldUtils::scaleHeightFieldToDegrees( hfLayer->getHeightField() ); bool markTileLoaded = false; if ( _terrainOptions.loadingPolicy()->mode().get() != LoadingPolicy::MODE_STANDARD ) { markTileLoaded = true; tile->setHasElevationHint( hasElevation ); } // install a tile switcher: tile->attachToTerrain( terrain ); //tile->setTerrain( terrain ); //terrain->registerTile( tile ); osg::Node* result = 0L; // create a PLOD so we can keep subdividing: osg::PagedLOD* plod = new osg::PagedLOD(); plod->setCenter( bs.center() ); plod->addChild( tile, min_range, max_range ); if (key.getLevelOfDetail() < getTerrainOptions().maxLOD().get()) { plod->setFileName( 1, createURI( _engineId, key ) ); //map->getId(), key ) ); plod->setRange( 1, 0.0, min_range ); } else { plod->setRange( 0, 0, FLT_MAX ); } #if 0 //USE_FILELOCATIONCALLBACK osgDB::Options* options = Registry::instance()->cloneOrCreateOptions(); options->setFileLocationCallback( new FileLocationCallback); plod->setDatabaseOptions( options ); #endif result = plod; // Install a callback that will load the actual tile data via the pager. result->addCullCallback( new PopulateStreamingTileDataCallback( _cull_thread_mapf ) ); // Install a cluster culler (FIXME for cube mode) //bool isCube = map->getMapOptions().coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE; if ( mapInfo.isGeocentric() && !mapInfo.isCube() ) { osg::ClusterCullingCallback* ccc = createClusterCullingCallback( tile, locator->getEllipsoidModel() ); result->addCullCallback( ccc ); } return result; } namespace { struct GeoImageData { GeoImageData() : _layerUID(-1) , _imageTileKey(0,0,0,0L) { } GeoImage _image; UID _layerUID; TileKey _imageTileKey; }; } osg::Node* OSGTileFactory::createPopulatedTile(const MapFrame& mapf, TerrainNode* terrain, const TileKey& key, bool wrapInPagedLOD, bool fallback, bool& validData ) { const MapInfo& mapInfo = mapf.getMapInfo(); bool isPlateCarre = !mapInfo.isGeocentric() && mapInfo.isGeographicSRS(); typedef std::vector<GeoImageData> GeoImageDataVector; GeoImageDataVector image_tiles; // Collect the image layers bool empty_map = mapf.imageLayers().size() == 0 && mapf.elevationLayers().size() == 0; // Create the images for the tile for( ImageLayerVector::const_iterator i = mapf.imageLayers().begin(); i != mapf.imageLayers().end(); ++i ) { ImageLayer* layer = i->get(); GeoImageData imageData; // Only try to create images if the key is valid if ( layer->isKeyValid( key ) ) { imageData._image = layer->createImage( key ); imageData._layerUID = layer->getUID(); imageData._imageTileKey = key; } // always push images, even it they are empty, so that the image_tiles vector is one-to-one // with the imageLayers() vector. image_tiles.push_back( imageData ); } bool hasElevation = false; //Create the heightfield for the tile osg::ref_ptr<osg::HeightField> hf; if ( mapf.elevationLayers().size() > 0 ) { mapf.getHeightField( key, false, hf, 0L); } //If we are on the first LOD and we couldn't get a heightfield tile, just create an empty one. Otherwise you can run into the situation //where you could have an inset heightfield on one hemisphere and the whole other hemisphere won't show up. if ( mapInfo.isGeocentric() && key.getLevelOfDetail() <= 1 && !hf.valid()) { hf = createEmptyHeightField( key ); } hasElevation = hf.valid(); //Determine if we've created any images unsigned int numValidImages = 0; for (unsigned int i = 0; i < image_tiles.size(); ++i) { if (image_tiles[i]._image.valid()) numValidImages++; } //If we couldn't create any imagery or heightfields, bail out if (!hf.valid() && (numValidImages == 0) && !empty_map) { OE_DEBUG << LC << "Could not create any imagery or heightfields for " << key.str() <<". Not building tile" << std::endl; validData = false; //If we're not asked to fallback on previous LOD's and we have no data, return NULL if (!fallback) { return NULL; } } else { validData = true; } //Try to interpolate any missing image layers from parent tiles for (unsigned int i = 0; i < mapf.imageLayers().size(); i++ ) { if (!image_tiles[i]._image.valid()) { if (mapf.getImageLayerAt(i)->isKeyValid(key)) { //If the key was valid and we have no image, then something possibly went wrong with the image creation such as a server being busy. createValidGeoImage(mapf.getImageLayerAt(i), key, image_tiles[i]._image, image_tiles[i]._imageTileKey); } //If we still couldn't create an image, either something is really wrong or the key wasn't valid, so just create a transparent placeholder image if (!image_tiles[i]._image.valid()) { //If the image is not valid, create an empty texture as a placeholder image_tiles[i]._image = GeoImage(ImageUtils::createEmptyImage(), key.getExtent()); image_tiles[i]._imageTileKey = key; } } } //Fill in missing heightfield information from parent tiles if (!hf.valid()) { //We have no heightfield sources, if ( mapf.elevationLayers().size() == 0 ) { hf = createEmptyHeightField( key ); } else { //Try to get a heightfield again, but this time fallback on parent tiles if ( mapf.getHeightField( key, true, hf, 0L ) ) { hasElevation = true; } else { //We couldn't get any heightfield, so just create an empty one. hf = createEmptyHeightField( key ); } } } // In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees if ( isPlateCarre ) { HeightFieldUtils::scaleHeightFieldToDegrees( hf.get() ); } osg::ref_ptr<GeoLocator> locator = GeoLocator::createForKey( key, mapInfo ); osgTerrain::HeightFieldLayer* hf_layer = new osgTerrain::HeightFieldLayer(); hf_layer->setLocator( locator.get() ); hf_layer->setHeightField( hf.get() ); bool isStreaming = _terrainOptions.loadingPolicy()->mode() == LoadingPolicy::MODE_SEQUENTIAL || _terrainOptions.loadingPolicy()->mode() == LoadingPolicy::MODE_PREEMPTIVE; Tile* tile = terrain->createTile( key, locator.get() ); tile->setTerrainTechnique( terrain->cloneTechnique() ); tile->setVerticalScale( _terrainOptions.verticalScale().value() ); //tile->setLocator( locator.get() ); tile->setElevationLayer( hf_layer ); //tile->setRequiresNormals( true ); tile->setDataVariance(osg::Object::DYNAMIC); //Assign the terrain system to the TerrainTile. //It is very important the terrain system is set while the MapConfig's sourceMutex is locked. //This registers the terrain tile so that adding/removing layers are always in sync. If you don't do this //you can end up with a situation where the database pager is waiting to merge a tile, then a layer is added, then //the tile is finally merged and is out of sync. double min_units_per_pixel = DBL_MAX; #if 0 // create contour layer: if (map->getContourTransferFunction() != NULL) { osgTerrain::ContourLayer* contourLayer(new osgTerrain::ContourLayer(map->getContourTransferFunction())); contourLayer->setMagFilter(_terrainOptions.getContourMagFilter().value()); contourLayer->setMinFilter(_terrainOptions.getContourMinFilter().value()); tile->setCustomColorLayer(layer,contourLayer); //TODO: need layerUID, not layer index here -GW ++layer; } #endif for (unsigned int i = 0; i < image_tiles.size(); ++i) { if (image_tiles[i]._image.valid()) { const GeoImage& geo_image = image_tiles[i]._image; double img_xmin, img_ymin, img_xmax, img_ymax; geo_image.getExtent().getBounds( img_xmin, img_ymin, img_xmax, img_ymax ); //Specify a new locator for the color with the coordinates of the TileKey that was actually used to create the image osg::ref_ptr<GeoLocator> img_locator = key.getProfile()->getSRS()->createLocator( img_xmin, img_ymin, img_xmax, img_ymax, isPlateCarre ); if ( mapInfo.isGeocentric() ) img_locator->setCoordinateSystemType( osgTerrain::Locator::GEOCENTRIC ); tile->setCustomColorLayer( CustomColorLayer( mapf.getImageLayerAt(i), geo_image.getImage(), img_locator.get(), key.getLevelOfDetail(), key) ); double upp = geo_image.getUnitsPerPixel(); // Scale the units per pixel to degrees if the image is mercator (and the key is geo) if ( geo_image.getSRS()->isMercator() && key.getExtent().getSRS()->isGeographic() ) upp *= 1.0f/111319.0f; min_units_per_pixel = osg::minimum(upp, min_units_per_pixel); } } osg::BoundingSphere bs = tile->getBound(); double maxRange = 1e10; double radius = bs.radius(); #if 0 //Compute the min range based on the actual bounds of the tile. This can break down if you have very high resolution //data with elevation variations and you can run out of memory b/c the elevation change is greater than the actual size of the tile so you end up //inifinitely subdividing (or at least until you run out of data or memory) double minRange = bs.radius() * _terrainOptions.minTileRangeFactor().value(); #else //double origMinRange = bs.radius() * _options.minTileRangeFactor().value(); //Compute the min range based on the 2D size of the tile GeoExtent extent = tile->getKey().getExtent(); GeoPoint lowerLeft(extent.getSRS(), extent.xMin(), extent.yMin(), 0.0, ALTMODE_ABSOLUTE); GeoPoint upperRight(extent.getSRS(), extent.xMax(), extent.yMax(), 0.0, ALTMODE_ABSOLUTE); osg::Vec3d ll, ur; lowerLeft.toWorld( ll ); upperRight.toWorld( ur ); double minRange = (ur - ll).length() / 2.0 * _terrainOptions.minTileRangeFactor().value(); #endif // a skirt hides cracks when transitioning between LODs: hf->setSkirtHeight(radius * _terrainOptions.heightFieldSkirtRatio().get() ); // for now, cluster culling does not work for CUBE rendering //bool isCube = mapInfo.isCube(); //map->getMapOptions().coordSysType() == MapOptions::CSTYPE_GEOCENTRIC_CUBE; if ( mapInfo.isGeocentric() && !mapInfo.isCube() ) { //TODO: Work on cluster culling computation for cube faces osg::ClusterCullingCallback* ccc = createClusterCullingCallback(tile, locator->getEllipsoidModel() ); tile->setCullCallback( ccc ); } // Wait until now, when the tile is fully baked, to assign the terrain to the tile. // Placeholder tiles might try to locate this tile as an ancestor, and access its layers // and locators...so they must be intact before making this tile available via setTerrain. // // If there's already a placeholder tile registered, this will be ignored. If there isn't, // this will register the new tile. tile->attachToTerrain( terrain ); //tile->setTerrain( terrain ); //terrain->registerTile( tile ); if ( isStreaming && key.getLevelOfDetail() > 0 ) { static_cast<StreamingTile*>(tile)->setHasElevationHint( hasElevation ); } osg::Node* result = 0L; if (wrapInPagedLOD) { // create a PLOD so we can keep subdividing: osg::PagedLOD* plod = new osg::PagedLOD(); plod->setCenter( bs.center() ); plod->addChild( tile, minRange, maxRange ); std::string filename = createURI( _engineId, key ); //map->getId(), key ); //Only add the next tile if it hasn't been blacklisted bool isBlacklisted = osgEarth::Registry::instance()->isBlacklisted( filename ); if (!isBlacklisted && key.getLevelOfDetail() < (unsigned int)getTerrainOptions().maxLOD().value() && validData ) { plod->setFileName( 1, filename ); plod->setRange( 1, 0.0, minRange ); } else { plod->setRange( 0, 0, FLT_MAX ); } #if USE_FILELOCATIONCALLBACK osgDB::Options* options = Registry::instance()->cloneOrCreateOptions(); options->setFileLocationCallback( new FileLocationCallback() ); plod->setDatabaseOptions( options ); #endif result = plod; if ( isStreaming ) result->addCullCallback( new PopulateStreamingTileDataCallback( _cull_thread_mapf ) ); } else { result = tile; } return result; } CustomColorLayerRef* OSGTileFactory::createImageLayer(const MapInfo& mapInfo, ImageLayer* layer, const TileKey& key, ProgressCallback* progress) { if ( !layer ) return 0L; GeoImage geoImage; //If the key is valid, try to get the image from the MapLayer bool keyValid = layer->isKeyValid( key ); if ( keyValid ) { geoImage = layer->createImage(key, progress); } else { //If the key is not valid, simply make a transparent tile geoImage = GeoImage(ImageUtils::createEmptyImage(), key.getExtent()); } if (geoImage.valid()) { osg::ref_ptr<GeoLocator> imgLocator = GeoLocator::createForKey( key, mapInfo ); if ( mapInfo.isGeocentric() ) imgLocator->setCoordinateSystemType( osgTerrain::Locator::GEOCENTRIC ); return new CustomColorLayerRef( CustomColorLayer( layer, geoImage.getImage(), imgLocator.get(), key.getLevelOfDetail(), key) ); } return NULL; } osgTerrain::HeightFieldLayer* OSGTileFactory::createHeightFieldLayer( const MapFrame& mapf, const TileKey& key, bool exactOnly ) { const MapInfo& mapInfo = mapf.getMapInfo(); bool isPlateCarre = !mapInfo.isGeocentric() && mapInfo.isGeographicSRS(); // try to create a heightfield at native res: osg::ref_ptr<osg::HeightField> hf; if ( !mapf.getHeightField( key, !exactOnly, hf, 0L ) ) { if ( exactOnly ) return NULL; else hf = createEmptyHeightField( key ); } // In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees if ( isPlateCarre ) { HeightFieldUtils::scaleHeightFieldToDegrees( hf.get() ); } osgTerrain::HeightFieldLayer* hfLayer = new osgTerrain::HeightFieldLayer( hf.get() ); GeoLocator* locator = GeoLocator::createForKey( key, mapInfo ); hfLayer->setLocator( locator ); return hfLayer; } osg::ClusterCullingCallback* OSGTileFactory::createClusterCullingCallback(Tile* tile, osg::EllipsoidModel* et) { //This code is a very slightly modified version of the DestinationTile::createClusterCullingCallback in VirtualPlanetBuilder. osg::HeightField* grid = ((osgTerrain::HeightFieldLayer*)tile->getElevationLayer())->getHeightField(); if (!grid) return 0; float verticalScale = 1.0f; Tile* customTile = dynamic_cast<Tile*>(tile); if (customTile) { verticalScale = customTile->getVerticalScale(); } double globe_radius = et ? et->getRadiusPolar() : 1.0; unsigned int numColumns = grid->getNumColumns(); unsigned int numRows = grid->getNumRows(); double midLong = grid->getOrigin().x()+grid->getXInterval()*((double)(numColumns-1))*0.5; double midLat = grid->getOrigin().y()+grid->getYInterval()*((double)(numRows-1))*0.5; double midZ = grid->getOrigin().z(); double midX,midY; et->convertLatLongHeightToXYZ(osg::DegreesToRadians(midLat),osg::DegreesToRadians(midLong),midZ, midX,midY,midZ); osg::Vec3 center_position(midX,midY,midZ); osg::Vec3 center_normal(midX,midY,midZ); center_normal.normalize(); osg::Vec3 transformed_center_normal = center_normal; unsigned int r,c; // populate the vertex/normal/texcoord arrays from the grid. double orig_X = grid->getOrigin().x(); double delta_X = grid->getXInterval(); double orig_Y = grid->getOrigin().y(); double delta_Y = grid->getYInterval(); double orig_Z = grid->getOrigin().z(); float min_dot_product = 1.0f; float max_cluster_culling_height = 0.0f; float max_cluster_culling_radius = 0.0f; for(r=0;r<numRows;++r) { for(c=0;c<numColumns;++c) { double X = orig_X + delta_X*(double)c; double Y = orig_Y + delta_Y*(double)r; double Z = orig_Z + grid->getHeight(c,r) * verticalScale; double height = Z; et->convertLatLongHeightToXYZ( osg::DegreesToRadians(Y), osg::DegreesToRadians(X), Z, X, Y, Z); osg::Vec3d v(X,Y,Z); osg::Vec3 dv = v - center_position; double d = sqrt(dv.x()*dv.x() + dv.y()*dv.y() + dv.z()*dv.z()); double theta = acos( globe_radius/ (globe_radius + fabs(height)) ); double phi = 2.0 * asin (d*0.5/globe_radius); // d/globe_radius; double beta = theta+phi; double cutoff = osg::PI_2 - 0.1; //log(osg::INFO,"theta="<<theta<<"\tphi="<<phi<<" beta "<<beta); if (phi<cutoff && beta<cutoff) { float local_dot_product = -sin(theta + phi); float local_m = globe_radius*( 1.0/ cos(theta+phi) - 1.0); float local_radius = static_cast<float>(globe_radius * tan(beta)); // beta*globe_radius; min_dot_product = osg::minimum(min_dot_product, local_dot_product); max_cluster_culling_height = osg::maximum(max_cluster_culling_height,local_m); max_cluster_culling_radius = osg::maximum(max_cluster_culling_radius,local_radius); } else { //log(osg::INFO,"Turning off cluster culling for wrap around tile."); return 0; } } } osg::ClusterCullingCallback* ccc = new osg::ClusterCullingCallback; ccc->set(center_position + transformed_center_normal*max_cluster_culling_height , transformed_center_normal, min_dot_product, max_cluster_culling_radius); return ccc; }
35.739175
156
0.615484
energonQuest
148a93b4de5d6cd5f069be01687639c56d3461d9
6,176
hpp
C++
osc-daemon/datainjest/jsonparser.hpp
oranellis/AeroRTEP
53f36642ab62702b68b60105045c4c5ed1e0933b
[ "MIT" ]
1
2022-01-26T07:38:19.000Z
2022-01-26T07:38:19.000Z
osc-daemon/datainjest/jsonparser.hpp
oranellis/AeroRTEP
53f36642ab62702b68b60105045c4c5ed1e0933b
[ "MIT" ]
4
2022-01-26T07:32:32.000Z
2022-02-21T22:08:53.000Z
osc-daemon/datainjest/jsonparser.hpp
oranellis/openSatCon
53f36642ab62702b68b60105045c4c5ed1e0933b
[ "MIT" ]
null
null
null
#ifndef JSONPARSER_H #define JSONPARSER_H #include <iostream> #include <list> #include <vector> #include <fstream> #include "../../includes/json.hpp" #include "../components/component.hpp" #include "../components/fueltank.hpp" #include "../components/actuators/thruster.hpp" #include "../components/actuators/rotator.hpp" #include "../osctypes.hpp" using namespace std; using json = nlohmann::json; namespace osc { /** \mainpage openSatCon's project documentation */ /** \struct craftconfig \brief craft configuration craftconfiguration type containing components, fueltanks, thrusters and rotators */ struct craftconfig { std::map<std::string, component> components; std::map<std::string, fueltank> fueltanks; std::map<std::string, thruster> thrusters; std::map<std::string, rotator> rotators; bool populated() { if (components.empty()) return false; else return true; } }; /** \parseJson(jsonPath) parses the json file from the path and produces a craft config object with mapped components @param[in] jsonPath path to json file */ inline craftconfig parseJson(std::string jsonPath) { // std::cout << "start"; // debug // map<string, std::list<double> > Components; //json j = json::parse(jsonPath); std::ifstream ifs(jsonPath); json j = json::parse(ifs); craftconfig returnConfig; //parse and map mass components for(int i = 0; i < j["MassComponentNo"]; i++) { double mass = j["MassComponents"][std::to_string(i)]["mass"]; momentofinertia moi; position pos; moi.Ixx = j["MassComponents"][std::to_string(i)]["moi"][0u]; moi.Iyy = j["MassComponents"][std::to_string(i)]["moi"][1u]; moi.Izz = j["MassComponents"][std::to_string(i)]["moi"][2u]; pos.x = j["MassComponents"][std::to_string(i)]["position"][0u]; pos.y = j["MassComponents"][std::to_string(i)]["position"][1u]; pos.z = j["MassComponents"][std::to_string(i)]["position"][2u]; powermodel power; power.off = j["MassComponents"][std::to_string(i)]["powermodel"][0u]; power.idle = j["MassComponents"][std::to_string(i)]["powermodel"][1u]; power.use = j["MassComponents"][std::to_string(i)]["powermodel"][2u]; power.max = j["MassComponents"][std::to_string(i)]["powermodel"][3u]; quaternion rot; component massComponent(mass, moi, pos, rot, power); std::string key = j["MassComponents"][std::to_string(i)]["key"]; returnConfig.components.insert(std::pair<std::string, component>(key, massComponent)); } // parse and map thruster components for(int i = 0; i < j["ThrusterComponentNo"]; i++) { double maxT = j["ThrusterComponents"][std::to_string(i)]["maxThrust"]; double mTFrac = j["ThrusterComponents"][std::to_string(i)]["minThrustFraction"]; double tFrac = j["ThrusterComponents"][std::to_string(i)]["thrustFraction"]; double spImpulse = j["ThrusterComponents"][std::to_string(i)]["specificImpulse"]; bool attitudeControl; if (j["ThrusterComponents"][std::to_string(i)]["attitudeControl"] == 0) { attitudeControl = false; } else { attitudeControl = true; } std::array<double, 3> tAxis; tAxis[0] = j["ThrusterComponents"][std::to_string(i)]["thrustAxis"][0u]; tAxis[1] = j["ThrusterComponents"][std::to_string(i)]["thrustAxis"][1u]; tAxis[2] = j["ThrusterComponents"][std::to_string(i)]["thrustAxis"][2u]; position tCenter; tCenter.x = j["ThrusterComponents"][std::to_string(i)]["thrustCenter"][0u]; tCenter.y = j["ThrusterComponents"][std::to_string(i)]["thrustCenter"][1u]; tCenter.z = j["ThrusterComponents"][std::to_string(i)]["thrustCenter"][2u]; thruster ThrusterComponent(maxT, mTFrac, tFrac, spImpulse, attitudeControl, tAxis, tCenter); std::string key = j["ThrusterComponents"][std::to_string(i)]["key"]; returnConfig.thrusters.insert (std::pair<std::string, thruster>(key, ThrusterComponent)); } // parse and map fuel tanks for(int i = 0; i < j["FuelTankNo"]; i++) { double fuelmass = j["FuelTanks"][std::to_string(i)]["fuelMass"]; double fuelcap = j["FuelTanks"][std::to_string(i)]["fuelCapacity"]; std::string fueltype = j["FuelTanks"][std::to_string(i)]["fuelType"]; position pos; pos.x = j["FuelTanks"][std::to_string(i)]["position"][0u]; pos.y = j["FuelTanks"][std::to_string(i)]["position"][1u]; pos.z = j["FuelTanks"][std::to_string(i)]["position"][2u]; fueltank FuelTank(fueltype, fuelmass, fuelcap, pos); std::string key = j["FuelTanks"][std::to_string(i)]["key"]; returnConfig.fueltanks.insert (std::pair<std::string, fueltank>(key, FuelTank)); } // // parse and map rotators for(int i = 0; i < j["RotatorNo"]; i++) { double mDipole = j["Rotators"][std::to_string(i)]["maxDipoleMoment"]; double torque = j["Rotators"][std::to_string(i)]["torque"]; double storedMomentum = j["Rotators"][std::to_string(i)]["storedMomentum"]; double rotSpeed = j["Rotators"][std::to_string(i)]["rotationSpeed"]; momentofinertia moi; moi.Ixx = j["Rotators"][std::to_string(i)]["moi"][0u]; moi.Iyy = j["Rotators"][std::to_string(i)]["moi"][1u]; moi.Izz = j["Rotators"][std::to_string(i)]["moi"][2u]; std::array<double, 3> direction; direction[0] = j["Rotators"][std::to_string(i)]["normalVector"][0u]; direction[1] = j["Rotators"][std::to_string(i)]["normalVector"][1u]; direction[2] = j["Rotators"][std::to_string(i)]["normalVector"][2u]; rotator RotatorComponent(mDipole, torque, storedMomentum, rotSpeed, moi, direction); std::string key = j["Rotators"][std::to_string(i)]["key"]; returnConfig.rotators.insert (std::pair<std::string, rotator>(key, RotatorComponent)); } return returnConfig; }; } #endif // JSONPARSER_H.begin();
38.842767
100
0.61739
oranellis
1492b850f21c0f4cdae48a5fd78dae7be59a36c4
34,463
cpp
C++
src/liblightmetrica/renderer/renderer_bdpt.cpp
jammm/lightmetrica-v2
6864942ec48d37f2c35dc30a38a26d7cc4bb527e
[ "MIT" ]
150
2015-12-28T10:26:02.000Z
2021-03-17T14:36:16.000Z
src/liblightmetrica/renderer/renderer_bdpt.cpp
jammm/lightmetrica-v2
6864942ec48d37f2c35dc30a38a26d7cc4bb527e
[ "MIT" ]
null
null
null
src/liblightmetrica/renderer/renderer_bdpt.cpp
jammm/lightmetrica-v2
6864942ec48d37f2c35dc30a38a26d7cc4bb527e
[ "MIT" ]
17
2016-02-08T10:57:55.000Z
2020-09-04T03:57:33.000Z
/* Lightmetrica - A modern, research-oriented renderer Copyright (c) 2015 Hisanari Otsu 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 <pch.h> #include <lightmetrica/renderer.h> #include <lightmetrica/property.h> #include <lightmetrica/random.h> #include <lightmetrica/scene3.h> #include <lightmetrica/film.h> #include <lightmetrica/bsdf.h> #include <lightmetrica/ray.h> #include <lightmetrica/intersection.h> #include <lightmetrica/emitter.h> #include <lightmetrica/sensor.h> #include <lightmetrica/surfacegeometry.h> #include <lightmetrica/primitive.h> #include <lightmetrica/scheduler.h> #include <lightmetrica/renderutils.h> #include <tbb/tbb.h> #define LM_BDPT_DEBUG 0 LM_NAMESPACE_BEGIN // -------------------------------------------------------------------------------- struct Path; struct MISWeight : public Component { LM_INTERFACE_CLASS(MISWeight, Component, 1); LM_INTERFACE_F(0, Evaluate, Float(const Path& path, const Scene3* scene, int s, bool direct)); }; // -------------------------------------------------------------------------------- #pragma region Path structures struct PathVertex { int type; SurfaceGeometry geom; const Primitive* primitive = nullptr; }; struct SubpathVertex { boost::optional<PathVertex> sv; boost::optional<PathVertex> direct; }; struct Subpath { std::vector<SubpathVertex> vertices; public: auto Sample(const Scene3* scene, Random* rng, TransportDirection transDir, int maxPathVertices) -> void { vertices.clear(); // -------------------------------------------------------------------------------- Vec3 initWo; for (int step = 0; maxPathVertices == -1 || step < maxPathVertices; step++) { if (step == 0) { #pragma region Sample initial vertex PathVertex sv; // Sample an emitter sv.type = transDir == TransportDirection::LE ? SurfaceInteractionType::L : SurfaceInteractionType::E; sv.primitive = scene->SampleEmitter(sv.type, rng->Next()); // Sample a position on the emitter and initial ray direction sv.primitive->SamplePositionAndDirection(rng->Next2D(), rng->Next2D(), sv.geom, initWo); // Add a vertex SubpathVertex v; v.sv = sv; vertices.push_back(v); #pragma endregion } else { #pragma region Sample a vertex with PDF with BSDF const auto sv = [&]() -> boost::optional<PathVertex> { // Previous & two before vertex const auto* pv = &vertices.back().sv.get(); const auto* ppv = vertices.size() > 1 ? &vertices[vertices.size() - 2].sv.get() : nullptr; // Sample a next direction Vec3 wo; const auto wi = ppv ? Math::Normalize(ppv->geom.p - pv->geom.p) : Vec3(); if (step == 1) { wo = initWo; } else { pv->primitive->SampleDirection(rng->Next2D(), rng->Next(), pv->type, pv->geom, wi, wo); } const auto f = pv->primitive->EvaluateDirection(pv->geom, pv->type, wi, wo, transDir, false); if (f.Black()) { return boost::none; } // Intersection query Ray ray = { pv->geom.p, wo }; Intersection isect; if (!scene->Intersect(ray, isect)) { return boost::none; } // Create vertex PathVertex v; v.geom = isect.geom; v.primitive = isect.primitive; v.type = isect.primitive->Type() & ~SurfaceInteractionType::Emitter; return v; }(); #pragma endregion // -------------------------------------------------------------------------------- #pragma region Sample a vertex with direct emitter sampling const auto direct = [&]() -> boost::optional<PathVertex> { PathVertex v; const auto& pv = vertices.back().sv; // Sample a emitter v.type = transDir == TransportDirection::LE ? SurfaceInteractionType::E : SurfaceInteractionType::L; v.primitive = scene->SampleEmitter(v.type, rng->Next()); // Sample a position on the emitter v.primitive->SamplePositionGivenPreviousPosition(rng->Next2D(), pv->geom, v.geom); // Check visibility if (!scene->Visible(pv->geom.p, v.geom.p)) { return boost::none; } return v; }(); #pragma endregion // -------------------------------------------------------------------------------- #pragma region Add a vertex if (sv || direct) { SubpathVertex v; v.sv = sv; v.direct = direct; vertices.push_back(v); } #pragma endregion // -------------------------------------------------------------------------------- #pragma region Path termination if (!sv) { break; } if (sv->geom.infinite) { break; } // TODO: replace it with efficient one const Float rrProb = 0.5_f; if (rng->Next() > rrProb) { break; } #pragma endregion } } } }; struct Path { std::vector<PathVertex> vertices; public: #pragma region BDPT path initialization auto Connect(const Scene3* scene, int s, int t, bool direct, const Subpath& subpathL, const Subpath& subpathE) -> bool { assert(s > 0 || t > 0); vertices.clear(); if (s == 0 && t > 0) { if (!direct) { if (!subpathE.vertices[t - 1].sv) { return false; } if ((subpathE.vertices[t - 1].sv->primitive->Type() & SurfaceInteractionType::L) == 0) { return false; } for (int i = t - 1; i >= 0; i--) { assert(subpathE.vertices[i].sv); vertices.push_back(*subpathE.vertices[i].sv); } } else { if (!subpathE.vertices[t - 1].direct) { return false; } vertices.push_back(*subpathE.vertices[t - 1].direct); for (int i = t - 2; i >= 0; i--) { assert(subpathE.vertices[i].sv); vertices.push_back(*subpathE.vertices[i].sv); } } vertices.front().type = SurfaceInteractionType::L; } else if (s > 0 && t == 0) { if (!direct) { if (!subpathL.vertices[s - 1].sv) { return false; } if ((subpathL.vertices[s - 1].sv->primitive->Type() & SurfaceInteractionType::E) == 0) { return false; } for (int i = 0; i < s; i++) { assert(subpathL.vertices[i].sv); vertices.push_back(*subpathL.vertices[i].sv); } } else { if (!subpathL.vertices[s - 1].direct) { return false; } for (int i = 0; i < s - 1; i++) { assert(subpathL.vertices[i].sv); vertices.push_back(*subpathL.vertices[i].sv); } vertices.push_back(*subpathL.vertices[s - 1].direct); } vertices.back().type = SurfaceInteractionType::E; } else { assert(s > 0 && t > 0); assert(!direct); if (!subpathL.vertices[s - 1].sv || !subpathE.vertices[t - 1].sv) { return false; } if (subpathL.vertices[s - 1].sv->geom.infinite || subpathE.vertices[t - 1].sv->geom.infinite) { return false; } if (!scene->Visible(subpathL.vertices[s - 1].sv->geom.p, subpathE.vertices[t - 1].sv->geom.p)) { return false; } for (int i = 0; i < s; i++) { assert(subpathL.vertices[i].sv); vertices.push_back(*subpathL.vertices[i].sv); } for (int i = t - 1; i >= 0; i--) { assert(subpathE.vertices[i].sv); vertices.push_back(*subpathE.vertices[i].sv); } } return true; } #pragma endregion public: #pragma region BDPT path evaluation auto EvaluateContribution(const MISWeight* mis, const Scene3* scene, int s, bool direct) const -> SPD { const auto Cstar = EvaluateUnweightContribution(scene, s, direct); //const auto Cstar = EvaluateF(s, direct) / EvaluatePDF(scene, s, direct); return Cstar.Black() ? SPD() : Cstar * mis->Evaluate(*this, scene, s, direct); } auto SelectionPDF(int s, bool direct) const -> Float { const Float rrProb = 0.5_f; const int n = (int)(vertices.size()); const int t = n - s; Float selectionProb = 1; // Light subpath for (int i = 1; i < s - 1; i++) { selectionProb *= rrProb; } // Eye subpath for (int i = 1; i < t - 1; i++) { selectionProb *= rrProb; } return selectionProb; } auto RasterPosition() const -> Vec2 { const auto& v = vertices[vertices.size() - 1]; const auto& vPrev = vertices[vertices.size() - 2]; Vec2 rasterPos; v.primitive->RasterPosition(Math::Normalize(vPrev.geom.p - v.geom.p), v.geom, rasterPos); return rasterPos; } auto EvaluateCst(int s) const -> SPD { const int n = (int)(vertices.size()); const int t = n - s; SPD cst; if (s == 0 && t > 0) { const auto& v = vertices[0]; const auto& vNext = vertices[1]; cst = v.primitive->EvaluatePosition(v.geom, true) * v.primitive->EvaluateDirection(v.geom, v.type, Vec3(), Math::Normalize(vNext.geom.p - v.geom.p), TransportDirection::EL, false); } else if (s > 0 && t == 0) { const auto& v = vertices[n - 1]; const auto& vPrev = vertices[n - 2]; cst = v.primitive->EvaluatePosition(v.geom, true) * v.primitive->EvaluateDirection(v.geom, v.type, Vec3(), Math::Normalize(vPrev.geom.p - v.geom.p), TransportDirection::LE, false); } else if (s > 0 && t > 0) { const auto* vL = &vertices[s - 1]; const auto* vE = &vertices[s]; const auto* vLPrev = s - 2 >= 0 ? &vertices[s - 2] : nullptr; const auto* vENext = s + 1 < n ? &vertices[s + 1] : nullptr; const auto fsL = vL->primitive->EvaluateDirection(vL->geom, vL->type, vLPrev ? Math::Normalize(vLPrev->geom.p - vL->geom.p) : Vec3(), Math::Normalize(vE->geom.p - vL->geom.p), TransportDirection::LE, true); const auto fsE = vE->primitive->EvaluateDirection(vE->geom, vE->type, vENext ? Math::Normalize(vENext->geom.p - vE->geom.p) : Vec3(), Math::Normalize(vL->geom.p - vE->geom.p), TransportDirection::EL, true); const Float G = RenderUtils::GeometryTerm(vL->geom, vE->geom); cst = fsL * G * fsE; } return cst; } auto EvaluateF(int s, bool direct) const -> SPD { const int n = (int)(vertices.size()); const int t = n - s; assert(n >= 2); // -------------------------------------------------------------------------------- SPD fL; if (s == 0) { fL = SPD(1_f); } else { { const auto* vL = &vertices[0]; fL = vL->primitive->EvaluatePosition(vL->geom, false); } for (int i = 0; i < s - 1; i++) { const auto* v = &vertices[i]; const auto* vPrev = i >= 1 ? &vertices[i - 1] : nullptr; const auto* vNext = &vertices[i + 1]; const auto wi = vPrev ? Math::Normalize(vPrev->geom.p - v->geom.p) : Vec3(); const auto wo = Math::Normalize(vNext->geom.p - v->geom.p); fL *= v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::LE, t == 0 && i == s - 2 && direct); fL *= RenderUtils::GeometryTerm(v->geom, vNext->geom); } } if (fL.Black()) { return SPD(); } // -------------------------------------------------------------------------------- SPD fE; if (t == 0) { fE = SPD(1_f); } else { { const auto* vE = &vertices[n - 1]; fE = vE->primitive->EvaluatePosition(vE->geom, false); } for (int i = n - 1; i > s; i--) { const auto* v = &vertices[i]; const auto* vPrev = &vertices[i - 1]; const auto* vNext = i < n - 1 ? &vertices[i + 1] : nullptr; const auto wi = vNext ? Math::Normalize(vNext->geom.p - v->geom.p) : Vec3(); const auto wo = Math::Normalize(vPrev->geom.p - v->geom.p); fE *= v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::EL, s == 0 && i == 1 && direct); fE *= RenderUtils::GeometryTerm(v->geom, vPrev->geom); } } if (fE.Black()) { return SPD(); } // -------------------------------------------------------------------------------- const auto cst = EvaluateCst(s); if (cst.Black()) { return SPD(); } // -------------------------------------------------------------------------------- return fL * cst * fE; } auto EvaluateUnweightContribution(const Scene3* scene, int s, bool direct) const -> SPD { const int n = (int)(vertices.size()); const int t = n - s; // -------------------------------------------------------------------------------- #pragma region Compute alphaL SPD alphaL; if (s == 0) { alphaL = SPD(1_f); } else { { const auto* v = &vertices[0]; const auto* vNext = &vertices[1]; alphaL = v->primitive->EvaluatePosition(v->geom, false) / v->primitive->EvaluatePositionGivenDirectionPDF(v->geom, Math::Normalize(vNext->geom.p - v->geom.p), false) / scene->EvaluateEmitterPDF(v->primitive).v; } for (int i = 0; i < s - 1; i++) { const auto* v = &vertices[i]; const auto* vPrev = i >= 1 ? &vertices[i - 1] : nullptr; const auto* vNext = &vertices[i + 1]; const auto wi = vPrev ? Math::Normalize(vPrev->geom.p - v->geom.p) : Vec3(); const auto wo = Math::Normalize(vNext->geom.p - v->geom.p); const auto fs = v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::LE, t == 0 && i == s - 2 && direct); if (fs.Black()) return SPD(); alphaL *= fs / (t == 0 && i == s - 2 && direct ? vNext->primitive->EvaluatePositionGivenPreviousPositionPDF(vNext->geom, v->geom, false).ConvertToProjSA(vNext->geom, v->geom) * scene->EvaluateEmitterPDF(vNext->primitive).v : v->primitive->EvaluateDirectionPDF(v->geom, v->type, wi, wo, false)); } } if (alphaL.Black()) { return SPD(); } #pragma endregion // -------------------------------------------------------------------------------- #pragma region Compute alphaE SPD alphaE; if (t == 0) { alphaE = SPD(1_f); } else { { const auto* v = &vertices[n - 1]; const auto* vPrev = &vertices[n - 2]; alphaE = v->primitive->EvaluatePosition(v->geom, false) / v->primitive->EvaluatePositionGivenDirectionPDF(v->geom, Math::Normalize(vPrev->geom.p - v->geom.p), false) / scene->EvaluateEmitterPDF(v->primitive).v; } for (int i = n - 1; i > s; i--) { const auto* v = &vertices[i]; const auto* vPrev = &vertices[i - 1]; const auto* vNext = i < n - 1 ? &vertices[i + 1] : nullptr; const auto wi = vNext ? Math::Normalize(vNext->geom.p - v->geom.p) : Vec3(); const auto wo = Math::Normalize(vPrev->geom.p - v->geom.p); const auto fs = v->primitive->EvaluateDirection(v->geom, v->type, wi, wo, TransportDirection::EL, s == 0 && i == 1 && direct); if (fs.Black()) return SPD(); alphaE *= fs / (s == 0 && i == 1 && direct ? vPrev->primitive->EvaluatePositionGivenPreviousPositionPDF(vPrev->geom, v->geom, false).ConvertToProjSA(vPrev->geom, v->geom) * scene->EvaluateEmitterPDF(vPrev->primitive).v : v->primitive->EvaluateDirectionPDF(v->geom, v->type, wi, wo, false)); } } if (alphaE.Black()) { return SPD(); } #pragma endregion // -------------------------------------------------------------------------------- #pragma region Compute Cst const auto cst = EvaluateCst(s); if (cst.Black()) { return SPD(); } #pragma endregion // -------------------------------------------------------------------------------- return alphaL * cst * alphaE; } auto Samplable(int s, bool direct) const -> bool { // There is no connection with some cases const int n = (int)(vertices.size()); const int t = n - s; if (s > 0 && t > 0 && direct) { return false; } // Delta connection with direct light sampling if (t == 0 && s > 0 && direct) { if (vertices[n - 2].primitive->IsDeltaDirection(vertices[n - 2].type)) { return false; } } if (s == 0 && t > 0 && direct) { if (vertices[1].primitive->IsDeltaDirection(vertices[1].type)) { return false; } } // Delta connection of endpoints if (s == 0 && t > 0) { const auto& v = vertices[0]; if (v.primitive->IsDeltaPosition(v.type)) { return false; } } else if (s > 0 && t == 0) { const auto& v = vertices[n - 1]; if (v.primitive->IsDeltaPosition(v.type)) { return false; } } else if (s > 0 && t > 0) { const auto* vL = &vertices[s - 1]; const auto* vE = &vertices[s]; if (vL->primitive->IsDeltaDirection(vL->type) || vE->primitive->IsDeltaDirection(vE->type)) { return false; } } return true; } auto EvaluatePDF(const Scene3* scene, int s, bool direct) const -> PDFVal { if (!Samplable(s, direct)) { return PDFVal(PDFMeasure::ProdArea, 0_f); } // Otherwise the path can be generated with the given strategy (s,t) // so p_{s,t} can be safely evaluated. PDFVal pdf(PDFMeasure::ProdArea, 1_f); const int n = (int)(vertices.size()); const int t = n - s; if (s > 0) { pdf *= vertices[0].primitive->EvaluatePositionGivenDirectionPDF(vertices[0].geom, Math::Normalize(vertices[1].geom.p - vertices[0].geom.p), false) * scene->EvaluateEmitterPDF(vertices[0].primitive).v; for (int i = 0; i < s - 1; i++) { const auto* vi = &vertices[i]; const auto* vip = i - 1 >= 0 ? &vertices[i - 1] : nullptr; const auto* vin = &vertices[i + 1]; if (t == 0 && i == s - 2 && direct) { pdf *= vin->primitive->EvaluatePositionGivenPreviousPositionPDF(vin->geom, vi->geom, false) * scene->EvaluateEmitterPDF(vin->primitive).v; } else { pdf *= vi->primitive->EvaluateDirectionPDF(vi->geom, vi->type, vip ? Math::Normalize(vip->geom.p - vi->geom.p) : Vec3(), Math::Normalize(vin->geom.p - vi->geom.p), false).ConvertToArea(vi->geom, vin->geom); } } } if (t > 0) { pdf *= vertices[n - 1].primitive->EvaluatePositionGivenDirectionPDF(vertices[n - 1].geom, Math::Normalize(vertices[n - 2].geom.p - vertices[n - 1].geom.p), false) * scene->EvaluateEmitterPDF(vertices[n - 1].primitive).v; for (int i = n - 1; i >= s + 1; i--) { const auto* vi = &vertices[i]; const auto* vip = &vertices[i - 1]; const auto* vin = i + 1 < n ? &vertices[i + 1] : nullptr; if (s == 0 && i == s + 1 && direct) { pdf *= vip->primitive->EvaluatePositionGivenPreviousPositionPDF(vip->geom, vi->geom, false) * scene->EvaluateEmitterPDF(vip->primitive).v; } else { pdf *= vi->primitive->EvaluateDirectionPDF(vi->geom, vi->type, vin ? Math::Normalize(vin->geom.p - vi->geom.p) : Vec3(), Math::Normalize(vip->geom.p - vi->geom.p), false).ConvertToArea(vi->geom, vip->geom); } } } return pdf; } #pragma endregion }; #pragma endregion // -------------------------------------------------------------------------------- #pragma region MIS weights implementations class MISWeight_Simple : public MISWeight { public: LM_IMPL_CLASS(MISWeight_Simple, MISWeight); public: LM_IMPL_F(Evaluate) = [this](const Path& path, const Scene3* scene, int s_, bool direct_) -> Float { const int n = (int)(path.vertices.size()); int nonzero = 0; for (int s = 0; s <= n; s++) { for (int d = 0; d < 2; d++) { bool direct = d == 1; const auto t = n - s; if (s > 0 && t > 0 && direct) { continue; } if (path.EvaluatePDF(scene, s, direct).v > 0_f) { nonzero++; } } } assert(nonzero != 0); return 1_f / nonzero; }; }; class MISWeight_PowerHeuristics : public MISWeight { public: LM_IMPL_CLASS(MISWeight_PowerHeuristics, MISWeight); public: LM_IMPL_F(Evaluate) = [this](const Path& path, const Scene3* scene, int s_, bool direct_) -> Float { const int n = static_cast<int>(path.vertices.size()); const auto ps = path.EvaluatePDF(scene, s_, direct_); assert(ps > 0_f); Float invWeight = 0; for (int s = 0; s <= n; s++) { for (int d = 0; d < 2; d++) { bool direct = d == 1; const auto t = n - s; if (s > 0 && t > 0 && direct) { continue; } const auto pi = path.EvaluatePDF(scene, s, direct); if (pi > 0_f) { const auto r = pi.v / ps.v; invWeight += r * r; } } } return 1_f / invWeight; }; }; LM_COMPONENT_REGISTER_IMPL(MISWeight_Simple, "misweight::simple"); LM_COMPONENT_REGISTER_IMPL(MISWeight_PowerHeuristics, "misweight::powerheuristics"); #pragma endregion // -------------------------------------------------------------------------------- struct Strategy { int s; int t; int d; bool operator==(const Strategy& o) const { return (s == o.s && t == o.t && d == o.d); } }; struct StrategyHash { const int N = 100; auto operator()(const Strategy& v) const -> size_t { return (v.s * N + v.t) * 2 + v.d; } }; /*! \brief BDPT renderer. Implements bidirectional path tracing. */ class Renderer_BDPT final : public Renderer { public: LM_IMPL_CLASS(Renderer_BDPT, Renderer); private: int maxNumVertices_; int minNumVertices_; Scheduler::UniquePtr sched_ = ComponentFactory::Create<Scheduler>(); MISWeight::UniquePtr mis_{ nullptr, nullptr }; public: LM_IMPL_F(Initialize) = [this](const PropertyNode* prop) -> bool { sched_->Load(prop); maxNumVertices_ = prop->ChildAs("max_num_vertices", -1); minNumVertices_ = prop->ChildAs("min_num_vertices", 0); mis_ = ComponentFactory::Create<MISWeight>("misweight::" + prop->ChildAs<std::string>("mis", "powerheuristics")); return true; }; LM_IMPL_F(Render) = [this](const Scene* scene_, Random* initRng, const std::string& outputPath) -> void { const auto* scene = static_cast<const Scene3*>(scene_); // -------------------------------------------------------------------------------- #if LM_COMPILER_CLANG tbb::enumerable_thread_specific<Subpath> subpathL_, subpathE_; tbb::enumerable_thread_specific<Path> path_; #else static thread_local Subpath subpathL, subpathE; static thread_local Path path; #endif // -------------------------------------------------------------------------------- #if LM_BDPT_DEBUG std::vector<Film::UniquePtr> strategyFilms1; std::vector<Film::UniquePtr> strategyFilms2; std::unordered_map<Strategy, size_t, StrategyHash> strategyFilmMap; std::mutex strategyFilmMutex; #endif // -------------------------------------------------------------------------------- auto* film = static_cast<const Sensor*>(scene->GetSensor()->emitter)->GetFilm(); const auto processedSamples = sched_->Process(scene, film, initRng, [&](Film* film, Random* rng) { #if LM_COMPILER_CLANG auto& subpathL = subpathL_.local(); auto& subpathE = subpathE_.local(); auto& path = path_.local(); #endif // -------------------------------------------------------------------------------- #pragma region Sample subpaths subpathL.Sample(scene, rng, TransportDirection::LE, maxNumVertices_); subpathE.Sample(scene, rng, TransportDirection::EL, maxNumVertices_); #pragma endregion // -------------------------------------------------------------------------------- #pragma region Evaluate path combinations const int nL = static_cast<int>(subpathL.vertices.size()); const int nE = static_cast<int>(subpathE.vertices.size()); for (int n = 2; n <= nE + nL; n++) { if (maxNumVertices_ != -1 && (n > maxNumVertices_ || n < minNumVertices_)) { continue; } // -------------------------------------------------------------------------------- const int minS = Math::Max(0, n - nE); const int maxS = Math::Min(nL, n); for (int s = minS; s <= maxS; s++) { for (int d = 0; d < 2; d++) { #pragma region Exclude some combination of paths to control number of strategies const bool direct = d == 1; const int t = n - s; // Only direct connection with the cases with s=0 and t=0 if (s > 0 && t > 0 && direct) { continue; } #pragma endregion // -------------------------------------------------------------------------------- #pragma region Connect subpaths & create fullpath if (!path.Connect(scene, s, t, direct, subpathL, subpathE)) { continue; } #pragma endregion // -------------------------------------------------------------------------------- #pragma region Evaluate contribution const auto C = path.EvaluateContribution(mis_.get(), scene, s, direct) / path.SelectionPDF(s, direct); if (C.Black()) { continue; } #pragma endregion // -------------------------------------------------------------------------------- #pragma region Accumulate to film film->Splat(path.RasterPosition(), C); #if LM_BDPT_DEBUG { const auto Cstar = path.EvaluateUnweightContribution(scene, s, direct) / path.SelectionPDF(s, direct); std::unique_lock<std::mutex> lock(strategyFilmMutex); Strategy strategy{ s, t, d }; if (strategyFilmMap.find(strategy) == strategyFilmMap.end()) { strategyFilms1.push_back(ComponentFactory::Clone<Film>(film)); strategyFilms2.push_back(ComponentFactory::Clone<Film>(film)); strategyFilms1.back()->Clear(); strategyFilms2.back()->Clear(); strategyFilmMap[strategy] = strategyFilms1.size()-1; } strategyFilms1[strategyFilmMap[strategy]]->Splat(path.RasterPosition(), C); strategyFilms2[strategyFilmMap[strategy]]->Splat(path.RasterPosition(), Cstar); } #endif #pragma endregion } } } #pragma endregion }); // -------------------------------------------------------------------------------- #if LM_BDPT_DEBUG for (const auto& kv : strategyFilmMap) { const auto* f1 = strategyFilms1[kv.second].get(); const auto* f2 = strategyFilms2[kv.second].get(); f1->Rescale((Float)(f1->Width() * f1->Height()) / processedSamples); f2->Rescale((Float)(f2->Width() * f2->Height()) / processedSamples); f1->Save(boost::str(boost::format("bdpt_f1_n%02d_s%02d_t%02d_d%d") % (kv.first.s + kv.first.t) % kv.first.s % kv.first.t % kv.first.d)); f2->Save(boost::str(boost::format("bdpt_f2_n%02d_s%02d_t%02d_d%d") % (kv.first.s + kv.first.t) % kv.first.s % kv.first.t % kv.first.d)); } #else LM_UNUSED(processedSamples); #endif // -------------------------------------------------------------------------------- #pragma region Save image { LM_LOG_INFO("Saving image"); LM_LOG_INDENTER(); film->Save(outputPath); } #pragma endregion }; }; LM_COMPONENT_REGISTER_IMPL(Renderer_BDPT, "renderer::bdpt"); LM_NAMESPACE_END
34.257455
232
0.448539
jammm
149357666f8259d27b2dfe44164a519c54c284f2
15,788
cpp
C++
admin/wmi/wbem/adapters/wmireverseperformancemonitor/wmiadapter_refresh/wmi_perf_object.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/adapters/wmireverseperformancemonitor/wmiadapter_refresh/wmi_perf_object.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/adapters/wmireverseperformancemonitor/wmiadapter_refresh/wmi_perf_object.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//////////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2000-2002, Microsoft Corporation. // // All rights reserved. // // Module Name: // // wmi_perf_object.cpp // // Abstract: // // implements object helper functionality // // History: // // initial a-marius // //////////////////////////////////////////////////////////////////////////////////// #include "precomp.h" // definitions #include "wmi_perf_object.h" // debuging features #ifndef _INC_CRTDBG #include <crtdbg.h> #endif _INC_CRTDBG // new stores file/line info #ifdef _DEBUG #ifndef NEW #define NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new NEW #endif NEW #endif _DEBUG ////////////////////////////////////////////////////////////////////////////////////////////// // methods ////////////////////////////////////////////////////////////////////////////////////////////// // return S_OK when correct // return S_FALSE when not correct HRESULT CPerformanceObject::IsCorrect ( IWbemQualifierSet* pSet, LPCWSTR* lptszNeed, DWORD dwNeed, LPCWSTR* lptszNeedNot, DWORD dwNeedNot ) { HRESULT hRes = S_OK; DWORD dwIndex = 0; // resolve all requested to be fulfiled with if ( lptszNeed && dwNeed ) { for ( dwIndex = 0; dwIndex < dwNeed; dwIndex++ ) { hRes = pSet->Get( lptszNeed[dwIndex], NULL, NULL, NULL ); // there is no requested qualifier if ( hRes == WBEM_E_NOT_FOUND ) { return S_FALSE; } if FAILED( hRes ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"find out if object is correct failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } } } // resolve all don't requested qualifiers if ( lptszNeedNot && dwNeedNot ) { for ( dwIndex = 0; dwIndex < dwNeedNot; dwIndex++) { hRes = pSet->Get( lptszNeedNot[dwIndex], NULL, NULL, NULL ); // there is found not requested qualifier if ( hRes == WBEM_S_NO_ERROR ) { return S_FALSE; } if ( hRes != WBEM_E_NOT_FOUND ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"find out if object is correct failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } hRes = WBEM_S_NO_ERROR; } } return hRes; } HRESULT CPerformanceObject::IsCorrectObject ( LPCWSTR* lptszFulFil, DWORD dwFulFil, LPCWSTR* lptszFulFilNot, DWORD dwFulFilNot ) { HRESULT hRes = S_OK; // have no object ??? if ( ! m_pObject ) { hRes = E_UNEXPECTED; } if SUCCEEDED ( hRes ) { if ( ! m_pObjectQualifierSet ) { if FAILED ( hRes = m_pObject->GetQualifierSet ( &m_pObjectQualifierSet ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"get qualifiers of object failed",hRes ); #endif __SUPPORT_MSGBOX } } if SUCCEEDED ( hRes ) { hRes = IsCorrect ( m_pObjectQualifierSet, lptszFulFil, dwFulFil, lptszFulFilNot, dwFulFilNot); } } return hRes; } HRESULT CPerformanceObject::GetNames ( DWORD* pdwPropNames, LPWSTR** ppPropNames, CIMTYPE** ppTypes, DWORD** ppScales, DWORD** ppLevels, DWORD** ppCounters, LONG lFlags, LPCWSTR* lptszPropNeed, DWORD dwPropNeed, LPCWSTR* lptszPropNeedNot, DWORD dwPropNeedNot, LPCWSTR lpwszQualifier ) { HRESULT hRes = S_OK; DWORD dwIndex = 0; if ( ! m_pObject ) { return E_UNEXPECTED; } if ( !pdwPropNames ) { return E_INVALIDARG; } // smart pointer for safearrays __WrapperSAFEARRAY saNames; if FAILED ( hRes = m_pObject->GetNames ( lpwszQualifier, lFlags, NULL, &saNames ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"find out names of object's properties failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } // init all variables if ( ppPropNames ) { (*ppPropNames) = NULL; } if ( ppTypes ) { (*ppTypes) = NULL; } if ( ppScales ) { (*ppScales) = NULL; } if ( ppLevels ) { (*ppLevels) = NULL; } if ( ppCounters ) { (*ppCounters) = NULL; } // let's do something if ( lptszPropNeed || lptszPropNeedNot ) { if ( ppPropNames ) { // I need find out required properties only ( use qualifier array ) __WrapperARRAY < LPWSTR > help; if SUCCEEDED( SAFEARRAY_TO_LPWSTRARRAY ( saNames, &help, help ) ) { for ( dwIndex = 0; dwIndex < help; dwIndex++ ) { CIMTYPE type = CIM_EMPTY; if FAILED ( hRes = GetQualifierType ( help[dwIndex], &type ) ) { return hRes; } switch ( type ) { case CIM_SINT32: case CIM_UINT32: case CIM_SINT64: case CIM_UINT64: { break; } default: { // bad property type :)) try { delete help.GetAt ( dwIndex ); help.SetAt ( dwIndex ); } catch ( ... ) { } continue; } } // test if it has proper qualifier set CComPtr<IWbemQualifierSet> pSet; if SUCCEEDED ( hRes = m_pObject->GetPropertyQualifierSet ( help[dwIndex], &pSet ) ) { if SUCCEEDED( hRes = IsCorrect ( pSet, lptszPropNeed, dwPropNeed, lptszPropNeedNot, dwPropNeedNot ) ) { // is not correct clear this name if ( hRes == S_FALSE ) { try { delete help.GetAt ( dwIndex ); help.SetAt ( dwIndex ); } catch ( ... ) { } } } else { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"IsCorrect failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } } else { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"GetPropertyQualifierSet failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } } for ( dwIndex = 0; dwIndex < help; dwIndex++ ) { if ( help[dwIndex] ) { (*pdwPropNames)++; } } try { if ( *pdwPropNames ) { if ( ( (*ppPropNames) = (LPWSTR*) new LPWSTR[ (*pdwPropNames) ] ) == NULL ) { hRes = E_OUTOFMEMORY; } if ( SUCCEEDED ( hRes ) ) { // clear them all for ( dwIndex = 0; dwIndex < (*pdwPropNames); dwIndex++ ) { (*ppPropNames)[dwIndex] = NULL; } DWORD dw = 0; for ( dwIndex = 0; dwIndex < help && SUCCEEDED ( hRes ); dwIndex++ ) { if ( help[dwIndex] ) { DWORD cchSize = lstrlenW(help[dwIndex]) + 1; if ( ( (*ppPropNames)[dw] = (LPWSTR) new WCHAR[ cchSize ] ) == NULL ) { RELEASE_DOUBLEARRAY ( (*ppPropNames), (*pdwPropNames) ); hRes = E_OUTOFMEMORY; } if ( SUCCEEDED ( hRes ) ) { StringCchCopyW ( (*ppPropNames)[dw], cchSize, help[dwIndex] ); } // increment internal index dw++; } } } } } catch ( ... ) { RELEASE_DOUBLEARRAY ( (*ppPropNames), (*pdwPropNames) ); hRes = E_UNEXPECTED; } } else { hRes = S_FALSE; } } } else { if ( ppPropNames ) { // I don't need find out anything so all properties are returned if FAILED ( hRes = SAFEARRAY_TO_LPWSTRARRAY ( saNames, ppPropNames, pdwPropNames ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"SAFEARRAY_TO_LPWSTRARRAY failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } } } if ( SUCCEEDED ( hRes ) ) { if ( ppTypes ) { try { if ( ( ( *ppTypes ) = new CIMTYPE[(*pdwPropNames)] ) == NULL ) { hRes = E_OUTOFMEMORY; goto myCleanup; } } catch ( ... ) { hRes = E_FAIL; goto myCleanup; } } // allocate all scales :)) if ( ppScales ) { try { if ( ( ( *ppScales ) = new DWORD[(*pdwPropNames)] ) == NULL ) { hRes = E_OUTOFMEMORY; goto myCleanup; } } catch ( ... ) { hRes = E_FAIL; goto myCleanup; } } // allocate all levels if ( ppLevels ) { try { if ( ( ( *ppLevels ) = new DWORD[(*pdwPropNames)] ) == NULL ) { hRes = E_OUTOFMEMORY; goto myCleanup; } } catch ( ... ) { hRes = E_FAIL; goto myCleanup; } } // allocate all counter types if ( ppCounters ) { try { if ( ( ( *ppCounters ) = new DWORD[(*pdwPropNames)] ) == NULL ) { hRes = E_OUTOFMEMORY; goto myCleanup; } } catch ( ... ) { hRes = E_FAIL; goto myCleanup; } } for ( dwIndex = 0; dwIndex < (*pdwPropNames); dwIndex++ ) { CIMTYPE type = CIM_EMPTY; if FAILED ( hRes = GetQualifierType ( (*ppPropNames)[dwIndex], &type ) ) { goto myCleanup; } switch ( type ) { case CIM_SINT32: case CIM_UINT32: case CIM_SINT64: case CIM_UINT64: { if ( ppTypes ) { (*ppTypes)[dwIndex] = type; } break; } default: { if ( ppTypes ) { (*ppTypes)[dwIndex] = CIM_EMPTY; } break; } } LPWSTR szScale = NULL; LPWSTR szLevel = NULL; LPWSTR szCounter = NULL; if ( ppScales ) { GetQualifierValue ( (*ppPropNames)[dwIndex], L"defaultscale", &szScale ); if ( szScale ) { ( *ppScales)[dwIndex] = _wtol ( szScale ); delete szScale; } else { ( *ppScales)[dwIndex] = 0L; } } if ( ppLevels ) { GetQualifierValue ( (*ppPropNames)[dwIndex], L"perfdetail", &szLevel ); if ( szLevel ) { ( *ppLevels)[dwIndex] = _wtol ( szLevel ); delete szLevel; } else { ( *ppLevels)[dwIndex] = 0L; } } if ( ppCounters ) { GetQualifierValue ( (*ppPropNames)[dwIndex], L"countertype", &szCounter ); if ( szCounter ) { ( *ppCounters)[dwIndex] = _wtol ( szCounter ); delete szCounter; } else { ( *ppCounters)[dwIndex] = 0L; } } } } return hRes; myCleanup: if ( ppTypes ) { delete [] (*ppTypes); (*ppTypes) = NULL; } if ( ppScales ) { delete [] (*ppScales); (*ppScales) = NULL; } if ( ppLevels ) { delete [] (*ppLevels); (*ppLevels) = NULL; } if ( ppCounters ) { delete [] (*ppCounters); (*ppCounters) = NULL; } return hRes; } ////////////////////////////////////////////////////////////////////////////////////////////// // helpers ////////////////////////////////////////////////////////////////////////////////////////////// // qualifier type for specified property HRESULT CPerformanceObject::GetQualifierType ( LPCWSTR wszPropName, CIMTYPE* type ) { HRESULT hRes = S_OK; ( *type ) = NULL; if ( ! m_pObject ) { return E_UNEXPECTED; } if FAILED ( hRes = m_pObject->Get ( wszPropName, NULL, NULL, type, NULL ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"Get method on object failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } return hRes; } // qualifier value for main object HRESULT CPerformanceObject::GetQualifierValue ( LPCWSTR wszQualifierName, LPWSTR* psz ) { HRESULT hRes = S_OK; ( *psz ) = NULL; if ( ! m_pObject ) { return E_UNEXPECTED; } if ( ! m_pObjectQualifierSet ) { CComPtr<IWbemQualifierSet> pQualifiers; if FAILED ( hRes = m_pObject->GetQualifierSet ( &pQualifiers ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"GetQualifierSet on object failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } ( m_pObjectQualifierSet = pQualifiers ) -> AddRef (); } return GetQualifierValue ( m_pObjectQualifierSet, wszQualifierName, psz ); } // qualifier value for specified property HRESULT CPerformanceObject::GetQualifierValue ( LPCWSTR wszPropName, LPCWSTR wszQualifierName, LPWSTR* psz ) { HRESULT hRes = S_OK; ( *psz ) = NULL; if ( ! m_pObject ) { return E_UNEXPECTED; } CComPtr<IWbemQualifierSet> pQualifiers; if FAILED ( hRes = m_pObject->GetPropertyQualifierSet ( wszPropName, &pQualifiers ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"GetPropertyQualifierSet on object failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } return GetQualifierValue ( pQualifiers, wszQualifierName, psz ); } // return qualifier value in string representation ( helper ) HRESULT CPerformanceObject::GetQualifierValue ( IWbemQualifierSet * pSet, LPCWSTR wszQualifierName, LPWSTR * psz ) { (*psz) = NULL; CComVariant var; CComVariant varDest; HRESULT hRes = S_OK; CComBSTR bstrQualifierName = wszQualifierName; if FAILED ( hRes = pSet->Get ( bstrQualifierName, NULL, &var, NULL ) ) { return hRes; } try { if SUCCEEDED ( ::VariantChangeType ( &varDest, &var, VARIANT_NOVALUEPROP , VT_BSTR) ) { try { DWORD cchSize = ::SysStringLen( V_BSTR(&varDest) ) + 1; if ( ( (*psz) = (LPWSTR) new WCHAR[ cchSize ] ) == NULL ) { return E_OUTOFMEMORY; } StringCchCopyW ( (*psz), cchSize, V_BSTR( &varDest ) ); } catch ( ... ) { delete (*psz); (*psz) = NULL; return E_UNEXPECTED; } } } catch ( ... ) { return E_UNEXPECTED; } return S_OK; } HRESULT CPerformanceObject::GetPropertyValue ( LPCWSTR wszPropertyName, LPWSTR * psz ) { if ( ! m_pObject ) { return E_UNEXPECTED; } (*psz) = NULL; CComVariant var; CComVariant varDest; HRESULT hRes = S_OK; CComBSTR bstrPropertyName = wszPropertyName; if FAILED ( hRes = m_pObject->Get ( bstrPropertyName, NULL, &var, NULL, NULL ) ) { #ifdef __SUPPORT_MSGBOX ERRORMESSAGE_DEFINITION; ERRORMESSAGE_RETURN ( hRes ); #else __SUPPORT_MSGBOX ___TRACE_ERROR( L"Get method on object failed",hRes ); return hRes; #endif __SUPPORT_MSGBOX } try { if SUCCEEDED ( ::VariantChangeType ( &varDest, &var, VARIANT_NOVALUEPROP , VT_BSTR) ) { try { DWORD cchSize = ::SysStringLen( V_BSTR(&varDest) ) + 1; if ( ( (*psz) = (LPWSTR) new WCHAR[ cchSize ] ) == NULL ) { return E_OUTOFMEMORY; } StringCchCopyW ( (*psz), cchSize, V_BSTR( &varDest ) ); } catch ( ... ) { delete (*psz); (*psz) = NULL; return E_UNEXPECTED; } } } catch ( ... ) { return E_UNEXPECTED; } return S_OK; }
20.345361
129
0.542184
npocmaka
1499268379b786c7f9ca67f5e1345a27cf997ae6
2,130
cpp
C++
aws-cpp-sdk-xray/source/model/ResponseTimeRootCauseEntity.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-xray/source/model/ResponseTimeRootCauseEntity.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-xray/source/model/ResponseTimeRootCauseEntity.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/xray/model/ResponseTimeRootCauseEntity.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace XRay { namespace Model { ResponseTimeRootCauseEntity::ResponseTimeRootCauseEntity() : m_nameHasBeenSet(false), m_coverage(0.0), m_coverageHasBeenSet(false), m_remote(false), m_remoteHasBeenSet(false) { } ResponseTimeRootCauseEntity::ResponseTimeRootCauseEntity(JsonView jsonValue) : m_nameHasBeenSet(false), m_coverage(0.0), m_coverageHasBeenSet(false), m_remote(false), m_remoteHasBeenSet(false) { *this = jsonValue; } ResponseTimeRootCauseEntity& ResponseTimeRootCauseEntity::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("Coverage")) { m_coverage = jsonValue.GetDouble("Coverage"); m_coverageHasBeenSet = true; } if(jsonValue.ValueExists("Remote")) { m_remote = jsonValue.GetBool("Remote"); m_remoteHasBeenSet = true; } return *this; } JsonValue ResponseTimeRootCauseEntity::Jsonize() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("Name", m_name); } if(m_coverageHasBeenSet) { payload.WithDouble("Coverage", m_coverage); } if(m_remoteHasBeenSet) { payload.WithBool("Remote", m_remote); } return payload; } } // namespace Model } // namespace XRay } // namespace Aws
20.480769
88
0.723474
curiousjgeorge
1499b5aee1367c1c968dd5feb57f343cc1732286
218
hpp
C++
rapidxml/include/rapidxml/utility.hpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
27
2020-01-02T07:40:57.000Z
2022-03-09T14:43:56.000Z
rapidxml/include/rapidxml/utility.hpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
null
null
null
rapidxml/include/rapidxml/utility.hpp
Berrysoft/XamlCpp
cc7da0cf83892ceb88926292b7c90b9f8da6128d
[ "MIT" ]
3
2020-05-21T07:02:08.000Z
2021-07-01T00:56:38.000Z
#ifndef XAML_RAPIDXML_UTILITY_HPP #define XAML_RAPIDXML_UTILITY_HPP #include <xaml/utility.h> #ifndef RAPIDXML_API #define RAPIDXML_API __XAML_IMPORT #endif // !RAPIDXML_API #endif // !XAML_RAPIDXML_UTILITY_HPP
19.818182
38
0.811927
Berrysoft
149aa7e39e2a79be7922f6278d651abcf2222ab0
3,450
cc
C++
vod/src/model/GetVideoListRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
vod/src/model/GetVideoListRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
vod/src/model/GetVideoListRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/vod/model/GetVideoListRequest.h> using AlibabaCloud::Vod::Model::GetVideoListRequest; GetVideoListRequest::GetVideoListRequest() : RpcServiceRequest("vod", "2017-03-21", "GetVideoList") { setMethod(HttpRequest::Method::Post); } GetVideoListRequest::~GetVideoListRequest() {} long GetVideoListRequest::getResourceOwnerId()const { return resourceOwnerId_; } void GetVideoListRequest::setResourceOwnerId(long resourceOwnerId) { resourceOwnerId_ = resourceOwnerId; setParameter("ResourceOwnerId", std::to_string(resourceOwnerId)); } std::string GetVideoListRequest::getStartTime()const { return startTime_; } void GetVideoListRequest::setStartTime(const std::string& startTime) { startTime_ = startTime; setParameter("StartTime", startTime); } std::string GetVideoListRequest::getStorageLocation()const { return storageLocation_; } void GetVideoListRequest::setStorageLocation(const std::string& storageLocation) { storageLocation_ = storageLocation; setParameter("StorageLocation", storageLocation); } long GetVideoListRequest::getCateId()const { return cateId_; } void GetVideoListRequest::setCateId(long cateId) { cateId_ = cateId; setParameter("CateId", std::to_string(cateId)); } int GetVideoListRequest::getPageSize()const { return pageSize_; } void GetVideoListRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter("PageSize", std::to_string(pageSize)); } std::string GetVideoListRequest::getResourceOwnerAccount()const { return resourceOwnerAccount_; } void GetVideoListRequest::setResourceOwnerAccount(const std::string& resourceOwnerAccount) { resourceOwnerAccount_ = resourceOwnerAccount; setParameter("ResourceOwnerAccount", resourceOwnerAccount); } std::string GetVideoListRequest::getEndTime()const { return endTime_; } void GetVideoListRequest::setEndTime(const std::string& endTime) { endTime_ = endTime; setParameter("EndTime", endTime); } long GetVideoListRequest::getOwnerId()const { return ownerId_; } void GetVideoListRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } int GetVideoListRequest::getPageNo()const { return pageNo_; } void GetVideoListRequest::setPageNo(int pageNo) { pageNo_ = pageNo; setParameter("PageNo", std::to_string(pageNo)); } std::string GetVideoListRequest::getSortBy()const { return sortBy_; } void GetVideoListRequest::setSortBy(const std::string& sortBy) { sortBy_ = sortBy; setParameter("SortBy", sortBy); } std::string GetVideoListRequest::getStatus()const { return status_; } void GetVideoListRequest::setStatus(const std::string& status) { status_ = status; setParameter("Status", status); }
22.847682
91
0.746667
iamzken
149e527a514999a5743443fb29371858a8d8af53
50,286
cpp
C++
test/adiar/zdd/test_binop.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
test/adiar/zdd/test_binop.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
test/adiar/zdd/test_binop.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
go_bandit([]() { describe("adiar/zdd/binop.cpp", []() { node_file zdd_F; node_file zdd_T; { // Garbage collect writers to free write-lock node_writer nw_F(zdd_F); nw_F << create_sink(false); node_writer nw_T(zdd_T); nw_T << create_sink(true); } ptr_t sink_T = create_sink_ptr(true); ptr_t sink_F = create_sink_ptr(false); node_file zdd_x0; node_file zdd_x1; { // Garbage collect writers early node_writer nw_x0(zdd_x0); nw_x0 << create_node(0,MAX_ID, sink_F, sink_T); node_writer nw_x1(zdd_x1); nw_x1 << create_node(1,MAX_ID, sink_F, sink_T); } describe("zdd_union", [&]() { it("should shortcut Ø on same file", [&]() { __zdd out = zdd_union(zdd_F, zdd_F); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_F._file_ptr)); }); it("should shortcut { Ø } on same file", [&]() { __zdd out = zdd_union(zdd_T, zdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_T._file_ptr)); }); it("should shortcut { {0} } on same file", [&]() { __zdd out = zdd_union(zdd_x0, zdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr)); }); it("should shortcut { {1} } on same file", [&]() { __zdd out = zdd_union(zdd_x1, zdd_x1); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(zdd_x1._file_ptr)); }); it("computes Ø U { {Ø} }", [&]() { __zdd out = zdd_union(zdd_F, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); level_info_test_stream<node_t> ms(out); AssertThat(ms.can_pull(), Is().False()); }); it("computes { Ø } U Ø", [&]() { __zdd out = zdd_union(zdd_T, zdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); level_info_test_stream<node_t> ms(out); AssertThat(ms.can_pull(), Is().False()); }); it("should shortcut on irrelevance for { {0} } U Ø", [&]() { /* 1 ---- x0 / \ F T */ __zdd out_1 = zdd_union(zdd_x0, zdd_F); AssertThat(out_1.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr)); __zdd out_2 = zdd_union(zdd_F, zdd_x0); AssertThat(out_2.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr)); }); it("computes { {0} } U { Ø }", [&]() { /* 1 ---- x0 / \ T T */ __zdd out = zdd_union(zdd_x0, zdd_T); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0} } U { {1} }", [&]() { /* 1 ---- x0 / \ 2 T ---- x1 / \ F T */ __zdd out = zdd_union(zdd_x0, zdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0,1}, {0,3} } U { {0,2}, {2} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ X F 2 | | (2,2) \ ---- x1 / \ \ / ==> / \ \ | T 2 (3,2) T (F,2) ---- x2 | / \ / \ / \ 3 F T (3,F) T F T ---- x3 / \ / \ F T F T */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(3,MAX_ID, sink_F, sink_T) << create_node(1,MAX_ID, create_node_ptr(3,MAX_ID), sink_T) << create_node(0,MAX_ID, sink_F, create_node_ptr(1,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID)) ; } __zdd out = zdd_union(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0,1}, {1} } U { {0,2}, {2} }", [&]() { /* 1 1 (1,1) || / \ | | 2 | | (2,2) / \ \ / ==> / \ F T 2 (F,2) (T,F) <-- since 2nd (2) skipped level / \ / \ F T F T */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(1,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID)) ; } __zdd out = zdd_union(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0}, {1,3}, {2,3}, {1} } U { {0,3}, {3} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ 2 T | | (2,2) \ ---- x1 / \ | | / \ \ 3 \ | | ==> (3,2) | \ ---- x2 \\ / \ / / \ | | 4 2 (4,2) (4,F) (T,2) ---- x3 / \ / \ / \ / \ / \ F T F T T T T T T T The high arc on (2) and (3) on the left is shortcutting the second ZDD, to compensate for the omitted nodes. */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(3,MAX_ID, sink_F, sink_T) << create_node(2,MAX_ID, create_node_ptr(3,MAX_ID), create_node_ptr(3,MAX_ID)) << create_node(1,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(3,MAX_ID)) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T) ; node_writer nw_b(zdd_b); nw_b << create_node(3,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(3,MAX_ID), create_node_ptr(3,MAX_ID)) ; } __zdd out = zdd_union(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(3,2) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,2), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,2)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,3u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("zdd_intsec", [&]() { it("should shortcut on same file", [&]() { __zdd out_1 = zdd_intsec(zdd_x0, zdd_x0); AssertThat(out_1.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr)); __zdd out_2 = zdd_intsec(zdd_x1, zdd_x1); AssertThat(out_2.get<node_file>()._file_ptr, Is().EqualTo(zdd_x1._file_ptr)); }); it("computes Ø ∩ { {Ø} }", [&]() { __zdd out = zdd_intsec(zdd_F, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { Ø } ∩ Ø", [&]() { __zdd out = zdd_intsec(zdd_T, zdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes (and shortcut) { {0} } ∩ Ø", [&]() { /* 1 F F ---- x0 / \ ==> F T */ __zdd out = zdd_intsec(zdd_x0, zdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes (and shortcut) Ø ∩ { {0} }", [&]() { __zdd out = zdd_intsec(zdd_F, zdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { {0} } ∩ { Ø }", [&]() { /* 1 T F ---- x0 / \ ==> F T */ __zdd out = zdd_intsec(zdd_x0, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { Ø, {0} } ∩ { Ø }", [&]() { /* 1 T T ---- x0 / \ ==> T T */ node_file zdd_a; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(0,MAX_ID, sink_T, sink_T); } __zdd out = zdd_intsec(zdd_a, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { {0}, {1} } ∩ { Ø }", [&]() { /* 1 T F ---- x0 / \ 2 T ==> ---- x1 / \ F T */ node_file zdd_a; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T) ; } __zdd out = zdd_intsec(zdd_a, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes (and shortcut) { {0,1}, {1} } ∩ { {0,1} }", [&]() { /* _1_ 1 1 ---- x0 / \ / \ / \ 2 3 F 2 ==> F 2 ---- x1 / \ / \ / \ / \ T T F T F T F T */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(1,MAX_ID-1, sink_T, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID-1), create_node_ptr(1,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, sink_F, create_node_ptr(1,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes (and skip to sink) { {0}, {1}, {0,1} } ∩ { Ø }", [&]() { /* 1 T F ---- x0 / \ \ / ==> 2 ---- x1 / \ F T */ node_file zdd_a; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(1,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes (and skip to sink) { {0,2}, {0}, {2} } \\ { {1}, {2}, Ø }", [&]() { /* 1 F ---- x0 / \ / \ _1_ ---- x1 | | / \ => 2 3 2 3 ---- x2 / \ / \ / \ / \ F T T T T F F T Where (2) and (3) are swapped in order on the right. Notice, that (2) on the right technically is illegal, but it makes for a much simpler counter-example that catches prod_pq_1.peek() throwing an error on being empty. */ node_file zdd_a; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(2,MAX_ID, sink_T, sink_T) << create_node(2,MAX_ID-1, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(2,MAX_ID)) ; } node_file zdd_b; { // Garbage collect writers early node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_T, sink_F) << create_node(2,MAX_ID-1, sink_F, sink_T) << create_node(1,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID-1)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes (and skips in) { {0,1,2}, {0,2}, {0}, {2} } } ∩ { {0,2}, {0}, {1}, {2} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ | _2_ 2 \ / \ \/ \ / \ | ==> | | 3 4 3 T 4 (3,3) (3,4) / \ / \ / \ / \ / \ / \ T T F T F T T T F T T T where (3) and (4) are swapped in order on the left one. (3,3) : ((2,1), (2,0)) , (3,4) : ((2,1), (2,1)) so (3,3) is forwarded while (3,4) is not and hence (3,3) is output first. */ node_file zdd_a; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(2,MAX_ID, sink_T, sink_T) << create_node(2,MAX_ID-1, sink_F, sink_T) << create_node(1,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(2,MAX_ID-1)) << create_node(0,MAX_ID, create_node_ptr(2,MAX_ID), create_node_ptr(1,MAX_ID)) ; } node_file zdd_b; { // Garbage collect writers early node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_T, sink_T) << create_node(2,MAX_ID-1, sink_F, sink_T) << create_node(1,MAX_ID, create_node_ptr(2,MAX_ID-1), sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0}, {1} } ∩ { {0,1} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ 2 T F 2 F (T,2) ---- x1 / \ / \ ==> / \ F T F T F F */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T) ; node_writer nw_b(zdd_b); nw_b << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, sink_F, create_node_ptr(1,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes (and skip) { {0}, {1}, {2}, {1,2}, {0,2} } ∩ { {0}, {2}, {0,2}, {0,1,2} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ 2 | | 2 / \ ---- x1 / \| |/ \ ==> | | 3 4 3 4 (3,3) (4,3) ---- x2 / \/ \ / \/ \ / \ / \ F T T F T T F T F T Notice, how (2,3) and (4,2) was skipped on the low and high of (1,1) */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(2,MAX_ID, sink_T, sink_T) << create_node(2,MAX_ID-1, sink_F, sink_T) << create_node(1,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(2,MAX_ID)) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_T, sink_T) << create_node(2,MAX_ID-1, sink_F, sink_T) << create_node(1,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(2,MAX_ID)) << create_node(0,MAX_ID, create_node_ptr(2,MAX_ID-1), create_node_ptr(1,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes (and skip) { {0}, {1} } ∩ { {1}, {0,2} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ 2 T 2 \ (2,2) F ---- x1 / \ / \ | => / \ F T F T 3 F T ---- x2 / \ F T */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T) ; node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_F, sink_T) << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes (and skip) { {0,2}, {1,2}, Ø } ∩ { {0,1}, {0}, {1} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ 2 \ 2 T (2,2) | ---- x1 / \ / / \ => / \ | T 3 T T T F F ---- x2 / \ F T This shortcuts the (3,T) tuple twice. */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(2,MAX_ID, sink_F, sink_T) << create_node(1,MAX_ID, sink_T, create_node_ptr(2,MAX_ID)) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(1,MAX_ID, sink_T, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), sink_T) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes (and shortcut) { {0,2}, {1,2}, Ø } ∩ { {0,2}, {0} }", [&]() { /* 1 1 (1,1) ---- x0 / \ / \ / \ 2 \ F | F | ---- x1 / \ / | ==> | T 3 2 (2,3) ---- x2 / \ / \ / \ F T T T F T This shortcuts the (3,T) tuple twice. */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(2,MAX_ID, sink_F, sink_T) << create_node(1,MAX_ID, sink_T, create_node_ptr(2,MAX_ID)) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(2,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(2,MAX_ID, sink_T, sink_T) << create_node(0,MAX_ID, sink_F, create_node_ptr(2,MAX_ID)) ; } __zdd out = zdd_intsec(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("zdd_diff", [&]() { it("should shortcut to Ø on same file for { {x0} }", [&]() { __zdd out = zdd_diff(zdd_x0, zdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut to Ø on same file for { {x1} }", [&]() { __zdd out = zdd_diff(zdd_x1, zdd_x1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { Ø } \\ Ø", [&]() { __zdd out = zdd_diff(zdd_T, zdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes Ø \\ { Ø }", [&]() { __zdd out = zdd_diff(zdd_F, zdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on { {x0} } \\ Ø", [&]() { __zdd out_1 = zdd_diff(zdd_x0, zdd_F); AssertThat(out_1.get<node_file>()._file_ptr, Is().EqualTo(zdd_x0._file_ptr)); }); it("should shortcut on irrelevance on { {x1} } \\ Ø", [&]() { __zdd out_2 = zdd_diff(zdd_x1, zdd_F); AssertThat(out_2.get<node_file>()._file_ptr, Is().EqualTo(zdd_x1._file_ptr)); }); it("computes (and shortcut) Ø \\ { {0} }", [&]() { __zdd out = zdd_intsec(zdd_F, zdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { {Ø} } \\ { {0} }", [&]() { __zdd out = zdd_diff(zdd_T, zdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("computes { {0} } \\ { Ø }", [&]() { /* 1 T 1 ---- x0 / \ ==> / \ F T F T */ __zdd out = zdd_diff(zdd_x0, zdd_T); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0}, Ø } \\ { Ø }", [&]() { /* 1 T 1 ---- x0 / \ ==> / \ T T F T */ node_file zdd_a; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(0,MAX_ID, sink_T, sink_T); } __zdd out = zdd_diff(zdd_a, zdd_T); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0,1}, {1} } \\ { {1}, Ø }", [&]() { /* 1 (1,1) ---- x0 || / \ 2 1 ==> (2,1) (2,F) ---- x1 / \ / \ / \ / \ F T T T F F F T */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(1,MAX_ID, sink_F, sink_T) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID), create_node_ptr(1,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(1,MAX_ID, sink_T, sink_T); } __zdd out = zdd_diff(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("computes { {0,1}, {1,2}, {1} } \\ { {1}, Ø }", [&]() { /* _1_ (1,1) ---- x0 / \ / \ 3 2 1 ==> (3,1) (2,F) ---- x1 / \ / \ / \ / \ / \ F 4 F T T T F (3,T) F T ---- x2 / \ / \ T T F T */ node_file zdd_a; node_file zdd_b; { // Garbage collect writers early node_writer nw_a(zdd_a); nw_a << create_node(2,MAX_ID, sink_T, sink_T) << create_node(1,MAX_ID, sink_F, sink_T) << create_node(1,MAX_ID-1, sink_F, create_node_ptr(2,MAX_ID)) << create_node(0,MAX_ID, create_node_ptr(1,MAX_ID-1), create_node_ptr(1,MAX_ID)) ; node_writer nw_b(zdd_b); nw_b << create_node(1,MAX_ID, sink_T, sink_T); } __zdd out = zdd_diff(zdd_a, zdd_b); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); }); });
37.752252
109
0.518474
logsem
149f5a1f03244b13f4f497f7a56b8cad684d179b
1,228
hpp
C++
Autocoders/test/enum1port/DrvTimingSignalPort.hpp
lydiaxing/fprime
f6b3e03f89e9aca1614243c9896d4a72aa0cc726
[ "Apache-2.0" ]
2
2020-09-08T05:39:05.000Z
2021-05-04T14:58:51.000Z
Autocoders/test/enum1port/DrvTimingSignalPort.hpp
JPLOpenSource/fprime-sw-Rel1.0
18364596c24fa369c938ef8758e5aa945ecc6a9b
[ "Apache-2.0" ]
2
2019-02-27T03:17:15.000Z
2019-03-01T22:34:30.000Z
Autocoders/test/enum1port/DrvTimingSignalPort.hpp
JPLOpenSource/fprime-sw-Rel1.0
18364596c24fa369c938ef8758e5aa945ecc6a9b
[ "Apache-2.0" ]
3
2019-02-17T20:41:15.000Z
2019-02-26T21:06:50.000Z
#ifndef DRV_BIU_RB_INT_SIG_RECEIVE_PORT_HPP #define DRV_BIU_RB_INT_SIG_RECEIVE_PORT_HPP #include <Fw/Port/FwInputPortBase.hpp> #include <Fw/Port/FwOutputPortBase.hpp> #include <Fw/Comp/FwCompBase.hpp> #include <Fw/Types/FwBasicTypes.hpp> namespace Drv { typedef enum { REAL_TIME_INTERRUPT } TimingSignal ; class InputTimingSignalPort : public Fw::InputPortBase { public: typedef void (*CompFuncPtr)(Fw::ComponentBase* callComp, NATIVE_INT_TYPE portNum, TimingSignal signal); InputTimingSignalPort(void); void init(void); void addCallComp(Fw::ComponentBase* callComp, CompFuncPtr funcPtr); void invoke(TimingSignal signal); protected: private: CompFuncPtr m_func; #if FW_PORT_SERIALIZATION void invokeSerial(Fw::SerializeBufferBase &buffer); #endif }; class OutputTimingSignalPort : public Fw::OutputPortBase { public: OutputTimingSignalPort(void); void init(void); void addCallPort(Drv::InputTimingSignalPort* callPort); void invoke(TimingSignal signal); protected: private: Drv::InputTimingSignalPort* m_port; }; } #endif
27.909091
111
0.680782
lydiaxing
14a15cb872a5518f55b20c5292e451f1211f3c42
321
hpp
C++
src/header_hpp/tcp_header.hpp
Maxim-byte/pcap_parser-
3f34b824699ec595ff34518d83b278d1cbcdeef5
[ "MIT" ]
null
null
null
src/header_hpp/tcp_header.hpp
Maxim-byte/pcap_parser-
3f34b824699ec595ff34518d83b278d1cbcdeef5
[ "MIT" ]
null
null
null
src/header_hpp/tcp_header.hpp
Maxim-byte/pcap_parser-
3f34b824699ec595ff34518d83b278d1cbcdeef5
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <iosfwd> #include <system_error> struct tcp_header { std::uint16_t s_port; std::uint16_t d_port; static tcp_header read_tcp_header(std::istream & stream, std::error_code & ec); static void print_tcp_header(std::ostream & stream, const tcp_header & header); };
20.0625
83
0.719626
Maxim-byte
14a336dc3427d323f6920fa0a13597de3d4ec19f
7,637
cpp
C++
src/rtc/momo_video_encoder_factory.cpp
S-YOU/momo
9047dd4eb58345e9fea151ee2e04deb876033947
[ "Apache-2.0" ]
null
null
null
src/rtc/momo_video_encoder_factory.cpp
S-YOU/momo
9047dd4eb58345e9fea151ee2e04deb876033947
[ "Apache-2.0" ]
null
null
null
src/rtc/momo_video_encoder_factory.cpp
S-YOU/momo
9047dd4eb58345e9fea151ee2e04deb876033947
[ "Apache-2.0" ]
null
null
null
#include "momo_video_encoder_factory.h" // WebRTC #include <absl/memory/memory.h> #include <absl/strings/match.h> #include <api/video_codecs/sdp_video_format.h> #include <media/base/codec.h> #include <media/base/media_constants.h> #include <media/base/vp9_profile.h> #include <media/engine/simulcast_encoder_adapter.h> #include <modules/video_coding/codecs/h264/include/h264.h> #include <modules/video_coding/codecs/vp8/include/vp8.h> #include <modules/video_coding/codecs/vp9/include/vp9.h> #include <rtc_base/logging.h> #if !defined(__arm__) || defined(__aarch64__) || defined(__ARM_NEON__) #include <modules/video_coding/codecs/av1/libaom_av1_encoder.h> #endif #if defined(__APPLE__) #include "mac_helper/objc_codec_factory_helper.h" #endif #if USE_MMAL_ENCODER #include "hwenc_mmal/mmal_h264_encoder.h" #endif #if USE_JETSON_ENCODER #include "hwenc_jetson/jetson_video_encoder.h" #endif #if USE_NVCODEC_ENCODER #include "hwenc_nvcodec/nvcodec_h264_encoder.h" #endif #include "h264_format.h" MomoVideoEncoderFactory::MomoVideoEncoderFactory( VideoCodecInfo::Type vp8_encoder, VideoCodecInfo::Type vp9_encoder, VideoCodecInfo::Type av1_encoder, VideoCodecInfo::Type h264_encoder, bool simulcast) : vp8_encoder_(vp8_encoder), vp9_encoder_(vp9_encoder), av1_encoder_(av1_encoder), h264_encoder_(h264_encoder) { #if defined(__APPLE__) video_encoder_factory_ = CreateObjCEncoderFactory(); #endif if (simulcast) { internal_encoder_factory_.reset(new MomoVideoEncoderFactory( vp8_encoder, vp9_encoder, av1_encoder, h264_encoder, false)); } } std::vector<webrtc::SdpVideoFormat> MomoVideoEncoderFactory::GetSupportedFormats() const { std::vector<webrtc::SdpVideoFormat> supported_codecs; // VP8 if (vp8_encoder_ == VideoCodecInfo::Type::Software || vp8_encoder_ == VideoCodecInfo::Type::Jetson) { supported_codecs.push_back(webrtc::SdpVideoFormat(cricket::kVp8CodecName)); } // VP9 if (vp9_encoder_ == VideoCodecInfo::Type::Software) { for (const webrtc::SdpVideoFormat& format : webrtc::SupportedVP9Codecs()) { supported_codecs.push_back(format); } } else if (vp9_encoder_ == VideoCodecInfo::Type::Jetson) { #if USE_JETSON_ENCODER supported_codecs.push_back(webrtc::SdpVideoFormat( cricket::kVp9CodecName, {{webrtc::kVP9FmtpProfileId, webrtc::VP9ProfileToString(webrtc::VP9Profile::kProfile0)}})); #endif } // AV1 // 今のところ Software のみ if (av1_encoder_ == VideoCodecInfo::Type::Software) { supported_codecs.push_back(webrtc::SdpVideoFormat(cricket::kAv1CodecName)); } // H264 std::vector<webrtc::SdpVideoFormat> h264_codecs = { CreateH264Format(webrtc::H264::kProfileBaseline, webrtc::H264::kLevel3_1, "1"), CreateH264Format(webrtc::H264::kProfileBaseline, webrtc::H264::kLevel3_1, "0"), CreateH264Format(webrtc::H264::kProfileConstrainedBaseline, webrtc::H264::kLevel3_1, "1"), CreateH264Format(webrtc::H264::kProfileConstrainedBaseline, webrtc::H264::kLevel3_1, "0")}; if (h264_encoder_ == VideoCodecInfo::Type::VideoToolbox) { // VideoToolbox の場合は video_encoder_factory_ から H264 を拾ってくる for (auto format : video_encoder_factory_->GetSupportedFormats()) { if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName)) { supported_codecs.push_back(format); } } } else if (h264_encoder_ == VideoCodecInfo::Type::NVIDIA) { #if USE_NVCODEC_ENCODER // NVIDIA の場合は対応してる場合のみ追加 if (NvCodecH264Encoder::IsSupported()) { for (const webrtc::SdpVideoFormat& format : h264_codecs) { supported_codecs.push_back(format); } } #endif } else if (h264_encoder_ != VideoCodecInfo::Type::NotSupported) { // その他のエンコーダの場合は手動で追加 for (const webrtc::SdpVideoFormat& format : h264_codecs) { supported_codecs.push_back(format); } } return supported_codecs; } std::unique_ptr<webrtc::VideoEncoder> MomoVideoEncoderFactory::CreateVideoEncoder( const webrtc::SdpVideoFormat& format) { if (absl::EqualsIgnoreCase(format.name, cricket::kVp8CodecName)) { if (vp8_encoder_ == VideoCodecInfo::Type::Software) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return webrtc::VP8Encoder::Create(); }); } #if USE_JETSON_ENCODER if (vp8_encoder_ == VideoCodecInfo::Type::Jetson) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return std::unique_ptr<webrtc::VideoEncoder>( absl::make_unique<JetsonVideoEncoder>(cricket::VideoCodec(format))); }); } #endif } if (absl::EqualsIgnoreCase(format.name, cricket::kVp9CodecName)) { if (vp9_encoder_ == VideoCodecInfo::Type::Software) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return webrtc::VP9Encoder::Create(cricket::VideoCodec(format)); }); } #if USE_JETSON_ENCODER if (vp9_encoder_ == VideoCodecInfo::Type::Jetson) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return std::unique_ptr<webrtc::VideoEncoder>( absl::make_unique<JetsonVideoEncoder>(cricket::VideoCodec(format))); }); } #endif } if (absl::EqualsIgnoreCase(format.name, cricket::kAv1CodecName)) { #if !defined(__arm__) || defined(__aarch64__) || defined(__ARM_NEON__) if (av1_encoder_ == VideoCodecInfo::Type::Software) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return webrtc::CreateLibaomAv1Encoder(); }); } #endif } if (absl::EqualsIgnoreCase(format.name, cricket::kH264CodecName)) { #if defined(__APPLE__) if (h264_encoder_ == VideoCodecInfo::Type::VideoToolbox) { return WithSimulcast( format, [this](const webrtc::SdpVideoFormat& format) { return video_encoder_factory_->CreateVideoEncoder(format); }); } #endif #if USE_MMAL_ENCODER if (h264_encoder_ == VideoCodecInfo::Type::MMAL) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return std::unique_ptr<webrtc::VideoEncoder>( absl::make_unique<MMALH264Encoder>(cricket::VideoCodec(format))); }); } #endif #if USE_JETSON_ENCODER if (h264_encoder_ == VideoCodecInfo::Type::Jetson) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return std::unique_ptr<webrtc::VideoEncoder>( absl::make_unique<JetsonVideoEncoder>(cricket::VideoCodec(format))); }); } #endif #if USE_NVCODEC_ENCODER if (h264_encoder_ == VideoCodecInfo::Type::NVIDIA && NvCodecH264Encoder::IsSupported()) { return WithSimulcast(format, [](const webrtc::SdpVideoFormat& format) { return std::unique_ptr<webrtc::VideoEncoder>( absl::make_unique<NvCodecH264Encoder>(cricket::VideoCodec(format))); }); } #endif } RTC_LOG(LS_ERROR) << "Trying to created encoder of unsupported format " << format.name; return nullptr; } std::unique_ptr<webrtc::VideoEncoder> MomoVideoEncoderFactory::WithSimulcast( const webrtc::SdpVideoFormat& format, std::function<std::unique_ptr<webrtc::VideoEncoder>( const webrtc::SdpVideoFormat&)> create) { if (internal_encoder_factory_) { return std::unique_ptr<webrtc::VideoEncoder>( new webrtc::SimulcastEncoderAdapter(internal_encoder_factory_.get(), format)); } else { return create(format); } }
34.400901
80
0.698049
S-YOU
14a342db004ab861a6396ea22f45922ed9fb8b92
8,925
cpp
C++
WebLayoutCore/Source/WebCore/rendering/TextPaintStyle.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2020-05-25T16:06:49.000Z
2020-05-25T16:06:49.000Z
WebLayoutCore/Source/WebCore/rendering/TextPaintStyle.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
null
null
null
WebLayoutCore/Source/WebCore/rendering/TextPaintStyle.cpp
gubaojian/trylearn
74dd5c6c977f8d867d6aa360b84bc98cb82f480c
[ "MIT" ]
1
2018-07-10T10:53:18.000Z
2018-07-10T10:53:18.000Z
/* * Copyright (C) 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "TextPaintStyle.h" #include "FocusController.h" #include "Frame.h" #include "GraphicsContext.h" #include "Page.h" #include "PaintInfo.h" #include "RenderStyle.h" #include "RenderText.h" #include "RenderTheme.h" #include "RenderView.h" #include "Settings.h" namespace WebCore { TextPaintStyle::TextPaintStyle(const Color& color) : fillColor(color) , strokeColor(color) { } bool textColorIsLegibleAgainstBackgroundColor(const Color& textColor, const Color& backgroundColor) { // Semi-arbitrarily chose 65025 (255^2) value here after a few tests. return differenceSquared(textColor, backgroundColor) > 65025; } static Color adjustColorForVisibilityOnBackground(const Color& textColor, const Color& backgroundColor) { if (textColorIsLegibleAgainstBackgroundColor(textColor, backgroundColor)) return textColor; int distanceFromWhite = differenceSquared(textColor, Color::white); int distanceFromBlack = differenceSquared(textColor, Color::black); if (distanceFromWhite < distanceFromBlack) return textColor.dark(); return textColor.light(); } TextPaintStyle computeTextPaintStyle(const Frame& frame, const RenderStyle& lineStyle, const PaintInfo& paintInfo) { TextPaintStyle paintStyle; #if ENABLE(LETTERPRESS) paintStyle.useLetterpressEffect = lineStyle.textDecorationsInEffect() & TextDecorationLetterpress; #endif auto viewportSize = frame.view() ? frame.view()->size() : IntSize(); paintStyle.strokeWidth = lineStyle.computedStrokeWidth(viewportSize); paintStyle.paintOrder = lineStyle.paintOrder(); paintStyle.lineJoin = lineStyle.joinStyle(); paintStyle.lineCap = lineStyle.capStyle(); paintStyle.miterLimit = lineStyle.strokeMiterLimit(); if (paintInfo.forceTextColor()) { paintStyle.fillColor = paintInfo.forcedTextColor(); paintStyle.strokeColor = paintInfo.forcedTextColor(); paintStyle.emphasisMarkColor = paintInfo.forcedTextColor(); return paintStyle; } if (lineStyle.insideDefaultButton()) { Page* page = frame.page(); if (page && page->focusController().isActive()) { paintStyle.fillColor = RenderTheme::singleton().systemColor(CSSValueActivebuttontext); return paintStyle; } } paintStyle.fillColor = lineStyle.visitedDependentColor(CSSPropertyWebkitTextFillColor); bool forceBackgroundToWhite = false; if (frame.document() && frame.document()->printing()) { if (lineStyle.printColorAdjust() == PrintColorAdjustEconomy) forceBackgroundToWhite = true; if (frame.settings().shouldPrintBackgrounds()) forceBackgroundToWhite = false; } // Make the text fill color legible against a white background if (forceBackgroundToWhite) paintStyle.fillColor = adjustColorForVisibilityOnBackground(paintStyle.fillColor, Color::white); paintStyle.strokeColor = lineStyle.computedStrokeColor(); // Make the text stroke color legible against a white background if (forceBackgroundToWhite) paintStyle.strokeColor = adjustColorForVisibilityOnBackground(paintStyle.strokeColor, Color::white); paintStyle.emphasisMarkColor = lineStyle.visitedDependentColor(CSSPropertyWebkitTextEmphasisColor); // Make the text stroke color legible against a white background if (forceBackgroundToWhite) paintStyle.emphasisMarkColor = adjustColorForVisibilityOnBackground(paintStyle.emphasisMarkColor, Color::white); return paintStyle; } TextPaintStyle computeTextSelectionPaintStyle(const TextPaintStyle& textPaintStyle, const RenderText& renderer, const RenderStyle& lineStyle, const PaintInfo& paintInfo, bool& paintSelectedTextOnly, bool& paintSelectedTextSeparately, bool& paintNonSelectedTextOnly, const ShadowData*& selectionShadow) { paintSelectedTextOnly = (paintInfo.phase == PaintPhaseSelection); paintSelectedTextSeparately = paintInfo.paintBehavior & PaintBehaviorExcludeSelection; paintNonSelectedTextOnly = paintInfo.paintBehavior & PaintBehaviorExcludeSelection; selectionShadow = (paintInfo.forceTextColor()) ? nullptr : lineStyle.textShadow(); TextPaintStyle selectionPaintStyle = textPaintStyle; #if ENABLE(TEXT_SELECTION) Color foreground = paintInfo.forceTextColor() ? paintInfo.forcedTextColor() : renderer.selectionForegroundColor(); if (foreground.isValid() && foreground != selectionPaintStyle.fillColor) { if (!paintSelectedTextOnly) paintSelectedTextSeparately = true; selectionPaintStyle.fillColor = foreground; } Color emphasisMarkForeground = paintInfo.forceTextColor() ? paintInfo.forcedTextColor() : renderer.selectionEmphasisMarkColor(); if (emphasisMarkForeground.isValid() && emphasisMarkForeground != selectionPaintStyle.emphasisMarkColor) { if (!paintSelectedTextOnly) paintSelectedTextSeparately = true; selectionPaintStyle.emphasisMarkColor = emphasisMarkForeground; } if (auto* pseudoStyle = renderer.getCachedPseudoStyle(SELECTION)) { const ShadowData* shadow = paintInfo.forceTextColor() ? nullptr : pseudoStyle->textShadow(); if (shadow != selectionShadow) { if (!paintSelectedTextOnly) paintSelectedTextSeparately = true; selectionShadow = shadow; } auto viewportSize = renderer.frame().view() ? renderer.frame().view()->size() : IntSize(); float strokeWidth = pseudoStyle->computedStrokeWidth(viewportSize); if (strokeWidth != selectionPaintStyle.strokeWidth) { if (!paintSelectedTextOnly) paintSelectedTextSeparately = true; selectionPaintStyle.strokeWidth = strokeWidth; } Color stroke = paintInfo.forceTextColor() ? paintInfo.forcedTextColor() : pseudoStyle->computedStrokeColor(); if (stroke != selectionPaintStyle.strokeColor) { if (!paintSelectedTextOnly) paintSelectedTextSeparately = true; selectionPaintStyle.strokeColor = stroke; } } #else UNUSED_PARAM(renderer); UNUSED_PARAM(lineStyle); UNUSED_PARAM(paintInfo); #endif return selectionPaintStyle; } void updateGraphicsContext(GraphicsContext& context, const TextPaintStyle& paintStyle, FillColorType fillColorType) { TextDrawingModeFlags mode = context.textDrawingMode(); TextDrawingModeFlags newMode = mode; #if ENABLE(LETTERPRESS) if (paintStyle.useLetterpressEffect) newMode |= TextModeLetterpress; else newMode &= ~TextModeLetterpress; #endif if (paintStyle.strokeWidth > 0 && paintStyle.strokeColor.isVisible()) newMode |= TextModeStroke; if (mode != newMode) { context.setTextDrawingMode(newMode); mode = newMode; } Color fillColor = fillColorType == UseEmphasisMarkColor ? paintStyle.emphasisMarkColor : paintStyle.fillColor; if (mode & TextModeFill && (fillColor != context.fillColor())) context.setFillColor(fillColor); if (mode & TextModeStroke) { if (paintStyle.strokeColor != context.strokeColor()) context.setStrokeColor(paintStyle.strokeColor); if (paintStyle.strokeWidth != context.strokeThickness()) context.setStrokeThickness(paintStyle.strokeWidth); context.setLineJoin(paintStyle.lineJoin); context.setLineCap(paintStyle.lineCap); if (paintStyle.lineJoin == MiterJoin) context.setMiterLimit(paintStyle.miterLimit); } } }
41.705607
301
0.732661
gubaojian
14a3fc3a17136a8fb0c0304476b086058ef673ee
4,009
hpp
C++
include/boost/winapi/init_once.hpp
xentrax/winapi
66564382fa780a6f3d88d875181667728a4c4ba0
[ "BSL-1.0" ]
null
null
null
include/boost/winapi/init_once.hpp
xentrax/winapi
66564382fa780a6f3d88d875181667728a4c4ba0
[ "BSL-1.0" ]
null
null
null
include/boost/winapi/init_once.hpp
xentrax/winapi
66564382fa780a6f3d88d875181667728a4c4ba0
[ "BSL-1.0" ]
null
null
null
/* * Copyright 2010 Vicente J. Botet Escriba * Copyright 2015 Andrey Semashev * * Distributed under the Boost Software License, Version 1.0. * See http://www.boost.org/LICENSE_1_0.txt */ #ifndef BOOST_WINAPI_INIT_ONCE_HPP_INCLUDED_ #define BOOST_WINAPI_INIT_ONCE_HPP_INCLUDED_ #include <boost/winapi/config.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #if BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6 #include <boost/winapi/basic_types.hpp> #if !defined(BOOST_USE_WINDOWS_H) extern "C" { #if defined(BOOST_WINAPI_IS_CYGWIN) || defined(BOOST_WINAPI_IS_MINGW_W64) struct _RTL_RUN_ONCE; #else union _RTL_RUN_ONCE; #endif typedef boost::winapi::BOOL_ (BOOST_WINAPI_WINAPI_CC *PINIT_ONCE_FN) ( ::_RTL_RUN_ONCE* InitOnce, boost::winapi::PVOID_ Parameter, boost::winapi::PVOID_ *Context); BOOST_WINAPI_IMPORT boost::winapi::VOID_ BOOST_WINAPI_WINAPI_CC InitOnceInitialize(::_RTL_RUN_ONCE* InitOnce); BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC InitOnceExecuteOnce( ::_RTL_RUN_ONCE* InitOnce, ::PINIT_ONCE_FN InitFn, boost::winapi::PVOID_ Parameter, boost::winapi::LPVOID_ *Context); BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC InitOnceBeginInitialize( ::_RTL_RUN_ONCE* lpInitOnce, boost::winapi::DWORD_ dwFlags, boost::winapi::PBOOL_ fPending, boost::winapi::LPVOID_ *lpContext); BOOST_WINAPI_IMPORT boost::winapi::BOOL_ BOOST_WINAPI_WINAPI_CC InitOnceComplete( ::_RTL_RUN_ONCE* lpInitOnce, boost::winapi::DWORD_ dwFlags, boost::winapi::LPVOID_ lpContext); } #endif namespace boost { namespace winapi { typedef union BOOST_MAY_ALIAS _RTL_RUN_ONCE { PVOID_ Ptr; } INIT_ONCE_, *PINIT_ONCE_, *LPINIT_ONCE_; extern "C" { typedef BOOL_ (BOOST_WINAPI_WINAPI_CC *PINIT_ONCE_FN_) (PINIT_ONCE_ lpInitOnce, PVOID_ Parameter, PVOID_ *Context); } BOOST_FORCEINLINE VOID_ InitOnceInitialize(PINIT_ONCE_ lpInitOnce) { ::InitOnceInitialize(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce)); } BOOST_FORCEINLINE BOOL_ InitOnceExecuteOnce(PINIT_ONCE_ lpInitOnce, PINIT_ONCE_FN_ InitFn, PVOID_ Parameter, LPVOID_ *Context) { return ::InitOnceExecuteOnce(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce), reinterpret_cast< ::PINIT_ONCE_FN >(InitFn), Parameter, Context); } BOOST_FORCEINLINE BOOL_ InitOnceBeginInitialize(PINIT_ONCE_ lpInitOnce, DWORD_ dwFlags, PBOOL_ fPending, LPVOID_ *lpContext) { return ::InitOnceBeginInitialize(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce), dwFlags, fPending, lpContext); } BOOST_FORCEINLINE BOOL_ InitOnceComplete(PINIT_ONCE_ lpInitOnce, DWORD_ dwFlags, LPVOID_ lpContext) { return ::InitOnceComplete(reinterpret_cast< ::_RTL_RUN_ONCE* >(lpInitOnce), dwFlags, lpContext); } #if defined( BOOST_USE_WINDOWS_H ) #define BOOST_WINAPI_INIT_ONCE_STATIC_INIT INIT_ONCE_STATIC_INIT BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_ASYNC_ = INIT_ONCE_ASYNC; BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CHECK_ONLY_ = INIT_ONCE_CHECK_ONLY; BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_INIT_FAILED_ = INIT_ONCE_INIT_FAILED; BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CTX_RESERVED_BITS_ = INIT_ONCE_CTX_RESERVED_BITS; #else // defined( BOOST_USE_WINDOWS_H ) #define BOOST_WINAPI_INIT_ONCE_STATIC_INIT {0} BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_ASYNC_ = 0x00000002UL; BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CHECK_ONLY_ = 0x00000001UL; BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_INIT_FAILED_ = 0x00000004UL; BOOST_CONSTEXPR_OR_CONST DWORD_ INIT_ONCE_CTX_RESERVED_BITS_ = 2; #endif // defined( BOOST_USE_WINDOWS_H ) BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_async = INIT_ONCE_ASYNC_; BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_check_only = INIT_ONCE_CHECK_ONLY_; BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_init_failed = INIT_ONCE_INIT_FAILED_; BOOST_CONSTEXPR_OR_CONST DWORD_ init_once_ctx_reserved_bits = INIT_ONCE_CTX_RESERVED_BITS_; } } #endif // BOOST_USE_WINAPI_VERSION >= BOOST_WINAPI_VERSION_WIN6 #endif // BOOST_WINAPI_INIT_ONCE_HPP_INCLUDED_
33.132231
148
0.817411
xentrax
14a54f67fcc0ce79af00e2c7bf1339ecaceceb7d
208
cpp
C++
Test/Expect/test007.cpp
dMajoIT/spin2cpp
f2ee655d150c9d69042b2dfaf8cae57123b7702c
[ "MIT" ]
39
2015-02-10T13:43:24.000Z
2022-03-08T14:56:41.000Z
Test/Expect/test007.cpp
cbmeeks/spin2cpp
d1707a50ee90d944590a6e82c6227a6ff6ce1042
[ "MIT" ]
230
2015-04-12T22:04:54.000Z
2022-03-30T05:22:11.000Z
Test/Expect/test007.cpp
cbmeeks/spin2cpp
d1707a50ee90d944590a6e82c6227a6ff6ce1042
[ "MIT" ]
21
2016-03-05T05:15:06.000Z
2022-03-24T11:58:15.000Z
// // another test // /* with an inline comment */ #define __SPIN2CPP__ #include <propeller.h> #include "test007.h" int32_t test007::Donext(void) { Count = Count + 1; return Count; }
12.235294
30
0.605769
dMajoIT
14a7f040fbb971eda3467c2c492b2a2ac5713d0d
1,776
cpp
C++
ProblemsSolved/Trie/searchInTheDictionary.cpp
searleser97/Algorithms
af791541d416c29867213d705375cbb3361f486c
[ "Apache-2.0" ]
7
2019-06-06T17:54:20.000Z
2021-03-24T02:31:55.000Z
ProblemsSolved/Trie/searchInTheDictionary.cpp
searleser97/Algorithms
af791541d416c29867213d705375cbb3361f486c
[ "Apache-2.0" ]
null
null
null
ProblemsSolved/Trie/searchInTheDictionary.cpp
searleser97/Algorithms
af791541d416c29867213d705375cbb3361f486c
[ "Apache-2.0" ]
1
2021-03-24T02:31:57.000Z
2021-03-24T02:31:57.000Z
#include <bits/stdc++.h> // wpt = number of words passing through // w = number of words ending in the node // c = character using namespace std; struct Trie { struct Node { unordered_map<char, Node *> ch; int w = 0, wpt = 0; }; Node *root = new Node(); void insert(string str) { Node *curr = root; for (int i = 0; i < str.size(); i++) { int c = str[i]; curr->wpt++; if (!curr->ch.count(c)) curr->ch[c] = new Node(); curr = curr->ch[c]; } curr->wpt++; curr->w++; } void getWords(Node *curr, vector<string> &words, string word) { if (curr->w) words.push_back(word); for (auto &c : curr->ch) { getWords(c.second, words, word + c.first); } } vector<string> getWordsByPrefix(string prefix) { vector<string> words; Node *node = root; for (int i = 0; i < prefix.size(); i++) { int c = prefix[i]; if (!node->ch.count(c)) return words; node = node->ch[c]; } int bckp = node->w; node->w = 0; getWords(node, words, prefix); node->w = bckp; return words; } }; void printv(vector<string> v) { if (!v.size()) { cout << "No match." << endl; return; } for (int i = 0; i < v.size(); i++) cout << v[i] << endl; // for (auto &s : v) cout << s << endl; } int main() { std::ios_base::sync_with_stdio(0); int n, k; Trie *tr = new Trie(); cin >> n; for (int i = 0; i < n; i++) { string aux; cin >> aux; tr->insert(aux); } cin >> k; for (int j = 0; j < k; j++) { string str; cin >> str; cout << "Case #" << j + 1 << ":" << '\n'; vector<string> ans = tr->getWordsByPrefix(str); sort(ans.begin(), ans.end()); printv(ans); } delete tr; return 0; }
20.894118
51
0.507883
searleser97
14a80a42984b1e4aaf97c5db6ac8e3ba79c13417
274
cpp
C++
example/main.cpp
That-Cool-Coder/sfml-tictactoe
af43fd32b70acd8e73b54a2feb074df93c36bc6d
[ "MIT" ]
null
null
null
example/main.cpp
That-Cool-Coder/sfml-tictactoe
af43fd32b70acd8e73b54a2feb074df93c36bc6d
[ "MIT" ]
null
null
null
example/main.cpp
That-Cool-Coder/sfml-tictactoe
af43fd32b70acd8e73b54a2feb074df93c36bc6d
[ "MIT" ]
null
null
null
#include "Engine.hpp" #include "ExtendingScene.hpp" #include <memory> #include <iostream> int main() { std::cout << "running"; Engine engine; std::shared_ptr<ExtendingScene> scene = std::make_shared<ExtendingScene>(); engine.load(scene); engine.run(); }
21.076923
79
0.675182
That-Cool-Coder
14a84792214f67e5ec46a4fc15e00dbdc182cd16
16,702
cc
C++
hackt_docker/hackt/src/Object/lang/PRS_attribute_registry.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/PRS_attribute_registry.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/lang/PRS_attribute_registry.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/lang/PRS_attribute_registry.cc" This defines the attribute actions for the cflat visitor. $Id: PRS_attribute_registry.cc,v 1.21 2010/09/01 22:14:20 fang Exp $ */ #include "util/static_trace.hh" DEFAULT_STATIC_TRACE_BEGIN #include <iostream> #include <map> #include "Object/lang/PRS_attribute_registry.hh" #include "Object/lang/cflat_printer.hh" #include "Object/expr/const_param_expr_list.hh" #include "Object/expr/pint_const.hh" #include "Object/expr/preal_const.hh" #include "Object/expr/expr_dump_context.hh" #include "Object/lang/PRS_attribute_common.hh" #include "main/cflat_options.hh" #include "common/TODO.hh" #include "util/memory/count_ptr.tcc" namespace HAC { namespace entity { namespace PRS { #include "util/using_ostream.hh" //----------------------------------------------------------------------------- // global initializers /** Locally modifiable to this unit only. */ static cflat_rule_attribute_registry_type __cflat_rule_attribute_registry; /** Public immutable reference */ const cflat_rule_attribute_registry_type& cflat_rule_attribute_registry(__cflat_rule_attribute_registry); //============================================================================= // class attribute_definition_entry method definitions //============================================================================= /** Utility function for registering an attribute class. */ template <class T> static size_t register_cflat_rule_attribute_class(void) { // typedef cflat_rule_attribute_registry_type::iterator iterator; typedef cflat_rule_attribute_registry_type::mapped_type mapped_type; const string k(T::name); mapped_type& m(__cflat_rule_attribute_registry[k]); if (m) { cerr << "Error: PRS attribute by the name \'" << k << "\' has already been registered!" << endl; THROW_EXIT; } m = cflat_rule_attribute_definition_entry(k, &T::main, &T::check_vals); // oddly, this is needed to force instantiation of the [] const operator const mapped_type& n __ATTRIBUTE_UNUSED_CTOR__((cflat_rule_attribute_registry.find(k)->second)); INVARIANT(n); return cflat_rule_attribute_registry.size(); } //============================================================================= /** Convenient home namespace for user-defined PRS rule attributes. Each class in this namespace represents an attribute. */ namespace cflat_rule_attributes { /** Macro for declaring and defining attribute classes. Here, the vistor_type is cflat_prs_printer. TODO: These classes should have hidden visibility. TODO: could also push name[] into the base class, but would we be creating an initialization order dependence? */ #define DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(class_name, att_name) \ DECLARE_PRS_RULE_ATTRIBUTE_CLASS(class_name, cflat_prs_printer) \ DEFINE_PRS_RULE_ATTRIBUTE_CLASS(class_name, att_name, \ register_cflat_rule_attribute_class) //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-after.texi @defmac after d Applies a fixed delay @var{d} to a single rule. Affects @command{hflat} output and @command{hacprsim} operation. @end defmac @defmac after_min d @defmacx after_max d Specifies upper and lower bounds on delays for a rule. The upper bound should be greater than or equal to the lower bound, however, this is not checked here. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(After, "after") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(AfterMin, "after_min") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(AfterMax, "after_max") /** Prints out "after x" before a rule in cflat. TODO: allow real-values. */ void After::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { ostream& o(p.os); o << "after "; v.at(0).is_a<const pint_const>()->dump(o, entity::expr_dump_context::default_value) << '\t'; } } void AfterMin::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { ostream& o(p.os); o << "after_min "; v.at(0).is_a<const pint_const>()->dump(o, entity::expr_dump_context::default_value) << '\t'; } } void AfterMax::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { ostream& o(p.os); o << "after_max "; v.at(0).is_a<const pint_const>()->dump(o, entity::expr_dump_context::default_value) << '\t'; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-rule-sizing.texi @defmac W width Specify the default transistor width for this rule. For uniformly sized stacks, writing this makes the rule much less cluttered than repeating sizes per literal. Widths can always be overridden per literal. @end defmac @defmac L length Specify the default transistor length for this rule. Lengths can always be overridden per literal. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Width, "W") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Length, "L") void Width::main(visitor_type& p, const values_type& v) { if (p.cfopts.size_prs) { INVARIANT(v.size() == 1); const preal_value_type s = v.front()->to_real_const(); p.os << "W=" << s << '\t'; } } void Length::main(visitor_type& p, const values_type& v) { if (p.cfopts.size_prs) { INVARIANT(v.size() == 1); const preal_value_type s = v.front()->to_real_const(); p.os << "L=" << s << '\t'; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-vt.texi @defmac hvt @defmacx lvt @defmacx svt If @option{hvt} is set, then emit all devices with in this particular rule with hvt (high voltage threshold), unless explicitly overridden in a node literal. If @option{lvt} is set, then emit all devices with in this particular rule with lvt (low voltage threshold), unless overridden. @option{svt} restores back to standard Vt as the default. When no parameter value is given, implicit value is 1. When multiple settings are given, the last one should take precedence. Default: svt @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(HVT, "hvt") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(LVT, "lvt") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(SVT, "svt") void HVT::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_LVS) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "hvt\t"; } } } void LVT::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_LVS) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "lvt\t"; } } } void SVT::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_LVS) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "svt\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-always_random.texi @defmac always_random b If @var{b} is true (1), rule delay is based on random exponential distribution. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Always_Random, "always_random") /** Prints out "always_random" before a rule in cflat. TODO: check to ensure use with after. */ void Always_Random::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { pint_value_type b = 1; // default true if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "always_random\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-weak.texi @defmac weak b If @var{b} is true (1), rule is considered weak, e.g. feedback, and may be overpowered by non-weak rules. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Weak, "weak") /** Prints out "weak" before a rule in cflat. */ void Weak::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "weak\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-unstab.texi @defmac unstab b If @var{b} is true (1), rule is allowed to be unstable, as an exception. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Unstab, "unstab") /** Prints out "unstab" before a rule in cflat. */ void Unstab::main(visitor_type& p, const values_type& v) { if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "unstab\t"; } } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-comb.texi @defmac comb b If @var{b} is true (1), use combinational feedback. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Comb, "comb") /** Prints out "comb" before a rule in cflat. */ void Comb::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "comb\t"; } } #else // do nothing yet #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-keeper.texi @defmac keeper b For LVS, If @var{b} is true (1), staticize (explicitly). This attribute will soon be deprecated in favor of a node attribute @t{autokeeper}. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Keeper, "keeper") /** Prints out "keeper" before a rule in cflat. */ void Keeper::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "keeper\t"; } } #else // do nothing yet #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-iskeeper.texi @defmac iskeeper [b] If @var{b} is true (1), flag that this rule is part of a standard keeper. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(IsKeeper, "iskeeper") /** Prints out "iskeeper" before a rule in cflat. */ void IsKeeper::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "iskeeper\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-isckeeper.texi @defmac isckeeper [b] If @var{b} is true (1), flag that this rule is part of a combinational feedback keeper. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(IsCKeeper, "isckeeper") /** Prints out "isckeeper" before a rule in cflat. */ void IsCKeeper::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "ckeeper\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-diode.texi @defmac diode [b] If @var{b} is true (1), flag that this rule generates a diode-connected transistor. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Diode, "diode") /** Prints out "diode" before a rule in cflat. */ void Diode::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "diode\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-res.texi @defmac res [b] If @var{b} is true (1), flag that this rule is a fake resistor. If unspecified, default value is true. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Res, "res") /** Prints out "res" before a rule in cflat. */ void Res::main(visitor_type& p, const values_type& v) { switch (p.cfopts.primary_tool) { case cflat_options::TOOL_PRSIM: // fall-through case cflat_options::TOOL_LVS: { pint_value_type b = 1; if (v.size()) { const pint_const& pi(*v[0].is_a<const pint_const>()); b = pi.static_constant_value(); } if (b) { ostream& o(p.os); o << "res\t"; } break; } default: break; } } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-output.texi @defmac output b If @var{b} is true (1), staticize (explicitly). Q: should this really be a rule-attribute? better off as node-attribute? @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(Output, "output") /** Prints out "comb" before a rule in cflat. */ void Output::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "output\t"; } } #else FINISH_ME(Fang); #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-loadcap.texi @defmac loadcap C Use @var{C} as load capacitance instead of inferring from configuration. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(LoadCap, "loadcap") /** Supposed to attach load to rule's output node? */ void LoadCap::main(visitor_type& p, const values_type& v) { #if 0 if (p.cfopts.primary_tool == cflat_options::TOOL_PRSIM) { // use real-value const pint_const& pi(*v[0].is_a<const pint_const>()); if (pi.static_constant_value()) { ostream& o(p.os); o << "keeper\t"; } } #else FINISH_ME(Fang); #endif } //----------------------------------------------------------------------------- /*** @texinfo prs/attribute-reff.texi @defmac N_reff R @defmacx P_reff R Use @var{R} as effective resistance to override the automatically computed value in other back-end tools. NOTE: This is a hack that should be replaced with a proper implementation of the "fold" expression macro. Consider this attribute deprecated from the start. @end defmac @end texinfo ***/ DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(N_reff, "N_reff") DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS(P_reff, "P_reff") /** Do nothing? */ void N_reff::main(visitor_type& p, const values_type& v) { } void P_reff::main(visitor_type& p, const values_type& v) { } #undef DECLARE_AND_DEFINE_CFLAT_PRS_ATTRIBUTE_CLASS //============================================================================= } // end namespace cflat_rule_attributes //============================================================================= } // end namespace PRS } // end namespace entity } // end namespace HAC DEFAULT_STATIC_TRACE_END
26.427215
79
0.639983
broken-wheel
14ac397aadeb7ee80c45813418617b33e65fe0c8
1,074
cpp
C++
tutorials/developers/tutorial_04gpu/wrapper_tutorial_04gpu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
23
2017-05-03T13:06:34.000Z
2018-06-07T07:12:43.000Z
tutorials/developers/tutorial_04gpu/wrapper_tutorial_04gpu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
2
2017-04-25T08:59:09.000Z
2017-05-11T16:41:55.000Z
tutorials/developers/tutorial_04gpu/wrapper_tutorial_04gpu.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
5
2017-02-16T14:26:40.000Z
2018-05-30T16:49:27.000Z
#include "Halide.h" #include "wrapper_tutorial_04gpu.h" #include <tiramisu/utils.h> #include <cstdlib> #include <iostream> #define NN 100 int main(int, char **) { Halide::Buffer<uint8_t> A_buf(NN, NN); Halide::Buffer<uint8_t> B_buf(NN, NN); // Initialize matrices with pseudorandom values: for (int i = 0; i < NN; i++) { for (int j = 0; j < NN; j++) { A_buf(j, i) = (i + 3) * (j + 1); B_buf(j, i) = (i + 1) * j + 2; } } // Output Halide::Buffer<uint8_t> C1_buf(NN, NN); matmul(A_buf.raw_buffer(), B_buf.raw_buffer(), C1_buf.raw_buffer()); // Reference matrix multiplication Halide::Buffer<uint8_t> C2_buf(NN, NN); init_buffer(C2_buf, (uint8_t)0); for (int i = 0; i < NN; i++) { for (int j = 0; j < NN; j++) { for (int k = 0; k < NN; k++) { // Note that indices are flipped (see tutorial 2) C2_buf(j, i) += A_buf(k, i) * B_buf(j, k); } } } compare_buffers("matmul", C1_buf, C2_buf); return 0; }
24.976744
72
0.527002
akmaru
14af31dd7dbeb0f08817d4103a1a040b59e892d3
310
cpp
C++
class03/stringIO_1.cpp
jeremypedersen/cppZero
69fc8119fdcc8186fee50896ff378a3c55076fa7
[ "Unlicense" ]
null
null
null
class03/stringIO_1.cpp
jeremypedersen/cppZero
69fc8119fdcc8186fee50896ff378a3c55076fa7
[ "Unlicense" ]
null
null
null
class03/stringIO_1.cpp
jeremypedersen/cppZero
69fc8119fdcc8186fee50896ff378a3c55076fa7
[ "Unlicense" ]
null
null
null
// // Code by: Jeremy Pedersen // // Licensed under the BSD 2-clause license (FreeBSD license) // #include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter your name: "; cin >> name; cout << "Hello " << name << endl; return 0; }
15.5
61
0.570968
jeremypedersen
14b1f30932ea11b4f9d351496847f5b7f2da42a5
3,161
hpp
C++
code/src/core/maths/util.hpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
3
2020-04-29T14:55:58.000Z
2020-08-20T08:43:24.000Z
code/src/core/maths/util.hpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
1
2022-03-12T11:37:46.000Z
2022-03-12T20:17:38.000Z
code/src/core/maths/util.hpp
shossjer/fimbulwinter
d894e4bddb5d2e6dc31a8112d245c6a1828604e3
[ "0BSD" ]
null
null
null
#pragma once #include <utility/type_traits.hpp> #include <cstdint> namespace core { namespace maths { template <typename T> struct constant { static const constexpr T pi = T(3.141592653589793238462643383279502884); }; using constantd = constant<double>; using constantf = constant<float>; template <typename T> class degree; template <typename T> class radian; template <typename T> class degree { public: using value_type = T; private: value_type value; public: degree() = default; explicit degree(const value_type value) : value(value) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value && mpl::is_different<U, T>::value>> degree(const degree<U> & degree) : value(degree.get()) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value>> degree(const radian<U> & radian) : value(value_type{radian.get()} / constant<value_type>::pi * value_type{180}) {} public: value_type get() const { return this->value; } public: friend radian<value_type> make_radian(const degree<value_type> & degree) { return radian<value_type>{value_type(degree.value / 180. * constantd::pi)}; } }; template <typename T> degree<T> make_degree(const T value) { return degree<T>{value}; } template <typename T, typename U> degree<T> make_degree(const degree<U> & degree) { return make_degree(T(degree.get())); } using degreef = degree<float>; using degreed = degree<double>; template <typename T> class radian { public: using value_type = T; private: value_type value; public: radian() = default; explicit radian(const value_type value) : value(value) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value && mpl::is_different<U, T>::value>> radian(const radian<U> & radian) : value(radian.get()) {} template <typename U, typename = mpl::enable_if_t<mpl::fits_in<U, T>::value>> radian(const degree<U> & degree) : value(value_type{degree.get()} / value_type{180} * constant<value_type>::pi) {} public: value_type get() const { return this->value; } public: friend degree<value_type> make_degree(const radian<value_type> & radian) { return degree<value_type>{value_type(radian.value / constantd::pi * 180.)}; } }; template <typename T> radian<T> make_radian(const T value) { return radian<T>{value}; } template <typename T, typename U> radian<T> make_radian(const radian<U> & radian) { return make_radian(T(radian.get())); } using radianf = radian<float>; using radiand = radian<double>; inline constexpr int32_t interpolate_and_scale(int32_t min, int32_t max, int32_t x) { const uint32_t q = (2 * ((uint32_t(1) << 31) - 1)) / (uint32_t(max) - min); const uint32_t r = (2 * ((uint32_t(1) << 31) - 1)) % (uint32_t(max) - min); return (uint32_t(x) - min) * q - int32_t((uint32_t(1) << 31) - 1) + r * (uint32_t(x) - min) / (uint32_t(max) - min); } } }
25.699187
119
0.632711
shossjer
14b2618b82efd914bfe32ecdc0225c598ca0603d
439
cpp
C++
LargerString.cpp
Kalaiarasan-Hema/kalai
2e3060727f5a18d4ad85c3f81214805c3ed12f8e
[ "Apache-2.0" ]
null
null
null
LargerString.cpp
Kalaiarasan-Hema/kalai
2e3060727f5a18d4ad85c3f81214805c3ed12f8e
[ "Apache-2.0" ]
null
null
null
LargerString.cpp
Kalaiarasan-Hema/kalai
2e3060727f5a18d4ad85c3f81214805c3ed12f8e
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <iostream> using namespace std; class LargerString { int n,i,a=0; string s1,s2; void get() { cout<<"INPUT"<<endl; getline(cin,s1); getline(cin,s2); } void display() { cout<<"OUTPUT"<<endl; for(i=0;i<n;i++) { if(s1[i]>s2[i]) {cout<<s1;break;} else {cout<<s2;break;} } } public: LargerString() { get(); display(); } }; int main() { LargerString rs; return 0; }
11.864865
25
0.560364
Kalaiarasan-Hema
14b365fcf0c112818dbed3011888703a4ad4bf86
2,650
cpp
C++
winsys/textbox.cpp
fcarreiro/albertum
62d7c63bdcd59efd6aadc139d61c4569fb335544
[ "MIT" ]
null
null
null
winsys/textbox.cpp
fcarreiro/albertum
62d7c63bdcd59efd6aadc139d61c4569fb335544
[ "MIT" ]
null
null
null
winsys/textbox.cpp
fcarreiro/albertum
62d7c63bdcd59efd6aadc139d61c4569fb335544
[ "MIT" ]
null
null
null
#include "stdafx.h" /***********************************************************/ CTextBox::CTextBox() { ispassword=false; maxlen=0; prof=NULL; } CTextBox::~CTextBox() { } /***********************************************************/ bool CTextBox::wm_lbuttondown(int a_x, int a_y) { if(!CWindow::IsVisible()) return true; if( a_x < CWindow::x+CWindow::width+CWindow::parent->GetX() && a_x > CWindow::x+CWindow::parent->GetX() && a_y < CWindow::y+CWindow::height+CWindow::parent->GetY()+15 && a_y > CWindow::y+CWindow::parent->GetY()+15) { BringToTop(); } return true; } bool CTextBox::wm_keydown(char key) { if(!CWindow::IsActive() || !prof) return true; if(key>31) { if(maxlen) { if(CWindow::strCaption.length() >= maxlen) return true; } if(ispassword) { if(CWindow::strCaption.length()*(prof->metrics['*'].abcA+prof->metrics['*'].abcB+prof->metrics['*'].abcC)<width-10) CWindow::strCaption+=key; } else { if(_stringwidth(CWindow::strCaption.c_str(),(ABC*)&prof->metrics)<width-10) CWindow::strCaption+=key; } } else { if(key==8 && CWindow::strCaption.length()>0) CWindow::strCaption.erase(CWindow::strCaption.end()-1); } return true; } /***********************************************************/ bool CTextBox::Render(IDirectDrawSurface7* surface, PROFILE* prof) { RECT r,s; if(!IsVisible()) return true; s.top=0; s.left=81; s.right=120; s.bottom=15; r.top=CWindow::y+CWindow::parent->GetY()+15; r.left=CWindow::x+CWindow::parent->GetX(); r.right=CWindow::x+CWindow::parent->GetX()+CWindow::width; r.bottom=CWindow::y+CWindow::parent->GetY()+CWindow::height+15; back->Blt(&r, prof->sBitmap, &s, DDBLT_WAIT, NULL); if(!CWindow::IsActive()) { s.left+=40; s.right+=40; ++r.top; ++r.left; --r.right; --r.bottom; back->Blt(&r, prof->sBitmap, &s, DDBLT_WAIT, NULL); } else { // agregar cursor al final } if(CWindow::strCaption.length()==0) return true; if(!ispassword) { DXDrawText(CWindow::x+CWindow::parent->GetX()+2, CWindow::y+CWindow::parent->GetY()+17, CWindow::strCaption.c_str(), 12, NULL, CWindow::IsActive() ? 0xFFFFFF : 0x0, prof->fonthandle); } else { std::string asterisks; _fillstring(asterisks, strCaption, '*'); DXDrawText(CWindow::x+CWindow::parent->GetX()+2, CWindow::y+CWindow::parent->GetY()+17, asterisks.c_str(), 12, NULL, CWindow::IsActive() ? 0xFFFFFF : 0x0, prof->fonthandle); } return true; } /***********************************************************/
21.2
119
0.555094
fcarreiro
14b36efe9242e74ac6c6043d90227f4833511f91
5,513
cpp
C++
rviz_default_plugins/src/rviz_default_plugins/displays/pose/pose_display_selection_handler.cpp
romi2002/rviz
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/displays/pose/pose_display_selection_handler.cpp
romi2002/rviz
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/src/rviz_default_plugins/displays/pose/pose_display_selection_handler.cpp
romi2002/rviz
8b2fcc1838e079d0e365894abd7cfd7b255b8d8b
[ "BSD-3-Clause-Clear" ]
1
2020-04-29T07:08:07.000Z
2020-04-29T07:08:07.000Z
/* * Copyright (c) 2008, Willow Garage, Inc. * Copyright (c) 2018, Bosch Software Innovations GmbH. * 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, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "rviz_default_plugins/displays/pose/pose_display_selection_handler.hpp" #ifdef _WIN32 # pragma warning(push) # pragma warning(disable:4996) #endif #include <OgreEntity.h> #ifdef _WIN32 # pragma warning(pop) #endif #include "rviz_rendering/objects/axes.hpp" #include "rviz_rendering/objects/arrow.hpp" #include "rviz_rendering/objects/shape.hpp" #include "rviz_common/interaction/selection_handler.hpp" #include "rviz_common/msg_conversions.hpp" #include "rviz_common/properties/vector_property.hpp" #include "rviz_common/properties/string_property.hpp" #include "rviz_common/properties/quaternion_property.hpp" #include "rviz_common/properties/enum_property.hpp" #include "rviz_common/display_context.hpp" #include "rviz_default_plugins/displays/pose/pose_display.hpp" namespace rviz_default_plugins { namespace displays { PoseDisplaySelectionHandler::PoseDisplaySelectionHandler( PoseDisplay * display, rviz_common::DisplayContext * context) : SelectionHandler(context), display_(display), frame_property_(nullptr), position_property_(nullptr), orientation_property_(nullptr) {} void PoseDisplaySelectionHandler::createProperties( const rviz_common::interaction::Picked & obj, rviz_common::properties::Property * parent_property) { (void) obj; rviz_common::properties::Property * cat = new rviz_common::properties::Property( "Pose " + display_->getName(), QVariant(), "", parent_property); properties_.push_back(cat); frame_property_ = new rviz_common::properties::StringProperty("Frame", "", "", cat); frame_property_->setReadOnly(true); position_property_ = new rviz_common::properties::VectorProperty( "Position", Ogre::Vector3::ZERO, "", cat); position_property_->setReadOnly(true); orientation_property_ = new rviz_common::properties::QuaternionProperty( "Orientation", Ogre::Quaternion::IDENTITY, "", cat); orientation_property_->setReadOnly(true); } rviz_common::interaction::V_AABB PoseDisplaySelectionHandler::getAABBs( const rviz_common::interaction::Picked & obj) { (void) obj; rviz_common::interaction::V_AABB aabbs; if (display_->pose_valid_) { /** with 'derive_world_bounding_box' set to 'true', the WorldBoundingBox is derived each time. setting it to 'false' results in the wire box not properly following the pose arrow, but it would be less computationally expensive. */ bool derive_world_bounding_box = true; if (display_->shape_property_->getOptionInt() == PoseDisplay::Arrow) { aabbs.push_back( display_->arrow_->getHead()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); aabbs.push_back( display_->arrow_->getShaft()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); } else { aabbs.push_back( display_->axes_->getXShape()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); aabbs.push_back( display_->axes_->getYShape()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); aabbs.push_back( display_->axes_->getZShape()->getEntity()->getWorldBoundingBox(derive_world_bounding_box)); } } return aabbs; } void PoseDisplaySelectionHandler::setMessage( geometry_msgs::msg::PoseStamped::ConstSharedPtr message) { // properties_.size() should only be > 0 after createProperties() // and before destroyProperties(), during which frame_property_, // position_property_, and orientation_property_ should be valid // pointers. if (properties_.size() > 0) { frame_property_->setStdString(message->header.frame_id); position_property_->setVector(rviz_common::pointMsgToOgre(message->pose.position)); orientation_property_->setQuaternion( rviz_common::quaternionMsgToOgre(message->pose.orientation)); } } } // namespace displays } // namespace rviz_default_plugins
40.536765
99
0.757482
romi2002
14b3e585a71ec7d513f1f6930eb9f51ae4c61d9c
588
cpp
C++
ch17/17_27.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch17/17_27.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch17/17_27.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
//exercise 17.27 //Write a program that reformats a nine-digit zip code as ddddd-dddd. #include <iostream> #include <regex> #include <string> using namespace std; string pattern = "(\\d{5})([.- ])?(\\d{4})"; string fmt = "$1-$3"; regex r(pattern); string s; int main(int argc, char const *argv[]) { while(getline(cin,s)) { smatch result; regex_search(s,result, r); if(!result.empty()) { cout<<result.format(fmt)<<endl; } else { cout<<"Sorry, No match."<<endl; } } return 0; }
16.333333
69
0.532313
zhang1990215
14b4b82e5c7bb9013ed2f0c01d64096795933733
19,282
tpp
C++
src/math/gradients.tpp
Algomorph/LevelSetFusionExperimentsCPP
f56962f0ad5c62e6706f818062782a2e1660afda
[ "Apache-2.0" ]
8
2019-01-07T14:12:21.000Z
2021-01-12T01:48:03.000Z
src/math/gradients.tpp
Algomorph/LevelSetFusionExperimentsCPP
f56962f0ad5c62e6706f818062782a2e1660afda
[ "Apache-2.0" ]
6
2018-12-19T16:43:33.000Z
2019-06-06T19:50:22.000Z
src/math/gradients.tpp
Algomorph/LevelSetFusionExperimentsCPP
f56962f0ad5c62e6706f818062782a2e1660afda
[ "Apache-2.0" ]
2
2019-01-07T14:12:28.000Z
2019-03-06T06:30:24.000Z
// ================================================================ // Created by Gregory Kramida on 10/26/18. // Copyright (c) 2018 Gregory Kramida // 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. // ================================================================ //local #include "gradients.hpp" #include "typedefs.hpp" namespace math { //region ==================================== LAPLACIAN AUXILIARY FUNCTIONS ============================================ template<typename ElementType> struct LaplaceOperatorFunctor { //same as replicating the prev_row_val to the border and doing (nonborder_value - 2*border_value + border_value) inline static ElementType apply_border_operator(ElementType nonborder_value, ElementType border_value) { return nonborder_value - border_value; } inline static ElementType apply_row_operator(ElementType next_row_val, ElementType row_val, ElementType prev_row_val) { return next_row_val - 2 * row_val + prev_row_val; } inline static ElementType apply_column_operator(ElementType next_col_val, ElementType col_val, ElementType prev_col_val) { return next_col_val - 2 * col_val + prev_col_val; } }; template<typename ElementType> struct NegativeLaplaceOperatorFunctor { //same as replicating the prev_row_val to the border and doing (nonborder_value + 2*border_value - border_value) inline static ElementType apply_border_operator(ElementType nonborder_value, ElementType border_value) { return -nonborder_value + border_value; } inline static ElementType apply_row_operator(ElementType next_row_val, ElementType row_val, ElementType prev_row_val) { return -next_row_val + 2 * row_val - prev_row_val; } inline static ElementType apply_column_operator(ElementType next_col_val, ElementType col_val, ElementType prev_col_val) { return -next_col_val + 2 * col_val - prev_col_val; } }; template<typename ElementType, typename LaplacelikeOperatorFunctor> inline void vector_field_laplacian_2d_aux( const Eigen::Matrix<ElementType,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& field, Eigen::Matrix<ElementType,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& laplacian) { eig::Index column_count = field.cols(); eig::Index row_count = field.rows(); laplacian = math::MatrixXv2f(row_count, column_count); #pragma omp parallel for for (eig::Index i_col = 0; i_col < column_count; i_col++) { ElementType prev_row_val = field(0, i_col); ElementType row_val = field(1, i_col); laplacian(0, i_col) = LaplacelikeOperatorFunctor::apply_border_operator(row_val, prev_row_val); eig::Index i_row; for (i_row = 1; i_row < row_count - 1; i_row++) { ElementType next_row_val = field(i_row + 1, i_col); //previous/next column values will be used later laplacian(i_row, i_col) = LaplacelikeOperatorFunctor::apply_row_operator(next_row_val, row_val, prev_row_val); prev_row_val = row_val; row_val = next_row_val; } laplacian(i_row, i_col) = LaplacelikeOperatorFunctor::apply_border_operator(prev_row_val, row_val); } #pragma omp parallel for for (eig::Index i_row = 0; i_row < row_count; i_row++) { ElementType prev_col_val = field(i_row, 0); ElementType col_val = field(i_row, 1); laplacian(i_row, 0) += LaplacelikeOperatorFunctor::apply_border_operator(col_val, prev_col_val); eig::Index i_col; for (i_col = 1; i_col < column_count - 1; i_col++) { ElementType next_col_val = field(i_row, i_col + 1); laplacian(i_row, i_col) += LaplacelikeOperatorFunctor::apply_column_operator(next_col_val, col_val, prev_col_val); prev_col_val = col_val; col_val = next_col_val; } laplacian(i_row, i_col) += LaplacelikeOperatorFunctor::apply_border_operator(prev_col_val, col_val); } } template<typename ElementType, typename LaplacelikeOperatorFunctor> inline void vector_field_laplacian_3d_aux( Eigen::Tensor<ElementType,3,Eigen::ColMajor>& laplacian, const Eigen::Tensor<ElementType,3,Eigen::ColMajor>& field) { int x_size = field.dimension(0); int y_size = field.dimension(1); int z_size = field.dimension(2); laplacian = Eigen::Tensor<ElementType,3,Eigen::ColMajor>(x_size, y_size, z_size); #pragma omp parallel for for (int z = 0; z < z_size; z++) { for (int y = 0; y < y_size; y++) { ElementType prev_row_val = field(0, y, z); ElementType row_val = field(1, y, z); laplacian(0, y, z) = LaplacelikeOperatorFunctor::apply_border_operator(row_val, prev_row_val); int x; for (x = 1; x < x_size - 1; x++) { ElementType next_row_val = field(x + 1, y, z); //previous/next column values will be used later laplacian(x, y, z) = LaplacelikeOperatorFunctor::apply_row_operator(next_row_val, row_val, prev_row_val); prev_row_val = row_val; row_val = next_row_val; } laplacian(x, y, z) = LaplacelikeOperatorFunctor::apply_border_operator(prev_row_val, row_val); } } #pragma omp parallel for for (int z = 0; z < z_size; z++) { for (int x = 0; x < x_size; x++) { ElementType prev_row_val = field(x, 0, z); ElementType row_val = field(x, 1, z); laplacian(x, 0, z) += LaplacelikeOperatorFunctor::apply_border_operator(row_val, prev_row_val); int y; for (y = 1; y < y_size - 1; y++) { ElementType next_row_val = field(x, y + 1, z); //previous/next column values will be used later laplacian(x, y, z) += LaplacelikeOperatorFunctor::apply_row_operator(next_row_val, row_val, prev_row_val); prev_row_val = row_val; row_val = next_row_val; } laplacian(x, y, z) += LaplacelikeOperatorFunctor::apply_border_operator(prev_row_val, row_val); } } #pragma omp parallel for for (int y = 0; y < y_size; y++) { for (int x = 0; x < x_size; x++) { ElementType prev_row_val = field(x, y, 0); ElementType row_val = field(x, y, 1); laplacian(x, y, 0) += LaplacelikeOperatorFunctor::apply_border_operator(row_val, prev_row_val); int z; for (z = 1; z < z_size - 1; z++) { ElementType next_row_val = field(x, y, z + 1); //previous/next column values will be used later laplacian(x, y, z) += LaplacelikeOperatorFunctor::apply_row_operator(next_row_val, row_val, prev_row_val); prev_row_val = row_val; row_val = next_row_val; } laplacian(x, y, z) += LaplacelikeOperatorFunctor::apply_border_operator(prev_row_val, row_val); } } } //endregion //region ============================================ LAPLACIAN FUNCTIONS ============================================== template<typename Scalar> void laplacian( Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& laplacian, const Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& field) { vector_field_laplacian_2d_aux<math::Vector2<Scalar>, LaplaceOperatorFunctor<math::Vector2<Scalar> > >(field, laplacian); } template<typename Scalar> void negative_laplacian( Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& laplacian, const Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& field){ vector_field_laplacian_2d_aux<math::Vector2<Scalar>, NegativeLaplaceOperatorFunctor<math::Vector2<Scalar> > >(field, laplacian); } template<typename Scalar> void laplacian( Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>& laplacian, const Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>& field) { vector_field_laplacian_3d_aux<math::Vector3<Scalar>, LaplaceOperatorFunctor<math::Vector3<Scalar> > >(laplacian, field); } //endregion //region ========================================= GRADIENT FUNCTIONS ================================================== template<typename Scalar> void gradient( Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& gradient_x, Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& gradient_y, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& field) { eig::Index column_count = field.cols(); eig::Index row_count = field.rows(); gradient_x = eig::MatrixXf(row_count, column_count); gradient_y = eig::MatrixXf(row_count, column_count); #pragma omp parallel for for (eig::Index i_col = 0; i_col < column_count; i_col++) { float prev_row_val = field(0, i_col); float row_val = field(1, i_col); gradient_y(0, i_col) = row_val - prev_row_val; eig::Index i_row; for (i_row = 1; i_row < row_count - 1; i_row++) { float next_row_val = field(i_row + 1, i_col); gradient_y(i_row, i_col) = 0.5 * (next_row_val - prev_row_val); prev_row_val = row_val; row_val = next_row_val; } gradient_y(i_row, i_col) = row_val - prev_row_val; } #pragma omp parallel for for (eig::Index i_row = 0; i_row < row_count; i_row++) { float prev_col_val = field(i_row, 0); float col_val = field(i_row, 1); gradient_x(i_row, 0) = col_val - prev_col_val; eig::Index i_col; for (i_col = 1; i_col < column_count - 1; i_col++) { float next_col_val = field(i_row, i_col + 1); gradient_x(i_row, i_col) = 0.5 * (next_col_val - prev_col_val); prev_col_val = col_val; col_val = next_col_val; } gradient_x(i_row, i_col) = col_val - prev_col_val; } } template<typename Scalar> void gradient( Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& gradient, const Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& field) { eig::Index column_count = field.cols(); eig::Index row_count = field.rows(); gradient = Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>(row_count, column_count); #pragma omp parallel for for (eig::Index i_col = 0; i_col < column_count; i_col++) { float prev_row_val = field(0, i_col); float row_val = field(1, i_col); gradient(0, i_col).y = row_val - prev_row_val; eig::Index i_row; for (i_row = 1; i_row < row_count - 1; i_row++) { float next_row_val = field(i_row + 1, i_col); gradient(i_row, i_col).y = 0.5 * (next_row_val - prev_row_val); prev_row_val = row_val; row_val = next_row_val; } gradient(i_row, i_col).y = row_val - prev_row_val; } #pragma omp parallel for for (eig::Index i_row = 0; i_row < row_count; i_row++) { float prev_col_val = field(i_row, 0); float col_val = field(i_row, 1); gradient(i_row, 0).x = col_val - prev_col_val; eig::Index i_col; for (i_col = 1; i_col < column_count - 1; i_col++) { float next_col_val = field(i_row, i_col + 1); gradient(i_row, i_col).x = 0.5 * (next_col_val - prev_col_val); prev_col_val = col_val; col_val = next_col_val; } gradient(i_row, i_col).x = col_val - prev_col_val; } } template<typename Scalar> void gradient( Eigen::Matrix<math::Matrix2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& gradient, const Eigen::Matrix<math::Vector2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>& field) { eig::Index row_count = field.rows(); eig::Index column_count = field.cols(); gradient = Eigen::Matrix<math::Matrix2<Scalar>,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor>(row_count, column_count); #pragma omp parallel for for (eig::Index i_col = 0; i_col < column_count; i_col++) { math::Vector2<Scalar> prev_row_vector = field(0, i_col); math::Vector2<Scalar> current_row_vector = field(1, i_col); gradient(0, i_col).set_column(1, current_row_vector - prev_row_vector); eig::Index i_row; //traverse each column in vertical (y) direction for (i_row = 1; i_row < row_count - 1; i_row++) { math::Vector2<Scalar> next_row_vector = field(i_row + 1, i_col); gradient(i_row, i_col).set_column(1, 0.5 * (next_row_vector - prev_row_vector)); prev_row_vector = current_row_vector; current_row_vector = next_row_vector; } gradient(i_row, i_col).set_column(1, current_row_vector - prev_row_vector); } #pragma omp parallel for for (eig::Index i_row = 0; i_row < row_count; i_row++) { math::Vector2<Scalar> prev_col_vector = field(i_row, 0); math::Vector2<Scalar> current_col_vector = field(i_row, 1); gradient(i_row, 0).set_column(0, current_col_vector - prev_col_vector); eig::Index i_col; for (i_col = 1; i_col < column_count - 1; i_col++) { math::Vector2<Scalar> next_col_vector = field(i_row, i_col + 1); gradient(i_row, i_col).set_column(0, 0.5 * (next_col_vector - prev_col_vector)); prev_col_vector = current_col_vector; current_col_vector = next_col_vector; } gradient(i_row, i_col).set_column(0, current_col_vector - prev_col_vector); } } template<typename Scalar> void gradient( Eigen::Tensor<math::Matrix3<Scalar>,3,Eigen::ColMajor>& gradient, const Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>& field){ eig::Index size_x = field.dimension(0); eig::Index size_y = field.dimension(1); eig::Index size_z = field.dimension(2); gradient = Eigen::Tensor<math::Matrix3<Scalar>,3,Eigen::ColMajor>(size_x, size_y, size_z); #pragma omp parallel for for (eig::Index z = 0; z < size_z; z++){ for (eig::Index y = 0; y < size_y; y++) { math::Vector3<Scalar> prev_vector = field(0, y, z); math::Vector3<Scalar> current_vector = field(1, y, z); gradient(0, y, z).set_column(0, current_vector - prev_vector); eig::Index x; //traverse each column in vertical (y) direction for (x = 1; x < size_x - 1; x++) { math::Vector3<Scalar> next_vector = field(x + 1, y, z); gradient(x, y, z).set_column(0, 0.5 * (next_vector - prev_vector)); prev_vector = current_vector; current_vector = next_vector; } gradient(x, y, z).set_column(0, current_vector - prev_vector); } } #pragma omp parallel for for (eig::Index z = 0; z < size_z; z++){ for (eig::Index x = 0; x < size_x; x++) { math::Vector3<Scalar> prev_vector = field(x, 0, z); math::Vector3<Scalar> current_vector = field(x, 1, z); gradient(x, 0, z).set_column(1, current_vector - prev_vector); eig::Index y; for (y = 1; y < size_y - 1; y++) { math::Vector3<Scalar> next_vector = field(x, y + 1, z); gradient(x, y, z).set_column(1, 0.5 * (next_vector - prev_vector)); prev_vector = current_vector; current_vector = next_vector; } gradient(x, y, z).set_column(1, current_vector - prev_vector); } } #pragma omp parallel for for (eig::Index y = 0; y < size_y; y++){ for (eig::Index x = 0; x < size_x; x++) { math::Vector3<Scalar> prev_vector = field(x, y, 0); math::Vector3<Scalar> current_vector = field(x, y, 1); gradient(x, y, 0).set_column(2, current_vector - prev_vector); eig::Index z; for (z = 1; z < size_z - 1; z++) { math::Vector3<Scalar> next_vector = field(x, y, z + 1); gradient(x, y, z).set_column(2, 0.5 * (next_vector - prev_vector)); prev_vector = current_vector; current_vector = next_vector; } gradient(x, y, z).set_column(2, current_vector - prev_vector); } } } //TODO: test which gradient method is faster template<typename Scalar> void gradient2( Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>& gradient, const Eigen::Tensor<Scalar,3,Eigen::ColMajor>& field){ gradient = Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>(field.dimensions()); int y_stride = field.dimension(0); int z_stride = y_stride * field.dimension(1); const int x_size = field.dimension(0); const int y_size = field.dimension(1); const int z_size = field.dimension(2); #pragma omp parallel for for (eig::Index i_element = 0; i_element < field.size(); i_element++) { int z_field = i_element / z_stride; int remainder = i_element % z_stride; int y_field = remainder / y_stride; int x_field = remainder % y_stride; //local gradient values float x_grad, y_grad, z_grad; // use forward/backward finite differences for borders, central differences for everything else if (x_field == 0) { x_grad = field(x_field + 1, y_field, z_field) - field(x_field, y_field, z_field); } else if (x_field == x_size - 1) { x_grad = field(x_field, y_field, z_field) - field(x_field - 1, y_field, z_field); } else { x_grad = 0.5 * field(x_field + 1, y_field, z_field) - field(x_field - 1, y_field, z_field); } if (y_field == 0) { y_grad = field(x_field, y_field + 1, z_field) - field(x_field, y_field, z_field); } else if (y_field == y_size - 1) { y_grad = field(x_field, y_field, z_field) - field(x_field, y_field - 1, z_field); } else { y_grad = 0.5 * field(x_field, y_field + 1, z_field) - field(x_field, y_field - 1, z_field); } if (z_field == 0) { z_grad = field(x_field, y_field, z_field + 1) - field(x_field, y_field, z_field); } else if (z_field == z_size - 1) { z_grad = field(x_field, y_field, z_field) - field(x_field, y_field, z_field - 1); } else { z_grad = 0.5 * field(x_field, y_field, z_field + 1) - field(x_field, y_field, z_field - 1); } gradient(i_element) = math::Vector3<Scalar>(x_grad, y_grad, z_grad); } } template<typename Scalar> void gradient( Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>& gradient, const Eigen::Tensor<Scalar,3,Eigen::ColMajor>& field) { gradient = Eigen::Tensor<math::Vector3<Scalar>,3,Eigen::ColMajor>(field.dimensions()); const int x_size = field.dimension(0); const int y_size = field.dimension(1); const int z_size = field.dimension(2); #pragma omp parallel for for (int z = 0; z < z_size; z++) { for (int y = 0; y < y_size; y++) { float preceding_value = field(0, y, z); float current_value = field(1, y, z); gradient(0, y, z).u = current_value - preceding_value; int x; for (x = 1; x < x_size - 1; x++) { float next_value = field(x + 1, y, z); gradient(x, y, z).u = 0.5 * (next_value - preceding_value); preceding_value = current_value; current_value = next_value; } gradient(x, y, z).u = current_value - preceding_value; } } #pragma omp parallel for for (int z = 0; z < z_size; z++) { for (int x = 0; x < x_size; x++) { float preceding_value = field(x, 0, z); float current_value = field(x, 1, z); gradient(x, 0, z).v = current_value - preceding_value; int y; for (y = 1; y < y_size - 1; y++) { float next_value = field(x, y + 1, z); gradient(x, y, z).v = 0.5 * (next_value - preceding_value); preceding_value = current_value; current_value = next_value; } gradient(x, y, z).v = current_value - preceding_value; } } #pragma omp parallel for for (int y = 0; y < y_size; y++) { for (int x = 0; x < x_size; x++) { float preceding_value = field(x, y, 0); float current_value = field(x, y, 1); gradient(x, y, 0).w = current_value - preceding_value; int z; for (z = 1; z < z_size - 1; z++) { float next_value = field(x, y, z + 1); gradient(x, y, z).w = 0.5 * (next_value - preceding_value); preceding_value = current_value; current_value = next_value; } gradient(x, y, z).w = current_value - preceding_value; } } } // endregion } // namespace math
38.718876
120
0.685665
Algomorph
14b888620bbe845ebeb6d46313c059dd5d9b7b1f
2,282
hpp
C++
modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
82
2015-08-15T05:18:30.000Z
2019-04-11T15:18:06.000Z
modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
16
2015-08-13T09:38:34.000Z
2019-05-06T11:28:13.000Z
modules/imgcodecs/src/grfmt_jpeg2000_openjpeg.hpp
artun3e/opencv
524a2fffe96195b906a95b548b0a185d3251eb7e
[ "BSD-3-Clause" ]
86
2015-08-08T08:28:34.000Z
2019-04-18T08:27:22.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2020, Stefan Brüns <stefan.bruens@rwth-aachen.de> #ifndef _GRFMT_OPENJPEG_H_ #define _GRFMT_OPENJPEG_H_ #ifdef HAVE_OPENJPEG #include "grfmt_base.hpp" #include <openjpeg.h> namespace cv { namespace detail { struct OpjStreamDeleter { void operator()(opj_stream_t* stream) const { opj_stream_destroy(stream); } }; struct OpjCodecDeleter { void operator()(opj_codec_t* codec) const { opj_destroy_codec(codec); } }; struct OpjImageDeleter { void operator()(opj_image_t* image) const { opj_image_destroy(image); } }; struct OpjMemoryBuffer { OPJ_BYTE* pos{nullptr}; OPJ_BYTE* begin{nullptr}; OPJ_SIZE_T length{0}; OpjMemoryBuffer() = default; explicit OpjMemoryBuffer(cv::Mat& mat) : pos{ mat.ptr() }, begin{ mat.ptr() }, length{ mat.rows * mat.cols * mat.elemSize() } { } OPJ_SIZE_T availableBytes() const CV_NOEXCEPT { return begin + length - pos; } }; using StreamPtr = std::unique_ptr<opj_stream_t, detail::OpjStreamDeleter>; using CodecPtr = std::unique_ptr<opj_codec_t, detail::OpjCodecDeleter>; using ImagePtr = std::unique_ptr<opj_image_t, detail::OpjImageDeleter>; } // namespace detail class Jpeg2KOpjDecoder CV_FINAL : public BaseImageDecoder { public: Jpeg2KOpjDecoder(); ~Jpeg2KOpjDecoder() CV_OVERRIDE = default; ImageDecoder newDecoder() const CV_OVERRIDE; bool readData( Mat& img ) CV_OVERRIDE; bool readHeader() CV_OVERRIDE; private: detail::StreamPtr stream_{nullptr}; detail::CodecPtr codec_{nullptr}; detail::ImagePtr image_{nullptr}; detail::OpjMemoryBuffer opjBuf_; OPJ_UINT32 m_maxPrec = 0; }; class Jpeg2KOpjEncoder CV_FINAL : public BaseImageEncoder { public: Jpeg2KOpjEncoder(); ~Jpeg2KOpjEncoder() CV_OVERRIDE = default; bool isFormatSupported( int depth ) const CV_OVERRIDE; bool write( const Mat& img, const std::vector<int>& params ) CV_OVERRIDE; ImageEncoder newEncoder() const CV_OVERRIDE; }; } //namespace cv #endif #endif/*_GRFMT_OPENJPEG_H_*/
22.82
94
0.705083
artun3e
14ba48f492acad0e0b28b660d08abb08276c3eaa
37,523
cpp
C++
src/RenderEngine/Particles/CreatorPlugins.cpp
Shimrra/alo-viewer
16fb9ab094e6a93db55199d210b43089fb4f25a0
[ "MIT" ]
11
2017-01-18T08:58:52.000Z
2021-11-12T16:23:28.000Z
src/RenderEngine/Particles/CreatorPlugins.cpp
TheSuperPlayer/alo-viewer
616cb5a330453a50501d730d28c92059b1121651
[ "MIT" ]
2
2020-06-25T01:35:44.000Z
2020-06-25T01:38:44.000Z
src/RenderEngine/Particles/CreatorPlugins.cpp
TheSuperPlayer/alo-viewer
616cb5a330453a50501d730d28c92059b1121651
[ "MIT" ]
6
2017-02-06T18:12:09.000Z
2021-12-24T16:38:34.000Z
#include "RenderEngine/Particles/CreatorPlugins.h" #include "RenderEngine/Particles/ParticleSystem.h" #include "RenderEngine/Particles/PluginDefs.h" #include "RenderEngine/RenderEngine.h" #include "General/Exceptions.h" #include "General/Math.h" #include "General/Log.h" using namespace std; namespace Alamo { static const int ALIGNMENT_NONE = 0; static const int ALIGNMENT_FORWARD = 1; static const int ALIGNMENT_REVERSE = 2; static Matrix MakeAlignmentMatrix(const Vector3& dir) { return Matrix( Quaternion(Vector3(0, 0,1), PI/2) * Quaternion(Vector3(0, 1,0), PI/2 - dir.tilt()) * Quaternion(Vector3(0, 0,1), dir.zAngle()) ); } void PropertyGroup::Read(ChunkReader& reader) { if (reader.group()) { Verify(reader.next() == 1); Read(reader); Verify(reader.next() == -1); return; } m_type = (Type)reader.readInteger(); m_point = reader.readVector3(); m_position = reader.readVector3(); m_magnitude.min = reader.readFloat(); m_magnitude.max = reader.readFloat(); m_radius.min = reader.readFloat(); m_radius.max = reader.readFloat(); m_minPosition = reader.readVector3(); m_maxPosition = reader.readVector3(); m_sphereAngle.min = PI/2 * (1.0f - reader.readFloat()); m_sphereAngle.max = PI/2 * (1.0f - reader.readFloat()); m_sphereRadius.min = reader.readFloat(); m_sphereRadius.max = reader.readFloat(); m_cylRadius = reader.readFloat(); m_cylHeight.min = reader.readFloat(); m_cylHeight.max = reader.readFloat(); m_torusRadius = reader.readFloat(); m_tubeRadius = reader.readFloat(); } Vector3 PropertyGroup::SampleTorus(float torusRadius, float tubeRadius, bool hollow) { float radius = (hollow) ? tubeRadius : GetRandom(0.0f, tubeRadius); float zAngle = GetRandom(0.0f, 2*PI); Vector2 circle(GetRandom(0.0f, 2*PI)); circle.x = circle.x * radius + torusRadius; return Vector3( cos(zAngle) * circle.x, sin(zAngle) * circle.x, circle.y * radius); } Vector3 PropertyGroup::Sample(bool hollow) const { switch (m_type) { case DIRECTION: { float magnitude = (hollow) ? ((GetRandom(0.0f, 1.0f) < 0.5f) ? m_magnitude.min : m_magnitude.max) : GetRandom(m_magnitude.min, m_magnitude.max); return normalize(m_position) * magnitude; } case SPHERE: { float radius = (hollow) ? m_radius.max : GetRandom(m_radius.min, m_radius.max); return Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * radius; } case RANGE: return Vector3( GetRandom(m_minPosition.x, m_maxPosition.x), GetRandom(m_minPosition.y, m_maxPosition.y), GetRandom(m_minPosition.z, m_maxPosition.z) ); case SPHERICAL_RANGE: { float tilt, radius; if (!hollow) { tilt = GetRandom(m_sphereAngle .min, m_sphereAngle .max); radius = GetRandom(m_sphereRadius.min, m_sphereRadius.max); } else switch (GetRandom(0,100) % (m_sphereAngle.min == 0 ? 3 : 4)) { case 0: radius = m_sphereRadius.max; tilt = GetRandom(m_sphereAngle.min, m_sphereAngle.max); break; case 1: radius = m_sphereRadius.min; tilt = GetRandom(m_sphereAngle.min, m_sphereAngle.max); break; case 2: radius = GetRandom(m_sphereRadius.min, m_sphereRadius.max); tilt = m_sphereAngle.max; break; case 3: radius = GetRandom(m_sphereRadius.min, m_sphereRadius.max); tilt = m_sphereAngle.min; break; } float zAngle = GetRandom(0.0f, 2*PI); return Vector3(zAngle, tilt) * radius; } case CYLINDER: { float radius = (hollow) ? m_cylRadius : GetRandom(0.0f, m_cylRadius); return Vector3( Vector2(GetRandom(0.0f, 2*PI)) * radius, GetRandom(m_cylHeight.min, m_cylHeight.max) ); } case TORUS: return SampleTorus(m_torusRadius, m_tubeRadius, hollow); } return m_point; } // // PointCreatorPlugin // void PointCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); END_PARAM_LIST } float PointCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float PointCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long PointCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void PointCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3(0,0,0); p->velocity = Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void PointCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* PointCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void PointCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } PointCreatorPlugin::PointCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // TrailCreatorPlugin // void TrailCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_INT (100, m_parent); END_PARAM_LIST } float TrailCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float TrailCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long TrailCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void TrailCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { assert(parent != NULL); const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3(0,0,0); p->velocity = Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += parent->position; } void TrailCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* TrailCreatorPlugin::Initialize() { ParticleSystem& system = m_emitter.GetSystem(); if (m_parent < system.GetNumEmitters()) { return system.GetEmitter(m_parent).RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_BIRTH); } return NULL; } void TrailCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } TrailCreatorPlugin::TrailCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // SphereCreatorPlugin // void SphereCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_FLOAT(100, m_radius); END_PARAM_LIST } float SphereCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float SphereCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long SphereCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void SphereCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3(GetRandom(0.0f, 2*PI), GetRandom(-PI, PI)) * m_radius; p->velocity = normalize(p->position) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void SphereCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* SphereCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void SphereCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } SphereCreatorPlugin::SphereCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // BoxCreatorPlugin // void BoxCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_FLOAT(100, m_length); PARAM_FLOAT(101, m_width); PARAM_FLOAT(102, m_height); END_PARAM_LIST } float BoxCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float BoxCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long BoxCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void BoxCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = Vector3( GetRandom(-0.5f, 0.5f) * m_length, GetRandom(-0.5f, 0.5f) * m_width, GetRandom(-0.5f, 0.5f) * m_height); p->velocity = normalize(p->position) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void BoxCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* BoxCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void BoxCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } BoxCreatorPlugin::BoxCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // TorusCreatorPlugin // void TorusCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); PARAM_FLOAT(100, m_torusRadius); PARAM_FLOAT(101, m_tubeRadius); END_PARAM_LIST } float TorusCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float TorusCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long TorusCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void TorusCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->position = PropertyGroup::SampleTorus(m_torusRadius, m_tubeRadius, false); p->velocity = normalize(p->position) * speed; p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; p->position += transform.getTranslation(); } void TorusCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* TorusCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void TorusCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } TorusCreatorPlugin::TorusCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // MeshCreatorPlugin // struct MeshCreatorBase::MeshCreatorData { const IRenderObject* m_object; const Model::Mesh* m_mesh; size_t m_subMesh; size_t m_vertex; }; void MeshCreatorBase::InitializeParticle(Particle* p, MeshCreatorData* data) const { p->position = Vector3(0,0,0); if (data->m_mesh != NULL) { const Model::Mesh* mesh = data->m_mesh; MASTER_VERTEX tmp; const MASTER_VERTEX* v = &tmp; switch (m_spawnLocation) { case MESH_ALL_VERTICES: v = &mesh->subMeshes[data->m_subMesh].vertices[data->m_vertex]; // Go to next vertex if (++data->m_vertex == mesh->subMeshes[data->m_subMesh].vertices.size()) { data->m_vertex = 0; data->m_subMesh = (data->m_subMesh + 1) % mesh->subMeshes.size(); } break; case MESH_RANDOM_VERTEX: { // Pick random submesh and vertex int subMesh = GetRandom(0, (int)mesh->subMeshes.size()); int vertex = GetRandom(0, (int)mesh->subMeshes[subMesh].vertices.size()); v = &mesh->subMeshes[subMesh].vertices[vertex]; break; } case MESH_RANDOM_SURFACE: { // Pick random submesh int subMesh = GetRandom(0, (int)mesh->subMeshes.size()); const Model::SubMesh& submesh = mesh->subMeshes[subMesh]; // Pick random face on submesh int face = GetRandom(0, (int)submesh.indices.size() / 3) * 3; const MASTER_VERTEX& v1 = submesh.vertices[submesh.indices[face + 0]]; const MASTER_VERTEX& v2 = submesh.vertices[submesh.indices[face + 1]]; const MASTER_VERTEX& v3 = submesh.vertices[submesh.indices[face + 2]]; // Pick random position on face (barycentric coordinates) float w1 = GetRandom(0.0f, 1.0f); float w2 = GetRandom(0.0f, 1.0f - w1); float w3 = 1.0f - w2 - w1; tmp.Position = v1.Position * w1 + v2.Position * w2 + v3.Position * w3; tmp.Normal = v1.Normal * w1 + v2.Normal * w2 + v3.Normal * w3; break; } } // Initialize particle based on vertex v const Matrix transform = data->m_object->GetBoneTransform(mesh->bone->index); Vector3 normal = Vector4(v->Normal, 0) * transform; Vector3 position = Vector4(v->Position, 1) * transform; p->position = position + normal * m_surfaceOffset; if (m_alignVelocityToNormal) { // Rotate +Z to normal p->velocity = Vector4(p->velocity, 0) * MakeAlignmentMatrix(normal); } } } MeshCreatorBase::MeshCreatorBase() { m_spawnLocation = MESH_RANDOM_SURFACE; m_alignVelocityToNormal = true; m_surfaceOffset = 0.0f; } void MeshCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_FLOAT( 0, m_pps); PARAM_FLOAT( 1, m_speed); PARAM_FLOAT( 2, m_speedVariation); PARAM_FLOAT( 3, m_burstThreshold); PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT( 10, m_DLODFarDistance); END_PARAM_LIST } float MeshCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return max(m_burstThreshold, 1.0f) / m_pps; } float MeshCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } unsigned long MeshCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return (m_burstThreshold >= m_pps) ? (unsigned long)(m_pps * m_burstThreshold) : 1; } void MeshCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); float speed = m_speed; if (m_speedVariation != 0.0f) { speed += GetRandom(-m_speedVariation, m_speedVariation) * m_speed; } p->spawnTime = time; p->velocity = Vector3(0,0,speed); MeshCreatorBase::InitializeParticle(p, (MeshCreatorData*)data); p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; } size_t MeshCreatorPlugin::GetPrivateDataSize() const { return sizeof(MeshCreatorData); } void MeshCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { MeshCreatorData* mcd = (MeshCreatorData*)data; mcd->m_object = object; mcd->m_mesh = mesh; mcd->m_vertex = 0; mcd->m_subMesh = 0; } ParticleSystem::Emitter* MeshCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } void MeshCreatorPlugin::ReadParameters(ChunkReader& reader) { Plugin::ReadParameters(reader); m_speedVariation /= 100.0f; } MeshCreatorPlugin::MeshCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } // // ShapeCreatorPlugin // void ShapeCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); END_PARAM_LIST } float ShapeCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return (m_stopTime == 0 || currentTime < m_stopTime) ? (!m_bursting ? m_spawnInterval / m_particlePerInterval : m_spawnInterval) : -1; } float ShapeCreatorPlugin::GetInitialSpawnDelay(void* data) const { return m_startDelay; } unsigned long ShapeCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return m_bursting ? (unsigned long)m_particlePerInterval : 1; } void ShapeCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); p->spawnTime = time; p->position = Vector4(m_position.Sample(m_hollowPosition), 1) * transform; p->velocity = m_velocity.Sample(m_hollowVelocity); if (m_localVelocity) { p->velocity = Vector4(p->velocity, 0) * transform; } if (parent != NULL) { if (m_inheritVelocity) { float speed = parent->velocity.length(); p->velocity += normalize(parent->velocity) * min(speed * m_inheritedVelocityScale, m_maxInheritedVelocity); } // Add parent position (relative to emitter, otherwise we add emitter twice) p->position += parent->position - transform.getTranslation(); } p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; } void ShapeCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* ShapeCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } ShapeCreatorPlugin::ShapeCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { } ShapeCreatorPlugin::ShapeCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params) : CreatorPlugin(emitter), ShapeCreator(params) { } // // OutwardVelocityShapeCreatorPlugin // void OutwardVelocityShapeCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_BOOL (300, m_outwardSpeed); END_PARAM_LIST } void OutwardVelocityShapeCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); } OutwardVelocityShapeCreatorPlugin::OutwardVelocityShapeCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter) { const string& name = emitter.GetSystem().GetName(); Log::WriteInfo("\"%s\" uses currently partially supported creator plugin", name.c_str()); } // // DeathCreatorPlugin // void DeathCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_CUSTOM(101, m_position); PARAM_BOOL (102, m_hollowPosition); PARAM_CUSTOM(103, m_velocity); PARAM_BOOL (104, m_hollowVelocity); PARAM_BOOL (105, m_localVelocity); PARAM_BOOL (106, m_inheritVelocity); PARAM_FLOAT (107, m_inheritedVelocityScale); PARAM_FLOAT (108, m_maxInheritedVelocity); PARAM_STRING(109, m_parentName); PARAM_INT (110, m_positionAlignment); PARAM_INT (111, m_velocityAlignment); END_PARAM_LIST } float DeathCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return -1; } float DeathCreatorPlugin::GetInitialSpawnDelay(void* data) const { return 0; } void DeathCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { assert(parent != NULL); ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); if (m_positionAlignment != ALIGNMENT_NONE || m_velocityAlignment != ALIGNMENT_NONE) { // Align Z with particle velocity vector if (m_velocityAlignment != ALIGNMENT_NONE) { p->velocity *= MakeAlignmentMatrix( (m_velocityAlignment == ALIGNMENT_REVERSE) ? -parent->velocity : parent->velocity); } if (m_positionAlignment != ALIGNMENT_NONE) { p->position *= MakeAlignmentMatrix( (m_positionAlignment == ALIGNMENT_REVERSE) ? -parent->position : parent->position); } } } ParticleSystem::Emitter* DeathCreatorPlugin::Initialize() { ParticleSystem& system = m_emitter.GetSystem(); if (m_parentEmitter != NULL) { return m_parentEmitter->RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_DEATH); } for (size_t i = 0; i < system.GetNumEmitters(); i++) { ParticleSystem::Emitter& e = system.GetEmitter(i); if (e.GetName() == m_parentName) { return e.RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_DEATH); } } return NULL; } DeathCreatorPlugin::DeathCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter), m_parentEmitter(NULL) { m_spawnInterval = 1.0f; m_bursting = true; m_startDelay = 0.0f; m_stopTime = 0.5f; m_hiresEmission = false; m_burstOnShown = true; } DeathCreatorPlugin::DeathCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params, ParticleSystem::Emitter* parentEmitter) : ShapeCreatorPlugin(emitter, params), m_parentEmitter(parentEmitter), m_positionAlignment(ALIGNMENT_NONE), m_velocityAlignment(ALIGNMENT_NONE) { m_spawnInterval = 1.0f; m_bursting = true; m_startDelay = 0.0f; m_stopTime = 0.5f; m_hiresEmission = false; m_burstOnShown = true; m_inheritVelocity = false; } // // EnhancedTrailCreatorPlugin // void EnhancedTrailCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_STRING(300, m_parentName); PARAM_INT (301, m_positionAlignment); PARAM_INT (302, m_velocityAlignment); END_PARAM_LIST } void EnhancedTrailCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { assert(parent != NULL); ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); if (m_positionAlignment != ALIGNMENT_NONE || m_velocityAlignment != ALIGNMENT_NONE) { // Align Z with particle velocity vector if (m_velocityAlignment != ALIGNMENT_NONE) { p->velocity *= MakeAlignmentMatrix( (m_velocityAlignment == ALIGNMENT_REVERSE) ? -parent->velocity : parent->velocity); } if (m_positionAlignment != ALIGNMENT_NONE) { p->position *= MakeAlignmentMatrix( (m_positionAlignment == ALIGNMENT_REVERSE) ? -parent->position : parent->position); } } } ParticleSystem::Emitter* EnhancedTrailCreatorPlugin::Initialize() { ParticleSystem& system = m_emitter.GetSystem(); if (m_parentEmitter != NULL) { return m_parentEmitter->RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_BIRTH); } for (size_t i = 0; i < system.GetNumEmitters(); i++) { ParticleSystem::Emitter& e = system.GetEmitter(i); if (e.GetName() == m_parentName) { return e.RegisterSpawn(&m_emitter, ParticleSystem::Emitter::SPAWN_BIRTH); } } return NULL; } EnhancedTrailCreatorPlugin::EnhancedTrailCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter), m_parentEmitter(NULL) { } EnhancedTrailCreatorPlugin::EnhancedTrailCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params, ParticleSystem::Emitter* parentEmitter) : ShapeCreatorPlugin(emitter, params), m_parentEmitter(parentEmitter), m_positionAlignment(ALIGNMENT_NONE), m_velocityAlignment(ALIGNMENT_NONE) { } // // EnhancedMeshCreatorPlugin // void EnhancedMeshCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_INT (105, m_spawnLocation); PARAM_BOOL (106, m_alignVelocityToNormal); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_FLOAT (200, m_surfaceOffset); END_PARAM_LIST } size_t EnhancedMeshCreatorPlugin::GetPrivateDataSize() const { return sizeof(MeshCreatorData); } unsigned long EnhancedMeshCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { MeshCreatorData* mcd = (MeshCreatorData*)data; unsigned long base = (mcd->m_mesh != NULL && m_spawnLocation == MESH_ALL_VERTICES ? (unsigned long)mcd->m_mesh->nVertices : 1); return base * ShapeCreatorPlugin::GetNumParticlesPerSpawn(data); } void EnhancedMeshCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { const Matrix& transform = p->emitter->GetTransform(); p->spawnTime = time; p->velocity = m_velocity.Sample(m_hollowVelocity); if (m_localVelocity) { p->velocity = Vector4(p->velocity, 0) * transform; } MeshCreatorBase::InitializeParticle(p, (MeshCreatorData*)data); p->acceleration = Vector3(0,0,0); p->texCoords = Vector4(0,0,1,1); p->size = 1.0f; p->color = Color(0.1f, 1.0f, 0.5f, 1.0f); p->rotation = 0.0f; } void EnhancedMeshCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { MeshCreatorData* mcd = (MeshCreatorData*)data; mcd->m_object = object; mcd->m_mesh = mesh; mcd->m_vertex = 0; mcd->m_subMesh = 0; } EnhancedMeshCreatorPlugin::EnhancedMeshCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter) { m_position.m_type = PropertyGroup::POINT; m_position.m_point = Vector3(0,0,0); m_hollowPosition = false; } EnhancedMeshCreatorPlugin::EnhancedMeshCreatorPlugin(ParticleSystem::Emitter& emitter, const ShapeCreator& params, unsigned long spawnLocation, float surfaceOffset) : ShapeCreatorPlugin(emitter, params) { m_spawnLocation = spawnLocation; m_surfaceOffset = surfaceOffset; m_alignVelocityToNormal = true; } // // HardwareSpawnerCreatorPlugin // void HardwareSpawnerCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (6000, m_particleCount); PARAM_FLOAT (6001, m_particleLifetime); PARAM_BOOL (6002, m_enableBursting); PARAM_CUSTOM(6003, m_position); PARAM_BOOL (6004, m_hollowPosition); PARAM_CUSTOM(6005, m_velocity); PARAM_BOOL (6006, m_hollowVelocity); PARAM_FLOAT3(6007, m_acceleration); PARAM_FLOAT (6008, m_attractAcceleration); PARAM_FLOAT3(6009, m_vortexAxis); PARAM_FLOAT (6010, m_vortexRotation); PARAM_FLOAT (6011, m_vortexAttraction); END_PARAM_LIST } float HardwareSpawnerCreatorPlugin::GetSpawnDelay(void* data, float currentTime) const { return -1; } float HardwareSpawnerCreatorPlugin::GetInitialSpawnDelay(void* data) const { return -1; } unsigned long HardwareSpawnerCreatorPlugin::GetNumParticlesPerSpawn(void* data) const { return 0; } void HardwareSpawnerCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { } void HardwareSpawnerCreatorPlugin::InitializeInstance(void* data, IRenderObject* object, const Model::Mesh* mesh) const { } ParticleSystem::Emitter* HardwareSpawnerCreatorPlugin::Initialize() { return m_emitter.GetSystem().RegisterSpawn(&m_emitter); } HardwareSpawnerCreatorPlugin::HardwareSpawnerCreatorPlugin(ParticleSystem::Emitter& emitter) : CreatorPlugin(emitter) { const string& name = emitter.GetSystem().GetName(); Log::WriteInfo("\"%s\" uses currently unsupported creator plugin", name.c_str()); } // // AlignedShapeCreatorPlugin // void AlignedShapeCreatorPlugin::CheckParameter(int id) { BEGIN_PARAM_LIST(id) PARAM_INT ( 4, m_globalLOD); PARAM_FLOAT( 6, m_preSimulateSeconds); PARAM_BOOL ( 7, m_autoUpdatePositions); PARAM_FLOAT( 8, m_minDLOD); PARAM_FLOAT( 9, m_DLODNearDistance); PARAM_FLOAT(10, m_DLODFarDistance); PARAM_FLOAT (100, m_particlePerInterval); PARAM_FLOAT (101, m_spawnInterval); PARAM_BOOL (102, m_bursting); PARAM_FLOAT (103, m_startDelay); PARAM_FLOAT (104, m_stopTime); PARAM_CUSTOM(105, m_position); PARAM_BOOL (106, m_hollowPosition); PARAM_CUSTOM(107, m_velocity); PARAM_BOOL (108, m_hollowVelocity); PARAM_BOOL (109, m_localVelocity); PARAM_BOOL (110, m_inheritVelocity); PARAM_FLOAT (111, m_inheritedVelocityScale); PARAM_FLOAT (112, m_maxInheritedVelocity); PARAM_BOOL (113, m_hiresEmission); PARAM_BOOL (114, m_burstOnShown); PARAM_INT (200, m_positionAlignmentDirection); PARAM_INT (201, m_positionAlignment); PARAM_INT (202, m_velocityAlignmentDirection); PARAM_INT (203, m_velocityAlignment); PARAM_STRING(204, m_bone); END_PARAM_LIST } void AlignedShapeCreatorPlugin::InitializeParticle(Particle* p, void* data, const Particle* parent, float time) const { ShapeCreatorPlugin::InitializeParticle(p, data, parent, time); } AlignedShapeCreatorPlugin::AlignedShapeCreatorPlugin(ParticleSystem::Emitter& emitter) : ShapeCreatorPlugin(emitter) { const string& name = emitter.GetSystem().GetName(); Log::WriteInfo("\"%s\" uses currently partially supported creator plugin", name.c_str()); } }
31.295246
156
0.677451
Shimrra
14be001cf3118bccaf3497cd6e40aefc040febf4
10,685
cpp
C++
lib/src/EBAMRTools/EBCoarToCoarRedist.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
10
2018-02-01T20:57:36.000Z
2022-03-17T02:57:49.000Z
lib/src/EBAMRTools/EBCoarToCoarRedist.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
19
2018-10-04T21:37:18.000Z
2022-02-25T16:20:11.000Z
lib/src/EBAMRTools/EBCoarToCoarRedist.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
11
2019-01-12T23:33:32.000Z
2021-08-09T15:19:50.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "EBCoarToCoarRedist.H" #include "LayoutIterator.H" #include "BaseIVFactory.H" #include "VoFIterator.H" #include "EBCellFactory.H" #include "CH_Timer.H" #include "NamespaceHeader.H" /***********************/ /***********************/ void EBCoarToCoarRedist:: resetWeights(const LevelData<EBCellFAB>& a_modifier, const int& a_ivar) { CH_TIME("EBCoarToCoarRedist::resetWeights"); CH_assert(isDefined()); Interval srcInterv(a_ivar, a_ivar); Interval dstInterv(0,0); a_modifier.copyTo(srcInterv, m_densityCoar, dstInterv); //set the weights to mass weighting if the modifier //is the coarse density. for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { const IntVectSet& coarSet = m_setsCoar[dit()]; BaseIVFAB<VoFStencil>& massStenFAB = m_stenCoar[dit()]; const BaseIVFAB<VoFStencil>& volStenFAB = m_volumeStenc[dit()]; const BaseIVFAB<VoFStencil>& stanStenFAB = m_standardStenc[dit()]; const EBISBox& ebisBox = m_ebislCoar[dit()]; const EBCellFAB& modFAB = m_densityCoar[dit()]; for (VoFIterator vofit(coarSet, ebisBox.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& thisVoF = vofit(); VoFStencil stanSten = stanStenFAB(thisVoF, 0); VoFStencil oldSten = volStenFAB(thisVoF, 0); VoFStencil newSten; for (int isten = 0; isten < oldSten.size(); isten++) { const VolIndex& thatVoF = oldSten.vof(isten); Real weight =modFAB(thatVoF, a_ivar); newSten.add(thatVoF, weight); } //need normalize by the whole standard stencil Real sum = 0.0; for (int isten = 0; isten < stanSten.size(); isten++) { const VolIndex& thatVoF = stanSten.vof(isten); Real weight = modFAB(thatVoF, 0); Real volfrac = ebisBox.volFrac(thatVoF); //it is weight*volfrac that is normalized sum += weight*volfrac; } if (Abs(sum) > 0.0) { Real scaling = 1.0/sum; newSten *= scaling; } massStenFAB(thisVoF, 0) = newSten; } } } /**********************/ EBCoarToCoarRedist:: EBCoarToCoarRedist() { m_isDefined = false; } /**********************/ EBCoarToCoarRedist:: ~EBCoarToCoarRedist() { } /**********************/ void EBCoarToCoarRedist:: define(const DisjointBoxLayout& a_dblFine, const DisjointBoxLayout& a_dblCoar, const EBISLayout& a_ebislCoar, const Box& a_domainCoar, const int& a_nref, const int& a_nvar, int a_redistRad) { CH_TIME("EBCoarToCoarRedist::define"); m_isDefined = true; m_nComp = a_nvar; m_refRat = a_nref; m_domainCoar = a_domainCoar; m_gridsCoar = a_dblCoar; m_ebislCoar = a_ebislCoar; m_redistRad = a_redistRad; //define the intvectsets over which the objects live m_setsCoar.define(m_gridsCoar); m_stenCoar.define(m_gridsCoar); m_volumeStenc.define(m_gridsCoar); m_standardStenc.define(m_gridsCoar); //make sets for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { Box gridBox = m_gridsCoar.get(dit()); gridBox.grow(a_redistRad); gridBox &= m_domainCoar; //find the complement of what we really want IntVectSet ivsComplement(gridBox); for (LayoutIterator litFine = a_dblFine.layoutIterator(); litFine.ok(); ++litFine) { Box projBox = coarsen(a_dblFine.get(litFine()), m_refRat); ivsComplement -= projBox; } //now the set we want is the gridbox - complement IntVectSet& coarSet = m_setsCoar[dit()]; coarSet = IntVectSet(gridBox); coarSet -= ivsComplement; IntVectSet irregIVS = m_ebislCoar[dit()].getIrregIVS(gridBox); coarSet &= irregIVS; } defineDataHolders(); //initialize the buffers to zero setToZero(); } /**********************/ void EBCoarToCoarRedist:: define(const EBLevelGrid& a_eblgFine, const EBLevelGrid& a_eblgCoar, const int& a_nref, const int& a_nvar, const int& a_redistRad) { CH_TIME("EBCoarToCoarRedist::define"); m_isDefined = true; m_nComp = a_nvar; m_refRat = a_nref; m_redistRad = a_redistRad; m_domainCoar= a_eblgCoar.getDomain().domainBox(); m_gridsCoar = a_eblgCoar.getDBL(); m_ebislCoar = a_eblgCoar.getEBISL(); //define the intvectsets over which the objects live //make sets. m_setsCoar.define(m_gridsCoar); //need the set of points under the fine grid that //will redistribute to this box IntVectSet coveringIVS = a_eblgFine.getCoveringIVS(); coveringIVS.coarsen(m_refRat); for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { Box gridBox = m_gridsCoar.get(dit()); gridBox.grow(a_redistRad); gridBox &= m_domainCoar; m_setsCoar[dit()] = m_ebislCoar[dit()].getIrregIVS(gridBox); m_setsCoar[dit()] &= coveringIVS; } defineDataHolders(); //initialize the buffers to zero setToZero(); } /***/ void EBCoarToCoarRedist:: defineDataHolders() { CH_TIME("EBCoarToCoarRedist::defineDataHolders"); EBCellFactory ebcellfactcoar(m_ebislCoar); m_densityCoar.define(m_gridsCoar, 1, 2*m_redistRad*IntVect::Unit, ebcellfactcoar); m_stenCoar.define(m_gridsCoar); m_volumeStenc.define(m_gridsCoar); m_standardStenc.define(m_gridsCoar); RedistStencil rdStenCoar(m_gridsCoar, m_ebislCoar, m_domainCoar, m_redistRad); for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { BaseIVFAB<VoFStencil>& stenFAB = m_stenCoar[dit()]; BaseIVFAB<VoFStencil>& volStenFAB = m_volumeStenc[dit()]; BaseIVFAB<VoFStencil>& stanStenFAB = m_standardStenc[dit()]; const EBISBox& ebisBox = m_ebislCoar[dit()]; const IntVectSet& ivs = m_setsCoar[dit()]; const BaseIVFAB<VoFStencil>& rdStenFAB = rdStenCoar[dit()]; const Box& gridCoar = m_gridsCoar.get(dit()); stenFAB.define( ivs, ebisBox.getEBGraph(), 1); volStenFAB.define( ivs, ebisBox.getEBGraph(), 1); stanStenFAB.define(ivs, ebisBox.getEBGraph(), 1); for (VoFIterator vofit(ivs, ebisBox.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& srcVoF = vofit(); VoFStencil newStencil; const VoFStencil& stanSten = rdStenFAB(srcVoF, 0); for (int istan = 0; istan < stanSten.size(); istan++) { const VolIndex& dstVoF = stanSten.vof(istan); const Real& weight = stanSten.weight(istan); if (gridCoar.contains(dstVoF.gridIndex())) { newStencil.add(dstVoF, weight); } } //set both to volume weighted. can be changed later stenFAB(srcVoF, 0) = newStencil; volStenFAB(srcVoF, 0) = newStencil; stanStenFAB(srcVoF, 0) = stanSten; } } BaseIVFactory<Real> factCoar(m_ebislCoar, m_setsCoar); IntVect ivghost = m_redistRad*IntVect::Unit; m_regsCoar.define(m_gridsCoar, m_nComp, ivghost, factCoar); } /**********************/ void EBCoarToCoarRedist:: setToZero() { CH_TIME("EBCoarToCoarRedist::setToZero"); for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { m_regsCoar[dit()].setVal(0.0); } } /**********************/ void EBCoarToCoarRedist:: increment(const BaseIVFAB<Real>& a_coarMass, const DataIndex& a_coarDataIndex, const Interval& a_variables) { CH_TIME("EBCoarToCoarRedist::increment"); BaseIVFAB<Real>& coarBuf = m_regsCoar[a_coarDataIndex]; const EBISBox& ebisBox = m_ebislCoar[a_coarDataIndex]; const Box& gridBox = m_gridsCoar.get(a_coarDataIndex); IntVectSet ivs = ebisBox.getIrregIVS(gridBox); const IntVectSet& fabIVS = a_coarMass.getIVS(); const IntVectSet& bufIVS = m_setsCoar[a_coarDataIndex]; CH_assert(fabIVS.contains(ivs)); //only a subset of our points are in the set (only the ones covered by finer grids). ivs &= bufIVS; for (VoFIterator vofit(ivs, ebisBox.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& vof = vofit(); for (int ivar = a_variables.begin(); ivar <= a_variables.end(); ivar++) { coarBuf(vof, ivar) += a_coarMass(vof, ivar); } } } /**********************/ void EBCoarToCoarRedist:: redistribute(LevelData<EBCellFAB>& a_coarSolution, const Interval& a_variables) { CH_TIME("EBCoarToCoarRedist::redistribute"); m_regsCoar.exchange(a_variables); //at all points in the buffer, subtract off the redistributed values for (DataIterator dit = m_gridsCoar.dataIterator(); dit.ok(); ++dit) { const BaseIVFAB<Real>& regCoar = m_regsCoar[dit()]; const IntVectSet& ivsCoar = m_setsCoar[dit()]; const EBISBox& ebisBoxCoar = m_ebislCoar[dit()]; const BaseIVFAB<VoFStencil>& stenFAB = m_stenCoar[dit()]; const Box& coarBox = m_gridsCoar.get(dit()); EBCellFAB& solFAB = a_coarSolution[dit()]; for (VoFIterator vofit(ivsCoar,ebisBoxCoar.getEBGraph()); vofit.ok(); ++vofit) { const VolIndex& srcVoF = vofit(); const VoFStencil& vofsten = stenFAB(srcVoF, 0); for (int isten = 0; isten < vofsten.size(); isten++) { const Real& weight = vofsten.weight(isten); const VolIndex& dstVoF = vofsten.vof(isten); //since we are just using the input redist stencil, //have to check if out of bounds if (coarBox.contains(dstVoF.gridIndex())) { for (int ivar = a_variables.begin(); ivar <= a_variables.end(); ivar++) { Real dmFine = regCoar(srcVoF, ivar); //ucoar+= massfine/volcoar, ie. //ucoar+= (wcoar*dmCoar*volFracfine/volfraccoar)=massfine/volcoar Real dUCoar = dmFine*weight; //SUBTRACTING because this is re-redistribution. solFAB(dstVoF, ivar) -= dUCoar; } } } } } } /**********************/ bool EBCoarToCoarRedist:: isDefined() const { return m_isDefined; } /**********************/ #include "NamespaceFooter.H"
32.776074
87
0.611418
rmrsk
14c023b1f14cb5937e594eaa32b8870fdd3cf503
5,458
cpp
C++
D3D12_ModelAnimation/asdx/src/formats/asdxResMAT.cpp
ProjectAsura/D3D12Samples
f4756807106e998ec2de7621fdd9125582859ae9
[ "MIT" ]
12
2016-11-03T08:38:57.000Z
2022-02-19T01:31:22.000Z
D3D12_ModelAnimation/asdx/src/formats/asdxResMAT.cpp
ProjectAsura/D3D12Samples
f4756807106e998ec2de7621fdd9125582859ae9
[ "MIT" ]
null
null
null
D3D12_ModelAnimation/asdx/src/formats/asdxResMAT.cpp
ProjectAsura/D3D12Samples
f4756807106e998ec2de7621fdd9125582859ae9
[ "MIT" ]
13
2017-05-15T12:34:50.000Z
2021-11-30T13:28:04.000Z
//------------------------------------------------------------------------------------------------- // File : asdxResMAT.cpp // Desc : Project Asura MaterialSet Data Format (*.mts) Loader // Copyright(c) Project Asura. All right reserved. //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- // Includes //------------------------------------------------------------------------------------------------- #include <asdxLogger.h> #include "asdxResMAT.h" namespace /* anonymous */ { //------------------------------------------------------------------------------------------------- // Constant Values. //------------------------------------------------------------------------------------------------- static constexpr u32 MAT_VERSION = 0x000001; /////////////////////////////////////////////////////////////////////////////////////////////////// // MAT_FILE_HEADER structure /////////////////////////////////////////////////////////////////////////////////////////////////// struct MAT_FILE_HEADER { u8 Magic[4]; //!< マジックです. 'M', 'A', 'T', '\0' u32 Version; //!< ファイルバージョンです. }; /////////////////////////////////////////////////////////////////////////////////////////////////// // MAT_FILE_PATH structure /////////////////////////////////////////////////////////////////////////////////////////////////// struct MAT_FILE_PATH { char16 Path[256]; //!< パス名です. }; /////////////////////////////////////////////////////////////////////////////////////////////////// // MAT_MATERIAL structure /////////////////////////////////////////////////////////////////////////////////////////////////// struct MAT_MATERIAL { u32 PathCount; //!< テクスチャ数です. u32 PhongCount; //!< Phong BRDF 数です. u32 DisneyCount; //!< Disney BRDF 数です. }; } // namespace /* anonymous */ namespace asdx { //------------------------------------------------------------------------------------------------- // MATファイルからマテリアルリソースを読み込みます. //------------------------------------------------------------------------------------------------- bool LoadResMaterialFromMAT( const char16* filename, ResMaterial* pResult ) { if ( filename == nullptr || pResult == nullptr ) { ELOG( "Error : Invalid Argument." ); return false; } FILE* pFile; auto err = _wfopen_s( &pFile, filename, L"rb" ); if ( err != 0 ) { ELOG( "Error : File Open Failed. filename = %s", filename ); return false; } MAT_FILE_HEADER header; fread( &header, sizeof(header), 1, pFile ); if ( header.Magic[0] != 'M' || header.Magic[1] != 'A' || header.Magic[2] != 'T' || header.Magic[3] != '\0' ) { ELOG( "Error : Invalid File." ); fclose( pFile ); return false; } if ( header.Version != MAT_VERSION ) { ELOG( "Error : Invalid File Version." ); fclose( pFile ); return false; } MAT_MATERIAL material; fread( &material, sizeof(material), 1, pFile ); (*pResult).Paths .resize( material.PathCount ); (*pResult).Phong .resize( material.PhongCount ); (*pResult).Disney.resize( material.DisneyCount ); for( u32 i=0; i<material.PathCount; ++i ) { MAT_FILE_PATH texture; fread( &texture, sizeof(texture), 1, pFile ); (*pResult).Paths[i] = texture.Path; } for( u32 i=0; i<material.PhongCount; ++i ) { fread( &(*pResult).Phong[i], sizeof(ResPhong), 1, pFile ); } for( u32 i=0; i<material.DisneyCount; ++i ) { fread( &(*pResult).Disney[i], sizeof(ResDisney), 1, pFile ); } fclose( pFile ); return true; } //------------------------------------------------------------------------------------------------- // MATファイルに保存します. //------------------------------------------------------------------------------------------------- bool SaveResMaterialToMAT( const char16* filename, const ResMaterial* pMaterial ) { if ( filename == nullptr || pMaterial == nullptr ) { ELOG( "Error : Invalid Argument."); return false; } FILE* pFile; auto err = _wfopen_s( &pFile, filename, L"wb" ); if ( err != 0 ) { ELOG( "Error : File Open Failed." ); return false; } MAT_FILE_HEADER header; header.Magic[0] = 'M'; header.Magic[1] = 'A'; header.Magic[2] = 'T'; header.Magic[3] = '\0'; header.Version = MAT_VERSION; fwrite( &header, sizeof(header), 1, pFile ); MAT_MATERIAL material = {}; material.PathCount = static_cast<u32>( pMaterial->Paths.size() ); material.PhongCount = static_cast<u32>( pMaterial->Phong.size() ); material.DisneyCount = static_cast<u32>( pMaterial->Disney.size() ); fwrite( &material, sizeof(material), 1, pFile ); for( u32 i=0; i<material.PathCount; ++i ) { MAT_FILE_PATH texture = {}; wcscpy_s( texture.Path, pMaterial->Paths[i].c_str() ); fwrite( &texture, sizeof(texture), 1, pFile ); } for( u32 i=0; i<material.PhongCount; ++i ) { fwrite( &pMaterial->Phong[i], sizeof(ResPhong), 1, pFile ); } for( u32 i=0; i<material.DisneyCount; ++i ) { fwrite( &pMaterial->Disney[i], sizeof(ResDisney), 1, pFile ); } fclose( pFile ); return true; } } // namespace asdx
32.295858
100
0.411689
ProjectAsura
14c1aca82b13408a9064e316ec3a4375af729e78
663
cpp
C++
modules/ide_old/src/OptionPage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/OptionPage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
modules/ide_old/src/OptionPage_1.cpp
DeepBlue14/rqt_ide
853964dc429d61c9afb6f1fe827f2e3e83f92713
[ "MIT" ]
null
null
null
#include "OptionPage_1.h" OptionPage_1::OptionPage_1(QWidget* parent) : QWidget(parent) { cssFileStrLstPtr = new QStringList(); cssFileLstWigPtr = new QListWidget(); scanForCssFiles(); outerLayout = new QGridLayout(); outerLayout->addWidget(cssFileLstWigPtr, 0, 0, Qt::AlignCenter); this->setLayout(outerLayout); } QStringList* OptionPage_1::scanForCssFiles() { QDir qssDir("./src/qss"); *cssFileStrLstPtr = qssDir.entryList(QDir::Files/*, sort*/); initCssOptionLstWig(); } void OptionPage_1::initCssOptionLstWig() { cssFileLstWigPtr->addItems(*cssFileStrLstPtr); } OptionPage_1::~OptionPage_1() { ; }
19.5
68
0.695324
DeepBlue14
14c2382a6fdefe166dc70b0171111b92fea69f8d
5,313
cpp
C++
GenesisSandbox/src/Layers/Sandbox2D.cpp
ivanchotom/Genesis
1e5536575bb85f38eb20c96a1ac6c8b2a026386b
[ "Apache-2.0" ]
1
2021-01-07T14:33:22.000Z
2021-01-07T14:33:22.000Z
GenesisSandbox/src/Layers/Sandbox2D.cpp
ivanchotom/Genesis
1e5536575bb85f38eb20c96a1ac6c8b2a026386b
[ "Apache-2.0" ]
null
null
null
GenesisSandbox/src/Layers/Sandbox2D.cpp
ivanchotom/Genesis
1e5536575bb85f38eb20c96a1ac6c8b2a026386b
[ "Apache-2.0" ]
null
null
null
#include "Sandbox2D.h" #include "ImGui/imgui.h" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtc/type_ptr.hpp" #include <chrono> static const uint32_t s_MapWidth = 24; static const char* s_MapTiles = "WWWWWWWWWWWWWWWWWWWWWWWW" "WWWWWWWWDDDDDWWWWWWWWWWW" "WWWWWDDDDDDDDDDDDWWWWWWW" "WWWWDDDDDDDDDDWWWDDDWWWW" "WWWWWDDDDDDDDDDDDDDWWWWW" "WWWWDDDDDDDDDDDDDDDWWWWW" "WWWWWDDDWWWDDDDDDDWWWWWW" "WWWWWDDDDDDDDDDDDDDWWWWW" "WWWWWDDDDDDDWWWWDDDWWWWW" "WWWWWWWDDDDDDDDDDWWWWWWW" "WWWWWWWWWDDDDDDWWWWWWWWW" "WWWWWWWWWWWDDDWWWWWWWWWW" "WWWWWWWWWWWWWWWWWWWWWWWW" "WWWWWWWWWWWWWWWWWWWWWWWW" ; Sandbox2D::Sandbox2D() : Layer("Sandbox2D"), m_CameraController(1280.0f / 720.0f, true) { } void Sandbox2D::OnAttach() { GS_PROFILE_FUNCTION(); m_CheckerboardTexture = GE::Texture2D::Create("assets/textures/Checkerboard.png"); m_SpriteSheet = GE::Texture2D::Create("assets/kenney/rpg/Spritesheet/RPGpack_sheet_2X.png"); m_TextureBarrel = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 1, 11 }, { 128, 128 }); m_TextureTree = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 2, 1 }, { 128, 128 }, {1, 2}); m_MapWidth = s_MapWidth; m_MapHeight = strlen(s_MapTiles) / s_MapWidth; s_TextureMap['W'] = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 11, 11 }, { 128, 128 }); s_TextureMap['D'] = GE::SubTexture2D::CreateFromCoords(m_SpriteSheet, { 6, 11 }, {128, 128} ); // Particle m_Particle.ColorBegin = { 254 / 255.0f, 212 / 255.0f, 123 / 255.0f, 1.0f }; m_Particle.ColorEnd = { 254 / 255.0f, 109 / 255.0f, 41 / 255.0f, 1.0f }; m_Particle.SizeBegin = 0.5f, m_Particle.SizeVariation = 0.3f, m_Particle.SizeEnd = 0.0f; m_Particle.LifeTime = 5.0f; m_Particle.Velocity = { 0.0f, 0.0f }; m_Particle.VelocityVariation = { 3.0f, 1.0f }; m_Particle.Position = { 0.0f, 0.0f }; m_CameraController.SetZoomLevel(5.0f); } void Sandbox2D::OnDetach() { GS_PROFILE_FUNCTION(); } void Sandbox2D::OnUpdate(GE::Timestep ts) { GS_PROFILE_FUNCTION(); //Update m_CameraController.OnUpdate(ts); //Render Prep GE::Renderer2D::ResetStats(); { GS_PROFILE_SCOPE("Renderer Prep"); GE::RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 }); GE::RenderCommand::Clear(); } #if OLD_PATH //Render Draw { static float rotation = 0.0f; rotation += ts * 50.0f; GS_PROFILE_SCOPE("Renderer Draw"); GE::Renderer2D::BeginScene(m_CameraController.GetCamera()); GE::Renderer2D::DrawRotatedQuad({ 1.0f, 0.0f }, { 0.8f, 0.8f }, glm::radians(-45.0f), { 0.8f, 0.2f, 0.3f, 1.0f }); GE::Renderer2D::DrawQuad({ -1.0f, 0.0f }, { 0.8f, 0.8f }, { 0.8f, 0.2f, 0.3f, 1.0f }); GE::Renderer2D::DrawQuad({ 0.5f, -0.5f }, { 0.5f, 0.75f }, { 0.2f, 0.3f, 0.8f, 1.0f }); GE::Renderer2D::DrawQuad({ 0.0f, 0.0f, -0.1f}, { 20.0f, 20.0f }, m_CheckerboardTexture, 10.0f); GE::Renderer2D::DrawRotatedQuad({ -2.0f, 0.0f, 0.0f }, { 1.0f, 1.0f }, glm::radians(rotation) , m_CheckerboardTexture, 20.0f); GE::Renderer2D::EndScene(); GE::Renderer2D::BeginScene(m_CameraController.GetCamera()); for (float y = -5.0; y < 5.0f; y += 0.5f) { for (float x = -5.0; x < 5.0f; x += 0.5f) { glm::vec4 color = { (x + 5.0f) / 10.0f, 0.4f, (y + 5.0f) / 10.0f, 0.7f }; GE::Renderer2D::DrawQuad({x, y}, { 0.45f, 0.45f }, color); } } GE::Renderer2D::EndScene(); } #endif if (GE::Input::IsMouseButtonPressed(GE_MOUSE_BUTTON_LEFT)) { auto [x, y] = GE::Input::GetMousePosition(); auto width = GE::Application::Get().GetWindow().GetWidth(); auto height = GE::Application::Get().GetWindow().GetHeight(); auto bounds = m_CameraController.GetBounds(); auto pos = m_CameraController.GetCamera().GetPosition(); x = (x / width) * bounds.GetWidth() - bounds.GetWidth() * 0.5f; y = bounds.GetHeight() * 0.5f - (y / height) * bounds.GetHeight(); m_Particle.Position = { x + pos.x, y + pos.y }; for (int i = 0; i < 50; i++) m_ParticleSystem.Emit(m_Particle); } m_ParticleSystem.OnUpdate(ts); m_ParticleSystem.OnRender(m_CameraController.GetCamera()); GE::Renderer2D::BeginScene(m_CameraController.GetCamera()); for (uint32_t y = 0; y < m_MapHeight; y++) { for (uint32_t x = 0; x < m_MapWidth; x++) { char tileType = s_MapTiles[x + y * m_MapWidth]; GE::Ref<GE::SubTexture2D> texture; if (s_TextureMap.find(tileType) != s_TextureMap.end()) texture = s_TextureMap[tileType]; else texture = m_TextureBarrel; GE::Renderer2D::DrawQuad({ x - m_MapWidth / 2.0f, y - m_MapHeight / 2.0f, 0.5f }, { 1.0f, 1.0f }, texture); } } //GE::Renderer2D::DrawQuad({ 0.0f, 0.0f, 0.5f }, { 1.0f, 1.0f }, m_TextureStairs); //GE::Renderer2D::DrawQuad({ 1.0f, 0.0f, 0.5f }, { 1.0f, 1.0f }, m_TextureBarrel); //GE::Renderer2D::DrawQuad({ -1.0f, 0.0f, 0.5f }, { 1.0f, 2.0f }, m_TextureTree); GE::Renderer2D::EndScene(); } void Sandbox2D::OnImGuiRender() { GS_PROFILE_FUNCTION(); ImGui::Begin("Settings"); auto stats = GE::Renderer2D::GetStats(); ImGui::Text("Renderer2D Stats:"); ImGui::Text("Draw Calls: %d", stats.DrawCalls); ImGui::Text("Quads: %d", stats.QuadCount); ImGui::Text("Vertices: %d", stats.GetTotalVertexCount()); ImGui::Text("Indices: %d", stats.GetTotalIndexCount()); ImGui::ColorEdit4("Square Color", glm::value_ptr(m_SquareColor)); ImGui::End(); } void Sandbox2D::OnEvent(GE::Event& e) { m_CameraController.OnEvent(e); }
29.192308
128
0.673254
ivanchotom
14c28818c7186f1404beb0a4f68d8284e3844b3c
8,884
cpp
C++
thorlcr/activities/selfjoin/thselfjoinslave.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
thorlcr/activities/selfjoin/thselfjoinslave.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
thorlcr/activities/selfjoin/thselfjoinslave.cpp
jakesmith/HPCC-Platform
c3b9268c492e473176ea36e3e916c4a544f47561
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #include "jlib.hpp" #include "thselfjoinslave.ipp" #include "tsorts.hpp" #include "tsorta.hpp" #include "thactivityutil.ipp" #include "thorport.hpp" #include "thsortu.hpp" #include "thsortu.hpp" #include "thexception.hpp" #include "thbufdef.hpp" #include "thorxmlwrite.hpp" #define NUMSLAVEPORTS 2 // actually should be num MP tags class SelfJoinSlaveActivity : public CSlaveActivity { typedef CSlaveActivity PARENT; private: Owned<IThorSorter> sorter; IHThorJoinArg * helper; unsigned portbase; bool isLocal; bool isLightweight; Owned<IRowStream> strm; ICompare * compare; ISortKeySerializer * keyserializer; mptag_t mpTagRPC; Owned<IJoinHelper> joinhelper; CriticalSection joinHelperCrit; Owned<IBarrier> barrier; SocketEndpoint server; bool isUnstable() { // actually don't think currently supported by join but maybe will be sometime return false; } IRowStream * doLocalSelfJoin() { ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: Performing local self-join"); Owned<IThorRowLoader> iLoader = createThorRowLoader(*this, ::queryRowInterfaces(input), compare, isUnstable() ? stableSort_none : stableSort_earlyAlloc, rc_mixed, SPILL_PRIORITY_SELFJOIN); Owned<IRowStream> rs = iLoader->load(inputStream, abortSoon); mergeStats(stats, iLoader, spillStatistics); // Not sure of the best policy if rs spills later on. PARENT::stopInput(0); return rs.getClear(); } IRowStream * doGlobalSelfJoin() { ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: Performing global self-join"); sorter->Gather(::queryRowInterfaces(input), inputStream, compare, NULL, NULL, keyserializer, NULL, NULL, false, isUnstable(), abortSoon, NULL); PARENT::stopInput(0); if (abortSoon) { barrier->cancel(); return NULL; } if (!barrier->wait(false)) { Sleep(1000); // let original error through throw MakeThorException(TE_BarrierAborted,"SELFJOIN: Barrier Aborted"); } rowcount_t totalrows; return sorter->startMerge(totalrows); } public: SelfJoinSlaveActivity(CGraphElementBase *_container, bool _isLocal, bool _isLightweight) : CSlaveActivity(_container, joinActivityStatistics) { helper = static_cast <IHThorJoinArg *> (queryHelper()); isLocal = _isLocal||_isLightweight; isLightweight = _isLightweight; portbase = 0; compare = NULL; keyserializer = NULL; mpTagRPC = TAG_NULL; if (isLocal) setRequireInitData(false); appendOutputLinked(this); } ~SelfJoinSlaveActivity() { if(portbase) queryJobChannel().freePort(portbase, NUMSLAVEPORTS); } // IThorSlaveActivity virtual void init(MemoryBuffer & data, MemoryBuffer &slaveData) override { if (!isLocal) { mpTagRPC = container.queryJobChannel().deserializeMPTag(data); mptag_t barrierTag = container.queryJobChannel().deserializeMPTag(data); barrier.setown(container.queryJobChannel().createBarrier(barrierTag)); portbase = queryJobChannel().allocPort(NUMSLAVEPORTS); server.setLocalHost(portbase); sorter.setown(CreateThorSorter(this, server,&container.queryJob().queryIDiskUsage(),&queryJobChannel().queryJobComm(),mpTagRPC)); server.serialize(slaveData); } compare = helper->queryCompareLeft(); // NB not CompareLeftRight keyserializer = helper->querySerializeLeft(); // hopefully never need right if (isLightweight) ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: LIGHTWEIGHT"); else if(isLocal) ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: LOCAL"); else ::ActPrintLog(this, thorDetailedLogLevel, "SELFJOIN: GLOBAL"); } virtual void reset() override { PARENT::reset(); if (sorter) return; // JCSMORE loop - shouldn't have to recreate sorter between loop iterations if (!isLocal && TAG_NULL != mpTagRPC) sorter.setown(CreateThorSorter(this, server,&container.queryJob().queryIDiskUsage(),&queryJobChannel().queryJobComm(),mpTagRPC)); } virtual void kill() override { sorter.clear(); if (portbase) { queryJobChannel().freePort(portbase, NUMSLAVEPORTS); portbase = 0; } PARENT::kill(); } // IThorDataLink virtual void start() override { ActivityTimer s(slaveTimerStats, timeActivities); PARENT::start(); bool hintunsortedoutput = getOptBool(THOROPT_UNSORTED_OUTPUT, (JFreorderable & helper->getJoinFlags()) != 0); bool hintparallelmatch = getOptBool(THOROPT_PARALLEL_MATCH, hintunsortedoutput); // i.e. unsorted, implies use parallel by default, otherwise no point if (helper->getJoinFlags()&JFlimitedprefixjoin) { CriticalBlock b(joinHelperCrit); // use std join helper (less efficient but implements limited prefix) joinhelper.setown(createJoinHelper(*this, helper, this, hintparallelmatch, hintunsortedoutput)); } else { CriticalBlock b(joinHelperCrit); joinhelper.setown(createSelfJoinHelper(*this, helper, this, hintparallelmatch, hintunsortedoutput)); } if (isLightweight) strm.set(inputStream); else { strm.setown(isLocal ? doLocalSelfJoin() : doGlobalSelfJoin()); assertex(strm); // NB: PARENT::stopInput(0) will now have been called } joinhelper->init(strm, NULL, ::queryRowAllocator(queryInput(0)), ::queryRowAllocator(queryInput(0)), ::queryRowMetaData(queryInput(0))); } virtual void abort() override { CSlaveActivity::abort(); if (joinhelper) joinhelper->stop(); } virtual void stop() override { if (hasStarted()) { if (!isLocal) { barrier->wait(false); sorter->stopMerge(); } { CriticalBlock b(joinHelperCrit); joinhelper.clear(); } if (strm) { if (!isLightweight) // if lightweight strm=input and PARENT::stop handles input stop strm->stop(); strm.clear(); } } PARENT::stop(); } CATCH_NEXTROW() { ActivityTimer t(slaveTimerStats, timeActivities); if(joinhelper) { OwnedConstThorRow row = joinhelper->nextRow(); if (row) { dataLinkIncrement(); return row.getClear(); } } return NULL; } virtual bool isGrouped() const override { return false; } virtual void getMetaInfo(ThorDataLinkMetaInfo &info) const override { initMetaInfo(info); info.buffersInput = true; info.unknownRowsOutput = true; } virtual void serializeStats(MemoryBuffer &mb) override { { CriticalBlock b(joinHelperCrit); rowcount_t p = joinhelper?joinhelper->getLhsProgress():0; stats.setStatistic(StNumLeftRows, p); mergeStats(stats, sorter, spillStatistics); // No danger of a race with reset() because that never replaces a valid sorter } CSlaveActivity::serializeStats(mb); } }; CActivityBase *createSelfJoinSlave(CGraphElementBase *container) { return new SelfJoinSlaveActivity(container, false, false); } CActivityBase *createLocalSelfJoinSlave(CGraphElementBase *container) { return new SelfJoinSlaveActivity(container, true, false); } CActivityBase *createLightweightSelfJoinSlave(CGraphElementBase *container) { return new SelfJoinSlaveActivity(container, true, true); }
35.536
196
0.624156
jeclrsg
14c52c2555445a43699fb6b307ef73452e952d3d
5,493
cpp
C++
src/modules/hip/kernel/jitter.cpp
asalmanp/rpp
f31df51103b625a8afa26c46451739c94603452f
[ "MIT" ]
null
null
null
src/modules/hip/kernel/jitter.cpp
asalmanp/rpp
f31df51103b625a8afa26c46451739c94603452f
[ "MIT" ]
null
null
null
src/modules/hip/kernel/jitter.cpp
asalmanp/rpp
f31df51103b625a8afa26c46451739c94603452f
[ "MIT" ]
null
null
null
#include <hip/hip_runtime.h> #define saturate_8u(value) ( (value) > 255 ? 255 : ((value) < 0 ? 0 : (value) )) __device__ unsigned int xorshift(int pixid){ unsigned int x = 123456789; unsigned int w = 88675123; unsigned int seed = x + pixid; unsigned int t = seed ^ (seed << 11); unsigned int res = w ^ (w >> 19) ^ (t ^(t >> 8)); return res; } extern "C" __global__ void jitter_pkd( unsigned char* input, unsigned char* output, const unsigned int height, const unsigned int width, const unsigned int channel, const unsigned int kernelSize ) { int id_x = hipBlockIdx_x *hipBlockDim_x + hipThreadIdx_x; int id_y = hipBlockIdx_y *hipBlockDim_y + hipThreadIdx_y; int id_z = hipBlockIdx_z *hipBlockDim_z + hipThreadIdx_z; if (id_x >= width || id_y >= height || id_z >= channel) return; int pixIdx = id_y * channel * width + id_x * channel; int nhx = xorshift(pixIdx) % (kernelSize); int nhy = xorshift(pixIdx) % (kernelSize); int bound = (kernelSize - 1) / 2; if((id_y - bound + nhy) >= 0 && (id_y - bound + nhy) <= height - 1 && (id_x - bound + nhx) >= 0 && (id_x - bound + nhx) <= width - 1) { int index = ((id_y - bound) * channel * width) + ((id_x - bound) * channel) + (nhy * channel * width) + (nhx * channel); for(int i = 0 ; i < channel ; i++) { output[pixIdx + i] = input[index + i]; } } else { for(int i = 0 ; i < channel ; i++) { output[pixIdx + i] = input[pixIdx + i]; } } } extern "C" __global__ void jitter_pln( unsigned char* input, unsigned char* output, const unsigned int height, const unsigned int width, const unsigned int channel, const unsigned int kernelSize ) { int id_x = hipBlockIdx_x *hipBlockDim_x + hipThreadIdx_x; int id_y = hipBlockIdx_y *hipBlockDim_y + hipThreadIdx_y; int id_z = hipBlockIdx_z *hipBlockDim_z + hipThreadIdx_z; if (id_x >= width || id_y >= height || id_z >= channel) return; int pixIdx = id_y * width + id_x; int channelPixel = height * width; int nhx = xorshift(pixIdx) % (kernelSize); int nhy = xorshift(pixIdx) % (kernelSize); int bound = (kernelSize - 1) / 2; if((id_y - bound + nhy) >= 0 && (id_y - bound + nhy) <= height - 1 && (id_x - bound + nhx) >= 0 && (id_x - bound + nhx) <= width - 1) { int index = ((id_y - bound) * width) + (id_x - bound) + (nhy * width) + (nhx); for(int i = 0 ; i < channel ; i++) { output[pixIdx + (height * width * i)] = input[index + (height * width * i)]; } } else { for(int i = 0 ; i < channel ; i++) { output[pixIdx + (height * width * i)] = input[pixIdx + (height * width * i)]; } } } extern "C" __global__ void jitter_batch( unsigned char* input, unsigned char* output, unsigned int *kernelSize, int *xroi_begin, int *xroi_end, int *yroi_begin, int *yroi_end, unsigned int *height, unsigned int *width, unsigned int *max_width, unsigned long *batch_index, const unsigned int channel, unsigned int *inc, // use width * height for pln and 1 for pkd const int plnpkdindex // use 1 pln 3 for pkd ) { int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y; int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z; int kernelSizeTemp = kernelSize[id_z]; int indextmp=0; long pixIdx = 0; int bound = (kernelSizeTemp - 1) / 2; if(id_x < width[id_z] && id_y < height[id_z]) { pixIdx = batch_index[id_z] + (id_x + id_y * max_width[id_z] ) * plnpkdindex ; if((id_y >= yroi_begin[id_z] ) && (id_y <= yroi_end[id_z]) && (id_x >= xroi_begin[id_z]) && (id_x <= xroi_end[id_z])) { int nhx = xorshift(pixIdx) % (kernelSizeTemp); int nhy = xorshift(pixIdx) % (kernelSizeTemp); if((id_y - bound + nhy) >= 0 && (id_y - bound + nhy) <= height[id_z] - 1 && (id_x - bound + nhx) >= 0 && (id_x - bound + nhx) <= width[id_z] - 1) { int index = batch_index[id_z] + ((((id_y - bound) * max_width[id_z]) + (id_x - bound)) * plnpkdindex) + (((nhy * max_width[id_z]) + (nhx)) * plnpkdindex); for(int i = 0 ; i < channel ; i++) { output[pixIdx] = input[index]; pixIdx += inc[id_z]; index += inc[id_z]; } } } else if((id_x < width[id_z] ) && (id_y < height[id_z])) { for(indextmp = 0; indextmp < channel; indextmp++) { output[pixIdx] = input[pixIdx]; pixIdx += inc[id_z]; } } } }
41.613636
170
0.488622
asalmanp
14c788f0cc38e96375cf1ed0906cfb9a6b03f640
8,319
cpp
C++
src/geode/model/representation/builder/section_builder.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
64
2019-08-02T14:31:01.000Z
2022-03-30T07:46:50.000Z
src/geode/model/representation/builder/section_builder.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
395
2019-08-02T17:15:10.000Z
2022-03-31T15:10:27.000Z
src/geode/model/representation/builder/section_builder.cpp
Geode-solutions/OpenGeode
e47621989e6fc152f529d4e1e7e3b9ef9e7d6ccc
[ "MIT" ]
8
2019-08-19T21:32:15.000Z
2022-03-06T18:41:10.000Z
/* * Copyright (c) 2019 - 2021 Geode-solutions * * 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 <geode/model/representation/builder/section_builder.h> #include <geode/mesh/core/edged_curve.h> #include <geode/mesh/core/mesh_id.h> #include <geode/mesh/core/point_set.h> #include <geode/mesh/core/surface_mesh.h> #include <geode/model/mixin/core/corner.h> #include <geode/model/mixin/core/line.h> #include <geode/model/mixin/core/model_boundary.h> #include <geode/model/mixin/core/surface.h> #include <geode/model/representation/builder/detail/copy.h> #include <geode/model/representation/core/section.h> namespace { template < typename Component > void register_new_component( geode::SectionBuilder& builder, const Component& component ) { builder.register_component( component.component_id() ); builder.register_mesh_component( component ); } } // namespace namespace geode { SectionBuilder::SectionBuilder( Section& section ) : TopologyBuilder( section ), AddComponentsBuilders< 2, Corners, Lines, Surfaces, ModelBoundaries >( section ), IdentifierBuilder( section ), section_( section ) { } ModelCopyMapping SectionBuilder::copy( const Section& section ) { set_name( section.name() ); const auto mapping = copy_components( section ); copy_relationships( mapping, section ); copy_component_geometry( mapping, section ); return mapping; } ModelCopyMapping SectionBuilder::copy_components( const Section& section ) { ModelCopyMapping mappings; mappings.emplace( Corner2D::component_type_static(), detail::copy_corner_components( section, section_, *this ) ); mappings.emplace( Line2D::component_type_static(), detail::copy_line_components( section, section_, *this ) ); mappings.emplace( Surface2D::component_type_static(), detail::copy_surface_components( section, section_, *this ) ); mappings.emplace( ModelBoundary2D::component_type_static(), detail::copy_model_boundary_components( section, *this ) ); return mappings; } void SectionBuilder::copy_component_geometry( const ModelCopyMapping& mappings, const Section& section ) { detail::copy_corner_geometry( section, section_, *this, mappings.at( Corner2D::component_type_static() ) ); detail::copy_line_geometry( section, section_, *this, mappings.at( Line2D::component_type_static() ) ); detail::copy_surface_geometry( section, section_, *this, mappings.at( Surface2D::component_type_static() ) ); create_unique_vertices( section.nb_unique_vertices() ); detail::copy_vertex_identifier_components( section, *this, Corner2D::component_type_static(), mappings.at( Corner2D::component_type_static() ) ); detail::copy_vertex_identifier_components( section, *this, Line2D::component_type_static(), mappings.at( Line2D::component_type_static() ) ); detail::copy_vertex_identifier_components( section, *this, Surface2D::component_type_static(), mappings.at( Surface2D::component_type_static() ) ); } const uuid& SectionBuilder::add_corner() { const auto& id = create_corner(); register_new_component( *this, section_.corner( id ) ); return id; } const uuid& SectionBuilder::add_corner( const MeshImpl& impl ) { const auto& id = create_corner( impl ); register_new_component( *this, section_.corner( id ) ); return id; } const uuid& SectionBuilder::add_line() { const auto& id = create_line(); register_new_component( *this, section_.line( id ) ); return id; } const uuid& SectionBuilder::add_line( const MeshImpl& impl ) { const auto& id = create_line( impl ); register_new_component( *this, section_.line( id ) ); return id; } const uuid& SectionBuilder::add_surface() { const auto& id = create_surface(); register_new_component( *this, section_.surface( id ) ); return id; } const uuid& SectionBuilder::add_surface( const MeshImpl& impl ) { const auto& id = create_surface( impl ); register_new_component( *this, section_.surface( id ) ); return id; } const uuid& SectionBuilder::add_model_boundary() { const auto& id = create_model_boundary(); register_component( section_.model_boundary( id ).component_id() ); return id; } void SectionBuilder::update_corner_mesh( const Corner2D& corner, std::unique_ptr< PointSet2D > mesh ) { unregister_mesh_component( corner ); set_corner_mesh( corner.id(), std::move( mesh ) ); register_mesh_component( corner ); } void SectionBuilder::update_line_mesh( const Line2D& line, std::unique_ptr< EdgedCurve2D > mesh ) { unregister_mesh_component( line ); set_line_mesh( line.id(), std::move( mesh ) ); register_mesh_component( line ); } void SectionBuilder::update_surface_mesh( const Surface2D& surface, std::unique_ptr< SurfaceMesh2D > mesh ) { unregister_mesh_component( surface ); set_surface_mesh( surface.id(), std::move( mesh ) ); register_mesh_component( surface ); } void SectionBuilder::remove_corner( const Corner2D& corner ) { unregister_component( corner.id() ); unregister_mesh_component( corner ); delete_corner( corner ); } void SectionBuilder::remove_line( const Line2D& line ) { unregister_component( line.id() ); unregister_mesh_component( line ); delete_line( line ); } void SectionBuilder::remove_surface( const Surface2D& surface ) { unregister_component( surface.id() ); unregister_mesh_component( surface ); delete_surface( surface ); } void SectionBuilder::remove_model_boundary( const ModelBoundary2D& boundary ) { unregister_component( boundary.id() ); delete_model_boundary( boundary ); } void SectionBuilder::add_corner_line_boundary_relationship( const Corner2D& corner, const Line2D& line ) { add_boundary_relation( corner.id(), line.id() ); } void SectionBuilder::add_line_surface_boundary_relationship( const Line2D& line, const Surface2D& surface ) { add_boundary_relation( line.id(), surface.id() ); } void SectionBuilder::add_corner_surface_internal_relationship( const Corner2D& corner, const Surface2D& surface ) { add_internal_relation( corner.id(), surface.id() ); } void SectionBuilder::add_line_surface_internal_relationship( const Line2D& line, const Surface2D& surface ) { add_internal_relation( line.id(), surface.id() ); } void SectionBuilder::add_line_in_model_boundary( const Line2D& line, const ModelBoundary2D& boundary ) { add_item_in_collection( line.id(), boundary.id() ); } } // namespace geode
35.4
80
0.669431
Geode-solutions
14c9c4279f8d741df6474b9718009f4928986ded
19,517
cpp
C++
src/gausskernel/storage/cstore/cstore_delta.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
src/gausskernel/storage/cstore/cstore_delta.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
src/gausskernel/storage/cstore/cstore_delta.cpp
opengauss-mirror/openGauss-graph
6beb138fd00abdbfddc999919f90371522118008
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * --------------------------------------------------------------------------------------- * * cstore_delta.cpp * routines to support ColStore delta * * IDENTIFICATION * src/gausskernel/storage/cstore/cstore_delta.cpp * * --------------------------------------------------------------------------------------- */ #include "access/cstore_delta.h" #include "access/cstore_insert.h" #include "access/heapam.h" #include "access/tableam.h" #include "catalog/dependency.h" #include "catalog/objectaddress.h" #include "catalog/pg_partition_fn.h" #include "nodes/makefuncs.h" #include "parser/parse_utilcmd.h" #include "utils/fmgroids.h" #include "utils/snapmgr.h" extern List* ChooseIndexColumnNames(const List* indexElems); extern void ComputeIndexAttrs(IndexInfo* indexInfo, Oid* typeOidP, Oid* collationOidP, Oid* classOidP, int16* colOptionP, List* attList, List* exclusionOpNames, Oid relId, const char* accessMethodName, Oid accessMethodId, bool amcanorder, bool isconstraint); static Oid GetCUIdxFromDeltaIdx(Relation deltaIdx, bool isPartition); /* * @Description: Move datas on delta to its corresponding CU. * @IN rel: the CU owns detal table. * @IN parentRel: if rel is a partition of a cstore, parentRel is * its parent relation. Otherwise parentRel is NULL. */ void MoveDeltaDataToCU(Relation rel, Relation parentRel) { if (RELATION_IS_PARTITIONED(rel)) { /* For partitioned table. */ List* partitionList = relationGetPartitionOidList(rel); ListCell* cell = NULL; Oid partitionOid = InvalidOid; Partition partition = NULL; Relation partRelation = NULL; foreach (cell, partitionList) { partitionOid = lfirst_oid(cell); /* Data movement consists of delete and insert, so we apply RowExclusiveLock. */ partition = partitionOpen(rel, partitionOid, RowExclusiveLock); partRelation = partitionGetRelation(rel, partition); MoveDeltaDataToCU(partRelation, rel); partitionClose(rel, partition, NoLock); releaseDummyRelation(&partRelation); } list_free_ext(partitionList); return; } Relation deltaRel = heap_open(RelationGetDeltaRelId(rel), RowExclusiveLock); TableScanDesc deltaScanDesc = tableam_scan_begin(deltaRel, GetActiveSnapshot(), 0, NULL); InsertArg args; HeapTuple deltaTup = NULL; ResultRelInfo *resultRelInfo = NULL; if (rel->rd_rel->relhasindex) { resultRelInfo = makeNode(ResultRelInfo); if (parentRel != NULL) { InitResultRelInfo(resultRelInfo, parentRel, 1, 0); } else { InitResultRelInfo(resultRelInfo, rel, 1, 0); } ExecOpenIndices(resultRelInfo, false); } CStoreInsert::InitInsertArg(rel, resultRelInfo, true, args); CStoreInsert cstoreInsert(rel, args, false, NULL, NULL); TupleDesc tupDesc = rel->rd_att; Datum* val = (Datum*)palloc(sizeof(Datum) * tupDesc->natts); bool* null = (bool*)palloc(sizeof(bool) * tupDesc->natts); bulkload_rows batchRow(tupDesc, RelationGetMaxBatchRows(rel), true); while ((deltaTup = (HeapTuple) tableam_scan_getnexttuple(deltaScanDesc, ForwardScanDirection)) != NULL) { tableam_tops_deform_tuple(deltaTup, tupDesc, val, null); /* ignore returned value because only one tuple is appended into */ (void)batchRow.append_one_tuple(val, null, tupDesc); /* delete the current tuple from delta table */ simple_heap_delete(deltaRel, &deltaTup->t_self); if (batchRow.full_rownum()) { /* insert into main table */ cstoreInsert.BatchInsert(&batchRow, 0); batchRow.reset(true); } } if (batchRow.m_rows_curnum > 0) { cstoreInsert.BatchInsert(&batchRow, 0); } cstoreInsert.SetEndFlag(); tableam_scan_end(deltaScanDesc); /* clean cstore insert */ pfree(val); pfree(null); CStoreInsert::DeInitInsertArg(args); batchRow.Destroy(); cstoreInsert.Destroy(); if (resultRelInfo != NULL) { ExecCloseIndices(resultRelInfo); pfree(resultRelInfo); } heap_close(deltaRel, RowExclusiveLock); } /* * @Description: Define unique index on delta table. * @IN relationId: the CU owns delta table. * @IN stmt: IndexStmt describing the properties of the new index. * @IN indexRelationId: the index on CU. * @IN parentRel: the parent relation of the CU if relationId is a partition of cstore. */ void DefineDeltaUniqueIndex(Oid relationId, IndexStmt* stmt, Oid indexRelationId, Relation parentRel) { if (!stmt->unique) { return; } Relation rel = NULL; Relation deltaRelation = NULL; Partition partition = NULL; int numberOfKeyAttributes = 0; List* indexColNames = NIL; char deltaIndexRelName[NAMEDATALEN] = {'\0'}; error_t ret = 0; Oid* typeObjectId = NULL; Oid* collationObjectId = NULL; Oid* classObjectId = NULL; int16* coloptions = NULL; Oid indexOid = InvalidOid; if (parentRel) { /* For partiontioned table. relationId is a partition id. */ /* We will build index on partioned delta table, so we just use AccessShareLock on partition. */ partition = partitionOpen(parentRel, relationId, AccessShareLock); rel = partitionGetRelation(parentRel, partition); partitionClose(parentRel, partition, NoLock); } else { /* For non-partioned table. */ rel = relation_open(relationId, AccessShareLock); } if (RELATION_IS_PARTITIONED(rel)) { /* For partitioned table. */ List* partitionList = relationGetPartitionOidList(rel); ListCell* cell = NULL; Oid partitionOid = InvalidOid; Oid partIdxOid = InvalidOid; /* * Global partition index does not support column store, * so each partition has an index. We build index on each * partition delta. */ foreach (cell, partitionList) { partitionOid = lfirst_oid(cell); partIdxOid = getPartitionIndexOid(indexRelationId, partitionOid); DefineDeltaUniqueIndex(partitionOid, stmt, partIdxOid, rel); } list_free_ext(partitionList); relation_close(rel, NoLock); return; } deltaRelation = heap_open(RelationGetDeltaRelId(rel), ShareLock); numberOfKeyAttributes = list_length(stmt->indexParams); indexColNames = ChooseIndexColumnNames(stmt->indexParams); if (!parentRel) { ret = snprintf_s(deltaIndexRelName, sizeof(deltaIndexRelName), sizeof(deltaIndexRelName) - 1, "pg_delta_index_%u", indexRelationId); } else { ret = snprintf_s(deltaIndexRelName, sizeof(deltaIndexRelName), sizeof(deltaIndexRelName) - 1, "pg_delta_part_index_%u", indexRelationId); } securec_check_ss_c(ret, "\0", "\0"); /* Unique index can only be btree. */ Oid accessMethodId = BTREE_AM_OID; IndexInfo* indexInfo = NULL; indexInfo = makeNode(IndexInfo); indexInfo->ii_NumIndexAttrs = numberOfKeyAttributes; indexInfo->ii_NumIndexKeyAttrs = numberOfKeyAttributes; indexInfo->ii_Expressions = NIL; indexInfo->ii_ExpressionsState = NIL; indexInfo->ii_Predicate = NIL; indexInfo->ii_PredicateState = NIL; indexInfo->ii_ExclusionOps = NULL; indexInfo->ii_ExclusionProcs = NULL; indexInfo->ii_ExclusionStrats = NULL; indexInfo->ii_Unique = true; indexInfo->ii_ReadyForInserts = true; indexInfo->ii_Concurrent = false; indexInfo->ii_BrokenHotChain = false; indexInfo->ii_PgClassAttrId = 0; typeObjectId = (Oid*)palloc(numberOfKeyAttributes * sizeof(Oid)); collationObjectId = (Oid*)palloc(numberOfKeyAttributes * sizeof(Oid)); classObjectId = (Oid*)palloc(numberOfKeyAttributes * sizeof(Oid)); coloptions = (int16*)palloc(numberOfKeyAttributes * sizeof(int16)); ComputeIndexAttrs(indexInfo, typeObjectId, collationObjectId, classObjectId, coloptions, stmt->indexParams, stmt->excludeOpNames, parentRel != NULL ? RelationGetRelid(parentRel) : relationId, "btree", accessMethodId, true, stmt->isconstraint); IndexCreateExtraArgs extra; SetIndexCreateExtraArgs(&extra, InvalidOid, false, false); indexOid = index_create( deltaRelation, deltaIndexRelName, InvalidOid, InvalidOid, indexInfo, indexColNames, BTREE_AM_OID, rel->rd_rel->reltablespace, collationObjectId, classObjectId, coloptions, (Datum)0, true, false, false, false, true, false, false, &extra ); Assert(OidIsValid(indexOid)); heap_close(deltaRelation, NoLock); if (parentRel) { releaseDummyRelation(&rel); } else { relation_close(rel, NoLock); } pfree(typeObjectId); pfree(collationObjectId); pfree(classObjectId); pfree(coloptions); } /* * @Description: Delete the index of old delta table and build index on new delta table. * @IN oldRelOid: the old cstore after relation files swap. * @IN newRelOid: the new cstore after relation files swap. * @IN parentOid: parent oid for partitioned table, otherwise InvalidOid. */ void BuildIndexOnNewDeltaTable(Oid oldRelOid, Oid newRelOid, Oid parentOid) { Relation oldRel = NULL; Relation newRel = NULL; Relation parentRel = NULL; Oid oldDeltaOid = InvalidOid; Oid newDeltaOid = InvalidOid; oldRel = heap_open(oldRelOid, AccessShareLock); oldDeltaOid = oldRel->rd_rel->reldeltarelid; heap_close(oldRel, NoLock); if (OidIsValid(parentOid)) { /* For partitioned table. */ parentRel = heap_open(parentOid, AccessShareLock); heap_close(parentRel, NoLock); Partition partition = partitionOpen(parentRel, newRelOid, AccessShareLock); newRel = partitionGetRelation(parentRel, partition); partitionClose(parentRel, partition, NoLock); } else { /* For non partitioned table. */ newRel = heap_open(newRelOid, AccessShareLock); } newDeltaOid = newRel->rd_rel->reldeltarelid; if (OidIsValid(parentOid)) { releaseDummyRelation(&newRel); } else { heap_close(newRel, NoLock); } /* Apply AccssShareLock because we only get information from old delta. */ Relation oldDelta = heap_open(oldDeltaOid, AccessShareLock); TupleDesc tupleDesc = RelationGetDescr(oldRel); int attmapLength = tupleDesc->natts; AttrNumber* attmap = (AttrNumber*)palloc0(sizeof(AttrNumber) * attmapLength); for (int i = 0; i < attmapLength; ++i) { attmap[i] = i + 1; } List* indexIds = RelationGetIndexList(oldDelta); heap_close(oldDelta, NoLock); /* Apply ShareLock because we will build index on new delta. */ Relation newDelta = heap_open(newDeltaOid, ShareLock); ListCell* cell = NULL; ObjectAddress indexObject; foreach (cell, indexIds) { Oid idxOid = lfirst_oid(cell); bool isPartition = OidIsValid(parentOid); Relation idxRel = index_open(idxOid, AccessShareLock); index_close(idxRel, NoLock); if (idxRel->rd_index != NULL && idxRel->rd_index->indisunique) { Oid CUIdxOid = GetCUIdxFromDeltaIdx(idxRel, isPartition); CreateStmtContext cxt; cxt.relation = makeRangeVar( get_namespace_name(RelationGetNamespace(oldRel)), RelationGetRelationName(oldRel), -1); IndexStmt* indexStmt = NULL; indexStmt = generateClonedIndexStmt(&cxt, idxRel, attmap, attmapLength, NULL); /* * Must delete the index on old delta table, or conflicts will happen between * new index name and old index name. */ indexObject.classId = RelationRelationId; indexObject.objectId = idxOid; indexObject.objectSubId = 0; performDeletion(&indexObject, DROP_RESTRICT, 0); DefineDeltaUniqueIndex(newRelOid, indexStmt, CUIdxOid, parentRel); } } heap_close(newDelta, NoLock); pfree_ext(attmap); list_free_ext(indexIds); } /* * @Description: Reindex index on delta. * @IN indexId: the index on CU * @IN indexPartId: the index on partition CU. * For partitioned cstore, indexPartId=InvaidOid means reindex all partition delta index. Otherwise reindex single partition delta index * For non-partioned cstore, indexPartId=InvaldOid. */ void ReindexDeltaIndex(Oid indexId, Oid indexPartId) { Oid heapId = IndexGetRelation(indexId, false); /* We get AccessShareLock on CU table because we will build index on delta table. */ Relation heapRelation = heap_open(heapId, AccessShareLock); /* Close CU table, but keep locks. */ heap_close(heapRelation, NoLock); Oid deltaIdxOid = InvalidOid; if (!RELATION_IS_PARTITIONED(heapRelation)) { /* For non partioned cstore table. */ deltaIdxOid = GetDeltaIdxFromCUIdx(indexId, false); reindex_index(deltaIdxOid, InvalidOid, false, NULL, false); } else { /* For partitioned cstore table. */ if (OidIsValid(indexPartId)) { deltaIdxOid = GetDeltaIdxFromCUIdx(indexPartId, true); reindex_index(deltaIdxOid, InvalidOid, false, NULL, false); } else { /* Reindex all indexes on part delta table. */ List* indexPartOidList = NIL; ListCell* partCell = NULL; Relation iRel = index_open(indexId, AccessShareLock); index_close(iRel, NoLock); indexPartOidList = indexGetPartitionOidList(iRel); foreach (partCell, indexPartOidList) { Oid indexPartOid = lfirst_oid(partCell); deltaIdxOid = GetDeltaIdxFromCUIdx(indexPartOid, true); reindex_index(deltaIdxOid, InvalidOid, false, NULL, false); } releasePartitionOidList(&indexPartOidList); } } } /* * @Description: Reindex on partition delta table. * @IN indexOid: parent index on CU * @IN partOid: partition CU oid */ void ReindexPartDeltaIndex(Oid indexOid, Oid partOid) { Relation pg_partition = NULL; ScanKeyData scanKey; SysScanDesc partScan; HeapTuple partTuple = NULL; Form_pg_partition partForm = NULL; Oid indexPartOid = InvalidOid; pg_partition = heap_open(PartitionRelationId, AccessShareLock); ScanKeyInit(&scanKey, Anum_pg_partition_indextblid, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(partOid)); partScan = systable_beginscan(pg_partition, PartitionIndexTableIdIndexId, true, SnapshotNow, 1, &scanKey); while ((partTuple = systable_getnext(partScan)) != NULL) { partForm = (Form_pg_partition)GETSTRUCT(partTuple); if (partForm->parentid == indexOid) { indexPartOid = HeapTupleGetOid(partTuple); break; } } systable_endscan(partScan); heap_close(pg_partition, AccessShareLock); if (!OidIsValid(indexPartOid)) { ereport(ERROR, (errcode(ERRCODE_CACHE_LOOKUP_FAILED), errmsg("cache lookup failed for partitioned index %u", indexOid))); } ReindexDeltaIndex(indexOid, indexPartOid); } /* * @Description: Get CU index oid from its corresponding delta index. * @IN deltaIdx: delta index * @IN isPartition: true means delta index name is like pg_delta_part_index_xxx, * false means delta index name is like pg_delta_index_xxx. * @Reture: the CU index oid */ static Oid GetCUIdxFromDeltaIdx(Relation deltaIdx, bool isPartition) { Oid CUIdxOid = 0; int curIdx = 0; const char* deltaIdxName = RelationGetRelationName(deltaIdx); if (isPartition) { /* For partitioned delta table index. */ curIdx = strlen("pg_delta_part_index_"); } else { /* For non partitioned delta table index. */ curIdx = strlen("pg_delta_index_"); } while (deltaIdxName[curIdx] != '\0') { CUIdxOid = CUIdxOid * 10 + (deltaIdxName[curIdx] - '0'); curIdx++; } return CUIdxOid; } /* * @Description: Get delta index oid from its corresponding CU index. * @IN CUIndexOid: CU index * @IN isPartitioned: indicates whether CU index is a partitioned index. * @Reture: the delta index oid */ Oid GetDeltaIdxFromCUIdx(Oid CUIndexOid, bool isPartitioned) { char deltaIdxName[NAMEDATALEN] = {'\0'}; Relation pgclass = NULL; ScanKeyData scanKey[1]; SysScanDesc scan = NULL; HeapTuple tup = NULL; Oid deltaIdxOid = InvalidOid; error_t ret = 0; if (!isPartitioned) { ret = snprintf_s(deltaIdxName, sizeof(deltaIdxName), sizeof(deltaIdxName) - 1, "pg_delta_index_%u", CUIndexOid); } else { ret = snprintf_s(deltaIdxName, sizeof(deltaIdxName), sizeof(deltaIdxName) - 1, "pg_delta_part_index_%u", CUIndexOid); } securec_check_ss_c(ret, "\0", "\0"); ScanKeyInit(&scanKey[0], Anum_pg_class_relname, BTEqualStrategyNumber, F_NAMEEQ, CStringGetDatum(deltaIdxName)); pgclass = heap_open(RelationRelationId, AccessShareLock); scan = systable_beginscan(pgclass, ClassNameNspIndexId, true, SnapshotNow, 1, scanKey); tup = systable_getnext(scan); if (HeapTupleIsValid(tup)) { deltaIdxOid = HeapTupleGetOid(tup); } else { ereport( ERROR, (errcode(ERRCODE_UNDEFINED_TABLE), errmsg("relation \"%s\" does not exist", deltaIdxName))); } systable_endscan(scan); heap_close(pgclass, AccessShareLock); return deltaIdxOid; } /* * @Description: Get CU index name from delta index. * @IN deltaIdx: delta index which name stores CU index oid * @Return: CU index name */ char* GetCUIdxNameFromDeltaIdx(Relation deltaIdx) { const char* deltaIdxName = RelationGetRelationName(deltaIdx); bool partitioned; if (pg_strncasecmp(deltaIdxName, "pg_delta_part_index_", strlen("pg_delta_part_index_")) == 0) { partitioned = true; } else { partitioned = false; } Oid CUIdxOid = GetCUIdxFromDeltaIdx(deltaIdx, partitioned); char* CUIdxName = NULL; if (!partitioned) { CUIdxName = get_rel_name(CUIdxOid); } else { HeapTuple tuple = SearchSysCacheCopy1(PARTRELID, ObjectIdGetDatum(CUIdxOid)); if (!HeapTupleIsValid(tuple)) { ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("could not find tuple for partition index %u", CUIdxOid))); } Form_pg_partition partForm = (Form_pg_partition)GETSTRUCT(tuple); Oid parentIdxOid = partForm->parentid; CUIdxName = get_rel_name(parentIdxOid); heap_freetuple(tuple); } return CUIdxName; }
34.60461
122
0.66168
opengauss-mirror
14cbc57d7d0ec22762b7ab742e77c7528846a63a
6,368
cpp
C++
PhysX_3.4/Samples/SampleFramework/renderer/src/RendererMaterial.cpp
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
1
2019-12-09T16:03:55.000Z
2019-12-09T16:03:55.000Z
PhysX_3.4/Samples/SampleFramework/renderer/src/RendererMaterial.cpp
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
null
null
null
PhysX_3.4/Samples/SampleFramework/renderer/src/RendererMaterial.cpp
RyanTorant/simple-physx
a065a9c734c134074c63c80a9109a398b22d040c
[ "Unlicense" ]
null
null
null
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. #include <RendererMaterial.h> #include <Renderer.h> #include <RendererMaterialDesc.h> #include <RendererMaterialInstance.h> #include <PsString.h> namespace Ps = physx::shdfnd; #undef PxI32 using namespace SampleRenderer; static PxU32 getVariableTypeSize(RendererMaterial::VariableType type) { PxU32 size = 0; switch(type) { case RendererMaterial::VARIABLE_FLOAT: size = sizeof(float)*1; break; case RendererMaterial::VARIABLE_FLOAT2: size = sizeof(float)*2; break; case RendererMaterial::VARIABLE_FLOAT3: size = sizeof(float)*3; break; case RendererMaterial::VARIABLE_FLOAT4: size = sizeof(float)*4; break; case RendererMaterial::VARIABLE_FLOAT4x4: size = sizeof(float)*4*4; break; case RendererMaterial::VARIABLE_INT: size = sizeof(int)*1; break; case RendererMaterial::VARIABLE_SAMPLER2D: size = sizeof(RendererTexture2D*); break; case RendererMaterial::VARIABLE_SAMPLER3D: size = sizeof(RendererTexture3D*); break; default: break; } RENDERER_ASSERT(size>0, "Unable to compute Variable Type size."); return size; } RendererMaterial::Variable::Variable(const char *name, VariableType type, unsigned int offset) { size_t len = strlen(name)+1; m_name = new char[len]; Ps::strlcpy(m_name, len, name); m_type = type; m_offset = offset; m_size = -1; } void RendererMaterial::Variable::setSize(PxU32 size) { m_size = size; } RendererMaterial::Variable::~Variable(void) { if(m_name) delete [] m_name; } const char *RendererMaterial::Variable::getName(void) const { return m_name; } RendererMaterial::VariableType RendererMaterial::Variable::getType(void) const { return m_type; } PxU32 RendererMaterial::Variable::getDataOffset(void) const { return m_offset; } PxU32 RendererMaterial::Variable::getDataSize(void) const { return m_size != -1 ? m_size : getVariableTypeSize(m_type); } const char *RendererMaterial::getPassName(Pass pass) { const char *passName = 0; switch(pass) { case PASS_UNLIT: passName="PASS_UNLIT"; break; case PASS_AMBIENT_LIGHT: passName="PASS_AMBIENT_LIGHT"; break; case PASS_POINT_LIGHT: passName="PASS_POINT_LIGHT"; break; case PASS_DIRECTIONAL_LIGHT: passName="PASS_DIRECTIONAL_LIGHT"; break; case PASS_SPOT_LIGHT_NO_SHADOW: passName="PASS_SPOT_LIGHT_NO_SHADOW"; break; case PASS_SPOT_LIGHT: passName="PASS_SPOT_LIGHT"; break; case PASS_NORMALS: passName="PASS_NORMALS"; break; case PASS_DEPTH: passName="PASS_DEPTH"; break; default: break; // LRR: The deferred pass causes compiles with the ARB_draw_buffers profile option, creating // multiple color draw buffers. This doesn't work in OGL on ancient Intel parts. //case PASS_DEFERRED: passName="PASS_DEFERRED"; break; } RENDERER_ASSERT(passName, "Unable to obtain name for the given Material Pass."); return passName; } RendererMaterial::RendererMaterial(const RendererMaterialDesc &desc, bool enableMaterialCaching) : m_type(desc.type), m_alphaTestFunc(desc.alphaTestFunc), m_srcBlendFunc(desc.srcBlendFunc), m_dstBlendFunc(desc.dstBlendFunc), m_refCount(1), mEnableMaterialCaching(enableMaterialCaching) { m_alphaTestRef = desc.alphaTestRef; m_blending = desc.blending; m_variableBufferSize = 0; } RendererMaterial::~RendererMaterial(void) { RENDERER_ASSERT(m_refCount == 0, "RendererMaterial was not released as often as it was created"); PxU32 numVariables = (PxU32)m_variables.size(); for(PxU32 i=0; i<numVariables; i++) { delete m_variables[i]; } } void RendererMaterial::release() { m_refCount--; if (!mEnableMaterialCaching) { PX_ASSERT(m_refCount == 0); delete this; } } void RendererMaterial::bind(RendererMaterial::Pass pass, RendererMaterialInstance *materialInstance, bool instanced) const { if(materialInstance) { PxU32 numVariables = (PxU32)m_variables.size(); for(PxU32 i = 0; i < numVariables; i++) { const Variable &variable = *m_variables[i]; bindVariable(pass, variable, materialInstance->m_data+variable.getDataOffset()); } } } bool RendererMaterial::rendererBlendingOverrideEnabled() const { return getRenderer().blendingOverrideEnabled(); } const RendererMaterial::Variable *RendererMaterial::findVariable(const char *name, RendererMaterial::VariableType varType) { RendererMaterial::Variable *var = 0; PxU32 numVariables = (PxU32)m_variables.size(); for(PxU32 i=0; i<numVariables; i++) { RendererMaterial::Variable &v = *m_variables[i]; if(!strcmp(v.getName(), name)) { var = &v; break; } } if(var && var->getType() != varType) { var = 0; } return var; }
32.489796
122
0.734139
RyanTorant
14cc20cc753fcc23a7fd2324113160f2b75cca1a
133
cpp
C++
src/kognac/log/logs.cpp
pjotrscholtze/kognac
161a4308367edb2d6ffac9c336e801a20e3ef41e
[ "Apache-2.0" ]
null
null
null
src/kognac/log/logs.cpp
pjotrscholtze/kognac
161a4308367edb2d6ffac9c336e801a20e3ef41e
[ "Apache-2.0" ]
2
2018-06-26T16:41:19.000Z
2021-09-16T12:26:05.000Z
src/kognac/log/logs.cpp
pjotrscholtze/kognac
161a4308367edb2d6ffac9c336e801a20e3ef41e
[ "Apache-2.0" ]
2
2018-09-18T11:38:18.000Z
2021-09-13T23:27:09.000Z
#include <kognac/logs.h> int Logger::minLevel = TRACEL; std::mutex Logger::mutex; std::unique_ptr<Logger::FileLogger> Logger::file;
22.166667
49
0.744361
pjotrscholtze
14cd791727342165625c0ef8a0d101fa739a0fc9
680
cpp
C++
algorithms/sherlock.squares.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
1
2015-03-21T20:08:28.000Z
2015-03-21T20:08:28.000Z
algorithms/sherlock.squares.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
null
null
null
algorithms/sherlock.squares.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; long squares(unsigned long long a, unsigned long long b) { long square_count=0; if(a==1) square_count=sqrt(b); else { long root_a=sqrt(a); square_count=((long)sqrt(b))-((long)sqrt(a)); if((root_a*root_a)==a)++square_count; } return square_count; } void Run() { //enter value of T for testcase int T; cin>>T; unsigned long long array[T][2]; //enter value of a && b for T number of testcases for(int i=0; i<T; ++i) cin>>array[i][0]>>array[i][1]; for(int j=0; j<T; ++j) cout<<squares(array[j][0],array[j][1])<<endl; return; } int main() { Run(); return 0; }
18.378378
57
0.601471
kosmaz
14cef1c043ea48e9b645ea32f53e2080712d90d4
2,168
cpp
C++
automated-tests/src/dali-toolkit-internal/utc-Dali-ColorConversion.cpp
Coquinho/dali-toolkit
8fea8f2ae64923690519e0de039ce4af51271d9f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
automated-tests/src/dali-toolkit-internal/utc-Dali-ColorConversion.cpp
Coquinho/dali-toolkit
8fea8f2ae64923690519e0de039ce4af51271d9f
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-10-19T15:47:43.000Z
2020-10-19T15:47:43.000Z
automated-tests/src/dali-toolkit-internal/utc-Dali-ColorConversion.cpp
expertisesolutions/dali-toolkit
eac3e6ee30183868f1af12addd94e7f2fc467ed7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <dali-toolkit-test-suite-utils.h> #include <dali-toolkit/internal/helpers/color-conversion.h> using namespace Dali; using namespace Dali::Toolkit; void dali_color_conversion_startup(void) { test_return_value = TET_UNDEF; } void dali_color_conversion_cleanup(void) { test_return_value = TET_PASS; } int UtcDaliPropertyHelperConvertHtmlStringToColor(void) { tet_infoline( "Test to check whether An HTML style hex string can be converted" ); const std::string stringColor( "#FF0000" ); Vector4 result; DALI_TEST_CHECK( Toolkit::Internal::ConvertStringToColor( stringColor, result ) ); DALI_TEST_EQUALS( result, Color::RED, TEST_LOCATION ); END_TEST; } int UtcDaliPropertyHelperConvertStringPropertyToColor(void) { tet_infoline( "Test to check whether A Property value containing a string can be converted" ); const std::string stringColor( "#00FF00" ); Property::Value colorProperty( stringColor ); Vector4 result; DALI_TEST_CHECK( Toolkit::Internal::ConvertPropertyToColor( colorProperty, result ) ); DALI_TEST_EQUALS( result, Color::GREEN, TEST_LOCATION ); END_TEST; } int UtcDaliPropertyHelperConvertVector4PropertyToColor(void) { tet_infoline( "Test to check whether A Property value containing a string can be converted" ); const Vector4 color( 0.0, 0.0, 1.0, 1.0 ); Property::Value colorProperty( color ); Vector4 result; DALI_TEST_CHECK( Toolkit::Internal::ConvertPropertyToColor( colorProperty, result ) ); DALI_TEST_EQUALS( result, Color::BLUE, TEST_LOCATION ); END_TEST; }
28.155844
96
0.756919
Coquinho
14d3398986db3d9f743d401e31399fb4372bd89b
441
cpp
C++
kickStart/1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
kickStart/1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
kickStart/1.cpp
Jonsy13/Competitive-Programming
67e1918488c82b7ab8272b57dd4ffcff9dd4b1ac
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main(){ int t; cin>>t; int k = 1; while(t--){ int n; cin>>n; int a[n]; for(int i =0;i<n;i++){ cin>>a[i]; } int count = 0; for(int i=1;i<n-1;i++){ if(a[i]>a[i+1] && a[i]>a[i-1]){ count++; } } cout<<"Case #"<<k<<": "<<count<<endl; k++; } }
17.64
45
0.328798
Jonsy13
14d692f3e56c4c78e67497ad16165b97e8036063
20,100
cpp
C++
src/menu_io.cpp
digitalcraig/EtherTerm
4f994bb9ecbb48fbb77875d4d655b65a8b257d42
[ "Zlib" ]
106
2015-02-01T18:01:48.000Z
2022-02-10T04:51:11.000Z
src/menu_io.cpp
digitalcraig/EtherTerm
4f994bb9ecbb48fbb77875d4d655b65a8b257d42
[ "Zlib" ]
60
2015-02-01T18:00:39.000Z
2022-01-17T17:27:34.000Z
src/menu_io.cpp
digitalcraig/EtherTerm
4f994bb9ecbb48fbb77875d4d655b65a8b257d42
[ "Zlib" ]
16
2015-02-02T00:00:35.000Z
2021-08-17T01:42:58.000Z
#include "menu_io.hpp" #include "sequence_decoder.hpp" #include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <cstring> MenuIO::MenuIO(sequence_decoder_ptr &decoder, const std::string &program_path) : m_sequence_decoder(decoder) , m_program_path(program_path) { std::cout << "MenuIO Created!" << std::endl; } MenuIO::~MenuIO() { std::cout << "~MenuIO" << std::endl; } /** * @brief Right string padding * @param str * @param space */ void MenuIO::rightSpacing(std::string &str, const int &space) // Pad Right { if(space == 0) return; int s = str.size(); // if Line > Space, Erase to Make it match! if(s >= space) { str.erase(space, s - space); return; } for(int i = 0; i < (space-s); i++) str += ' '; } /** * @brief Left String Padding. * @param str * @param space */ void MenuIO::leftSpacing(std::string &str, const int &space) // Pad Left { if(space == 0) return; int s = str.size(); // if Line > Space, Erase to Make it match! if(s > space) { // Truncate to the last space digits. str.erase(0, s - space); return; } for(int i = 0; i < (space-s); i++) str.insert(0, 1, ' '); } /** * @brief Setup Text Input Fields * @param text * @param len */ void MenuIO::inputField(std::string &text, int &len) { std::string repeat; char formatted[1024]= {0}; char sTmp[3] = {0}; char sTmp2[3] = {0}; // Parse for Input String Modifiers std::string::size_type tempLength; std::string::size_type position; std::string::size_type stringSize; char INPUT_COLOR[255]= {0}; bool isColorOverRide = false; //found input color stringSize = text.size()-1; if(len == 0) { return; } // Override Input Length for ANSI position = text.find("|IN", 0); if(position != std::string::npos) { // Make sure we don't go past the bounds if(position+4 <= stringSize) { // (Unit Test Notes) // Need to Test if idDigit! And only if, both are // Then we cut these out and erase!, Otherwise // We only remove the |IN pipe sequence. if(isdigit(text[position+3]) && isdigit(text[position+4])) { sTmp[0] = text[position+3]; sTmp[1] = text[position+4]; text.erase(position, 5); tempLength = atoi(sTmp); if((signed)tempLength < len) len = tempLength; // Set new Length } else { text.erase(position, 3); } } } // Override Foreground/Background Input Field Colors position = text.find("|FB",0); if(position != std::string::npos) { // (Unit Test Notes) // Need to Test if isDigit! And only if, both are // Then we cut these out and erase!, Otherwise // We only remove the |FB pipe sequence. memset(&sTmp, 0, 3); memset(&sTmp2, 0, 3); // Make sure we don't go past the bounds if(position+6 <= stringSize) { if(isdigit(text[position+3]) && isdigit(text[position+4]) && isdigit(text[position+5]) && isdigit(text[position+6])) { sTmp[0] = text[position+3]; // Foreground 00-15 sTmp[1] = text[position+4]; sTmp2[0] = text[position+5]; // Background 16-23 sTmp2[1] = text[position+6]; text.erase(position, 7); sprintf(INPUT_COLOR, "|%s|%s", sTmp, sTmp2); isColorOverRide = true; } else { text.erase(position, 3); } } } // Pad len amount of spaces. if(len > 0) { repeat.insert(0, len, ' '); } // Set Default Input Color if none was passed. if(!isColorOverRide) { sprintf(INPUT_COLOR,"|00|19"); } // Format Input Field sprintf(formatted, "%s|07|16[%s%s|07|16]%s\x1b[%iD", (char *)text.c_str(), // Field Name INPUT_COLOR, // Field Fg,Bg Color repeat.c_str(), // Padding length of Field INPUT_COLOR, // Reset Input len+1); // Move back to starting position of field. text = formatted; } /* * Get Single Key Input (Blocking) * int MenuIO::getKey() { std::string inputSequence; while(!TheInputHandler::Instance()->isGlobalShutdown()) { // Catch updates when in the menu system. TheSequenceManager::Instance()->update(); if(TheInputHandler::Instance()->update()) { if(TheInputHandler::Instance()->getInputSequence(inputSequence)) break; } SDL_Delay(10); } // If Global Exit, return right away. if(TheInputHandler::Instance()->isGlobalShutdown()) { return EOF; } return inputSequence[0]; }*/ /* * Get Single Key Input (Non-Blocking) * * Not Used At this time. * int MenuIO::checkKey() { std::string inputSequence; if(TheInputHandler::Instance()->isGlobalShutdown()) { return EOF; } if(TheInputHandler::Instance()->update()) { inputSequence = TheInputHandler::Instance()->getInputSequence(); } else { SDL_Delay(10); return 0; } return inputSequence[0]; } */ /* * Get Input up to <ENTER> */ /* void MenuIO::getLine(char *line, // Returns Input into Line int length, // Max Input Length of String char *leadoff, // Data to Display in Default String {Optional} int hid) // If input is Echoed as hidden {Optional} { int sequence = 0; int secondSequence = 0; int i = 0; int Col = 0; int isEscapeSequence = 0; int cursorBlink = 0; bool startBlinking = false; std::string output; std::string input; std::string inputSequence; // Cursor Blinking. time_t ttime, ttime2; ttime = SDL_GetTicks(); #define DEL 0x7f // If were starting Off Input with a String already in buffer! display it! if(leadoff != 0) { input = leadoff; i = input.size(); Col = i; //TheSequenceManager::Instance()->decode(input); m_sequence_decoder->decodeEscSequenceData(input); } while(!TheInputHandler::Instance()->isGlobalShutdown()) { // Catch Screen updates when in the menu system. TheSequenceManager::Instance()->update(); if(TheInputHandler::Instance()->update() && !TheInputHandler::Instance()->isGlobalShutdown()) { // We got data, turn off the cursor! ttime = SDL_GetTicks(); startBlinking = false; cursorBlink = 0; // Get the Sequence. if(TheInputHandler::Instance()->getInputSequence(inputSequence)) { // Check for Abort, single ESC character. if(inputSequence == "\x1b" && inputSequence.size() == 1) { isEscapeSequence = false; strcpy(line,"\x1b"); return; } } } else { if(TheSequenceParser::Instance()->isCursorActive() && !TheInputHandler::Instance()->isGlobalShutdown()) { startBlinking = true; // Setup Timer for Blinking Cursor // Initial State = On, then Switch to off in next loop. if(cursorBlink % 2 == 0) { ttime2 = SDL_GetTicks(); if(startBlinking && (ttime2 - ttime) > 400) { TheRenderer::Instance()->renderCursorOffScreen(); TheRenderer::Instance()->drawTextureScreen(); --cursorBlink; ttime = SDL_GetTicks(); } } else { ttime2 = SDL_GetTicks(); if(startBlinking && (ttime2 - ttime) > 400) { TheRenderer::Instance()->renderCursorOnScreen(); TheRenderer::Instance()->drawTextureScreen(); ++cursorBlink; ttime = SDL_GetTicks(); } } } SDL_Delay(10); continue; } // Catch any shutdown here before doing anymore. if(TheInputHandler::Instance()->isGlobalShutdown()) { return; } sequence = inputSequence[0]; if(sequence == '\r') { sequence = '\n'; } // Escape in this case, ignore, later add movement in string if((int)sequence == 27) { if(inputSequence.size() >= 3) secondSequence = inputSequence[2]; isEscapeSequence = true; } else { isEscapeSequence = false; } // Catch all Escaped Keys for Cursor Movement if(isEscapeSequence) { switch(secondSequence) { case '3' : // Delete if(i != 0 || Col != 0) { sequenceToAnsi("\x1b[D \x1b[D"); input.erase(Col-1,1); --i; --Col; } break; default : break; } } else if((int)sequence == 25) { // CTRL Y - Clear Line input.erase(); i = Col; for(; i != 0; i--) { sequenceToAnsi("\x1b[D \x1b[D"); } i = 0; Col = i; } // delete 127 // Do destructive backspace // on VT100 Terms 127 DEL == BS! // Since we have no DELETE in this, delete on 1 liens will works like BS. else if((int)sequence == 0x08 || (int)sequence == 207 || (int)sequence == 0x7f) { if(i != 0 || Col != 0) { sequenceToAnsi("\x1b[D \x1b[D"); input.erase(Col-1,1); --i; --Col; } } // Normal Key Input, Letters & numbers else if((int)sequence > 31 && (int)sequence < 126) { if(i != length-1) { if(hid) { sequenceToAnsi("*"); } else { output = sequence; sequenceToAnsi(output); } input += sequence; ++i; ++Col; } } else if(sequence == '\r' || sequence == '\n') { strncpy(line, (char *)input.c_str(), length); break; } } // If Global Exit, return right away. if(TheInputHandler::Instance()->isGlobalShutdown()) { return; } } */ /** * @brief Foreground ESC Sequence Translation * @param data * @param fg */ void MenuIO::foregroundColorSequence(char *data, int fg) { switch(fg) { case 0: strcat(data, "x[0;30m"); break; case 1: strcat(data, "x[0;34m"); break; case 2: strcat(data, "x[0;32m"); break; case 3: strcat(data, "x[0;36m"); break; case 4: strcat(data, "x[0;31m"); break; case 5: strcat(data, "x[0;35m"); break; case 6: strcat(data, "x[0;33m"); break; case 7: strcat(data, "x[0;37m"); break; case 8: strcat(data, "x[1;30m"); break; case 9: strcat(data, "x[1;34m"); break; case 10: strcat(data, "x[1;32m"); break; case 11: strcat(data, "x[1;36m"); break; case 12: strcat(data, "x[1;31m"); break; case 13: strcat(data, "x[1;35m"); break; case 14: strcat(data, "x[1;33m"); break; case 15: strcat(data, "x[1;37m"); break; default : break; } data[0] = '\x1b'; } /** * @brief Background ESC Sequence Translation * @param data * @param bg */ void MenuIO::backgroundColorSequence(char *data, int bg) { switch(bg) { case 16: strcat(data, "x[40m"); break; case 17: strcat(data, "x[44m"); break; case 18: strcat(data, "x[42m"); break; case 19: strcat(data, "x[46m"); break; case 20: strcat(data, "x[41m"); break; case 21: strcat(data, "x[45m"); break; case 22: strcat(data, "x[43m"); break; case 23: strcat(data, "x[47m"); break; // Default to none. case 24: strcat(data, "x[0m"); break; default : break; } data[0] = '\x1b'; } /** * @brief Parses MCI and PIPE Codes to ANSI Sequences * @param sequence */ void MenuIO::sequenceToAnsi(const std::string &sequence) { std::string::size_type id1 = 0; // Pipe Position char pipe_sequence[3]; // Holds 1, 2nd digit of Pipe char pipe_position1[3]; // Hold XY Pos for ANSI Position Codes char pipe_position2[3]; // Hold XY Pos for ANSI Position Codes char esc_sequence[1024]; // Holds Converted Pipe 2 ANSI std::string data_string = sequence; #define SP 0x20 // Search for First Pipe while(id1 != std::string::npos) { id1 = data_string.find("|", id1); if(id1 != std::string::npos && id1+2 < data_string.size()) { memset(&pipe_sequence,0,sizeof(pipe_sequence)); memset(&esc_sequence,0,sizeof(esc_sequence)); pipe_sequence[0] = data_string[id1+1]; // Get First # after Pipe pipe_sequence[1] = data_string[id1+2]; // Get Second Number After Pipe if(pipe_sequence[0] == '\0' || pipe_sequence[0] == '\r' || pipe_sequence[0] == EOF) break; if(pipe_sequence[1] == '\0' || pipe_sequence[1] == '\r' || pipe_sequence[0] == EOF) break; //std::cout << "\r\n*** pipe_sequence: " << pipe_sequence << std::endl; if(isdigit(pipe_sequence[0]) && isdigit(pipe_sequence[1])) { std::string temp_sequence = ""; std::string::size_type type; temp_sequence += pipe_sequence[0]; temp_sequence += pipe_sequence[1]; int pipe_color_value = 0; try { pipe_color_value = std::stoi(temp_sequence, &type); if(pipe_color_value >= 0 && pipe_color_value < 16) { foregroundColorSequence(esc_sequence, pipe_color_value); } else if(pipe_color_value >= 16 && pipe_color_value < 24) { backgroundColorSequence(esc_sequence, pipe_color_value); } else { ++id1; } // Replace pipe code with ANSI Sequence if(strcmp(esc_sequence,"") != 0) { data_string.replace(id1, 3, esc_sequence); } } catch(const std::invalid_argument& ia) { std::cout << "Invalid argument: " << ia.what() << '\n'; ++id1; } } // Else not a Pipe Color / Parse for Screen Modification else if(pipe_sequence[0] == 'C') { // Carriage Return / New Line if(strcmp(pipe_sequence,"CR") == 0) { backgroundColorSequence(esc_sequence, 16); // Clear Background Attribute first strcat(esc_sequence,"\r\n"); data_string.replace(id1, 3, esc_sequence); id1 = 0; } // Clear Screen else if(strcmp(pipe_sequence,"CS") == 0) { backgroundColorSequence(esc_sequence, 16); // Set Scroll Region, Clear Background, Then Home Cursor. strcat(esc_sequence,"\x1b[2J\x1b[1;1H"); data_string.replace(id1, 3, esc_sequence); id1 = 0; } } else { if(strcmp(pipe_sequence,"XY") == 0 && id1+6 < data_string.size()) { memset(&pipe_position1, 0, sizeof(pipe_position1)); memset(&pipe_position2, 0, sizeof(pipe_position2)); // X Pos pipe_position1[0] = data_string[id1+3]; pipe_position1[1] = data_string[id1+4]; // Y Pos pipe_position2[0] = data_string[id1+5]; pipe_position2[1] = data_string[id1+6]; // Clear Background Attribute first backgroundColorSequence(esc_sequence, 16); char char_replacement[2048] = {0}; sprintf(char_replacement,"%s\x1b[%i;%iH", esc_sequence, atoi(pipe_position2), atoi(pipe_position1)); data_string.replace(id1, 7, char_replacement); } else { // End of the Line, nothing parsed out so // Skip ahead past current code. ++id1; } } } else { break; } id1 = data_string.find("|",id1); } m_sequence_decoder->decodeEscSequenceData(data_string); } /** * @brief Reads in ANSI text file and pushes to Display * @param file_name */ void MenuIO::displayMenuAnsi(const std::string &file_name) { std::string path = m_program_path; #ifdef _WIN32 path.append("assets\\directory\\"); #else path.append("assets/directory/"); #endif path.append(file_name); std::string buff; FILE *fp; int sequence = 0; if((fp = fopen(path.c_str(), "r+")) == nullptr) { std::cout << "MenuIO displayAnsiFile(): not found: " << std::endl << path << std::endl; return; } do { sequence = getc(fp); if(sequence != EOF) buff += sequence; } while(sequence != EOF); fclose(fp); // Send to the Sequence Manager. m_sequence_decoder->decodeEscSequenceData(buff); }
27.198917
121
0.455174
digitalcraig
14d7bdb2822f5bcdc8414f3ab70607112b6e2e82
7,861
cpp
C++
SpoutSDK/Example/Cinder/source/CinderSpoutReceiver.cpp
f-tischler/Spout2
0173a81ebcbc63c96c020e92563359c4f8e0791f
[ "BSD-2-Clause" ]
null
null
null
SpoutSDK/Example/Cinder/source/CinderSpoutReceiver.cpp
f-tischler/Spout2
0173a81ebcbc63c96c020e92563359c4f8e0791f
[ "BSD-2-Clause" ]
null
null
null
SpoutSDK/Example/Cinder/source/CinderSpoutReceiver.cpp
f-tischler/Spout2
0173a81ebcbc63c96c020e92563359c4f8e0791f
[ "BSD-2-Clause" ]
null
null
null
/* Basic Spout receiver for Cinder Uses the Spout SDK Based on the RotatingBox CINDER example without much modification Nothing fancy about this, just the basics. Search for "SPOUT" to see what is required ========================================================================== Copyright (C) 2014-2017 Lynn Jarvis. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ========================================================================== 11.05.14 - used updated Spout Dll with host fbo option and rgba 04.06.14 - used updated Spout Dll 04/06 with host fbo option removed - added Update function - moved receiver initialization from Setup to Update for sender detection 11.07.14 - changed to Spout SDK instead of the dll 29.09.14 - update with with SDK revision 12.10.14 - recompiled for release 03.01.15 - SDK recompile - SpoutPanel detected from registry install path 04.02.15 - SDK recompile for default DX9 (see SpoutGLDXinterop.h) 14.02.15 - SDK recompile for default DX11 and auto compatibility detection (see SpoutGLDXinterop.cpp) 21.05.15 - Added optional SetDX9 call - Recompiled for both DX9 and DX11 for new installer 26.05.15 - Recompile for revised SpoutPanel registry write of sender name 01.07.15 - Convert project to VS2012 - add a window title 30.03.16 - Rebuild for 2.005 release - VS2012 /MT 17.01.16 - Rebuild for 2.006 release - VS2012 /MT */ #include "cinder/app/AppBasic.h" #include "cinder/gl/Texture.h" // -------- SPOUT ------------- #include "..\..\..\SpoutSDK\Spout.h" // ---------------------------- using namespace ci; using namespace ci::app; class SpoutBoxApp : public AppBasic { public: void setup(); void draw(); void update(); void mouseDown(MouseEvent event); // -------- SPOUT ------------- SpoutReceiver spoutreceiver; // Create a Spout receiver object void prepareSettings(Settings *settings); void shutdown(); bool bInitialized; // true if a sender initializes OK bool bDoneOnce; // only try to initialize once bool bMemoryMode; // tells us if texture share compatible unsigned int g_Width, g_Height; // size of the texture being sent out char SenderName[256]; // sender name gl::Texture spoutTexture; // Local Cinder texture used for sharing // ---------------------------- }; // -------- SPOUT ------------- void SpoutBoxApp::prepareSettings(Settings *settings) { g_Width = 320; // set global width and height to something g_Height = 240; // they need to be reset when the receiver connects to a sender settings->setTitle("CinderSpoutReceiver"); settings->setWindowSize( g_Width, g_Height ); settings->setFullScreen( false ); settings->setResizable( true ); // allowed for a receiver settings->setFrameRate( 60.0f ); } // ---------------------------- void SpoutBoxApp::setup() { } void SpoutBoxApp::update() { unsigned int width, height; // -------- SPOUT ------------- if(!bInitialized) { // This is a receiver, so the initialization is a little more complex than a sender // The receiver will attempt to connect to the name it is sent. // Alternatively set the optional bUseActive flag to attempt to connect to the active sender. // If the sender name is not initialized it will attempt to find the active sender // If the receiver does not find any senders the initialization will fail // and "CreateReceiver" can be called repeatedly until a sender is found. // "CreateReceiver" will update the passed name, and dimensions. SenderName[0] = NULL; // the name will be filled when the receiver connects to a sender width = g_Width; // pass the initial width and height (they will be adjusted if necessary) height = g_Height; // Initialize a receiver if(spoutreceiver.CreateReceiver(SenderName, width, height, true)) { // true to find the active sender // Optionally test for texture share compatibility // bMemoryMode informs us whether Spout initialized for texture share or memory share bMemoryMode = spoutreceiver.GetMemoryShareMode(); // Is the size of the detected sender different from the current texture size ? // This is detected for both texture share and memoryshare if(width != g_Width || height != g_Height) { // Reset the global width and height g_Width = width; g_Height = height; // Reset the local receiving texture size spoutTexture = gl::Texture(g_Width, g_Height); // reset render window setWindowSize(g_Width, g_Height); } bInitialized = true; } else { // Receiver initialization will fail if no senders are running // Keep trying until one starts } } // endif not initialized // ---------------------------- } // -------- SPOUT ------------- void SpoutBoxApp::shutdown() { spoutreceiver.ReleaseReceiver(); } void SpoutBoxApp::mouseDown(MouseEvent event) { // Select a sender if( event.isRightDown() ) { spoutreceiver.SelectSenderPanel(); } } // ---------------------------- void SpoutBoxApp::draw() { unsigned int width, height; char txt[256]; gl::setMatricesWindow( getWindowSize() ); gl::clear(); gl::color( Color( 1, 1, 1 ) ); // Save current global width and height - they will be changed // by receivetexture if the sender changes dimensions width = g_Width; height = g_Height; // // Try to receive the texture at the current size // // NOTE : if ReceiveTexture is called with a framebuffer object bound, // include the FBO id as an argument so that the binding is restored afterwards // because Spout uses an fbo for intermediate rendering if(bInitialized) { if(spoutreceiver.ReceiveTexture(SenderName, width, height, spoutTexture.getId(), spoutTexture.getTarget())) { // Width and height are changed for sender change so the local texture has to be resized. if(width != g_Width || height != g_Height ) { // The sender dimensions have changed - update the global width and height g_Width = width; g_Height = height; // Update the local texture to receive the new dimensions spoutTexture = gl::Texture(g_Width, g_Height); // reset render window setWindowSize(g_Width, g_Height); return; // quit for next round } // Otherwise draw the texture and fill the screen gl::draw(spoutTexture, getWindowBounds()); // Show the user what it is receiving gl::enableAlphaBlending(); sprintf_s(txt, "Receiving from [%s]", SenderName); gl::drawString( txt, Vec2f( toPixels( 20 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); sprintf_s(txt, "fps : %2.2d", (int)getAverageFps()); gl::drawString( txt, Vec2f(getWindowWidth() - toPixels( 100 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); gl::drawString( "RH click to select a sender", Vec2f( toPixels( 20 ), getWindowHeight() - toPixels( 40 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); gl::disableAlphaBlending(); return; // received OK } } gl::enableAlphaBlending(); gl::drawString( "No sender detected", Vec2f( toPixels( 20 ), toPixels( 20 ) ), Color( 1, 1, 1 ), Font( "Verdana", toPixels( 24 ) ) ); gl::disableAlphaBlending(); // ---------------------------- } CINDER_APP_BASIC( SpoutBoxApp, RendererGl )
35.570136
165
0.671416
f-tischler
14dd25fbae2effecb6bffdd2e067030137e52ee0
4,155
cc
C++
src/projects/attractors/attractor_system_blueprint.cc
frtru/GemParticles
7447c4720f902be9686bbed2a490368374fc614a
[ "MIT" ]
19
2017-03-02T21:13:40.000Z
2022-03-24T03:14:10.000Z
src/projects/attractors/attractor_system_blueprint.cc
frtru/GemParticles
7447c4720f902be9686bbed2a490368374fc614a
[ "MIT" ]
46
2016-10-12T22:56:05.000Z
2020-07-06T06:13:45.000Z
OpenGL_Project/src/projects/attractors/attractor_system_blueprint.cc
felixyf0124/COMP477_F19_A2
80f96e130ef2715c3f10de25d1b973a60cc440e5
[ "MIT" ]
5
2017-03-03T02:13:15.000Z
2021-05-02T12:25:20.000Z
/************************************************************************* * Copyright (c) 2016 Fran�ois Trudel * * 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. *************************************************************************/ #include "projects/attractors/attractor_system_blueprint.hh" //C system files //C++ system files #include <memory> #include <limits> //Other libraries' .h files //Your project's .h files #include "core/particle_module.hh" #include "emitters/spherical_stream_emitter.hh" #include "renderers/core_opengl_renderer.hh" //Project specific components #include "projects/attractors/attractor_particle_system.hh" #include "projects/attractors/avx_particle_attractor.hh" namespace gem { namespace particle { namespace attractor_project { namespace blueprint { namespace attractor_system_builder { namespace { const glm::f32vec3 _ZeroVector = glm::f32vec3(0.0f, 0.0f, 0.0f); // Instead of using setters for every attribute, might as well put them public. // These parameters will be used during the Create() function to properly build the particle system glm::vec4 _HotColor = { 0.8235294117647059f, 0.0941176470588235f, 0.1803921568627451f, 1.0f }; glm::vec4 _ColdColor = { 0.1294117647058824f, 0.1607843137254902, 0.6392156862745098, 1.0f }; glm::f32vec3 _POI = { 1.0f, 1.0f, 1.0f }; float _InitialRadius = 1.0f; float _AccelerationRate = 0.0f; float _MaxDistance = 6.0f; std::size_t _ParticleCount = 1000000u; std::string _ParticleSystemName; // Handles on the dynamics to hand them over to the event handler // There are only used during the construction of the particle system std::shared_ptr< ParticleAttractor > _AttractorDynamicHandle; std::shared_ptr< ProximityColorUpdater > _ProximityColorUpdaterHandle; } void Create() { _AttractorDynamicHandle = std::make_shared<ParticleAttractor>(_POI, _AccelerationRate); _ProximityColorUpdaterHandle = std::make_shared<ProximityColorUpdater>(_POI, _HotColor, _ColdColor, _MaxDistance); auto wEmitter = std::make_shared<SphericalStreamEmitter>(_POI, _ZeroVector, _InitialRadius, 0.0f, std::numeric_limits<double>::max()); auto wParticleSystem = std::make_unique<ParticleSystem<LifeDeathCycle::Disabled> >(_ParticleCount, _ParticleSystemName, wEmitter); wParticleSystem->BindRenderer(std::make_shared<CoreGLRenderer>()); wParticleSystem->AddDynamic(_AttractorDynamicHandle); wParticleSystem->AddDynamic(_ProximityColorUpdaterHandle); particle_module::AddSystem(std::move(wParticleSystem)); } std::shared_ptr< ParticleAttractor > GetAttractorHandle() { return _AttractorDynamicHandle; } std::shared_ptr< ProximityColorUpdater > GetProximityColorUpdaterHandle() { return _ProximityColorUpdaterHandle; } void SetHotColor(const glm::vec4 &color) { _HotColor = color; } void SetColdColor(const glm::vec4 &color) { _ColdColor = color; } void SetPOI(const glm::f32vec3 &pos) { _POI = pos; } void SetInitialRadius(float radius) { _InitialRadius = radius; } void SetAccelerationRate(float rate) { _AccelerationRate = rate; } void SetMaxDistance(float distance) { _MaxDistance = distance; } void SetParticleCount(std::size_t count) { _ParticleCount = count; } void SetParticleSystemName(const std::string &name) { _ParticleSystemName = name; } } /* namespace attractor_system_builder */ } /* namespace blueprint */ } /* namespace attractor_project */ } /* namespace particle */ } /* namespace gem */
50.670732
136
0.711913
frtru
14dde6a45cd7c87b114d1b501f67ec47bdfb933f
1,031
cpp
C++
compiler/bino/tests/Functional.tests.cpp
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
compiler/bino/tests/Functional.tests.cpp
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
compiler/bino/tests/Functional.tests.cpp
periannath/ONE
61e0bdf2bcd0bc146faef42b85d469440e162886
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2019 Samsung Electronics Co., Ltd. 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. */ /** * Let's test functionals in "bino". * * NOTE The tests in this file assume that operator overloading works well. */ #include "bino.h" #include <gtest/gtest.h> TEST(FunctionalTests, transform_both_uniform) { auto inc = [](int n) { return n + 1; }; auto f = bino::transform_both(inc); auto res = f(std::make_pair(1, 3)); ASSERT_EQ(res.first, 2); ASSERT_EQ(res.second, 4); }
28.638889
75
0.70805
periannath
14dfc88d136480df8c85d062485ac70518677c59
3,687
cpp
C++
src/ItemFactory.cpp
zethon/ttvg
51d79ee3154669447dd522731aa0f7057e723abd
[ "MIT" ]
2
2020-11-02T20:51:36.000Z
2021-12-20T21:53:41.000Z
src/ItemFactory.cpp
zethon/ttvg
51d79ee3154669447dd522731aa0f7057e723abd
[ "MIT" ]
41
2020-07-20T16:37:48.000Z
2022-03-27T00:52:06.000Z
src/ItemFactory.cpp
zethon/ttvg
51d79ee3154669447dd522731aa0f7057e723abd
[ "MIT" ]
1
2020-11-02T20:51:37.000Z
2020-11-02T20:51:37.000Z
#include <boost/filesystem.hpp> #include <lua/lua.hpp> #include <fmt/core.h> #include "Item.h" #include "ItemFactory.h" #include "TTLua.h" namespace tt { namespace { ItemFactory* checkItemFactory(lua_State* L) { lua_rawgeti(L, LUA_REGISTRYINDEX, ITEMFACTORY_LUA_IDX); int type = lua_type(L, -1); if (type != LUA_TLIGHTUSERDATA) { return nullptr; } ItemFactory* state = static_cast<ItemFactory*>(lua_touserdata(L, -1)); if (!state) { return nullptr; } lua_pop(L, 1); return state; } int ItemFactory_createItem(lua_State* L) { auto fact = checkItemFactory(L); const auto itemname = lua_tostring(L, 1); std::size_t size = sizeof(ItemPtr); void* userdata = lua_newuserdata(L, size); // create a shared_ptr in the space Lua allocated // for us, so if we never assign this to anyone/thing // else it should gt deleted new(userdata) ItemPtr{fact->createItem(itemname)}; luaL_setmetatable(L, Item::CLASS_NAME); return 1; } } // anonymous namespace const struct luaL_Reg ItemFactory::LuaMethods[] = { {"createItem", ItemFactory_createItem}, {nullptr, nullptr} }; // // Default item size. // Might want this to be the same as a "tile size" on the map. // constexpr auto DEFAULT_ITEM_WIDTH = 36.0f; constexpr auto DEFAULT_ITEM_HEIGHT = 36.0f; ItemFactory::ItemFactory(ResourceManager& resMgr) : _resources { resMgr } { } /** * * Create an Item from the specified name. * */ ItemPtr ItemFactory::createItem(const std::string& name, const ItemCallbacks& callbacks) { std::string jsonFile = _resources.getFilename(fmt::format("items/{}.json", name)); if( !boost::filesystem::exists(jsonFile) ) { auto error = fmt::format("file '{}' not found", jsonFile); throw std::runtime_error(error); } std::ifstream file(jsonFile.c_str()); nl::json json; if(file.is_open()) { file >> json; } std::string textureFile = fmt::format("items/{}.png", name); sf::Texture* texture = _resources.cacheTexture(textureFile); // // By default, scale item image to tile size. // int width = texture->getSize().x; int height = texture->getSize().y; float scaleX = DEFAULT_ITEM_WIDTH / width; float scaleY = DEFAULT_ITEM_HEIGHT / height; // // Optionally allow for item author to specify // size and scale. // if( json.find("image-attr") != json.end()) { nl::json children = json["image-attr"]; if (children.find("width") != children.end() && children.find("height") != children.end() && children.find("scale-x") != children.end() && children.find("scale-y") != children.end()) { width = json["image-attr"]["width"]; height = json["image-attr"]["height"]; scaleX = json["image-attr"]["scale-x"]; scaleY = json["image-attr"]["scale-y"]; } } auto item = std::make_shared<Item>( name, *texture, sf::Vector2i{ width, height } ); item->setScale(scaleX, scaleY); if(json.find("name") != json.end()) { item->setName(json["name"]); } if(json.find("description") != json.end()) { item->setDescription(json["description"]); } if(json.find("obtainable") != json.end()) { item->setObtainable(json["obtainable"]); } item->callbacks = callbacks; return item; } } // namespace tt
22.900621
74
0.578248
zethon
14e02a116364ab8938c4efdf66d78a9f5a9b980b
4,357
cpp
C++
src/API/API.cpp
adityavaishampayan/micromouse_bfs
b9dfceb895f245a5c918505c7cf4b6d93e4ed192
[ "MIT" ]
null
null
null
src/API/API.cpp
adityavaishampayan/micromouse_bfs
b9dfceb895f245a5c918505c7cf4b6d93e4ed192
[ "MIT" ]
null
null
null
src/API/API.cpp
adityavaishampayan/micromouse_bfs
b9dfceb895f245a5c918505c7cf4b6d93e4ed192
[ "MIT" ]
null
null
null
#include "API.h" /** * @brief A funtion to return the width of the maze. * @return */ int API::mazeWidth() { std::cout << "mazeWidth" << std::endl; std::string response; std::cin >> response; return atoi(response.c_str()); } /** * @brief A funtion to return the width of the maze. * @return */ int API::mazeHeight() { std::cout << "mazeHeight" << std::endl; std::string response; std::cin >> response; return atoi(response.c_str()); } /** * @brief A funtion to check if there is a wall in front of the robot in the maze. * @return */ bool API::wallFront() { std::cout << "wallFront" << std::endl; std::string response; std::cin >> response; return response == "true"; } /** * @brief A funtion to check if there is a wall to the right of the robot in the maze. * @return */ bool API::wallRight() { std::cout << "wallRight" << std::endl; std::string response; std::cin >> response; return response == "true"; } /** * @brief A funtion to check if there is a wall to the left of the robot in the maze. * @return */ bool API::wallLeft() { std::cout << "wallLeft" << std::endl; std::string response; std::cin >> response; return response == "true"; } /** * @brief A funtion to move the robot forward by one cell. */ void API::moveForward() { std::cout << "moveForward" << std::endl; std::string response; std::cin >> response; if (response != "ack") { std::cerr << response << std::endl; throw; } } /** * @brief A function to turn the robot ninty degrees to the right in the same cell. */ void API::turnRight() { std::cout << "turnRight" << std::endl; std::string ack; std::cin >> ack; } /** * @brief A function to turn the robot ninty degrees to the left in the same cell. */ void API::turnLeft() { std::cout << "turnLeft" << std::endl; std::string ack; std::cin >> ack; } /** * @brief A function to display a wall at the given position in the maze. * @param x * @param y * @param direction */ void API::setWall(int x, int y, char direction) { std::cout << "setWall " << x << " " << y << " " << direction << std::endl; } /** * @brief A function to display a wall at the given position in the maze. * @param x * @param y * @param direction */ void API::clearWall(int x, int y, char direction) { std::cout << "clearWall " << x << " " << y << " " << direction << std::endl; } /** * @brief A function to set the color of the cell at the given position in the maze. * @param x * @param y * @param color */ void API::setColor(int x, int y, char color) { std::cout << "setColor " << x << " " << y << " " << color << std::endl; } /** * @brief A function to lear the color of the cell at the given position in the maze. * @param x * @param y */ void API::clearColor(int x, int y) { std::cout << "clearColor " << x << " " << y << std::endl; } /** * @brief A function to clear the color of all cells in the maze. */ void API::clearAllColor() { std::cout << "clearAllColor" << std::endl; } /** * @brief A function to set the text of the cell at the given position in the maze. * @param x * @param y * @param text */ void API::setText(int x, int y, const std::string& text) { std::cout << "setText " << x << " " << y << " " << text << std::endl; } /** * @brief A function to clear the text of the cell at the given position. * @param x * @param y */ void API::clearText(int x, int y) { std::cout << "clearText " << x << " " << y << std::endl; } /** * @brief A function clear the text of all cells in the maze. */ void API::clearAllText() { std::cout << "clearAllText" << std::endl; } /** * @brief A function to check whether the reset button is pressed or not. * @return */ bool API::wasReset() { std::cout << "wasReset" << std::endl; std::string response; std::cin >> response; return response == "true"; } /** * @brief A function to acknowledge the reset and allow the robot to move back to the start of the maze. */ void API::ackReset() { std::cout << "ackReset" << std::endl; std::string ack; std::cin >> ack; }
24.340782
105
0.564609
adityavaishampayan
14e0ecc6593bddabb738b8c9545f982121bb21fc
52
cpp
C++
src/endian.cpp
u3shit/stcm-editor
2bf6576ad4e86ef7cae602182b90cfe2246a1565
[ "WTFPL" ]
56
2016-03-20T19:44:55.000Z
2021-09-03T13:08:16.000Z
src/endian.cpp
u3shit/stcm-editor
2bf6576ad4e86ef7cae602182b90cfe2246a1565
[ "WTFPL" ]
23
2016-06-09T21:09:28.000Z
2021-05-10T10:46:18.000Z
src/endian.cpp
u3shit/stcm-editor
2bf6576ad4e86ef7cae602182b90cfe2246a1565
[ "WTFPL" ]
12
2016-09-12T11:03:15.000Z
2021-07-04T06:10:06.000Z
#include "endian.hpp" #include "endian.binding.hpp"
17.333333
29
0.75
u3shit
14e416931d3fc6af0f1df54769211162e8398e3a
4,771
cpp
C++
folly/test/UnicodeTest.cpp
facebookxx/folly
2da5b6427c302c34e72c4f0aedaa1d9ed892f6fe
[ "Apache-2.0" ]
1
2021-05-18T09:33:02.000Z
2021-05-18T09:33:02.000Z
folly/test/UnicodeTest.cpp
facebookxx/folly
2da5b6427c302c34e72c4f0aedaa1d9ed892f6fe
[ "Apache-2.0" ]
1
2021-05-26T00:37:20.000Z
2021-05-26T00:37:20.000Z
folly/test/UnicodeTest.cpp
facebookxx/folly
2da5b6427c302c34e72c4f0aedaa1d9ed892f6fe
[ "Apache-2.0" ]
1
2021-12-14T10:26:10.000Z
2021-12-14T10:26:10.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/Unicode.h> #include <initializer_list> #include <stdexcept> #include <folly/Range.h> #include <folly/portability/GTest.h> using folly::utf8ToCodePoint; void testValid(std::initializer_list<unsigned char> data, char32_t expected) { { const unsigned char* p = data.begin(); const unsigned char* e = data.end(); EXPECT_EQ(utf8ToCodePoint(p, e, /* skipOnError */ false), expected) << folly::StringPiece( (const char*)data.begin(), (const char*)data.end()); } { const unsigned char* p = data.begin(); const unsigned char* e = data.end(); EXPECT_EQ(utf8ToCodePoint(p, e, /* skipOnError */ true), expected) << folly::StringPiece( (const char*)data.begin(), (const char*)data.end()); } } void testInvalid(std::initializer_list<unsigned char> data) { { const unsigned char* p = data.begin(); const unsigned char* e = data.end(); EXPECT_THROW( utf8ToCodePoint(p, e, /* skipOnError */ false), std::runtime_error) << folly::StringPiece( (const char*)data.begin(), (const char*)data.end()); } { const unsigned char* p = data.begin(); const unsigned char* e = data.end(); EXPECT_EQ(utf8ToCodePoint(p, e, /* skipOnError */ true), 0xfffd) << folly::StringPiece( (const char*)data.begin(), (const char*)data.end()); } } TEST(InvalidUtf8ToCodePoint, rfc3629Overlong) { // https://tools.ietf.org/html/rfc3629 // Implementations of the decoding algorithm above MUST protect against // decoding invalid sequences. For instance, a naive implementation may // decode the overlong UTF-8 sequence C0 80 into the character U+0000 [...] // Decoding invalid sequences may have security consequences or cause other // problems. testInvalid({0xC0, 0x80}); } TEST(InvalidUtf8ToCodePoint, rfc3629SurrogatePair) { // https://tools.ietf.org/html/rfc3629 // Implementations of the decoding algorithm above MUST protect against // decoding invalid sequences. For instance, a naive implementation may // decode [...] the surrogate pair ED A1 8C ED BE B4 into U+233B4. // Decoding invalid sequences may have security consequences or cause other // problems. testInvalid({0xED, 0xA1, 0x8C, 0xED, 0xBE, 0xB4}); } TEST(InvalidUtf8ToCodePoint, MarkusKuhnSingleUTF16Surrogates) { // https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt // 5.1.1 U+D800 = ed a0 80 // 5.1.2 U+DB7F = ed ad bf // 5.1.3 U+DB80 = ed ae 80 // 5.1.4 U+DBFF = ed af bf // 5.1.5 U+DC00 = ed b0 80 // 5.1.6 U+DF80 = ed be 80 // 5.1.7 U+DFFF = ed bf bf testInvalid({0xed, 0xa0, 0x80}); testInvalid({0xed, 0xad, 0xbf}); testInvalid({0xed, 0xae, 0x80}); testInvalid({0xed, 0xaf, 0xbf}); testInvalid({0xed, 0xb0, 0x80}); testInvalid({0xed, 0xbe, 0x80}); testInvalid({0xed, 0xbf, 0xbf}); } TEST(InvalidUtf8ToCodePoint, MarkusKuhnPairedUTF16Surrogates) { // https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt // 5.2.1 U+D800 U+DC00 = ed a0 80 ed b0 80 // 5.2.2 U+D800 U+DFFF = ed a0 80 ed bf bf // 5.2.3 U+DB7F U+DC00 = ed ad bf ed b0 80 // 5.2.4 U+DB7F U+DFFF = ed ad bf ed bf bf // 5.2.5 U+DB80 U+DC00 = ed ae 80 ed b0 80 // 5.2.6 U+DB80 U+DFFF = ed ae 80 ed bf bf // 5.2.7 U+DBFF U+DC00 = ed af bf ed b0 80 // 5.2.8 U+DBFF U+DFFF = ed af bf ed bf bf testInvalid({0xed, 0xa0, 0x80, 0xed, 0xb0, 0x80}); testInvalid({0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf}); testInvalid({0xed, 0xad, 0xbf, 0xed, 0xb0, 0x80}); testInvalid({0xed, 0xad, 0xbf, 0xed, 0xbf, 0xbf}); testInvalid({0xed, 0xae, 0x80, 0xed, 0xb0, 0x80}); testInvalid({0xed, 0xae, 0x80, 0xed, 0xbf, 0xbf}); testInvalid({0xed, 0xaf, 0xbf, 0xed, 0xb0, 0x80}); testInvalid({0xed, 0xaf, 0xbf, 0xed, 0xbf, 0xbf}); } TEST(ValidUtf8ToCodePoint, FourCloverLeaf) { testValid({0xF0, 0x9F, 0x8D, 0x80}, 0x1F340); // u8"\U0001F340"; } TEST(InvalidUtf8ToCodePoint, FourCloverLeafAsSurrogates) { testInvalid({0xd8, 0x3c, 0xdf, 0x40}); // u8"\U0001F340"; } TEST(ValidUtf8ToCodePoint, LastCodePoint) { testValid({0xF4, 0x8F, 0xBF, 0xBF}, 0x10FFFF); // u8"\U0010FFFF"; }
36.419847
78
0.666317
facebookxx
14e549408580d37599d215c3be8c2bbe495ac395
349
cpp
C++
leetcode121.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode121.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
leetcode121.cpp
SJTUGavinLiu/Leetcodes
99d4010bc34e78d22e3c8b6436e4489a7d1338da
[ "MIT" ]
null
null
null
class Solution { public: int maxProfit(vector<int>& prices) { int Max = 0; int buy = INT_MIN; int sale = 0; for(auto price: prices) { if(-price > buy) buy = -price; if(buy + price > sale) sale = buy + price; } return sale; } };
19.388889
40
0.418338
SJTUGavinLiu
14e770757b4c2e2718dc9d8cf3d1dd3b3c8c34c3
637
cpp
C++
src/ButtonJoystick.cpp
stevendaniluk/SimRacingInputs
ca23999b9ed56acfc76c0e38ad4560476192cac9
[ "WTFPL" ]
null
null
null
src/ButtonJoystick.cpp
stevendaniluk/SimRacingInputs
ca23999b9ed56acfc76c0e38ad4560476192cac9
[ "WTFPL" ]
null
null
null
src/ButtonJoystick.cpp
stevendaniluk/SimRacingInputs
ca23999b9ed56acfc76c0e38ad4560476192cac9
[ "WTFPL" ]
null
null
null
#include <Arduino.h> #include "ButtonJoystick.h" ButtonJoystick::ButtonJoystick(Joystick_* joystick, uint8_t key, uint8_t pin, bool low_on = true) : ButtonInput::ButtonInput(pin, low_on) , joystick_(joystick) , key_(key) {} ButtonJoystick::ButtonJoystick(Joystick_* joystick, uint8_t key, uint8_t pin, int range_low, int range_high) : ButtonInput::ButtonInput(pin, range_low, range_high) , joystick_(joystick) , key_(key) {} void ButtonJoystick::send(bool pressed) const { #ifdef SIM_SERIAL_DEBUG Serial.print(key_); Serial.print(" state: "); Serial.println(pressed); #else joystick_->setButton(key_, pressed); #endif }
27.695652
108
0.748823
stevendaniluk
14e79150cb86102e088502d9aa01e3f9b95523ac
2,952
hpp
C++
qir/qat/ValidationPass/ValidationPassConfiguration.hpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/ValidationPass/ValidationPassConfiguration.hpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
qir/qat/ValidationPass/ValidationPassConfiguration.hpp
troelsfr/qat
55ba460b6be307fc2ac7e8143bf14d7e117da161
[ "MIT" ]
null
null
null
#pragma once // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "Commandline/ConfigurationManager.hpp" #include "QatTypes/QatTypes.hpp" #include <functional> #include <set> namespace microsoft { namespace quantum { struct OpcodeValue { String id{""}; String predicate{""}; OpcodeValue(String const& name, String const& fi = "") : id{name} , predicate{fi} { } OpcodeValue() = default; OpcodeValue(OpcodeValue&&) = default; OpcodeValue(OpcodeValue const&) = default; OpcodeValue& operator=(OpcodeValue&&) = default; OpcodeValue& operator=(OpcodeValue const&) = default; bool operator==(OpcodeValue const& other) const { return id == other.id && predicate == other.predicate; } }; } // namespace quantum } // namespace microsoft namespace std { template <> struct hash<microsoft::quantum::OpcodeValue> { size_t operator()(microsoft::quantum::OpcodeValue const& x) const { hash<std::string> hasher; return hasher(x.id + "." + x.predicate); } }; } // namespace std namespace microsoft { namespace quantum { class ValidationPassConfiguration { public: using Set = std::unordered_set<std::string>; using OpcodeSet = std::unordered_set<OpcodeValue>; // Setup and construction // ValidationPassConfiguration() = default; /// Setup function that adds the configuration flags to the ConfigurationManager. See the /// ConfigurationManager documentation for more details on how the setup process is implemented. void setup(ConfigurationManager& config); static ValidationPassConfiguration fromProfileName(String const& name); OpcodeSet const& allowedOpcodes() const; Set const& allowedExternalCallNames() const; bool allowInternalCalls() const; bool allowlistOpcodes() const; bool allowlistExternalCalls() const; bool allowlistPointerTypes() const; Set const& allowedPointerTypes() const; String profileName() const; private: void addAllowedExternalCall(String const& name); void addAllowedOpcode(String const& name); void addAllowedPointerType(String const& name); String profile_name_{"null"}; OpcodeSet opcodes_{}; Set external_calls_{}; Set allowed_pointer_types_{}; bool allowlist_opcodes_{true}; bool allowlist_external_calls_{true}; bool allow_internal_calls_{false}; bool allowlist_pointer_types_{false}; bool allow_primitive_return_{true}; bool allow_struct_return_{true}; bool allow_pointer_return_{true}; }; } // namespace quantum } // namespace microsoft
27.849057
104
0.631098
troelsfr
14e9189d89d5f3b2ce772f522dd64dda00ab0936
9,010
cpp
C++
LargeBarrelAnalysis/HitFinderTools.cpp
nenprio/j-pet-framework-examples
b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e
[ "Apache-2.0" ]
null
null
null
LargeBarrelAnalysis/HitFinderTools.cpp
nenprio/j-pet-framework-examples
b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e
[ "Apache-2.0" ]
1
2020-07-15T12:47:16.000Z
2020-07-15T12:47:16.000Z
LargeBarrelAnalysis/HitFinderTools.cpp
nenprio/j-pet-framework-examples
b76e8c289e91932a2e7bf30b19ab6fcaaa8d2d1e
[ "Apache-2.0" ]
null
null
null
/** * @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may find a copy of the License in the LICENCE file. * * 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 HitFinderTools.cpp */ using namespace std; #include "UniversalFileLoader.h" #include "HitFinderTools.h" #include <TMath.h> #include <vector> #include <cmath> #include <map> /** * Helper method for sotring signals in vector */ void HitFinderTools::sortByTime(vector<JPetPhysSignal>& sigVec) { sort(sigVec.begin(), sigVec.end(), [](const JPetPhysSignal & sig1, const JPetPhysSignal & sig2) { return sig1.getTime() < sig2.getTime(); } ); } /** * Method distributing Signals according to Scintillator they belong to */ map<int, vector<JPetPhysSignal>> HitFinderTools::getSignalsBySlot( const JPetTimeWindow* timeWindow, bool useCorrupts ){ map<int, vector<JPetPhysSignal>> signalSlotMap; if (!timeWindow) { WARNING("Pointer of Time Window object is not set, returning empty map"); return signalSlotMap; } const unsigned int nSignals = timeWindow->getNumberOfEvents(); for (unsigned int i = 0; i < nSignals; i++) { auto physSig = dynamic_cast<const JPetPhysSignal&>(timeWindow->operator[](i)); if(!useCorrupts && physSig.getRecoFlag() == JPetBaseSignal::Corrupted) { continue; } int slotID = physSig.getBarrelSlot().getID(); auto search = signalSlotMap.find(slotID); if (search == signalSlotMap.end()) { vector<JPetPhysSignal> tmp; tmp.push_back(physSig); signalSlotMap.insert(pair<int, vector<JPetPhysSignal>>(slotID, tmp)); } else { search->second.push_back(physSig); } } return signalSlotMap; } /** * Loop over all Scins invoking matching procedure */ vector<JPetHit> HitFinderTools::matchAllSignals( map<int, vector<JPetPhysSignal>>& allSignals, const map<unsigned int, vector<double>>& velocitiesMap, double timeDiffAB, int refDetScinId, JPetStatistics& stats, bool saveHistos ) { vector<JPetHit> allHits; for (auto& slotSigals : allSignals) { // Loop for Reference Detector ID if (slotSigals.first == refDetScinId) { for (auto refSignal : slotSigals.second) { auto refHit = createDummyRefDetHit(refSignal); allHits.push_back(refHit); } continue; } // Loop for other slots than reference one auto slotHits = matchSignals( slotSigals.second, velocitiesMap, timeDiffAB, stats, saveHistos ); allHits.insert(allHits.end(), slotHits.begin(), slotHits.end()); } return allHits; } /** * Method matching signals on the same Scintillator */ vector<JPetHit> HitFinderTools::matchSignals( vector<JPetPhysSignal>& slotSignals, const map<unsigned int, vector<double>>& velocitiesMap, double timeDiffAB, JPetStatistics& stats, bool saveHistos ) { vector<JPetHit> slotHits; vector<JPetPhysSignal> remainSignals; sortByTime(slotSignals); while (slotSignals.size() > 0) { auto physSig = slotSignals.at(0); if(slotSignals.size() == 1){ remainSignals.push_back(physSig); break; } for (unsigned int j = 1; j < slotSignals.size(); j++) { if (slotSignals.at(j).getTime() - physSig.getTime() < timeDiffAB) { if (physSig.getPM().getSide() != slotSignals.at(j).getPM().getSide()) { auto hit = createHit( physSig, slotSignals.at(j), velocitiesMap, stats, saveHistos ); slotHits.push_back(hit); slotSignals.erase(slotSignals.begin() + j); slotSignals.erase(slotSignals.begin() + 0); break; } else { if (j == slotSignals.size() - 1) { remainSignals.push_back(physSig); slotSignals.erase(slotSignals.begin() + 0); break; } else { continue; } } } else { remainSignals.push_back(physSig); slotSignals.erase(slotSignals.begin() + 0); break; } } } if(remainSignals.size()>0 && saveHistos){ stats.getHisto1D("remain_signals_per_scin") ->Fill((float)(remainSignals.at(0).getPM().getScin().getID()), remainSignals.size()); } return slotHits; } /** * Method for Hit creation - setting all fields, that make sense here */ JPetHit HitFinderTools::createHit( const JPetPhysSignal& signal1, const JPetPhysSignal& signal2, const map<unsigned int, vector<double>>& velocitiesMap, JPetStatistics& stats, bool saveHistos ) { JPetPhysSignal signalA; JPetPhysSignal signalB; if (signal1.getPM().getSide() == JPetPM::SideA) { signalA = signal1; signalB = signal2; } else { signalA = signal2; signalB = signal1; } auto radius = signalA.getPM().getBarrelSlot().getLayer().getRadius(); auto theta = TMath::DegToRad() * signalA.getPM().getBarrelSlot().getTheta(); auto velocity = UniversalFileLoader::getConfigurationParameter( velocitiesMap, getProperChannel(signalA) ); checkTheta(theta); JPetHit hit; hit.setSignalA(signalA); hit.setSignalB(signalB); hit.setTime((signalA.getTime() + signalB.getTime()) / 2.0); hit.setQualityOfTime(-1.0); hit.setTimeDiff(signalB.getTime() - signalA.getTime()); hit.setQualityOfTimeDiff(-1.0); hit.setEnergy(-1.0); hit.setQualityOfEnergy(-1.0); hit.setScintillator(signalA.getPM().getScin()); hit.setBarrelSlot(signalA.getPM().getBarrelSlot()); hit.setPosX(radius * cos(theta)); hit.setPosY(radius * sin(theta)); hit.setPosZ(velocity * hit.getTimeDiff() / 2000.0); if(signalA.getRecoFlag() == JPetBaseSignal::Good && signalB.getRecoFlag() == JPetBaseSignal::Good) { hit.setRecoFlag(JPetHit::Good); if(saveHistos) { stats.getHisto1D("good_vs_bad_hits")->Fill(1); stats.getHisto2D("time_diff_per_scin") ->Fill(hit.getTimeDiff(), (float)(hit.getScintillator().getID())); stats.getHisto2D("hit_pos_per_scin") ->Fill(hit.getPosZ(), (float)(hit.getScintillator().getID())); } } else if (signalA.getRecoFlag() == JPetBaseSignal::Corrupted || signalB.getRecoFlag() == JPetBaseSignal::Corrupted){ hit.setRecoFlag(JPetHit::Corrupted); if(saveHistos) { stats.getHisto1D("good_vs_bad_hits")->Fill(2); } } else { hit.setRecoFlag(JPetHit::Unknown); if(saveHistos) { stats.getHisto1D("good_vs_bad_hits")->Fill(3); } } return hit; } /** * Method for Hit creation in case of reference detector. * Setting only some necessary fields. */ JPetHit HitFinderTools::createDummyRefDetHit(const JPetPhysSignal& signalB) { JPetHit hit; hit.setSignalB(signalB); hit.setTime(signalB.getTime()); hit.setQualityOfTime(-1.0); hit.setTimeDiff(0.0); hit.setQualityOfTimeDiff(-1.0); hit.setEnergy(-1.0); hit.setQualityOfEnergy(-1.0); hit.setScintillator(signalB.getPM().getScin()); hit.setBarrelSlot(signalB.getPM().getBarrelSlot()); return hit; } /** * Helper method for getting TOMB channel */ int HitFinderTools::getProperChannel(const JPetPhysSignal& signal) { auto someSigCh = signal.getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrValue)[0]; return someSigCh.getTOMBChannel().getChannel(); } /** * Helper method for checking if theta is in radians */ void HitFinderTools::checkTheta(const double& theta) { if (theta > 2 * TMath::Pi()) { WARNING("Probably wrong values of Barrel Slot theta - conversion to radians failed. Check please."); } } /** * Calculation of the total TOT of the hit - Time over Threshold: * the sum of the TOTs on all of the thresholds (1-4) and on the both sides (A,B) */ double HitFinderTools::calculateTOT(const JPetHit& hit) { double tot = 0.0; auto sigALead = hit.getSignalA().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum); auto sigBLead = hit.getSignalB().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Leading, JPetRawSignal::ByThrNum); auto sigATrail = hit.getSignalA().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum); auto sigBTrail = hit.getSignalB().getRecoSignal().getRawSignal() .getPoints(JPetSigCh::Trailing, JPetRawSignal::ByThrNum); if (sigALead.size() > 0 && sigATrail.size() > 0){ for (unsigned i = 0; i < sigALead.size() && i < sigATrail.size(); i++){ tot += (sigATrail.at(i).getValue() - sigALead.at(i).getValue()); } } if (sigBLead.size() > 0 && sigBTrail.size() > 0){ for (unsigned i = 0; i < sigBLead.size() && i < sigBTrail.size(); i++){ tot += (sigBTrail.at(i).getValue() - sigBLead.at(i).getValue()); } } return tot; }
33.619403
104
0.681798
nenprio
14e9e47c065834ccf1e618fe1828066c4175e948
11,407
cpp
C++
libmetartc2/src/yangencoder/YangFfmpegEncoderMeta.cpp
zhoulipeng/metaRTC
c466cced24e99ee43132378ced0311036ddbbfa0
[ "MIT" ]
1
2022-01-20T03:07:07.000Z
2022-01-20T03:07:07.000Z
libmetartc2/src/yangencoder/YangFfmpegEncoderMeta.cpp
zhoulipeng/metaRTC
c466cced24e99ee43132378ced0311036ddbbfa0
[ "MIT" ]
null
null
null
libmetartc2/src/yangencoder/YangFfmpegEncoderMeta.cpp
zhoulipeng/metaRTC
c466cced24e99ee43132378ced0311036ddbbfa0
[ "MIT" ]
null
null
null
/* * YangFfmpegEncoderMeta.cpp * * Created on: 2020年9月26日 * Author: yang */ #include "YangFfmpegEncoderMeta.h" #include "YangVideoEncoderFfmpeg.h" #include <yangutil/sys/YangLog.h> #include <yangavutil/video/YangMeta.h> YangFfmpegEncoderMeta::YangFfmpegEncoderMeta() { #if Yang_Ffmpeg_UsingSo unloadLib(); #endif } YangFfmpegEncoderMeta::~YangFfmpegEncoderMeta() { #if Yang_Ffmpeg_UsingSo unloadLib(); m_lib.unloadObject(); m_lib1.unloadObject(); #endif } #if Yang_Ffmpeg_UsingSo void YangFfmpegEncoderMeta::loadLib() { yang_av_buffer_unref = (void (*)(AVBufferRef **buf)) m_lib1.loadFunction( "av_buffer_unref"); yang_av_hwframe_ctx_init = (int32_t (*)(AVBufferRef *ref)) m_lib1.loadFunction( "av_hwframe_ctx_init"); yang_av_frame_alloc = (AVFrame* (*)(void)) m_lib1.loadFunction( "av_frame_alloc"); yang_av_image_get_buffer_size = (int32_t (*)(enum AVPixelFormat pix_fmt, int32_t width, int32_t height, int32_t align)) m_lib1.loadFunction( "av_image_get_buffer_size"); yang_av_hwdevice_ctx_create = (int32_t (*)(AVBufferRef **device_ctx, enum AVHWDeviceType type, const char *device, AVDictionary *opts, int32_t flags)) m_lib1.loadFunction("av_hwdevice_ctx_create"); yang_av_hwframe_transfer_data = (int32_t (*)(AVFrame *dst, const AVFrame *src, int32_t flags)) m_lib1.loadFunction("av_hwframe_transfer_data"); yang_av_free = (void (*)(void *ptr)) m_lib1.loadFunction("av_free"); yang_av_frame_free = (void (*)(AVFrame **frame)) m_lib1.loadFunction( "av_frame_free"); yang_av_buffer_ref = (AVBufferRef* (*)(AVBufferRef *buf)) m_lib1.loadFunction( "av_buffer_ref"); yang_av_image_fill_arrays = (int32_t (*)(uint8_t *dst_data[4], int32_t dst_linesize[4], const uint8_t *src, enum AVPixelFormat pix_fmt, int32_t width, int32_t height, int32_t align)) m_lib1.loadFunction( "av_image_fill_arrays"); yang_av_hwframe_ctx_alloc = (AVBufferRef* (*)(AVBufferRef *device_ctx)) m_lib1.loadFunction( "av_hwframe_ctx_alloc"); yang_av_hwframe_get_buffer = (int32_t (*)(AVBufferRef *hwframe_ctx, AVFrame *frame, int32_t flags)) m_lib1.loadFunction( "av_hwframe_get_buffer"); yang_av_malloc = (void* (*)(size_t size)) m_lib1.loadFunction("av_malloc"); yang_avcodec_alloc_context3 = (AVCodecContext* (*)(const AVCodec *codec)) m_lib.loadFunction( "avcodec_alloc_context3"); yang_av_init_packet = (void (*)(AVPacket *pkt)) m_lib.loadFunction( "av_init_packet"); yang_avcodec_find_encoder_by_name = (AVCodec* (*)(const char *name)) m_lib.loadFunction( "avcodec_find_encoder_by_name"); yang_avcodec_open2 = (int32_t (*)(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)) m_lib.loadFunction("avcodec_open2"); yang_avcodec_send_frame = (int32_t (*)(AVCodecContext *avctx, const AVFrame *frame)) m_lib.loadFunction("avcodec_send_frame"); yang_avcodec_receive_packet = (int32_t (*)(AVCodecContext *avctx, AVPacket *avpkt)) m_lib.loadFunction("avcodec_receive_packet"); yang_avcodec_close = (int32_t (*)(AVCodecContext *avctx)) m_lib.loadFunction( "avcodec_close"); } void YangFfmpegEncoderMeta::unloadLib() { yang_av_hwframe_ctx_alloc = NULL; yang_av_hwframe_ctx_init = NULL; yang_av_buffer_unref = NULL; yang_avcodec_find_encoder_by_name = NULL; yang_av_hwdevice_ctx_create = NULL; yang_av_frame_alloc = NULL; yang_avcodec_open2 = NULL; yang_av_image_get_buffer_size = NULL; yang_av_malloc = NULL; yang_av_image_fill_arrays = NULL; yang_av_init_packet = NULL; yang_av_hwframe_get_buffer = NULL; yang_av_hwframe_transfer_data = NULL; yang_avcodec_send_frame = NULL; yang_avcodec_receive_packet = NULL; yang_av_frame_free = NULL; yang_avcodec_close = NULL; yang_av_free = NULL; } #endif #define HEX2BIN(a) (((a)&0x40)?((a)&0xf)+9:((a)&0xf)) //void ConvertYCbCr2BGR(uint8_t *pYUV,uint8_t *pBGR,int32_t iWidth,int32_t iHeight); //void ConvertRGB2YUV(int32_t w,int32_t h,uint8_t *bmp,uint8_t *yuv); //int32_t g_m_fx2=2; void YangFfmpegEncoderMeta::yang_find_next_start_code(YangVideoCodec pve,uint8_t *buf,int32_t bufLen,int32_t *vpsPos,int32_t *vpsLen,int32_t *spsPos,int32_t *spsLen,int32_t *ppsPos,int32_t *ppsLen) { int32_t i = 0; // printf("\n**********************extradate.....=%d\n",bufLen); // for(int32_t j=0;j<bufLen;j++) printf("%02x,",*(buf+j)); //printf("\n*************************************\n"); *spsPos=0;*ppsPos=0; if(pve==Yang_VED_265) { *vpsPos=0; while(i<bufLen-3){ if (buf[i] == 0 && buf[i + 1] == 0 &&buf[i + 2] == 0&& buf[i + 3] == 1){ *vpsPos=i+4; i+=4; break; } i++; } } while (i <bufLen-3) { if (buf[i] == 0 && buf[i + 1] == 0 &&buf[i + 2] == 0&& buf[i + 3] == 1){ if(pve==Yang_VED_265) *vpsLen=i-4; *spsPos=i+4; i+=4; break; } i++; } while (i <bufLen-3) { if (buf[i] == 0 && buf[i + 1] == 0 &&buf[i + 2] == 0&& buf[i + 3] == 1){ *spsLen=i-*spsPos; *ppsPos=i+4; *ppsLen=bufLen-*ppsPos; break; } i++; } } int32_t YangFfmpegEncoderMeta::set_hwframe_ctx(AVPixelFormat ctxformat,AVPixelFormat swformat,YangVideoInfo *yvp,AVCodecContext *ctx, AVBufferRef *hw_device_ctx,int32_t pwid,int32_t phei) { AVBufferRef *hw_frames_ref; AVHWFramesContext *frames_ctx = NULL; int32_t err = 0; int32_t ret=0; if (!(hw_frames_ref = yang_av_hwframe_ctx_alloc(hw_device_ctx))) { yang_error("Failed to create VAAPI frame context.\n"); return -1; } frames_ctx = (AVHWFramesContext*) (hw_frames_ref->data); frames_ctx->format = ctxformat; frames_ctx->sw_format = swformat; frames_ctx->width = pwid; frames_ctx->height = phei; frames_ctx->initial_pool_size = 0; if ((err = yang_av_hwframe_ctx_init(hw_frames_ref)) < 0) { yang_error("Failed to initialize VAAPI frame context.Error code: %d\n", ret); yang_av_buffer_unref(&hw_frames_ref); return err; } ctx->hw_frames_ctx = yang_av_buffer_ref(hw_frames_ref); ctx->hw_device_ctx = yang_av_buffer_ref(hw_device_ctx); // ctx->hwaccel_flags=1; if (!ctx->hw_frames_ctx) err = AVERROR(ENOMEM); yang_av_buffer_unref(&hw_frames_ref); return err; } enum AVPixelFormat get_hw_format22(AVCodecContext *ctx, const enum AVPixelFormat *pix_fmts) { if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Intel) return AV_PIX_FMT_VAAPI; if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Nvdia) return AV_PIX_FMT_CUDA; if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Android) return AV_PIX_FMT_MEDIACODEC; return AV_PIX_FMT_VAAPI; } void YangFfmpegEncoderMeta::yang_getSpsPps(YangH2645Conf *pconf, YangVideoInfo *p_yvp, YangVideoEncInfo *penc) { #if Yang_Ffmpeg_UsingSo m_lib.loadObject("libavcodec"); m_lib1.loadObject("libavutil"); loadLib(); #endif YangVideoCodec m_encoderType=(YangVideoCodec)p_yvp->videoEncoderType; YangVideoHwType m_hwType=(YangVideoHwType)p_yvp->videoEncHwType; AVCodec *m_codec=NULL; AVCodecContext *m_codecCtx = NULL; AVBufferRef *hw_device_ctx=NULL; //hevc_vaapi nvenc nvdec vdpau h264_nvenc if(m_encoderType==Yang_VED_264){ if(m_hwType==YangV_Hw_Intel) m_codec = yang_avcodec_find_encoder_by_name("h264_vaapi");//avcodec_find_encoder(AV_CODEC_ID_H264); if(m_hwType==YangV_Hw_Nvdia) m_codec = yang_avcodec_find_encoder_by_name("h264_nvenc"); if(m_hwType==YangV_Hw_Android) m_codec = yang_avcodec_find_encoder_by_name("h264_mediacodec"); }else if(m_encoderType==Yang_VED_265){ if(m_hwType==YangV_Hw_Intel) m_codec = yang_avcodec_find_encoder_by_name("hevc_vaapi"); if(m_hwType==YangV_Hw_Nvdia) m_codec = yang_avcodec_find_encoder_by_name("hevc_nvenc"); if(m_hwType==YangV_Hw_Android) m_codec = yang_avcodec_find_encoder_by_name("hevc_mediacodec"); } m_codecCtx = yang_avcodec_alloc_context3(m_codec); YangVideoEncoderFfmpeg::initParam(m_codecCtx,p_yvp,penc); m_codecCtx->get_format = get_hw_format22; // AV_PIX_FMT_NV12;//get_hw_format; int32_t ret=0; //AV_HWDEVICE_TYPE_CUDA YangVideoEncoderFfmpeg::g_hwType=(YangVideoHwType)p_yvp->videoEncHwType; if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Intel){ ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_VAAPI,"/dev/dri/renderD128", NULL, 0); m_codecCtx->pix_fmt = AV_PIX_FMT_VAAPI; }else if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Nvdia){ ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA,"CUDA", NULL, 0); m_codecCtx->pix_fmt = AV_PIX_FMT_CUDA; }else if(YangVideoEncoderFfmpeg::g_hwType==YangV_Hw_Android){ ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_MEDIACODEC,"MEDIACODEC", NULL, 0); m_codecCtx->pix_fmt = AV_PIX_FMT_MEDIACODEC; } //YangVideoEncoderFfmpeg::g_hwType=m_codecCtx->pix_fmt ; if(ret<0){ printf("\nhw create error!..ret=%d\n",ret); exit(1); } //ret = yang_av_hwdevice_ctx_create(&hw_device_ctx, AV_HWDEVICE_TYPE_CUDA,"CUDA", NULL, 0); //AV_PIX_FMT_NV12;//AV_PIX_FMT_VAAPI;AV_PIX_FMT_YUV420P;//AV_PIX_FMT_CUDA //AV_PIX_FMT_CUDA AVPixelFormat ctxformat,swformat; if(p_yvp->videoEncHwType==YangV_Hw_Intel) ctxformat = AV_PIX_FMT_VAAPI; if(p_yvp->videoEncHwType==YangV_Hw_Nvdia) ctxformat = AV_PIX_FMT_CUDA; if(p_yvp->videoEncHwType==YangV_Hw_Android) ctxformat = AV_PIX_FMT_MEDIACODEC; if(p_yvp->bitDepth==8) swformat = AV_PIX_FMT_NV12; if(p_yvp->bitDepth==10) swformat = AV_PIX_FMT_P010; if(p_yvp->bitDepth==16) swformat = AV_PIX_FMT_P016; if ((ret = set_hwframe_ctx(ctxformat,swformat,p_yvp,m_codecCtx, hw_device_ctx, p_yvp->outWidth, p_yvp->outHeight)) < 0) { printf("Failed to set hwframe context.\n"); //goto close; } m_codecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; ret = yang_avcodec_open2(m_codecCtx, m_codec, NULL); if (ret < 0){ printf("\navcodec_open2 failure................\n"); exit(1); } int32_t vpsPos=0,vpsLen=0; int32_t spsPos=0,ppsPos=0; int32_t spsLen=0,ppsLen=0; yang_find_next_start_code(m_encoderType,m_codecCtx->extradata,m_codecCtx->extradata_size,&vpsPos,&vpsLen,&spsPos,&spsLen,&ppsPos,&ppsLen); if(m_encoderType==Yang_VED_265) { pconf->vpsLen=vpsLen; memcpy(pconf->vps,m_codecCtx->extradata+vpsPos,vpsLen); //printf("\n**************vpsLen===%d...\n",pconf->vpsLen); //for(int32_t i=0;i<pconf->vpsLen;i++) printf("%02x,",pconf->vps[i]); } pconf->spsLen=spsLen; pconf->ppsLen=ppsLen; memcpy(pconf->sps,m_codecCtx->extradata+spsPos,spsLen); memcpy(pconf->pps,m_codecCtx->extradata+ppsPos,ppsLen); yang_av_buffer_unref(&hw_device_ctx); if (m_codecCtx){ yang_avcodec_close(m_codecCtx); yang_av_free(m_codecCtx); } m_codecCtx = NULL; } //Conf264 t_conf264; void YangFfmpegEncoderMeta::yang_initVmd(YangVideoMeta *p_vmd, YangVideoInfo *p_yvp, YangVideoEncInfo *penc) { if (!p_vmd->isInit) { yang_getSpsPps(&p_vmd->mp4Meta, p_yvp,penc); if(p_yvp->videoEncoderType==Yang_VED_264) yang_getConfig_Flv_H264(&p_vmd->mp4Meta, p_vmd->livingMeta.buffer,&p_vmd->livingMeta.bufLen); if(p_yvp->videoEncoderType==Yang_VED_265) yang_getConfig_Flv_H265(&p_vmd->mp4Meta, p_vmd->livingMeta.buffer,&p_vmd->livingMeta.bufLen); // yang_getH265Config_Flv(&p_vmd->mp4Meta, p_vmd->flvMeta.buffer, &p_vmd->flvMeta.bufLen); p_vmd->isInit = 1; } }
39.470588
197
0.721048
zhoulipeng
14eac644e16c9ef95f3c39eb91d37e7a2eb98a1e
18,787
cpp
C++
Core/third_party/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp
InfiniteSynthesis/lynx-native
022e277ee6767f5b668269a17b1679072cf7c3d6
[ "MIT" ]
677
2017-09-23T16:03:12.000Z
2022-03-26T08:32:10.000Z
Core/third_party/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp
InfiniteSynthesis/lynx-native
022e277ee6767f5b668269a17b1679072cf7c3d6
[ "MIT" ]
3
2018-06-11T02:04:02.000Z
2020-04-24T09:26:05.000Z
Core/third_party/JavaScriptCore/dfg/DFGOSRExitCompiler64.cpp
InfiniteSynthesis/lynx-native
022e277ee6767f5b668269a17b1679072cf7c3d6
[ "MIT" ]
92
2017-09-21T14:21:27.000Z
2022-03-25T13:29:42.000Z
/* * Copyright (C) 2011, 2013-2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "DFGOSRExitCompiler.h" #if ENABLE(DFG_JIT) && USE(JSVALUE64) #include "DFGOperations.h" #include "DFGOSRExitCompilerCommon.h" #include "DFGSpeculativeJIT.h" #include "JSCInlines.h" #include "VirtualRegister.h" #include <wtf/DataLog.h> namespace JSC { namespace DFG { void OSRExitCompiler::compileExit(VM& vm, const OSRExit& exit, const Operands<ValueRecovery>& operands, SpeculationRecovery* recovery) { m_jit.jitAssertTagsInPlace(); // Pro-forma stuff. if (Options::printEachOSRExit()) { SpeculationFailureDebugInfo* debugInfo = new SpeculationFailureDebugInfo; debugInfo->codeBlock = m_jit.codeBlock(); debugInfo->kind = exit.m_kind; debugInfo->bytecodeOffset = exit.m_codeOrigin.bytecodeIndex; m_jit.debugCall(vm, debugOperationPrintSpeculationFailure, debugInfo); } // Perform speculation recovery. This only comes into play when an operation // starts mutating state before verifying the speculation it has already made. if (recovery) { switch (recovery->type()) { case SpeculativeAdd: m_jit.sub32(recovery->src(), recovery->dest()); m_jit.or64(GPRInfo::tagTypeNumberRegister, recovery->dest()); break; case SpeculativeAddImmediate: m_jit.sub32(AssemblyHelpers::Imm32(recovery->immediate()), recovery->dest()); m_jit.or64(GPRInfo::tagTypeNumberRegister, recovery->dest()); break; case BooleanSpeculationCheck: m_jit.xor64(AssemblyHelpers::TrustedImm32(static_cast<int32_t>(ValueFalse)), recovery->dest()); break; default: break; } } // Refine some array and/or value profile, if appropriate. if (!!exit.m_jsValueSource) { if (exit.m_kind == BadCache || exit.m_kind == BadIndexingType) { // If the instruction that this originated from has an array profile, then // refine it. If it doesn't, then do nothing. The latter could happen for // hoisted checks, or checks emitted for operations that didn't have array // profiling - either ops that aren't array accesses at all, or weren't // known to be array acceses in the bytecode. The latter case is a FIXME // while the former case is an outcome of a CheckStructure not knowing why // it was emitted (could be either due to an inline cache of a property // property access, or due to an array profile). CodeOrigin codeOrigin = exit.m_codeOriginForExitProfile; if (ArrayProfile* arrayProfile = m_jit.baselineCodeBlockFor(codeOrigin)->getArrayProfile(codeOrigin.bytecodeIndex)) { GPRReg usedRegister; if (exit.m_jsValueSource.isAddress()) usedRegister = exit.m_jsValueSource.base(); else usedRegister = exit.m_jsValueSource.gpr(); GPRReg scratch1; GPRReg scratch2; scratch1 = AssemblyHelpers::selectScratchGPR(usedRegister); scratch2 = AssemblyHelpers::selectScratchGPR(usedRegister, scratch1); if (isARM64()) { m_jit.pushToSave(scratch1); m_jit.pushToSave(scratch2); } else { m_jit.push(scratch1); m_jit.push(scratch2); } GPRReg value; if (exit.m_jsValueSource.isAddress()) { value = scratch1; m_jit.loadPtr(AssemblyHelpers::Address(exit.m_jsValueSource.asAddress()), value); } else value = exit.m_jsValueSource.gpr(); m_jit.load32(AssemblyHelpers::Address(value, JSCell::structureIDOffset()), scratch1); m_jit.store32(scratch1, arrayProfile->addressOfLastSeenStructureID()); m_jit.load8(AssemblyHelpers::Address(value, JSCell::indexingTypeAndMiscOffset()), scratch1); m_jit.move(AssemblyHelpers::TrustedImm32(1), scratch2); m_jit.lshift32(scratch1, scratch2); m_jit.or32(scratch2, AssemblyHelpers::AbsoluteAddress(arrayProfile->addressOfArrayModes())); if (isARM64()) { m_jit.popToRestore(scratch2); m_jit.popToRestore(scratch1); } else { m_jit.pop(scratch2); m_jit.pop(scratch1); } } } if (MethodOfGettingAValueProfile profile = exit.m_valueProfile) { if (exit.m_jsValueSource.isAddress()) { // We can't be sure that we have a spare register. So use the tagTypeNumberRegister, // since we know how to restore it. m_jit.load64(AssemblyHelpers::Address(exit.m_jsValueSource.asAddress()), GPRInfo::tagTypeNumberRegister); profile.emitReportValue(m_jit, JSValueRegs(GPRInfo::tagTypeNumberRegister)); m_jit.move(AssemblyHelpers::TrustedImm64(TagTypeNumber), GPRInfo::tagTypeNumberRegister); } else profile.emitReportValue(m_jit, JSValueRegs(exit.m_jsValueSource.gpr())); } } // What follows is an intentionally simple OSR exit implementation that generates // fairly poor code but is very easy to hack. In particular, it dumps all state that // needs conversion into a scratch buffer so that in step 6, where we actually do the // conversions, we know that all temp registers are free to use and the variable is // definitely in a well-known spot in the scratch buffer regardless of whether it had // originally been in a register or spilled. This allows us to decouple "where was // the variable" from "how was it represented". Consider that the // Int32DisplacedInJSStack recovery: it tells us that the value is in a // particular place and that that place holds an unboxed int32. We have two different // places that a value could be (displaced, register) and a bunch of different // ways of representing a value. The number of recoveries is two * a bunch. The code // below means that we have to have two + a bunch cases rather than two * a bunch. // Once we have loaded the value from wherever it was, the reboxing is the same // regardless of its location. Likewise, before we do the reboxing, the way we get to // the value (i.e. where we load it from) is the same regardless of its type. Because // the code below always dumps everything into a scratch buffer first, the two // questions become orthogonal, which simplifies adding new types and adding new // locations. // // This raises the question: does using such a suboptimal implementation of OSR exit, // where we always emit code to dump all state into a scratch buffer only to then // dump it right back into the stack, hurt us in any way? The asnwer is that OSR exits // are rare. Our tiering strategy ensures this. This is because if an OSR exit is // taken more than ~100 times, we jettison the DFG code block along with all of its // exits. It is impossible for an OSR exit - i.e. the code we compile below - to // execute frequently enough for the codegen to matter that much. It probably matters // enough that we don't want to turn this into some super-slow function call, but so // long as we're generating straight-line code, that code can be pretty bad. Also // because we tend to exit only along one OSR exit from any DFG code block - that's an // empirical result that we're extremely confident about - the code size of this // doesn't matter much. Hence any attempt to optimize the codegen here is just purely // harmful to the system: it probably won't reduce either net memory usage or net // execution time. It will only prevent us from cleanly decoupling "where was the // variable" from "how was it represented", which will make it more difficult to add // features in the future and it will make it harder to reason about bugs. // Save all state from GPRs into the scratch buffer. ScratchBuffer* scratchBuffer = vm.scratchBufferForSize(sizeof(EncodedJSValue) * operands.size()); EncodedJSValue* scratch = scratchBuffer ? static_cast<EncodedJSValue*>(scratchBuffer->dataBuffer()) : 0; for (size_t index = 0; index < operands.size(); ++index) { const ValueRecovery& recovery = operands[index]; switch (recovery.technique()) { case InGPR: case UnboxedInt32InGPR: case UnboxedInt52InGPR: case UnboxedStrictInt52InGPR: case UnboxedCellInGPR: m_jit.store64(recovery.gpr(), scratch + index); break; default: break; } } // And voila, all GPRs are free to reuse. // Save all state from FPRs into the scratch buffer. for (size_t index = 0; index < operands.size(); ++index) { const ValueRecovery& recovery = operands[index]; switch (recovery.technique()) { case UnboxedDoubleInFPR: case InFPR: m_jit.move(AssemblyHelpers::TrustedImmPtr(scratch + index), GPRInfo::regT0); m_jit.storeDouble(recovery.fpr(), MacroAssembler::Address(GPRInfo::regT0)); break; default: break; } } // Now, all FPRs are also free. // Save all state from the stack into the scratch buffer. For simplicity we // do this even for state that's already in the right place on the stack. // It makes things simpler later. for (size_t index = 0; index < operands.size(); ++index) { const ValueRecovery& recovery = operands[index]; switch (recovery.technique()) { case DisplacedInJSStack: case CellDisplacedInJSStack: case BooleanDisplacedInJSStack: case Int32DisplacedInJSStack: case DoubleDisplacedInJSStack: case Int52DisplacedInJSStack: case StrictInt52DisplacedInJSStack: m_jit.load64(AssemblyHelpers::addressFor(recovery.virtualRegister()), GPRInfo::regT0); m_jit.store64(GPRInfo::regT0, scratch + index); break; default: break; } } // Need to ensure that the stack pointer accounts for the worst-case stack usage at exit. This // could toast some stack that the DFG used. We need to do it before storing to stack offsets // used by baseline. m_jit.addPtr( CCallHelpers::TrustedImm32( -m_jit.codeBlock()->jitCode()->dfgCommon()->requiredRegisterCountForExit * sizeof(Register)), CCallHelpers::framePointerRegister, CCallHelpers::stackPointerRegister); // Restore the DFG callee saves and then save the ones the baseline JIT uses. m_jit.emitRestoreCalleeSaves(); m_jit.emitSaveCalleeSavesFor(m_jit.baselineCodeBlock()); // The tag registers are needed to materialize recoveries below. m_jit.emitMaterializeTagCheckRegisters(); if (exit.isExceptionHandler()) m_jit.copyCalleeSavesToVMEntryFrameCalleeSavesBuffer(vm); // Do all data format conversions and store the results into the stack. for (size_t index = 0; index < operands.size(); ++index) { const ValueRecovery& recovery = operands[index]; VirtualRegister reg = operands.virtualRegisterForIndex(index); if (reg.isLocal() && reg.toLocal() < static_cast<int>(m_jit.baselineCodeBlock()->calleeSaveSpaceAsVirtualRegisters())) continue; int operand = reg.offset(); switch (recovery.technique()) { case InGPR: case UnboxedCellInGPR: case DisplacedInJSStack: case CellDisplacedInJSStack: case BooleanDisplacedInJSStack: case InFPR: m_jit.load64(scratch + index, GPRInfo::regT0); m_jit.store64(GPRInfo::regT0, AssemblyHelpers::addressFor(operand)); break; case UnboxedInt32InGPR: case Int32DisplacedInJSStack: m_jit.load64(scratch + index, GPRInfo::regT0); m_jit.zeroExtend32ToPtr(GPRInfo::regT0, GPRInfo::regT0); m_jit.or64(GPRInfo::tagTypeNumberRegister, GPRInfo::regT0); m_jit.store64(GPRInfo::regT0, AssemblyHelpers::addressFor(operand)); break; case UnboxedInt52InGPR: case Int52DisplacedInJSStack: m_jit.load64(scratch + index, GPRInfo::regT0); m_jit.rshift64( AssemblyHelpers::TrustedImm32(JSValue::int52ShiftAmount), GPRInfo::regT0); m_jit.boxInt52(GPRInfo::regT0, GPRInfo::regT0, GPRInfo::regT1, FPRInfo::fpRegT0); m_jit.store64(GPRInfo::regT0, AssemblyHelpers::addressFor(operand)); break; case UnboxedStrictInt52InGPR: case StrictInt52DisplacedInJSStack: m_jit.load64(scratch + index, GPRInfo::regT0); m_jit.boxInt52(GPRInfo::regT0, GPRInfo::regT0, GPRInfo::regT1, FPRInfo::fpRegT0); m_jit.store64(GPRInfo::regT0, AssemblyHelpers::addressFor(operand)); break; case UnboxedDoubleInFPR: case DoubleDisplacedInJSStack: m_jit.move(AssemblyHelpers::TrustedImmPtr(scratch + index), GPRInfo::regT0); m_jit.loadDouble(MacroAssembler::Address(GPRInfo::regT0), FPRInfo::fpRegT0); m_jit.purifyNaN(FPRInfo::fpRegT0); m_jit.boxDouble(FPRInfo::fpRegT0, GPRInfo::regT0); m_jit.store64(GPRInfo::regT0, AssemblyHelpers::addressFor(operand)); break; case Constant: m_jit.store64( AssemblyHelpers::TrustedImm64(JSValue::encode(recovery.constant())), AssemblyHelpers::addressFor(operand)); break; case DirectArgumentsThatWereNotCreated: case ClonedArgumentsThatWereNotCreated: // Don't do this, yet. break; default: RELEASE_ASSERT_NOT_REACHED(); break; } } // Now that things on the stack are recovered, do the arguments recovery. We assume that arguments // recoveries don't recursively refer to each other. But, we don't try to assume that they only // refer to certain ranges of locals. Hence why we need to do this here, once the stack is sensible. // Note that we also roughly assume that the arguments might still be materialized outside of its // inline call frame scope - but for now the DFG wouldn't do that. emitRestoreArguments(operands); // Adjust the old JIT's execute counter. Since we are exiting OSR, we know // that all new calls into this code will go to the new JIT, so the execute // counter only affects call frames that performed OSR exit and call frames // that were still executing the old JIT at the time of another call frame's // OSR exit. We want to ensure that the following is true: // // (a) Code the performs an OSR exit gets a chance to reenter optimized // code eventually, since optimized code is faster. But we don't // want to do such reentery too aggressively (see (c) below). // // (b) If there is code on the call stack that is still running the old // JIT's code and has never OSR'd, then it should get a chance to // perform OSR entry despite the fact that we've exited. // // (c) Code the performs an OSR exit should not immediately retry OSR // entry, since both forms of OSR are expensive. OSR entry is // particularly expensive. // // (d) Frequent OSR failures, even those that do not result in the code // running in a hot loop, result in recompilation getting triggered. // // To ensure (c), we'd like to set the execute counter to // counterValueForOptimizeAfterWarmUp(). This seems like it would endanger // (a) and (b), since then every OSR exit would delay the opportunity for // every call frame to perform OSR entry. Essentially, if OSR exit happens // frequently and the function has few loops, then the counter will never // become non-negative and OSR entry will never be triggered. OSR entry // will only happen if a loop gets hot in the old JIT, which does a pretty // good job of ensuring (a) and (b). But that doesn't take care of (d), // since each speculation failure would reset the execute counter. // So we check here if the number of speculation failures is significantly // larger than the number of successes (we want 90% success rate), and if // there have been a large enough number of failures. If so, we set the // counter to 0; otherwise we set the counter to // counterValueForOptimizeAfterWarmUp(). handleExitCounts(m_jit, exit); // Reify inlined call frames. reifyInlinedCallFrames(m_jit, exit); // And finish. adjustAndJumpToTarget(vm, m_jit, exit); } } } // namespace JSC::DFG #endif // ENABLE(DFG_JIT) && USE(JSVALUE64)
47.085213
134
0.652792
InfiniteSynthesis
14eacd949b434e2a6dba2aae117bb7d6bbec8b0a
3,836
cxx
C++
vtkm/filter/vector_analysis/DotProduct.cxx
Kitware/vtk-m
b24a878f72b288d69c9da8c7ac33f08db6d39ba9
[ "BSD-3-Clause" ]
null
null
null
vtkm/filter/vector_analysis/DotProduct.cxx
Kitware/vtk-m
b24a878f72b288d69c9da8c7ac33f08db6d39ba9
[ "BSD-3-Clause" ]
null
null
null
vtkm/filter/vector_analysis/DotProduct.cxx
Kitware/vtk-m
b24a878f72b288d69c9da8c7ac33f08db6d39ba9
[ "BSD-3-Clause" ]
null
null
null
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ #include <vtkm/cont/ErrorFilterExecution.h> #include <vtkm/filter/vector_analysis/DotProduct.h> #include <vtkm/worklet/WorkletMapField.h> namespace // anonymous namespace making worklet::DotProduct internal to this .cxx { struct DotProductWorklet : vtkm::worklet::WorkletMapField { using ControlSignature = void(FieldIn, FieldIn, FieldOut); template <typename T1, typename T2, typename T3> VTKM_EXEC void operator()(const T1& v1, const T2& v2, T3& outValue) const { VTKM_ASSERT(v1.GetNumberOfComponents() == v2.GetNumberOfComponents()); outValue = v1[0] * v2[0]; for (vtkm::IdComponent i = 1; i < v1.GetNumberOfComponents(); ++i) { outValue += v1[i] * v2[i]; } } }; template <typename PrimaryArrayType> vtkm::cont::UnknownArrayHandle DoDotProduct(const PrimaryArrayType& primaryArray, const vtkm::cont::Field& secondaryField) { using T = typename PrimaryArrayType::ValueType::ComponentType; vtkm::cont::Invoker invoke; vtkm::cont::ArrayHandle<T> outputArray; if (secondaryField.GetData().IsBaseComponentType<T>()) { invoke(DotProductWorklet{}, primaryArray, secondaryField.GetData().ExtractArrayFromComponents<T>(), outputArray); } else { // Data types of primary and secondary array do not match. Rather than try to replicate every // possibility, get the secondary array as a FloatDefault. vtkm::cont::UnknownArrayHandle castSecondaryArray = secondaryField.GetDataAsDefaultFloat(); invoke(DotProductWorklet{}, primaryArray, castSecondaryArray.ExtractArrayFromComponents<vtkm::FloatDefault>(), outputArray); } return outputArray; } } // anonymous namespace namespace vtkm { namespace filter { namespace vector_analysis { VTKM_CONT DotProduct::DotProduct() { this->SetOutputFieldName("dotproduct"); } VTKM_CONT vtkm::cont::DataSet DotProduct::DoExecute(const vtkm::cont::DataSet& inDataSet) { vtkm::cont::Field primaryField = this->GetFieldFromDataSet(0, inDataSet); vtkm::cont::UnknownArrayHandle primaryArray = primaryField.GetData(); vtkm::cont::Field secondaryField = this->GetFieldFromDataSet(1, inDataSet); if (primaryArray.GetNumberOfComponentsFlat() != secondaryField.GetData().GetNumberOfComponentsFlat()) { throw vtkm::cont::ErrorFilterExecution( "Primary and secondary arrays of DotProduct filter have different number of components."); } vtkm::cont::UnknownArrayHandle outArray; if (primaryArray.IsBaseComponentType<vtkm::Float32>()) { outArray = DoDotProduct(primaryArray.ExtractArrayFromComponents<vtkm::Float32>(), secondaryField); } else if (primaryArray.IsBaseComponentType<vtkm::Float64>()) { outArray = DoDotProduct(primaryArray.ExtractArrayFromComponents<vtkm::Float64>(), secondaryField); } else { primaryArray = primaryField.GetDataAsDefaultFloat(); outArray = DoDotProduct(primaryArray.ExtractArrayFromComponents<vtkm::FloatDefault>(), secondaryField); } return this->CreateResultField(inDataSet, this->GetOutputFieldName(), this->GetFieldFromDataSet(inDataSet).GetAssociation(), outArray); } } // namespace vector_analysis } // namespace filter } // namespace vtkm
31.966667
98
0.67414
Kitware
14eb26ca8cef187940b640d6857f6d548271a543
682
hpp
C++
source/forge/vulkan/device.hpp
aegooby/forge
972e811ef7e454c2a862cc575fd4355a84a83ad0
[ "Apache-2.0" ]
null
null
null
source/forge/vulkan/device.hpp
aegooby/forge
972e811ef7e454c2a862cc575fd4355a84a83ad0
[ "Apache-2.0" ]
null
null
null
source/forge/vulkan/device.hpp
aegooby/forge
972e811ef7e454c2a862cc575fd4355a84a83ad0
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../__common.hpp" #include "common.hpp" namespace forge { namespace vulkan { class device { private: class context& context; public: struct queue { std::uint32_t index = ~0u; vk::Queue queue; }; /** @brief Represents the GPU used. */ vk::PhysicalDevice physical; /** @brief Interface for physical device(s). */ vk::UniqueDevice logical; struct queues { queue graphics; queue present; bool same(); std::vector<std::uint32_t> indices(); } queues; device(class context&); void start(); }; } // namespace vulkan } // namespace forge
17.487179
51
0.576246
aegooby
14eb57e668f98ee99ce110ba47c98e3868a76913
19,431
cc
C++
components/sync_sessions/session_store.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/sync_sessions/session_store.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/sync_sessions/session_store.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_sessions/session_store.h" #include <stdint.h> #include <algorithm> #include <set> #include <utility> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/pickle.h" #include "base/strings/stringprintf.h" #include "base/trace_event/trace_event.h" #include "components/sync/base/time.h" #include "components/sync/model/entity_change.h" #include "components/sync/model/metadata_batch.h" #include "components/sync/model/mutable_data_batch.h" #include "components/sync/protocol/model_type_state.pb.h" #include "components/sync/protocol/sync.pb.h" #include "components/sync_device_info/local_device_info_util.h" #include "components/sync_sessions/session_sync_prefs.h" #include "components/sync_sessions/sync_sessions_client.h" namespace sync_sessions { namespace { using sync_pb::SessionSpecifics; using syncer::MetadataChangeList; using syncer::ModelTypeStore; std::string TabNodeIdToClientTag(const std::string& session_tag, int tab_node_id) { CHECK_GT(tab_node_id, TabNodePool::kInvalidTabNodeID); return base::StringPrintf("%s %d", session_tag.c_str(), tab_node_id); } std::string EncodeStorageKey(const std::string& session_tag, int tab_node_id) { base::Pickle pickle; pickle.WriteString(session_tag); pickle.WriteInt(tab_node_id); return std::string(static_cast<const char*>(pickle.data()), pickle.size()); } bool DecodeStorageKey(const std::string& storage_key, std::string* session_tag, int* tab_node_id) { base::Pickle pickle(storage_key.c_str(), storage_key.size()); base::PickleIterator iter(pickle); if (!iter.ReadString(session_tag)) { return false; } if (!iter.ReadInt(tab_node_id)) { return false; } return true; } std::unique_ptr<syncer::EntityData> MoveToEntityData( const std::string& client_name, SessionSpecifics* specifics) { auto entity_data = std::make_unique<syncer::EntityData>(); entity_data->name = client_name; if (specifics->has_header()) { entity_data->name += " (header)"; } else if (specifics->has_tab()) { entity_data->name += base::StringPrintf(" (tab node %d)", specifics->tab_node_id()); } entity_data->specifics.mutable_session()->Swap(specifics); return entity_data; } std::string GetSessionTagWithPrefs(const std::string& cache_guid, SessionSyncPrefs* sync_prefs) { DCHECK(sync_prefs); // If a legacy GUID exists, keep honoring it. const std::string persisted_guid = sync_prefs->GetLegacySyncSessionsGUID(); if (!persisted_guid.empty()) { DVLOG(1) << "Restoring persisted session sync guid: " << persisted_guid; return persisted_guid; } DVLOG(1) << "Using sync cache guid as session sync guid: " << cache_guid; return cache_guid; } void ForwardError(syncer::OnceModelErrorHandler error_handler, const base::Optional<syncer::ModelError>& error) { if (error) { std::move(error_handler).Run(*error); } } // Parses the content of |record_list| into |*initial_data|. The output // parameters are first for binding purposes. base::Optional<syncer::ModelError> ParseInitialDataOnBackendSequence( std::map<std::string, sync_pb::SessionSpecifics>* initial_data, std::string* session_name, std::unique_ptr<ModelTypeStore::RecordList> record_list) { DCHECK(initial_data); DCHECK(initial_data->empty()); DCHECK(record_list); for (ModelTypeStore::Record& record : *record_list) { const std::string& storage_key = record.id; SessionSpecifics specifics; if (storage_key.empty() || !specifics.ParseFromString(std::move(record.value))) { DVLOG(1) << "Ignoring corrupt database entry with key: " << storage_key; continue; } (*initial_data)[storage_key] = std::move(specifics); } *session_name = syncer::GetPersonalizableDeviceNameBlocking(); return base::nullopt; } } // namespace struct SessionStore::Builder { SyncSessionsClient* sessions_client = nullptr; OpenCallback callback; SessionInfo local_session_info; std::unique_ptr<syncer::ModelTypeStore> underlying_store; std::unique_ptr<syncer::MetadataBatch> metadata_batch; std::map<std::string, sync_pb::SessionSpecifics> initial_data; }; // static void SessionStore::Open( const std::string& cache_guid, SyncSessionsClient* sessions_client, OpenCallback callback) { DCHECK(sessions_client); DVLOG(1) << "Opening session store"; auto builder = std::make_unique<Builder>(); builder->sessions_client = sessions_client; builder->callback = std::move(callback); builder->local_session_info.device_type = syncer::GetLocalDeviceType(); builder->local_session_info.session_tag = GetSessionTagWithPrefs( cache_guid, sessions_client->GetSessionSyncPrefs()); sessions_client->GetStoreFactory().Run( syncer::SESSIONS, base::BindOnce(&OnStoreCreated, std::move(builder))); } SessionStore::WriteBatch::WriteBatch( std::unique_ptr<ModelTypeStore::WriteBatch> batch, CommitCallback commit_cb, syncer::OnceModelErrorHandler error_handler, SyncedSessionTracker* session_tracker) : batch_(std::move(batch)), commit_cb_(std::move(commit_cb)), error_handler_(std::move(error_handler)), session_tracker_(session_tracker) { DCHECK(batch_); DCHECK(commit_cb_); DCHECK(error_handler_); DCHECK(session_tracker_); } SessionStore::WriteBatch::~WriteBatch() { DCHECK(!batch_) << "Destructed without prior commit"; } std::string SessionStore::WriteBatch::PutAndUpdateTracker( const sync_pb::SessionSpecifics& specifics, base::Time modification_time) { UpdateTrackerWithSpecifics(specifics, modification_time, session_tracker_); return PutWithoutUpdatingTracker(specifics); } std::vector<std::string> SessionStore::WriteBatch::DeleteForeignEntityAndUpdateTracker( const std::string& storage_key) { std::string session_tag; int tab_node_id; bool success = DecodeStorageKey(storage_key, &session_tag, &tab_node_id); DCHECK(success); DCHECK_NE(session_tag, session_tracker_->GetLocalSessionTag()); std::vector<std::string> deleted_storage_keys; deleted_storage_keys.push_back(storage_key); if (tab_node_id == TabNodePool::kInvalidTabNodeID) { // Removal of a foreign header entity cascades the deletion of all tabs in // the same session too. for (int cascading_tab_node_id : session_tracker_->LookupTabNodeIds(session_tag)) { std::string tab_storage_key = GetTabStorageKey(session_tag, cascading_tab_node_id); // Note that DeleteForeignSession() below takes care of removing all tabs // from the tracker, so no DeleteForeignTab() needed. batch_->DeleteData(tab_storage_key); deleted_storage_keys.push_back(std::move(tab_storage_key)); } // Delete session itself. session_tracker_->DeleteForeignSession(session_tag); } else { // Removal of a foreign tab entity. session_tracker_->DeleteForeignTab(session_tag, tab_node_id); } batch_->DeleteData(storage_key); return deleted_storage_keys; } std::string SessionStore::WriteBatch::PutWithoutUpdatingTracker( const sync_pb::SessionSpecifics& specifics) { DCHECK(AreValidSpecifics(specifics)); const std::string storage_key = GetStorageKey(specifics); batch_->WriteData(storage_key, specifics.SerializeAsString()); return storage_key; } std::string SessionStore::WriteBatch::DeleteLocalTabWithoutUpdatingTracker( int tab_node_id) { std::string storage_key = EncodeStorageKey(session_tracker_->GetLocalSessionTag(), tab_node_id); batch_->DeleteData(storage_key); return storage_key; } MetadataChangeList* SessionStore::WriteBatch::GetMetadataChangeList() { return batch_->GetMetadataChangeList(); } // static void SessionStore::WriteBatch::Commit(std::unique_ptr<WriteBatch> batch) { DCHECK(batch); std::move(batch->commit_cb_) .Run(std::move(batch->batch_), base::BindOnce(&ForwardError, std::move(batch->error_handler_))); } // static bool SessionStore::AreValidSpecifics(const SessionSpecifics& specifics) { if (specifics.session_tag().empty()) { return false; } if (specifics.has_tab()) { return specifics.tab_node_id() >= 0 && specifics.tab().tab_id() > 0; } if (specifics.has_header()) { // Verify that tab IDs appear only once within a header. Intended to prevent // http://crbug.com/360822. std::set<int> session_tab_ids; for (const sync_pb::SessionWindow& window : specifics.header().window()) { for (int tab_id : window.tab()) { bool success = session_tab_ids.insert(tab_id).second; if (!success) { return false; } } } return !specifics.has_tab() && specifics.tab_node_id() == TabNodePool::kInvalidTabNodeID; } return false; } // static std::string SessionStore::GetClientTag(const SessionSpecifics& specifics) { DCHECK(AreValidSpecifics(specifics)); if (specifics.has_header()) { return specifics.session_tag(); } DCHECK(specifics.has_tab()); return TabNodeIdToClientTag(specifics.session_tag(), specifics.tab_node_id()); } // static std::string SessionStore::GetStorageKey(const SessionSpecifics& specifics) { DCHECK(AreValidSpecifics(specifics)); return EncodeStorageKey(specifics.session_tag(), specifics.tab_node_id()); } // static std::string SessionStore::GetHeaderStorageKey(const std::string& session_tag) { return EncodeStorageKey(session_tag, TabNodePool::kInvalidTabNodeID); } // static std::string SessionStore::GetTabStorageKey(const std::string& session_tag, int tab_node_id) { DCHECK_GE(tab_node_id, 0); return EncodeStorageKey(session_tag, tab_node_id); } bool SessionStore::StorageKeyMatchesLocalSession( const std::string& storage_key) const { std::string session_tag; int tab_node_id; bool success = DecodeStorageKey(storage_key, &session_tag, &tab_node_id); DCHECK(success); return session_tag == local_session_info_.session_tag; } // static std::string SessionStore::GetTabClientTagForTest(const std::string& session_tag, int tab_node_id) { return TabNodeIdToClientTag(session_tag, tab_node_id); } // static void SessionStore::OnStoreCreated( std::unique_ptr<Builder> builder, const base::Optional<syncer::ModelError>& error, std::unique_ptr<ModelTypeStore> underlying_store) { DCHECK(builder); if (error) { std::move(builder->callback) .Run(error, /*store=*/nullptr, /*metadata_batch=*/nullptr); return; } DCHECK(underlying_store); builder->underlying_store = std::move(underlying_store); Builder* builder_copy = builder.get(); builder_copy->underlying_store->ReadAllMetadata( base::BindOnce(&OnReadAllMetadata, std::move(builder))); } // static void SessionStore::OnReadAllMetadata( std::unique_ptr<Builder> builder, const base::Optional<syncer::ModelError>& error, std::unique_ptr<syncer::MetadataBatch> metadata_batch) { DCHECK(builder); if (error) { std::move(builder->callback) .Run(error, /*store=*/nullptr, /*metadata_batch=*/nullptr); return; } DCHECK(metadata_batch); builder->metadata_batch = std::move(metadata_batch); Builder* builder_copy = builder.get(); builder_copy->underlying_store->ReadAllDataAndPreprocess( base::BindOnce( &ParseInitialDataOnBackendSequence, base::Unretained(&builder_copy->initial_data), base::Unretained(&builder_copy->local_session_info.client_name)), base::BindOnce(&OnReadAllData, std::move(builder))); } // static void SessionStore::OnReadAllData( std::unique_ptr<Builder> builder, const base::Optional<syncer::ModelError>& error) { DCHECK(builder); if (error) { std::move(builder->callback) .Run(error, /*store=*/nullptr, /*metadata_batch=*/nullptr); return; } // We avoid initialization of the store if the callback was cancelled, in // case dependencies (SessionSyncClient) are already destroyed, even though // the current implementation doesn't seem to crash otherwise. if (builder->callback.IsCancelled()) { return; } // WrapUnique() used because constructor is private. auto session_store = base::WrapUnique(new SessionStore( builder->local_session_info, std::move(builder->underlying_store), std::move(builder->initial_data), builder->metadata_batch->GetAllMetadata(), builder->sessions_client)); std::move(builder->callback) .Run(/*error=*/base::nullopt, std::move(session_store), std::move(builder->metadata_batch)); } SessionStore::SessionStore( const SessionInfo& local_session_info, std::unique_ptr<syncer::ModelTypeStore> underlying_store, std::map<std::string, sync_pb::SessionSpecifics> initial_data, const syncer::EntityMetadataMap& initial_metadata, SyncSessionsClient* sessions_client) : local_session_info_(local_session_info), store_(std::move(underlying_store)), sessions_client_(sessions_client), session_tracker_(sessions_client) { session_tracker_.InitLocalSession(local_session_info_.session_tag, local_session_info_.client_name, local_session_info_.device_type); DCHECK(store_); DVLOG(1) << "Initializing session store with " << initial_data.size() << " restored entities and " << initial_metadata.size() << " metadata entries."; bool found_local_header = false; for (auto& storage_key_and_specifics : initial_data) { const std::string& storage_key = storage_key_and_specifics.first; SessionSpecifics& specifics = storage_key_and_specifics.second; // The store should not contain invalid data, but as a precaution we filter // out anyway in case the persisted data is corrupted. if (!AreValidSpecifics(specifics)) { continue; } // Metadata should be available if data is available. If not, it means // the local store is corrupt, because we delete all data and metadata // at the same time (e.g. sync is disabled). auto metadata_it = initial_metadata.find(storage_key); if (metadata_it == initial_metadata.end()) { continue; } const base::Time mtime = syncer::ProtoTimeToTime(metadata_it->second->modification_time()); if (specifics.session_tag() != local_session_info_.session_tag) { UpdateTrackerWithSpecifics(specifics, mtime, &session_tracker_); } else if (specifics.has_header()) { // This is previously stored local header information. Restoring the local // is actually needed on Android only where we might not have a complete // view of local window/tabs. // Two local headers cannot coexist because they would use the very same // storage key in ModelTypeStore/LevelDB. DCHECK(!found_local_header); found_local_header = true; UpdateTrackerWithSpecifics(specifics, mtime, &session_tracker_); DVLOG(1) << "Loaded local header."; } else { DCHECK(specifics.has_tab()); // This is a valid old tab node, add it to the tracker and associate // it (using the new tab id). DVLOG(1) << "Associating local tab " << specifics.tab().tab_id() << " with node " << specifics.tab_node_id(); // TODO(mastiz): Move call to ReassociateLocalTab() into // UpdateTrackerWithSpecifics(), possibly merge with OnTabNodeSeen(). Also // consider merging this branch with processing of foreign tabs above. session_tracker_.ReassociateLocalTab( specifics.tab_node_id(), SessionID::FromSerializedValue(specifics.tab().tab_id())); UpdateTrackerWithSpecifics(specifics, mtime, &session_tracker_); } } // Cleanup all foreign sessions, since orphaned tabs may have been added after // the header. for (const SyncedSession* session : session_tracker_.LookupAllForeignSessions(SyncedSessionTracker::RAW)) { session_tracker_.CleanupSession(session->session_tag); } } SessionStore::~SessionStore() = default; std::unique_ptr<syncer::DataBatch> SessionStore::GetSessionDataForKeys( const std::vector<std::string>& storage_keys) const { // Decode |storage_keys| into a map that can be fed to // SerializePartialTrackerToSpecifics(). std::map<std::string, std::set<int>> session_tag_to_node_ids; for (const std::string& storage_key : storage_keys) { std::string session_tag; int tab_node_id; bool success = DecodeStorageKey(storage_key, &session_tag, &tab_node_id); DCHECK(success); session_tag_to_node_ids[session_tag].insert(tab_node_id); } // Run the actual serialization into a data batch. auto batch = std::make_unique<syncer::MutableDataBatch>(); SerializePartialTrackerToSpecifics( session_tracker_, session_tag_to_node_ids, base::BindRepeating( [](syncer::MutableDataBatch* batch, const std::string& session_name, sync_pb::SessionSpecifics* specifics) { DCHECK(AreValidSpecifics(*specifics)); // Local variable used to avoid assuming argument evaluation order. const std::string storage_key = GetStorageKey(*specifics); batch->Put(storage_key, MoveToEntityData(session_name, specifics)); }, batch.get())); return batch; } std::unique_ptr<syncer::DataBatch> SessionStore::GetAllSessionData() const { auto batch = std::make_unique<syncer::MutableDataBatch>(); SerializeTrackerToSpecifics( session_tracker_, base::BindRepeating( [](syncer::MutableDataBatch* batch, const std::string& session_name, sync_pb::SessionSpecifics* specifics) { DCHECK(AreValidSpecifics(*specifics)); // Local variable used to avoid assuming argument evaluation order. const std::string storage_key = GetStorageKey(*specifics); batch->Put(storage_key, MoveToEntityData(session_name, specifics)); }, batch.get())); return batch; } std::unique_ptr<SessionStore::WriteBatch> SessionStore::CreateWriteBatch( syncer::OnceModelErrorHandler error_handler) { // The store is guaranteed to outlive WriteBatch instances (as per API // requirement). return std::make_unique<WriteBatch>( store_->CreateWriteBatch(), base::BindOnce(&ModelTypeStore::CommitWriteBatch, base::Unretained(store_.get())), std::move(error_handler), &session_tracker_); } void SessionStore::DeleteAllDataAndMetadata() { session_tracker_.Clear(); store_->DeleteAllDataAndMetadata(base::DoNothing()); sessions_client_->GetSessionSyncPrefs()->ClearLegacySyncSessionsGUID(); // At all times, the local session must be tracked. session_tracker_.InitLocalSession(local_session_info_.session_tag, local_session_info_.client_name, local_session_info_.device_type); } } // namespace sync_sessions
35.137432
80
0.710926
Ron423c
14eba12bfab9282f6a9c5387272c7ea5d4cc445a
1,875
cpp
C++
basic/graph/graph.cpp
sanjosh/smallprogs
8acf7a357080b9154b55565be7c7667db0d4049b
[ "Apache-2.0" ]
7
2017-02-28T06:33:43.000Z
2021-12-17T04:58:19.000Z
basic/graph/graph.cpp
sanjosh/smallprogs
8acf7a357080b9154b55565be7c7667db0d4049b
[ "Apache-2.0" ]
null
null
null
basic/graph/graph.cpp
sanjosh/smallprogs
8acf7a357080b9154b55565be7c7667db0d4049b
[ "Apache-2.0" ]
3
2017-02-28T06:33:30.000Z
2021-02-25T09:42:31.000Z
#include <vector> #include <set> #include <queue> #include <iostream> using namespace std; class Graph { int32_t maxV_ = 0; std::vector<std::set<int32_t>> adj_list_; public: explicit Graph(int32_t maxV) : maxV_(maxV) { adj_list_.resize(maxV); } void AddEdge(int32_t v, int32_t w) { adj_list_[v].insert(w); adj_list_[w].insert(v); } bool IsAdjacent(int32_t v, int32_t w) const { return (adj_list_[v].count(w) > 0); } const std::set<int32_t> GetAdjacent(int32_t v) const { return adj_list_[v]; } void BFS() const { std::queue<int32_t> q; std::set<int32_t> visited; q.push(0); visited.insert(0); while (q.size()) { auto cur = q.front(); q.pop(); visited.insert(cur); cout << "bfs visiting " << cur << endl; auto v_list = GetAdjacent(cur); for (auto v : v_list) { if (visited.find(v) == visited.end()) { q.push(v); } } } } std::set<int32_t> visited_; void InitDFS() { visited_.clear(); } bool DFS(int32_t cur) { visited_.insert(cur); cout << "dfs visiting " << cur << endl; auto adj_list = GetAdjacent(cur); for (auto v : adj_list) { if (visited_.count(v) == 0) { if (DFS(v) == true) { return true; } } } return false; } }; int main() { auto g = Graph(20); g.AddEdge(0, 3); g.AddEdge(0, 9); g.AddEdge(0, 7); g.AddEdge(0, 19); g.AddEdge(3, 8); g.AddEdge(3, 12); g.AddEdge(3, 16); cout << g.IsAdjacent(8, 3) << endl; g.BFS(); g.InitDFS(); cout << g.DFS(0) << endl; }
18.75
57
0.472533
sanjosh
14efa87201392e873efbbdcc4b76d96e77765db9
3,509
cc
C++
remoting/protocol/monitored_video_stub_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
remoting/protocol/monitored_video_stub_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
remoting/protocol/monitored_video_stub_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/protocol/monitored_video_stub.h" #include <stdint.h> #include <utility> #include "base/bind.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/task_environment.h" #include "base/test/test_timeouts.h" #include "base/timer/timer.h" #include "remoting/protocol/protocol_mock_objects.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::AnyNumber; using ::testing::AtMost; using ::testing::InvokeWithoutArgs; namespace remoting { namespace protocol { static const int64_t kTestOverrideDelayMilliseconds = 1; class MonitoredVideoStubTest : public testing::Test { protected: void SetUp() override { packet_.reset(new VideoPacket()); monitor_.reset(new MonitoredVideoStub( &video_stub_, base::TimeDelta::FromMilliseconds(kTestOverrideDelayMilliseconds), base::Bind( &MonitoredVideoStubTest::OnVideoChannelStatus, base::Unretained(this)))); EXPECT_CALL(video_stub_, ProcessVideoPacketPtr(_, _)).Times(AnyNumber()); } MOCK_METHOD1(OnVideoChannelStatus, void(bool connected)); base::test::SingleThreadTaskEnvironment task_environment_; MockVideoStub video_stub_; std::unique_ptr<MonitoredVideoStub> monitor_; std::unique_ptr<VideoPacket> packet_; base::OneShotTimer timer_end_test_; }; TEST_F(MonitoredVideoStubTest, OnChannelConnected) { EXPECT_CALL(*this, OnVideoChannelStatus(true)); // On slow machines, the connectivity check timer may fire before the test // finishes, so we expect to see at most one transition to not ready. EXPECT_CALL(*this, OnVideoChannelStatus(false)).Times(AtMost(1)); monitor_->ProcessVideoPacket(std::move(packet_), {}); base::RunLoop().RunUntilIdle(); } TEST_F(MonitoredVideoStubTest, OnChannelDisconnected) { EXPECT_CALL(*this, OnVideoChannelStatus(true)); monitor_->ProcessVideoPacket(std::move(packet_), {}); base::RunLoop run_loop; EXPECT_CALL(*this, OnVideoChannelStatus(false)) .WillOnce(InvokeWithoutArgs(&run_loop, &base::RunLoop::QuitWhenIdle)); run_loop.Run(); } TEST_F(MonitoredVideoStubTest, OnChannelStayConnected) { // Verify no extra connected events are fired when packets are received // frequently EXPECT_CALL(*this, OnVideoChannelStatus(true)); // On slow machines, the connectivity check timer may fire before the test // finishes, so we expect to see at most one transition to not ready. EXPECT_CALL(*this, OnVideoChannelStatus(false)).Times(AtMost(1)); monitor_->ProcessVideoPacket(std::move(packet_), {}); monitor_->ProcessVideoPacket(std::move(packet_), {}); base::RunLoop().RunUntilIdle(); } TEST_F(MonitoredVideoStubTest, OnChannelStayDisconnected) { // Verify no extra disconnected events are fired. EXPECT_CALL(*this, OnVideoChannelStatus(true)).Times(1); EXPECT_CALL(*this, OnVideoChannelStatus(false)).Times(1); monitor_->ProcessVideoPacket(std::move(packet_), {}); task_environment_.GetMainThreadTaskRunner()->PostDelayedTask( FROM_HERE, base::RunLoop::QuitCurrentWhenIdleClosureDeprecated(), // The delay should be much greater than |kTestOverrideDelayMilliseconds|. TestTimeouts::tiny_timeout()); base::RunLoop().Run(); } } // namespace protocol } // namespace remoting
34.067961
80
0.753491
sarang-apps
14f4972a6c5a6f091e8642bd6cc91165e4952c14
2,891
hpp
C++
include/nbla/cuda/function/batch_normalization.hpp
claymodel/nnabla-ext-cuda
cf5304884fe63675a704eaf6c94a4663ed7fc46b
[ "Apache-2.0" ]
2
2020-11-10T04:45:18.000Z
2021-08-06T14:44:06.000Z
include/nbla/cuda/function/batch_normalization.hpp
claymodel/nnabla-ext-cuda
cf5304884fe63675a704eaf6c94a4663ed7fc46b
[ "Apache-2.0" ]
1
2020-11-09T08:40:20.000Z
2020-11-09T08:40:20.000Z
include/nbla/cuda/function/batch_normalization.hpp
claymodel/nnabla-ext-cuda
cf5304884fe63675a704eaf6c94a4663ed7fc46b
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2017 Sony Corporation. 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. /** Batch Normalization */ #ifndef __NBLA_CUDA_FUNCTION_BATCHNORM_HPP__ #define __NBLA_CUDA_FUNCTION_BATCHNORM_HPP__ #include <nbla/cuda/cuda.hpp> #include <nbla/function/batch_normalization.hpp> #include <vector> using std::vector; namespace nbla { template <typename T> class BatchNormalizationCuda : public BatchNormalization<T> { protected: int device_; int blocks; // for transpose Variable v_axes_; Variable v_in_strides_; Variable v_out_strides_; Variable v_out_shape_; Variable v_in_shape_; Variable v_in_trans_; Variable v_din_trans_; // work memory for data of each axis Variable v_dmean_; Variable v_dvar_; Variable v_t_; Variable v_inv_sqrt_variance_; // work memory for each block data of shuffle reduction Variable v_mean_reduction_space_; Variable v_variance_reduction_space_; Variable v_tmp_reduction_space_; public: typedef typename CudaType<T>::type Tc; BatchNormalizationCuda(const Context &ctx, const vector<int> axes, float decay_rate, float eps, bool batch_stat) : BatchNormalization<T>(ctx, axes, decay_rate, eps, batch_stat), device_(std::stoi(ctx.device_id)) {} virtual ~BatchNormalizationCuda() {} virtual string name() { return "BatchNormalizationCuda"; } virtual vector<string> allowed_array_classes() { return SingletonManager::get<Cuda>()->array_classes(); } protected: virtual void setup_impl(const Variables &inputs, const Variables &outputs); virtual void forward_impl(const Variables &inputs, const Variables &outputs); virtual void backward_impl(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); virtual void forward_impl_batch(const Variables &inputs, const Variables &outputs); virtual void forward_impl_global(const Variables &inputs, const Variables &outputs); virtual void backward_impl_batch(const Variables &inputs, const Variables &outputs, const vector<bool> &propagate_down, const vector<bool> &accum); }; } #endif
35.256098
79
0.700104
claymodel
14f524cda3b10c321eb3cb0bfb363bfb813ba607
334
cpp
C++
Engine/Plugins/Online/Android/OnlineSubsystemGameCircle/Source/OnlineSubsystemGameCircle/Private/OnlineAGSGameCircleClientCallbacks.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/Online/Android/OnlineSubsystemGameCircle/Source/OnlineSubsystemGameCircle/Private/OnlineAGSGameCircleClientCallbacks.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/Online/Android/OnlineSubsystemGameCircle/Source/OnlineSubsystemGameCircle/Private/OnlineAGSGameCircleClientCallbacks.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "OnlineAGSGameCircleClientCallbacks.h" void FOnlineShowGameCircleCallback::onShowGameCircleCb(AmazonGames::ErrorCode errorCode, int developerTag) { } void FOnlineShowSignInPageCallback::onShowSignInPageCb(AmazonGames::ErrorCode errorCode, int developerTag) { }
27.833333
106
0.832335
windystrife
14f5393ec096ee23599774671ff019f7efe9fb00
455
hh
C++
src/phantasm-hardware-interface/vulkan/common/debug_callback.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
6
2020-12-09T13:53:26.000Z
2021-12-24T14:13:17.000Z
src/phantasm-hardware-interface/vulkan/common/debug_callback.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
5
2020-01-29T09:46:36.000Z
2020-09-04T16:15:53.000Z
src/phantasm-hardware-interface/vulkan/common/debug_callback.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
null
null
null
#pragma once #include <phantasm-hardware-interface/vulkan/loader/volk.hh> namespace phi::vk::detail { VKAPI_ATTR VkBool32 VKAPI_CALL debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, VkDebugUtilsMessageTypeFlagsEXT type, VkDebugUtilsMessengerCallbackDataEXT const* callback_data, void* user_data); }
35
104
0.593407
project-arcana
14f59e5b89402ef03b8e4a61b2a3f80717043c07
15,068
cpp
C++
Projects/TestShadow/src/TestScene.cpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
Projects/TestShadow/src/TestScene.cpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
Projects/TestShadow/src/TestScene.cpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <vector> #include <stdio.h> #include "TestScene.hpp" #include "MapHelper.hpp" #include "GraphicsUtilities.h" #include "TextureUtilities.h" #include "Sphere.h" #include "Plane.h" #include "Helmet.h" #include "AnimPeople.h" #include "InputController.hpp" #include "Actor.h" #include "FastRand.hpp" namespace Diligent { SampleBase* CreateSample() { return new TestScene(); } void TestScene::GetEngineInitializationAttribs(RENDER_DEVICE_TYPE DeviceType, EngineCreateInfo& EngineCI, SwapChainDesc& SCDesc) { SampleBase::GetEngineInitializationAttribs(DeviceType, EngineCI, SCDesc); EngineCI.Features.DepthClamp = DEVICE_FEATURE_STATE_OPTIONAL; // We do not need the depth buffer from the swap chain in this sample SCDesc.DepthBufferFormat = TEX_FORMAT_UNKNOWN; } void TestScene::Initialize(const SampleInitInfo& InitInfo) { SampleBase::Initialize(InitInfo); Init = InitInfo; CreateRenderPass(); m_Camera.SetPos(float3(5.0f, 0.0f, 0.0f)); m_Camera.SetRotation(PI_F / 2.f, 0, 0); m_Camera.SetRotationSpeed(0.005f); m_Camera.SetMoveSpeed(5.f); m_Camera.SetSpeedUpScales(5.f, 10.f); // Create a shader source stream factory to load shaders from files. RefCntAutoPtr<IShaderSourceInputStreamFactory> pShaderSourceFactory; m_pEngineFactory->CreateDefaultShaderSourceStreamFactory(nullptr, &pShaderSourceFactory); envMaps.reset(new EnvMap(Init, m_BackgroundMode, m_pRenderPass)); ambientlight.reset(new AmbientLight(Init, m_pRenderPass, pShaderSourceFactory)); PointLight* light1 = new PointLight(Init, m_pRenderPass, pShaderSourceFactory); light1->setLocation(float3(-1, 0, 0)); light1->setColor(float3(1, 0, 0)); PointLight* light2 = new PointLight(Init, m_pRenderPass, pShaderSourceFactory); light2->setLocation(float3(0, 0, 0)); light2->setColor(float3(0, 1, 0)); PointLight *light3 = new PointLight(Init, m_pRenderPass, pShaderSourceFactory); light3->setLocation(float3(1, 0, 0)); light3->setColor(float3(0, 0, 1)); lights.emplace_back(light1); lights.emplace_back(light2); lights.emplace_back(light3); Helmet* casque1 = new Helmet(Init, m_BackgroundMode, m_pRenderPass); casque1->setPosition(float3(-1, 0, 0)); Helmet* casque2 = new Helmet(Init, m_BackgroundMode, m_pRenderPass); casque2->setPosition(float3(0, 0, 0)); Helmet* casque3 = new Helmet(Init, m_BackgroundMode, m_pRenderPass); casque3->setPosition(float3(1, 0, 0)); Plane* sol = new Plane(Init, m_BackgroundMode, m_pRenderPass); sol->setPosition(float3(0, -0.25, 0)); actors.emplace_back(casque1); actors.emplace_back(casque2); actors.emplace_back(casque3); actors.emplace_back(sol); } void TestScene::CreateRenderPass() { // Attachment 0 - Color buffer // Attachment 1 - Depth Z // Attachment 2 - Depth buffer // Attachment 3 - Final color buffer constexpr Uint32 NumAttachments = 4; // Prepare render pass attachment descriptions RenderPassAttachmentDesc Attachments[NumAttachments]; Attachments[0].Format = TEX_FORMAT_RGBA8_UNORM; Attachments[0].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[0].FinalState = RESOURCE_STATE_INPUT_ATTACHMENT; Attachments[0].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[0].StoreOp = ATTACHMENT_STORE_OP_DISCARD; // We will not need the result after the end of the render pass Attachments[1].Format = TEX_FORMAT_R32_FLOAT; Attachments[1].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[1].FinalState = RESOURCE_STATE_INPUT_ATTACHMENT; Attachments[1].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[1].StoreOp = ATTACHMENT_STORE_OP_DISCARD; // We will not need the result after the end of the render pass Attachments[2].Format = DepthBufferFormat; Attachments[2].InitialState = RESOURCE_STATE_DEPTH_WRITE; Attachments[2].FinalState = RESOURCE_STATE_DEPTH_WRITE; Attachments[2].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[2].StoreOp = ATTACHMENT_STORE_OP_DISCARD; // We will not need the result after the end of the render pass Attachments[3].Format = m_pSwapChain->GetDesc().ColorBufferFormat; Attachments[3].InitialState = RESOURCE_STATE_RENDER_TARGET; Attachments[3].FinalState = RESOURCE_STATE_RENDER_TARGET; Attachments[3].LoadOp = ATTACHMENT_LOAD_OP_CLEAR; Attachments[3].StoreOp = ATTACHMENT_STORE_OP_STORE; // Subpass 1 - Render G-buffer // Subpass 2 - Lighting constexpr Uint32 NumSubpasses = 2; // Prepar subpass descriptions SubpassDesc Subpasses[NumSubpasses]; // clang-format off // Subpass 0 attachments - 2 render targets and depth buffer AttachmentReference RTAttachmentRefs0[] = { {0, RESOURCE_STATE_RENDER_TARGET}, {1, RESOURCE_STATE_RENDER_TARGET} }; AttachmentReference DepthAttachmentRef0 = {2, RESOURCE_STATE_DEPTH_WRITE}; // Subpass 1 attachments - 1 render target, depth buffer, 2 input attachments AttachmentReference RTAttachmentRefs1[] = { {3, RESOURCE_STATE_RENDER_TARGET} }; AttachmentReference DepthAttachmentRef1 = {2, RESOURCE_STATE_DEPTH_WRITE}; AttachmentReference InputAttachmentRefs1[] = { {0, RESOURCE_STATE_INPUT_ATTACHMENT}, {1, RESOURCE_STATE_INPUT_ATTACHMENT} }; // clang-format on Subpasses[0].RenderTargetAttachmentCount = _countof(RTAttachmentRefs0); Subpasses[0].pRenderTargetAttachments = RTAttachmentRefs0; Subpasses[0].pDepthStencilAttachment = &DepthAttachmentRef0; Subpasses[1].RenderTargetAttachmentCount = _countof(RTAttachmentRefs1); Subpasses[1].pRenderTargetAttachments = RTAttachmentRefs1; Subpasses[1].pDepthStencilAttachment = &DepthAttachmentRef1; Subpasses[1].InputAttachmentCount = _countof(InputAttachmentRefs1); Subpasses[1].pInputAttachments = InputAttachmentRefs1; // We need to define dependency between subpasses 0 and 1 to ensure that // all writes are complete before we use the attachments for input in subpass 1. SubpassDependencyDesc Dependencies[1]; Dependencies[0].SrcSubpass = 0; Dependencies[0].DstSubpass = 1; Dependencies[0].SrcStageMask = PIPELINE_STAGE_FLAG_RENDER_TARGET; Dependencies[0].DstStageMask = PIPELINE_STAGE_FLAG_PIXEL_SHADER; Dependencies[0].SrcAccessMask = ACCESS_FLAG_RENDER_TARGET_WRITE; Dependencies[0].DstAccessMask = ACCESS_FLAG_SHADER_READ; RenderPassDesc RPDesc; RPDesc.Name = "Deferred shading render pass desc"; RPDesc.AttachmentCount = _countof(Attachments); RPDesc.pAttachments = Attachments; RPDesc.SubpassCount = _countof(Subpasses); RPDesc.pSubpasses = Subpasses; RPDesc.DependencyCount = _countof(Dependencies); RPDesc.pDependencies = Dependencies; m_pDevice->CreateRenderPass(RPDesc, &m_pRenderPass); VERIFY_EXPR(m_pRenderPass != nullptr); } RefCntAutoPtr<IFramebuffer> TestScene::CreateFramebuffer(ITextureView* pDstRenderTarget) { const auto& RPDesc = m_pRenderPass->GetDesc(); const auto& SCDesc = m_pSwapChain->GetDesc(); // Create window-size offscreen render target TextureDesc TexDesc; TexDesc.Name = "Color G-buffer"; TexDesc.Type = RESOURCE_DIM_TEX_2D; TexDesc.BindFlags = BIND_RENDER_TARGET | BIND_INPUT_ATTACHMENT; TexDesc.Format = RPDesc.pAttachments[0].Format; TexDesc.Width = SCDesc.Width; TexDesc.Height = SCDesc.Height; TexDesc.MipLevels = 1; // Define optimal clear value TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = 0.f; TexDesc.ClearValue.Color[1] = 0.f; TexDesc.ClearValue.Color[2] = 0.f; TexDesc.ClearValue.Color[3] = 0.f; RefCntAutoPtr<ITexture> pColorBuffer; m_pDevice->CreateTexture(TexDesc, nullptr, &pColorBuffer); // OpenGL does not allow combining swap chain render target with any // other render target, so we have to create an auxiliary texture. RefCntAutoPtr<ITexture> pOpenGLOffsreenColorBuffer; if (pDstRenderTarget == nullptr) { TexDesc.Name = "OpenGL Offscreen Render Target"; TexDesc.Format = SCDesc.ColorBufferFormat; m_pDevice->CreateTexture(TexDesc, nullptr, &pOpenGLOffsreenColorBuffer); pDstRenderTarget = pOpenGLOffsreenColorBuffer->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET); } TexDesc.Name = "Depth Z G-buffer"; TexDesc.Format = RPDesc.pAttachments[1].Format; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.Color[0] = 1.f; TexDesc.ClearValue.Color[1] = 1.f; TexDesc.ClearValue.Color[2] = 1.f; TexDesc.ClearValue.Color[3] = 1.f; RefCntAutoPtr<ITexture> pDepthZBuffer; m_pDevice->CreateTexture(TexDesc, nullptr, &pDepthZBuffer); TexDesc.Name = "Depth buffer"; TexDesc.Format = RPDesc.pAttachments[2].Format; TexDesc.BindFlags = BIND_DEPTH_STENCIL; TexDesc.ClearValue.Format = TexDesc.Format; TexDesc.ClearValue.DepthStencil.Depth = 1.f; TexDesc.ClearValue.DepthStencil.Stencil = 0; RefCntAutoPtr<ITexture> pDepthBuffer; m_pDevice->CreateTexture(TexDesc, nullptr, &pDepthBuffer); ITextureView* pAttachments[] = // { pColorBuffer->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET), pDepthZBuffer->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET), pDepthBuffer->GetDefaultView(TEXTURE_VIEW_DEPTH_STENCIL), pDstRenderTarget // }; FramebufferDesc FBDesc; FBDesc.Name = "G-buffer framebuffer"; FBDesc.pRenderPass = m_pRenderPass; FBDesc.AttachmentCount = _countof(pAttachments); FBDesc.ppAttachments = pAttachments; RefCntAutoPtr<IFramebuffer> pFramebuffer; m_pDevice->CreateFramebuffer(FBDesc, &pFramebuffer); VERIFY_EXPR(pFramebuffer != nullptr); ColorBuffer = pColorBuffer; DepthZBuffer = pDepthZBuffer; return pFramebuffer; } IFramebuffer* TestScene::GetCurrentFramebuffer() { auto* pCurrentBackBufferRTV = m_pDevice->GetDeviceCaps().IsGLDevice() ? nullptr : m_pSwapChain->GetCurrentBackBufferRTV(); auto fb_it = m_FramebufferCache.find(pCurrentBackBufferRTV); if (fb_it != m_FramebufferCache.end()) { return fb_it->second; } else { auto it = m_FramebufferCache.emplace(pCurrentBackBufferRTV, CreateFramebuffer(pCurrentBackBufferRTV)); VERIFY_EXPR(it.second); return it.first->second; } } // Render a frame void TestScene::Render() { auto* pFramebuffer = GetCurrentFramebuffer(); ambientlight->CreateSRB(ColorBuffer, DepthZBuffer); for (auto light : lights) { light->CreateSRB(ColorBuffer, DepthZBuffer); } BeginRenderPassAttribs RPBeginInfo; RPBeginInfo.pRenderPass = m_pRenderPass; RPBeginInfo.pFramebuffer = pFramebuffer; OptimizedClearValue ClearValues[4]; // Color ClearValues[0].Color[0] = 0.f; ClearValues[0].Color[1] = 0.f; ClearValues[0].Color[2] = 0.f; ClearValues[0].Color[3] = 0.f; // Depth Z ClearValues[1].Color[0] = 1.f; ClearValues[1].Color[1] = 1.f; ClearValues[1].Color[2] = 1.f; ClearValues[1].Color[3] = 1.f; // Depth buffer ClearValues[2].DepthStencil.Depth = 1.f; // Final color buffer ClearValues[3].Color[0] = 0.0625f; ClearValues[3].Color[1] = 0.0625f; ClearValues[3].Color[2] = 0.0625f; ClearValues[3].Color[3] = 0.f; RPBeginInfo.pClearValues = ClearValues; RPBeginInfo.ClearValueCount = _countof(ClearValues); RPBeginInfo.StateTransitionMode = RESOURCE_STATE_TRANSITION_MODE_TRANSITION; m_pImmediateContext->BeginRenderPass(RPBeginInfo); for (auto actor : actors) { if (actor->getState() == Actor::ActorState::Active) { actor->RenderActor(m_Camera, false); } } m_pImmediateContext->NextSubpass(); envMaps->RenderActor(m_Camera, false); ambientlight->RenderActor(m_Camera, false); for (auto light : lights) { light->RenderActor(m_Camera, false); } m_pImmediateContext->EndRenderPass(); if (m_pDevice->GetDeviceCaps().IsGLDevice()) { // In OpenGL we now have to copy our off-screen buffer to the default framebuffer auto* pOffscreenRenderTarget = pFramebuffer->GetDesc().ppAttachments[3]->GetTexture(); auto* pBackBuffer = m_pSwapChain->GetCurrentBackBufferRTV()->GetTexture(); CopyTextureAttribs CopyAttribs{pOffscreenRenderTarget, RESOURCE_STATE_TRANSITION_MODE_TRANSITION, pBackBuffer, RESOURCE_STATE_TRANSITION_MODE_TRANSITION}; m_pImmediateContext->CopyTexture(CopyAttribs); } } void TestScene::Update(double CurrTime, double ElapsedTime) { SampleBase::Update(CurrTime, ElapsedTime); m_Camera.Update(m_InputController, static_cast<float>(ElapsedTime)); // Animate Actors for (auto actor : actors) { actor->Update(CurrTime, ElapsedTime); } for (auto light : lights) { light->UpdateActor(CurrTime, ElapsedTime); } //if (m_InputController.IsKeyDown(InputKeys::MoveBackward)) // actors.back()->setState(Actor::ActorState::Dead); } void TestScene::removeActor(Actor* actor) { auto iter = std::find(begin(actors), end(actors), actor); if (iter != end(actors)) { std::iter_swap(iter, end(actors) - 1); actors.pop_back(); } } } // namespace Diligent
35.537736
128
0.708123
JorisSAN
14f59f090cacba7bebc8f80f24d667e36a0b703c
1,420
cc
C++
src/tir/pass/skip_assert.cc
robo-corg/incubator-tvm
4ddfdb4b15d05a5bf85a984837967d004efee5dd
[ "Apache-2.0" ]
4
2018-01-09T07:35:33.000Z
2021-04-20T05:52:50.000Z
src/tir/pass/skip_assert.cc
robo-corg/incubator-tvm
4ddfdb4b15d05a5bf85a984837967d004efee5dd
[ "Apache-2.0" ]
4
2021-03-30T11:59:59.000Z
2022-03-12T00:40:23.000Z
src/tir/pass/skip_assert.cc
robo-corg/incubator-tvm
4ddfdb4b15d05a5bf85a984837967d004efee5dd
[ "Apache-2.0" ]
3
2021-07-20T07:40:15.000Z
2021-08-03T08:39:17.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <tvm/tir/expr.h> #include <tvm/tir/ir_pass.h> #include <tvm/tir/stmt_functor.h> namespace tvm { namespace tir { class AssertSkipper : public StmtMutator { public: Stmt VisitStmt_(const AssertStmtNode* op) final { Stmt stmt = StmtMutator::VisitStmt_(op); op = stmt.as<AssertStmtNode>(); return op->body; } }; Stmt SkipAssert(Stmt stmt) { return AssertSkipper()(std::move(stmt)); } LoweredFunc SkipAssert(LoweredFunc f) { auto n = make_object<LoweredFuncNode>(*f.operator->()); n->body = SkipAssert(f->body); return LoweredFunc(n); } } // namespace tir } // namespace tvm
29.583333
63
0.724648
robo-corg
14f5ab3a1550bd0d3946bf255f65796998f5fb5e
1,405
cpp
C++
tools/rcomp-src/lib/BSymbolTable.cpp
Aaron-Goldman/creative-engine
c1f0a89cefe77415fc03283277e4472d771b6ebc
[ "MIT" ]
13
2019-06-13T03:30:58.000Z
2022-01-20T01:20:37.000Z
tools/rcomp-src/lib/BSymbolTable.cpp
Aaron-Goldman/creative-engine
c1f0a89cefe77415fc03283277e4472d771b6ebc
[ "MIT" ]
21
2019-07-15T14:11:20.000Z
2020-11-08T18:14:03.000Z
tools/rcomp-src/lib/BSymbolTable.cpp
Aaron-Goldman/creative-engine
c1f0a89cefe77415fc03283277e4472d771b6ebc
[ "MIT" ]
12
2019-05-29T14:30:38.000Z
2021-02-03T10:07:41.000Z
#include "BSymbolTable.h" // hash a string to a value between 0-255 static TInt16 hash(const char *s) { // this routine is stupid simple. There are other hash algorithms that produce a better distribution of hash values. // better distribution makes it so one bucket list doesn't get huge while others are empty. // better distribution probably comes at a CPU processing cost, though. // for our purposes, this is fine. TInt v = 0; while (*s != '\0') { v += *s; s++; } return v%256; } BSymbolTable::BSymbolTable() { // } BSymbolTable::~BSymbolTable() { // } BSymbol *BSymbolTable::LookupSymbol(const char *name) { TInt h = hash(name); BSymbolList &bucket = buckets[h]; for (BSymbol *sym = bucket.First(); !bucket.End(sym); sym=bucket.Next(sym)) { if (strcmp(sym->name, name) == 0) { return sym; } } return ENull; } TBool BSymbolTable::AddSymbol(const char *aName, TUint32 aValue, TAny *aPtr) { BSymbol *sym = LookupSymbol(aName); if (sym) { // already exists if (sym->value == aValue && sym->aptr == aPtr) { // trying to add a duplicate, pretend it succeeded) return ETrue; } else { // trying to add same name with different value! return EFalse; } } // doesn't exist, we'll add it TInt h = hash(aName); sym = new BSymbol(aName, aValue, aPtr); buckets[h].AddTail(*sym); return ETrue; }
25.089286
119
0.639146
Aaron-Goldman
14f872707c041bd974f3a0aca60b326a40771979
7,972
cpp
C++
LibRaw/src/decoders/decoders_libraw_dcrdefs.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
497
2019-06-20T09:52:58.000Z
2022-03-31T12:56:49.000Z
LibRaw/src/decoders/decoders_libraw_dcrdefs.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
58
2019-06-19T10:53:49.000Z
2022-02-14T22:43:18.000Z
LibRaw/src/decoders/decoders_libraw_dcrdefs.cpp
lcsteyn/DSS
7991c8ddbeb7b2626234cd8ba1e9cb336bbf97c9
[ "BSD-3-Clause" ]
57
2019-07-08T16:08:01.000Z
2022-03-12T15:00:04.000Z
/* -*- C++ -*- * Copyright 2019-2020 LibRaw LLC (info@libraw.org) * LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). */ #include "../../internal/dcraw_defs.h" void LibRaw::nikon_coolscan_load_raw() { if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); for (int row = 0; row < raw_height; row++) { if(tiff_bps <=8) fread(buf, 1, bufsize, ifp); else read_shorts(ubuf,width*3); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (is_NikonTransfer == 2) { // it is also (tiff_bps == 8) for (int col = 0; col < width; col++) { ip[col][0] = ((float)curve[buf[col * 3]]) / 255.0f; ip[col][1] = ((float)curve[buf[col * 3 + 1]]) / 255.0f; ip[col][2] = ((float)curve[buf[col * 3 + 2]]) / 255.0f; ip[col][3] = 0; } } else if (tiff_bps <= 8) { for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } } else { for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } } free(buf); } void LibRaw::broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; ushort _raw_stride = (ushort)load_flags; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + _raw_stride, 1, _raw_stride, ifp) < _raw_stride) derror(); FORC(_raw_stride) data[c] = data[_raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void LibRaw::android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void LibRaw::android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void LibRaw::unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < (int)maximum) ; for (row = raw_height - 1; row >= 0; row--) { checkCancel(); read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } #ifdef USE_6BY9RPI void LibRaw::rpi_load_raw8() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = raw_width; else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw8()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp++, col++) RAW(row, col + c) = dp[c]; } free(data); maximum = 0xff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void LibRaw::rpi_load_raw12() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = (raw_width * 3 + 1) / 2; else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw12()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 3, col += 2) FORC(2) RAW(row, col + c) = (dp[c] << 4) | (dp[2] >> (c << 2) & 0xF); } free(data); maximum = 0xfff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void LibRaw::rpi_load_raw14() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = ((raw_width * 7) + 3) >> 2; else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw14()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 7, col += 4) { RAW(row, col + 0) = (dp[0] << 6) | (dp[4] >> 2); RAW(row, col + 1) = (dp[1] << 6) | ((dp[4] & 0x3) << 4) | ((dp[5] & 0xf0) >> 4); RAW(row, col + 2) = (dp[2] << 6) | ((dp[5] & 0xf) << 2) | ((dp[6] & 0xc0) >> 6); RAW(row, col + 3) = (dp[3] << 6) | ((dp[6] & 0x3f) << 2); } } free(data); maximum = 0x3fff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void LibRaw::rpi_load_raw16() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = { 0,0 }; rev = 3 * (order == 0x4949); if (raw_stride == 0) dwide = (raw_width * 2); else dwide = raw_stride; data = (uchar *)malloc(dwide * 2); merror(data, "rpi_load_raw16()"); for (row = 0; row < raw_height; row++) { if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 2, col++) RAW(row, col + c) = (dp[1] << 8) | dp[0]; } free(data); maximum = 0xffff; if (!strcmp(make, "OmniVision") || !strcmp(make, "Sony") || !strcmp(make, "RaspberryPi")) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } #endif
27.874126
83
0.546162
lcsteyn
14f9c3b396b7d23e09f4c84c111d35d4f788a86e
10,281
cc
C++
lite/backends/cuda/math/gemm.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/backends/cuda/math/gemm.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/backends/cuda/math/gemm.cc
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/backends/cuda/math/gemm.h" #include <iostream> #include "lite/core/device_info.h" namespace paddle { namespace lite { namespace cuda { namespace math { template <typename PTypeIn, typename PTypeOut> bool Gemm<PTypeIn, PTypeOut>::init(const bool trans_a, bool trans_b, const int m, const int n, const int k, Context<TARGET(kCUDA)> *ctx) { if (cu_handle_ == nullptr) { this->exe_stream_ = ctx->exec_stream(); CUBLAS_CALL(cublasCreate(&cu_handle_)); CUBLAS_CALL(cublasSetMathMode(cu_handle_, CUBLAS_TENSOR_OP_MATH)); CUBLAS_CALL(cublasSetStream(cu_handle_, this->exe_stream_)); } lda_ = (!trans_a) ? k : m; ldb_ = (!trans_b) ? n : k; ldc_ = n; m_ = m; n_ = n; k_ = k; cu_trans_a_ = trans_a ? CUBLAS_OP_T : CUBLAS_OP_N; cu_trans_b_ = trans_b ? CUBLAS_OP_T : CUBLAS_OP_N; return true; } template <typename PTypeIn, typename PTypeOut> bool Gemm<PTypeIn, PTypeOut>::init(const bool trans_a, bool trans_b, const int m, const int n, const int k, const int lda, const int ldb, const int ldc, Context<TARGET(kCUDA)> *ctx) { if (cu_handle_ == nullptr) { this->exe_stream_ = ctx->exec_stream(); CUBLAS_CALL(cublasCreate(&cu_handle_)); CUBLAS_CALL(cublasSetMathMode(cu_handle_, CUBLAS_TENSOR_OP_MATH)); CUBLAS_CALL(cublasSetStream(cu_handle_, this->exe_stream_)); } m_ = m; n_ = n; k_ = k; lda_ = lda; ldb_ = ldb; ldc_ = ldc; cu_trans_a_ = trans_a ? CUBLAS_OP_T : CUBLAS_OP_N; cu_trans_b_ = trans_b ? CUBLAS_OP_T : CUBLAS_OP_N; return true; } template <> bool Gemm<float, float>::run(const float alpha, const float beta, const float *a, const float *b, float *c, Context<TARGET(kCUDA)> *ctx) { CUBLAS_CALL(cublasSgemm(cu_handle_, cu_trans_b_, cu_trans_a_, n_, m_, k_, &alpha, b, ldb_, a, lda_, &beta, c, ldc_)); return true; } template <> bool Gemm<half, half>::run(const half alpha, const half beta, const half *a, const half *b, half *c, Context<TARGET(kCUDA)> *ctx) { CUBLAS_CALL(cublasHgemm(cu_handle_, cu_trans_b_, cu_trans_a_, n_, m_, k_, &alpha, b, ldb_, a, lda_, &beta, c, ldc_)); return true; } template class Gemm<float, float>; template class Gemm<half, half>; // LtGemm template <typename T> class cublasTypeWrapper; template <> class cublasTypeWrapper<float> { public: static const cudaDataType_t type = CUDA_R_32F; }; template <> class cublasTypeWrapper<half> { public: static const cudaDataType_t type = CUDA_R_16F; }; #if (CUBLAS_VER_MAJOR * 10 + CUBLAS_VER_MINOR) == 101 template <typename PTypeIn, typename PTypeOut> bool LtGemm<PTypeIn, PTypeOut>::init(const bool trans_a, const bool trans_b, const int m, const int n, const int k, Context<TARGET(kCUDA)> *ctx) { int lda = (!trans_a) ? k : m; int ldb = (!trans_b) ? n : k; int ldc = n; return this->init(trans_a, trans_b, m, n, k, lda, ldb, ldc, ctx); } template <typename PTypeIn, typename PTypeOut> bool LtGemm<PTypeIn, PTypeOut>::init(const bool trans_a, const bool trans_b, const int m, const int n, const int k, const int lda, const int ldb, const int ldc, Context<TARGET(kCUDA)> *ctx) { if (handle_ == nullptr) { this->exe_stream_ = ctx->exec_stream(); CUBLAS_CALL(cublasLtCreate(&handle_)); } m_ = m; n_ = n; k_ = k; lda_ = lda; ldb_ = ldb; ldc_ = ldc; cu_trans_a_ = trans_a ? CUBLAS_OP_T : CUBLAS_OP_N; cu_trans_b_ = trans_b ? CUBLAS_OP_T : CUBLAS_OP_N; // create operation desciriptor; see cublasLtMatmulDescAttributes_t for // details about defaults; here we just need to set the transforms for A and B CUBLAS_CALL(cublasLtMatmulDescCreate(&matmul_desc_, cublasTypeWrapper<PTypeOut>::type)); CUBLAS_CALL(cublasLtMatmulDescSetAttribute(matmul_desc_, CUBLASLT_MATMUL_DESC_TRANSA, &cu_trans_b_, sizeof(cu_trans_b_))); CUBLAS_CALL(cublasLtMatmulDescSetAttribute(matmul_desc_, CUBLASLT_MATMUL_DESC_TRANSA, &cu_trans_a_, sizeof(cu_trans_a_))); // create matrix descriptors, we are good with the details here so no need to // set any extra attributes CUBLAS_CALL(cublasLtMatrixLayoutCreate(&a_desc_, cublasTypeWrapper<PTypeOut>::type, trans_a == false ? k : m, trans_a == false ? m : k, lda)); CUBLAS_CALL(cublasLtMatrixLayoutCreate(&b_desc_, cublasTypeWrapper<PTypeOut>::type, trans_b == false ? n : k, trans_b == false ? k : n, ldb)); CUBLAS_CALL(cublasLtMatrixLayoutCreate( &c_desc_, cublasTypeWrapper<PTypeOut>::type, n, m, ldc)); // create preference handle; here we could use extra attributes to disable // tensor ops or to make sure algo selected will work with badly aligned A, B, // C; here for simplicity we just assume A,B,C are always well aligned (e.g. // directly come from cudaMalloc) CUBLAS_CALL(cublasLtMatmulPreferenceCreate(&preference_)); if (!workspace_) { CUDA_CALL(cudaMalloc(&this->workspace_, workspace_size_)); } CUBLAS_CALL(cublasLtMatmulPreferenceSetAttribute( preference_, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &workspace_size_, sizeof(workspace_size_))); // we just need the best available heuristic to try and run matmul. There is // no guarantee this will work, e.g. if A is badly aligned, you can request // more (e.g. 32) algos and try to run them one by one until something works CUBLAS_CALL(cublasLtMatmulAlgoGetHeuristic(handle_, matmul_desc_, b_desc_, a_desc_, c_desc_, c_desc_, preference_, 1, &heuristic_result_, &returned_results_)); if (returned_results_ == 0) { LOG(FATAL) << "cuBLAS API failed with status " << CUBLAS_STATUS_NOT_SUPPORTED; } return true; } template <typename PTypeIn, typename PTypeOut> bool LtGemm<PTypeIn, PTypeOut>::run(const PTypeOut alpha, const PTypeOut beta, const PTypeIn *a, const PTypeIn *b, PTypeOut *c, Context<TARGET(kCUDA)> *ctx) { CUBLAS_CALL(cublasLtMatmul(handle_, matmul_desc_, &alpha, b, b_desc_, a, a_desc_, &beta, c, c_desc_, c, c_desc_, &heuristic_result_.algo, workspace_, workspace_size_, this->exe_stream_)); return true; } template class LtGemm<float, float>; template class LtGemm<half, half>; #endif } // namespace math } // namespace cuda } // namespace lite } // namespace paddle
36.717857
80
0.474273
wanglei91
14fff2061d3ec43180b620697164e8801e972f3c
6,181
cpp
C++
voxelyzeMain/main2.cpp
fgolemo/EC14-voxelyze
7fcb1abe4e2d35f996437f833c8febd01e368901
[ "Apache-2.0" ]
null
null
null
voxelyzeMain/main2.cpp
fgolemo/EC14-voxelyze
7fcb1abe4e2d35f996437f833c8febd01e368901
[ "Apache-2.0" ]
null
null
null
voxelyzeMain/main2.cpp
fgolemo/EC14-voxelyze
7fcb1abe4e2d35f996437f833c8febd01e368901
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "VX_Object.h" #include "VX_Environment.h" #include "VX_Sim.h" #include "VX_SimGA.h" int main(int argc, char *argv[]) { char* InputFile; //create the main objects CVXC_Structure structure; CVX_Object Object; CVX_Environment Environment; CVX_SimGA Simulator; long int Step = 0; vfloat Time = 0.0; //in seconds bool print_scrn = false; //first, parse inputs. Use as: -f followed by the filename of the .vxa file that describes the simulation. Can also follow this with -p to cause console output to occur if (argc < 3) { // Check the value of argc. If not enough parameters have been passed, inform user and exit. std::cout << "\nInput file required. Quitting.\n"; return(0); //return, indicating via code (0) that we did not complete the simulation } else { // if we got enough parameters... for (int i = 1; i < argc; i++) { if (strcmp(argv[i],"-f") == 0) { InputFile = argv[i + 1]; // We know the next argument *should* be the filename: } else if (strcmp(argv[i],"-p") == 0) { print_scrn=true; //decide if output to the console is desired } } } //setup main object Simulator.pEnv = &Environment; //connect Simulation to environment Environment.pObj = &Object; //connect environment to object //import the configuration file if (!Simulator.LoadVXAFile(InputFile)){ if (print_scrn) std::cout << "\nProblem importing VXA file. Quitting\n"; return(0); //return, indicating via code (0) that we did not complete the simulation } std::string ReturnMessage; if (print_scrn) std::cout << "\nImporting Environment into simulator...\n"; Simulator.Import(&Environment, 0, &ReturnMessage); if (print_scrn) std::cout << "Simulation import return message:\n" << ReturnMessage << "\n"; Simulator.pEnv->UpdateCurTemp(Time); //set the starting temperature (nac: pointer removed for debugging) Simulator.EnableFeature(VXSFEAT_EQUILIBRIUM_MODE); StopCondition oldStopConditionType = Simulator.GetStopConditionType(); vfloat oldStopConditionValue = Simulator.GetStopConditionValue(); Simulator.SetStopConditionType(SC_MIN_KE); Simulator.SetStopConditionValue(0.1); while (not Simulator.StopConditionMet()) { // do some reporting via the stdoutput if required: if (Step%100 == 0.0 && print_scrn) //Only output every n time steps { // std::cout << "Time: " << Time << std::endl; std::cout << "CM: " << Simulator.GetCM().x << std::endl; // std::cout << " \tVox 0 X: " << Vox0Pos.x << "mm" << "\tVox 0 Y: " << Vox0Pos.y << "mm" << "\tVox 0 Z: " << Vox0Pos.z << "mm\n"; //just display the position of the first voxel in the voxelarray //std::cout << "Scale: " << Simulator.VoxArray[0].GetCurScale().x << std::endl; // display the scale of voxel 0 as it (potentially) expands and contracts } //do the actual simulation step Simulator.TimeStep(&ReturnMessage); Step += 1; //increment the step counter Time += Simulator.dt; //update the sim tim after the step Simulator.pEnv->UpdateCurTemp(Time); //pass in the global time, and a pointer to the local object so its material temps can be modified (nac: pointer removed for debugging) } std::cout << "Done Round One" << std::endl; Simulator.IniCM=Simulator.GetCM(); //set the starting CM position std::cout << "Initial CM: " << Simulator.IniCM.x << std::endl; Simulator.EnableFeature(VXSFEAT_EQUILIBRIUM_MODE,false); Simulator.SetStopConditionType(SC_MIN_MAXMOVE); while (not Simulator.StopConditionMet()) { // do some reporting via the stdoutput if required: if (Step%100 == 0.0 && print_scrn) //Only output every n time steps { // std::cout << "Time: " << Time << std::endl; std::cout << "CM: " << Simulator.GetCM().x << std::endl; // std::cout << " \tVox 0 X: " << Vox0Pos.x << "mm" << "\tVox 0 Y: " << Vox0Pos.y << "mm" << "\tVox 0 Z: " << Vox0Pos.z << "mm\n"; //just display the position of the first voxel in the voxelarray //std::cout << "Scale: " << Simulator.VoxArray[0].GetCurScale().x << std::endl; // display the scale of voxel 0 as it (potentially) expands and contracts } //do the actual simulation step Simulator.TimeStep(&ReturnMessage); Step += 1; //increment the step counter Time += Simulator.dt; //update the sim tim after the step Simulator.pEnv->UpdateCurTemp(Time); //pass in the global time, and a pointer to the local object so its material temps can be modified (nac: pointer removed for debugging) } std::cout << "Done Round Two" << std::endl; Simulator.SetStopConditionType(oldStopConditionType); Simulator.SetStopConditionValue(oldStopConditionValue+Time); // Time = 0.0; // Step = 0; Simulator.pEnv->UpdateCurTemp(Time); std::cout << "Time: " << Time << std::endl; while (not Simulator.StopConditionMet()) { // do some reporting via the stdoutput if required: if (Step%100 == 0.0 && print_scrn) //Only output every n time steps { // std::cout << "Time: " << Time << std::endl; std::cout << "CM: " << Simulator.GetCM().x << std::endl; // std::cout << " \tVox 0 X: " << Vox0Pos.x << "mm" << "\tVox 0 Y: " << Vox0Pos.y << "mm" << "\tVox 0 Z: " << Vox0Pos.z << "mm\n"; //just display the position of the first voxel in the voxelarray //std::cout << "Scale: " << Simulator.VoxArray[0].GetCurScale().x << std::endl; // display the scale of voxel 0 as it (potentially) expands and contracts } //do the actual simulation step Simulator.TimeStep(&ReturnMessage); Step += 1; //increment the step counter Time += Simulator.dt; //update the sim tim after the step Simulator.pEnv->UpdateCurTemp(Time); //pass in the global time, and a pointer to the local object so its material temps can be modified (nac: pointer removed for debugging) } if (print_scrn) std::cout << "Ended at: " << Time << std::endl; std::cout << "Final CM: " << Simulator.GetCM().x << std::endl; Simulator.SaveResultFile(Simulator.FitnessFileName); return 1; //code for successful completion // could return fitness value if greater efficiency is desired }
42.627586
199
0.662514
fgolemo
09005bf2b2f330f6e4982b99eacc1f1abc4be7ea
307
cpp
C++
src/visualiser/src/VisualiserImage/visualiser_image_input.cpp
Greakz/mdh-cmake-cubevis
6c64ec0e14dcdd07e69fa1f018aa7954eeeaf173
[ "MIT" ]
null
null
null
src/visualiser/src/VisualiserImage/visualiser_image_input.cpp
Greakz/mdh-cmake-cubevis
6c64ec0e14dcdd07e69fa1f018aa7954eeeaf173
[ "MIT" ]
5
2021-08-24T11:09:54.000Z
2021-08-24T21:14:15.000Z
src/visualiser/src/VisualiserImage/visualiser_image_input.cpp
Greakz/mdh-cmake-cubevis
6c64ec0e14dcdd07e69fa1f018aa7954eeeaf173
[ "MIT" ]
null
null
null
#include "../../include/i_visualiser.h" void VisualiserImage::mouse_position_update(double x_pos, double y_pos, double last_x_pos, double last_y_pos, bool left_button, bool middle_button) { } void VisualiserImage::mouse_wheel_update(double xoffset, double yoffset, bool left_button, bool middle_button) { }
51.166667
149
0.807818
Greakz
09045cceff8347b26b4d8226ba2efd4db1374823
8,303
cpp
C++
evaluation/individual_modules/host_gemv.cpp
spcl/fblas
96425fbdbaeab6f43997d839836b8224a04f3b53
[ "BSD-3-Clause" ]
68
2019-02-07T21:30:21.000Z
2022-02-16T20:09:27.000Z
evaluation/individual_modules/host_gemv.cpp
spcl/fblas
96425fbdbaeab6f43997d839836b8224a04f3b53
[ "BSD-3-Clause" ]
2
2019-03-15T17:49:03.000Z
2019-07-24T14:05:35.000Z
evaluation/individual_modules/host_gemv.cpp
spcl/fblas
96425fbdbaeab6f43997d839836b8224a04f3b53
[ "BSD-3-Clause" ]
25
2019-03-15T03:00:15.000Z
2021-08-04T10:21:43.000Z
/** Test program for the streaming_gemv module (version 1, i.e. A non trasposed, rowstramed and tiles by rows) Please note: for this test we want to generate data on device. Therefore the input sizes must be a multiple of the tile size The kernels are executed multiple times: - for each execution it takes the time using the OpenCL Profiling info command, considering the start and the end of a kernel. The execution time is takes that elapses between the start of the first kernel to the end of the last one. - it outputs in a file all the summary metrics as well as all the measured timings */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string> #include <iostream> #include <fstream> #include <cblas.h> #include "CL/opencl.h" #include "../../include/utils/ocl_utils.hpp" #include "../../include/utils/utils.hpp" #include "../../include/utils/test.hpp" #define CHECK using namespace std; template <typename T> void evaluate(std::string program_path, size_t n, size_t m, T alpha, T beta, int tile_n, int tile_m, std::vector<double> &times, int runs) { std::cout << " alpha= " <<alpha<< ", beta= "<<beta<<std::endl; cl::Platform platform; cl::Device device; cl::Context context; cl::Program program; timestamp_t comp_start; IntelFPGAOCLUtils::initOpenCL(platform,device,context,program,program_path); std::vector<std::string> kernel_names; if (std::is_same<T, float>::value) kernel_names={"sgemv_generate_x","sgemv_generate_y","sgemv_generate_matrix","sgemv","sgemv_write_vector"}; else kernel_names={"dgemv_generate_x","dgemv_generate_y","dgemv_generate_matrix","dgemv","dgemv_write_vector"}; std::vector<cl::Kernel> kernels; std::vector<cl::CommandQueue> queues; const int num_kernels=kernel_names.size(); IntelFPGAOCLUtils::createCommandQueues(context,device,queues,num_kernels); IntelFPGAOCLUtils::createKernels(program,kernel_names,kernels); int len_y= n; int len_x= m; T *fpga_res; posix_memalign ((void **)&fpga_res, IntelFPGAOCLUtils::AOCL_ALIGNMENT, len_y*sizeof(T)); cl::Buffer output(context, CL_MEM_READ_WRITE,len_y* sizeof(T)); int x_repetitions=ceil((float)(len_y)/tile_n); int y_repetitions=1; int lda=m; int one=1; //generate x kernels[0].setArg(0, sizeof(unsigned int),&len_x); kernels[0].setArg(1, sizeof(unsigned int),&x_repetitions); //generate y kernels[1].setArg(0, sizeof(unsigned int),&len_y); kernels[1].setArg(1, sizeof(unsigned int),&y_repetitions); //generate matrix kernels[2].setArg(0, sizeof(int),&n); kernels[2].setArg(1, sizeof(int),&m); //sgemv kernels[3].setArg(0, sizeof(int),&one); kernels[3].setArg(1, sizeof(int),&n); kernels[3].setArg(2, sizeof(int),&m); kernels[3].setArg(3, sizeof(T),&alpha); kernels[3].setArg(4, sizeof(T),&beta); //sink kernels[4].setArg(0,sizeof(cl_mem), &output); kernels[4].setArg(1,sizeof(int),&len_y); kernels[4].setArg(2,sizeof(int),&tile_n); //enable profiling (needed in 19.1) for(int r=0;r<runs;r++) { cl::Event events[5]; for(int i=0;i<num_kernels;i++) { queues[i].enqueueTask(kernels[i],nullptr,&events[i]); queues[i].flush(); } //wait for(int i=0;i<num_kernels;i++) queues[i].finish(); ulong min_start, max_end=0; ulong end; ulong start; for(int i=0;i<num_kernels;i++) { events[i].getProfilingInfo<ulong>(CL_PROFILING_COMMAND_START,&start); events[i].getProfilingInfo<ulong>(CL_PROFILING_COMMAND_END,&end); if(i==0) min_start=start; if(start<min_start) min_start=start; if(end>max_end) max_end=end; } times.push_back((double)((max_end-min_start)/1000.0f)); } //since the kernels will not save the result, is useless to check correctness //copy back queues[0].enqueueReadBuffer(output,CL_TRUE,0,len_y*sizeof(T),fpga_res); #if defined(CHECK) //NOTE: this assumes a particular way of generating data //Also, consider that for very large input size, precision errors could occur T *A,*x,*y; A=new T[n*m](); x=new T[len_x](); y=new T[len_y](); for(int i=0;i<n;i++) for(int j=0;j<m;j++) A[i*m+j]=i; for(int j=0;j<len_x;j++) x[j]=j; for(int j=0;j<len_y;j++) y[j]=j; double flteps; //NOTE THAT THIS MATRIX IS STORED BY ROW //CBLAS_ORDER ord= row_streamed? CblasRowMajor : CblasColMajor; comp_start=current_time_usecs(); if (std::is_same<T, float>::value){ cblas_sgemv(CblasRowMajor,CblasNoTrans,n,m,alpha,(float *)A,m,(float *)x,1,beta,(float *)y,1); flteps= 1e-4; } else{ cblas_dgemv(CblasRowMajor,CblasNoTrans,n,m,alpha,(double *)A,m,(double *)x,1,beta,(double *)y,1); flteps= 1e-6; } bool ok=true; //for(int i=0;i<len_y;i++)//orig for(int i=0;i<len_y;i++) { if(!test_equals(fpga_res[i],y[i],flteps)) //orig { std::cout <<"["<<i<<"] "<< fpga_res[i]<<"\t"<<y[i]<<std::endl; ok=false; } } if(ok) cout << "Result verified!"<<endl; else cout << "Result not correct!!! "<<endl; #endif } int main(int argc, char *argv[]) { //command line argument parsing if(argc<17) { cerr << "Matrix-vector multiplication Ax where A is NxM and B is a vector of M elements " <<endl; cerr << "Usage: "<< argv[0]<<"-b <binary file> -n <row of A> -m <column of A> -a <alpha> -c <beta> -k <length of tile TN> -j <length of tile TM> -r <runs> [-p <precision>]"<<endl; exit(-1); } int c; int n,m; int tile_n,tile_m,runs; bool double_precision; double alpha, beta; std::string program_path; while ((c = getopt (argc, argv, "n:m:p:b:c:a:k:j:r:")) != -1) switch (c) { case 'b': program_path=std::string(optarg); break; case 'n': n=atoi(optarg); break; case 'm': m=atoi(optarg); break; case 'p': { std::string str=optarg; if(str=="single") double_precision=false; else if(str=="double") double_precision=true; else { cerr << "Unrecognized option: " <<optarg<<endl; exit(-1); } } break; case 'k': tile_n=atoi(optarg); break; case 'j': tile_m=atoi(optarg); break; case 'a': alpha = atof(optarg); break; case 'c': beta=atof(optarg); break; case 'r': runs=atoi(optarg); break; default: cerr << "Usage: "<< argv[0]<<" -n <length of the vectors> -p <single/double>"<<endl; exit(-1); } cout << "Matrix: " << n << " x "<<m<<". Tiles: "<<tile_n<<" x "<<tile_m<<endl; timestamp_t cpu_time,fpga_time; long data_bytes; std::vector<double> times; if(!double_precision) evaluate<float>(program_path,n,m,alpha,beta,tile_n,tile_m,times,runs); else evaluate<double>(program_path,n,m,alpha,beta,tile_n,tile_m,times,runs); //compute the average and standard deviation of times double mean=0; for(auto t:times) mean+=t; mean/=runs; //report the mean in usecs double stddev=0; for(auto t:times) stddev+=((t-mean)*(t-mean)); stddev=sqrt(stddev/runs); double computation_gops=(((double)(2.0f*n*m+2*n))/(1000000000.0)); //for each element we perform a multiplication and an add. We have also to multiply the element of y double measured_gops=computation_gops/((mean)/1000000.0); cout << "FPGA Computation time (usec): " << mean << " (sttdev: " << stddev<<")"<<endl; std::cout << "FPGA GOps/s: " << measured_gops<<std::endl; //save the info into output file ofstream fout("output.dat"); fout << "#N = "<<n<<", Runs = "<<runs<<endl; fout << "#Average Computation time (usecs): "<<mean<<endl; fout << "#Standard deviation (usecs): "<<stddev<<endl; fout << "#GOPS/s: "<<measured_gops<<endl; fout << "#Execution times (usecs):"<<endl; for(auto t:times) fout << t << endl; fout.close(); return 0; }
30.083333
189
0.606889
spcl
0904bfee413fd4264bf1b9927aca82724a143515
592
cpp
C++
Effective-Modern-C++/include/item22/widget.cpp
AndrewAndJenny/AlgorithmTrain
4f6e1b723d7776d1ce4927f84d70da5e56aa9e96
[ "MIT" ]
19
2021-01-09T09:03:03.000Z
2021-12-09T10:37:23.000Z
Effective-Modern-C++/include/item22/widget.cpp
AndrewAndJenny/AlgorithmTrain
4f6e1b723d7776d1ce4927f84d70da5e56aa9e96
[ "MIT" ]
1
2021-03-28T01:06:41.000Z
2021-04-05T08:31:31.000Z
Effective-Modern-C++/include/item22/widget.cpp
AndrewAndJenny/AlgorithmTrain
4f6e1b723d7776d1ce4927f84d70da5e56aa9e96
[ "MIT" ]
2
2021-01-27T06:20:29.000Z
2021-07-07T04:58:14.000Z
#include "gadget.h" #include "widget.h" #include <string> #include <vector> struct Widget::Impl //跟之前⼀样 { std::string name; std::vector<double> data; Gadget g1, g2, g3; }; Widget::Widget() :pImpl(std::make_unique<Impl>()){ } //根据Item 21, 通过std::make_shared来创建std::unique_ptr Widget::~Widget() = default; //同上述代码效果⼀致 Widget::Widget(Widget&& rhs) = default; //在这⾥定义 Widget& Widget::operator=(Widget&& rhs) = default; Widget::Widget(const Widget& rhs) :pImpl(std::make_unique<Impl>(*rhs.pImpl)) {} Widget& Widget::operator=(const Widget& rhs) { *pImpl = *rhs.pImpl; return *this; }
21.142857
87
0.679054
AndrewAndJenny
0904ceb13629470931a2aedbfcd7f852495e2713
317
cpp
C++
Source/Kernel/Devices/Drivers/VMware/Mouse/MouseDriver.cpp
jbatonnet/System
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
[ "MIT" ]
3
2020-04-24T20:23:24.000Z
2022-01-06T22:27:01.000Z
Source/Kernel/Devices/Drivers/VMware/Mouse/MouseDriver.cpp
jbatonnet/system
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
[ "MIT" ]
null
null
null
Source/Kernel/Devices/Drivers/VMware/Mouse/MouseDriver.cpp
jbatonnet/system
227cf491ab5d0660a6bcf654f6cad09d1f82ba8e
[ "MIT" ]
1
2021-06-25T17:35:08.000Z
2021-06-25T17:35:08.000Z
#include <Kernel/Devices/DeviceManager.h> #include "MouseDriver.h" #include "MouseDevice.h" #include "Mouse.h" using namespace System::Devices; MouseDriver::MouseDriver() { } void MouseDriver::Load() { Device* device = new MouseDevice(); DeviceManager::AddDevice(device); } void MouseDriver::Unload() { }
15.095238
41
0.719243
jbatonnet
09090593b10866d99df7843392491aeb21458c68
29,133
cpp
C++
source/core/tjs2/tjsOctPack.cpp
metarin/krkrv
42e5c23483539e2bc1e8d6858548cf13165494e1
[ "BSD-3-Clause" ]
null
null
null
source/core/tjs2/tjsOctPack.cpp
metarin/krkrv
42e5c23483539e2bc1e8d6858548cf13165494e1
[ "BSD-3-Clause" ]
null
null
null
source/core/tjs2/tjsOctPack.cpp
metarin/krkrv
42e5c23483539e2bc1e8d6858548cf13165494e1
[ "BSD-3-Clause" ]
null
null
null
#include "tjsCommHead.h" #include <map> #include <vector> #include <string> #include "tjsArray.h" #include "tjsError.h" namespace TJS { enum OctPackType { OctPack_ascii, // a : ASCII string(ヌル文字が補完される) OctPack_ASCII, // A : ASCII string(スペースが補完される) OctPack_bitstring, // b : bit string(下位ビットから上位ビットの順) OctPack_BITSTRING, // B : bit string(上位ビットから下位ビットの順) OctPack_char, // c : 符号付き1バイト数値(-128 ~ 127) OctPack_CHAR, // C : 符号無し1バイト数値(0~255) OctPack_double, // d : 倍精度浮動小数点 OctPack_float, // f : 単精度浮動小数点 OctPack_hex, // h : hex string(low nybble first) OctPack_HEX, // H : hex string(high nybble first) OctPack_int, // i : 符号付きint数値(通常4バイト) OctPack_INT, // I : 符号無しint数値(通常4バイト) OctPack_long, // l : 符号付きlong数値(通常4バイト) OctPack_LONG, // L : 符号無しlong数値(通常4バイト) OctPack_noshort, // n : short数値(ネットワークバイトオーダ) network byte order short OctPack_NOLONG, // N : long数値(ネットワークバイトオーダ) network byte order long OctPack_pointer, // p : 文字列へのポインタ null terminate char OctPack_POINTER, // P : 構造体(固定長文字列)へのポインタ fix length char OctPack_short, // s : 符号付きshort数値(通常2バイト) sign OctPack_SHORT, // S : 符号無しshort数値(通常2バイト) unsign OctPack_leshort, // v : リトルエンディアンによるshort値 little endian short OctPack_LELONG, // V : リトルエンディアンによるlong値 little endian long OctPack_uuencode, // u : uuencodeされた文字列 OctPack_BRE, // w : BER圧縮された整数値 OctPack_null, // x : ヌル文字 OctPack_NULL, // X : back up a byte OctPack_fill, // @ : 絶対位置までヌル文字を埋める OctPack_base64, // m : Base64 encode / decode OctPack_EOT }; static const tjs_char OctPackChar[OctPack_EOT] = { TJS_W('a'), TJS_W('A'), TJS_W('b'), TJS_W('B'), TJS_W('c'), TJS_W('C'), TJS_W('d'), TJS_W('f'), TJS_W('h'), TJS_W('H'), TJS_W('i'), TJS_W('I'), TJS_W('l'), TJS_W('L'), TJS_W('n'), TJS_W('N'), TJS_W('p'), TJS_W('P'), TJS_W('s'), TJS_W('S'), TJS_W('v'), TJS_W('V'), TJS_W('u'), TJS_W('w'), TJS_W('x'), TJS_W('X'), TJS_W('@'), TJS_W('m'), }; static bool OctPackMapInit = false; static std::map<tjs_char,tjs_int> OctPackMap; static void OctPackMapInitialize() { if( OctPackMapInit ) return; for( tjs_int i = 0; i < OctPack_EOT; i++ ) { OctPackMap.insert( std::map<tjs_char,tjs_int>::value_type( OctPackChar[i], i ) ); } OctPackMapInit = true; } struct OctPackTemplate { OctPackType Type; tjs_int Length; }; static const tjs_char* ParseTemplateLength( OctPackTemplate& result, const tjs_char* c ) { if( *c ) { if( *c == TJS_W('*') ) { c++; result.Length = -1; // tail list } else if( *c >= TJS_W('0') && *c <= TJS_W('9') ) { tjs_int num = 0; while( *c && ( *c >= TJS_W('0') && *c <= TJS_W('9') ) ) { num *= 10; num += *c - TJS_W('0'); c++; } result.Length = num; } else { result.Length = 1; } } else { result.Length = 1; } return c; } static void ParsePackTemplate( std::vector<OctPackTemplate>& result, const tjs_char* templ ) { OctPackMapInitialize(); const tjs_char* c = templ; while( *c ) { std::map<tjs_char,tjs_int>::iterator f = OctPackMap.find( *c ); if( f == OctPackMap.end() ) { TJS_eTJSError( TJSUnknownPackUnpackTemplateCharcter ); } else { c++; OctPackTemplate t; t.Type = static_cast<OctPackType>(f->second); c = ParseTemplateLength( t, c ); result.push_back( t ); } } } static void AsciiToBin( std::vector<tjs_uint8>& bin, const ttstr& arg, tjs_nchar fillchar, tjs_int len ) { const tjs_char* str = arg.c_str(); if( len < 0 ) len = arg.length(); tjs_int i = 0; for( ; i < len && *str != TJS_W('\0'); str++, i++ ) { bin.push_back( (tjs_uint8)*str ); } for( ; i < len; i++ ) { bin.push_back( fillchar ); } } // mtol : true : 上位ビットから下位ビット, false : 下位ビットから上位ビット // 指定した数値の方が大きくても、その分は無視 static void BitStringToBin( std::vector<tjs_uint8>& bin, const ttstr& arg, bool mtol, tjs_int len ) { const tjs_char* str = arg.c_str(); if( len < 0 ) len = arg.length(); tjs_uint8 val = 0; tjs_int pos = 0; if( mtol ) { pos = 7; for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str == TJS_W('0') ) { // val |= 0; } else if( *str == TJS_W('1') ) { val |= 1 << pos; } else { TJS_eTJSError( TJSUnknownBitStringCharacter ); } if( pos == 0 ) { bin.push_back( val ); pos = 7; val = 0; } else { pos--; } } if( pos < 7 ) { bin.push_back( val ); } } else { for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str == TJS_W('0') ) { // val |= 0; } else if( *str == TJS_W('1') ) { val |= 1 << pos; } else { TJS_eTJSError( TJSUnknownBitStringCharacter ); } if( pos == 7 ) { bin.push_back( val ); pos = val = 0; } else { pos++; } } if( pos ) { bin.push_back( val ); } } } // mtol static void HexToBin( std::vector<tjs_uint8>& bin, const ttstr& arg, bool mtol, tjs_int len ) { const tjs_char* str = arg.c_str(); if( len < 0 ) len = arg.length(); tjs_uint8 val = 0; tjs_int pos = 0; if( mtol ) { // 上位ニブルが先 pos = 1; for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str >= TJS_W('0') && *str <= TJS_W('9') ) { val |= (*str - TJS_W('0')) << (pos*4); } else if( *str >= TJS_W('a') && *str <= TJS_W('f') ) { val |= (*str - TJS_W('a') + 10) << (pos*4); } else if( *str >= TJS_W('A') && *str <= TJS_W('E') ) { val |= (*str - TJS_W('A') + 10) << (pos*4); } else { TJS_eTJSError( TJSUnknownHexStringCharacter ); } if( pos == 0 ) { bin.push_back( val ); pos = 1; val = 0; } else { pos--; } } if( pos < 1 ) { bin.push_back( val ); } } else { // 下位ニブルが先 for( tjs_int i = 0; i < len && *str != TJS_W('\0'); str++, i++ ) { if( *str >= TJS_W('0') && *str <= TJS_W('9') ) { val |= (*str - TJS_W('0')) << (pos*4); } else if( *str >= TJS_W('a') && *str <= TJS_W('f') ) { val |= (*str - TJS_W('a') + 10) << (pos*4); } else if( *str >= TJS_W('A') && *str <= TJS_W('E') ) { val |= (*str - TJS_W('A') + 10) << (pos*4); } else { TJS_eTJSError( TJSUnknownHexStringCharacter ); } if( pos ) { bin.push_back( val ); pos = val = 0; } else { pos++; } } if( pos ) { bin.push_back( val ); } } } // TRet : 最終的に出力する型 // TTmp : 一時的に出力する型 variant は一時的に tjs_int にしないといけないなど template<typename TRet, typename TTmp, int NBYTE, typename TRetTmp> static void ReadNumberLE( std::vector<tjs_uint8>& result, const std::vector<tTJSVariant>& args, tjs_int numargs, tjs_int& argindex, tjs_int len ) { if( len < 0 ) len = numargs - argindex; if( (len+argindex) > numargs ) len = numargs - argindex; for( tjs_int a = 0; a < len; a++ ) { TRet c = (TRet)(TTmp)args[argindex+a]; TRetTmp val = *(TRetTmp*)&c; for( int i = 0; i < NBYTE; i++ ) { TRetTmp tmp = ( val >> (i*8) ) & 0xFF; result.push_back( (tjs_uint8)tmp ); // little endian } } argindex += len-1; } template<typename TRet, typename TTmp, int NBYTE, typename TRetTmp> static void ReadNumberBE( std::vector<tjs_uint8>& result, const std::vector<tTJSVariant>& args, tjs_int numargs, tjs_int& argindex, tjs_int len ) { if( len < 0 ) len = numargs - argindex; if( (len+argindex) > numargs ) len = numargs - argindex; for( tjs_int a = 0; a < len; a++ ) { TRet c = (TRet)(TTmp)args[argindex+a]; for( int i = 0; i < NBYTE; i++ ) { result.push_back( ((*(TRetTmp*)&c)&(0xFF<<((NBYTE-1-i)*8)))>>((NBYTE-1-i)*8) ); // big endian } } argindex += len-1; } #if TJS_HOST_IS_BIG_ENDIAN # define ReadNumber ReadNumberBE #else # define ReadNumber ReadNumberLE #endif // from base64 plug-in (C) 2009 Kiyobee // 扱いやすいように一部書き換えている // inbuf の内容を base64 エンコードして、outbuf に文字列として出力 // outbuf のサイズは、insize / 4 * 3 必要 // outbuf のサイズは、(insize+2)/3 * 4 必要 static void encodeBase64( const tjs_uint8* inbuf, tjs_uint insize, tjs_string& outbuf) { outbuf.reserve( outbuf.size() + ((insize+2)/3) * 4 ); static const char* base64str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; tjs_int insize_3 = insize - 3; tjs_int outptr = 0; tjs_int i; for(i=0; i<=insize_3; i+=3) { outbuf.push_back( base64str[ (inbuf[i ] >> 2) & 0x3F ] ); outbuf.push_back( base64str[((inbuf[i ] << 4) & 0x30) | ((inbuf[i+1] >> 4) & 0x0F)] ); outbuf.push_back( base64str[((inbuf[i+1] << 2) & 0x3C) | ((inbuf[i+2] >> 6) & 0x03)] ); outbuf.push_back( base64str[ (inbuf[i+2] ) & 0x3F ] ); } switch(insize % 3) { case 2: outbuf.push_back( base64str[ (inbuf[i ] >> 2) & 0x3F ] ); outbuf.push_back( base64str[((inbuf[i ] << 4) & 0x30) | ((inbuf[i+1] >> 4) & 0x0F)] ); outbuf.push_back( base64str[ (inbuf[i+1] << 2) & 0x3C ] ); outbuf.push_back( '=' ); break; case 1: outbuf.push_back( base64str[ (inbuf[i ] >> 2) & 0x3F ] ); outbuf.push_back( base64str[ (inbuf[i ] << 4) & 0x30 ] ); outbuf.push_back( '=' ); outbuf.push_back( '=' ); break; } } static void decodeBase64( const tjs_string& inbuf, std::vector<tjs_uint8>& outbuf ) { tjs_int len = (tjs_int)inbuf.length(); const tjs_char* data = inbuf.c_str(); if( len < 4 ) { // too short return; } outbuf.reserve( len / 4 * 3 ); static const tjs_int base64tonum[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; tjs_int dptr = 0; tjs_int len_4 = len - 4; while( dptr < len_4 ) { outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 2) | (base64tonum[data[dptr+1]] >> 4) ) ); dptr++; outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 4) | (base64tonum[data[dptr+1]] >> 2) ) ); dptr++; outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 6) | (base64tonum[data[dptr+1]]) ) ); dptr+=2; } outbuf.push_back( static_cast<tjs_uint8>( (base64tonum[data[dptr]] << 2) | (base64tonum[data[dptr+1]] >> 4) )) ; dptr++; tjs_uint8 tmp = static_cast<tjs_uint8>( base64tonum[data[dptr++]] << 4 ); if( data[dptr] != TJS_W('=') ) { tmp |= base64tonum[data[dptr]] >> 2; outbuf.push_back( tmp ); tmp = base64tonum[data[dptr++]] << 6; if( data[dptr] != TJS_W('=') ) { tmp |= base64tonum[data[dptr]]; outbuf.push_back( tmp ); } } } static tTJSVariantOctet* Pack( const std::vector<OctPackTemplate>& templ, const std::vector<tTJSVariant>& args ) { tjs_int numargs = static_cast<tjs_int>(args.size()); std::vector<tjs_uint8> result; tjs_size count = templ.size(); tjs_int argindex = 0; for( tjs_size i = 0; i < count && argindex < numargs; argindex++ ) { OctPackType t = templ[i].Type; tjs_int len = templ[i].Length; switch( t ) { case OctPack_ascii: // a : ASCII string(ヌル文字が補完される) AsciiToBin( result, args[argindex], '\0', len ); break; case OctPack_ASCII: // A : ASCII string(スペースが補完される) AsciiToBin( result, args[argindex], ' ', len ); break; case OctPack_bitstring: // b : bit string(下位ビットから上位ビットの順) BitStringToBin( result, args[argindex], false, len ); break; case OctPack_BITSTRING: // B : bit string(上位ビットから下位ビットの順) BitStringToBin( result, args[argindex], true, len ); break; case OctPack_char: // c : 符号付き1バイト数値(-128 ~ 127) ReadNumber<tjs_int8,tjs_int,1,tjs_int8>( result, args, numargs, argindex, len ); break; case OctPack_CHAR: // C : 符号無し1バイト数値(0~255) ReadNumber<tjs_uint8,tjs_int,1,tjs_uint8>( result, args, numargs, argindex, len ); break; case OctPack_double: // d : 倍精度浮動小数点 ReadNumber<tjs_real,tjs_real,8,tjs_uint64>( result, args, numargs, argindex, len ); break; case OctPack_float: // f : 単精度浮動小数点 ReadNumber<float,tjs_real,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_hex: // h : hex string(low nybble first) HexToBin( result, args[argindex], false, len ); break; case OctPack_HEX: // H : hex string(high nybble first) HexToBin( result, args[argindex], true, len ); break; case OctPack_int: // i : 符号付きint数値(通常4バイト) case OctPack_long: // l : 符号付きlong数値(通常4バイト) ReadNumber<tjs_int,tjs_int,4,tjs_int32>( result, args, numargs, argindex, len ); break; case OctPack_INT: // I : 符号無しint数値(通常4バイト) case OctPack_LONG: // L : 符号無しlong数値(通常4バイト) ReadNumber<tjs_uint,tjs_int64,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_noshort: // n : unsigned short数値(ネットワークバイトオーダ) network byte order short ReadNumberBE<tjs_uint16,tjs_int,2,tjs_uint16>( result, args, numargs, argindex, len ); break; case OctPack_NOLONG: // N : unsigned long数値(ネットワークバイトオーダ) network byte order long ReadNumberBE<tjs_uint,tjs_int64,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_pointer: // p : 文字列へのポインタ null terminate char case OctPack_POINTER: // P : 構造体(固定長文字列)へのポインタ fix length char // TODO break; case OctPack_short: // s : 符号付きshort数値(通常2バイト) sign ReadNumber<tjs_int16,tjs_int,2,tjs_int16>( result, args, numargs, argindex, len ); break; case OctPack_SHORT: // S : 符号無しshort数値(通常2バイト) unsign ReadNumber<tjs_uint16,tjs_int,2,tjs_uint16>( result, args, numargs, argindex, len ); break; case OctPack_leshort: // v : リトルエンディアンによるunsigned short値 little endian short ReadNumberLE<tjs_uint16,tjs_int,2,tjs_uint16>( result, args, numargs, argindex, len ); break; case OctPack_LELONG: // V : リトルエンディアンによるunsigned long値 little endian long ReadNumberLE<tjs_uint,tjs_int64,4,tjs_uint32>( result, args, numargs, argindex, len ); break; case OctPack_uuencode: // u : uuencodeされた文字列 TJS_eTJSError( TJSNotSupportedUuencode ); break; case OctPack_BRE: // w : BER圧縮された整数値 TJS_eTJSError( TJSNotSupportedBER ); break; case OctPack_null: // x : ヌル文字 for( tjs_int a = 0; a < len; a++ ) { result.push_back( 0 ); } argindex--; break; case OctPack_NULL: // X : back up a byte for( tjs_int a = 0; a < len; a++ ) { result.pop_back(); } argindex--; break; case OctPack_fill: { // @ : 絶対位置までヌル文字を埋める tjs_size count = result.size(); for( tjs_size i = count; i < (tjs_size)len; i++ ) { result.push_back( 0 ); } argindex--; break; } case OctPack_base64: { // m : Base64 encode / decode ttstr tmp = args[argindex]; decodeBase64( tmp.AsStdString(), result ); break; } } if( len >= 0 ) { // '*' の時は-1が入り、リストの末尾まで読む i++; } } if( result.size() > 0 ) return TJSAllocVariantOctet( &(result[0]), (tjs_uint)result.size() ); else return NULL; } static void BinToAscii( const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len, ttstr& result ) { //std::vector<tjs_nchar> tmp(len+1); std::vector<tjs_nchar> tmp; tmp.reserve(len+1); for( tjs_int i = 0; i < static_cast<tjs_int>(len) && data != tail; data++, i++ ) { if( (*data) != '\0' ) { tmp.push_back( (tjs_nchar)*data ); } } tmp.push_back( (tjs_nchar)'\0' ); result = tTJSString( &(tmp[0]) ); } // mtol : true : 上位ビットから下位ビット, false : 下位ビットから上位ビット // 指定した数値の方が大きくても、その分は無視 static void BinToBitString( const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len, ttstr& result, bool mtol ) { //std::vector<tjs_char> tmp(len+1); std::vector<tjs_char> tmp; tmp.reserve(len+1); tjs_int pos = 0; if( mtol ) { for( ; data < tail; data++ ) { for( tjs_int i = 0; i < 8 && pos < static_cast<tjs_int>(len); i++, pos++ ) { if( (*data)&(0x01<<(7-i)) ) { tmp.push_back( TJS_W('1') ); } else { tmp.push_back( TJS_W('0') ); } } if( pos >= static_cast<tjs_int>(len) ) break; } } else { for( ; data < tail; data++ ) { for( tjs_int i = 0; i < 8 && pos < static_cast<tjs_int>(len); i++, pos++ ) { if( (*data)&(0x01<<i) ) { tmp.push_back( TJS_W('1') ); } else { tmp.push_back( TJS_W('0') ); } } if( pos >= static_cast<tjs_int>(len) ) break; } } tmp.push_back( TJS_W('\0') ); result = tTJSString( &(tmp[0]) ); } // TRet : 最終的に出力する型 template<typename TRet, int NBYTE> static void BinToNumberLE( std::vector<TRet>& result, const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len ) { if( len < 0 ) len = (tjs_uint)(((tail - data)+NBYTE-1)/NBYTE); if( (data+len*NBYTE) < tail ) tail = data+len*NBYTE; TRet val = 0; tjs_uint bytes = 0; for( ; data < tail; data++ ) { val |= (*data) << (bytes*8); if( bytes >= (NBYTE-1) ) { // little endian bytes = 0; result.push_back( val ); val = 0; } else { bytes++; } } if( bytes ) { result.push_back( val ); } } template<typename TRet, typename TTmp, int NBYTE> static void BinToNumberLEReal( std::vector<TRet>& result, const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len ) { if( len < 0 ) len = (tjs_uint)(((tail - data)+NBYTE-1)/NBYTE); if( (data+len*NBYTE) < tail ) tail = data+len*NBYTE; TTmp val = 0; tjs_uint bytes = 0; for( ; data < tail; data++ ) { val |= (TTmp)(*data) << (bytes*8); if( bytes >= (NBYTE-1) ) { // little endian bytes = 0; result.push_back( *(TRet*)&val ); val = 0; } else { bytes++; } } if( bytes ) { result.push_back( *(TRet*)&val ); } } template<typename TRet, int NBYTE> static void BinToNumberBE( std::vector<TRet>& result, const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len ) { if( len < 0 ) len = (tjs_uint)(((tail - data)+NBYTE-1)/NBYTE); if( (data+len*NBYTE) < tail ) tail = data+len*NBYTE; TRet val = 0; tjs_uint bytes = NBYTE-1; for( ; data < tail; data++ ) { val |= (*data) << (bytes*8); if( bytes == 0 ) { // big endian bytes = NBYTE-1; result.push_back( val ); val = 0; } else { bytes--; } } if( bytes < (NBYTE-1) ) { result.push_back( val ); } } #if TJS_HOST_IS_BIG_ENDIAN # define BinToNumber BinToNumberBE #else # define BinToNumber BinToNumberLE # define BinToReal BinToNumberLEReal #endif // mtol static void BinToHex( const tjs_uint8 *data, const tjs_uint8 *tail, tjs_uint len, ttstr& result, bool mtol ) { if( (data+len) < tail ) tail = data+(len+1)/2; //std::vector<tjs_char> tmp(len+1); std::vector<tjs_char> tmp; tmp.reserve(len+1); tjs_int pos = 0; if( mtol ) { // 上位ニブルが先 pos = 1; for( tjs_int i = 0; i < static_cast<tjs_int>(len) && data < tail; i++ ) { tjs_char ch = ((*data)&(0xF<<(pos*4)))>>(pos*4); if( ch > 9 ) { ch = TJS_W('A') + (ch-10); } else { ch = TJS_W('0') + ch; } tmp.push_back( ch ); if( pos == 0 ) { pos = 1; data++; } else { pos--; } } } else { // 下位ニブルが先 for( tjs_int i = 0; i < static_cast<tjs_int>(len) && data < tail; i++ ) { tjs_char ch = ((*data)&(0xF<<(pos*4)))>>(pos*4); if( ch > 9 ) { ch = TJS_W('A') + (ch-10); } else { ch = TJS_W('0') + ch; } tmp.push_back( ch ); if( pos ) { pos = 0; data++; } else { pos++; } } } tmp.push_back( TJS_W('\0') ); result = tTJSString( &(tmp[0]) ); } static iTJSDispatch2* Unpack( const std::vector<OctPackTemplate>& templ, const tjs_uint8 *data, tjs_uint length ) { tTJSArrayObject* result = reinterpret_cast<tTJSArrayObject*>( TJSCreateArrayObject() ); tTJSArrayNI *ni; if(TJS_FAILED(result->NativeInstanceSupport(TJS_NIS_GETINSTANCE, TJSGetArrayClassID(), (iTJSNativeInstance**)&ni))) TJS_eTJSError(TJSSpecifyArray); const tjs_uint8 *current = data; const tjs_uint8 *tail = data + length; tjs_size len = length; tjs_size count = templ.size(); tjs_int argindex = 0; for( tjs_int i = 0; i < (tjs_int)count && current < tail; argindex++ ) { OctPackType t = templ[i].Type; tjs_size len = templ[i].Length; switch( t ) { case OctPack_ascii:{ // a : ASCII string(ヌル文字が補完される) if( len < 0 ) len = (tail - current); ttstr ret; BinToAscii( current, tail, (tjs_uint)len, ret ); result->Add( ni, tTJSVariant( ret ) ); current += len; break; } case OctPack_ASCII: { // A : ASCII string(スペースが補完される) if( len < 0 ) len = (tail - current); ttstr ret; BinToAscii( current, tail, (tjs_uint)len, ret ); result->Add( ni, tTJSVariant( ret ) ); current += len; break; } case OctPack_bitstring: { // b : bit string(下位ビットから上位ビットの順) if( len < 0 ) len = (tail - current)*8; ttstr ret; BinToBitString( current, tail, (tjs_uint)len, ret, false ); result->Add( ni, tTJSVariant( ret ) ); current += (len+7)/8; break; } case OctPack_BITSTRING: { // B : bit string(上位ビットから下位ビットの順) if( len < 0 ) len = (tail - current)*8; ttstr ret; BinToBitString( current, tail, (tjs_uint)len, ret, true ); result->Add( ni, tTJSVariant( ret ) ); current += (len+7)/8; break; } case OctPack_char: { // c : 符号付き1バイト数値(-128 ~ 127) if( len < 0 ) len = tail - current; std::vector<tjs_int8> ret; BinToNumber<tjs_int8,1>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_int8>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len; break; } case OctPack_CHAR: { // C : 符号無し1バイト数値(0~255) if( len < 0 ) len = tail - current; std::vector<tjs_uint8> ret; BinToNumber<tjs_uint8,1>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint8>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len; break; } case OctPack_double: { // d : 倍精度浮動小数点 if( len < 0 ) len = (tail - current)/8; std::vector<tjs_real> ret; BinToReal<tjs_real,tjs_uint64,8>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_real>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_real)*iter ) ); } current += len*8; break; } case OctPack_float: { // f : 単精度浮動小数点 if( len < 0 ) len = (tail - current)/4; std::vector<float> ret; BinToReal<float,tjs_uint32,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<float>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_real)*iter ) ); } current += len*4; break; } case OctPack_hex: { // h : hex string(low nybble first) if( len < 0 ) len = (tail - current)*2; ttstr ret; BinToHex( current, tail, (tjs_uint)len, ret, false ); result->Add( ni, tTJSVariant( ret ) ); current += (len+1)/2; break; } case OctPack_HEX: { // H : hex string(high nybble first) if( len < 0 ) len = (tail - current)*2; ttstr ret; BinToHex( current, tail, (tjs_uint)len, ret, true ); result->Add( ni, tTJSVariant( ret ) ); current += (len+1)/2; break; } case OctPack_int: // i : 符号付きint数値(通常4バイト) case OctPack_long: { // l : 符号付きlong数値(通常4バイト) if( len < 0 ) len = (tail - current)/4; std::vector<tjs_int> ret; BinToNumber<tjs_int,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_int>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*4; break; } case OctPack_INT: // I : 符号無しint数値(通常4バイト) case OctPack_LONG: { // L : 符号無しlong数値(通常4バイト) if( len < 0 ) len = (tail - current)/4; std::vector<tjs_uint> ret; BinToNumber<tjs_uint,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_int64)*iter ) ); } current += len*4; break; } case OctPack_noshort: { // n : unsigned short数値(ネットワークバイトオーダ) network byte order short if( len < 0 ) len = (tail - current)/2; std::vector<tjs_uint16> ret; BinToNumberBE<tjs_uint16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_NOLONG: { // N : unsigned long数値(ネットワークバイトオーダ) network byte order long if( len < 0 ) len = ((tail - current)/4); std::vector<tjs_uint> ret; BinToNumberBE<tjs_uint,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_int64)*iter ) ); } current += len*4; break; } case OctPack_pointer: // p : 文字列へのポインタ null terminate char TJS_eTJSError( TJSNotSupportedUnpackLP ); break; case OctPack_POINTER: // P : 構造体(固定長文字列)へのポインタ fix length char TJS_eTJSError( TJSNotSupportedUnpackP ); break; case OctPack_short: { // s : 符号付きshort数値(通常2バイト) sign if( len < 0 ) len = ((tail - current)/2); std::vector<tjs_int16> ret; BinToNumber<tjs_int16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_int16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_SHORT: { // S : 符号無しshort数値(通常2バイト) unsign if( len < 0 ) len = ((tail - current)/2); std::vector<tjs_uint16> ret; BinToNumber<tjs_uint16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_leshort: { // v : リトルエンディアンによるunsigned short値 little endian short if( len < 0 ) len = ((tail - current)/2); std::vector<tjs_uint16> ret; BinToNumberLE<tjs_uint16,2>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint16>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tTVInteger)*iter ) ); } current += len*2; break; } case OctPack_LELONG: { // V : リトルエンディアンによるunsigned long値 little endian long if( len < 0 ) len = ((tail - current)/4); std::vector<tjs_uint> ret; BinToNumberLE<tjs_uint,4>( ret, current, tail, (tjs_uint)len ); for( std::vector<tjs_uint>::const_iterator iter = ret.begin(); iter != ret.end(); iter++ ) { result->Add( ni, tTJSVariant( (tjs_int64)*iter ) ); } current += len*4; break; } case OctPack_uuencode: // u : uuencodeされた文字列 TJS_eTJSError( TJSNotSupportedUuencode ); break; case OctPack_BRE: // w : BER圧縮された整数値 TJS_eTJSError( TJSNotSupportedBER ); break; case OctPack_null: // x : ヌル文字 if( len < 0 ) len = (tail - current); for( tjs_int x = 0; x < (tjs_int)len; x++ ) { current++; } break; case OctPack_NULL: // X : back up a byte if( len < 0 ) len = (current - data); for( tjs_int x = 0; x < (tjs_int)len; x++ ) { if( data != current ) current--; else break; } break; case OctPack_fill: { // @ : 絶対位置までヌル文字を埋める if( len < 0 ) len = (tail - current); current = &(data[len]); break; } case OctPack_base64: { // m : Base64 encode / decode tjs_string ret; encodeBase64( current, (tjs_uint)(tail-current), ret ); result->Add( ni, tTJSVariant( ret.c_str() ) ); current = tail; break; } } i++; } return result; } tjs_error TJSOctetPack( tTJSVariant **args, tjs_int numargs, const std::vector<tTJSVariant>& items, tTJSVariant *result ) { if( numargs < 1 ) return TJS_E_BADPARAMCOUNT; if( args[0]->Type() != tvtString ) return TJS_E_INVALIDPARAM; if( result ) { std::vector<OctPackTemplate> templ; ParsePackTemplate( templ, ((ttstr)*args[0]).c_str() ); tTJSVariantOctet* oct = Pack( templ, items ); *result = oct; if( oct ) oct->Release(); else *result = tTJSVariant((iTJSDispatch2*)NULL,(iTJSDispatch2*)NULL); } return TJS_S_OK; } tjs_error TJSOctetUnpack( const tTJSVariantOctet * target, tTJSVariant **args, tjs_int numargs, tTJSVariant *result ) { if( numargs < 1 ) return TJS_E_BADPARAMCOUNT; if( args[0]->Type() != tvtString ) return TJS_E_INVALIDPARAM; if( !target ) return TJS_E_INVALIDPARAM; if( result ) { std::vector<OctPackTemplate> templ; ParsePackTemplate( templ, ((ttstr)*args[0]).c_str() ); iTJSDispatch2* disp = Unpack( templ, target->GetData(), target->GetLength() ); *result = tTJSVariant(disp,disp); if( disp ) disp->Release(); } return TJS_S_OK; } } // namespace TJS
32.770529
147
0.600144
metarin
090ad33ddc5f7ee52ea84fc6e6ae207604f628a5
5,283
cpp
C++
Private/HTNWorldState.cpp
ThomasWilliamWallace/htn_planner
689192a3c3a7c6668bb1bc1192229d8eaef66f26
[ "MIT" ]
2
2020-08-30T17:05:29.000Z
2020-12-02T17:13:42.000Z
Private/HTNWorldState.cpp
ThomasWilliamWallace/htn_planner
689192a3c3a7c6668bb1bc1192229d8eaef66f26
[ "MIT" ]
null
null
null
Private/HTNWorldState.cpp
ThomasWilliamWallace/htn_planner
689192a3c3a7c6668bb1bc1192229d8eaef66f26
[ "MIT" ]
null
null
null
#include "HTNWorldState.h" #include <cmath> #include "PlayerData.h" #include "AbstractItem.h" #include "pLog.h" #include <sstream> #include "Missions.h" //*********************************************************** HTNWorldState::HTNWorldState(UPlayerData* playerPtr, PlayerMap& playerMap, std::vector<RealItemType*>& realItems, UPlayerData* requester, std::vector<UPlayerData*> attackers, std::vector<UPlayerData*> playersInTheRoom, float health, float sanity, float strength, float agility, float intelligence): m_ptrToSelf(playerPtr), m_health(health), m_sanity(sanity), m_strength(strength), m_agility(agility), m_intelligence(intelligence), m_evading(m_ptrToSelf->lastAction->m_action == EActions::evade), m_location(m_ptrToSelf->locationClass.location), m_missionClass(playerPtr->missionClass), m_requester(requester), m_attackers(attackers), m_playersInTheRoom(playersInTheRoom) { for (auto &item : realItems) { m_items.push_back(std::make_shared<SimItem>(CreateSimFromRealItem::CreateSimFromRealItem, item)); if ((m_items.back()->m_carryingPlayer) == m_ptrToSelf) { m_itemCarriedPtr = m_items.back(); } } // std::cout << "constructed HTNWorldState.m_items:\n"; // for (auto& itemPtr : m_items) // { // std::cout << itemPtr << "; realItem=" << itemPtr->m_realItem << "\n"; // } // std::cout << "\n"; } HTNWorldState::HTNWorldState(HTNWorldState const& ws2): m_ptrToSelf(ws2.m_ptrToSelf), m_health(ws2.m_health), m_sanity(ws2.m_sanity), m_strength(ws2.m_strength), m_agility(ws2.m_agility), m_intelligence(ws2.m_intelligence), m_evading(ws2.m_evading), m_location(ws2.m_location), m_missionClass(ws2.m_missionClass), m_itemCarriedPtr(nullptr), m_requester(ws2.m_requester), m_attackers(ws2.m_attackers), m_playersInTheRoom(ws2.m_playersInTheRoom) { for (auto &item : ws2.m_items) { m_items.emplace_back(std::make_shared<SimItem>(*(item.get()))); m_items.back()->m_realItem = item->m_realItem; if (ws2.m_itemCarriedPtr != nullptr && ws2.m_itemCarriedPtr->m_realItem == item->m_realItem) { m_itemCarriedPtr = m_items.back(); } } // std::cout << "COPY constructed HTNWorldState.m_items:\n"; // for (auto& itemPtr : m_items) // { // std::cout << itemPtr << "; realItem=" << itemPtr->m_realItem << "\n"; // } // std::cout << "\n"; } HTNWorldState& HTNWorldState::operator=(HTNWorldState const& ws2) { m_ptrToSelf = ws2.m_ptrToSelf; m_health = ws2.m_health; m_sanity = ws2.m_sanity; m_strength = ws2.m_strength; m_agility = ws2.m_agility; m_intelligence = ws2.m_intelligence; m_evading = ws2.m_evading; m_location = ws2.m_location; m_itemCarriedPtr = nullptr; m_requester = ws2.m_requester; m_attackers = ws2.m_attackers; m_playersInTheRoom = ws2.m_playersInTheRoom; m_items.clear(); for (auto &item : ws2.m_items) { m_items.emplace_back(std::make_shared<SimItem>(*(item.get()))); m_items.back()->m_realItem = item->m_realItem; if (ws2.m_itemCarriedPtr == item) { m_itemCarriedPtr = m_items.back(); } } // std::cout << "ASSIGNMENT constructed HTNWorldState.m_items:\n"; // for (auto& itemPtr : m_items) // { // std::cout << itemPtr << "; realItem=" << itemPtr->m_realItem << "\n"; // } // std::cout << "\n"; m_missionClass = ws2.m_missionClass; return *this; } void HTNWorldState::Print() { std::stringstream ss; ss << "HTNWorldState::Print\n"; ss << "m_health:" << m_health << "\n"; ss << "m_sanity:" << m_sanity << "\n"; ss << "m_strength:" << m_strength << "\n"; ss << "m_agility:" << m_agility << "\n"; ss << "m_intelligence:" << m_intelligence << "\n"; ss << "m_evading:" << m_evading << "\n"; ss << "m_location:" << static_cast<int>(m_location) << "\n"; ss << "m_ptrToSelf:" << m_ptrToSelf << "\n"; ss << "m_itemCarriedPtr:" << GetRaw(m_itemCarriedPtr) << "\n"; ss << "m_requester:" << m_requester << "\n"; for (auto &simItem : m_items) { ss << "SimItem: " << simItem->ToString() << " carried by "; if (simItem->m_carryingPlayer != nullptr) { ss << simItem->m_carryingPlayer->m_playerName; } else { ss << "NULLPTR"; } ss << " in the " << simItem->m_locationClass.ToString() << " with a link to real item " << simItem << "\n"; } for (auto &p : m_attackers) { ss << "Being attacked by player " << p->m_playerName << " in the " << LocationToString(m_location) << ".\n"; } for (auto &p : m_playersInTheRoom) { if (p != nullptr) ss << "PlayerData " << p->m_playerName << " is also in the " << LocationToString(m_location) << ".\n"; else ThrowException("ERROR NULL PLAYERDATA VALUE"); } ss << "]\n"; // ss << "m_missionClass:" << m_missionClass->MissionName() << "\n"; pLog(ss); } bool HTNWorldState::IsInTheRoom(UPlayerData const& playerPtr) const { for (auto &p : m_playersInTheRoom) { if (p == &playerPtr) { return true; } } return false; }
32.213415
118
0.609881
ThomasWilliamWallace
090b808402fce273cb8c666bb99d5fc9f37f149a
857
cpp
C++
eval_server/src/answer.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
1
2016-11-02T08:42:05.000Z
2016-11-02T08:42:05.000Z
eval_server/src/answer.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
null
null
null
eval_server/src/answer.cpp
tnct-spc/procon2014
c2df3257675db2adb9caa882b9026145801c6e4d
[ "MIT" ]
null
null
null
#include "answer.hpp" // 🍣🍣🍣 解答変換 🍣🍣🍣 void Answer::convert(std::string const& s) { answer_type al; answer_atom a; std::istringstream ss; ss.str(s); int nl; // 選択回数 ss >> nl; for(int i = 0; i < nl; i++) { std::string pos; ss >> pos; point_type ipos{std::stoi(pos.substr(0, 1), nullptr, 16), std::stoi(pos.substr(1, 1), nullptr, 16)}; if(ipos.x == -1 || ipos.y == -1) { outerr << "ERROR: illegal position: \"" + pos + "\"\n"; return; } else a.position = ipos; int nx; // 交換回数 ss >> nx; std::string move(""); ss >> move; a.actions = std::move(move); al.list.push_back(a); } final_answer = al; outerr << "STATUS: submitted answer was loaded successfully\n" << std::endl; sane = true; }
23.805556
108
0.493582
tnct-spc
090b83580727fe842d882ffad58bdb622651caed
3,591
cpp
C++
src-plugins/itkProcessRegistrationDiffeomorphicDemons/itkProcessRegistrationDiffeomorphicDemonsPlugin.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/itkProcessRegistrationDiffeomorphicDemons/itkProcessRegistrationDiffeomorphicDemonsPlugin.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
src-plugins/itkProcessRegistrationDiffeomorphicDemons/itkProcessRegistrationDiffeomorphicDemonsPlugin.cpp
ocommowi/medInria-public
9074e40c886881666e7a52c53309d8d28e35c0e6
[ "BSD-4-Clause" ]
null
null
null
/*========================================================================= medInria Copyright (c) INRIA 2013. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include "itkProcessRegistrationDiffeomorphicDemons.h" #include "itkProcessRegistrationDiffeomorphicDemonsPlugin.h" #include "itkProcessRegistrationDiffeomorphicDemonsToolBox.h" #include <dtkLog/dtkLog.h> // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsPluginPrivate // ///////////////////////////////////////////////////////////////// class itkProcessRegistrationDiffeomorphicDemonsPluginPrivate { public: // Class variables go here. }; // ///////////////////////////////////////////////////////////////// // itkProcessRegistrationDiffeomorphicDemonsPlugin // ///////////////////////////////////////////////////////////////// itkProcessRegistrationDiffeomorphicDemonsPlugin::itkProcessRegistrationDiffeomorphicDemonsPlugin(QObject *parent) : dtkPlugin(parent), d(new itkProcessRegistrationDiffeomorphicDemonsPluginPrivate) { } itkProcessRegistrationDiffeomorphicDemonsPlugin::~itkProcessRegistrationDiffeomorphicDemonsPlugin() { delete d; d = NULL; } bool itkProcessRegistrationDiffeomorphicDemonsPlugin::initialize() { if (!itkProcessRegistrationDiffeomorphicDemons::registered()) { dtkWarn() << "Unable to register itkProcessRegistrationDiffeomorphicDemons type"; } if (!itkProcessRegistrationDiffeomorphicDemonsToolBox::registered()) { dtkWarn() << "Unable to register itkProcessRegistrationDiffeomorphicDemons toolbox"; } return true; } bool itkProcessRegistrationDiffeomorphicDemonsPlugin::uninitialize() { return true; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::name() const { return "itkProcessRegistrationDiffeomorphicDemonsPlugin"; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::contact() const { return QString::fromUtf8("benoit.bleuze@inria.fr"); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::authors() const { QStringList list; list << QString::fromUtf8("Benoît Bleuzé"); return list; } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::contributors() const { QStringList list; list << "Vincent Garcia"; return list; } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::description() const { return tr("Applies the diffeomorphic demons as they can be found in itk. Converts any type of image to float before applying the change, since the diffeomorphic demons only work on float images <br/> see: <a href=\"http://www.insight-journal.org/browse/publication/154\" > http://www.insight-journal.org/browse/publication/154 </a>"); } QString itkProcessRegistrationDiffeomorphicDemonsPlugin::version() const { return ITKPROCESSREGISTRATIONDIFFEOMORPHICDEMONSPLUGIN_VERSION; } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::dependencies() const { return QStringList(); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::tags() const { return QStringList(); } QStringList itkProcessRegistrationDiffeomorphicDemonsPlugin::types() const { return QStringList() << "itkProcessRegistrationDiffeomorphicDemons"; } Q_EXPORT_PLUGIN2(itkProcessRegistrationDiffeomorphicDemonsPlugin, itkProcessRegistrationDiffeomorphicDemonsPlugin)
31.5
338
0.714286
ocommowi