text
stringlengths
54
60.6k
<commit_before>#include "request.hh" #include <cstring> #include <memory> #include <string_view> #include <curl/curl.h> namespace aur { namespace { std::string UrlEscape(const std::string_view sv) { char* ptr = curl_easy_escape(nullptr, sv.data(), sv.size()); std::string escaped(ptr); curl_free(ptr); return escaped; } char* AppendUnsafe(char* to, std::string_view from) { auto ptr = mempcpy(to, from.data(), from.size()); return static_cast<char*>(ptr); } template <typename... Pieces> void StrAppend(std::string* out, const Pieces&... args) { std::vector<std::string_view> v{args...}; std::string::size_type append_sz = 0; for (const auto& piece : v) { append_sz += piece.size(); } auto original_sz = out->size(); out->resize(original_sz + append_sz); char* ptr = out->data() + original_sz; for (const auto& piece : v) { ptr = AppendUnsafe(ptr, piece); } } template <typename... Pieces> std::string StrCat(const Pieces&... args) { std::string out; StrAppend(&out, args...); return out; } void QueryParamFormatter(std::string* out, const std::pair<std::string, std::string>& kv) { StrAppend(out, kv.first, "=", UrlEscape(kv.second)); } template <typename Iterator, typename Formatter> std::string StrJoin(Iterator begin, Iterator end, std::string_view s, Formatter&& f) { std::string result; std::string_view sep(""); for (Iterator it = begin; it != end; ++it) { result.append(sep.data(), sep.size()); f(&result, *it); sep = s; } return result; } } // namespace void RpcRequest::AddArg(const std::string& key, const std::string& value) { args_.emplace_back(key, value); } std::vector<std::string> RpcRequest::Build(const std::string& baseurl) const { const auto next_span = [&](const std::string_view& s) { // No chopping needed. if (s.size() <= approx_max_length_) { return s; } // Try to chop at the final ampersand before the cutoff length. auto n = s.substr(0, approx_max_length_).rfind('&'); if (n != std::string_view::npos) { return s.substr(0, n); } // We found a single arg which is Too Damn Long. Look for the ampersand just // after the length limit and use all of it. n = s.substr(approx_max_length_).find('&'); if (n != std::string_view::npos) { return s.substr(0, n + approx_max_length_); } // We're at the end of the querystring and have no place to chop. return s; }; const auto qs = StrJoin(args_.begin(), args_.end(), "&", &QueryParamFormatter); std::string_view sv(qs); std::vector<std::string> requests; while (!sv.empty()) { const auto span = next_span(sv); requests.push_back(StrCat(baseurl, "/rpc?", base_querystring_, "&", span)); sv.remove_prefix(std::min(sv.length(), span.length() + 1)); } return requests; } RpcRequest::RpcRequest( const std::vector<std::pair<std::string, std::string>>& base_params, long unsigned approx_max_length) : base_querystring_(StrJoin(base_params.begin(), base_params.end(), "&", &QueryParamFormatter)), approx_max_length_(approx_max_length) {} // static RawRequest RawRequest::ForTarball(const Package& package) { return RawRequest(package.aur_urlpath); } // static RawRequest RawRequest::ForSourceFile(const Package& package, const std::string& filename) { return RawRequest(StrCat("/cgit/aur.git/plain/", filename, "?h=", UrlEscape(package.pkgbase))); } std::vector<std::string> RawRequest::Build(const std::string& baseurl) const { return {StrCat(baseurl, urlpath_)}; } std::vector<std::string> CloneRequest::Build(const std::string& baseurl) const { return {StrCat(baseurl, "/", reponame_)}; } } // namespace aur <commit_msg>Avoid temporary lifetime extension next_span lambda<commit_after>#include "request.hh" #include <cstring> #include <memory> #include <string_view> #include <curl/curl.h> namespace aur { namespace { std::string UrlEscape(const std::string_view sv) { char* ptr = curl_easy_escape(nullptr, sv.data(), sv.size()); std::string escaped(ptr); curl_free(ptr); return escaped; } char* AppendUnsafe(char* to, std::string_view from) { auto ptr = mempcpy(to, from.data(), from.size()); return static_cast<char*>(ptr); } template <typename... Pieces> void StrAppend(std::string* out, const Pieces&... args) { std::vector<std::string_view> v{args...}; std::string::size_type append_sz = 0; for (const auto& piece : v) { append_sz += piece.size(); } auto original_sz = out->size(); out->resize(original_sz + append_sz); char* ptr = out->data() + original_sz; for (const auto& piece : v) { ptr = AppendUnsafe(ptr, piece); } } template <typename... Pieces> std::string StrCat(const Pieces&... args) { std::string out; StrAppend(&out, args...); return out; } void QueryParamFormatter(std::string* out, const std::pair<std::string, std::string>& kv) { StrAppend(out, kv.first, "=", UrlEscape(kv.second)); } template <typename Iterator, typename Formatter> std::string StrJoin(Iterator begin, Iterator end, std::string_view s, Formatter&& f) { std::string result; std::string_view sep(""); for (Iterator it = begin; it != end; ++it) { result.append(sep.data(), sep.size()); f(&result, *it); sep = s; } return result; } } // namespace void RpcRequest::AddArg(const std::string& key, const std::string& value) { args_.emplace_back(key, value); } std::vector<std::string> RpcRequest::Build(const std::string& baseurl) const { const auto next_span = [&](std::string_view s) -> std::string_view { // No chopping needed. if (s.size() <= approx_max_length_) { return s; } // Try to chop at the final ampersand before the cutoff length. auto n = s.substr(0, approx_max_length_).rfind('&'); if (n != std::string_view::npos) { return s.substr(0, n); } // We found a single arg which is Too Damn Long. Look for the ampersand just // after the length limit and use all of it. n = s.substr(approx_max_length_).find('&'); if (n != std::string_view::npos) { return s.substr(0, n + approx_max_length_); } // We're at the end of the querystring and have no place to chop. return s; }; const auto qs = StrJoin(args_.begin(), args_.end(), "&", &QueryParamFormatter); std::string_view sv(qs); std::vector<std::string> requests; while (!sv.empty()) { const auto span = next_span(sv); requests.push_back(StrCat(baseurl, "/rpc?", base_querystring_, "&", span)); sv.remove_prefix(std::min(sv.length(), span.length() + 1)); } return requests; } RpcRequest::RpcRequest( const std::vector<std::pair<std::string, std::string>>& base_params, long unsigned approx_max_length) : base_querystring_(StrJoin(base_params.begin(), base_params.end(), "&", &QueryParamFormatter)), approx_max_length_(approx_max_length) {} // static RawRequest RawRequest::ForTarball(const Package& package) { return RawRequest(package.aur_urlpath); } // static RawRequest RawRequest::ForSourceFile(const Package& package, const std::string& filename) { return RawRequest(StrCat("/cgit/aur.git/plain/", filename, "?h=", UrlEscape(package.pkgbase))); } std::vector<std::string> RawRequest::Build(const std::string& baseurl) const { return {StrCat(baseurl, urlpath_)}; } std::vector<std::string> CloneRequest::Build(const std::string& baseurl) const { return {StrCat(baseurl, "/", reponame_)}; } } // namespace aur <|endoftext|>
<commit_before>#include <QtWidgets> #include "seafile-applet.h" #include "utils/utils.h" #include "about-dialog.h" #ifdef HAVE_SPARKLE_SUPPORT #include "auto-update-service.h" namespace { } // namespace #endif AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("About %1").arg(getBrand())); setWindowIcon(QIcon(":/images/seafile.png")); setWindowFlags((windowFlags() & ~Qt::WindowContextHelpButtonHint) | Qt::WindowStaysOnTopHint); version_text_ = tr("<h2>%1 Client %2</h2>") .arg(getBrand()) .arg(STRINGIZE(SEAFILE_CLIENT_VERSION)) #ifdef SEAFILE_CLIENT_REVISION .append(tr("<h5> REV %1 </h5>")) .arg(STRINGIZE(SEAFILE_CLIENT_REVISION)) #endif ; mVersionText->setText(version_text_); connect(mOKBtn, SIGNAL(clicked()), this, SLOT(close())); #ifdef HAVE_SPARKLE_SUPPORT mCheckUpdateBtn->setVisible(true); connect(mCheckUpdateBtn, SIGNAL(clicked()), this, SLOT(checkUpdate())); #else mCheckUpdateBtn->setVisible(false); #endif } #ifdef HAVE_SPARKLE_SUPPORT void AboutDialog::checkUpdate() { AutoUpdateService::instance()->checkUpdate(); close(); } #endif <commit_msg>Fix version check display<commit_after>#include <QtWidgets> #include "seafile-applet.h" #include "utils/utils.h" #include "about-dialog.h" #ifdef HAVE_SPARKLE_SUPPORT #include "auto-update-service.h" #endif namespace { } // namespace AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent) { setupUi(this); setWindowTitle(tr("About %1").arg(getBrand())); setWindowIcon(QIcon(":/images/seafile.png")); setWindowFlags((windowFlags() & ~Qt::WindowContextHelpButtonHint) | Qt::WindowStaysOnTopHint); version_text_ = tr("<h2>%1 Client %2</h2>") .arg(getBrand()) .arg(STRINGIZE(SEAFILE_CLIENT_VERSION)) #ifdef SEAFILE_CLIENT_REVISION .append(tr("<h5> REV %1 </h5>")) .arg(STRINGIZE(SEAFILE_CLIENT_REVISION)) #endif ; mVersionText->setText(version_text_); connect(mOKBtn, SIGNAL(clicked()), this, SLOT(close())); mCheckUpdateBtn->setVisible(false); #ifdef HAVE_SPARKLE_SUPPORT if (AutoUpdateService::instance()->shouldSupportAutoUpdate()) { mCheckUpdateBtn->setVisible(true); connect(mCheckUpdateBtn, SIGNAL(clicked()), this, SLOT(checkUpdate())); } #endif } #ifdef HAVE_SPARKLE_SUPPORT void AboutDialog::checkUpdate() { AutoUpdateService::instance()->checkUpdate(); close(); } #endif <|endoftext|>
<commit_before>/** * @file AvailableSoftware.C * @author Christian Holm Christensen <cholm@master.hehi.nbi.dk> * @date Tue Oct 16 17:54:11 2012 * * @brief Find available packages * * @ingroup pwglf_forward_trains_util */ #ifndef AVAILABLESOFTWARE_C #define AVAILABLESOFTWARE_C #ifndef __CINT__ # include <TString.h> # include <TSystem.h> # include <TError.h> # include <TObjArray.h> # include <TList.h> # include <TPRegexp.h> # include <TObjString.h> # include <fstream> #else class TString; class TList; #endif /** * Railway code to find available packages on Grid * * * @ingroup pwglf_forward_trains_util */ struct AvailableSoftware { static const char* GetField(TObject* o) { static TString r; if (!o) return ""; TString s(o->GetName()); TString t = s.Strip(TString::kBoth,' '); r = t.Strip(TString::kBoth, '\t'); return r.Data(); } /** * Get the full map of packages to dependencies * * @return the list */ static TList* GetMap() { static TList l; if (l.GetEntries() > 0) return &l; TString c("wget -q http://alimonitor.cern.ch/packages/ -O - | " "sed -n -e '/<tr class=table_row/,/<\\/tr>/ p' | " "sed -n -e '/<td/,/<\\/td>/ p' | " "sed -e '/\\/*td.*>/d' | " "sed -e 's/<a.*>\\(.*\\)<\\/a>/\\1/'"); TString values = gSystem->GetFromPipe(c); TObjArray* tokens = values.Tokenize("\n"); Int_t n = tokens->GetEntries(); std::ofstream out("values"); out << values << std::endl; out.close(); // Printf("%s", values.Data()); // tokens->ls(); for (Int_t i = 0; i < n; i += 1) { // 2-3 lines per package TObject* opack = tokens->At(i+0); TString pack = GetField(opack); if (pack.IsNull()) { i += 2; continue; } TObjString* odeps = static_cast<TObjString*>(tokens->At(i+1)); TObjString* oblank= static_cast<TObjString*>(tokens->At(i+2)); TObjString* oavail= static_cast<TObjString*>(tokens->At(i+3)); TObjString* odate = static_cast<TObjString*>(tokens->At(i+4)); i += 4; if (oblank) { TString blk = GetField(oblank); if (!blk.IsNull()) ::Warning("", "blanck is not blanck: \"%s\"", oblank->GetName()); } if (oavail) { TString avail = GetField(oavail); if (!avail.EqualTo("Available")) continue; } // TString& pack = opack->String(); pack.ReplaceAll("VO_ALICE@", ""); // TString& deps = odeps->String(); TString deps = GetField(odeps); deps.ReplaceAll("VO_ALICE@", ""); if (!(pack.BeginsWith("AliPhysics") || pack.BeginsWith("AliRoot") || pack.BeginsWith("ROOT"))) continue; if (pack.Contains(".post_install")) continue; l.Add(new TNamed(pack, deps)); // Printf("%-30s: %s", pack.Data(), deps.Data()); } l.Sort(); // l.ls(); tokens->Delete(); delete tokens; return &l; } /** * Get a package * * @param name Package Name * @param query Query. Either a specific version or some combination of * * - last: the newest * - regular: No special tags * - release: Only release tags * - analysis: Only analysis tags * * @return Pointer to package or null */ static TObject* GetPackage(const TString& name, const TString& query) { TList* l = GetMap(); Bool_t list = (query.Contains("list", TString::kIgnoreCase) || query.Contains("help", TString::kIgnoreCase)); Bool_t last = (query.Contains("last", TString::kIgnoreCase) || query.Contains("newest", TString::kIgnoreCase)); Bool_t nots = (query.Contains("nonspecial", TString::kIgnoreCase) || query.Contains("regular", TString::kIgnoreCase) || query.Contains("normal", TString::kIgnoreCase) || query.Contains("standard", TString::kIgnoreCase)); Bool_t rele = (query.Contains("release", TString::kIgnoreCase)); Bool_t anat = (query.Contains("analysis", TString::kIgnoreCase)); if (!query.IsNull() && (!list && !last && !nots && !rele && !anat)) { Info("GetPackage", "%s=%s already specified, leaving that", name.Data(), query.Data()); TObject* o = l->FindObject(Form("%s::%s",name.Data(),query.Data())); return o; } TPRegexp pRele(Form("%s::v[0-9]-[0-9]+-(Rev-|)[0-9]+.*",name.Data())); TPRegexp pAnat(Form("%s::vAN-[0-9]{8}.*", name.Data())); TString vers(Form("%s::%s", name.Data(), query.Data())); if (list) { TString qual; if (nots) qual.Append("regular "); if (rele) qual.Append("release "); if (anat) qual.Append("analysis "); Printf("Available %sversion of %s", qual.Data(), name.Data()); } TIter prev(l, kIterBackward); TObject* o = 0; TObject* r = 0; Bool_t m = false; while ((o = prev())) { TString n(o->GetName()); if (!n.BeginsWith(name)) { if (m) break; continue; } // We found the package m = true; if (last || list) { Bool_t isRele = pRele.MatchB(n); Bool_t isAnat = pAnat.MatchB(n); Bool_t isSpec = !(isRele || isAnat); if (nots && isSpec) continue; if (anat && !isAnat) continue; if (rele && !isRele) continue; if (list) { n.ReplaceAll(Form("%s::", name.Data()), ""); Printf("\t%s", n.Data()); continue; } r = o; break; } if (!vers.EqualTo(n)) continue; r = o; break; } if (!r && !list) Warning("GetPackage", "No match found for %s", vers.Data()); return r; } static Bool_t GetVer(TObject* pack, const TString& name, TString& ret) { if (!pack) { // if (!ret.IsNull()) ret = ""; return false; } ret = pack->GetName(); ret.ReplaceAll(Form("%s::", name.Data()), ""); return true; } /** * Get the dependencies * * @param pack Package * @param which Which dependency * @param ret Return version of dependency * * @return true on success */ static Bool_t GetDep(TObject* pack, const TString& which, TString& ret) { if (!pack) return false; TString deps(pack->GetTitle()); TObjArray* tokens = deps.Tokenize(","); TIter next(tokens); TObjString* s = 0; while ((s = static_cast<TObjString*>(next()))) { TString t = s->String().Strip(TString::kBoth); if (t.BeginsWith(which)) { ret = t; ret.ReplaceAll(Form("%s::",which.Data()), ""); break; } } tokens->Delete(); delete tokens; return !(ret.IsNull()); } static Bool_t Check(TString& aliphysics, TString& aliroot, TString& root) { // Figure out what to do. Bool_t show = (aliphysics.Contains("list", TString::kIgnoreCase) || aliroot.Contains("list", TString::kIgnoreCase) || root.Contains( "list", TString::kIgnoreCase)); TObject* foundPhysics = GetPackage("AliPhysics", aliphysics); GetVer(foundPhysics, "AliPhysics", aliphysics); GetDep(foundPhysics, "AliRoot", aliroot); TObject* foundAliRoot = GetPackage("AliRoot", aliroot); GetVer(foundAliRoot, "AliRoot", aliroot); GetDep(foundAliRoot, "ROOT", root); TObject* foundRoot = GetPackage("ROOT", root); GetVer(foundRoot, "ROOT", root); if (show) return false; if (aliphysics.IsNull() || aliroot.IsNull() || root.IsNull()) { Warning("Check", "Missing packages (%s,%s,%s)", aliphysics.Data(), aliroot.Data(), root.Data()); return false; } return true; } static void Test(const TString& phy, const TString& ali=TString(), const TString& roo=TString()) { TString aliphysics(Form("list,%s", phy.Data())); TString aliroot (Form("list,%s", ali.Data())); TString root (Form("list,%s", roo.Data())); Printf("Checking with AliPhysics=%s AliROOT=%s ROOT=%s", phy.Data(), ali.Data(), roo.Data()); AvailableSoftware::Check(aliphysics,aliroot, root); aliphysics = Form("last,%s",phy.Data()); aliroot = Form("last,%s",ali.Data()); root = Form("last,%s",roo.Data()); if (AvailableSoftware::Check(aliphysics,aliroot, root)) Printf("Got AliPhysics=%s AliROOT=%s ROOT=%s", aliphysics.Data(), aliroot.Data(), root.Data()); } static void Test() { Printf("All available"); AvailableSoftware::Test(""); Printf("All regular"); AvailableSoftware::Test("regular","regular","regular"); Printf("All releases"); AvailableSoftware::Test("release","release","release"); Printf("All analysis tags"); AvailableSoftware::Test("analysis","analysis","analysis"); } }; #endif <commit_msg>fix search patterns<commit_after>/** * @file AvailableSoftware.C * @author Christian Holm Christensen <cholm@master.hehi.nbi.dk> * @date Tue Oct 16 17:54:11 2012 * * @brief Find available packages * * @ingroup pwglf_forward_trains_util */ #ifndef AVAILABLESOFTWARE_C #define AVAILABLESOFTWARE_C #ifndef __CINT__ # include <TString.h> # include <TSystem.h> # include <TError.h> # include <TObjArray.h> # include <TList.h> # include <TPRegexp.h> # include <TObjString.h> # include <fstream> #else class TString; class TList; #endif /** * Railway code to find available packages on Grid * * * @ingroup pwglf_forward_trains_util */ struct AvailableSoftware { static const char* GetField(TObject* o) { static TString r; if (!o) return ""; TString s(o->GetName()); TString t = s.Strip(TString::kBoth,' '); r = t.Strip(TString::kBoth, '\t'); return r.Data(); } /** * Get the full map of packages to dependencies * * @return the list */ static TList* GetMap() { static TList l; if (l.GetEntries() > 0) return &l; TString c("wget -q http://alimonitor.cern.ch/packages/ -O - | " "sed -n -e '/<tr class=table_row/,/<\\/tr>/ p' | " "sed -n -e '/<td/,/<\\/td>/ p' | " "sed -e '/\\/*td.*>/d' | " "sed -e 's/<a.*>\\(.*\\)<\\/a>/\\1/'"); TString values = gSystem->GetFromPipe(c); TObjArray* tokens = values.Tokenize("\n"); Int_t n = tokens->GetEntries(); std::ofstream out("values"); out << values << std::endl; out.close(); // Printf("%s", values.Data()); // tokens->ls(); for (Int_t i = 0; i < n; i += 1) { // 2-3 lines per package TObject* opack = tokens->At(i+0); TString pack = GetField(opack); if (pack.IsNull()) { i += 2; continue; } TObjString* odeps = static_cast<TObjString*>(tokens->At(i+1)); TObjString* oblank= static_cast<TObjString*>(tokens->At(i+2)); TObjString* oavail= static_cast<TObjString*>(tokens->At(i+3)); TObjString* odate = static_cast<TObjString*>(tokens->At(i+4)); i += 4; if (oblank) { TString blk = GetField(oblank); if (!blk.IsNull()) ::Warning("", "blanck is not blanck: \"%s\"", oblank->GetName()); } if (oavail) { TString avail = GetField(oavail); if (!avail.EqualTo("Available")) continue; } // TString& pack = opack->String(); pack.ReplaceAll("VO_ALICE@", ""); // TString& deps = odeps->String(); TString deps = GetField(odeps); deps.ReplaceAll("VO_ALICE@", ""); if (!(pack.BeginsWith("AliPhysics") || pack.BeginsWith("AliRoot") || pack.BeginsWith("ROOT"))) continue; if (pack.Contains(".post_install")) continue; l.Add(new TNamed(pack, deps)); // Printf("%-30s: %s", pack.Data(), deps.Data()); } l.Sort(); // l.ls(); tokens->Delete(); delete tokens; return &l; } /** * Get a package * * @param name Package Name * @param query Query. Either a specific version or some combination of * * - last: the newest * - regular: No special tags * - release: Only release tags * - analysis: Only analysis tags * * @return Pointer to package or null */ static TObject* GetPackage(const TString& name, const TString& query) { TList* l = GetMap(); Bool_t list = (query.Contains("list", TString::kIgnoreCase) || query.Contains("help", TString::kIgnoreCase)); Bool_t last = (query.Contains("last", TString::kIgnoreCase) || query.Contains("newest", TString::kIgnoreCase)); Bool_t nots = (query.Contains("nonspecial", TString::kIgnoreCase) || query.Contains("regular", TString::kIgnoreCase) || query.Contains("normal", TString::kIgnoreCase) || query.Contains("standard", TString::kIgnoreCase)); Bool_t rele = (query.Contains("release", TString::kIgnoreCase)); Bool_t anat = (query.Contains("analysis", TString::kIgnoreCase)); if (!query.IsNull() && (!list && !last && !nots && !rele && !anat)) { Info("GetPackage", "%s=%s already specified, leaving that", name.Data(), query.Data()); TObject* o = l->FindObject(Form("%s::%s",name.Data(),query.Data())); return o; } TString relPat; relPat.Form("%s::v[0-9]-[0-9]{2}+-(Rev-|)[0-9]{2}", name.Data()); if (name.Contains("AliPhysics")) relPat.Append("-[0-9]{2}"); if (name.Contains("ROOT")) relPat.Append("(-alice[0-9]*|)"); relPat.Append("(-[0-9]+|)$"); TPRegexp pRele(relPat); TPRegexp pAnat(Form("%s::vAN-[0-9]{8}(-[0-9]+|)$", name.Data())); TString vers(Form("%s::%s", name.Data(), query.Data())); if (list) { TString qual; if (nots) qual.Append("regular "); if (rele) qual.Append("release "); if (anat) qual.Append("analysis "); Printf("Available %sversion of %s", qual.Data(), name.Data()); } TIter prev(l, kIterBackward); TObject* o = 0; TObject* r = 0; Bool_t m = false; while ((o = prev())) { TString n(o->GetName()); if (!n.BeginsWith(name)) { if (m) break; continue; } // We found the package m = true; if (last || list) { Bool_t isRele = pRele.MatchB(n); Bool_t isAnat = pAnat.MatchB(n); Bool_t isSpec = !(isRele || isAnat); if (nots && isSpec) continue; if (anat && !isAnat) continue; if (rele && !isRele) continue; if (list) { n.ReplaceAll(Form("%s::", name.Data()), ""); Printf("\t%s", n.Data()); continue; } r = o; break; } if (!vers.EqualTo(n)) continue; r = o; break; } if (!r && !list) Warning("GetPackage", "No match found for %s", vers.Data()); return r; } static Bool_t GetVer(TObject* pack, const TString& name, TString& ret) { if (!pack) { // if (!ret.IsNull()) ret = ""; return false; } ret = pack->GetName(); ret.ReplaceAll(Form("%s::", name.Data()), ""); return true; } /** * Get the dependencies * * @param pack Package * @param which Which dependency * @param ret Return version of dependency * * @return true on success */ static Bool_t GetDep(TObject* pack, const TString& which, TString& ret) { if (!pack) return false; TString deps(pack->GetTitle()); TObjArray* tokens = deps.Tokenize(","); TIter next(tokens); TObjString* s = 0; while ((s = static_cast<TObjString*>(next()))) { TString t = s->String().Strip(TString::kBoth); if (t.BeginsWith(which)) { ret = t; ret.ReplaceAll(Form("%s::",which.Data()), ""); break; } } tokens->Delete(); delete tokens; return !(ret.IsNull()); } static Bool_t Check(TString& aliphysics, TString& aliroot, TString& root) { // Figure out what to do. Bool_t show = (aliphysics.Contains("list", TString::kIgnoreCase) || aliroot.Contains("list", TString::kIgnoreCase) || root.Contains( "list", TString::kIgnoreCase)); TObject* foundPhysics = GetPackage("AliPhysics", aliphysics); GetVer(foundPhysics, "AliPhysics", aliphysics); GetDep(foundPhysics, "AliRoot", aliroot); TObject* foundAliRoot = GetPackage("AliRoot", aliroot); GetVer(foundAliRoot, "AliRoot", aliroot); GetDep(foundAliRoot, "ROOT", root); TObject* foundRoot = GetPackage("ROOT", root); GetVer(foundRoot, "ROOT", root); if (show) return false; if (aliphysics.IsNull() || aliroot.IsNull() || root.IsNull()) { Warning("Check", "Missing packages (%s,%s,%s)", aliphysics.Data(), aliroot.Data(), root.Data()); return false; } return true; } static void Test(const TString& phy, const TString& ali=TString(), const TString& roo=TString()) { TString aliphysics(Form("list,%s", phy.Data())); TString aliroot (Form("list,%s", ali.Data())); TString root (Form("list,%s", roo.Data())); Printf("Checking with AliPhysics=%s AliROOT=%s ROOT=%s", phy.Data(), ali.Data(), roo.Data()); AvailableSoftware::Check(aliphysics,aliroot, root); aliphysics = Form("last,%s",phy.Data()); aliroot = Form("last,%s",ali.Data()); root = Form("last,%s",roo.Data()); if (AvailableSoftware::Check(aliphysics,aliroot, root)) Printf("Got AliPhysics=%s AliROOT=%s ROOT=%s", aliphysics.Data(), aliroot.Data(), root.Data()); } static void Test() { Printf("All available"); AvailableSoftware::Test(""); Printf("All regular"); AvailableSoftware::Test("regular","regular","regular"); Printf("All releases"); AvailableSoftware::Test("release","release","release"); Printf("All analysis tags"); AvailableSoftware::Test("analysis","analysis","analysis"); } }; #endif <|endoftext|>
<commit_before>#pragma ident "$Id:$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ /** * @file StaStats.cpp */ #include <iostream> // debug #include "gps_constants.hpp" #include "StaStats.hpp" namespace gpstk { using namespace std; using namespace gpstk; StaStats::StaStats( const string stationName, const int maxSVsAtOneTime, const int minStaAtOneTime ) { staName = stationName; maxNumSimultaneousSVs = maxSVsAtOneTime; minNumSimultaneousSta = minStaAtOneTime; maxSVCount = 0; maxSVDuration = 0; maxSVOccurrances = 0; lastMaxSVEpoch = -1; minSVCount = gpstk::MAX_PRN+2; minSVDuration = 0; minSVOccurrances = 0; lastMinSVEpoch = -1; numEpochsGreaterThenMaxSVs = 0; numEpochsLessThanMinStas = 0; dataEntered = false; totalObsCount = 0; for (int i=0;i<18;++i) obsCountByBin[i] = 0; } // Had to add this in order to force the minimum station count // for the "stats across all SVs" object in compSatVis void StaStats::updateMinStations( const int minStaAtOneTime ) { minNumSimultaneousSta = minStaAtOneTime; } void StaStats::addToElvBins( const double elevation ) { totalObsCount++; double scaledElv = elevation; scaledElv /= 5.0; int ndx = (int) scaledElv; //cout << "elv, scaledElv, ndx = " << elevation << ", " << scaledElv << ", " << ndx << endl; if (ndx>17) ndx = 17; if (ndx<0) ndx = 0; obsCountByBin[ndx]++; } void StaStats::addEpochInfo( const int count, const int epochID ) { dataEntered = true; stats.Add( (double) count); if (count>maxNumSimultaneousSVs) numEpochsGreaterThenMaxSVs++; if (count<minNumSimultaneousSta) numEpochsLessThanMinStas++; if (count<minSVCount) { minSVCount = count; minSVDuration = 0; minSVOccurrances = 0; lastMinSVEpoch = epochID; } if (count==minSVCount) { minSVDuration++; if (epochID==lastMinSVEpoch || epochID!= (lastMinSVEpoch+1) ) minSVOccurrances++; lastMinSVEpoch = epochID; } if (count>maxSVCount) { maxSVCount = count; maxSVDuration = 0; maxSVOccurrances = 0; lastMaxSVEpoch = epochID; } if (count==maxSVCount) { maxSVDuration++; if (epochID==lastMaxSVEpoch || epochID!=(lastMaxSVEpoch+1) ) maxSVOccurrances++; lastMaxSVEpoch = epochID; } //cout << "maxSVCount, minSVCount = " << maxSVCount << ", " << minSVCount << endl; } std::string StaStats::getStr(int intervalSize) const { int maxMinutes = (maxSVDuration * intervalSize) / 60; int minMinutes = (minSVDuration * intervalSize) / 60; char line[100]; sprintf( line, " %5s %5.2f | %2d %4d %3d | %2d %4d %3d | %4d", staName.c_str(),stats.Average(), minSVCount,minMinutes,minSVOccurrances, maxSVCount,maxMinutes,maxSVOccurrances, numEpochsGreaterThenMaxSVs); std::string retStr(line); return(retStr); } std::string StaStats::getSatStr(int intervalSize) const { int maxMinutes = (maxSVDuration * intervalSize) / 60; int minMinutes = (minSVDuration * intervalSize) / 60; char line[100]; sprintf( line, "%5s %5.2f ! %2d %4d %3d ! %2d %4d %3d ! %4d", staName.c_str(),stats.Average(), minSVCount,minMinutes,minSVOccurrances, maxSVCount,maxMinutes,maxSVOccurrances, numEpochsLessThanMinStas); std::string retStr(line); return(retStr); } std::string StaStats::getSatAvgStr() const { char line[100]; sprintf( line, " Avg %5.2f ! ! ! %4d\n", stats.Average(), numEpochsLessThanMinStas); std::string retStr(line); return(retStr); } std::string StaStats::getElvBinValues() const { char line[180]; //cout << "StaNum, Total Obs = " << staNum << ", " << totalObsCount << endl; sprintf( line, " %5s %6d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d %5d", staName.c_str(),totalObsCount, obsCountByBin[ 0],obsCountByBin[ 1],obsCountByBin[ 2],obsCountByBin[ 3], obsCountByBin[ 4],obsCountByBin[ 5],obsCountByBin[ 6],obsCountByBin[ 7], obsCountByBin[ 8],obsCountByBin[ 9],obsCountByBin[10],obsCountByBin[11], obsCountByBin[12],obsCountByBin[13],obsCountByBin[14],obsCountByBin[15], obsCountByBin[16],obsCountByBin[17] ); std::string retStr(line); return(retStr); } } // namespace <commit_msg>Fixing one last set of warnings for 32-bit compiling, caused by incorrect output format string in a printf.<commit_after>#pragma ident "$Id$" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ /** * @file StaStats.cpp */ #include <iostream> // debug #include "gps_constants.hpp" #include "StaStats.hpp" namespace gpstk { using namespace std; using namespace gpstk; StaStats::StaStats( const string stationName, const int maxSVsAtOneTime, const int minStaAtOneTime ) { staName = stationName; maxNumSimultaneousSVs = maxSVsAtOneTime; minNumSimultaneousSta = minStaAtOneTime; maxSVCount = 0; maxSVDuration = 0; maxSVOccurrances = 0; lastMaxSVEpoch = -1; minSVCount = gpstk::MAX_PRN+2; minSVDuration = 0; minSVOccurrances = 0; lastMinSVEpoch = -1; numEpochsGreaterThenMaxSVs = 0; numEpochsLessThanMinStas = 0; dataEntered = false; totalObsCount = 0; for (int i=0;i<18;++i) obsCountByBin[i] = 0; } // Had to add this in order to force the minimum station count // for the "stats across all SVs" object in compSatVis void StaStats::updateMinStations( const int minStaAtOneTime ) { minNumSimultaneousSta = minStaAtOneTime; } void StaStats::addToElvBins( const double elevation ) { totalObsCount++; double scaledElv = elevation; scaledElv /= 5.0; int ndx = (int) scaledElv; //cout << "elv, scaledElv, ndx = " << elevation << ", " << scaledElv << ", " << ndx << endl; if (ndx>17) ndx = 17; if (ndx<0) ndx = 0; obsCountByBin[ndx]++; } void StaStats::addEpochInfo( const int count, const int epochID ) { dataEntered = true; stats.Add( (double) count); if (count>maxNumSimultaneousSVs) numEpochsGreaterThenMaxSVs++; if (count<minNumSimultaneousSta) numEpochsLessThanMinStas++; if (count<minSVCount) { minSVCount = count; minSVDuration = 0; minSVOccurrances = 0; lastMinSVEpoch = epochID; } if (count==minSVCount) { minSVDuration++; if (epochID==lastMinSVEpoch || epochID!= (lastMinSVEpoch+1) ) minSVOccurrances++; lastMinSVEpoch = epochID; } if (count>maxSVCount) { maxSVCount = count; maxSVDuration = 0; maxSVOccurrances = 0; lastMaxSVEpoch = epochID; } if (count==maxSVCount) { maxSVDuration++; if (epochID==lastMaxSVEpoch || epochID!=(lastMaxSVEpoch+1) ) maxSVOccurrances++; lastMaxSVEpoch = epochID; } //cout << "maxSVCount, minSVCount = " << maxSVCount << ", " << minSVCount << endl; } std::string StaStats::getStr(int intervalSize) const { int maxMinutes = (maxSVDuration * intervalSize) / 60; int minMinutes = (minSVDuration * intervalSize) / 60; char line[100]; sprintf( line, " %5s %5.2f | %2d %4d %3d | %2d %4d %3d | %4d", staName.c_str(),stats.Average(), minSVCount,minMinutes,minSVOccurrances, maxSVCount,maxMinutes,maxSVOccurrances, numEpochsGreaterThenMaxSVs); std::string retStr(line); return(retStr); } std::string StaStats::getSatStr(int intervalSize) const { int maxMinutes = (maxSVDuration * intervalSize) / 60; int minMinutes = (minSVDuration * intervalSize) / 60; char line[100]; sprintf( line, "%5s %5.2f ! %2d %4d %3d ! %2d %4d %3d ! %4d", staName.c_str(),stats.Average(), minSVCount,minMinutes,minSVOccurrances, maxSVCount,maxMinutes,maxSVOccurrances, numEpochsLessThanMinStas); std::string retStr(line); return(retStr); } std::string StaStats::getSatAvgStr() const { char line[100]; sprintf( line, " Avg %5.2f ! ! ! %4d\n", stats.Average(), numEpochsLessThanMinStas); std::string retStr(line); return(retStr); } std::string StaStats::getElvBinValues() const { char line[180]; //cout << "StaNum, Total Obs = " << staNum << ", " << totalObsCount << endl; sprintf( line, " %5s %6ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld %5ld", staName.c_str(),totalObsCount, obsCountByBin[ 0],obsCountByBin[ 1],obsCountByBin[ 2],obsCountByBin[ 3], obsCountByBin[ 4],obsCountByBin[ 5],obsCountByBin[ 6],obsCountByBin[ 7], obsCountByBin[ 8],obsCountByBin[ 9],obsCountByBin[10],obsCountByBin[11], obsCountByBin[12],obsCountByBin[13],obsCountByBin[14],obsCountByBin[15], obsCountByBin[16],obsCountByBin[17] ); std::string retStr(line); return(retStr); } } // namespace <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #if !defined(XMLUNIDEFS_HPP) #define XMLUNIDEFS_HPP #include <util/XercesDefs.hpp> // --------------------------------------------------------------------------- // Constants for the Unicode characters of interest to us in an XML parser // We don't put these inside the class because then they could not be const // inline values, which would have significant performance ramifications. // // We cannot use a namespace because of the requirement to support old // compilers. // --------------------------------------------------------------------------- const XMLCh chNull = 0x00; const XMLCh chHTab = 0x09; const XMLCh chLF = 0x0A; const XMLCh chCR = 0x0D; const XMLCh chAmpersand = 0x26; const XMLCh chAsterisk = 0x2A; const XMLCh chAt = 0x40; const XMLCh chBackSlash = 0x5C; const XMLCh chBang = 0x21; const XMLCh chCloseAngle = 0x3E; const XMLCh chCloseCurly = 0x7D; const XMLCh chCloseParen = 0x29; const XMLCh chCloseSquare = 0x5D; const XMLCh chColon = 0x3A; const XMLCh chComma = 0x2C; const XMLCh chDash = 0x2D; const XMLCh chDollarSign = 0x24; const XMLCh chDoubleQuote = 0x22; const XMLCh chEqual = 0x3D; const XMLCh chForwardSlash = 0x2F; const XMLCh chGrave = 0x60; const XMLCh chOpenAngle = 0x3C; const XMLCh chOpenCurly = 0x7B; const XMLCh chOpenParen = 0x28; const XMLCh chOpenSquare = 0x5B; const XMLCh chPercent = 0x25; const XMLCh chPeriod = 0x2E; const XMLCh chPipe = 0x7C; const XMLCh chPlus = 0x2B; const XMLCh chPound = 0x23; const XMLCh chQuestion = 0x3F; const XMLCh chSingleQuote = 0x27; const XMLCh chSpace = 0x20; const XMLCh chSemiColon = 0x3B; const XMLCh chTilde = 0x7E; const XMLCh chUnderscore = 0x5F; const XMLCh chSwappedUnicodeMarker = XMLCh(0xFFFE); const XMLCh chUnicodeMarker = XMLCh(0xFEFF); const XMLCh chDigit_0 = 0x30; const XMLCh chDigit_1 = 0x31; const XMLCh chDigit_2 = 0x32; const XMLCh chDigit_3 = 0x33; const XMLCh chDigit_4 = 0x34; const XMLCh chDigit_5 = 0x35; const XMLCh chDigit_6 = 0x36; const XMLCh chDigit_7 = 0x37; const XMLCh chDigit_8 = 0x38; const XMLCh chDigit_9 = 0x39; const XMLCh chLatin_A = 0x41; const XMLCh chLatin_B = 0x42; const XMLCh chLatin_C = 0x43; const XMLCh chLatin_D = 0x44; const XMLCh chLatin_E = 0x45; const XMLCh chLatin_F = 0x46; const XMLCh chLatin_G = 0x47; const XMLCh chLatin_H = 0x48; const XMLCh chLatin_I = 0x49; const XMLCh chLatin_J = 0x4A; const XMLCh chLatin_K = 0x4B; const XMLCh chLatin_L = 0x4C; const XMLCh chLatin_M = 0x4D; const XMLCh chLatin_N = 0x4E; const XMLCh chLatin_O = 0x4F; const XMLCh chLatin_P = 0x50; const XMLCh chLatin_Q = 0x51; const XMLCh chLatin_R = 0x52; const XMLCh chLatin_S = 0x53; const XMLCh chLatin_T = 0x54; const XMLCh chLatin_U = 0x55; const XMLCh chLatin_V = 0x56; const XMLCh chLatin_W = 0x57; const XMLCh chLatin_X = 0x58; const XMLCh chLatin_Y = 0x59; const XMLCh chLatin_Z = 0x5A; const XMLCh chLatin_a = 0x61; const XMLCh chLatin_b = 0x62; const XMLCh chLatin_c = 0x63; const XMLCh chLatin_d = 0x64; const XMLCh chLatin_e = 0x65; const XMLCh chLatin_f = 0x66; const XMLCh chLatin_g = 0x67; const XMLCh chLatin_h = 0x68; const XMLCh chLatin_i = 0x69; const XMLCh chLatin_j = 0x6A; const XMLCh chLatin_k = 0x6B; const XMLCh chLatin_l = 0x6C; const XMLCh chLatin_m = 0x6D; const XMLCh chLatin_n = 0x6E; const XMLCh chLatin_o = 0x6F; const XMLCh chLatin_p = 0x70; const XMLCh chLatin_q = 0x71; const XMLCh chLatin_r = 0x72; const XMLCh chLatin_s = 0x73; const XMLCh chLatin_t = 0x74; const XMLCh chLatin_u = 0x75; const XMLCh chLatin_v = 0x76; const XMLCh chLatin_w = 0x77; const XMLCh chLatin_x = 0x78; const XMLCh chLatin_y = 0x79; const XMLCh chLatin_z = 0x7A; const XMLCh chYenSign = 0xA5; const XMLCh chWonSign = 0x20A9; #endif <commit_msg>Added two more character definitions.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ #if !defined(XMLUNIDEFS_HPP) #define XMLUNIDEFS_HPP #include <util/XercesDefs.hpp> // --------------------------------------------------------------------------- // Constants for the Unicode characters of interest to us in an XML parser // We don't put these inside the class because then they could not be const // inline values, which would have significant performance ramifications. // // We cannot use a namespace because of the requirement to support old // compilers. // --------------------------------------------------------------------------- const XMLCh chNull = 0x00; const XMLCh chHTab = 0x09; const XMLCh chLF = 0x0A; const XMLCh chCR = 0x0D; const XMLCh chAmpersand = 0x26; const XMLCh chAsterisk = 0x2A; const XMLCh chAt = 0x40; const XMLCh chBackSlash = 0x5C; const XMLCh chBang = 0x21; const XMLCh chCloseAngle = 0x3E; const XMLCh chCloseCurly = 0x7D; const XMLCh chCloseParen = 0x29; const XMLCh chCloseSquare = 0x5D; const XMLCh chColon = 0x3A; const XMLCh chComma = 0x2C; const XMLCh chDash = 0x2D; const XMLCh chDollarSign = 0x24; const XMLCh chDoubleQuote = 0x22; const XMLCh chEqual = 0x3D; const XMLCh chForwardSlash = 0x2F; const XMLCh chGrave = 0x60; const XMLCh chOpenAngle = 0x3C; const XMLCh chOpenCurly = 0x7B; const XMLCh chOpenParen = 0x28; const XMLCh chOpenSquare = 0x5B; const XMLCh chPercent = 0x25; const XMLCh chPeriod = 0x2E; const XMLCh chPipe = 0x7C; const XMLCh chPlus = 0x2B; const XMLCh chPound = 0x23; const XMLCh chQuestion = 0x3F; const XMLCh chSingleQuote = 0x27; const XMLCh chSpace = 0x20; const XMLCh chSemiColon = 0x3B; const XMLCh chTilde = 0x7E; const XMLCh chUnderscore = 0x5F; const XMLCh chSwappedUnicodeMarker = XMLCh(0xFFFE); const XMLCh chUnicodeMarker = XMLCh(0xFEFF); const XMLCh chDigit_0 = 0x30; const XMLCh chDigit_1 = 0x31; const XMLCh chDigit_2 = 0x32; const XMLCh chDigit_3 = 0x33; const XMLCh chDigit_4 = 0x34; const XMLCh chDigit_5 = 0x35; const XMLCh chDigit_6 = 0x36; const XMLCh chDigit_7 = 0x37; const XMLCh chDigit_8 = 0x38; const XMLCh chDigit_9 = 0x39; const XMLCh chLatin_A = 0x41; const XMLCh chLatin_B = 0x42; const XMLCh chLatin_C = 0x43; const XMLCh chLatin_D = 0x44; const XMLCh chLatin_E = 0x45; const XMLCh chLatin_F = 0x46; const XMLCh chLatin_G = 0x47; const XMLCh chLatin_H = 0x48; const XMLCh chLatin_I = 0x49; const XMLCh chLatin_J = 0x4A; const XMLCh chLatin_K = 0x4B; const XMLCh chLatin_L = 0x4C; const XMLCh chLatin_M = 0x4D; const XMLCh chLatin_N = 0x4E; const XMLCh chLatin_O = 0x4F; const XMLCh chLatin_P = 0x50; const XMLCh chLatin_Q = 0x51; const XMLCh chLatin_R = 0x52; const XMLCh chLatin_S = 0x53; const XMLCh chLatin_T = 0x54; const XMLCh chLatin_U = 0x55; const XMLCh chLatin_V = 0x56; const XMLCh chLatin_W = 0x57; const XMLCh chLatin_X = 0x58; const XMLCh chLatin_Y = 0x59; const XMLCh chLatin_Z = 0x5A; const XMLCh chLatin_a = 0x61; const XMLCh chLatin_b = 0x62; const XMLCh chLatin_c = 0x63; const XMLCh chLatin_d = 0x64; const XMLCh chLatin_e = 0x65; const XMLCh chLatin_f = 0x66; const XMLCh chLatin_g = 0x67; const XMLCh chLatin_h = 0x68; const XMLCh chLatin_i = 0x69; const XMLCh chLatin_j = 0x6A; const XMLCh chLatin_k = 0x6B; const XMLCh chLatin_l = 0x6C; const XMLCh chLatin_m = 0x6D; const XMLCh chLatin_n = 0x6E; const XMLCh chLatin_o = 0x6F; const XMLCh chLatin_p = 0x70; const XMLCh chLatin_q = 0x71; const XMLCh chLatin_r = 0x72; const XMLCh chLatin_s = 0x73; const XMLCh chLatin_t = 0x74; const XMLCh chLatin_u = 0x75; const XMLCh chLatin_v = 0x76; const XMLCh chLatin_w = 0x77; const XMLCh chLatin_x = 0x78; const XMLCh chLatin_y = 0x79; const XMLCh chLatin_z = 0x7A; const XMLCh chYenSign = 0xA5; const XMLCh chWonSign = 0x20A9; const XMLCh chLineSeparator = 0x2028; const XMLCh chParagraphSeparator = 0x2029; #endif <|endoftext|>
<commit_before>#include "settingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <algorithm> // find_if #include "utils/logoutput.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingContainer::SettingContainer(std::string key, std::string label) : key(key) , label(label) { } SettingConfig* SettingContainer::addChild(std::string key, std::string label) { children.emplace_back(key, label); return &children.back(); } SettingConfig& SettingContainer::getOrCreateChild(std::string key, std::string label) { auto child_it = std::find_if(children.begin(), children.end(), [&key](SettingConfig& child) { return child.key == key; } ); if (child_it == children.end()) { children.emplace_back(key, label); return children.back(); } else { return *child_it; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } void SettingContainer::debugOutputAllSettings() const { std::cerr << "\nCATEGORY: " << key << std::endl; for (const SettingConfig& child : children) { child.debugOutputAllSettings(); } } bool SettingRegistry::settingExists(std::string key) const { return settings.find(key) != settings.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = settings.find(key); if (it == settings.end()) return nullptr; return it->second; } SettingContainer* SettingRegistry::getCategory(std::string key) { for (SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } const SettingContainer* SettingRegistry::getCategory(std::string key) const { for (const SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } SettingContainer& SettingRegistry::getOrCreateCategory(std::string cat_name, const rapidjson::Value& category) { std::list<SettingContainer>::iterator category_found = std::find_if(categories.begin(), categories.end(), [&cat_name](SettingContainer& cat) { return cat.getKey().compare(cat_name) == 0; }); if (category_found != categories.end()) { // category is already present; add settings to category return *category_found; } else { std::string label = cat_name; if (category.IsObject() && category.HasMember("label") && category["label"].IsString()) { label = category["label"].GetString(); } categories.emplace_back(cat_name, label); return categories.back(); } } SettingRegistry::SettingRegistry() { } bool SettingRegistry::settingsLoaded() const { return settings.size() > 0; } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } int SettingRegistry::loadJSONsettings(std::string filename) { rapidjson::Document json_document; int err = loadJSON(filename, json_document); if (err) { return err; } if (json_document.HasMember("inherits")) { std::string filename_copy = std::string(filename.c_str()); // copy the string because dirname(.) changes the input string!!! char* filename_cstr = (char*)filename_copy.c_str(); int err = loadJSONsettings(std::string(dirname(filename_cstr)) + std::string("/") + json_document["inherits"].GetString()); if (err) { return err; } return loadJSONsettingsFromDoc(json_document, false); } else { return loadJSONsettingsFromDoc(json_document, true); } } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("machine_extruder_trains")) { const rapidjson::Value& trains = json_document["machine_extruder_trains"]; SettingContainer& category_trains = getOrCreateCategory("machine_extruder_trains", trains); if (trains.IsObject()) { for (rapidjson::Value::ConstMemberIterator train_iterator = trains.MemberBegin(); train_iterator != trains.MemberEnd(); ++train_iterator) { SettingConfig& child = category_trains.getOrCreateChild(train_iterator->name.GetString(), std::string("Extruder ") + train_iterator->name.GetString()); const rapidjson::Value& train = train_iterator->value; for (rapidjson::Value::ConstMemberIterator setting_iterator = train.MemberBegin(); setting_iterator != train.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&child, setting_iterator, warn_duplicates, false); } } } else if (trains.IsArray()) { int train_nr = 0; for (rapidjson::Value::ConstValueIterator train_iterator = trains.Begin(); train_iterator != trains.End(); ++train_iterator) { SettingConfig& child = category_trains.getOrCreateChild(std::to_string(train_nr), std::string("Extruder ") + std::to_string(train_nr)); const rapidjson::Value& train = *train_iterator; for (rapidjson::Value::ConstMemberIterator setting_iterator = train.MemberBegin(); setting_iterator != train.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&child, setting_iterator, warn_duplicates, false); } train_nr++; } } } if (json_document.HasMember("machine_settings")) { const rapidjson::Value& machine_settings = json_document["machine_settings"]; SettingContainer& category = getOrCreateCategory("machine_settings", machine_settings); // _addCategory(std::string("machine_settings"), machine_settings, warn_duplicates); // TODO: make machine_settings a category with a settings field and a label field and throw away rest of the code in this code block for (rapidjson::Value::ConstMemberIterator setting_iterator = machine_settings.MemberBegin(); setting_iterator != machine_settings.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&category, setting_iterator, warn_duplicates); } } if (json_document.HasMember("categories")) { for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator) { _addCategory(category_iterator->name.GetString(), category_iterator->value, warn_duplicates); } } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, false); } } return 0; } void SettingRegistry::_addCategory(std::string cat_name, const rapidjson::Value& fields, bool warn_duplicates) { if (!fields.IsObject()) { return; } if (!fields.HasMember("settings") || !fields["settings"].IsObject()) { return; } SettingContainer& category = getOrCreateCategory(cat_name, fields); const rapidjson::Value& json_object_container = fields["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&category, setting_iterator, warn_duplicates); } } void SettingRegistry::_addSettingToContainer(SettingContainer* parent, const rapidjson::Value::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; std::string label; if (!json_object_it->value.HasMember("label") || !data["label"].IsString()) { label = "N/A"; } else { label = data["label"].GetString(); } /// Create the new setting config object. SettingConfig& config = parent->getOrCreateChild(json_object_it->name.GetString(), label); _loadSettingValues(&config, json_object_it, warn_duplicates, add_to_settings); } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (data.HasMember("default")) { const rapidjson::Value& dflt = data["default"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { if (data.HasMember("type") && data["type"].IsString() && (data["type"].GetString() == std::string("polygon") || data["type"].GetString() == std::string("polygons"))) { logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); } else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } /// Register the setting in the settings map lookup. if (warn_duplicates && settingExists(config->getKey())) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", config->getKey().c_str(), config->getLabel().c_str(), getSettingConfig(config->getKey())->getLabel().c_str()); } if (add_to_settings) { settings[config->getKey()] = config; } /// When this setting has children, add those children to this setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(config, setting_iterator, warn_duplicates, add_to_settings); } } } }//namespace cura <commit_msg>machine extruder trains now can't be an array anymore (CURA-494)<commit_after>#include "settingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <algorithm> // find_if #include "utils/logoutput.h" #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingContainer::SettingContainer(std::string key, std::string label) : key(key) , label(label) { } SettingConfig* SettingContainer::addChild(std::string key, std::string label) { children.emplace_back(key, label); return &children.back(); } SettingConfig& SettingContainer::getOrCreateChild(std::string key, std::string label) { auto child_it = std::find_if(children.begin(), children.end(), [&key](SettingConfig& child) { return child.key == key; } ); if (child_it == children.end()) { children.emplace_back(key, label); return children.back(); } else { return *child_it; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } void SettingContainer::debugOutputAllSettings() const { std::cerr << "\nCATEGORY: " << key << std::endl; for (const SettingConfig& child : children) { child.debugOutputAllSettings(); } } bool SettingRegistry::settingExists(std::string key) const { return settings.find(key) != settings.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = settings.find(key); if (it == settings.end()) return nullptr; return it->second; } SettingContainer* SettingRegistry::getCategory(std::string key) { for (SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } const SettingContainer* SettingRegistry::getCategory(std::string key) const { for (const SettingContainer& cat : categories) if (cat.getKey().compare(key) == 0) return &cat; return nullptr; } SettingContainer& SettingRegistry::getOrCreateCategory(std::string cat_name, const rapidjson::Value& category) { std::list<SettingContainer>::iterator category_found = std::find_if(categories.begin(), categories.end(), [&cat_name](SettingContainer& cat) { return cat.getKey().compare(cat_name) == 0; }); if (category_found != categories.end()) { // category is already present; add settings to category return *category_found; } else { std::string label = cat_name; if (category.IsObject() && category.HasMember("label") && category["label"].IsString()) { label = category["label"].GetString(); } categories.emplace_back(cat_name, label); return categories.back(); } } SettingRegistry::SettingRegistry() { } bool SettingRegistry::settingsLoaded() const { return settings.size() > 0; } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } int SettingRegistry::loadJSONsettings(std::string filename) { rapidjson::Document json_document; int err = loadJSON(filename, json_document); if (err) { return err; } if (json_document.HasMember("inherits")) { std::string filename_copy = std::string(filename.c_str()); // copy the string because dirname(.) changes the input string!!! char* filename_cstr = (char*)filename_copy.c_str(); int err = loadJSONsettings(std::string(dirname(filename_cstr)) + std::string("/") + json_document["inherits"].GetString()); if (err) { return err; } return loadJSONsettingsFromDoc(json_document, false); } else { return loadJSONsettingsFromDoc(json_document, true); } } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("machine_extruder_trains")) { const rapidjson::Value& trains = json_document["machine_extruder_trains"]; SettingContainer& category_trains = getOrCreateCategory("machine_extruder_trains", trains); if (trains.IsObject()) { for (rapidjson::Value::ConstMemberIterator train_iterator = trains.MemberBegin(); train_iterator != trains.MemberEnd(); ++train_iterator) { SettingConfig& child = category_trains.getOrCreateChild(train_iterator->name.GetString(), std::string("Extruder ") + train_iterator->name.GetString()); const rapidjson::Value& train = train_iterator->value; for (rapidjson::Value::ConstMemberIterator setting_iterator = train.MemberBegin(); setting_iterator != train.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&child, setting_iterator, warn_duplicates, false); } } } } if (json_document.HasMember("machine_settings")) { const rapidjson::Value& machine_settings = json_document["machine_settings"]; SettingContainer& category = getOrCreateCategory("machine_settings", machine_settings); // _addCategory(std::string("machine_settings"), machine_settings, warn_duplicates); // TODO: make machine_settings a category with a settings field and a label field and throw away rest of the code in this code block for (rapidjson::Value::ConstMemberIterator setting_iterator = machine_settings.MemberBegin(); setting_iterator != machine_settings.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&category, setting_iterator, warn_duplicates); } } if (json_document.HasMember("categories")) { for (rapidjson::Value::ConstMemberIterator category_iterator = json_document["categories"].MemberBegin(); category_iterator != json_document["categories"].MemberEnd(); ++category_iterator) { _addCategory(category_iterator->name.GetString(), category_iterator->value, warn_duplicates); } } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, false); } } return 0; } void SettingRegistry::_addCategory(std::string cat_name, const rapidjson::Value& fields, bool warn_duplicates) { if (!fields.IsObject()) { return; } if (!fields.HasMember("settings") || !fields["settings"].IsObject()) { return; } SettingContainer& category = getOrCreateCategory(cat_name, fields); const rapidjson::Value& json_object_container = fields["settings"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(&category, setting_iterator, warn_duplicates); } } void SettingRegistry::_addSettingToContainer(SettingContainer* parent, const rapidjson::Value::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; std::string label; if (!json_object_it->value.HasMember("label") || !data["label"].IsString()) { label = "N/A"; } else { label = data["label"].GetString(); } /// Create the new setting config object. SettingConfig& config = parent->getOrCreateChild(json_object_it->name.GetString(), label); _loadSettingValues(&config, json_object_it, warn_duplicates, add_to_settings); } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, bool warn_duplicates, bool add_to_settings) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (data.HasMember("default")) { const rapidjson::Value& dflt = data["default"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { if (data.HasMember("type") && data["type"].IsString() && (data["type"].GetString() == std::string("polygon") || data["type"].GetString() == std::string("polygons"))) { logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); } else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } /// Register the setting in the settings map lookup. if (warn_duplicates && settingExists(config->getKey())) { cura::logError("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", config->getKey().c_str(), config->getLabel().c_str(), getSettingConfig(config->getKey())->getLabel().c_str()); } if (add_to_settings) { settings[config->getKey()] = config; } /// When this setting has children, add those children to this setting. if (data.HasMember("children") && data["children"].IsObject()) { const rapidjson::Value& json_object_container = data["children"]; for (rapidjson::Value::ConstMemberIterator setting_iterator = json_object_container.MemberBegin(); setting_iterator != json_object_container.MemberEnd(); ++setting_iterator) { _addSettingToContainer(config, setting_iterator, warn_duplicates, add_to_settings); } } } }//namespace cura <|endoftext|>
<commit_before>// // Robot.cpp // maproom-robot // // Created by Christopher Anderson on 2/18/17. // // #include "Robot.h" static const float kTolerance = 0.04f; static const float kHeartbeatTimeoutSec = 2.0f; static const float kCameraTimeoutSec = 0.5f; static const float kPenMovementTime = 0.1f; static const float kCalibrationWaitSec = 1.0f; static const float kAngleWaitSec = 2.0f; static const float kMoveWaitSec = 2.0f; static const float kRotationToleranceStart = 10.0f; static const float kRotationToleranceFinal = 3.0f; const static float kSqSizeM = 0.25; const static int kNumPositions = 5; const static ofVec2f positions[] = { { 0.0, 0.0 }, { -kSqSizeM, -kSqSizeM }, { kSqSizeM, -kSqSizeM }, { kSqSizeM, kSqSizeM }, { -kSqSizeM, kSqSizeM }, { 0.0, 0.0 } }; void cmdCalibrateAngle(char *buf, int measured) { sprintf(buf, "MRCAL%+06d\n", measured); } void cmdRot(char *buf, int target, int measured) { sprintf(buf, "MRROT%+06d%+06d\n", target, measured); } void cmdMove(char *buf, int angle, int magnitude, int measured) { sprintf(buf, "MRMOV%+06d%+06d%+06d\n", angle, magnitude, measured); } void cmdDraw(char *buf, int angle, int magnitude, int measured) { sprintf(buf, "MRDRW%+06d%+06d%+06d\n", angle, magnitude, measured); } void cmdStop(char *buf, bool penDown) { sprintf(buf, "MRSTP%d\n", penDown ? 1 : 0); } void Robot::setCommunication(const string &rIp, int rPort) { ip = rIp; port = rPort; socket.Create(); socket.Connect(ip.c_str(), port); socket.SetNonBlocking(true); } void Robot::sendMessage(const string &message) { socket.Send(message.c_str(), message.length()); lastMessage = message; } void Robot::sendHeartbeat() { sendMessage("MRHB\n"); } void Robot::calibrate() { cmdCalibrateAngle(msg, rot); sendMessage(msg); } void Robot::stop() { setState(R_STOPPED); cmdStop(msg, (penState == P_UP ? true : false)); sendMessage(msg); } void Robot::start() { setState(R_START); } void Robot::testRotate(float angle) { targetRot = angle; cmdRot(msg, angle, rot); sendMessage(msg); // setState(R_ROTATING_TO_ANGLE); } void Robot::testMove(float direction, float magnitude) { moveDir = direction; moveMag = magnitude; // setState(R_MOVING); cmdMove(msg, direction, magnitude, rot); sendMessage(msg); } void Robot::updateCamera(const ofVec3f &newRvec, const ofVec3f &newTvec, const ofMatrix4x4 &cameraWorldInv) { rvec = newRvec; tvec = newTvec; // http://answers.opencv.org/question/110441/use-rotation-vector-from-aruco-in-unity3d/ float angle = sqrt(rvec.x*rvec.x + rvec.y*rvec.y + rvec.z*rvec.z); ofVec3f axis(rvec.x, rvec.y, rvec.z); ofQuaternion rvecQuat; rvecQuat.makeRotate(angle / 3.14159 * 180.0, axis); mat.makeIdentityMatrix(); mat.setRotate(rvecQuat); mat.setTranslation(tvec); mat = mat * cameraWorldInv; // Get position in world worldPos = mat.getTranslation(); // Translate to the center of the marker planePos.set(worldPos.x, worldPos.y); // planePos += ofVec2f(kMarkerSizeM / 2.0, kMarkerSizeM / 2.0); // Get z-axis rotation ofVec3f xAxis = ofVec3f(1.0, 0.0, 0.0) * mat; ofVec2f xAxisVec = ofVec2f(xAxis.x, xAxis.y) - ofVec2f(worldPos.x, worldPos.y); float xAxisAngle = atan2(xAxisVec.y, xAxisVec.x); // rotation is right-handed, and goes from 0-360 starting on the +x axis rot = fmod(ofRadToDeg(xAxisAngle) + 360, 360.0); lastCameraUpdateTime = ofGetElapsedTimef(); } void Robot::gotHeartbeat() { lastHeartbeatTime = ofGetElapsedTimef(); } bool Robot::commsUp() { return true; return ofGetElapsedTimef() - lastHeartbeatTime < kHeartbeatTimeoutSec; } bool Robot::cvDetected() { return ofGetElapsedTimef() - lastCameraUpdateTime < kCameraTimeoutSec; } void Robot::setState(RobotState newState) { cout << "State change " << state << " to " << newState << endl; state = newState; stateStartTime = ofGetElapsedTimef(); } void Robot::moveRobot(char *msg, ofVec2f target, bool drawing, bool &shouldSend) { ofVec2f dir = target - planePos; float len = dir.length(); dir.normalize(); float mag = ofMap(len, 0, 1, 150, 250, true); float rad = atan2(dir.y, dir.x); float angle = fmod(ofRadToDeg(rad) + 360, 360.0); if (drawing) { cout << "DRAWING" << endl; cmdDraw(msg, angle, mag, rot); } else { cout << "MOVING" << endl; cmdMove(msg, angle, mag, rot); } shouldSend = ofGetFrameNum() % 4 == 0; cout << planePos << endl; cout << target << endl; cout << msg << endl; } bool Robot::inPosition(ofVec2f target) { ofVec2f dir = target - planePos; float len = dir.length(); return (len < kTolerance ? true : false); } void Robot::setPathType(int pathType) { navState.pathType = pathType; } void Robot::startNavigation(ofVec2f start, ofVec2f end) { navState.start = start; navState.end = end; setState(R_POSITIONING); } void Robot::update() { bool shouldSend = false; float elapsedStateTime = ofGetElapsedTimef() - stateStartTime; float rotAngleDiff = ofAngleDifferenceDegrees(targetRot, rot); if (!enableMessages) { return; } // if (!commsUp()) { // if (state != R_NO_CONN) { // cout << "Comms down, moving to NO_CONN" << endl; // setState(R_NO_CONN); // } // // cmdStop(msg, false); // shouldSend = true; // } else if (!cvDetected()) { if (state != R_NO_CONN) { cout << "CV down, moving to NO_CONN" << endl; setState(R_NO_CONN); } cmdStop(msg, false); shouldSend = true; } else if (state == R_NO_CONN) { // Now connected and seen! setState(R_START); cmdStop(msg, false); shouldSend = true; } else if (state == R_START) { // If we're started, immediately calibrate the angle setState(R_CALIBRATING_ANGLE); } else if (state == R_CALIBRATING_ANGLE) { // We're calibrating the angle for a bit cmdCalibrateAngle(msg, rot); shouldSend = true; if (elapsedStateTime >= kCalibrationWaitSec) { // We've calibrated enough setState(R_POSITIONING); } } else if (state == R_ROTATING_TO_ANGLE) { // We're rotating to a target angle if (abs(rotAngleDiff) > kRotationToleranceFinal) { // Too far from angle, keep moving. cmdRot(msg, targetRot, rot); shouldSend = true; } else { // Close enough to angle, wait to see if the robot stays close enough. setState(R_WAITING_ANGLE); } } else if (state == R_WAITING_ANGLE) { // We're waiting after issuing rotate commands if (elapsedStateTime < kAngleWaitSec) { // Pass } else if (abs(rotAngleDiff) > kRotationToleranceFinal) { // We're out of tolerance, try rotating again. setState(R_ROTATING_TO_ANGLE); } else if (elapsedStateTime > kAngleWaitSec) { // We've waited long enough, stop. setState(R_STOPPED); cmdStop(msg, false); shouldSend = true; } } else if (state == R_POSITIONING) { cout << "STATE POSITIONING" << endl; // move in direction at magnitude if (inPosition(navState.start)) { cmdStop(msg, false); shouldSend = true; if (elapsedStateTime > 1.0f) { setState(R_WAITING_TO_DRAW); } } else { // move is different from draw moveRobot(msg, navState.start, false, shouldSend); shouldSend = true; } } else if (state == R_WAITING_TO_DRAW) { cout << "WAITING TO DRAW" << endl; // wait for okay to draw if (navState.drawReady) { setState(R_DRAWING); navState.drawReady = false; } } else if (state == R_DRAWING) { cout << "DRAWING" << endl; if (inPosition(navState.end)) { setState(R_DONE_DRAWING); } else { moveRobot(msg, navState.end, true, shouldSend); shouldSend = true; } } else if (state == R_DONE_DRAWING) { cout << "DONE DRAWING" << endl; // we're stopped, pen is up cmdStop(msg, true); shouldSend = true; if (elapsedStateTime > 1.0f) { navState.readyForNextPath = true; } } else if (state == R_STOPPED) { cout << "STOPPED" << endl; // We're stopped. Stop. cmdStop(msg, false); shouldSend = true; } if (shouldSend && enableMessages) { sendMessage(msg); } } <commit_msg>dont send all the time<commit_after>// // Robot.cpp // maproom-robot // // Created by Christopher Anderson on 2/18/17. // // #include "Robot.h" static const float kTolerance = 0.04f; static const float kHeartbeatTimeoutSec = 2.0f; static const float kCameraTimeoutSec = 0.5f; static const float kPenMovementTime = 0.1f; static const float kCalibrationWaitSec = 1.0f; static const float kAngleWaitSec = 2.0f; static const float kMoveWaitSec = 2.0f; static const float kRotationToleranceStart = 10.0f; static const float kRotationToleranceFinal = 3.0f; const static float kSqSizeM = 0.25; const static int kNumPositions = 5; const static ofVec2f positions[] = { { 0.0, 0.0 }, { -kSqSizeM, -kSqSizeM }, { kSqSizeM, -kSqSizeM }, { kSqSizeM, kSqSizeM }, { -kSqSizeM, kSqSizeM }, { 0.0, 0.0 } }; void cmdCalibrateAngle(char *buf, int measured) { sprintf(buf, "MRCAL%+06d\n", measured); } void cmdRot(char *buf, int target, int measured) { sprintf(buf, "MRROT%+06d%+06d\n", target, measured); } void cmdMove(char *buf, int angle, int magnitude, int measured) { sprintf(buf, "MRMOV%+06d%+06d%+06d\n", angle, magnitude, measured); } void cmdDraw(char *buf, int angle, int magnitude, int measured) { sprintf(buf, "MRDRW%+06d%+06d%+06d\n", angle, magnitude, measured); } void cmdStop(char *buf, bool penDown) { sprintf(buf, "MRSTP%d\n", penDown ? 1 : 0); } void Robot::setCommunication(const string &rIp, int rPort) { ip = rIp; port = rPort; socket.Create(); socket.Connect(ip.c_str(), port); socket.SetNonBlocking(true); } void Robot::sendMessage(const string &message) { socket.Send(message.c_str(), message.length()); lastMessage = message; } void Robot::sendHeartbeat() { sendMessage("MRHB\n"); } void Robot::calibrate() { cmdCalibrateAngle(msg, rot); sendMessage(msg); } void Robot::stop() { setState(R_STOPPED); cmdStop(msg, (penState == P_UP ? true : false)); sendMessage(msg); } void Robot::start() { setState(R_START); } void Robot::testRotate(float angle) { targetRot = angle; cmdRot(msg, angle, rot); sendMessage(msg); // setState(R_ROTATING_TO_ANGLE); } void Robot::testMove(float direction, float magnitude) { moveDir = direction; moveMag = magnitude; // setState(R_MOVING); cmdMove(msg, direction, magnitude, rot); sendMessage(msg); } void Robot::updateCamera(const ofVec3f &newRvec, const ofVec3f &newTvec, const ofMatrix4x4 &cameraWorldInv) { rvec = newRvec; tvec = newTvec; // http://answers.opencv.org/question/110441/use-rotation-vector-from-aruco-in-unity3d/ float angle = sqrt(rvec.x*rvec.x + rvec.y*rvec.y + rvec.z*rvec.z); ofVec3f axis(rvec.x, rvec.y, rvec.z); ofQuaternion rvecQuat; rvecQuat.makeRotate(angle / 3.14159 * 180.0, axis); mat.makeIdentityMatrix(); mat.setRotate(rvecQuat); mat.setTranslation(tvec); mat = mat * cameraWorldInv; // Get position in world worldPos = mat.getTranslation(); // Translate to the center of the marker planePos.set(worldPos.x, worldPos.y); // planePos += ofVec2f(kMarkerSizeM / 2.0, kMarkerSizeM / 2.0); // Get z-axis rotation ofVec3f xAxis = ofVec3f(1.0, 0.0, 0.0) * mat; ofVec2f xAxisVec = ofVec2f(xAxis.x, xAxis.y) - ofVec2f(worldPos.x, worldPos.y); float xAxisAngle = atan2(xAxisVec.y, xAxisVec.x); // rotation is right-handed, and goes from 0-360 starting on the +x axis rot = fmod(ofRadToDeg(xAxisAngle) + 360, 360.0); lastCameraUpdateTime = ofGetElapsedTimef(); } void Robot::gotHeartbeat() { lastHeartbeatTime = ofGetElapsedTimef(); } bool Robot::commsUp() { return true; return ofGetElapsedTimef() - lastHeartbeatTime < kHeartbeatTimeoutSec; } bool Robot::cvDetected() { return ofGetElapsedTimef() - lastCameraUpdateTime < kCameraTimeoutSec; } void Robot::setState(RobotState newState) { cout << "State change " << state << " to " << newState << endl; state = newState; stateStartTime = ofGetElapsedTimef(); } void Robot::moveRobot(char *msg, ofVec2f target, bool drawing, bool &shouldSend) { ofVec2f dir = target - planePos; float len = dir.length(); dir.normalize(); float mag = ofMap(len, 0, 1, 150, 250, true); float rad = atan2(dir.y, dir.x); float angle = fmod(ofRadToDeg(rad) + 360, 360.0); if (drawing) { cout << "DRAWING" << endl; cmdDraw(msg, angle, mag, rot); } else { cout << "MOVING" << endl; cmdMove(msg, angle, mag, rot); } shouldSend = true; cout << planePos << endl; cout << target << endl; cout << msg << endl; } bool Robot::inPosition(ofVec2f target) { ofVec2f dir = target - planePos; float len = dir.length(); return (len < kTolerance ? true : false); } void Robot::setPathType(int pathType) { navState.pathType = pathType; } void Robot::startNavigation(ofVec2f start, ofVec2f end) { navState.start = start; navState.end = end; setState(R_POSITIONING); } void Robot::update() { bool shouldSend = false; float elapsedStateTime = ofGetElapsedTimef() - stateStartTime; float rotAngleDiff = ofAngleDifferenceDegrees(targetRot, rot); if (!enableMessages) { return; } // if (!commsUp()) { // if (state != R_NO_CONN) { // cout << "Comms down, moving to NO_CONN" << endl; // setState(R_NO_CONN); // } // // cmdStop(msg, false); // shouldSend = true; // } else if (!cvDetected()) { if (state != R_NO_CONN) { cout << "CV down, moving to NO_CONN" << endl; setState(R_NO_CONN); } cmdStop(msg, false); shouldSend = true; } else if (state == R_NO_CONN) { // Now connected and seen! setState(R_START); cmdStop(msg, false); shouldSend = true; } else if (state == R_START) { // If we're started, immediately calibrate the angle setState(R_CALIBRATING_ANGLE); } else if (state == R_CALIBRATING_ANGLE) { // We're calibrating the angle for a bit cmdCalibrateAngle(msg, rot); shouldSend = true; if (elapsedStateTime >= kCalibrationWaitSec) { // We've calibrated enough setState(R_POSITIONING); } } else if (state == R_ROTATING_TO_ANGLE) { // We're rotating to a target angle if (abs(rotAngleDiff) > kRotationToleranceFinal) { // Too far from angle, keep moving. cmdRot(msg, targetRot, rot); shouldSend = true; } else { // Close enough to angle, wait to see if the robot stays close enough. setState(R_WAITING_ANGLE); } } else if (state == R_WAITING_ANGLE) { // We're waiting after issuing rotate commands if (elapsedStateTime < kAngleWaitSec) { // Pass } else if (abs(rotAngleDiff) > kRotationToleranceFinal) { // We're out of tolerance, try rotating again. setState(R_ROTATING_TO_ANGLE); } else if (elapsedStateTime > kAngleWaitSec) { // We've waited long enough, stop. setState(R_STOPPED); cmdStop(msg, false); shouldSend = true; } } else if (state == R_POSITIONING) { cout << "STATE POSITIONING" << endl; // move in direction at magnitude if (inPosition(navState.start)) { cmdStop(msg, false); shouldSend = true; if (elapsedStateTime > 1.0f) { setState(R_WAITING_TO_DRAW); } } else { // move is different from draw moveRobot(msg, navState.start, false, shouldSend); } } else if (state == R_WAITING_TO_DRAW) { cout << "WAITING TO DRAW" << endl; // wait for okay to draw if (navState.drawReady) { setState(R_DRAWING); navState.drawReady = false; } } else if (state == R_DRAWING) { cout << "DRAWING" << endl; if (inPosition(navState.end)) { setState(R_DONE_DRAWING); } else { moveRobot(msg, navState.end, true, shouldSend); } } else if (state == R_DONE_DRAWING) { cout << "DONE DRAWING" << endl; // we're stopped, pen is up cmdStop(msg, true); shouldSend = true; if (elapsedStateTime > 1.0f) { navState.readyForNextPath = true; } } else if (state == R_STOPPED) { cout << "STOPPED" << endl; // We're stopped. Stop. cmdStop(msg, false); shouldSend = true; } if (shouldSend) { shouldSend = ofGetFrameNum() % 4 == 0; } if (shouldSend && enableMessages) { sendMessage(msg); } } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.8 2000/11/02 07:23:27 roddey * Just a test of checkin access * * Revision 1.7 2000/08/18 21:29:14 andyh * Change version to 1.3 in preparation for upcoming Xerces 1.3 * and XML4C 3.3 stable releases * * Revision 1.6 2000/08/07 20:31:34 jpolast * include SAX2_EXPORT module * * Revision 1.5 2000/08/01 18:26:02 aruna1 * Tru64 support added * * Revision 1.4 2000/07/29 05:36:37 jberry * Fix misspelling in Mac OS port * * Revision 1.3 2000/07/19 18:20:12 andyh * Macintosh port: fix problems with yesterday's code checkin. A couple * of the changes were mangled or missed. * * Revision 1.2 2000/04/04 20:11:29 abagchi * Added PTX support * * Revision 1.1 2000/03/02 19:54:50 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.13 2000/03/02 01:51:00 aruna1 * Sun CC 5.0 related changes * * Revision 1.12 2000/02/24 20:05:26 abagchi * Swat for removing Log from API docs * * Revision 1.11 2000/02/22 01:00:10 aruna1 * GNUGDefs references removed. Now only GCCDefs is used instead * * Revision 1.10 2000/02/06 07:48:05 rahulj * Year 2K copyright swat. * * Revision 1.9 2000/02/01 23:43:32 abagchi * AS/400 related change * * Revision 1.8 2000/01/21 22:12:29 abagchi * OS390 Change: changed OE390 to OS390 * * Revision 1.7 2000/01/14 01:18:35 roddey * Added a macro, XMLStrL(), which is defined one way or another according * to whether the per-compiler file defines XML_LSTRSUPPORT or not. This * allows conditional support of L"" type prefixes. * * Revision 1.6 2000/01/14 00:52:06 roddey * Updated the version information for the next release, i.e. 1.1.0 * * Revision 1.5 1999/12/17 01:28:53 rahulj * Merged in changes submitted for UnixWare 7 port. Platform * specific files are still missing. * * Revision 1.4 1999/12/16 23:47:10 rahulj * Updated for version 1.0.1 * * Revision 1.3 1999/12/01 17:16:16 rahulj * Added support for IRIX 6.5.5 using SGI MIPSpro C++ 7.3 and 7.21 generating 32 bit objects. Changes submitted by Marc Stuessel * * Revision 1.2 1999/11/10 02:02:51 abagchi * Changed version numbers * * Revision 1.1.1.1 1999/11/09 01:05:35 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:19 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(XERCESDEFS_HPP) #define XERCESDEFS_HPP // Just a check in test, remove me! // --------------------------------------------------------------------------- // These are the various representations of the current version of Xerces. // These are updated for every build. They must be at the top because they // can be used by various per-compiler headers below. // --------------------------------------------------------------------------- #define Xerces_DLLVersionStr "1_3" static const char* const gXercesVersionStr = "1_3"; static const char* const gXercesFullVersionStr = "1_3_0"; static const unsigned int gXercesMajVersion = 1; static const unsigned int gXercesMinVersion = 2; static const unsigned int gXercesRevision = 0; // --------------------------------------------------------------------------- // Include the header that does automatic sensing of the current platform // and compiler. // --------------------------------------------------------------------------- #include <util/AutoSense.hpp> // --------------------------------------------------------------------------- // According to the platform we include a platform specific file. This guy // will set up any platform specific stuff, such as character mode. // --------------------------------------------------------------------------- #if defined(XML_WIN32) #include <util/Platforms/Win32/Win32Defs.hpp> #endif #if defined(XML_AIX) #include <util/Platforms/AIX/AIXDefs.hpp> #endif #if defined(XML_SOLARIS) #include <util/Platforms/Solaris/SolarisDefs.hpp> #endif #if defined(XML_UNIXWARE) #include <util/Platforms/UnixWare/UnixWareDefs.hpp> #endif #if defined(XML_HPUX) #include <util/Platforms/HPUX/HPUXDefs.hpp> #endif #if defined(XML_IRIX) #include <util/Platforms/IRIX/IRIXDefs.hpp> #endif #if defined(XML_TANDEM) #include <util/Platforms/Tandem/TandemDefs.hpp> #endif #if defined(XML_LINUX) #include <util/Platforms/Linux/LinuxDefs.hpp> #endif #if defined(XML_OS390) #include <util/Platforms/OS390/OS390Defs.hpp> #endif #if defined(XML_PTX) #include <util/Platforms/PTX/PTXDefs.hpp> #endif #if defined(XML_OS2) #include <util/Platforms/OS2/OS2Defs.hpp> #endif #if defined(XML_MACOS) || defined(XML_MACOSX) #include <util/Platforms/MacOS/MacOSDefs.hpp> #endif #if defined(XML_AS400) #include <util/Platforms/OS400/OS400Defs.hpp> #endif #if defined(XML_TRU64) #include <util/Platforms/Tru64/Tru64Defs.hpp> #endif // --------------------------------------------------------------------------- // And now we subinclude a header according to the development environment // we are on. This guy defines for each platform some basic stuff that is // specific to the development environment. // --------------------------------------------------------------------------- #if defined(XML_VISUALCPP) #include <util/Compilers/VCPPDefs.hpp> #endif #if defined(XML_CSET) #include <util/Compilers/CSetDefs.hpp> #endif #if defined(XML_BORLAND) #include <util/Compilers/BorlandCDefs.hpp> #endif #if defined(XML_SUNCC) || defined(XML_SUNCC5) #include <util/Compilers/SunCCDefs.hpp> #endif #if defined(XML_SCOCC) #include <util/Compilers/SCOCCDefs.hpp> #endif #if defined(XML_SOLARIS_KAICC) #include <util/Compilers/SunKaiDefs.hpp> #endif #if defined(XML_HPUX_CC) || defined(XML_HPUX_aCC) || defined(XML_HPUX_KAICC) #include <util/Compilers/HPCCDefs.hpp> #endif #if defined(XML_MIPSPRO_CC) #include <util/Compilers/MIPSproDefs.hpp> #endif #if defined(XML_TANDEMCC) #include <util/Compilers/TandemCCDefs.hpp> #endif #if defined(XML_GCC) #include <util/Compilers/GCCDefs.hpp> #endif #if defined(XML_MVSCPP) #include <util/Compilers/MVSCPPDefs.hpp> #endif #if defined(XML_IBMVAW32) #include <util/Compilers/IBMVAW32Defs.hpp> #endif #if defined(XML_IBMVAOS2) #include <util/Compilers/IBMVAOS2Defs.hpp> #endif #if defined(XML_METROWERKS) #include <util/Compilers/CodeWarriorDefs.hpp> #endif #if defined(XML_PTX_CC) #include <util/Compilers/PTXCCDefs.hpp> #endif #if defined(XML_AS400) #include <util/Compilers/OS400SetDefs.hpp> #endif #if defined(XML_TRU64) #include <util/Compilers/DECCXXDefs.hpp> #endif // --------------------------------------------------------------------------- // Some general typedefs that are defined for internal flexibility. // // Note that UTF16Ch is fixed at 16 bits, whereas XMLCh floats in size per // platform, to whatever is the native wide char format there. UCS4Ch is // fixed at 32 bits. The types we defined them in terms of are defined per // compiler, using whatever types are the right ones for them to get these // 16/32 bit sizes. // --------------------------------------------------------------------------- typedef unsigned char XMLByte; typedef XMLUInt16 UTF16Ch; typedef XMLUInt32 UCS4Ch; // --------------------------------------------------------------------------- // Handle boolean. If the platform can handle booleans itself, then we // map our boolean type to the native type. Otherwise we create a default // one as an int and define const values for true and false. // // This flag will be set in the per-development environment stuff above. // --------------------------------------------------------------------------- #if defined(NO_NATIVE_BOOL) #ifndef bool typedef int bool; #endif #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #endif // --------------------------------------------------------------------------- // According to whether the compiler suports L"" type strings, we define // the XMLStrL() macro one way or another. // --------------------------------------------------------------------------- #if defined(XML_LSTRSUPPORT) #define XMLStrL(str) L##str #else #define XMLStrL(str) str #endif // --------------------------------------------------------------------------- // Set up the import/export keyword for our core projects. The // PLATFORM_XXXX keywords are set in the per-development environment // include above. // --------------------------------------------------------------------------- #if defined(PROJ_XMLUTIL) #define XMLUTIL_EXPORT PLATFORM_EXPORT #else #define XMLUTIL_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_XMLPARSER) #define XMLPARSER_EXPORT PLATFORM_EXPORT #else #define XMLPARSER_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX4C) #define SAX_EXPORT PLATFORM_EXPORT #else #define SAX_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX2) #define SAX2_EXPORT PLATFORM_EXPORT #else #define SAX2_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_DOM) #define CDOM_EXPORT PLATFORM_EXPORT #else #define CDOM_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_PARSERS) #define PARSERS_EXPORT PLATFORM_EXPORT #else #define PARSERS_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_VALIDATORS) #define VALIDATORS_EXPORT PLATFORM_EXPORT #else #define VALIDATORS_EXPORT PLATFORM_IMPORT #endif #endif <commit_msg>Fix incorrect version number in gXercesMinVersion. From Pieter Van-Dyck<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.9 2000/11/07 18:14:39 andyh * Fix incorrect version number in gXercesMinVersion. * From Pieter Van-Dyck * * Revision 1.8 2000/11/02 07:23:27 roddey * Just a test of checkin access * * Revision 1.7 2000/08/18 21:29:14 andyh * Change version to 1.3 in preparation for upcoming Xerces 1.3 * and XML4C 3.3 stable releases * * Revision 1.6 2000/08/07 20:31:34 jpolast * include SAX2_EXPORT module * * Revision 1.5 2000/08/01 18:26:02 aruna1 * Tru64 support added * * Revision 1.4 2000/07/29 05:36:37 jberry * Fix misspelling in Mac OS port * * Revision 1.3 2000/07/19 18:20:12 andyh * Macintosh port: fix problems with yesterday's code checkin. A couple * of the changes were mangled or missed. * * Revision 1.2 2000/04/04 20:11:29 abagchi * Added PTX support * * Revision 1.1 2000/03/02 19:54:50 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.13 2000/03/02 01:51:00 aruna1 * Sun CC 5.0 related changes * * Revision 1.12 2000/02/24 20:05:26 abagchi * Swat for removing Log from API docs * * Revision 1.11 2000/02/22 01:00:10 aruna1 * GNUGDefs references removed. Now only GCCDefs is used instead * * Revision 1.10 2000/02/06 07:48:05 rahulj * Year 2K copyright swat. * * Revision 1.9 2000/02/01 23:43:32 abagchi * AS/400 related change * * Revision 1.8 2000/01/21 22:12:29 abagchi * OS390 Change: changed OE390 to OS390 * * Revision 1.7 2000/01/14 01:18:35 roddey * Added a macro, XMLStrL(), which is defined one way or another according * to whether the per-compiler file defines XML_LSTRSUPPORT or not. This * allows conditional support of L"" type prefixes. * * Revision 1.6 2000/01/14 00:52:06 roddey * Updated the version information for the next release, i.e. 1.1.0 * * Revision 1.5 1999/12/17 01:28:53 rahulj * Merged in changes submitted for UnixWare 7 port. Platform * specific files are still missing. * * Revision 1.4 1999/12/16 23:47:10 rahulj * Updated for version 1.0.1 * * Revision 1.3 1999/12/01 17:16:16 rahulj * Added support for IRIX 6.5.5 using SGI MIPSpro C++ 7.3 and 7.21 generating 32 bit objects. Changes submitted by Marc Stuessel * * Revision 1.2 1999/11/10 02:02:51 abagchi * Changed version numbers * * Revision 1.1.1.1 1999/11/09 01:05:35 twl * Initial checkin * * Revision 1.3 1999/11/08 20:45:19 rahul * Swat for adding in Product name and CVS comment log variable. * */ #if !defined(XERCESDEFS_HPP) #define XERCESDEFS_HPP // --------------------------------------------------------------------------- // These are the various representations of the current version of Xerces. // These are updated for every build. They must be at the top because they // can be used by various per-compiler headers below. // --------------------------------------------------------------------------- #define Xerces_DLLVersionStr "1_3" static const char* const gXercesVersionStr = "1_3"; static const char* const gXercesFullVersionStr = "1_3_0"; static const unsigned int gXercesMajVersion = 1; static const unsigned int gXercesMinVersion = 3; static const unsigned int gXercesRevision = 0; // --------------------------------------------------------------------------- // Include the header that does automatic sensing of the current platform // and compiler. // --------------------------------------------------------------------------- #include <util/AutoSense.hpp> // --------------------------------------------------------------------------- // According to the platform we include a platform specific file. This guy // will set up any platform specific stuff, such as character mode. // --------------------------------------------------------------------------- #if defined(XML_WIN32) #include <util/Platforms/Win32/Win32Defs.hpp> #endif #if defined(XML_AIX) #include <util/Platforms/AIX/AIXDefs.hpp> #endif #if defined(XML_SOLARIS) #include <util/Platforms/Solaris/SolarisDefs.hpp> #endif #if defined(XML_UNIXWARE) #include <util/Platforms/UnixWare/UnixWareDefs.hpp> #endif #if defined(XML_HPUX) #include <util/Platforms/HPUX/HPUXDefs.hpp> #endif #if defined(XML_IRIX) #include <util/Platforms/IRIX/IRIXDefs.hpp> #endif #if defined(XML_TANDEM) #include <util/Platforms/Tandem/TandemDefs.hpp> #endif #if defined(XML_LINUX) #include <util/Platforms/Linux/LinuxDefs.hpp> #endif #if defined(XML_OS390) #include <util/Platforms/OS390/OS390Defs.hpp> #endif #if defined(XML_PTX) #include <util/Platforms/PTX/PTXDefs.hpp> #endif #if defined(XML_OS2) #include <util/Platforms/OS2/OS2Defs.hpp> #endif #if defined(XML_MACOS) || defined(XML_MACOSX) #include <util/Platforms/MacOS/MacOSDefs.hpp> #endif #if defined(XML_AS400) #include <util/Platforms/OS400/OS400Defs.hpp> #endif #if defined(XML_TRU64) #include <util/Platforms/Tru64/Tru64Defs.hpp> #endif // --------------------------------------------------------------------------- // And now we subinclude a header according to the development environment // we are on. This guy defines for each platform some basic stuff that is // specific to the development environment. // --------------------------------------------------------------------------- #if defined(XML_VISUALCPP) #include <util/Compilers/VCPPDefs.hpp> #endif #if defined(XML_CSET) #include <util/Compilers/CSetDefs.hpp> #endif #if defined(XML_BORLAND) #include <util/Compilers/BorlandCDefs.hpp> #endif #if defined(XML_SUNCC) || defined(XML_SUNCC5) #include <util/Compilers/SunCCDefs.hpp> #endif #if defined(XML_SCOCC) #include <util/Compilers/SCOCCDefs.hpp> #endif #if defined(XML_SOLARIS_KAICC) #include <util/Compilers/SunKaiDefs.hpp> #endif #if defined(XML_HPUX_CC) || defined(XML_HPUX_aCC) || defined(XML_HPUX_KAICC) #include <util/Compilers/HPCCDefs.hpp> #endif #if defined(XML_MIPSPRO_CC) #include <util/Compilers/MIPSproDefs.hpp> #endif #if defined(XML_TANDEMCC) #include <util/Compilers/TandemCCDefs.hpp> #endif #if defined(XML_GCC) #include <util/Compilers/GCCDefs.hpp> #endif #if defined(XML_MVSCPP) #include <util/Compilers/MVSCPPDefs.hpp> #endif #if defined(XML_IBMVAW32) #include <util/Compilers/IBMVAW32Defs.hpp> #endif #if defined(XML_IBMVAOS2) #include <util/Compilers/IBMVAOS2Defs.hpp> #endif #if defined(XML_METROWERKS) #include <util/Compilers/CodeWarriorDefs.hpp> #endif #if defined(XML_PTX_CC) #include <util/Compilers/PTXCCDefs.hpp> #endif #if defined(XML_AS400) #include <util/Compilers/OS400SetDefs.hpp> #endif #if defined(XML_TRU64) #include <util/Compilers/DECCXXDefs.hpp> #endif // --------------------------------------------------------------------------- // Some general typedefs that are defined for internal flexibility. // // Note that UTF16Ch is fixed at 16 bits, whereas XMLCh floats in size per // platform, to whatever is the native wide char format there. UCS4Ch is // fixed at 32 bits. The types we defined them in terms of are defined per // compiler, using whatever types are the right ones for them to get these // 16/32 bit sizes. // --------------------------------------------------------------------------- typedef unsigned char XMLByte; typedef XMLUInt16 UTF16Ch; typedef XMLUInt32 UCS4Ch; // --------------------------------------------------------------------------- // Handle boolean. If the platform can handle booleans itself, then we // map our boolean type to the native type. Otherwise we create a default // one as an int and define const values for true and false. // // This flag will be set in the per-development environment stuff above. // --------------------------------------------------------------------------- #if defined(NO_NATIVE_BOOL) #ifndef bool typedef int bool; #endif #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #endif // --------------------------------------------------------------------------- // According to whether the compiler suports L"" type strings, we define // the XMLStrL() macro one way or another. // --------------------------------------------------------------------------- #if defined(XML_LSTRSUPPORT) #define XMLStrL(str) L##str #else #define XMLStrL(str) str #endif // --------------------------------------------------------------------------- // Set up the import/export keyword for our core projects. The // PLATFORM_XXXX keywords are set in the per-development environment // include above. // --------------------------------------------------------------------------- #if defined(PROJ_XMLUTIL) #define XMLUTIL_EXPORT PLATFORM_EXPORT #else #define XMLUTIL_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_XMLPARSER) #define XMLPARSER_EXPORT PLATFORM_EXPORT #else #define XMLPARSER_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX4C) #define SAX_EXPORT PLATFORM_EXPORT #else #define SAX_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_SAX2) #define SAX2_EXPORT PLATFORM_EXPORT #else #define SAX2_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_DOM) #define CDOM_EXPORT PLATFORM_EXPORT #else #define CDOM_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_PARSERS) #define PARSERS_EXPORT PLATFORM_EXPORT #else #define PARSERS_EXPORT PLATFORM_IMPORT #endif #if defined(PROJ_VALIDATORS) #define VALIDATORS_EXPORT PLATFORM_EXPORT #else #define VALIDATORS_EXPORT PLATFORM_IMPORT #endif #endif <|endoftext|>
<commit_before>#include "implicit.h" #include "math_util.h" #include "transformed.h" #include <memory> static const scalar MIN_STEP = 0.0001; using std::make_shared; ImplicitSurface::ImplicitSurface(ImplicitEvalFunc f_, ImplicitGradFunc g_, scalar lipschitz_const, const bounds::AABB& bounds) : f(f_), g(g_), L(lipschitz_const), bbox(bounds) { } Vec3 ImplicitSurface::normal(SubGeo subgeo, const Vec3& point) const { return g(point).normal(); } /* * intersectino using a basic sphere-tracing algorithm */ scalar_fp ImplicitSurface::intersect(const Ray& r, scalar_fp max_t) const { scalar t0, t1; if (!bbox.intersect(r, t0, t1)) return sfp_none; if (max_t < t0 || max_t < MIN_STEP || t1 < MIN_STEP) return sfp_none; if (max_t.is()) t1 = std::min(max_t.get(), t1); scalar t = MIN_STEP; scalar rdn = r.direction.norm(); scalar dist = f(r.evaluate(t)); if (fabs(dist) < MIN_STEP) return scalar_fp{t}; const auto rdnl = rdn * L; do { scalar t_diff = std::max(dist, MIN_STEP) / rdnl; scalar new_t = t + t_diff; scalar new_dist = f(r.evaluate(new_t)); if (fabs(new_dist) < MIN_STEP) { // If we find a near-enough surface point, use the secant approximation to // find the zero-point. return scalar_fp{t + (dist - 0) / (dist - new_dist) * t_diff}; } t = new_t; dist = new_dist; } while (t < t1); return sfp_none; } class GradFromEval { public: GradFromEval(ImplicitEvalFunc f_) : f(f_) { } Vec3 grad(const Vec3& v) { scalar EPS = 0.0001; scalar p = f(v); return Vec3( (f(v + Vec3::x_axis * EPS) - p) / EPS, (f(v + Vec3::y_axis * EPS) - p) / EPS, (f(v + Vec3::z_axis * EPS) - p) / EPS); } private: ImplicitEvalFunc f; }; ImplicitGradFunc gradient_from_sdf(ImplicitEvalFunc f) { auto grad = make_shared<GradFromEval>(f); return [=](const Vec3& v) { return grad->grad(v); }; } //////////////////////////////////////////////////////////////////////////////// shared_ptr<Geometry> make_torus(Vec3 normal, scalar outer_radius, scalar inner_radius) { auto sdf = [=](const Vec3& v) { scalar xz = sqrt(v.x*v.x + v.z*v.z); scalar a = xz - inner_radius; scalar b = v.y; return sqrt(a*a + b*b) - outer_radius; }; auto gsdf = gradient_from_sdf(sdf); const auto Rxz = outer_radius + inner_radius; const auto lb = Vec3{-Rxz, -inner_radius, -Rxz}; return make_shared<Transformed>( make_shared<ImplicitSurface>(sdf, gsdf, 1.0, bounds::AABB{lb, -lb}), Transform{Mat33::rotate_match(Vec3::y_axis, normal), Vec3::zero}); } shared_ptr<Geometry> make_capsule(Vec3 direction, scalar length, scalar radius) { Vec3 a = direction.normal() * (length / 2); Vec3 b = -a; auto sdf = [=](const Vec3& v) { Vec3 va = v - a, ba = b - a; scalar s = clamp( va.dot(ba) / ba.norm2(), 0, 1); return ( va - ba * s ).norm() - radius; }; Vec3 r{radius}; Vec3 lb = -direction.abs() - r; return make_shared<ImplicitSurface>(sdf, gradient_from_sdf(sdf), 1.0, bounds::AABB{lb, -lb}); } shared_ptr<Geometry> make_rounded_box(Vec3 size, scalar radius) { Vec3 hw = size.abs() * 0.5; auto sdf = [=] (const Vec3& v) { return max(v.abs() - hw, Vec3::zero).norm() - radius; }; auto ub = hw + Vec3{radius}; return make_shared<ImplicitSurface>(sdf, gradient_from_sdf(sdf), 1.0, bounds::AABB{-ub, ub}); } <commit_msg>Fixes (via swap) torus outer/inner radius<commit_after>#include "implicit.h" #include "math_util.h" #include "transformed.h" #include <memory> static const scalar MIN_STEP = 0.0001; using std::make_shared; ImplicitSurface::ImplicitSurface(ImplicitEvalFunc f_, ImplicitGradFunc g_, scalar lipschitz_const, const bounds::AABB& bounds) : f(f_), g(g_), L(lipschitz_const), bbox(bounds) { } Vec3 ImplicitSurface::normal(SubGeo subgeo, const Vec3& point) const { return g(point).normal(); } /* * intersectino using a basic sphere-tracing algorithm */ scalar_fp ImplicitSurface::intersect(const Ray& r, scalar_fp max_t) const { scalar t0, t1; if (!bbox.intersect(r, t0, t1)) return sfp_none; if (max_t < t0 || max_t < MIN_STEP || t1 < MIN_STEP) return sfp_none; if (max_t.is()) t1 = std::min(max_t.get(), t1); scalar t = MIN_STEP; scalar rdn = r.direction.norm(); scalar dist = f(r.evaluate(t)); if (fabs(dist) < MIN_STEP) return scalar_fp{t}; const auto rdnl = rdn * L; do { scalar t_diff = std::max(dist, MIN_STEP) / rdnl; scalar new_t = t + t_diff; scalar new_dist = f(r.evaluate(new_t)); if (fabs(new_dist) < MIN_STEP) { // If we find a near-enough surface point, use the secant approximation to // find the zero-point. return scalar_fp{t + (dist - 0) / (dist - new_dist) * t_diff}; } t = new_t; dist = new_dist; } while (t < t1); return sfp_none; } class GradFromEval { public: GradFromEval(ImplicitEvalFunc f_) : f(f_) { } Vec3 grad(const Vec3& v) { scalar EPS = 0.0001; scalar p = f(v); return Vec3( (f(v + Vec3::x_axis * EPS) - p) / EPS, (f(v + Vec3::y_axis * EPS) - p) / EPS, (f(v + Vec3::z_axis * EPS) - p) / EPS); } private: ImplicitEvalFunc f; }; ImplicitGradFunc gradient_from_sdf(ImplicitEvalFunc f) { auto grad = make_shared<GradFromEval>(f); return [=](const Vec3& v) { return grad->grad(v); }; } //////////////////////////////////////////////////////////////////////////////// shared_ptr<Geometry> make_torus(Vec3 normal, scalar outer_radius, scalar inner_radius) { auto sdf = [=](const Vec3& v) { scalar xz = sqrt(v.x*v.x + v.z*v.z); scalar a = xz - outer_radius; scalar b = v.y; return sqrt(a*a + b*b) - inner_radius; }; auto gsdf = gradient_from_sdf(sdf); const auto Rxz = outer_radius + inner_radius; const auto lb = Vec3{-Rxz, -inner_radius, -Rxz}; return make_shared<Transformed>( make_shared<ImplicitSurface>(sdf, gsdf, 1.0, bounds::AABB{lb, -lb}), Transform{Mat33::rotate_match(Vec3::y_axis, normal), Vec3::zero}); } shared_ptr<Geometry> make_capsule(Vec3 direction, scalar length, scalar radius) { Vec3 a = direction.normal() * (length / 2); Vec3 b = -a; auto sdf = [=](const Vec3& v) { Vec3 va = v - a, ba = b - a; scalar s = clamp( va.dot(ba) / ba.norm2(), 0, 1); return ( va - ba * s ).norm() - radius; }; Vec3 r{radius}; Vec3 lb = -direction.abs() - r; return make_shared<ImplicitSurface>(sdf, gradient_from_sdf(sdf), 1.0, bounds::AABB{lb, -lb}); } shared_ptr<Geometry> make_rounded_box(Vec3 size, scalar radius) { Vec3 hw = size.abs() * 0.5; auto sdf = [=] (const Vec3& v) { return max(v.abs() - hw, Vec3::zero).norm() - radius; }; auto ub = hw + Vec3{radius}; return make_shared<ImplicitSurface>(sdf, gradient_from_sdf(sdf), 1.0, bounds::AABB{-ub, ub}); } <|endoftext|>
<commit_before>#include <WPILib.h> #include "Subsystems/IntakeWheel.h" #include "Subsystems/IntakeHorizontal.h" #include "Subsystems/IntakeVertical.h" #include "Subsystems/Catapult.h" #include "Subsystems/CatapultFire.h" #include "Subsystems/Chassis.h" #include "Subsystems/Climber.h" #include "AutonCommands/1BallReturn.h" #include "AutonCommands/1BallAuton.h" #include "AutonCommands/PickUpAuton.h" #include "AutonCommands/PickUpReturn.h" #include "AutonCommands/NoAuton.h" #include "Commands/RobotSensors.h" #include "Commands/CameraFeed.h" #include "Subsystems/Blinkies.h" #include "Subsystems/CatStopCalculations.h" class Robot: public IterativeRobot { private: Command *autonomousCommand; SendableChooser* autonChooser; LiveWindow *lw; Compressor* compressor; Command *robotSensors; CameraFeed *cameraFeed; void RobotInit() { compressor = new Compressor(CAN_PNMMODULE); compressor->Start(); robotSensors = new RobotSensors(); robotSensors->Start(); cameraFeed = new CameraFeed(); cameraFeed->Start(); // Create a single static instance of all of your subsystems. The following // line should be repeated for each subsystem in the project. Chassis::GetInstance(); IntakeWheel::GetInstance(); IntakeHorizontal::GetInstance(); IntakeVertical::GetInstance(); Climber::GetInstance(); Catapult::GetInstance(); CatapultFire::GetInstance(); CatStopCalculations::GetInstance(); //Creates Radio Buttons for selection of Auton modes, include and AddObject() for each //Autonomous Mode being added autonChooser = new SendableChooser(); autonChooser->AddDefault("One Ball Auton", new OneBallAuton()); autonChooser->AddObject("No Auton", new NoAuton()); autonChooser->AddObject("One Ball Return", new OneBallReturn()); autonChooser->AddObject("Pick Up Ball Auton", new PickUpAuton()); autonChooser->AddObject("Pick Up Ball Return Auton", new PickUpReturn()); SmartDashboard::PutData("Autonomous Choices", autonChooser); lw = LiveWindow::GetInstance(); } void DisabledInit() { // printf("Default %s() method... Overload me!\n", __FUNCTION__); Blinkies::PutCommand("roundEnd"); } void DisabledPeriodic() { Scheduler::GetInstance()->Run(); } void AutonomousInit() { autonomousCommand = (Command *)autonChooser->GetSelected(); if(autonomousCommand != nullptr) { autonomousCommand->Start(); } } void AutonomousPeriodic() { Scheduler::GetInstance()->Run(); } void TeleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand !=nullptr) autonomousCommand->Cancel(); IntakeHorizontal::GetInstance()->Actuate(true); } void TeleopPeriodic() { Scheduler::GetInstance()->Run(); } void TestPeriodic() { lw->Run(); } }; START_ROBOT_CLASS(Robot); <commit_msg>Added positions for the other intake axis on teleop enable.<commit_after>#include <WPILib.h> #include "Subsystems/IntakeWheel.h" #include "Subsystems/IntakeHorizontal.h" #include "Subsystems/IntakeVertical.h" #include "Subsystems/IntakePin.h" #include "Subsystems/Catapult.h" #include "Subsystems/CatapultFire.h" #include "Subsystems/Chassis.h" #include "Subsystems/Climber.h" #include "AutonCommands/1BallReturn.h" #include "AutonCommands/1BallAuton.h" #include "AutonCommands/PickUpAuton.h" #include "AutonCommands/PickUpReturn.h" #include "AutonCommands/NoAuton.h" #include "Commands/RobotSensors.h" #include "Commands/CameraFeed.h" #include "Subsystems/Blinkies.h" #include "Subsystems/CatStopCalculations.h" class Robot: public IterativeRobot { private: Command *autonomousCommand; SendableChooser* autonChooser; LiveWindow *lw; Compressor* compressor; Command *robotSensors; CameraFeed *cameraFeed; void RobotInit() { compressor = new Compressor(CAN_PNMMODULE); compressor->Start(); robotSensors = new RobotSensors(); robotSensors->Start(); cameraFeed = new CameraFeed(); cameraFeed->Start(); // Create a single static instance of all of your subsystems. The following // line should be repeated for each subsystem in the project. Chassis::GetInstance(); IntakeWheel::GetInstance(); IntakeHorizontal::GetInstance(); IntakeVertical::GetInstance(); IntakePin::GetInstance(); Climber::GetInstance(); Catapult::GetInstance(); CatapultFire::GetInstance(); CatStopCalculations::GetInstance(); //Creates Radio Buttons for selection of Auton modes, include and AddObject() for each //Autonomous Mode being added autonChooser = new SendableChooser(); autonChooser->AddDefault("One Ball Auton", new OneBallAuton()); autonChooser->AddObject("No Auton", new NoAuton()); autonChooser->AddObject("One Ball Return", new OneBallReturn()); autonChooser->AddObject("Pick Up Ball Auton", new PickUpAuton()); autonChooser->AddObject("Pick Up Ball Return Auton", new PickUpReturn()); SmartDashboard::PutData("Autonomous Choices", autonChooser); lw = LiveWindow::GetInstance(); } void DisabledInit() { // printf("Default %s() method... Overload me!\n", __FUNCTION__); Blinkies::PutCommand("roundEnd"); } void DisabledPeriodic() { Scheduler::GetInstance()->Run(); } void AutonomousInit() { autonomousCommand = (Command *)autonChooser->GetSelected(); if(autonomousCommand != nullptr) { autonomousCommand->Start(); } } void AutonomousPeriodic() { Scheduler::GetInstance()->Run(); } void TeleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. if (autonomousCommand !=nullptr) autonomousCommand->Cancel(); //Set Default positions for the intake axis upon telop enable. IntakeHorizontal::GetInstance()->Actuate(true); IntakeVertical::GetInstance()->Actuate(false); IntakePin::GetInstance()->Actuate(false); } void TeleopPeriodic() { Scheduler::GetInstance()->Run(); } void TestPeriodic() { lw->Run(); } }; START_ROBOT_CLASS(Robot); <|endoftext|>
<commit_before>/* Robot.cpp -- Implementation of Robot class Copyright (C) 2014 Tushar Pankaj This file is part of San Diego Robotics 101 Robosub. San Diego Robotics 101 Robosub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by he Free Software Foundation, either version 3 of the License, or (at your option) any later version. San Diego Robotics 101 Robosub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with San Diego Robotics 101 Robosub. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <thread> #include <chrono> #include "Robot.hpp" #include "Serial.hpp" #include "TXPacket.hpp" void Robot::start() { serial.open_serial(); serial.start(); std::cout << "Moving forward at full speed"; serial.get_tx_packet()->set_vel_x(127); std::this_thread::sleep_for(std::chrono::seconds(5)); serial.get_tx_packet()->set_vel_x(0); std::cout << "done" << std::endl; std::cout << "Moving up at full speed"; serial.get_tx_packet()->set_vel_z(127); std::this_thread::sleep_for(std::chrono::seconds(5)); serial.get_tx_packet()->set_vel_z(0); std::cout << "done" << std::endl; std::cout << "Moving backward at full speed"; serial.get_tx_packet()->set_vel_x(-128); std::this_thread::sleep_for(std::chrono::seconds(5)); serial.get_tx_packet()->set_vel_x(0); std::cout << "done" << std::endl; } <commit_msg>Edited program to test all axes<commit_after>/* Robot.cpp -- Implementation of Robot class Copyright (C) 2014 Tushar Pankaj This file is part of San Diego Robotics 101 Robosub. San Diego Robotics 101 Robosub is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by he Free Software Foundation, either version 3 of the License, or (at your option) any later version. San Diego Robotics 101 Robosub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with San Diego Robotics 101 Robosub. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <thread> #include <chrono> #include "Robot.hpp" #include "Serial.hpp" #include "TXPacket.hpp" void Robot::start() { serial.open_serial(); serial.start(); std::cout << "Moving forward at full speed..."; serial.get_tx_packet()->set_vel_x(127); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "done" << std::endl; std::cout << "Moving backward at full speed..."; serial.get_tx_packet()->set_vel_x(-127); std::this_thread::sleep_for(std::chrono::seconds(5)); serial.get_tx_packet()->set_vel_x(0); std::cout << "done" << std::endl; std::cout << "Moving left at full speed..."; serial.get_tx_packet()->set_vel_y(127); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "done" << std::endl; std::cout << "Moving right at full speed..."; serial.get_tx_packet()->set_vel_y(-127); std::this_thread::sleep_for(std::chrono::seconds(5)); serial.get_tx_packet()->set_vel_y(0); std::cout << "done" << std::endl; std::cout << "Moving up at full speed..."; serial.get_tx_packet()->set_vel_z(127); std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "done" << std::endl; std::cout << "Moving down at full speed..."; serial.get_tx_packet()->set_vel_z(-127); std::this_thread::sleep_for(std::chrono::seconds(5)); serial.get_tx_packet()->set_vel_z(0); std::cout << "done" << std::endl; } <|endoftext|>
<commit_before>// Copyright 2011 Friedrich W. H. Kossebau <kossebau@kde.org> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program. If not, see <http://www.gnu.org/licenses/>. #include "plasmarunner.h" // Marble #include <GeoDataCoordinates.h> #include <GeoDataFolder.h> #include <GeoDataPlacemark.h> #include <BookmarkManager.h> #include <GeoDataTreeModel.h> // KDE #include <KProcess> #include <KIcon> #include <KLocale> namespace Marble { static const int minContainsMatchLength = 3; PlasmaRunner::PlasmaRunner(QObject *parent, const QVariantList &args) : AbstractRunner(parent, args) { setIgnoredTypes(Plasma::RunnerContext::NetworkLocation | Plasma::RunnerContext::FileSystem | Plasma::RunnerContext::Help); QList<Plasma::RunnerSyntax> syntaxes; syntaxes << Plasma::RunnerSyntax(QLatin1String(":q:"), i18n("Shows the coordinates :q: in OpenStreetMap with Marble.")); syntaxes << Plasma::RunnerSyntax(QLatin1String(":q:"), i18n("Shows the geo bookmark containing :q: in OpenStreetMap with Marble.")); setSyntaxes(syntaxes); } void PlasmaRunner::match(Plasma::RunnerContext &context) { QList<Plasma::QueryMatch> matches; const QString query = context.query(); bool success = false; // TODO: how to estimate that input is in Degree, not Radian? GeoDataCoordinates coordinates = GeoDataCoordinates::fromString(query, success); if (success) { const QVariant coordinatesData = QVariantList() << QVariant(coordinates.longitude(GeoDataCoordinates::Degree)) << QVariant(coordinates.latitude(GeoDataCoordinates::Degree)) << QVariant(0.1); // TODO: make this distance value configurable Plasma::QueryMatch match(this); match.setIcon(KIcon(QLatin1String("marble"))); match.setText(i18n("Show the coordinates %1 in OpenStreetMap with Marble", query)); match.setData(coordinatesData); match.setId(query); match.setRelevance(1.0); match.setType(Plasma::QueryMatch::ExactMatch); matches << match; } // TODO: BookmarkManager does not yet listen to updates, also does not sync between processes :( // So for now always load on demand, even if expensive possibly BookmarkManager bookmarkManager(new GeoDataTreeModel); bookmarkManager.loadFile( QLatin1String("bookmarks/bookmarks.kml") ); foreach (GeoDataFolder* folder, bookmarkManager.folders()) { collectMatches(matches, query, folder); } if ( ! matches.isEmpty() ) { context.addMatches(query, matches); } } void PlasmaRunner::collectMatches(QList<Plasma::QueryMatch> &matches, const QString &query, const GeoDataFolder *folder) { const QString queryLower = query.toLower(); QVector<GeoDataFeature*>::const_iterator it = folder->constBegin(); QVector<GeoDataFeature*>::const_iterator end = folder->constEnd(); for (; it != end; ++it) { GeoDataFolder *folder = dynamic_cast<GeoDataFolder*>(*it); if ( folder ) { collectMatches(matches, query, folder); continue; } GeoDataPlacemark *placemark = dynamic_cast<GeoDataPlacemark*>( *it ); if ( placemark ) { // For short query strings only match exactly, to get a sane number of matches if (query.length() < minContainsMatchLength) { if ( placemark->name().toLower() != queryLower && ( placemark->descriptionIsCDATA() || // TODO: support also with CDATA placemark->description().toLower() != queryLower ) ) { continue; } } else { if ( ! placemark->name().toLower().contains(queryLower) && ( placemark->descriptionIsCDATA() || // TODO: support also with CDATA ! placemark->description().toLower().contains(queryLower) ) ) { continue; } } const GeoDataCoordinates coordinates = placemark->coordinate(); const qreal lon = coordinates.longitude(GeoDataCoordinates::Degree); const qreal lat = coordinates.latitude(GeoDataCoordinates::Degree); const QVariant coordinatesData = QVariantList() << QVariant(lon) << QVariant(lat) << QVariant(placemark->lookAt()->range()*METER2KM); Plasma::QueryMatch match(this); match.setIcon(KIcon(QLatin1String("marble"))); match.setText(placemark->name()); match.setSubtext(i18n("Show in OpenStreetMap with Marble")); match.setData(coordinatesData); match.setId(placemark->name()+QString::number(lat)+QString::number(lon)); match.setRelevance(1.0); match.setType(Plasma::QueryMatch::ExactMatch); matches << match; } } } void PlasmaRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match) { Q_UNUSED(context) const QVariantList data = match.data().toList(); const QString latLon = QString::fromUtf8("%L1").arg(data.at(1).toReal()) + QString::fromUtf8(" %L1").arg(data.at(0).toReal()); const QString distance = data.at(2).toString(); const QStringList parameters = QStringList() << QLatin1String( "--latlon" ) << latLon << QLatin1String( "--distance" ) << distance << QLatin1String( "--map" ) << QLatin1String( "earth/openstreetmap/openstreetmap.dgml" ); KProcess::startDetached( QLatin1String("marble"), parameters ); } } <commit_msg>Fixes: PlasmaRunner needs to load the "marble" and "marble_qt" catalogs<commit_after>// Copyright 2011 Friedrich W. H. Kossebau <kossebau@kde.org> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program. If not, see <http://www.gnu.org/licenses/>. #include "plasmarunner.h" // Marble #include <GeoDataCoordinates.h> #include <GeoDataFolder.h> #include <GeoDataPlacemark.h> #include <BookmarkManager.h> #include <GeoDataTreeModel.h> // KDE #include <KProcess> #include <KIcon> #include <KLocale> #include <KGlobal> namespace Marble { static const int minContainsMatchLength = 3; PlasmaRunner::PlasmaRunner(QObject *parent, const QVariantList &args) : AbstractRunner(parent, args) { KLocale* locale = KGlobal::locale(); locale->insertCatalog(QLatin1String("marble")); locale->insertCatalog(QLatin1String("marble_qt")); setIgnoredTypes(Plasma::RunnerContext::NetworkLocation | Plasma::RunnerContext::FileSystem | Plasma::RunnerContext::Help); QList<Plasma::RunnerSyntax> syntaxes; syntaxes << Plasma::RunnerSyntax(QLatin1String(":q:"), i18n("Shows the coordinates :q: in OpenStreetMap with Marble.")); syntaxes << Plasma::RunnerSyntax(QLatin1String(":q:"), i18n("Shows the geo bookmark containing :q: in OpenStreetMap with Marble.")); setSyntaxes(syntaxes); } void PlasmaRunner::match(Plasma::RunnerContext &context) { QList<Plasma::QueryMatch> matches; const QString query = context.query(); bool success = false; // TODO: how to estimate that input is in Degree, not Radian? GeoDataCoordinates coordinates = GeoDataCoordinates::fromString(query, success); if (success) { const QVariant coordinatesData = QVariantList() << QVariant(coordinates.longitude(GeoDataCoordinates::Degree)) << QVariant(coordinates.latitude(GeoDataCoordinates::Degree)) << QVariant(0.1); // TODO: make this distance value configurable Plasma::QueryMatch match(this); match.setIcon(KIcon(QLatin1String("marble"))); match.setText(i18n("Show the coordinates %1 in OpenStreetMap with Marble", query)); match.setData(coordinatesData); match.setId(query); match.setRelevance(1.0); match.setType(Plasma::QueryMatch::ExactMatch); matches << match; } // TODO: BookmarkManager does not yet listen to updates, also does not sync between processes :( // So for now always load on demand, even if expensive possibly BookmarkManager bookmarkManager(new GeoDataTreeModel); bookmarkManager.loadFile( QLatin1String("bookmarks/bookmarks.kml") ); foreach (GeoDataFolder* folder, bookmarkManager.folders()) { collectMatches(matches, query, folder); } if ( ! matches.isEmpty() ) { context.addMatches(query, matches); } } void PlasmaRunner::collectMatches(QList<Plasma::QueryMatch> &matches, const QString &query, const GeoDataFolder *folder) { const QString queryLower = query.toLower(); QVector<GeoDataFeature*>::const_iterator it = folder->constBegin(); QVector<GeoDataFeature*>::const_iterator end = folder->constEnd(); for (; it != end; ++it) { GeoDataFolder *folder = dynamic_cast<GeoDataFolder*>(*it); if ( folder ) { collectMatches(matches, query, folder); continue; } GeoDataPlacemark *placemark = dynamic_cast<GeoDataPlacemark*>( *it ); if ( placemark ) { // For short query strings only match exactly, to get a sane number of matches if (query.length() < minContainsMatchLength) { if ( placemark->name().toLower() != queryLower && ( placemark->descriptionIsCDATA() || // TODO: support also with CDATA placemark->description().toLower() != queryLower ) ) { continue; } } else { if ( ! placemark->name().toLower().contains(queryLower) && ( placemark->descriptionIsCDATA() || // TODO: support also with CDATA ! placemark->description().toLower().contains(queryLower) ) ) { continue; } } const GeoDataCoordinates coordinates = placemark->coordinate(); const qreal lon = coordinates.longitude(GeoDataCoordinates::Degree); const qreal lat = coordinates.latitude(GeoDataCoordinates::Degree); const QVariant coordinatesData = QVariantList() << QVariant(lon) << QVariant(lat) << QVariant(placemark->lookAt()->range()*METER2KM); Plasma::QueryMatch match(this); match.setIcon(KIcon(QLatin1String("marble"))); match.setText(placemark->name()); match.setSubtext(i18n("Show in OpenStreetMap with Marble")); match.setData(coordinatesData); match.setId(placemark->name()+QString::number(lat)+QString::number(lon)); match.setRelevance(1.0); match.setType(Plasma::QueryMatch::ExactMatch); matches << match; } } } void PlasmaRunner::run(const Plasma::RunnerContext &context, const Plasma::QueryMatch &match) { Q_UNUSED(context) const QVariantList data = match.data().toList(); const QString latLon = QString::fromUtf8("%L1").arg(data.at(1).toReal()) + QString::fromUtf8(" %L1").arg(data.at(0).toReal()); const QString distance = data.at(2).toString(); const QStringList parameters = QStringList() << QLatin1String( "--latlon" ) << latLon << QLatin1String( "--distance" ) << distance << QLatin1String( "--map" ) << QLatin1String( "earth/openstreetmap/openstreetmap.dgml" ); KProcess::startDetached( QLatin1String("marble"), parameters ); } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Syscoin Signed Message:\n"; <commit_msg>back to btc signed message prefix for compatibility<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util/validation.h> #include <consensus/validation.h> #include <tinyformat.h> /** Convert ValidationState to a human-readable message for logging */ std::string FormatStateMessage(const ValidationState &state) { return strprintf("%s%s", state.GetRejectReason(), state.GetDebugMessage().empty() ? "" : ", "+state.GetDebugMessage()); } const std::string strMessageMagic = "Bitcoin Signed Message:\n"; <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /////////////////////////////////////////////////////////////////////////////// // Get the ip address and port number of a schedd from the collector. /////////////////////////////////////////////////////////////////////////////// #include "condor_common.h" #include "condor_config.h" #include "condor_string.h" #include "daemon.h" #include "get_full_hostname.h" #include "my_hostname.h" #include "daemon_types.h" extern "C" { // Return the host portion of a daemon name string. Either the name // includes an "@" sign, in which case we return whatever is after it, // or it doesn't, in which case we just return what we got passed. const char* get_host_part( const char* name ) { char* tmp; if (name == NULL) return NULL; tmp = strchr( name, '@' ); if( tmp ) { return ++tmp; } else { return name; } } // Return a pointer to a newly allocated string that contains the // valid daemon name that corresponds with the given name. Basically, // see if there's an '@'. If so, resolve everything after it as a // hostname. If not, resolve what we were passed as a hostname. // The string is allocated with strnewp() (or it's equivalent), so you // should deallocate it with delete []. char* get_daemon_name( const char* name ) { char *tmp, *fullname, *tmpname, *daemon_name = NULL; int size; // First, check for a '@' in the name. tmpname = strdup( name ); tmp = strchr( tmpname, '@' ); if( tmp ) { // There's a '@'. *tmp = '\0'; tmp++; if( *tmp ) { // There was something after the @, try to resolve it // as a full hostname: fullname = get_full_hostname( tmp ); } else { // There was nothing after the @, use localhost: fullname = strnewp( my_full_hostname() ); } if( fullname ) { size = strlen(tmpname) + strlen(fullname) + 2; daemon_name = new char[size]; sprintf( daemon_name, "%s@%s", tmpname, fullname ); delete [] fullname; } } else { // There's no '@', just try to resolve the hostname. daemon_name = get_full_hostname( tmpname ); } free( tmpname ); // If there was an error, this will still be NULL. return daemon_name; } // Given some name, create a valid name for ourself with our full // hostname. If the name contains an '@', strip off everything after // it and append my_full_hostname(). If there's no '@', try to // resolve what we have and see if it's my_full_hostname. If so, use // it, otherwise, use name@my_full_hostname(). We return the answer // in a string which should be deallocated w/ delete []. char* build_valid_daemon_name( char* name ) { char *tmp, *tmpname, *daemon_name = NULL; int size; // This flag determines if we want to just return a copy of // my_full_hostname(), or if we want to append // "@my_full_hostname" to the name we were given. The name we // were given might include an '@', in which case, we trim off // everything after the '@'. bool just_host = false; if( name && *name ) { tmpname = strnewp( name ); tmp = strchr( tmpname, '@' ); if( tmp ) { // name we were passed has an '@', ignore everything // after (and including) the '@'. *tmp = '\0'; } else { // no '@', see if what we have is our hostname if( (tmp = get_full_hostname(name)) ) { if( !strcmp(tmp, my_full_hostname()) ) { // Yup, so just the full hostname. just_host = true; } delete [] tmp; } } } else { // Passed NULL for the name. just_host = true; } if( just_host ) { daemon_name = strnewp( my_full_hostname() ); } else { size = strlen(tmpname) + strlen(my_full_hostname()) + 2; daemon_name = new char[size]; sprintf( daemon_name, "%s@%s", tmpname, my_full_hostname() ); delete [] tmpname; } return daemon_name; } char* get_schedd_addr(const char* name, const char* pool) { static char addr[100]; Daemon d( DT_SCHEDD, name, pool ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_startd_addr(const char* name, const char* pool) { static char addr[100]; Daemon d( DT_STARTD, name, pool ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_master_addr(const char* name, const char* pool) { static char addr[100]; Daemon d( DT_MASTER, name, pool ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_negotiator_addr(const char* name) { static char addr[100]; Daemon d( DT_COLLECTOR, name ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_collector_addr(const char* name) { static char addr[100]; Daemon d( DT_COLLECTOR, name ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_daemon_addr( daemon_t dt, const char* name, const char* pool ) { switch( dt ) { case DT_MASTER: return get_master_addr( name, pool ); case DT_STARTD: return get_startd_addr( name, pool ); case DT_SCHEDD: return get_schedd_addr( name, pool ); case DT_NEGOTIATOR: return get_negotiator_addr( name ); case DT_COLLECTOR: return get_collector_addr( name ); default: return NULL; } return NULL; } int is_valid_sinful( const char *sinful ) { char* tmp; if( !sinful ) return FALSE; if( !(sinful[0] == '<') ) return FALSE; if( !(tmp = strchr(sinful, ':')) ) return FALSE; if( !(tmp = strrchr(sinful, '>')) ) return FALSE; return TRUE; } } /* extern "C" */ <commit_msg>In get_negotiator_addr(), we need to instantiate a Daemon object of type DT_NEGOTIATOR, not DT_COLLECTOR! Whoops. This was preventing the -negotiator option to The Tool to really talk to the collector.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /////////////////////////////////////////////////////////////////////////////// // Get the ip address and port number of a schedd from the collector. /////////////////////////////////////////////////////////////////////////////// #include "condor_common.h" #include "condor_config.h" #include "condor_string.h" #include "daemon.h" #include "get_full_hostname.h" #include "my_hostname.h" #include "daemon_types.h" extern "C" { // Return the host portion of a daemon name string. Either the name // includes an "@" sign, in which case we return whatever is after it, // or it doesn't, in which case we just return what we got passed. const char* get_host_part( const char* name ) { char* tmp; if (name == NULL) return NULL; tmp = strchr( name, '@' ); if( tmp ) { return ++tmp; } else { return name; } } // Return a pointer to a newly allocated string that contains the // valid daemon name that corresponds with the given name. Basically, // see if there's an '@'. If so, resolve everything after it as a // hostname. If not, resolve what we were passed as a hostname. // The string is allocated with strnewp() (or it's equivalent), so you // should deallocate it with delete []. char* get_daemon_name( const char* name ) { char *tmp, *fullname, *tmpname, *daemon_name = NULL; int size; // First, check for a '@' in the name. tmpname = strdup( name ); tmp = strchr( tmpname, '@' ); if( tmp ) { // There's a '@'. *tmp = '\0'; tmp++; if( *tmp ) { // There was something after the @, try to resolve it // as a full hostname: fullname = get_full_hostname( tmp ); } else { // There was nothing after the @, use localhost: fullname = strnewp( my_full_hostname() ); } if( fullname ) { size = strlen(tmpname) + strlen(fullname) + 2; daemon_name = new char[size]; sprintf( daemon_name, "%s@%s", tmpname, fullname ); delete [] fullname; } } else { // There's no '@', just try to resolve the hostname. daemon_name = get_full_hostname( tmpname ); } free( tmpname ); // If there was an error, this will still be NULL. return daemon_name; } // Given some name, create a valid name for ourself with our full // hostname. If the name contains an '@', strip off everything after // it and append my_full_hostname(). If there's no '@', try to // resolve what we have and see if it's my_full_hostname. If so, use // it, otherwise, use name@my_full_hostname(). We return the answer // in a string which should be deallocated w/ delete []. char* build_valid_daemon_name( char* name ) { char *tmp, *tmpname, *daemon_name = NULL; int size; // This flag determines if we want to just return a copy of // my_full_hostname(), or if we want to append // "@my_full_hostname" to the name we were given. The name we // were given might include an '@', in which case, we trim off // everything after the '@'. bool just_host = false; if( name && *name ) { tmpname = strnewp( name ); tmp = strchr( tmpname, '@' ); if( tmp ) { // name we were passed has an '@', ignore everything // after (and including) the '@'. *tmp = '\0'; } else { // no '@', see if what we have is our hostname if( (tmp = get_full_hostname(name)) ) { if( !strcmp(tmp, my_full_hostname()) ) { // Yup, so just the full hostname. just_host = true; } delete [] tmp; } } } else { // Passed NULL for the name. just_host = true; } if( just_host ) { daemon_name = strnewp( my_full_hostname() ); } else { size = strlen(tmpname) + strlen(my_full_hostname()) + 2; daemon_name = new char[size]; sprintf( daemon_name, "%s@%s", tmpname, my_full_hostname() ); delete [] tmpname; } return daemon_name; } char* get_schedd_addr(const char* name, const char* pool) { static char addr[100]; Daemon d( DT_SCHEDD, name, pool ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_startd_addr(const char* name, const char* pool) { static char addr[100]; Daemon d( DT_STARTD, name, pool ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_master_addr(const char* name, const char* pool) { static char addr[100]; Daemon d( DT_MASTER, name, pool ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_negotiator_addr(const char* name) { static char addr[100]; Daemon d( DT_NEGOTIATOR, name ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_collector_addr(const char* name) { static char addr[100]; Daemon d( DT_COLLECTOR, name ); if( d.locate() ) { strncpy( addr, d.addr(), 100 ); return addr; } else { return NULL; } } char* get_daemon_addr( daemon_t dt, const char* name, const char* pool ) { switch( dt ) { case DT_MASTER: return get_master_addr( name, pool ); case DT_STARTD: return get_startd_addr( name, pool ); case DT_SCHEDD: return get_schedd_addr( name, pool ); case DT_NEGOTIATOR: return get_negotiator_addr( name ); case DT_COLLECTOR: return get_collector_addr( name ); default: return NULL; } return NULL; } int is_valid_sinful( const char *sinful ) { char* tmp; if( !sinful ) return FALSE; if( !(sinful[0] == '<') ) return FALSE; if( !(tmp = strchr(sinful, ':')) ) return FALSE; if( !(tmp = strrchr(sinful, '>')) ) return FALSE; return TRUE; } } /* extern "C" */ <|endoftext|>
<commit_before>/* ** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the Condor Design Team not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the Condor ** Design Team make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Authors: Cai, Weiru ** University of Wisconsin, Computer Sciences Dept. ** Modified by Jim Basney: added startd functionality ** */ /////////////////////////////////////////////////////////////////////////////// // Get the ip address and port number of a schedd from the collector. /////////////////////////////////////////////////////////////////////////////// #include "condor_common.h" #include "condor_query.h" extern "C" { char* get_daemon_addr(const char* name, AdTypes adtype, const char* attribute) { CondorQuery query(adtype); ClassAd* scan; char* daemonAddr = (char*)malloc(sizeof(char)*100); char constraint[500]; ClassAdList ads; sprintf(constraint, "%s == \"%s\"", ATTR_NAME, name); query.addConstraint(constraint); query.fetchAds(ads); ads.Open(); scan = ads.Next(); if(!scan) { delete daemonAddr; return NULL; } if(scan->EvalString(attribute, NULL, daemonAddr) == FALSE) { delete daemonAddr; return NULL; } return daemonAddr; } char* get_schedd_addr(const char* name) { return get_daemon_addr(name, SCHEDD_AD, ATTR_SCHEDD_IP_ADDR); } char* get_startd_addr(const char* name) { return get_daemon_addr(name, STARTD_AD, ATTR_STARTD_IP_ADDR); } char* get_master_addr(const char* name) { return get_daemon_addr(name, MASTER_AD, ATTR_MASTER_IP_ADDR); } } <commit_msg>We now run the name we're passed through get_full_hostname() to resolve the hostname before we query the collector for the daemon's sinful string.<commit_after>/* ** Copyright 1986, 1987, 1988, 1989, 1990, 1991 by the Condor Design Team ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, ** provided that the above copyright notice appear in all copies and that ** both that copyright notice and this permission notice appear in ** supporting documentation, and that the names of the University of ** Wisconsin and the Condor Design Team not be used in advertising or ** publicity pertaining to distribution of the software without specific, ** written prior permission. The University of Wisconsin and the Condor ** Design Team make no representations about the suitability of this ** software for any purpose. It is provided "as is" without express ** or implied warranty. ** ** THE UNIVERSITY OF WISCONSIN AND THE CONDOR DESIGN TEAM DISCLAIM ALL ** WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE UNIVERSITY OF ** WISCONSIN OR THE CONDOR DESIGN TEAM BE LIABLE FOR ANY SPECIAL, INDIRECT ** OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS ** OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE ** OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE ** OR PERFORMANCE OF THIS SOFTWARE. ** ** Authors: Cai, Weiru ** University of Wisconsin, Computer Sciences Dept. ** Modified by Jim Basney: added startd functionality ** */ /////////////////////////////////////////////////////////////////////////////// // Get the ip address and port number of a schedd from the collector. /////////////////////////////////////////////////////////////////////////////// #include "condor_common.h" #include "condor_query.h" #include "get_full_hostname.h" extern "C" { char* get_daemon_addr(const char* name, AdTypes adtype, const char* attribute) { CondorQuery query(adtype); ClassAd* scan; char* daemonAddr = (char*)malloc(sizeof(char)*100); char constraint[500]; ClassAdList ads; char* fullname; // Make sure we've got a fully qualified name. fullname = get_full_hostname( name ); if( !fullname ) { return NULL; } sprintf(constraint, "%s == \"%s\"", ATTR_NAME, fullname); query.addConstraint(constraint); query.fetchAds(ads); ads.Open(); scan = ads.Next(); if(!scan) { delete daemonAddr; return NULL; } if(scan->EvalString(attribute, NULL, daemonAddr) == FALSE) { delete daemonAddr; return NULL; } return daemonAddr; } char* get_schedd_addr(const char* name) { return get_daemon_addr(name, SCHEDD_AD, ATTR_SCHEDD_IP_ADDR); } char* get_startd_addr(const char* name) { return get_daemon_addr(name, STARTD_AD, ATTR_STARTD_IP_ADDR); } char* get_master_addr(const char* name) { return get_daemon_addr(name, MASTER_AD, ATTR_MASTER_IP_ADDR); } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetView.h" #include "otbWrapperQtWidgetParameterGroup.h" #include "otbWrapperQtWidgetParameterFactory.h" #include "otbWrapperQtWidgetProgressReport.h" #include "otbWrapperOutputImageParameter.h" #include "otbWrapperQtWidgetSimpleProgressReport.h" #include "itksys/SystemTools.hxx" namespace otb { namespace Wrapper { QtWidgetView::QtWidgetView(Application* app) { m_Model = new QtWidgetModel(app); m_Application = app; } QtWidgetView::~QtWidgetView() { } void QtWidgetView::CreateGui() { // Create a VBoxLayout with the header, the input widgets, and the footer QVBoxLayout *mainLayout = new QVBoxLayout(); QTabWidget *tab = new QTabWidget(); tab->addTab(CreateInputWidgets(), "Parameters"); QTextEdit *log = new QTextEdit(); connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) ); tab->addTab(log, "Logs"); QtWidgetProgressReport* prog = new QtWidgetProgressReport(m_Model); prog->SetApplication(m_Application); tab->addTab(prog, "Progress Reporting ..."); tab->addTab(CreateDoc(), "Documentation"); mainLayout->addWidget(tab); QtWidgetSimpleProgressReport * progressReport = new QtWidgetSimpleProgressReport(m_Model); progressReport->SetApplication(m_Application); QHBoxLayout *footLayout = new QHBoxLayout; footLayout->addWidget(progressReport); footLayout->addWidget(CreateFooter()); mainLayout->addLayout(footLayout); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(mainLayout); // Put the main group inside a scroll area QScrollArea *scrollArea = new QScrollArea; scrollArea->setWidget(mainGroup); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setWidgetResizable(true); QVBoxLayout *scrollLayout = new QVBoxLayout(); scrollLayout->addWidget(scrollArea); // Make the scroll layout the main layout this->setLayout(scrollLayout); } QWidget* QtWidgetView::CreateInputWidgets() { QtWidgetParameterBase* params = QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model); return params; } QWidget* QtWidgetView::CreateFooter() { // an HLayout with two buttons : Execute and Quit QGroupBox *footerGroup = new QGroupBox; QHBoxLayout *footerLayout = new QHBoxLayout; footerGroup->setFixedHeight(40); footerGroup->setContentsMargins(0, 0, 0, 0); footerLayout->setContentsMargins(5, 5, 5, 5); m_ExecButton = new QPushButton(footerGroup); m_ExecButton->setDefault(true); m_ExecButton->setEnabled(false); m_ExecButton->setText(QObject::tr("Execute")); connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) ); connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) ); m_QuitButton = new QPushButton(footerGroup); m_QuitButton->setText(QObject::tr("Quit")); connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) ); // Put the buttons on the right footerLayout->addStretch(); footerLayout->addWidget(m_ExecButton); footerLayout->addWidget(m_QuitButton); footerGroup->setLayout(footerLayout); return footerGroup; } QWidget* QtWidgetView::CreateDoc() { QTextEdit *text = new QTextEdit; text->setReadOnly(true); QTextDocument * doc = new QTextDocument(); itk::OStringStream oss; oss << "<center><h2>"<<m_Application->GetDocName()<<"</center></h2>"; oss << "<h3>Brief Description</h3>"; oss << "<body>"<<m_Application->GetDescription()<<"</body>"; oss << "<h3>Tags</h3>"; oss << "<body>"; for(unsigned int i=0; i<m_Application->GetDocTags().size(); i++) { oss << m_Application->GetDocTags()[i]<<" "; ; } oss <<"</body>"; oss << "<h3>Long Description</h3>"; oss << "<body>"<<m_Application->GetDocLongDescription()<<"</body>"; std::string val; this->SetDocParameters(val); oss<<val; oss << "<h3>Limitations</h3>"; oss << "<body>"<<m_Application->GetDocLimitations()<<"</body>"; oss << "<h3>Authors</h3>"; oss << "<body>"<<m_Application->GetDocAuthors()<<"</body>"; oss << "<h3>See also</h3>"; oss << "<body>"<<m_Application->GetDocSeeAlso()<<"</body>"; oss << "<h3>Command line example</h3>"; oss << "<code>"<<m_Application->GetDocCLExample()<<"</code>"; doc->setHtml( oss.str().c_str()); text->setDocument( doc ); return text; } void QtWidgetView::SetDocParameters( std::string & val ) { const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( true ); const unsigned int nbOfParam = appKeyList.size(); itk::OStringStream oss; oss << "<h3>Parameters</h3>"; // Mandatory parameters oss << "<h4>Mandatory parameters</h4>"; oss << "<li>"; for( unsigned int i=0; i<nbOfParam; i++ ) { Parameter::Pointer param = m_Application->GetParameterByKey( appKeyList[i] ); // Check if mandatory parameter are present and have value if( param->GetMandatory() == true ) { oss << "<body><i>"<< param->GetName() << "</i>: "<<param->GetDescription()<<"</body>"; } } oss << "</body></li>"; // Optionnal parameters oss << "<h4>Optionnal parameters</h4>"; oss << "<body><li>"; bool found = false; for( unsigned int i=0; i<nbOfParam; i++ ) { Parameter::Pointer param = m_Application->GetParameterByKey( appKeyList[i] ); // Check if mandatory parameter are present and have value if( param->GetMandatory() == false ) { oss << "<body><i>" <<param->GetName() << "</i>: "<<param->GetDescription()<<"</body>"; found = true; } } if( !found ) oss << "None"; oss << "</li>"; val = oss.str(); } void QtWidgetView::CloseSlot() { // Close the widget this->close(); // Emit a signal to close any widget that this gui belonging to emit QuitSignal(); } } } <commit_msg>STYLE : add space in parameter description.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetView.h" #include "otbWrapperQtWidgetParameterGroup.h" #include "otbWrapperQtWidgetParameterFactory.h" #include "otbWrapperQtWidgetProgressReport.h" #include "otbWrapperOutputImageParameter.h" #include "otbWrapperQtWidgetSimpleProgressReport.h" #include "itksys/SystemTools.hxx" namespace otb { namespace Wrapper { QtWidgetView::QtWidgetView(Application* app) { m_Model = new QtWidgetModel(app); m_Application = app; } QtWidgetView::~QtWidgetView() { } void QtWidgetView::CreateGui() { // Create a VBoxLayout with the header, the input widgets, and the footer QVBoxLayout *mainLayout = new QVBoxLayout(); QTabWidget *tab = new QTabWidget(); tab->addTab(CreateInputWidgets(), "Parameters"); QTextEdit *log = new QTextEdit(); connect( m_Model->GetLogOutput(), SIGNAL(NewContentLog(QString)), log, SLOT(append(QString) ) ); tab->addTab(log, "Logs"); QtWidgetProgressReport* prog = new QtWidgetProgressReport(m_Model); prog->SetApplication(m_Application); tab->addTab(prog, "Progress Reporting ..."); tab->addTab(CreateDoc(), "Documentation"); mainLayout->addWidget(tab); QtWidgetSimpleProgressReport * progressReport = new QtWidgetSimpleProgressReport(m_Model); progressReport->SetApplication(m_Application); QHBoxLayout *footLayout = new QHBoxLayout; footLayout->addWidget(progressReport); footLayout->addWidget(CreateFooter()); mainLayout->addLayout(footLayout); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(mainLayout); // Put the main group inside a scroll area QScrollArea *scrollArea = new QScrollArea; scrollArea->setWidget(mainGroup); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setWidgetResizable(true); QVBoxLayout *scrollLayout = new QVBoxLayout(); scrollLayout->addWidget(scrollArea); // Make the scroll layout the main layout this->setLayout(scrollLayout); } QWidget* QtWidgetView::CreateInputWidgets() { QtWidgetParameterBase* params = QtWidgetParameterFactory::CreateQtWidget(m_Model->GetApplication()->GetParameterList(), m_Model); return params; } QWidget* QtWidgetView::CreateFooter() { // an HLayout with two buttons : Execute and Quit QGroupBox *footerGroup = new QGroupBox; QHBoxLayout *footerLayout = new QHBoxLayout; footerGroup->setFixedHeight(40); footerGroup->setContentsMargins(0, 0, 0, 0); footerLayout->setContentsMargins(5, 5, 5, 5); m_ExecButton = new QPushButton(footerGroup); m_ExecButton->setDefault(true); m_ExecButton->setEnabled(false); m_ExecButton->setText(QObject::tr("Execute")); connect( m_ExecButton, SIGNAL(clicked()), m_Model, SLOT(ExecuteAndWriteOutputSlot() ) ); connect( m_Model, SIGNAL(SetApplicationReady(bool)), m_ExecButton, SLOT(setEnabled(bool)) ); m_QuitButton = new QPushButton(footerGroup); m_QuitButton->setText(QObject::tr("Quit")); connect( m_QuitButton, SIGNAL(clicked()), this, SLOT(CloseSlot()) ); // Put the buttons on the right footerLayout->addStretch(); footerLayout->addWidget(m_ExecButton); footerLayout->addWidget(m_QuitButton); footerGroup->setLayout(footerLayout); return footerGroup; } QWidget* QtWidgetView::CreateDoc() { QTextEdit *text = new QTextEdit; text->setReadOnly(true); QTextDocument * doc = new QTextDocument(); itk::OStringStream oss; oss << "<center><h2>"<<m_Application->GetDocName()<<"</center></h2>"; oss << "<h3>Brief Description</h3>"; oss << "<body>"<<m_Application->GetDescription()<<"</body>"; oss << "<h3>Tags</h3>"; oss << "<body>"; for(unsigned int i=0; i<m_Application->GetDocTags().size(); i++) { oss << m_Application->GetDocTags()[i]<<" "; ; } oss <<"</body>"; oss << "<h3>Long Description</h3>"; oss << "<body>"<<m_Application->GetDocLongDescription()<<"</body>"; std::string val; this->SetDocParameters(val); oss<<val; oss << "<h3>Limitations</h3>"; oss << "<body>"<<m_Application->GetDocLimitations()<<"</body>"; oss << "<h3>Authors</h3>"; oss << "<body>"<<m_Application->GetDocAuthors()<<"</body>"; oss << "<h3>See also</h3>"; oss << "<body>"<<m_Application->GetDocSeeAlso()<<"</body>"; oss << "<h3>Command line example</h3>"; oss << "<code>"<<m_Application->GetDocCLExample()<<"</code>"; doc->setHtml( oss.str().c_str()); text->setDocument( doc ); return text; } void QtWidgetView::SetDocParameters( std::string & val ) { const std::vector<std::string> appKeyList = m_Application->GetParametersKeys( true ); const unsigned int nbOfParam = appKeyList.size(); itk::OStringStream oss; oss << "<h3>Parameters</h3>"; // Mandatory parameters oss << "<h4>Mandatory parameters</h4>"; oss << "<li>"; for( unsigned int i=0; i<nbOfParam; i++ ) { Parameter::Pointer param = m_Application->GetParameterByKey( appKeyList[i] ); // Check if mandatory parameter are present and have value if( param->GetMandatory() == true ) { oss << "<body><i>"<< param->GetName() << "</i> : "<<param->GetDescription()<<"</body>"; } } oss << "</body></li>"; // Optionnal parameters oss << "<h4>Optionnal parameters</h4>"; oss << "<body><li>"; bool found = false; for( unsigned int i=0; i<nbOfParam; i++ ) { Parameter::Pointer param = m_Application->GetParameterByKey( appKeyList[i] ); // Check if mandatory parameter are present and have value if( param->GetMandatory() == false ) { oss << "<body><i>" <<param->GetName() << "</i> : "<<param->GetDescription()<<"</body>"; found = true; } } if( !found ) oss << "None"; oss << "</li>"; val = oss.str(); } void QtWidgetView::CloseSlot() { // Close the widget this->close(); // Emit a signal to close any widget that this gui belonging to emit QuitSignal(); } } } <|endoftext|>
<commit_before>#include "RoleBase.h" #include "Creature.h" #include "interface.h" #include "Action.h" #include "Utils.h" #include "NavigationFinder.h" #include "Engine.h" #include "World.h" #include "Object.h" #include "Avatar.h" CRoleBase::CRoleBase(void) { m_pCreature = NULL; m_pActionComplete = NULL; m_nOrceDirection = 0; m_nMoveing = 0; m_fMoveSpeed = 6.0f; m_nMoveToType = 0; m_nUpdateMove = 1; } CRoleBase::~CRoleBase(void) { SAFE_DELETE(m_pActionComplete); SAFE_DELETE(m_pCreature); SAFE_DELETE(m_pPathFind); } //ʼɫ int CRoleBase::Init(int nRoleID, const char* strCharFile) { if (m_pCreature)return 1; m_nMoveing = 1; m_nRoleID = nRoleID; m_pCreature = new CCreature(); m_pActionComplete = MakeInterface(this, &CRoleBase::OnActionMsg); m_pCreature->SetActionComplete(m_pActionComplete); m_pCreature->Load(strCharFile); m_pCreature->SetupBody(1, 0); m_pCreature->SetPosition(vec3_zero); m_pCreature->SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pCreature->SetRoleID(nRoleID); m_AngleYaw.SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pPathFind = new CNavigationFinder(); m_pPathFind->SetMode(CNavigationFinder::MODE_PATHFIND_STRAIGHT); return 1; } void CRoleBase::Update(float ifps) { if (NULL == m_pCreature)return; if (m_nUpdateMove) { m_AngleYaw.Update(ifps); UpdateMove(ifps); m_pCreature->SetDirection(m_AngleYaw.GetForwardDirection(), m_nOrceDirection); } m_pCreature->Update(); } int CRoleBase::OnActionMsg(void* pVoid) { _ActionCallback* pInfo = (_ActionCallback*)pVoid; switch (pInfo->nMsgID) { case 0: { OnKeyFrame((_ActionCallback_KeyFrame*)pVoid); }break; case 1: { OnActionComplete((_ActionCallback_Complete*)pVoid); }break; } return 1; } //ؼ֡ص void CRoleBase::OnKeyFrame(_ActionCallback_KeyFrame* pKeyInfo) { }//ɻص void CRoleBase::OnActionComplete(_ActionCallback_Complete* pActInfo) { if (NULL == m_pCreature)return; if (m_nMoveing) { m_pCreature->PlayAction("run"); } else { m_pCreature->PlayAction("stand"); } } CAction* CRoleBase::PlayAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->PlayAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } CAction* CRoleBase::OrceAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->OrceAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } void CRoleBase::SetPosition(const vec3& vPosition, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; m_pCreature->SetPosition(vPosition, nOrce); } void CRoleBase::SetDirection(const vec3& vDirection, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; if (m_pCreature->GetNowAction()->GetLockMove() && !nOrce)return; m_nOrceDirection = nOrce; m_AngleYaw.SetDirection(vDirection); } void CRoleBase::SetDirectionTo(const vec3& vDirection, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; if (m_pCreature->GetNowAction()->GetLockMove() && !nOrce)return; m_nOrceDirection = nOrce; m_AngleYaw.SetDestDirection(vDirection); } int CRoleBase::MoveTo(const vec3& vPosition) { if (NULL == m_pCreature)return -1; if (m_pCreature->GetNowAction()->GetLockMove())return -1; m_vStartPathPosition = m_vNowPathPosition = m_pCreature->GetPosition(); m_nMoveing = 1; m_nMoveToType = 0; m_vDestPathPosition = vPosition; m_pCreature->PlayAction("run", 1); return 1; } int CRoleBase::MoveToPath(const vec3& vPosition) { if (NULL == m_pCreature)return -1; if (m_pCreature->GetNowAction()->GetLockMove())return -1; m_pPathFind->Create(m_pCreature->GetPosition(), vPosition, 0); if (m_pPathFind->GetReached() || m_pPathFind->GetNumPoints() >= 2) { m_nMoveing = 1; m_nMoveToType = 1; m_nNowPathPoint = 0; m_vNowPathPosition = m_pCreature->GetPosition(); m_pCreature->PlayAction("run", 1); return 1; } return 0; } void CRoleBase::StopMove() { m_nMoveing = 0; m_pCreature->PlayAction("stand", 1); }<commit_msg>StopMove<commit_after>#include "RoleBase.h" #include "Creature.h" #include "interface.h" #include "Action.h" #include "Utils.h" #include "NavigationFinder.h" #include "Engine.h" #include "World.h" #include "Object.h" #include "Avatar.h" CRoleBase::CRoleBase(void) { m_pCreature = NULL; m_pActionComplete = NULL; m_nOrceDirection = 0; m_nMoveing = 0; m_fMoveSpeed = 6.0f; m_nMoveToType = 0; m_nUpdateMove = 1; } CRoleBase::~CRoleBase(void) { SAFE_DELETE(m_pActionComplete); SAFE_DELETE(m_pCreature); SAFE_DELETE(m_pPathFind); } //ʼɫ int CRoleBase::Init(int nRoleID, const char* strCharFile) { if (m_pCreature)return 1; m_nMoveing = 1; m_nRoleID = nRoleID; m_pCreature = new CCreature(); m_pActionComplete = MakeInterface(this, &CRoleBase::OnActionMsg); m_pCreature->SetActionComplete(m_pActionComplete); m_pCreature->Load(strCharFile); m_pCreature->SetupBody(1, 0); m_pCreature->SetPosition(vec3_zero); m_pCreature->SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pCreature->SetRoleID(nRoleID); m_AngleYaw.SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pPathFind = new CNavigationFinder(); m_pPathFind->SetMode(CNavigationFinder::MODE_PATHFIND_STRAIGHT); return 1; } void CRoleBase::Update(float ifps) { if (NULL == m_pCreature)return; if (m_nUpdateMove) { m_AngleYaw.Update(ifps); UpdateMove(ifps); m_pCreature->SetDirection(m_AngleYaw.GetForwardDirection(), m_nOrceDirection); } m_pCreature->Update(); } int CRoleBase::OnActionMsg(void* pVoid) { _ActionCallback* pInfo = (_ActionCallback*)pVoid; switch (pInfo->nMsgID) { case 0: { OnKeyFrame((_ActionCallback_KeyFrame*)pVoid); }break; case 1: { OnActionComplete((_ActionCallback_Complete*)pVoid); }break; } return 1; } //ؼ֡ص void CRoleBase::OnKeyFrame(_ActionCallback_KeyFrame* pKeyInfo) { }//ɻص void CRoleBase::OnActionComplete(_ActionCallback_Complete* pActInfo) { if (NULL == m_pCreature)return; if (m_nMoveing) { m_pCreature->PlayAction("run"); } else { m_pCreature->PlayAction("stand"); } } CAction* CRoleBase::PlayAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->PlayAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } CAction* CRoleBase::OrceAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->OrceAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } void CRoleBase::SetPosition(const vec3& vPosition, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; m_pCreature->SetPosition(vPosition, nOrce); } void CRoleBase::SetDirection(const vec3& vDirection, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; if (m_pCreature->GetNowAction()->GetLockMove() && !nOrce)return; m_nOrceDirection = nOrce; m_AngleYaw.SetDirection(vDirection); } void CRoleBase::SetDirectionTo(const vec3& vDirection, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; if (m_pCreature->GetNowAction()->GetLockMove() && !nOrce)return; m_nOrceDirection = nOrce; m_AngleYaw.SetDestDirection(vDirection); } int CRoleBase::MoveTo(const vec3& vPosition) { if (NULL == m_pCreature)return -1; if (m_pCreature->GetNowAction()->GetLockMove())return -1; m_vStartPathPosition = m_vNowPathPosition = m_pCreature->GetPosition(); m_nMoveing = 1; m_nMoveToType = 0; m_vDestPathPosition = vPosition; m_pCreature->PlayAction("run", 1); return 1; } int CRoleBase::MoveToPath(const vec3& vPosition) { if (NULL == m_pCreature)return -1; if (m_pCreature->GetNowAction()->GetLockMove())return -1; m_pPathFind->Create(m_pCreature->GetPosition(), vPosition, 0); if (m_pPathFind->GetReached() || m_pPathFind->GetNumPoints() >= 2) { m_nMoveing = 1; m_nMoveToType = 1; m_nNowPathPoint = 0; m_vNowPathPosition = m_pCreature->GetPosition(); m_pCreature->PlayAction("run", 1); return 1; } return 0; } void CRoleBase::StopMove() { m_nMoveing = 0; m_pCreature->PlayAction("stand", 1); } void CRoleBase::StopMove(const vec3& vPosition) { m_nMoveing = 0; SetPosition(vPosition, 1); m_pCreature->PlayAction("stand", 1); }<|endoftext|>
<commit_before>#include "action.h" #include "algebra.h" #include <cmath> #include <iostream> #include <typeinfo> bool action::act(int frame_number) { if (frame_number < get_start_frame()) {return true;} if (current_frame == 0) {will_start();} remaining_action = false; if (own_act()) {remaining_action = true;} // size_t children_size = children.size(); for (int i = 0; i < children.size();/*no increment*/) { if (children[i]->act(current_frame)) { remaining_action = true; ++i; } else { // the child action is finished // call its did_finish function, if it has one auto child_did_finish = children[i]->did_finish; if (child_did_finish) {child_did_finish(shared_from_this(),children[i]);} children.erase(children.begin() + i); } } ++current_frame; return remaining_action; } /* // sequential_action bool sequential_action::act(int frame_number) { if (action::act(frame_number)) {return true;} else if (action_queue.empty()) {return false;} else { children.push_back(action_queue.front()); action_queue.pop(); return true; } } */ // move void move::update_children_frame_count_settings() { std::shared_ptr<move> move_child_ptr; for (auto child : children) { if ((move_child_ptr = std::dynamic_pointer_cast<move>(child))) { move_child_ptr->fixed_frame_count = this->fixed_frame_count; move_child_ptr->node_speed = this->node_speed; move_child_ptr->low_frame_limit = this->low_frame_limit; move_child_ptr->high_frame_limit = this->high_frame_limit; move_child_ptr->frame_count_method = this->frame_count_method; move_child_ptr->internal_update(); move_child_ptr->update_children_frame_count_settings(); } } } void shift::compute_f_count_and_increments() { if (frame_count_method == fixed) {f_count = fixed_frame_count;} else { int d_max = (std::abs(dx) > std::abs(dy)) ? dx : dy; if (d_max == 0) {f_count = 0;} else {f_count = std::abs(std::ceil((double) d_max / (double) node_speed));} if (frame_count_method == limit) { if (f_count < low_frame_limit) { f_count = low_frame_limit; } if (f_count > high_frame_limit) { f_count = high_frame_limit; } } } if (f_count == 0) { // debug std::cout << "f_count == 0" << std::endl; x_increment = 0; y_increment = 0; return; } /* Suppose we have 60 people and we want to divide them into 13 approximately equal-sized groups. Euclidean division suggests groups of size 4. But then there are 8 people leftover. Each person from the 8 remaining should be assigned to a group of 4, leaving 8 groups of 5 and 5 groups of 4. Generalizing: let there be n people we wish to divide into g groups, and let floor(n / g) == k, so that there are k people in each group before assigning the remaining r people to groups. We then assign an addition person to each of r groups. There are then r groups of k + 1 people and (g - r) groups of k people. No two groups then differ in size by more than 1 person. Mathematically, we write n = (k + 1) * r + k * (g - r) Here, we will divide dx or dy into f_count increments, no two of which differ by more than one coordinate in size. dx = (x_increment + 1) * x_r + (x_increment)(f_count - x_r); */ auto quo_rem = algebra::fdiv_qr(dx,f_count); x_increment = std::get<0>(quo_rem); x_r = std::get<1>(quo_rem); quo_rem = algebra::fdiv_qr(dy,f_count); y_increment = std::get<0>(quo_rem); y_r = std::get<1>(quo_rem); } shift::shift(std::shared_ptr<node> n_, int start_frame_, int dx_, int dy_, frame_count_method_type fcm) : move(n_, start_frame_, fcm), dx(dx_), dy(dy_) { compute_f_count_and_increments(); } bool shift::own_act() { bool remaining_action = true; if (current_frame < x_r) {n->shift(x_increment + 1,0);} else if (current_frame < f_count) {n->shift(x_increment,0);} else {remaining_action = false;} if (current_frame < y_r) {n->shift(0,y_increment + 1);} else if (current_frame < f_count) {n->shift(0,y_increment);} else {remaining_action = false;} // do not update current_frame here. it is updated in action::act() return remaining_action; } // space_children space_children::space_children(std::shared_ptr<node> n_, int start_frame_, int dx_, int dy_, frame_count_method_type fcm) : move(n_,start_frame_,fcm), dx(dx_), dy(dy_) { create_children(); } bool space_children::own_act() { return false; } void space_children::create_children() { children.clear(); std::shared_ptr<shift> child_shift; for (int i = 1; i < n->get_children().size(); ++i) { // debug std::cout << "adding child shift(...,...," << dx * i << "," << dy * i << ")" << std::endl; child_shift = std::make_shared<shift>(n->get_children()[i],0,dx * i, dy * i); child_shift->fixed_frame_count = this->fixed_frame_count; child_shift->node_speed = this->node_speed; child_shift->low_frame_limit = this->low_frame_limit; child_shift->high_frame_limit = this->high_frame_limit; child_shift->use_frame_count_method(frame_count_method); children.push_back(child_shift); } } // settle settle::settle(std::shared_ptr<node> n_, int start_frame_, dimension dim_, int target_coordinate_, frame_count_method_type fcm) : move(n_,start_frame_,fcm), dim(dim_), target_coordinate(target_coordinate_) { create_children(); } void settle::create_children() { for (auto child_node : n->get_children()) { std::shared_ptr<shift> child_shift; int delta; switch (dim) { case dimension::x: delta = target_coordinate - child_node->get_location().x; child_shift = std::make_shared<shift>(child_node,0,delta,0); break; case dimension::y: delta = target_coordinate - child_node->get_location().y; child_shift = std::make_shared<shift>(child_node,0,0,delta); break; } child_shift->use_frame_count_method(this->frame_count_method); children.push_back(child_shift); } } <commit_msg>shift::own_act() : fix extra frame bug<commit_after>#include "action.h" #include "algebra.h" #include <cmath> #include <iostream> #include <typeinfo> bool action::act(int frame_number) { if (frame_number < get_start_frame()) {return true;} if (current_frame == 0) {will_start();} remaining_action = false; if (own_act()) {remaining_action = true;} // size_t children_size = children.size(); for (int i = 0; i < children.size();/*no increment*/) { if (children[i]->act(current_frame)) { remaining_action = true; ++i; } else { // the child action is finished // call its did_finish function, if it has one auto child_did_finish = children[i]->did_finish; if (child_did_finish) {child_did_finish(shared_from_this(),children[i]);} children.erase(children.begin() + i); } } ++current_frame; return remaining_action; } /* // sequential_action bool sequential_action::act(int frame_number) { if (action::act(frame_number)) {return true;} else if (action_queue.empty()) {return false;} else { children.push_back(action_queue.front()); action_queue.pop(); return true; } } */ // move void move::update_children_frame_count_settings() { std::shared_ptr<move> move_child_ptr; for (auto child : children) { if ((move_child_ptr = std::dynamic_pointer_cast<move>(child))) { move_child_ptr->fixed_frame_count = this->fixed_frame_count; move_child_ptr->node_speed = this->node_speed; move_child_ptr->low_frame_limit = this->low_frame_limit; move_child_ptr->high_frame_limit = this->high_frame_limit; move_child_ptr->frame_count_method = this->frame_count_method; move_child_ptr->internal_update(); move_child_ptr->update_children_frame_count_settings(); } } } void shift::compute_f_count_and_increments() { if (frame_count_method == fixed) {f_count = fixed_frame_count;} else { int d_max = (std::abs(dx) > std::abs(dy)) ? dx : dy; if (d_max == 0) {f_count = 0;} else {f_count = std::abs(std::ceil((double) d_max / (double) node_speed));} if (frame_count_method == limit) { if (f_count < low_frame_limit) { f_count = low_frame_limit; } if (f_count > high_frame_limit) { f_count = high_frame_limit; } } } if (f_count == 0) { // debug std::cout << "f_count == 0" << std::endl; x_increment = 0; y_increment = 0; return; } /* Suppose we have 60 people and we want to divide them into 13 approximately equal-sized groups. Euclidean division suggests groups of size 4. But then there are 8 people leftover. Each person from the 8 remaining should be assigned to a group of 4, leaving 8 groups of 5 and 5 groups of 4. Generalizing: let there be n people we wish to divide into g groups, and let floor(n / g) == k, so that there are k people in each group before assigning the remaining r people to groups. We then assign an addition person to each of r groups. There are then r groups of k + 1 people and (g - r) groups of k people. No two groups then differ in size by more than 1 person. Mathematically, we write n = (k + 1) * r + k * (g - r) Here, we will divide dx or dy into f_count increments, no two of which differ by more than one coordinate in size. dx = (x_increment + 1) * x_r + (x_increment)(f_count - x_r); */ auto quo_rem = algebra::fdiv_qr(dx,f_count); x_increment = std::get<0>(quo_rem); x_r = std::get<1>(quo_rem); quo_rem = algebra::fdiv_qr(dy,f_count); y_increment = std::get<0>(quo_rem); y_r = std::get<1>(quo_rem); } shift::shift(std::shared_ptr<node> n_, int start_frame_, int dx_, int dy_, frame_count_method_type fcm) : move(n_, start_frame_, fcm), dx(dx_), dy(dy_) { compute_f_count_and_increments(); } bool shift::own_act() { bool remaining_action = true; if (current_frame < x_r) {n->shift(x_increment + 1,0);} else if (current_frame < f_count) {n->shift(x_increment,0);} if (current_frame < y_r) {n->shift(0,y_increment + 1);} else if (current_frame < f_count) {n->shift(0,y_increment);} if (current_frame >= f_count - 1) {remaining_action = false;} // do not update current_frame here. it is updated in action::act() return remaining_action; } // space_children space_children::space_children(std::shared_ptr<node> n_, int start_frame_, int dx_, int dy_, frame_count_method_type fcm) : move(n_,start_frame_,fcm), dx(dx_), dy(dy_) { create_children(); } bool space_children::own_act() { return false; } void space_children::create_children() { children.clear(); std::shared_ptr<shift> child_shift; for (int i = 1; i < n->get_children().size(); ++i) { // debug std::cout << "adding child shift(...,...," << dx * i << "," << dy * i << ")" << std::endl; child_shift = std::make_shared<shift>(n->get_children()[i],0,dx * i, dy * i); child_shift->fixed_frame_count = this->fixed_frame_count; child_shift->node_speed = this->node_speed; child_shift->low_frame_limit = this->low_frame_limit; child_shift->high_frame_limit = this->high_frame_limit; child_shift->use_frame_count_method(frame_count_method); children.push_back(child_shift); } } // settle settle::settle(std::shared_ptr<node> n_, int start_frame_, dimension dim_, int target_coordinate_, frame_count_method_type fcm) : move(n_,start_frame_,fcm), dim(dim_), target_coordinate(target_coordinate_) { create_children(); } void settle::create_children() { for (auto child_node : n->get_children()) { std::shared_ptr<shift> child_shift; int delta; switch (dim) { case dimension::x: delta = target_coordinate - child_node->get_location().x; child_shift = std::make_shared<shift>(child_node,0,delta,0); break; case dimension::y: delta = target_coordinate - child_node->get_location().y; child_shift = std::make_shared<shift>(child_node,0,0,delta); break; } child_shift->use_frame_count_method(this->frame_count_method); children.push_back(child_shift); } } <|endoftext|>
<commit_before>//============================================================================ // Name : Application.cpp // Author : Rian van Gijlswijk // Description : Main application file. //============================================================================ #include "Application.h" #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> namespace raytracer { namespace core { using namespace std; using namespace tracer; using namespace exporter; using namespace math; using namespace threading; boost::mutex datasetMutex; boost::mutex tracingIncMutex; boost::threadpool::pool tp; void Application::init(int argc, char * argv[]) { parseCommandLineArgs(argc, argv); start(); run(); } void Application::parseCommandLineArgs(int argc, char * argv[]) { for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "-h") == 0) { std::cout << "Ionospheric Ray Tracer\n\n" << "Synopsis:\n" << "\tirt [-opts] scenarioConfig\n\n" << "Description: \n" << "\tPerform ionospheric ray tracing on a celestial object described by the _celestialConfig json file. " << "If no config file is supplied, use a default scenario.\n\n" << "Options:\n" << "\t-c | --config\t Application config file\n" << "\t-i | --iterations\t The number of consecutive times every ray option should be run.\n" << "\t-h | --help\t This help.\n" << "\t-o | --output\t Path where output file should be stored.\n" << "\t-p | --parallelism\t Multithreading indicator.\n" << "\t-v | --verbose\t Verbose, display log output\n" << "\t-vv \t\t Very verbose, display log and debug output\n"; std::exit(0); } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--scenario") == 0) { _celestialConfigFile = argv[i+1]; } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) { _applicationConfigFile = argv[i+1]; } else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--parallelism") == 0) { _parallelism = atoi(argv[i+1]); } else if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--output") == 0) { _outputFile = argv[i+1]; } else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--iterations") == 0) { _iterations = atoi(argv[i+1]); } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { _verbosity = boost::log::trivial::info; } else if (strcmp(argv[i], "-vv") == 0) { _verbosity = boost::log::trivial::debug; } } // load scenario config file. Must be given. _celestialConfigFile = argv[argc-1]; } void Application::start() { _isRunning = true; _applicationConfig = Config(_applicationConfigFile); _celestialConfig = Config(_celestialConfigFile); if (_parallelism < 1) { _parallelism = _applicationConfig.getInt("parallelism"); } if (_iterations < 1) { _iterations = _applicationConfig.getInt("iterations"); } // boost::log::add_file_log("log/sample.log"); boost::log::core::get()->set_filter( boost::log::trivial::severity >= _verbosity); tp = boost::threadpool::pool(_parallelism); BOOST_LOG_TRIVIAL(debug) << "applicationConfig: " << _applicationConfigFile << endl << _applicationConfig << endl << "celestialConfig:" << _celestialConfigFile << endl << _celestialConfig; } void Application::run() { Timer tmr; BOOST_LOG_TRIVIAL(info) << "Parallelism is " << _applicationConfig.getInt("parallelism"); BOOST_LOG_TRIVIAL(warning) << _applicationConfig.getInt("iterations") << " iterations"; // trace a ray int rayCounter = 0; for (int iteration = 0; iteration < _applicationConfig.getInt("iterations"); iteration++) { BOOST_LOG_TRIVIAL(warning) << "Iteration " << (iteration+1) << " of " << _applicationConfig.getInt("iterations"); createScene(); int numWorkers = 0; double fmin = _applicationConfig.getObject("frequencies")["min"].asDouble(); double fstep = _applicationConfig.getObject("frequencies")["step"].asDouble(); double fmax = _applicationConfig.getObject("frequencies")["max"].asDouble(); double SZAmin = _applicationConfig.getObject("SZA")["min"].asDouble(); double SZAstep = _applicationConfig.getObject("SZA")["step"].asDouble(); double SZAmax = _applicationConfig.getObject("SZA")["max"].asDouble(); BOOST_LOG_TRIVIAL(info) << "Scanning frequencies " << fmin << " Hz to " << fmax << "Hz with steps of " << fstep << "Hz"; BOOST_LOG_TRIVIAL(info) << "Scanning SZA " << SZAmin << " deg to " << SZAmax << " deg with steps of " << SZAstep << " deg"; for (double freq = fmin; freq <= fmax; freq += fstep) { for (double SZA = SZAmin; SZA <= SZAmax; SZA += SZAstep) { Ray r; r.rayNumber = ++rayCounter; r.frequency = freq; r.signalPower = 0; r.o.y = 2 + _celestialConfig.getInt("radius"); r.originalAngle = SZA * Constants::PI / 180.0; Vector3d direction = Vector3d(cos(Constants::PI/2.0 - r.originalAngle), sin(Constants::PI/2.0 - r.originalAngle), 0); r.d = direction.norm(); Worker w; w.schedule(&tp, r); numWorkers++; } } BOOST_LOG_TRIVIAL(warning) << numWorkers << " workers queued"; tp.wait(); flushScene(); } stop(); double t = tmr.elapsed(); double tracingsPerSec = _numTracings / t; char buffer[80]; sprintf(buffer, "Elapsed: %5.2f sec. %d tracings done. %5.2f tracings/sec", t, _numTracings, tracingsPerSec); BOOST_LOG_TRIVIAL(warning) << buffer; //CsvExporter ce; //ce.dump("Debug/data.csv", dataSet); MatlabExporter me; me.dump(_outputFile, dataSet); BOOST_LOG_TRIVIAL(warning) << "Results stored at: " << _outputFile; } void Application::stop() { _isRunning = false; } /** * Add geometries to the scenemanager */ void Application::createScene() { int numSceneObjectsCreated = 0; double R = _celestialConfig.getInt("radius"); double angularStepSize = Constants::PI/360; IonosphereConfigParser plh = IonosphereConfigParser(); // terrain for (double latitude = Constants::PI/2; latitude < Constants::PI/2 + 10*Constants::PI/180; latitude += angularStepSize) { for (double theta = 0; theta < Constants::PI/2; theta += angularStepSize) { Vector3d N = Vector3d(cos(theta), sin(theta), cos(latitude)).norm(); Plane3d mesh = Plane3d(N, Vector3d(R*N.x, R*N.y, R*N.z)); mesh.size = angularStepSize * R; Terrain* tr = new Terrain(mesh); numSceneObjectsCreated++; _scm.addToScene(tr); } } const Json::Value ionosphereConfig = _celestialConfig.getObject("ionosphere"); int start = ionosphereConfig["start"].asInt(); int dh = ionosphereConfig["step"].asInt(); int end =ionosphereConfig["end"].asInt(); for (double latitude = Constants::PI/2; latitude < Constants::PI/2 + 10*Constants::PI/180; latitude += angularStepSize) { for (double theta = Constants::PI/4; theta < Constants::PI/2; theta += angularStepSize) { for (int h = start; h < end; h += dh) { Vector3d N = Vector3d(cos(theta), sin(theta), cos(latitude)).norm(); Plane3d mesh = Plane3d(N, Vector3d((R+h)*N.x, (R+h)*N.y, (R+h)*N.z)); mesh.size = angularStepSize * R; Ionosphere* io = new Ionosphere(mesh); io->layerHeight = dh; for (int idx = 0; idx < ionosphereConfig["layers"].size(); idx++) { double electronPeakDensity = atof(ionosphereConfig["layers"][idx].get("electronPeakDensity", "").asCString()); double peakProductionAltitude = ionosphereConfig["layers"][idx].get("peakProductionAltitude", "").asDouble(); double neutralScaleHeight = ionosphereConfig["layers"][idx].get("neutralScaleHeight", 11.1e3).asDouble(); io->superimposeElectronNumberDensity(electronPeakDensity, peakProductionAltitude, neutralScaleHeight); } numSceneObjectsCreated++; _scm.addToScene(io); } } } // const Json::Value atmosphereConfig = _celestialConfig.getObject("atmosphere"); // int hS = atmosphereConfig.get("start", 0).asInt(); // int hE = atmosphereConfig.get("end", 0).asInt(); // dh = 2000; // // for (double theta = 0; theta < 2*Constants::PI; theta += Constants::PI/180) { // double nextTheta = theta + Constants::PI/180; // // for (int h = hS; h < hE; h += dh) { // Atmosphere* atm = new Atmosphere(Vector3d(cos(theta), sin(theta), 0),Vector3d((R + h) * cos(theta), (R + h) * sin(theta), 0)); // atm->layerHeight = dh; // // numSceneObjectsCreated++; // _scm.addToScene(atm); // } // } if (numSceneObjectsCreated > 1e9) BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e9 << "G scene objects created"; else if (numSceneObjectsCreated > 1e6) BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e6 << "M scene objects created"; else if (numSceneObjectsCreated > 1e3) BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e3 << "K scene objects created"; else BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated << " scene objects created"; } /** * Flush the scene by clearing the list of scene objects */ void Application::flushScene() { _scm.removeAllFromScene(); } void Application::addToDataset(Data dat) { datasetMutex.lock(); dataSet.push_back(dat); datasetMutex.unlock(); } void Application::incrementTracing() { tracingIncMutex.lock(); _numTracings++; tracingIncMutex.unlock(); } SceneManager Application::getSceneManager() { return _scm; } Config Application::getApplicationConfig() { return _applicationConfig; } Config Application::getCelestialConfig() { return _celestialConfig; } void Application::setCelestialConfig(Config conf) { _celestialConfig = conf; } } /* namespace core */ } /* namespace raytracer */ <commit_msg>Added check for missing scenario file<commit_after>//============================================================================ // Name : Application.cpp // Author : Rian van Gijlswijk // Description : Main application file. //============================================================================ #include "Application.h" #include <string> #include <regex> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/utility/setup/file.hpp> namespace raytracer { namespace core { using namespace std; using namespace tracer; using namespace exporter; using namespace math; using namespace threading; boost::mutex datasetMutex; boost::mutex tracingIncMutex; boost::threadpool::pool tp; void Application::init(int argc, char * argv[]) { parseCommandLineArgs(argc, argv); start(); run(); } void Application::parseCommandLineArgs(int argc, char * argv[]) { for (int i = 0; i < argc; i++) { if (strcmp(argv[i], "-h") == 0) { std::cout << "Ionospheric Ray Tracer\n\n" << "Synopsis:\n" << "\tirt [-opts] scenarioConfig\n\n" << "Description: \n" << "\tPerform ionospheric ray tracing on a celestial object described by the _celestialConfig json file. " << "If no config file is supplied, use a default scenario.\n\n" << "Options:\n" << "\t-c | --config\t Application config file\n" << "\t-i | --iterations\t The number of consecutive times every ray option should be run.\n" << "\t-h | --help\t This help.\n" << "\t-o | --output\t Path where output file should be stored.\n" << "\t-p | --parallelism\t Multithreading indicator.\n" << "\t-v | --verbose\t Verbose, display log output\n" << "\t-vv \t\t Very verbose, display log and debug output\n"; std::exit(0); } else if (strcmp(argv[i], "-s") == 0 || strcmp(argv[i], "--scenario") == 0) { _celestialConfigFile = argv[i+1]; } else if (strcmp(argv[i], "-c") == 0 || strcmp(argv[i], "--config") == 0) { _applicationConfigFile = argv[i+1]; } else if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "--parallelism") == 0) { _parallelism = atoi(argv[i+1]); } else if (strcmp(argv[i], "-o") == 0 || strcmp(argv[i], "--output") == 0) { _outputFile = argv[i+1]; } else if (strcmp(argv[i], "-i") == 0 || strcmp(argv[i], "--iterations") == 0) { _iterations = atoi(argv[i+1]); } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) { _verbosity = boost::log::trivial::info; } else if (strcmp(argv[i], "-vv") == 0) { _verbosity = boost::log::trivial::debug; } } // load scenario config file. Must be given. std::cout << argv[argc-1] << endl; if (!std::regex_match (argv[argc-1], std::regex("[A-Za-z0-9_/]+\.json") )) { BOOST_LOG_TRIVIAL(fatal) << "No scenario file given! Exiting."; std::exit(0); } _celestialConfigFile = argv[argc-1]; } void Application::start() { _isRunning = true; _applicationConfig = Config(_applicationConfigFile); _celestialConfig = Config(_celestialConfigFile); if (_parallelism < 1) { _parallelism = _applicationConfig.getInt("parallelism"); } if (_iterations < 1) { _iterations = _applicationConfig.getInt("iterations"); } // boost::log::add_file_log("log/sample.log"); boost::log::core::get()->set_filter( boost::log::trivial::severity >= _verbosity); tp = boost::threadpool::pool(_parallelism); BOOST_LOG_TRIVIAL(debug) << "applicationConfig: " << _applicationConfigFile << endl << _applicationConfig << endl << "celestialConfig:" << _celestialConfigFile << endl << _celestialConfig; } void Application::run() { Timer tmr; BOOST_LOG_TRIVIAL(info) << "Parallelism is " << _applicationConfig.getInt("parallelism"); BOOST_LOG_TRIVIAL(warning) << _applicationConfig.getInt("iterations") << " iterations"; // trace a ray int rayCounter = 0; for (int iteration = 0; iteration < _applicationConfig.getInt("iterations"); iteration++) { BOOST_LOG_TRIVIAL(warning) << "Iteration " << (iteration+1) << " of " << _applicationConfig.getInt("iterations"); createScene(); int numWorkers = 0; double fmin = _applicationConfig.getObject("frequencies")["min"].asDouble(); double fstep = _applicationConfig.getObject("frequencies")["step"].asDouble(); double fmax = _applicationConfig.getObject("frequencies")["max"].asDouble(); double SZAmin = _applicationConfig.getObject("SZA")["min"].asDouble(); double SZAstep = _applicationConfig.getObject("SZA")["step"].asDouble(); double SZAmax = _applicationConfig.getObject("SZA")["max"].asDouble(); BOOST_LOG_TRIVIAL(info) << "Scanning frequencies " << fmin << " Hz to " << fmax << "Hz with steps of " << fstep << "Hz"; BOOST_LOG_TRIVIAL(info) << "Scanning SZA " << SZAmin << " deg to " << SZAmax << " deg with steps of " << SZAstep << " deg"; for (double freq = fmin; freq <= fmax; freq += fstep) { for (double SZA = SZAmin; SZA <= SZAmax; SZA += SZAstep) { Ray r; r.rayNumber = ++rayCounter; r.frequency = freq; r.signalPower = 0; r.o.y = 2 + _celestialConfig.getInt("radius"); r.originalAngle = SZA * Constants::PI / 180.0; Vector3d direction = Vector3d(cos(Constants::PI/2.0 - r.originalAngle), sin(Constants::PI/2.0 - r.originalAngle), 0); r.d = direction.norm(); Worker w; w.schedule(&tp, r); numWorkers++; } } BOOST_LOG_TRIVIAL(warning) << numWorkers << " workers queued"; tp.wait(); flushScene(); } stop(); double t = tmr.elapsed(); double tracingsPerSec = _numTracings / t; char buffer[80]; sprintf(buffer, "Elapsed: %5.2f sec. %d tracings done. %5.2f tracings/sec", t, _numTracings, tracingsPerSec); BOOST_LOG_TRIVIAL(warning) << buffer; //CsvExporter ce; //ce.dump("Debug/data.csv", dataSet); MatlabExporter me; me.dump(_outputFile, dataSet); BOOST_LOG_TRIVIAL(warning) << "Results stored at: " << _outputFile; } void Application::stop() { _isRunning = false; } /** * Add geometries to the scenemanager */ void Application::createScene() { int numSceneObjectsCreated = 0; double R = _celestialConfig.getInt("radius"); double angularStepSize = Constants::PI/360; IonosphereConfigParser plh = IonosphereConfigParser(); // terrain for (double latitude = Constants::PI/2; latitude < Constants::PI/2 + 10*Constants::PI/180; latitude += angularStepSize) { for (double theta = 0; theta < Constants::PI/2; theta += angularStepSize) { Vector3d N = Vector3d(cos(theta), sin(theta), cos(latitude)).norm(); Plane3d mesh = Plane3d(N, Vector3d(R*N.x, R*N.y, R*N.z)); mesh.size = angularStepSize * R; Terrain* tr = new Terrain(mesh); numSceneObjectsCreated++; _scm.addToScene(tr); } } const Json::Value ionosphereConfig = _celestialConfig.getObject("ionosphere"); int start = ionosphereConfig["start"].asInt(); int dh = ionosphereConfig["step"].asInt(); int end =ionosphereConfig["end"].asInt(); for (double latitude = Constants::PI/2; latitude < Constants::PI/2 + 10*Constants::PI/180; latitude += angularStepSize) { for (double theta = Constants::PI/4; theta < Constants::PI/2; theta += angularStepSize) { for (int h = start; h < end; h += dh) { Vector3d N = Vector3d(cos(theta), sin(theta), cos(latitude)).norm(); Plane3d mesh = Plane3d(N, Vector3d((R+h)*N.x, (R+h)*N.y, (R+h)*N.z)); mesh.size = angularStepSize * R; Ionosphere* io = new Ionosphere(mesh); io->layerHeight = dh; for (int idx = 0; idx < ionosphereConfig["layers"].size(); idx++) { double electronPeakDensity = atof(ionosphereConfig["layers"][idx].get("electronPeakDensity", "").asCString()); double peakProductionAltitude = ionosphereConfig["layers"][idx].get("peakProductionAltitude", "").asDouble(); double neutralScaleHeight = ionosphereConfig["layers"][idx].get("neutralScaleHeight", 11.1e3).asDouble(); io->superimposeElectronNumberDensity(electronPeakDensity, peakProductionAltitude, neutralScaleHeight); } numSceneObjectsCreated++; _scm.addToScene(io); } } } // const Json::Value atmosphereConfig = _celestialConfig.getObject("atmosphere"); // int hS = atmosphereConfig.get("start", 0).asInt(); // int hE = atmosphereConfig.get("end", 0).asInt(); // dh = 2000; // // for (double theta = 0; theta < 2*Constants::PI; theta += Constants::PI/180) { // double nextTheta = theta + Constants::PI/180; // // for (int h = hS; h < hE; h += dh) { // Atmosphere* atm = new Atmosphere(Vector3d(cos(theta), sin(theta), 0),Vector3d((R + h) * cos(theta), (R + h) * sin(theta), 0)); // atm->layerHeight = dh; // // numSceneObjectsCreated++; // _scm.addToScene(atm); // } // } if (numSceneObjectsCreated > 1e9) BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e9 << "G scene objects created"; else if (numSceneObjectsCreated > 1e6) BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e6 << "M scene objects created"; else if (numSceneObjectsCreated > 1e3) BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated/1.0e3 << "K scene objects created"; else BOOST_LOG_TRIVIAL(info) << setprecision(3) << numSceneObjectsCreated << " scene objects created"; } /** * Flush the scene by clearing the list of scene objects */ void Application::flushScene() { _scm.removeAllFromScene(); } void Application::addToDataset(Data dat) { datasetMutex.lock(); dataSet.push_back(dat); datasetMutex.unlock(); } void Application::incrementTracing() { tracingIncMutex.lock(); _numTracings++; tracingIncMutex.unlock(); } SceneManager Application::getSceneManager() { return _scm; } Config Application::getApplicationConfig() { return _applicationConfig; } Config Application::getCelestialConfig() { return _celestialConfig; } void Application::setCelestialConfig(Config conf) { _celestialConfig = conf; } } /* namespace core */ } /* namespace raytracer */ <|endoftext|>
<commit_before>/// Project #include <Doremi/Core/Include/Manager/AI/AITargetManager.hpp> #include <PlayerHandlerServer.hpp> // Components #include <EntityComponent/EntityHandler.hpp> #include <EntityComponent/Components/TransformComponent.hpp> #include <EntityComponent/Components/RangeComponent.hpp> #include <EntityComponent/Components/EntityTypeComponent.hpp> #include <EntityComponent/Components/RigidBodyComponent.hpp> #include <EntityComponent/Components/PhysicsMaterialComponent.hpp> #include <EntityComponent/Components/AiAgentComponent.hpp> #include <EntityComponent/Components/PotentialFieldComponent.hpp> #include <EntityComponent/Components/MovementComponent.hpp> // Events #include <Doremi/Core/Include/EventHandler/EventHandler.hpp> #include <Doremi/Core/Include/EventHandler/Events/AnimationTransitionEvent.hpp> // Helper #include <Helper/ProximityChecker.hpp> /// Engine // Physics #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RayCastManager.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> // Config #include <DoremiEngine/Configuration/Include/ConfigurationModule.hpp> // Third party #include <DirectXMath.h> #include <iostream> namespace Doremi { namespace Core { AITargetManager::AITargetManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "AITargetManager") { m_playerMovementImpact = m_sharedContext.GetConfigurationModule().GetAllConfigurationValues().AIAimOffset; m_maxActorsUpdated = 1; // We may only update one AI per update... TODOCONFIG m_actorToUpdate = 0; } AITargetManager::~AITargetManager() {} void AITargetManager::Update(double p_dt) { using namespace DirectX; int updatedActors = 0; int lastUpdatedActor = 0; // gets all the players in the world, used to see if we can see anyone of them std::map<uint32_t, PlayerServer*> t_players = static_cast<PlayerHandlerServer*>(PlayerHandler::GetInstance())->GetPlayerMap(); size_t length = EntityHandler::GetInstance().GetLastEntityIndex(); EntityHandler& t_entityHandler = EntityHandler::GetInstance(); for(size_t i = m_actorToUpdate + 1; i != m_actorToUpdate; i++) { if(i > length) { i = 0; if(i == m_actorToUpdate) { break; } } // Check and update the attack timer bool shouldFire = false; if(t_entityHandler.HasComponents(i, (int)ComponentType::AIAgent)) { AIAgentComponent* timer = t_entityHandler.GetComponentFromStorage<AIAgentComponent>(i); timer->attackTimer += static_cast<float>(p_dt); // If above attack freq we should attack if(timer->attackTimer > timer->attackFrequency) { shouldFire = true; } else { // else continue to next for itteration shouldFire = false; } } else { shouldFire = false; // No timer? TODOKO log error and dont let it fire! } if(t_entityHandler.HasComponents(i, (int)ComponentType::Range | (int)ComponentType::AIAgent | (int)ComponentType::Transform) && updatedActors < m_maxActorsUpdated) { // They have a range component and are AI agents, let's see if a player is in range! // I use proximitychecker here because i'm guessing it's faster than raycast TransformComponent* AITransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(i); RangeComponent* aiRange = t_entityHandler.GetComponentFromStorage<RangeComponent>(i); int closestVisiblePlayer = -1; float checkRange = 1000; float closestDistance = checkRange; // Hardcoded range, not intreseted if player is outside this int onlyOnePlayerCounts = 1; // Check waht player is close and visible for(auto pairs : t_players) { int playerID = pairs.second->m_playerEntityID; float distanceToPlayer = ProximityChecker::GetInstance().GetDistanceBetweenEntities(pairs.second->m_playerEntityID, i); if(distanceToPlayer < closestDistance) { // It's after this we start whit heavy computation so this is counted as a updated actor lastUpdatedActor = i; updatedActors += onlyOnePlayerCounts; onlyOnePlayerCounts = 0; // Potential player found, check if we see him // We are in range!! Let's raycast in a appropirate direction!! so start with finding that direction! if(!EntityHandler::GetInstance().HasComponents(playerID, (int)ComponentType::Transform)) // Just for saftey :D { std::cout << "Player missing transformcomponent?" << std::endl; return; } // Fetch some components TransformComponent* playerTransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(playerID); // Get things in to vectors XMVECTOR playerPos = XMLoadFloat3(&playerTransform->position); XMVECTOR AIPos = XMLoadFloat3(&AITransform->position); // Calculate direction XMVECTOR direction = playerPos - AIPos; // Might be the wrong way direction = XMVector3Normalize(direction); XMFLOAT3 directionFloat; XMStoreFloat3(&directionFloat, direction); // Offset origin of ray so we dont hit ourself XMVECTOR rayOrigin = AIPos + direction * 3.0f; // TODOCONFIG x.xf is offset from the units body, might need to increase if // the bodies radius is larger than x.x XMFLOAT3 rayOriginFloat; XMStoreFloat3(&rayOriginFloat, rayOrigin); // Send it to physx for raycast calculation int bodyHit = m_sharedContext.GetPhysicsModule().GetRayCastManager().CastRay(rayOriginFloat, directionFloat, checkRange); if(bodyHit == -1) { continue; } // we check if it was a bullet we did hit, in this case we probably did hit our own bullet and should take this as a // player hit // This is a bit of a wild guess and we should probably do a new raycast from the hit location but screw that! bool wasBullet = false; if(EntityHandler::GetInstance().HasComponents(bodyHit, (int)ComponentType::EntityType)) { EntityTypeComponent* typeComp = EntityHandler::GetInstance().GetComponentFromStorage<EntityTypeComponent>(bodyHit); if(((int)typeComp->type & (int)EntityType::EnemyBullet) == (int)EntityType::EnemyBullet) // if first entity is bullet { wasBullet = true; } } if(bodyHit == playerID || wasBullet) { closestDistance = distanceToPlayer; closestVisiblePlayer = pairs.second->m_playerEntityID; // Rotate the enemy to face the player XMMATRIX mat = XMMatrixInverse(nullptr, XMMatrixLookAtLH(AIPos, AIPos + direction, XMLoadFloat3(&XMFLOAT3(0, 1, 0)))); XMVECTOR rotation = XMQuaternionRotationMatrix(mat); XMFLOAT4 quater; XMStoreFloat4(&quater, rotation); AITransform->rotation = quater; } } } if(closestVisiblePlayer != -1) { // We now know what player is closest and visible if(shouldFire) { if(closestDistance <= aiRange->range) { FireAtEntity(closestVisiblePlayer, i, closestDistance); if(t_entityHandler.HasComponents(i, (int)ComponentType::AIAgent)) { AIAgentComponent* timer = t_entityHandler.GetComponentFromStorage<AIAgentComponent>(i); timer->attackTimer = 0; } else { // WTF??? someone who isnt AI agen got here?? std::cout << "Non enemy entered the AI fire logic..." << std::endl; } } } // If we see a player turn off the phermonetrail if(t_entityHandler.HasComponents(i, (int)ComponentType::PotentialField)) { PotentialFieldComponent* pfComp = t_entityHandler.GetComponentFromStorage<PotentialFieldComponent>(i); pfComp->ChargedActor->SetUsePhermonetrail(false); pfComp->ChargedActor->SetActivePotentialVsType(DoremiEngine::AI::AIActorType::Player, true); } } else if(t_entityHandler.HasComponents(i, (int)ComponentType::PotentialField)) { // if we dont see a player set phemonetrail and shit PotentialFieldComponent* pfComp = t_entityHandler.GetComponentFromStorage<PotentialFieldComponent>(i); pfComp->ChargedActor->SetUsePhermonetrail(true); pfComp->ChargedActor->SetActivePotentialVsType(DoremiEngine::AI::AIActorType::Player, false); } } } m_actorToUpdate = lastUpdatedActor; } void AITargetManager::FireAtEntity(const size_t& p_entityID, const size_t& p_enemyID, const float& p_distance) { EntityHandler& t_entityHandler = EntityHandler::GetInstance(); TransformComponent* playerTransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(p_entityID); MovementComponent* playerMovement = t_entityHandler.GetComponentFromStorage<MovementComponent>(p_entityID); TransformComponent* AITransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(p_enemyID); // Get things in to vectors XMVECTOR playerPos = XMLoadFloat3(&playerTransform->position); XMVECTOR AIPos = XMLoadFloat3(&AITransform->position); // calculate direction again... XMVECTOR direction = playerPos - AIPos; // Might be the wrong way direction = XMVector3Normalize(direction); direction += XMVector3Normalize(XMLoadFloat3(&playerMovement->movement) * m_playerMovementImpact); direction = XMVector3Normalize(direction); XMFLOAT3 directionFloat; XMStoreFloat3(&directionFloat, direction); XMVECTOR bulletOrigin = AIPos + direction * 3.0f; // TODOCONFIG x.xf is offset from the units body, might need to increase if // the bodies radius is larger than x.x XMFLOAT3 bulletOriginFloat; XMStoreFloat3(&bulletOriginFloat, bulletOrigin); int id = t_entityHandler.CreateEntity(Blueprints::BulletEntity, bulletOriginFloat); m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetCallbackFiltering(id, 3, 1, 8, 2); // Add a force to the body TODOCONFIG should not be hard coded the force amount direction *= 1500.0f; XMFLOAT3 force; XMStoreFloat3(&force, direction); m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddForceToBody(id, force); AnimationTransitionEvent* t_animationTransition = new AnimationTransitionEvent(p_enemyID, Animation::ATTACK); EventHandler::GetInstance()->BroadcastEvent(t_animationTransition); } } }<commit_msg>Tweaked enemy raytrace and bullet creation<commit_after>/// Project #include <Doremi/Core/Include/Manager/AI/AITargetManager.hpp> #include <PlayerHandlerServer.hpp> // Components #include <EntityComponent/EntityHandler.hpp> #include <EntityComponent/Components/TransformComponent.hpp> #include <EntityComponent/Components/RangeComponent.hpp> #include <EntityComponent/Components/EntityTypeComponent.hpp> #include <EntityComponent/Components/RigidBodyComponent.hpp> #include <EntityComponent/Components/PhysicsMaterialComponent.hpp> #include <EntityComponent/Components/AiAgentComponent.hpp> #include <EntityComponent/Components/PotentialFieldComponent.hpp> #include <EntityComponent/Components/MovementComponent.hpp> // Events #include <Doremi/Core/Include/EventHandler/EventHandler.hpp> #include <Doremi/Core/Include/EventHandler/Events/AnimationTransitionEvent.hpp> // Helper #include <Helper/ProximityChecker.hpp> /// Engine // Physics #include <DoremiEngine/Physics/Include/PhysicsModule.hpp> #include <DoremiEngine/Physics/Include/RayCastManager.hpp> #include <DoremiEngine/Physics/Include/RigidBodyManager.hpp> // Config #include <DoremiEngine/Configuration/Include/ConfigurationModule.hpp> // Third party #include <DirectXMath.h> #include <iostream> namespace Doremi { namespace Core { AITargetManager::AITargetManager(const DoremiEngine::Core::SharedContext& p_sharedContext) : Manager(p_sharedContext, "AITargetManager") { m_playerMovementImpact = m_sharedContext.GetConfigurationModule().GetAllConfigurationValues().AIAimOffset; m_maxActorsUpdated = 1; // We may only update one AI per update... TODOCONFIG m_actorToUpdate = 0; } AITargetManager::~AITargetManager() {} void AITargetManager::Update(double p_dt) { using namespace DirectX; int updatedActors = 0; int lastUpdatedActor = 0; // gets all the players in the world, used to see if we can see anyone of them std::map<uint32_t, PlayerServer*> t_players = static_cast<PlayerHandlerServer*>(PlayerHandler::GetInstance())->GetPlayerMap(); size_t length = EntityHandler::GetInstance().GetLastEntityIndex(); EntityHandler& t_entityHandler = EntityHandler::GetInstance(); for(size_t i = m_actorToUpdate + 1; i != m_actorToUpdate; i++) { if(i > length) { i = 0; if(i == m_actorToUpdate) { break; } } // Check and update the attack timer bool shouldFire = false; if(t_entityHandler.HasComponents(i, (int)ComponentType::AIAgent)) { AIAgentComponent* timer = t_entityHandler.GetComponentFromStorage<AIAgentComponent>(i); timer->attackTimer += static_cast<float>(p_dt); // If above attack freq we should attack if(timer->attackTimer > timer->attackFrequency) { shouldFire = true; } else { // else continue to next for itteration shouldFire = false; } } else { shouldFire = false; // No timer? TODOKO log error and dont let it fire! } if(t_entityHandler.HasComponents(i, (int)ComponentType::Range | (int)ComponentType::AIAgent | (int)ComponentType::Transform) && updatedActors < m_maxActorsUpdated) { // They have a range component and are AI agents, let's see if a player is in range! // I use proximitychecker here because i'm guessing it's faster than raycast TransformComponent* AITransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(i); RangeComponent* aiRange = t_entityHandler.GetComponentFromStorage<RangeComponent>(i); int closestVisiblePlayer = -1; float checkRange = 1000; float closestDistance = checkRange; // Hardcoded range, not intreseted if player is outside this int onlyOnePlayerCounts = 1; // Check waht player is close and visible for(auto pairs : t_players) { int playerID = pairs.second->m_playerEntityID; float distanceToPlayer = ProximityChecker::GetInstance().GetDistanceBetweenEntities(pairs.second->m_playerEntityID, i); if(distanceToPlayer < closestDistance) { // It's after this we start whit heavy computation so this is counted as a updated actor lastUpdatedActor = i; updatedActors += onlyOnePlayerCounts; onlyOnePlayerCounts = 0; // Potential player found, check if we see him // We are in range!! Let's raycast in a appropirate direction!! so start with finding that direction! if(!EntityHandler::GetInstance().HasComponents(playerID, (int)ComponentType::Transform)) // Just for saftey :D { std::cout << "Player missing transformcomponent?" << std::endl; return; } // Fetch some components TransformComponent* playerTransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(playerID); // Get things in to vectors XMVECTOR playerPos = XMLoadFloat3(&playerTransform->position); XMVECTOR AIPos = XMLoadFloat3(&AITransform->position); // Calculate direction XMVECTOR direction = playerPos - AIPos; // Might be the wrong way direction = XMVector3Normalize(direction); XMFLOAT3 directionFloat; XMStoreFloat3(&directionFloat, direction); // Offset origin of ray so we dont hit ourself XMVECTOR rayOrigin = AIPos + direction * 3.5f; // TODOCONFIG x.xf is offset from the units body, might need to increase if // the bodies radius is larger than x.x XMFLOAT3 rayOriginFloat; XMStoreFloat3(&rayOriginFloat, rayOrigin); // Send it to physx for raycast calculation int bodyHit = m_sharedContext.GetPhysicsModule().GetRayCastManager().CastRay(rayOriginFloat, directionFloat, checkRange); if(bodyHit == -1) { continue; } // we check if it was a bullet we did hit, in this case we probably did hit our own bullet and should take this as a // player hit // This is a bit of a wild guess and we should probably do a new raycast from the hit location but screw that! bool wasBullet = false; if(EntityHandler::GetInstance().HasComponents(bodyHit, (int)ComponentType::EntityType)) { EntityTypeComponent* typeComp = EntityHandler::GetInstance().GetComponentFromStorage<EntityTypeComponent>(bodyHit); if(((int)typeComp->type & (int)EntityType::EnemyBullet) == (int)EntityType::EnemyBullet) // if first entity is bullet { wasBullet = true; } } if(bodyHit == playerID || wasBullet) { closestDistance = distanceToPlayer; closestVisiblePlayer = pairs.second->m_playerEntityID; // Rotate the enemy to face the player XMMATRIX mat = XMMatrixInverse(nullptr, XMMatrixLookAtLH(AIPos, AIPos + direction, XMLoadFloat3(&XMFLOAT3(0, 1, 0)))); XMVECTOR rotation = XMQuaternionRotationMatrix(mat); XMFLOAT4 quater; XMStoreFloat4(&quater, rotation); AITransform->rotation = quater; } } } if(closestVisiblePlayer != -1) { // We now know what player is closest and visible if(shouldFire) { if(closestDistance <= aiRange->range) { FireAtEntity(closestVisiblePlayer, i, closestDistance); if(t_entityHandler.HasComponents(i, (int)ComponentType::AIAgent)) { AIAgentComponent* timer = t_entityHandler.GetComponentFromStorage<AIAgentComponent>(i); timer->attackTimer = 0; } else { // WTF??? someone who isnt AI agen got here?? std::cout << "Non enemy entered the AI fire logic..." << std::endl; } } } // If we see a player turn off the phermonetrail if(t_entityHandler.HasComponents(i, (int)ComponentType::PotentialField)) { PotentialFieldComponent* pfComp = t_entityHandler.GetComponentFromStorage<PotentialFieldComponent>(i); pfComp->ChargedActor->SetUsePhermonetrail(false); pfComp->ChargedActor->SetActivePotentialVsType(DoremiEngine::AI::AIActorType::Player, true); } } else if(t_entityHandler.HasComponents(i, (int)ComponentType::PotentialField)) { // if we dont see a player set phemonetrail and shit PotentialFieldComponent* pfComp = t_entityHandler.GetComponentFromStorage<PotentialFieldComponent>(i); pfComp->ChargedActor->SetUsePhermonetrail(true); pfComp->ChargedActor->SetActivePotentialVsType(DoremiEngine::AI::AIActorType::Player, false); } } } m_actorToUpdate = lastUpdatedActor; } void AITargetManager::FireAtEntity(const size_t& p_entityID, const size_t& p_enemyID, const float& p_distance) { EntityHandler& t_entityHandler = EntityHandler::GetInstance(); TransformComponent* playerTransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(p_entityID); MovementComponent* playerMovement = t_entityHandler.GetComponentFromStorage<MovementComponent>(p_entityID); TransformComponent* AITransform = t_entityHandler.GetComponentFromStorage<TransformComponent>(p_enemyID); // Get things in to vectors XMVECTOR playerPos = XMLoadFloat3(&playerTransform->position); XMVECTOR AIPos = XMLoadFloat3(&AITransform->position); // calculate direction again... XMVECTOR direction = playerPos - AIPos; // Might be the wrong way direction = XMVector3Normalize(direction); direction += XMVector3Normalize(XMLoadFloat3(&playerMovement->movement) * m_playerMovementImpact); direction = XMVector3Normalize(direction); XMFLOAT3 directionFloat; XMStoreFloat3(&directionFloat, direction); XMVECTOR bulletOrigin = AIPos + direction * 3.5f; // TODOCONFIG x.xf is offset from the units body, might need to increase if // the bodies radius is larger than x.x XMFLOAT3 bulletOriginFloat; XMStoreFloat3(&bulletOriginFloat, bulletOrigin); int id = t_entityHandler.CreateEntity(Blueprints::BulletEntity, bulletOriginFloat); m_sharedContext.GetPhysicsModule().GetRigidBodyManager().SetCallbackFiltering(id, 3, 1, 8, 2); // Add a force to the body TODOCONFIG should not be hard coded the force amount direction *= 1500.0f; XMFLOAT3 force; XMStoreFloat3(&force, direction); m_sharedContext.GetPhysicsModule().GetRigidBodyManager().AddForceToBody(id, force); AnimationTransitionEvent* t_animationTransition = new AnimationTransitionEvent(p_enemyID, Animation::ATTACK); EventHandler::GetInstance()->BroadcastEvent(t_animationTransition); } } }<|endoftext|>
<commit_before>#define BOOST_TEST_MODULE "test_read_rectangular_box_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/input/read_external_interaction.hpp> BOOST_AUTO_TEST_CASE(read_pulling_force_interaction) { mjolnir::LoggerManager::set_default_logger("test_read_pulling_force_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; { using namespace toml::literals; const toml::value v = u8R"( interaction = "PullingForce" parameters = [ {index = 0, force = [ 1.0, 2.0, 10.0]}, {index = 100, force = [-5.0, 0.0, 0.0]}, ] )"_toml; const auto base = mjolnir::read_external_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::PullingForceInteraction<traits_type>*>(base.get()); BOOST_TEST(static_cast<bool>(derv)); const auto& interaction = *derv; BOOST_TEST(interaction.parameters().at(0).first == 0); BOOST_TEST(interaction.parameters().at(1).first == 100); BOOST_TEST(mjolnir::math::X(interaction.parameters().at(0).second) == 1.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Y(interaction.parameters().at(0).second) == 2.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Z(interaction.parameters().at(0).second) == 10.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::X(interaction.parameters().at(1).second) ==-5.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Y(interaction.parameters().at(1).second) == 0.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Z(interaction.parameters().at(1).second) == 0.0, boost::test_tools::tolerance(1e-8)); } } <commit_msg>fix: typo in the BOOST_TEST_MODULE name<commit_after>#define BOOST_TEST_MODULE "test_read_pulling_force_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/input/read_external_interaction.hpp> BOOST_AUTO_TEST_CASE(read_pulling_force_interaction) { mjolnir::LoggerManager::set_default_logger("test_read_pulling_force_interaction.log"); using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>; { using namespace toml::literals; const toml::value v = u8R"( interaction = "PullingForce" parameters = [ {index = 0, force = [ 1.0, 2.0, 10.0]}, {index = 100, force = [-5.0, 0.0, 0.0]}, ] )"_toml; const auto base = mjolnir::read_external_interaction<traits_type>(v); BOOST_TEST(static_cast<bool>(base)); const auto derv = dynamic_cast<mjolnir::PullingForceInteraction<traits_type>*>(base.get()); BOOST_TEST(static_cast<bool>(derv)); const auto& interaction = *derv; BOOST_TEST(interaction.parameters().at(0).first == 0); BOOST_TEST(interaction.parameters().at(1).first == 100); BOOST_TEST(mjolnir::math::X(interaction.parameters().at(0).second) == 1.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Y(interaction.parameters().at(0).second) == 2.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Z(interaction.parameters().at(0).second) == 10.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::X(interaction.parameters().at(1).second) ==-5.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Y(interaction.parameters().at(1).second) == 0.0, boost::test_tools::tolerance(1e-8)); BOOST_TEST(mjolnir::math::Z(interaction.parameters().at(1).second) == 0.0, boost::test_tools::tolerance(1e-8)); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2009 * * School of Computing, University of Utah, * Salt Lake City, UT 84112, USA * * and the Gauss Group * http://www.cs.utah.edu/formal_verification * * See LICENSE for licensing information */ #include <iostream> #include <sstream> #include <memory> #include <boost/range/adaptor/reversed.hpp> #include <boost/range/adaptor/indirected.hpp> #include "Trace.hpp" using boost::adaptors::reverse; using boost::adaptors::indirect; using std::make_shared; using std::move; bool Trace::add(std::unique_ptr<Envelope> env) { const int index = env->index; // check if already in the list if (index <= size() - 1) { // return true only when the envelopes match return trace[index]->getEnvelope() == *env; } // otherwise append to the list auto last_op = make_shared<Transition>(pid, size() - 1, move(env)); trace.push_back(last_op); auto env_t = last_op->getEnvelope(); bool blocking_flag = false; if (env_t.func_id == OpType::ISEND || env_t.func_id == OpType::IRECV) { ulist.push_back(last_op->index); } else if (env_t.func_id == OpType::WAIT || env_t.func_id == OpType::WAITALL || env_t.func_id == OpType::TEST || env_t.func_id == OpType::TESTALL) { for (auto & req : env_t.req_procs) { auto curr = trace[req]; if (curr->addIntraCB(last_op)) { last_op->addAncestor(curr); } ulist.remove(curr->index); } } int i = size() - 2; for (auto & curr : indirect(reverse())) { if (curr.getEnvelope().completesBefore(env_t)) { if (blocking_flag) { if (env_t.func_id != OpType::SEND && (ulist.size() == 0 || index < ulist.front())) { return true; } //if a blocking call occured in the past //the only calls that can slip through it are //Isend and Irecv auto env_f = curr.getEnvelope(); if (env_f.func_id == OpType::IRECV) { if (curr.addIntraCB(last_op)) { last_op->addAncestor(trace[i]); } //terminate if this satisfies the Irecv intraCB rule if (env_t.matchRecv(env_f)) { return true; } } else if (env_f.func_id == OpType::ISEND) { if (curr.addIntraCB(last_op)) { last_op->addAncestor(trace[i]); } //terminate if this satisfies the Isend intraCB rule if (env_t.matchSend(env_f)) { return true; } } } else { if (curr.addIntraCB(last_op)) { last_op->addAncestor(trace[i]); } /* avo 06/11/08 - trying not to add redundant edges */ //a blocking call occured earlier //to avoid unnecessary CB edges if (curr.getEnvelope().isBlockingType()) { blocking_flag = true; } } } i--; } return true; } <commit_msg>Make it compile.<commit_after>/* * Copyright (c) 2008-2009 * * School of Computing, University of Utah, * Salt Lake City, UT 84112, USA * * and the Gauss Group * http://www.cs.utah.edu/formal_verification * * See LICENSE for licensing information */ #include <iostream> #include <sstream> #include <memory> #include <boost/range/adaptor/reversed.hpp> #include <boost/range/adaptor/indirected.hpp> #include "Trace.hpp" using boost::adaptors::reverse; using boost::adaptors::indirect; using std::make_shared; using std::move; using std::unique_ptr; bool Trace::add(std::unique_ptr<Envelope> env) { const int index = env->index; // check if already in the list if (index <= size() - 1) { // return true only when the envelopes match return trace[index]->getEnvelope() == *env; } // otherwise append to the list auto last_op = make_shared<Transition>(pid, size() - 1, move(env)); trace.push_back(last_op); auto env_t = last_op->getEnvelope(); bool blocking_flag = false; if (env_t.func_id == OpType::ISEND || env_t.func_id == OpType::IRECV) { ulist.push_back(last_op->index); } else if (env_t.func_id == OpType::WAIT || env_t.func_id == OpType::WAITALL || env_t.func_id == OpType::TEST || env_t.func_id == OpType::TESTALL) { for (auto & req : env_t.req_procs) { auto curr = trace[req]; if (curr->addIntraCB(last_op)) { last_op->addAncestor(curr); } ulist.remove(curr->index); } } int i = size() - 2; for (auto & curr : indirect(reverse())) { if (curr.getEnvelope().completesBefore(env_t)) { if (blocking_flag) { if (env_t.func_id != OpType::SEND && (ulist.size() == 0 || index < ulist.front())) { return true; } //if a blocking call occured in the past //the only calls that can slip through it are //Isend and Irecv auto env_f = curr.getEnvelope(); if (env_f.func_id == OpType::IRECV) { if (curr.addIntraCB(last_op)) { last_op->addAncestor(trace[i]); } //terminate if this satisfies the Irecv intraCB rule if (env_t.matchRecv(env_f)) { return true; } } else if (env_f.func_id == OpType::ISEND) { if (curr.addIntraCB(last_op)) { last_op->addAncestor(trace[i]); } //terminate if this satisfies the Isend intraCB rule if (env_t.matchSend(env_f)) { return true; } } } else { if (curr.addIntraCB(last_op)) { last_op->addAncestor(trace[i]); } /* avo 06/11/08 - trying not to add redundant edges */ //a blocking call occured earlier //to avoid unnecessary CB edges if (curr.getEnvelope().isBlockingType()) { blocking_flag = true; } } } i--; } return true; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright 2008, Daniel nnerby // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other 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 "pch.hpp" #include <core/Query/SortTracksWithData.h> #include <core/Library/Base.h> #include <core/config_format.h> #include <boost/algorithm/string.hpp> #include <core/xml/ParserNode.h> #include <core/xml/WriterNode.h> #include <core/LibraryTrack.h> #include <core/Common.h> using namespace musik::core; ////////////////////////////////////////// ///\brief ///Constructor ////////////////////////////////////////// Query::SortTracksWithData::SortTracksWithData(void) :clearedTrackResults(false) { } ////////////////////////////////////////// ///\brief ///Destructor ////////////////////////////////////////// Query::SortTracksWithData::~SortTracksWithData(void){ } ////////////////////////////////////////// ///\brief ///Executes the query, meaning id does all the querying to the database. ////////////////////////////////////////// bool Query::SortTracksWithData::ParseQuery(Library::Base *library,db::Connection &db){ // Create smart SQL statment std::string selectSQL("SELECT temp_track_sort.track_id "); std::string selectSQLTables("temp_track_sort JOIN tracks ON tracks.id=temp_track_sort.track_id "); std::string selectSQLSort; db::CachedStatement selectMetaKeyId("SELECT id FROM meta_keys WHERE name=?",db); // Check if it's a fixed field if(musik::core::Library::Base::IsStaticMetaKey(this->sortByMetaKey)){ selectSQL += ",tracks."+this->sortByMetaKey; selectSQLSort += (selectSQLSort.empty()?" ORDER BY tracks.":",tracks.") + this->sortByMetaKey; // Check if it's a special MTO (many to one relation) field }else if(musik::core::Library::Base::IsSpecialMTOMetaKey(this->sortByMetaKey) || musik::core::Library::Base::IsSpecialMTMMetaKey(this->sortByMetaKey)){ if(this->sortByMetaKey=="album"){ selectSQLTables += " LEFT OUTER JOIN albums ON albums.id=tracks.album_id "; selectSQL += ",albums.name"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY albums.sort_order":",albums.sort_order"); } if(this->sortByMetaKey=="visual_genre" || this->sortByMetaKey=="genre"){ selectSQLTables += " LEFT OUTER JOIN genres ON genres.id=tracks.visual_genre_id "; selectSQL += ",genres.name"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY genres.sort_order":",genres.sort_order"); } if(this->sortByMetaKey=="visual_artist" || this->sortByMetaKey=="artist"){ selectSQLTables += " LEFT OUTER JOIN artists ON artists.id=tracks.visual_artist_id"; selectSQL += ",artists.name"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY artists.sort_order":",artists.sort_order"); } } else { // Sort by metakeys table selectMetaKeyId.BindText(0,this->sortByMetaKey); if(selectMetaKeyId.Step()==db::Row){ selectSQLTables += " LEFT OUTER JOIN (SELECT track_meta.track_id,meta_values.content,meta_values.sort_order FROM track_meta,meta_values WHERE track_meta.meta_value_id=meta_values.id AND meta_values.meta_key_id="+boost::lexical_cast<std::string>(selectMetaKeyId.ColumnInt(0))+") the_meta ON the_meta.track_id=tracks.id "; selectSQL += ",the_meta.content"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY the_meta.sort_order":",the_meta.sort_order"); } selectMetaKeyId.Reset(); } // First lets start by inserting all tracks in a temporary table db.Execute("DROP TABLE IF EXISTS temp_track_sort"); db.Execute("CREATE TEMPORARY TABLE temp_track_sort (id INTEGER PRIMARY KEY AUTOINCREMENT,track_id INTEGER NOT NULL default 0)"); { db::Statement insertTracks("INSERT INTO temp_track_sort (track_id) VALUES (?)",db); for(int i(0);i<this->tracksToSort.size();++i){ DBINT track(this->tracksToSort[i]); insertTracks.BindInt(0,track); insertTracks.Step(); insertTracks.Reset(); insertTracks.UnBindAll(); } } // Finaly keep sort order of inserted order. selectSQLSort += ",temp_track_sort.id"; //////////////////////////////////////////////////////// // The main SQL query what this class is all about std::string sql=selectSQL+" FROM "+selectSQLTables+selectSQLSort; if(!library->QueryCanceled(this)){ db::Statement selectTracks(sql.c_str(),db); TrackWithSortdataVector tempTrackResults; int row(0); while(selectTracks.Step()==db::ReturnCode::Row){ TrackWithSortdata newSortData; newSortData.track.reset(new LibraryTrack(selectTracks.ColumnInt(0),library->Id())); newSortData.sortData = selectTracks.ColumnTextUTF(1); // Convert the content to lower if futher sorting need to be done boost::algorithm::to_lower(newSortData.sortData); tempTrackResults.push_back( newSortData ); // Each 100 result, lock the mutex and insert the results if( (++row)%100==0 ){ boost::mutex::scoped_lock lock(library->resultMutex); this->trackResults.insert(this->trackResults.end(),tempTrackResults.begin(),tempTrackResults.end()); tempTrackResults.clear(); } } // If there are any results not inserted, insert now if(!tempTrackResults.empty()){ boost::mutex::scoped_lock lock(library->resultMutex); this->trackResults.insert(this->trackResults.end(),tempTrackResults.begin(),tempTrackResults.end()); } // All done succesfully, return true return true; }else{ return false; } } ////////////////////////////////////////// ///\brief ///Copy a query /// ///\returns ///A shared_ptr to the Query::Base ////////////////////////////////////////// Query::Ptr Query::SortTracksWithData::copy() const{ Query::Ptr queryCopy(new Query::SortTracksWithData(*this)); queryCopy->PostCopy(); return queryCopy; } ////////////////////////////////////////// ///\brief ///Add a track (trackId) in for sorting ////////////////////////////////////////// void Query::SortTracksWithData::AddTrack(DBINT trackId){ this->tracksToSort.push_back(trackId); } ////////////////////////////////////////// ///\brief ///What metakey to sort by ////////////////////////////////////////// void Query::SortTracksWithData::SortByMetaKey(std::string metaKey){ this->sortByMetaKey = metaKey; } ////////////////////////////////////////// ///\brief ///If you are reusing the query, clear what tracks to sort by ////////////////////////////////////////// void Query::SortTracksWithData::ClearTracks(){ this->tracksToSort.clear(); } ////////////////////////////////////////// ///\brief ///Receive the query from XML /// ///\param queryNode ///Reference to query XML node /// ///The excpeted input format is like this: ///\code ///<query type="SortTracksWithData"> /// <tracks>1,3,5,7</tracks> ///</query> ///\endcode /// ///\returns ///true when successfully received ////////////////////////////////////////// bool Query::SortTracksWithData::ReceiveQuery(musik::core::xml::ParserNode &queryNode){ while( musik::core::xml::ParserNode node = queryNode.ChildNode() ){ if(node.Name()=="sortby"){ node.WaitForContent(); this->sortByMetaKey = node.Content(); } else if(node.Name()=="tracks"){ node.WaitForContent(); typedef std::vector<std::string> StringVector; StringVector values; try{ // lexical_cast can throw boost::algorithm::split(values,node.Content(),boost::algorithm::is_any_of(",")); for(StringVector::iterator value=values.begin();value!=values.end();++value){ this->tracksToSort.push_back( boost::lexical_cast<DBINT>(*value) ); } } catch(...){ return false; } } } return true; } ////////////////////////////////////////// ///\brief ///The name ("SortTracksWithData") of the query. ////////////////////////////////////////// std::string Query::SortTracksWithData::Name(){ return "SortTracksWithData"; } ////////////////////////////////////////// ///\brief ///Send the query to a musikServer ////////////////////////////////////////// bool Query::SortTracksWithData::SendQuery(musik::core::xml::WriterNode &queryNode){ { xml::WriterNode sortbyNode(queryNode,"sortby"); sortbyNode.Content() = this->sortByMetaKey; } { xml::WriterNode tracksNode(queryNode,"tracks"); for(IntVector::iterator trackId=this->tracksToSort.begin();trackId!=this->tracksToSort.end();++trackId){ if(!tracksNode.Content().empty()){ tracksNode.Content().append(","); } tracksNode.Content().append(boost::lexical_cast<std::string>(*trackId)); } } return true; } ////////////////////////////////////////// ///\brief ///Execute the callbacks. In this case the "TrackResults" signal ////////////////////////////////////////// bool Query::SortTracksWithData::RunCallbacks(Library::Base *library){ bool bReturn(false); TrackWithSortdataVector trackResultsCopy; { // Scope for swapping the results safely boost::mutex::scoped_lock lock(library->resultMutex); trackResultsCopy.swap(this->trackResults); } { boost::mutex::scoped_lock lock(library->libraryMutex); if( (this->status & Status::Ended)!=0){ // If the query is finished, this function should return true to report that it is finished. bReturn = true; } } // Check for Tracks if( !trackResultsCopy.empty() ){ // Call the slots this->TrackResults(&trackResultsCopy,!this->clearedTrackResults); if(!this->clearedTrackResults){ this->clearedTrackResults = true; } } return bReturn; } ////////////////////////////////////////// ///\brief ///Send the results to the client /// ///The expected output format is like this: ///\code /// <tracklist> /// <t id="1">thesortdata</t> /// <t id="2">thesortdata</t> /// <t id="5">thesortdata</t> /// </tracklist> ///\endcode /// ////////////////////////////////////////// bool Query::SortTracksWithData::SendResults(musik::core::xml::WriterNode &queryNode,Library::Base *library){ bool continueSending(true); while(continueSending && !library->QueryCanceled(this)){ TrackWithSortdataVector trackResultsCopy; { // Scope for swapping the results safely boost::mutex::scoped_lock lock(library->resultMutex); trackResultsCopy.swap(this->trackResults); } { boost::mutex::scoped_lock lock(library->libraryMutex); if( (this->status & Status::Ended)!=0){ // If the query is finished, stop sending continueSending = false; } } // Check for Tracks if( !trackResultsCopy.empty() && !library->QueryCanceled(this) ){ musik::core::xml::WriterNode tracklist(queryNode,"tracklist"); if(!this->clearedTrackResults){ tracklist.Attributes()["clear"] = "true"; this->clearedTrackResults = true; } for(TrackWithSortdataVector::iterator track=trackResultsCopy.begin();track!=trackResultsCopy.end();++track){ musik::core::xml::WriterNode trackNode(tracklist,"t"); trackNode.Attributes()["id"] = boost::lexical_cast<std::string>( track->track->Id() ); trackNode.Content() = UTF_TO_UTF8(track->sortData); } } if(continueSending){ if( trackResultsCopy.empty() ){ // Yield for more results boost::thread::yield(); } } } return true; } ////////////////////////////////////////// ///\brief ///Receive results from the musikServer. ////////////////////////////////////////// bool Query::SortTracksWithData::ReceiveResults(musik::core::xml::ParserNode &queryNode,Library::Base *library){ while( musik::core::xml::ParserNode node = queryNode.ChildNode() ){ typedef std::vector<std::string> StringVector; // Receive tracks if( node.Name()=="tracklist"){ while( musik::core::xml::ParserNode trackNode = node.ChildNode("t") ){ trackNode.WaitForContent(); DBINT trackId(boost::lexical_cast<DBINT>(trackNode.Attributes()["id"])); TrackWithSortdata newSortData; newSortData.track.reset(new LibraryTrack(trackId,library->Id())); newSortData.sortData = UTF8_TO_UTF(trackNode.Content()); { boost::mutex::scoped_lock lock(library->resultMutex); this->trackResults.push_back(newSortData); } } } } return true; } ////////////////////////////////////////// ///\brief ///Operator to be able to sort using the sortData ////////////////////////////////////////// bool Query::SortTracksWithData::TrackWithSortdata::operator<(const TrackWithSortdata &trackWithSortData) const{ return this->sortData < trackWithSortData.sortData; } <commit_msg>Small fix in query::SortTracksWithData to handle NULL values.<commit_after>////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright 2008, Daniel nnerby // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other 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 "pch.hpp" #include <core/Query/SortTracksWithData.h> #include <core/Library/Base.h> #include <core/config_format.h> #include <boost/algorithm/string.hpp> #include <core/xml/ParserNode.h> #include <core/xml/WriterNode.h> #include <core/LibraryTrack.h> #include <core/Common.h> using namespace musik::core; ////////////////////////////////////////// ///\brief ///Constructor ////////////////////////////////////////// Query::SortTracksWithData::SortTracksWithData(void) :clearedTrackResults(false) { } ////////////////////////////////////////// ///\brief ///Destructor ////////////////////////////////////////// Query::SortTracksWithData::~SortTracksWithData(void){ } ////////////////////////////////////////// ///\brief ///Executes the query, meaning id does all the querying to the database. ////////////////////////////////////////// bool Query::SortTracksWithData::ParseQuery(Library::Base *library,db::Connection &db){ // Create smart SQL statment std::string selectSQL("SELECT temp_track_sort.track_id "); std::string selectSQLTables("temp_track_sort JOIN tracks ON tracks.id=temp_track_sort.track_id "); std::string selectSQLSort; db::CachedStatement selectMetaKeyId("SELECT id FROM meta_keys WHERE name=?",db); // Check if it's a fixed field if(musik::core::Library::Base::IsStaticMetaKey(this->sortByMetaKey)){ selectSQL += ",tracks."+this->sortByMetaKey; selectSQLSort += (selectSQLSort.empty()?" ORDER BY tracks.":",tracks.") + this->sortByMetaKey; // Check if it's a special MTO (many to one relation) field }else if(musik::core::Library::Base::IsSpecialMTOMetaKey(this->sortByMetaKey) || musik::core::Library::Base::IsSpecialMTMMetaKey(this->sortByMetaKey)){ if(this->sortByMetaKey=="album"){ selectSQLTables += " LEFT OUTER JOIN albums ON albums.id=tracks.album_id "; selectSQL += ",albums.name"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY albums.sort_order":",albums.sort_order"); } if(this->sortByMetaKey=="visual_genre" || this->sortByMetaKey=="genre"){ selectSQLTables += " LEFT OUTER JOIN genres ON genres.id=tracks.visual_genre_id "; selectSQL += ",genres.name"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY genres.sort_order":",genres.sort_order"); } if(this->sortByMetaKey=="visual_artist" || this->sortByMetaKey=="artist"){ selectSQLTables += " LEFT OUTER JOIN artists ON artists.id=tracks.visual_artist_id"; selectSQL += ",artists.name"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY artists.sort_order":",artists.sort_order"); } } else { // Sort by metakeys table selectMetaKeyId.BindText(0,this->sortByMetaKey); if(selectMetaKeyId.Step()==db::Row){ selectSQLTables += " LEFT OUTER JOIN (SELECT track_meta.track_id,meta_values.content,meta_values.sort_order FROM track_meta,meta_values WHERE track_meta.meta_value_id=meta_values.id AND meta_values.meta_key_id="+boost::lexical_cast<std::string>(selectMetaKeyId.ColumnInt(0))+") the_meta ON the_meta.track_id=tracks.id "; selectSQL += ",the_meta.content"; selectSQLSort += (selectSQLSort.empty()?" ORDER BY the_meta.sort_order":",the_meta.sort_order"); } selectMetaKeyId.Reset(); } // First lets start by inserting all tracks in a temporary table db.Execute("DROP TABLE IF EXISTS temp_track_sort"); db.Execute("CREATE TEMPORARY TABLE temp_track_sort (id INTEGER PRIMARY KEY AUTOINCREMENT,track_id INTEGER NOT NULL default 0)"); { db::Statement insertTracks("INSERT INTO temp_track_sort (track_id) VALUES (?)",db); for(int i(0);i<this->tracksToSort.size();++i){ DBINT track(this->tracksToSort[i]); insertTracks.BindInt(0,track); insertTracks.Step(); insertTracks.Reset(); insertTracks.UnBindAll(); } } // Finaly keep sort order of inserted order. selectSQLSort += ",temp_track_sort.id"; //////////////////////////////////////////////////////// // The main SQL query what this class is all about std::string sql=selectSQL+" FROM "+selectSQLTables+selectSQLSort; if(!library->QueryCanceled(this)){ db::Statement selectTracks(sql.c_str(),db); TrackWithSortdataVector tempTrackResults; int row(0); while(selectTracks.Step()==db::ReturnCode::Row){ TrackWithSortdata newSortData; newSortData.track.reset(new LibraryTrack(selectTracks.ColumnInt(0),library->Id())); const utfchar* sortDataPtr = selectTracks.ColumnTextUTF(1); if(sortDataPtr){ newSortData.sortData = sortDataPtr; } // Convert the content to lower if futher sorting need to be done boost::algorithm::to_lower(newSortData.sortData); tempTrackResults.push_back( newSortData ); // Each 100 result, lock the mutex and insert the results if( (++row)%100==0 ){ boost::mutex::scoped_lock lock(library->resultMutex); this->trackResults.insert(this->trackResults.end(),tempTrackResults.begin(),tempTrackResults.end()); tempTrackResults.clear(); } } // If there are any results not inserted, insert now if(!tempTrackResults.empty()){ boost::mutex::scoped_lock lock(library->resultMutex); this->trackResults.insert(this->trackResults.end(),tempTrackResults.begin(),tempTrackResults.end()); } // All done succesfully, return true return true; }else{ return false; } } ////////////////////////////////////////// ///\brief ///Copy a query /// ///\returns ///A shared_ptr to the Query::Base ////////////////////////////////////////// Query::Ptr Query::SortTracksWithData::copy() const{ Query::Ptr queryCopy(new Query::SortTracksWithData(*this)); queryCopy->PostCopy(); return queryCopy; } ////////////////////////////////////////// ///\brief ///Add a track (trackId) in for sorting ////////////////////////////////////////// void Query::SortTracksWithData::AddTrack(DBINT trackId){ this->tracksToSort.push_back(trackId); } ////////////////////////////////////////// ///\brief ///What metakey to sort by ////////////////////////////////////////// void Query::SortTracksWithData::SortByMetaKey(std::string metaKey){ this->sortByMetaKey = metaKey; } ////////////////////////////////////////// ///\brief ///If you are reusing the query, clear what tracks to sort by ////////////////////////////////////////// void Query::SortTracksWithData::ClearTracks(){ this->tracksToSort.clear(); } ////////////////////////////////////////// ///\brief ///Receive the query from XML /// ///\param queryNode ///Reference to query XML node /// ///The excpeted input format is like this: ///\code ///<query type="SortTracksWithData"> /// <tracks>1,3,5,7</tracks> ///</query> ///\endcode /// ///\returns ///true when successfully received ////////////////////////////////////////// bool Query::SortTracksWithData::ReceiveQuery(musik::core::xml::ParserNode &queryNode){ while( musik::core::xml::ParserNode node = queryNode.ChildNode() ){ if(node.Name()=="sortby"){ node.WaitForContent(); this->sortByMetaKey = node.Content(); } else if(node.Name()=="tracks"){ node.WaitForContent(); typedef std::vector<std::string> StringVector; StringVector values; try{ // lexical_cast can throw boost::algorithm::split(values,node.Content(),boost::algorithm::is_any_of(",")); for(StringVector::iterator value=values.begin();value!=values.end();++value){ this->tracksToSort.push_back( boost::lexical_cast<DBINT>(*value) ); } } catch(...){ return false; } } } return true; } ////////////////////////////////////////// ///\brief ///The name ("SortTracksWithData") of the query. ////////////////////////////////////////// std::string Query::SortTracksWithData::Name(){ return "SortTracksWithData"; } ////////////////////////////////////////// ///\brief ///Send the query to a musikServer ////////////////////////////////////////// bool Query::SortTracksWithData::SendQuery(musik::core::xml::WriterNode &queryNode){ { xml::WriterNode sortbyNode(queryNode,"sortby"); sortbyNode.Content() = this->sortByMetaKey; } { xml::WriterNode tracksNode(queryNode,"tracks"); for(IntVector::iterator trackId=this->tracksToSort.begin();trackId!=this->tracksToSort.end();++trackId){ if(!tracksNode.Content().empty()){ tracksNode.Content().append(","); } tracksNode.Content().append(boost::lexical_cast<std::string>(*trackId)); } } return true; } ////////////////////////////////////////// ///\brief ///Execute the callbacks. In this case the "TrackResults" signal ////////////////////////////////////////// bool Query::SortTracksWithData::RunCallbacks(Library::Base *library){ bool bReturn(false); TrackWithSortdataVector trackResultsCopy; { // Scope for swapping the results safely boost::mutex::scoped_lock lock(library->resultMutex); trackResultsCopy.swap(this->trackResults); } { boost::mutex::scoped_lock lock(library->libraryMutex); if( (this->status & Status::Ended)!=0){ // If the query is finished, this function should return true to report that it is finished. bReturn = true; } } // Check for Tracks if( !trackResultsCopy.empty() ){ // Call the slots this->TrackResults(&trackResultsCopy,!this->clearedTrackResults); if(!this->clearedTrackResults){ this->clearedTrackResults = true; } } return bReturn; } ////////////////////////////////////////// ///\brief ///Send the results to the client /// ///The expected output format is like this: ///\code /// <tracklist> /// <t id="1">thesortdata</t> /// <t id="2">thesortdata</t> /// <t id="5">thesortdata</t> /// </tracklist> ///\endcode /// ////////////////////////////////////////// bool Query::SortTracksWithData::SendResults(musik::core::xml::WriterNode &queryNode,Library::Base *library){ bool continueSending(true); while(continueSending && !library->QueryCanceled(this)){ TrackWithSortdataVector trackResultsCopy; { // Scope for swapping the results safely boost::mutex::scoped_lock lock(library->resultMutex); trackResultsCopy.swap(this->trackResults); } { boost::mutex::scoped_lock lock(library->libraryMutex); if( (this->status & Status::Ended)!=0){ // If the query is finished, stop sending continueSending = false; } } // Check for Tracks if( !trackResultsCopy.empty() && !library->QueryCanceled(this) ){ musik::core::xml::WriterNode tracklist(queryNode,"tracklist"); if(!this->clearedTrackResults){ tracklist.Attributes()["clear"] = "true"; this->clearedTrackResults = true; } for(TrackWithSortdataVector::iterator track=trackResultsCopy.begin();track!=trackResultsCopy.end();++track){ musik::core::xml::WriterNode trackNode(tracklist,"t"); trackNode.Attributes()["id"] = boost::lexical_cast<std::string>( track->track->Id() ); trackNode.Content() = UTF_TO_UTF8(track->sortData); } } if(continueSending){ if( trackResultsCopy.empty() ){ // Yield for more results boost::thread::yield(); } } } return true; } ////////////////////////////////////////// ///\brief ///Receive results from the musikServer. ////////////////////////////////////////// bool Query::SortTracksWithData::ReceiveResults(musik::core::xml::ParserNode &queryNode,Library::Base *library){ while( musik::core::xml::ParserNode node = queryNode.ChildNode() ){ typedef std::vector<std::string> StringVector; // Receive tracks if( node.Name()=="tracklist"){ while( musik::core::xml::ParserNode trackNode = node.ChildNode("t") ){ trackNode.WaitForContent(); DBINT trackId(boost::lexical_cast<DBINT>(trackNode.Attributes()["id"])); TrackWithSortdata newSortData; newSortData.track.reset(new LibraryTrack(trackId,library->Id())); newSortData.sortData = UTF8_TO_UTF(trackNode.Content()); { boost::mutex::scoped_lock lock(library->resultMutex); this->trackResults.push_back(newSortData); } } } } return true; } ////////////////////////////////////////// ///\brief ///Operator to be able to sort using the sortData ////////////////////////////////////////// bool Query::SortTracksWithData::TrackWithSortdata::operator<(const TrackWithSortdata &trackWithSortData) const{ return this->sortData < trackWithSortData.sortData; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // 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 <Hect.h> using namespace hect; #include <catch.hpp> // Loads the asset at the given path and verifies that re-encoding and decoding // the asset results in equivalence for both binary and data encoding template <typename T> void testEncoding(const Path& assetPath) { Engine& engine = Engine::instance(); auto handle = engine.assetCache().getHandle<T>(assetPath); REQUIRE(handle); T& asset = *handle; // JSON DataValue dataValue; { DataValueEncoder encoder; encoder << asset; dataValue = *encoder.dataValues().begin(); } { T decodedAsset; DataValueDecoder decoder(dataValue, engine.assetCache()); decoder >> decodedAsset; INFO(assetPath.asString()); REQUIRE(asset == decodedAsset); } // Binary std::vector<uint8_t> data; { MemoryWriteStream stream(data); BinaryEncoder encoder(stream); encoder << asset; } { T decodedAsset; MemoryReadStream stream(data); BinaryDecoder decoder(stream, engine.assetCache()); decoder >> decodedAsset; INFO(assetPath.asString()); REQUIRE(asset == decodedAsset); } } const std::vector<Path> directoryPaths { "Hect/Rendering", "Hect/Scenes", "Hect/Shaders" }; // Loads all files of a certain extension and verifies that re-encoding and // decoding the asset results in equivalence for both binary and data encoding template <typename T> void testEncodingForExtension(const std::string& extension) { for (const Path& directoryPath : directoryPaths) { Engine& engine = Engine::instance(); FileSystem& fileSystem = engine.fileSystem(); for (const Path& filePath : fileSystem.filesInDirectory(directoryPath)) { if (filePath.extension() == extension) { testEncoding<T>(filePath); } } } } TEST_CASE("Decode and re-encode all built-in Hect materials", "[Encoding][Material]") { testEncodingForExtension<Material>("material"); } TEST_CASE("Decode and re-encode all built-in Hect meshes", "[Encoding][Mesh]") { testEncodingForExtension<Mesh>("mesh"); } TEST_CASE("Decode and re-encode all built-in Hect shaders", "[Encoding][Shader]") { testEncodingForExtension<Shader>("shader"); } TEST_CASE("Decode and re-encode built-in Hect textures", "[Encoding][Texture2]") { testEncodingForExtension<Texture2>("texture2"); } <commit_msg>Add materials path to encoding tests<commit_after>/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // 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 <Hect.h> using namespace hect; #include <catch.hpp> // Loads the asset at the given path and verifies that re-encoding and decoding // the asset results in equivalence for both binary and data encoding template <typename T> void testEncoding(const Path& assetPath) { Engine& engine = Engine::instance(); auto handle = engine.assetCache().getHandle<T>(assetPath); REQUIRE(handle); T& asset = *handle; // JSON DataValue dataValue; { DataValueEncoder encoder; encoder << asset; dataValue = *encoder.dataValues().begin(); } { T decodedAsset; DataValueDecoder decoder(dataValue, engine.assetCache()); decoder >> decodedAsset; INFO(assetPath.asString()); REQUIRE(asset == decodedAsset); } // Binary std::vector<uint8_t> data; { MemoryWriteStream stream(data); BinaryEncoder encoder(stream); encoder << asset; } { T decodedAsset; MemoryReadStream stream(data); BinaryDecoder decoder(stream, engine.assetCache()); decoder >> decodedAsset; INFO(assetPath.asString()); REQUIRE(asset == decodedAsset); } } const std::vector<Path> directoryPaths { "Hect/Materials", "Hect/Rendering", "Hect/Scenes", "Hect/Shaders" }; // Loads all files of a certain extension and verifies that re-encoding and // decoding the asset results in equivalence for both binary and data encoding template <typename T> void testEncodingForExtension(const std::string& extension) { for (const Path& directoryPath : directoryPaths) { Engine& engine = Engine::instance(); FileSystem& fileSystem = engine.fileSystem(); for (const Path& filePath : fileSystem.filesInDirectory(directoryPath)) { if (filePath.extension() == extension) { testEncoding<T>(filePath); } } } } TEST_CASE("Decode and re-encode all built-in Hect materials", "[Encoding][Material]") { testEncodingForExtension<Material>("material"); } TEST_CASE("Decode and re-encode all built-in Hect meshes", "[Encoding][Mesh]") { testEncodingForExtension<Mesh>("mesh"); } TEST_CASE("Decode and re-encode all built-in Hect shaders", "[Encoding][Shader]") { testEncodingForExtension<Shader>("shader"); } TEST_CASE("Decode and re-encode built-in Hect textures", "[Encoding][Texture2]") { testEncodingForExtension<Texture2>("texture2"); } <|endoftext|>
<commit_before>// Program.cpp (Oclgrind) // Copyright (c) 2013-2014, James Price and Simon McIntosh-Smith, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "common.h" #include <fstream> #include "llvm/Assembly/AssemblyAnnotationWriter.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Linker.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/system_error.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Scalar.h" #include <clang/CodeGen/CodeGenAction.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include "Kernel.h" #include "Program.h" #include "WorkItem.h" #define ENV_DUMP_SPIR "OCLGRIND_DUMP_SPIR" #define CL_DUMP_NAME "/tmp/oclgrind_%lX.cl" #define IR_DUMP_NAME "/tmp/oclgrind_%lX.s" #define BC_DUMP_NAME "/tmp/oclgrind_%lX.bc" #if defined(_WIN32) #define REMAP_DIR "Z:/remapped/" #else #define REMAP_DIR "/remapped/" #endif #define REMAP_INPUT "input.cl" #define CLC_H_PATH REMAP_DIR"clc.h" extern const char CLC_H_DATA[]; const char *EXTENSIONS[] = { "cl_khr_fp64", "cl_khr_3d_image_writes", "cl_khr_global_int32_base_atomics", "cl_khr_global_int32_extended_atomics", "cl_khr_local_int32_base_atomics", "cl_khr_local_int32_extended_atomics", "cl_khr_byte_addressable_store", }; using namespace oclgrind; using namespace std; Program::Program(llvm::Module *module) : m_module(module) { m_action = NULL; m_buildLog = ""; m_buildOptions = ""; m_buildStatus = CL_BUILD_SUCCESS; m_uid = generateUID(); } Program::Program(const string& source) { m_source = source; m_module = NULL; m_action = NULL; m_buildLog = ""; m_buildOptions = ""; m_buildStatus = CL_BUILD_NONE; m_uid = 0; } Program::~Program() { WorkItem::InterpreterCache::clear(m_uid); if (m_module) { delete m_module; } if (m_action) { delete m_action; } } bool Program::build(const char *options, list<Header> headers) { m_buildStatus = CL_BUILD_IN_PROGRESS; m_buildOptions = options ? options : ""; // Create build log m_buildLog = ""; llvm::raw_string_ostream buildLog(m_buildLog); // Do nothing if program was created with binary if (m_source.empty() && m_module) { m_buildStatus = CL_BUILD_SUCCESS; return true; } if (m_module) { delete m_module; m_module = NULL; WorkItem::InterpreterCache::clear(m_uid); } // Assign a new UID to this program m_uid = generateUID(); // Set compiler arguments vector<const char*> args; args.push_back("-cl-kernel-arg-info"); args.push_back("-triple"); args.push_back("spir64-unknown-unknown"); args.push_back("-g"); // Define extensions for (int i = 0; i < sizeof(EXTENSIONS)/sizeof(const char*); i++) { args.push_back("-D"); args.push_back(EXTENSIONS[i]); } // Disable optimizations by default due to bugs in Khronos SPIR generator bool optimize = false; args.push_back("-O0"); // Add OpenCL build options if (options) { char *_options = strdup(options); char *opt = strtok(_options, " "); while (opt) { // Ignore options that break PCH if (strcmp(opt, "-cl-fast-relaxed-math") != 0 && strcmp(opt, "-cl-single-precision-constant") != 0) { args.push_back(opt); // Check for optimization flags if (strncmp(opt, "-O", 2) == 0) { if (strcmp(opt, "-O0") == 0) { optimize = false; } else { optimize = true; } } } opt = strtok(NULL, " "); } } // Select precompiled header const char *pch = NULL; if (optimize) { pch = INSTALL_ROOT"/include/spirsim/clc.pch"; } else { pch = INSTALL_ROOT"/include/spirsim/clc.noopt.pch"; } // Use precompiled header if it exists, otherwise fall back to embedded clc.h ifstream pchfile(pch); if (pchfile.good()) { args.push_back("-include-pch"); args.push_back(pch); } else { args.push_back("-include"); args.push_back(CLC_H_PATH); buildLog << "WARNING: Unable to find precompiled header.\n"; } pchfile.close(); // Append input file to arguments (remapped later) args.push_back(REMAP_INPUT); // Create diagnostics engine clang::DiagnosticOptions *diagOpts = new clang::DiagnosticOptions(); llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID( new clang::DiagnosticIDs()); clang::TextDiagnosticPrinter diagConsumer(buildLog, diagOpts); clang::DiagnosticsEngine diags(diagID, diagOpts, &diagConsumer, false); // Create compiler invocation llvm::OwningPtr<clang::CompilerInvocation> invocation( new clang::CompilerInvocation); clang::CompilerInvocation::CreateFromArgs(*invocation, &args[0], &args[0] + args.size(), diags); // Create compiler instance clang::CompilerInstance compiler; compiler.setInvocation(invocation.take()); // Remap include files llvm::MemoryBuffer *buffer; compiler.getHeaderSearchOpts().AddPath(REMAP_DIR, clang::frontend::Quoted, false, false, false); list<Header>::iterator itr; for (itr = headers.begin(); itr != headers.end(); itr++) { buffer = llvm::MemoryBuffer::getMemBuffer(itr->second->m_source, "", false); compiler.getPreprocessorOpts().addRemappedFile(REMAP_DIR + itr->first, buffer); } // Remap clc.h buffer = llvm::MemoryBuffer::getMemBuffer(CLC_H_DATA, "", false); compiler.getPreprocessorOpts().addRemappedFile(CLC_H_PATH, buffer); // Remap input file buffer = llvm::MemoryBuffer::getMemBuffer(m_source, "", false); compiler.getPreprocessorOpts().addRemappedFile(REMAP_INPUT, buffer); // Prepare diagnostics compiler.createDiagnostics(args.size(), &args[0], &diagConsumer, false); if (!compiler.hasDiagnostics()) { m_buildStatus = CL_BUILD_ERROR; return false; } // Compile llvm::LLVMContext& context = llvm::getGlobalContext(); clang::CodeGenAction *action = new clang::EmitLLVMOnlyAction(&context); if (compiler.ExecuteAction(*action)) { // Retrieve module m_action = new llvm::OwningPtr<clang::CodeGenAction>(action); m_module = action->takeModule(); m_buildStatus = CL_BUILD_SUCCESS; } else { m_buildStatus = CL_BUILD_ERROR; } // Dump temps if required const char *dumpSpir = getenv(ENV_DUMP_SPIR); if (dumpSpir && strcmp(dumpSpir, "1") == 0) { // Temporary directory #if defined(_WIN32) const char *tmpdir = getenv("TEMP"); #else const char *tmpdir = "/tmp"; #endif // Construct unique output filenames size_t sz = snprintf(NULL, 0, "%s/oclgrind_%lX.XX", tmpdir, m_uid) + 1; char *tempCL = new char[sz]; char *tempIR = new char[sz]; char *tempBC = new char[sz]; sprintf(tempCL, "%s/oclgrind_%lX.cl", tmpdir, m_uid); sprintf(tempIR, "%s/oclgrind_%lX.ll", tmpdir, m_uid); sprintf(tempBC, "%s/oclgrind_%lX.bc", tmpdir, m_uid); // Dump source ofstream cl; cl.open(tempCL); cl << m_source; cl.close(); if (m_buildStatus == CL_BUILD_SUCCESS) { // Dump IR string err; llvm::raw_fd_ostream ir(tempIR, err); llvm::AssemblyAnnotationWriter asmWriter; m_module->print(ir, &asmWriter); ir.close(); // Dump bitcode llvm::raw_fd_ostream bc(tempBC, err); llvm::WriteBitcodeToFile(m_module, bc); bc.close(); } delete[] tempCL; delete[] tempIR; delete[] tempBC; } return m_buildStatus == CL_BUILD_SUCCESS; } Program* Program::createFromBitcode(const unsigned char *bitcode, size_t length) { // Load bitcode from file llvm::MemoryBuffer *buffer; llvm::StringRef data((const char*)bitcode, length); buffer = llvm::MemoryBuffer::getMemBuffer(data, "", false); if (!buffer) { return NULL; } // Parse bitcode into IR module llvm::LLVMContext& context = llvm::getGlobalContext(); llvm::Module *module = ParseBitcodeFile(buffer, context); if (!module) { return NULL; } return new Program(module); } Program* Program::createFromBitcodeFile(const string filename) { // Load bitcode from file llvm::OwningPtr<llvm::MemoryBuffer> buffer; if (llvm::MemoryBuffer::getFile(filename, buffer)) { return NULL; } // Parse bitcode into IR module llvm::LLVMContext& context = llvm::getGlobalContext(); llvm::Module *module = ParseBitcodeFile(buffer.get(), context); if (!module) { return NULL; } return new Program(module); } Program* Program::createFromPrograms(list<const Program*> programs) { llvm::LLVMContext& context = llvm::getGlobalContext(); llvm::Module *module = new llvm::Module("oclgrind_linked", context); llvm::Linker linker("oclgrind", module); // Link modules list<const Program*>::iterator itr; for (itr = programs.begin(); itr != programs.end(); itr++) { if (linker.LinkInModule(CloneModule((*itr)->m_module))) { return NULL; } } return new Program(linker.releaseModule()); } Kernel* Program::createKernel(const string name) { // Iterate over functions in module to find kernel llvm::Function *function = NULL; llvm::Module::iterator funcItr; for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++) { // Check kernel name if (funcItr->getName().str() != name) continue; function = funcItr; break; } if (function == NULL) { return NULL; } // Assign identifiers to unnamed temporaries llvm::FunctionPass *instNamer = llvm::createInstructionNamerPass(); instNamer->runOnFunction(*((llvm::Function*)function)); delete instNamer; try { return new Kernel(*this, function, m_module); } catch (FatalError& err) { cerr << endl << "OCLGRIND FATAL ERROR " << "(" << err.getFile() << ":" << err.getLine() << ")" << endl << err.what() << endl << "When creating kernel '" << name << "'" << endl; return NULL; } } unsigned char* Program::getBinary() const { if (!m_module) { return NULL; } std::string str; llvm::raw_string_ostream stream(str); llvm::WriteBitcodeToFile(m_module, stream); stream.str(); unsigned char *bitcode = new unsigned char[str.length()]; memcpy(bitcode, str.c_str(), str.length()); return bitcode; } size_t Program::getBinarySize() const { if (!m_module) { return 0; } std::string str; llvm::raw_string_ostream stream(str); llvm::WriteBitcodeToFile(m_module, stream); stream.str(); return str.length(); } const string& Program::getBuildLog() const { return m_buildLog; } const string& Program::getBuildOptions() const { return m_buildOptions; } unsigned int Program::getBuildStatus() const { return m_buildStatus; } unsigned long Program::generateUID() const { srand(now()); return rand(); } list<string> Program::getKernelNames() const { list<string> names; // Iterate over functions in module to find kernels unsigned int num = 0; llvm::Function *function = NULL; llvm::Module::iterator funcItr; for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++) { if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL) { names.push_back(funcItr->getName().str()); } } return names; } unsigned int Program::getNumKernels() const { assert(m_module != NULL); // Iterate over functions in module to find kernels unsigned int num = 0; llvm::Function *function = NULL; llvm::Module::iterator funcItr; for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++) { if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL) { num++; } } return num; } const string& Program::getSource() const { return m_source; } unsigned long Program::getUID() const { return m_uid; } <commit_msg>Use user-include syntax<commit_after>// Program.cpp (Oclgrind) // Copyright (c) 2013-2014, James Price and Simon McIntosh-Smith, // University of Bristol. All rights reserved. // // This program is provided under a three-clause BSD license. For full // license terms please see the LICENSE file distributed with this // source code. #include "common.h" #include <fstream> #include "llvm/Assembly/AssemblyAnnotationWriter.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Linker.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/system_error.h" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Transforms/Scalar.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "Kernel.h" #include "Program.h" #include "WorkItem.h" #define ENV_DUMP_SPIR "OCLGRIND_DUMP_SPIR" #define CL_DUMP_NAME "/tmp/oclgrind_%lX.cl" #define IR_DUMP_NAME "/tmp/oclgrind_%lX.s" #define BC_DUMP_NAME "/tmp/oclgrind_%lX.bc" #if defined(_WIN32) #define REMAP_DIR "Z:/remapped/" #else #define REMAP_DIR "/remapped/" #endif #define REMAP_INPUT "input.cl" #define CLC_H_PATH REMAP_DIR"clc.h" extern const char CLC_H_DATA[]; const char *EXTENSIONS[] = { "cl_khr_fp64", "cl_khr_3d_image_writes", "cl_khr_global_int32_base_atomics", "cl_khr_global_int32_extended_atomics", "cl_khr_local_int32_base_atomics", "cl_khr_local_int32_extended_atomics", "cl_khr_byte_addressable_store", }; using namespace oclgrind; using namespace std; Program::Program(llvm::Module *module) : m_module(module) { m_action = NULL; m_buildLog = ""; m_buildOptions = ""; m_buildStatus = CL_BUILD_SUCCESS; m_uid = generateUID(); } Program::Program(const string& source) { m_source = source; m_module = NULL; m_action = NULL; m_buildLog = ""; m_buildOptions = ""; m_buildStatus = CL_BUILD_NONE; m_uid = 0; } Program::~Program() { WorkItem::InterpreterCache::clear(m_uid); if (m_module) { delete m_module; } if (m_action) { delete m_action; } } bool Program::build(const char *options, list<Header> headers) { m_buildStatus = CL_BUILD_IN_PROGRESS; m_buildOptions = options ? options : ""; // Create build log m_buildLog = ""; llvm::raw_string_ostream buildLog(m_buildLog); // Do nothing if program was created with binary if (m_source.empty() && m_module) { m_buildStatus = CL_BUILD_SUCCESS; return true; } if (m_module) { delete m_module; m_module = NULL; WorkItem::InterpreterCache::clear(m_uid); } // Assign a new UID to this program m_uid = generateUID(); // Set compiler arguments vector<const char*> args; args.push_back("-cl-kernel-arg-info"); args.push_back("-triple"); args.push_back("spir64-unknown-unknown"); args.push_back("-g"); // Define extensions for (int i = 0; i < sizeof(EXTENSIONS)/sizeof(const char*); i++) { args.push_back("-D"); args.push_back(EXTENSIONS[i]); } // Disable optimizations by default due to bugs in Khronos SPIR generator bool optimize = false; args.push_back("-O0"); // Add OpenCL build options if (options) { char *_options = strdup(options); char *opt = strtok(_options, " "); while (opt) { // Ignore options that break PCH if (strcmp(opt, "-cl-fast-relaxed-math") != 0 && strcmp(opt, "-cl-single-precision-constant") != 0) { args.push_back(opt); // Check for optimization flags if (strncmp(opt, "-O", 2) == 0) { if (strcmp(opt, "-O0") == 0) { optimize = false; } else { optimize = true; } } } opt = strtok(NULL, " "); } } // Select precompiled header const char *pch = NULL; if (optimize) { pch = INSTALL_ROOT"/include/spirsim/clc.pch"; } else { pch = INSTALL_ROOT"/include/spirsim/clc.noopt.pch"; } // Use precompiled header if it exists, otherwise fall back to embedded clc.h ifstream pchfile(pch); if (pchfile.good()) { args.push_back("-include-pch"); args.push_back(pch); } else { args.push_back("-include"); args.push_back(CLC_H_PATH); buildLog << "WARNING: Unable to find precompiled header.\n"; } pchfile.close(); // Append input file to arguments (remapped later) args.push_back(REMAP_INPUT); // Create diagnostics engine clang::DiagnosticOptions *diagOpts = new clang::DiagnosticOptions(); llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID( new clang::DiagnosticIDs()); clang::TextDiagnosticPrinter diagConsumer(buildLog, diagOpts); clang::DiagnosticsEngine diags(diagID, diagOpts, &diagConsumer, false); // Create compiler invocation llvm::OwningPtr<clang::CompilerInvocation> invocation( new clang::CompilerInvocation); clang::CompilerInvocation::CreateFromArgs(*invocation, &args[0], &args[0] + args.size(), diags); // Create compiler instance clang::CompilerInstance compiler; compiler.setInvocation(invocation.take()); // Remap include files llvm::MemoryBuffer *buffer; compiler.getHeaderSearchOpts().AddPath(REMAP_DIR, clang::frontend::Quoted, false, false, false); list<Header>::iterator itr; for (itr = headers.begin(); itr != headers.end(); itr++) { buffer = llvm::MemoryBuffer::getMemBuffer(itr->second->m_source, "", false); compiler.getPreprocessorOpts().addRemappedFile(REMAP_DIR + itr->first, buffer); } // Remap clc.h buffer = llvm::MemoryBuffer::getMemBuffer(CLC_H_DATA, "", false); compiler.getPreprocessorOpts().addRemappedFile(CLC_H_PATH, buffer); // Remap input file buffer = llvm::MemoryBuffer::getMemBuffer(m_source, "", false); compiler.getPreprocessorOpts().addRemappedFile(REMAP_INPUT, buffer); // Prepare diagnostics compiler.createDiagnostics(args.size(), &args[0], &diagConsumer, false); if (!compiler.hasDiagnostics()) { m_buildStatus = CL_BUILD_ERROR; return false; } // Compile llvm::LLVMContext& context = llvm::getGlobalContext(); clang::CodeGenAction *action = new clang::EmitLLVMOnlyAction(&context); if (compiler.ExecuteAction(*action)) { // Retrieve module m_action = new llvm::OwningPtr<clang::CodeGenAction>(action); m_module = action->takeModule(); m_buildStatus = CL_BUILD_SUCCESS; } else { m_buildStatus = CL_BUILD_ERROR; } // Dump temps if required const char *dumpSpir = getenv(ENV_DUMP_SPIR); if (dumpSpir && strcmp(dumpSpir, "1") == 0) { // Temporary directory #if defined(_WIN32) const char *tmpdir = getenv("TEMP"); #else const char *tmpdir = "/tmp"; #endif // Construct unique output filenames size_t sz = snprintf(NULL, 0, "%s/oclgrind_%lX.XX", tmpdir, m_uid) + 1; char *tempCL = new char[sz]; char *tempIR = new char[sz]; char *tempBC = new char[sz]; sprintf(tempCL, "%s/oclgrind_%lX.cl", tmpdir, m_uid); sprintf(tempIR, "%s/oclgrind_%lX.ll", tmpdir, m_uid); sprintf(tempBC, "%s/oclgrind_%lX.bc", tmpdir, m_uid); // Dump source ofstream cl; cl.open(tempCL); cl << m_source; cl.close(); if (m_buildStatus == CL_BUILD_SUCCESS) { // Dump IR string err; llvm::raw_fd_ostream ir(tempIR, err); llvm::AssemblyAnnotationWriter asmWriter; m_module->print(ir, &asmWriter); ir.close(); // Dump bitcode llvm::raw_fd_ostream bc(tempBC, err); llvm::WriteBitcodeToFile(m_module, bc); bc.close(); } delete[] tempCL; delete[] tempIR; delete[] tempBC; } return m_buildStatus == CL_BUILD_SUCCESS; } Program* Program::createFromBitcode(const unsigned char *bitcode, size_t length) { // Load bitcode from file llvm::MemoryBuffer *buffer; llvm::StringRef data((const char*)bitcode, length); buffer = llvm::MemoryBuffer::getMemBuffer(data, "", false); if (!buffer) { return NULL; } // Parse bitcode into IR module llvm::LLVMContext& context = llvm::getGlobalContext(); llvm::Module *module = ParseBitcodeFile(buffer, context); if (!module) { return NULL; } return new Program(module); } Program* Program::createFromBitcodeFile(const string filename) { // Load bitcode from file llvm::OwningPtr<llvm::MemoryBuffer> buffer; if (llvm::MemoryBuffer::getFile(filename, buffer)) { return NULL; } // Parse bitcode into IR module llvm::LLVMContext& context = llvm::getGlobalContext(); llvm::Module *module = ParseBitcodeFile(buffer.get(), context); if (!module) { return NULL; } return new Program(module); } Program* Program::createFromPrograms(list<const Program*> programs) { llvm::LLVMContext& context = llvm::getGlobalContext(); llvm::Module *module = new llvm::Module("oclgrind_linked", context); llvm::Linker linker("oclgrind", module); // Link modules list<const Program*>::iterator itr; for (itr = programs.begin(); itr != programs.end(); itr++) { if (linker.LinkInModule(CloneModule((*itr)->m_module))) { return NULL; } } return new Program(linker.releaseModule()); } Kernel* Program::createKernel(const string name) { // Iterate over functions in module to find kernel llvm::Function *function = NULL; llvm::Module::iterator funcItr; for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++) { // Check kernel name if (funcItr->getName().str() != name) continue; function = funcItr; break; } if (function == NULL) { return NULL; } // Assign identifiers to unnamed temporaries llvm::FunctionPass *instNamer = llvm::createInstructionNamerPass(); instNamer->runOnFunction(*((llvm::Function*)function)); delete instNamer; try { return new Kernel(*this, function, m_module); } catch (FatalError& err) { cerr << endl << "OCLGRIND FATAL ERROR " << "(" << err.getFile() << ":" << err.getLine() << ")" << endl << err.what() << endl << "When creating kernel '" << name << "'" << endl; return NULL; } } unsigned char* Program::getBinary() const { if (!m_module) { return NULL; } std::string str; llvm::raw_string_ostream stream(str); llvm::WriteBitcodeToFile(m_module, stream); stream.str(); unsigned char *bitcode = new unsigned char[str.length()]; memcpy(bitcode, str.c_str(), str.length()); return bitcode; } size_t Program::getBinarySize() const { if (!m_module) { return 0; } std::string str; llvm::raw_string_ostream stream(str); llvm::WriteBitcodeToFile(m_module, stream); stream.str(); return str.length(); } const string& Program::getBuildLog() const { return m_buildLog; } const string& Program::getBuildOptions() const { return m_buildOptions; } unsigned int Program::getBuildStatus() const { return m_buildStatus; } unsigned long Program::generateUID() const { srand(now()); return rand(); } list<string> Program::getKernelNames() const { list<string> names; // Iterate over functions in module to find kernels unsigned int num = 0; llvm::Function *function = NULL; llvm::Module::iterator funcItr; for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++) { if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL) { names.push_back(funcItr->getName().str()); } } return names; } unsigned int Program::getNumKernels() const { assert(m_module != NULL); // Iterate over functions in module to find kernels unsigned int num = 0; llvm::Function *function = NULL; llvm::Module::iterator funcItr; for(funcItr = m_module->begin(); funcItr != m_module->end(); funcItr++) { if (funcItr->getCallingConv() == llvm::CallingConv::SPIR_KERNEL) { num++; } } return num; } const string& Program::getSource() const { return m_source; } unsigned long Program::getUID() const { return m_uid; } <|endoftext|>
<commit_before>#include "sequence/details/Utils.hpp" #include <cassert> #include <cmath> #include <cstring> #include <algorithm> #include <bitset> #include <set> #include <utility> #include "sequence/Tools.hpp" #include "sequence/details/Hash.hpp" #include "sequence/details/StringView.hpp" #include "sequence/details/StringUtils.hpp" namespace sequence { namespace details { #if defined(_WIN64) || defined(_WIN32) #define PATH_SEPARATOR '\\' #elif defined(__APPLE__) || defined(__linux) #define PATH_SEPARATOR '/' #else #error "Unexpected platform" #endif std::pair<CStringView, CStringView> getInternalPrefixAndSuffix(CStringView pattern) { assert(pattern.contains(PADDING_CHAR)); return std::make_pair(pattern.substr(0, pattern.indexOf(PADDING_CHAR)), pattern.substr(pattern.lastIndexOf(PADDING_CHAR) + 1)); } IndexParser::IndexParser(CStringView str) { for (const char c : str) { put(c); } } void IndexParser::put(const char c) { assert(isdigit(c)); const Index diff = c - '0'; overflowed |= index > (std::numeric_limits<uint32_t>::max() / 10); index *= 10; overflowed |= index > (std::numeric_limits<uint32_t>::max() - diff); index += diff; } std::vector<StringView> integerRanges(StringView view) { return ranges(view, [](const char c) { return isdigit(c); }); } void extractFileIndicesAndNormalize(StringView path, Indices &indices) { const auto npos = CStringView::npos; if (path.contains(PADDING_CHAR)) return;//we can't process file names that contain PADDING_CHAR indices.clear(); const size_t lastSeparator = path.lastIndexOf(PATH_SEPARATOR); const size_t fileIndex = lastSeparator == npos ? 0 : lastSeparator + 1; const size_t lastDot = path.lastIndexOf('.'); const char *lastDotPtr = lastDot == npos ? path.end() : path.begin() + lastDot; const std::vector<StringView> integers(integerRanges(path.substr(fileIndex))); for (StringView integer : integers) { if (integer.begin() > lastDotPtr) { continue; } IndexParser parser(integer); if (!parser.overflowed && (integer.size() < MAX_PADDING)) { indices.push_back(parser.index); memset(integer.ptr(), PADDING_CHAR, integer.size()); } } } void bake(Index value, StringView placeholder) { const auto pStart = placeholder.begin(); for (auto pEnd = placeholder.end(); pEnd != pStart;) { --pEnd; *pEnd = '0' + value % 10; value /= 10; } } std::vector<StringView> getPlaceholders(StringView pattern) { return ranges(pattern, [](char c) { return c == PADDING_CHAR; }); } std::vector<CStringView> getText(CStringView pattern) { return ranges(pattern, [](char c) { return c != PADDING_CHAR; }); } void bake(StringView pattern, size_t index, Index value) { const auto placeholders = getPlaceholders(pattern); assert(index < placeholders.size()); bake(value, placeholders[index]); } size_t estimateDistinctIndices(const Indices &indices) { constexpr size_t bits = 18; // 262 144 combinations, 32kiB constexpr size_t size = 1 << bits; constexpr uint32_t mask = size - 1; std::bitset<size> set; // this will consume size / 8 bytes for (const uint32_t value : indices) { set.set(hash(value) & mask); } return set.count(); } void Bucket::ingest(const Indices &indices) { if (columns.empty()) { columns.resize(indices.size()); } assert(columns.size() == indices.size()); for (size_t i = 0; i < indices.size(); ++i) { columns[i].push_back(indices[i]); } } bool Bucket::single() const { return !columns.empty() && columns[0].size() == 1; } bool Bucket::splittable() const { return columns.size() > 1 && columns[0].size() > 1; } void Bucket::split(size_t index, std::function<void(Bucket)> push) const { assert(index < columns.size()); const Indices &pivot = columns[index]; std::unordered_map<Index, Bucket> map; Indices tmp; assert(columns.size() > 0); tmp.reserve(columns.size() - 1); for (size_t row = 0; row < pivot.size(); ++row) { const Index pivotValue = pivot[row]; Bucket &reduced = map[pivotValue]; if (reduced.pattern.empty()) { reduced.pattern = pattern; bake(reduced.pattern, index, pivotValue); } tmp.clear(); for (size_t col = 0; col < columns.size(); ++col) { if (col != index) { tmp.push_back(columns[col][row]); } } reduced.ingest(tmp); } for (auto &pair : map) { push(std::move(pair.second)); } } void Bucket::flatten(std::function<void(Bucket)> push) const { assert(columns.size() > 0); for (size_t row = 0; row < columns[0].size(); ++row) { Bucket file(pattern); auto placeholders = getPlaceholders(file.pattern); for (size_t col = 0; col < columns.size(); ++col) { bake(columns[col][row], placeholders[col]); } push(std::move(file)); } } //////////////////////////////////////////////////////////////////////////////// SplitBucket::SplitBucket(Bucket &&bucket) { assert(!bucket.splittable()); pattern = std::move(bucket.pattern); assert(bucket.columns.size() <= 1); if (bucket.columns.size() == 1) { sortedIndices = std::move(bucket.columns[0]); std::sort(std::begin(sortedIndices), std::end(sortedIndices)); } } SplitBucket::SplitBucket(SplitBucket &a, SplitBucket &b) { assert(a.canMerge(b)); CStringView prefix, suffix; std::tie(prefix, suffix) = getInternalPrefixAndSuffix(a.pattern); pattern = concat(prefix, "#", suffix); sortedIndices = std::move(a.sortedIndices); sortedIndices.insert(std::end(sortedIndices), std::begin(b.sortedIndices), std::end(b.sortedIndices)); std::sort(std::begin(sortedIndices), std::end(sortedIndices)); } struct FakeSet { typedef Index value_type; bool isDisjoint = true; void push_back(const Index &) { isDisjoint = false; } }; bool SplitBucket::containsPadding() const { return CStringView(pattern).contains(PADDING_CHAR); } bool SplitBucket::canMerge(const SplitBucket &other) const { if (!containsPadding() || !other.containsPadding() || getInternalPrefixAndSuffix(pattern) != getInternalPrefixAndSuffix(other.pattern)) { return false; } FakeSet set; std::set_intersection(std::begin(sortedIndices), std::end(sortedIndices), std::begin(other.sortedIndices), std::end(other.sortedIndices), std::back_inserter(set)); return set.isDisjoint; } std::string SplitBucket::getBakedPattern(Index value) const { CStringView prefix, suffix; std::tie(prefix, suffix) = getInternalPrefixAndSuffix(pattern); const auto padding = pattern.size() - prefix.size() - suffix.size(); char buffer[10]; // 4,294,967,295 is 10 characters long maximum. StringView view(buffer, padding == 1 ? 1 + std::log10(value) : padding); bake(value, view); return concat(prefix, view, suffix); } char getStep(Indices sortedIndices) { bool minimum_step_set = false; size_t minimum_step = std::numeric_limits<char>::max(); if (sortedIndices.size() >= 2) { for (auto previous = std::begin(sortedIndices), next = std::next(previous); next != std::end(sortedIndices); ++previous, ++next) { assert(*next > *previous); const size_t diff = *next - *previous; if (diff < minimum_step) { minimum_step = diff; minimum_step_set = true; } } } assert(minimum_step <= std::numeric_limits<char>::max()); return minimum_step_set ? static_cast<char>(minimum_step) : -1; } template <typename Itr> Itr findRangeEnd(Itr first, Itr last, size_t step) { return std::adjacent_find(first, last, [step](const Index a, const Index b) { assert(b > a); return (b - a) != step; }); } void SplitBucket::pack() { step = getStep(sortedIndices); if (step > 0) { auto rangeStart = std::begin(sortedIndices); const auto end = std::end(sortedIndices); for (auto rangeEnd = findRangeEnd(rangeStart, end, step); rangeEnd != end; rangeEnd = findRangeEnd(rangeStart, end, step)) { ranges.emplace_back(*rangeStart, *rangeEnd); rangeStart = std::next(rangeEnd); } ranges.emplace_back(*rangeStart, sortedIndices.back()); sortedIndices.clear(); } } void SplitBucket::output(bool bakeSingleton, std::function<void(Item)> push) { if (ranges.size()) { // PACKED items for (const auto range : ranges) { if (range.start == range.end && bakeSingleton) { push(createSingleFile(getBakedPattern(range.start))); } else { push(createSequence(pattern, range.start, range.end, step)); } } } else { // INDICED items if (sortedIndices.size() > 1) { push(Item(pattern, std::move(sortedIndices))); } else if (sortedIndices.size() == 1) { // SINGLE items push(createSingleFile(getBakedPattern(sortedIndices[0]))); } else if (sortedIndices.empty()) { // SINGLE items push(createSingleFile(pattern)); } } } //////////////////////////////////////////////////////////////////////////////// Bucket &FileBucketizer::getOrAdd(CStringView bucket, uint32_t seed) { const uint32_t hashed = hash(bucket, seed); auto itr = hash_map.find(hashed); auto &vector = itr == hash_map.end() ? hash_map[hashed] : itr->second; for (auto &item : vector) { if (bucket == item.pattern) { return item; } } vector.emplace_back(bucket.toString()); return vector.back(); } Bucket &FileBucketizer::ingest(StringView filename) { extractFileIndicesAndNormalize(filename, tmp); auto &bucket = getOrAdd(filename, tmp.size()); bucket.ingest(tmp); return bucket; } std::vector<Bucket> FileBucketizer::transfer() { std::vector<Bucket> dst; for (auto &pair : hash_map) { auto &src = pair.second; std::move(std::begin(src), std::end(src), std::back_inserter(dst)); } hash_map.clear(); return dst; } } // namespace details } // namespace sequence <commit_msg>fix crash if bakesingletone true Signed-off-by: Viacheslav Yartsev <slava@ahead.io><commit_after>#include "sequence/details/Utils.hpp" #include <cassert> #include <cmath> #include <cstring> #include <algorithm> #include <bitset> #include <set> #include <utility> #include "sequence/Tools.hpp" #include "sequence/details/Hash.hpp" #include "sequence/details/StringView.hpp" #include "sequence/details/StringUtils.hpp" namespace sequence { namespace details { #if defined(_WIN64) || defined(_WIN32) #define PATH_SEPARATOR '\\' #elif defined(__APPLE__) || defined(__linux) #define PATH_SEPARATOR '/' #else #error "Unexpected platform" #endif std::pair<CStringView, CStringView> getInternalPrefixAndSuffix(CStringView pattern) { assert(pattern.contains(PADDING_CHAR)); return std::make_pair(pattern.substr(0, pattern.indexOf(PADDING_CHAR)), pattern.substr(pattern.lastIndexOf(PADDING_CHAR) + 1)); } IndexParser::IndexParser(CStringView str) { for (const char c : str) { put(c); } } void IndexParser::put(const char c) { assert(isdigit(c)); const Index diff = c - '0'; overflowed |= index > (std::numeric_limits<uint32_t>::max() / 10); index *= 10; overflowed |= index > (std::numeric_limits<uint32_t>::max() - diff); index += diff; } std::vector<StringView> integerRanges(StringView view) { return ranges(view, [](const char c) { return isdigit(c); }); } void extractFileIndicesAndNormalize(StringView path, Indices &indices) { const auto npos = CStringView::npos; if (path.contains(PADDING_CHAR)) return;//we can't process file names that contain PADDING_CHAR indices.clear(); const size_t lastSeparator = path.lastIndexOf(PATH_SEPARATOR); const size_t fileIndex = lastSeparator == npos ? 0 : lastSeparator + 1; const size_t lastDot = path.lastIndexOf('.'); const char *lastDotPtr = lastDot == npos ? path.end() : path.begin() + lastDot; const std::vector<StringView> integers(integerRanges(path.substr(fileIndex))); for (StringView integer : integers) { if (integer.begin() > lastDotPtr) { continue; } IndexParser parser(integer); if (!parser.overflowed && (integer.size() < MAX_PADDING)) { indices.push_back(parser.index); memset(integer.ptr(), PADDING_CHAR, integer.size()); } } } void bake(Index value, StringView placeholder) { const auto pStart = placeholder.begin(); for (auto pEnd = placeholder.end(); pEnd != pStart;) { --pEnd; *pEnd = '0' + value % 10; value /= 10; } } std::vector<StringView> getPlaceholders(StringView pattern) { return ranges(pattern, [](char c) { return c == PADDING_CHAR; }); } std::vector<CStringView> getText(CStringView pattern) { return ranges(pattern, [](char c) { return c != PADDING_CHAR; }); } void bake(StringView pattern, size_t index, Index value) { const auto placeholders = getPlaceholders(pattern); assert(index < placeholders.size()); bake(value, placeholders[index]); } size_t estimateDistinctIndices(const Indices &indices) { constexpr size_t bits = 18; // 262 144 combinations, 32kiB constexpr size_t size = 1 << bits; constexpr uint32_t mask = size - 1; std::bitset<size> set; // this will consume size / 8 bytes for (const uint32_t value : indices) { set.set(hash(value) & mask); } return set.count(); } void Bucket::ingest(const Indices &indices) { if (columns.empty()) { columns.resize(indices.size()); } assert(columns.size() == indices.size()); for (size_t i = 0; i < indices.size(); ++i) { columns[i].push_back(indices[i]); } } bool Bucket::single() const { return !columns.empty() && columns[0].size() == 1; } bool Bucket::splittable() const { return columns.size() > 1 && columns[0].size() > 1; } void Bucket::split(size_t index, std::function<void(Bucket)> push) const { assert(index < columns.size()); const Indices &pivot = columns[index]; std::unordered_map<Index, Bucket> map; Indices tmp; assert(columns.size() > 0); tmp.reserve(columns.size() - 1); for (size_t row = 0; row < pivot.size(); ++row) { const Index pivotValue = pivot[row]; Bucket &reduced = map[pivotValue]; if (reduced.pattern.empty()) { reduced.pattern = pattern; bake(reduced.pattern, index, pivotValue); } tmp.clear(); for (size_t col = 0; col < columns.size(); ++col) { if (col != index) { tmp.push_back(columns[col][row]); } } reduced.ingest(tmp); } for (auto &pair : map) { push(std::move(pair.second)); } } void Bucket::flatten(std::function<void(Bucket)> push) const { assert(columns.size() > 0); for (size_t row = 0; row < columns[0].size(); ++row) { Bucket file(pattern); auto placeholders = getPlaceholders(file.pattern); for (size_t col = 0; col < columns.size(); ++col) { bake(columns[col][row], placeholders[col]); } push(std::move(file)); } } //////////////////////////////////////////////////////////////////////////////// SplitBucket::SplitBucket(Bucket &&bucket) { assert(!bucket.splittable()); pattern = std::move(bucket.pattern); assert(bucket.columns.size() <= 1); if (bucket.columns.size() == 1) { sortedIndices = std::move(bucket.columns[0]); std::sort(std::begin(sortedIndices), std::end(sortedIndices)); } } SplitBucket::SplitBucket(SplitBucket &a, SplitBucket &b) { assert(a.canMerge(b)); CStringView prefix, suffix; std::tie(prefix, suffix) = getInternalPrefixAndSuffix(a.pattern); pattern = concat(prefix, "#", suffix); sortedIndices = std::move(a.sortedIndices); sortedIndices.insert(std::end(sortedIndices), std::begin(b.sortedIndices), std::end(b.sortedIndices)); std::sort(std::begin(sortedIndices), std::end(sortedIndices)); } struct FakeSet { typedef Index value_type; bool isDisjoint = true; void push_back(const Index &) { isDisjoint = false; } }; bool SplitBucket::containsPadding() const { return CStringView(pattern).contains(PADDING_CHAR); } bool SplitBucket::canMerge(const SplitBucket &other) const { if (!containsPadding() || !other.containsPadding() || getInternalPrefixAndSuffix(pattern) != getInternalPrefixAndSuffix(other.pattern)) { return false; } FakeSet set; std::set_intersection(std::begin(sortedIndices), std::end(sortedIndices), std::begin(other.sortedIndices), std::end(other.sortedIndices), std::back_inserter(set)); return set.isDisjoint; } std::string SplitBucket::getBakedPattern(Index value) const { CStringView prefix, suffix; std::tie(prefix, suffix) = getInternalPrefixAndSuffix(pattern); const auto padding = pattern.size() - prefix.size() - suffix.size(); char buffer[10]; // 4,294,967,295 is 10 characters long maximum. StringView view(buffer, padding == 1 ? 1 + std::log10(value >=1 ? value : 1) : padding); bake(value, view); return concat(prefix, view, suffix); } char getStep(Indices sortedIndices) { bool minimum_step_set = false; size_t minimum_step = std::numeric_limits<char>::max(); if (sortedIndices.size() >= 2) { for (auto previous = std::begin(sortedIndices), next = std::next(previous); next != std::end(sortedIndices); ++previous, ++next) { assert(*next > *previous); const size_t diff = *next - *previous; if (diff < minimum_step) { minimum_step = diff; minimum_step_set = true; } } } assert(minimum_step <= std::numeric_limits<char>::max()); return minimum_step_set ? static_cast<char>(minimum_step) : -1; } template <typename Itr> Itr findRangeEnd(Itr first, Itr last, size_t step) { return std::adjacent_find(first, last, [step](const Index a, const Index b) { assert(b > a); return (b - a) != step; }); } void SplitBucket::pack() { step = getStep(sortedIndices); if (step > 0) { auto rangeStart = std::begin(sortedIndices); const auto end = std::end(sortedIndices); for (auto rangeEnd = findRangeEnd(rangeStart, end, step); rangeEnd != end; rangeEnd = findRangeEnd(rangeStart, end, step)) { ranges.emplace_back(*rangeStart, *rangeEnd); rangeStart = std::next(rangeEnd); } ranges.emplace_back(*rangeStart, sortedIndices.back()); sortedIndices.clear(); } } void SplitBucket::output(bool bakeSingleton, std::function<void(Item)> push) { if (ranges.size()) { // PACKED items for (const auto range : ranges) { if (range.start == range.end && bakeSingleton) { push(createSingleFile(getBakedPattern(range.start))); } else { push(createSequence(pattern, range.start, range.end, step)); } } } else { // INDICED items if (sortedIndices.size() > 1) { push(Item(pattern, std::move(sortedIndices))); } else if (sortedIndices.size() == 1) { // SINGLE items push(createSingleFile(getBakedPattern(sortedIndices[0]))); } else if (sortedIndices.empty()) { // SINGLE items push(createSingleFile(pattern)); } } } //////////////////////////////////////////////////////////////////////////////// Bucket &FileBucketizer::getOrAdd(CStringView bucket, uint32_t seed) { const uint32_t hashed = hash(bucket, seed); auto itr = hash_map.find(hashed); auto &vector = itr == hash_map.end() ? hash_map[hashed] : itr->second; for (auto &item : vector) { if (bucket == item.pattern) { return item; } } vector.emplace_back(bucket.toString()); return vector.back(); } Bucket &FileBucketizer::ingest(StringView filename) { extractFileIndicesAndNormalize(filename, tmp); auto &bucket = getOrAdd(filename, tmp.size()); bucket.ingest(tmp); return bucket; } std::vector<Bucket> FileBucketizer::transfer() { std::vector<Bucket> dst; for (auto &pair : hash_map) { auto &src = pair.second; std::move(std::begin(src), std::end(src), std::back_inserter(dst)); } hash_map.clear(); return dst; } } // namespace details } // namespace sequence <|endoftext|>
<commit_before>#include "WirelessDiags.h" #include <linux/types.h> #include <sys/socket.h> // For sockets #include <fcntl.h> // For socket open #include <unistd.h> // For socket close #include <stdexcept> // For runtime_error #include <linux/wireless.h> // For wifi stats #include <sys/ioctl.h> // For comminication with the kernel #include <iostream> // For reading system info #include <fstream> // " #include <cstring> // For memset using namespace std; WirelessDiags::WirelessDiags( string name) { interfaceName = name; prev_total_bytes = 0; gettimeofday(&prev_time,NULL); // Set the prevtime to be the time this object was created using the default time zone calcBitRate(); // Initialize the previous byte counts } // Helper function to read the number of bytes sent and received over time to calculate // the current bitrate float WirelessDiags::calcBitRate() { // Path to the linux provided stats. These files are pointers to memory locations // and are not on disk. string receive_bytes_stat_path = "/sys/class/net/wlan1/statistics/rx_bytes"; string transmit_bytes_stat_path = "/sys/class/net/wlan1/statistics/tx_bytes"; // Open, read and close the bytes received and bytes sent file pointers. ifstream receive_bytes_stat, transmit_bytes_stat; // Throw an exception if there was a problem receive_bytes_stat.exceptions( std::ifstream::failbit | std::ifstream::badbit ); transmit_bytes_stat.exceptions( std::ifstream::failbit | std::ifstream::badbit ); // Open the files transmit_bytes_stat.open(transmit_bytes_stat_path.c_str()); receive_bytes_stat.open(receive_bytes_stat_path.c_str()); string receive_stat; getline(receive_bytes_stat,receive_stat); receive_bytes_stat.close(); string transmit_stat; getline(transmit_bytes_stat,transmit_stat); transmit_bytes_stat.close(); // Remember the total bytes transmitted so we can take the difference // between recordings at each time interval. prev_total_bytes = total_bytes; // Convert string to int string::size_type sz; // alias of size_t long int rx_bytes = stoi(receive_stat,&sz); long int tx_bytes = stoi(transmit_stat,&sz); // Get the total bytes transmitted and recevied. This is the total bandwidth used. total_bytes = rx_bytes + tx_bytes; // If we haven't set the value of the previous reading skip. This will never be zero since it is the number of // bytes sent and received since boot. if (prev_total_bytes == 0) return 0; // Get the bytes transmitted and received as a function of time. // This assumes the function is called using the sensor check function. // Perhaps this function should keep track of the time elapsed itself? struct timeval now; gettimeofday(&now, NULL); // compute the elapsed time in seconds with millisecond resolution double elapsedTime = (now.tv_sec - prev_time.tv_sec) * 1000.0; // sec to ms elapsedTime += (now.tv_usec - prev_time.tv_usec) / 1000.0; // us to ms // Now convert milliseconds to seconds elapsedTime *= 1000; // Remember when this was called so we can calculate the delay next // time it is called prev_time = now; float byte_rate = byte_rate = (total_bytes - prev_total_bytes)*1.0f/elapsedTime; // Rate in B/s return byte_rate; } WirelessInfo WirelessDiags::getInfo(){ WirelessInfo sigInfo; // Declare an iwreq (wireless interface request object) for use in IOCTL communication iwreq req; // Allocate space for the request object memset(&req, 0, sizeof(struct iwreq)); // Populate the interface name in the request object strcpy(req.ifr_name, interfaceName.c_str()); // Declare an iw_statistics object to store the IOCTL results in iw_statistics *stats; // Create socket through which to talk to the kernel int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // Allocate space for the iw_statistics object, point to it from the request, // and store the length of the object in the request. req.u.data.pointer = (iw_statistics *)malloc(sizeof(iw_statistics)); req.u.data.length = sizeof(iw_statistics); // Use IOCTL to request the wireless stats. If -1 there was an error. if(ioctl(sockfd, SIOCGIWSTATS, &req) == -1){ string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); // Throw an error throw runtime_error(errorMsg); return sigInfo; } else if(((iw_statistics *)req.u.data.pointer)->qual.updated & IW_QUAL_DBM){ // Opened the socket so read the data sigInfo.level = ((iw_statistics *)req.u.data.pointer)->qual.level - 256; sigInfo.quality=((iw_statistics *)req.u.data.pointer)->qual.qual; sigInfo.noise=((iw_statistics *)req.u.data.pointer)->qual.noise; } //SIOCGIWESSID for ssid char buffer[32]; memset(buffer, 0, 32); req.u.essid.pointer = buffer; req.u.essid.length = 32; //this will gather the SSID of the connected network if(ioctl(sockfd, SIOCGIWESSID, &req) == -1){ // There was an error throw an exception string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); throw runtime_error(errorMsg); } else { // Opened the socket so read the data memcpy(&sigInfo.ssid, req.u.essid.pointer, req.u.essid.length); memset(&sigInfo.ssid[req.u.essid.length],0,1); } //SIOCGIWRATE for bits/sec (convert to mbit) int bitrate=-1; //this will get the claimed bitrate of the link if(ioctl(sockfd, SIOCGIWRATE, &req) == -1){ // There was an error throw an exception string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); throw runtime_error(errorMsg); } else { // Opened the socket so read the data memcpy(&bitrate, &req.u.bitrate, sizeof(int)); sigInfo.bandwidthAvailable=bitrate/1000000; } //SIOCGIFHWADDR for mac addr ifreq req2; strcpy(req2.ifr_name, interfaceName.c_str()); //this will get the mac address of the interface if(ioctl(sockfd, SIOCGIFHWADDR, &req2) == -1){ // There was an error throw an exception string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); throw runtime_error(errorMsg); } else{ // Opened the socket so read the data sprintf(sigInfo.mac, "%.2X", (unsigned char)req2.ifr_hwaddr.sa_data[0]); for(int s=1; s<6; s++){ sprintf(sigInfo.mac+strlen(sigInfo.mac), ":%.2X", (unsigned char)req2.ifr_hwaddr.sa_data[s]); } } // We are done so clean up close(sockfd); sigInfo.bandwidthUsed = calcBitRate(); return sigInfo; } <commit_msg>Bug fix: have to divide not multiply to get seconds from milliseconds<commit_after>#include "WirelessDiags.h" #include <linux/types.h> #include <sys/socket.h> // For sockets #include <fcntl.h> // For socket open #include <unistd.h> // For socket close #include <stdexcept> // For runtime_error #include <linux/wireless.h> // For wifi stats #include <sys/ioctl.h> // For comminication with the kernel #include <iostream> // For reading system info #include <fstream> // " #include <cstring> // For memset using namespace std; WirelessDiags::WirelessDiags( string name) { interfaceName = name; prev_total_bytes = 0; gettimeofday(&prev_time,NULL); // Set the prevtime to be the time this object was created using the default time zone calcBitRate(); // Initialize the previous byte counts } // Helper function to read the number of bytes sent and received over time to calculate // the current bitrate float WirelessDiags::calcBitRate() { // Path to the linux provided stats. These files are pointers to memory locations // and are not on disk. string receive_bytes_stat_path = "/sys/class/net/wlan1/statistics/rx_bytes"; string transmit_bytes_stat_path = "/sys/class/net/wlan1/statistics/tx_bytes"; // Open, read and close the bytes received and bytes sent file pointers. ifstream receive_bytes_stat, transmit_bytes_stat; // Throw an exception if there was a problem receive_bytes_stat.exceptions( std::ifstream::failbit | std::ifstream::badbit ); transmit_bytes_stat.exceptions( std::ifstream::failbit | std::ifstream::badbit ); // Open the files transmit_bytes_stat.open(transmit_bytes_stat_path.c_str()); receive_bytes_stat.open(receive_bytes_stat_path.c_str()); string receive_stat; getline(receive_bytes_stat,receive_stat); receive_bytes_stat.close(); string transmit_stat; getline(transmit_bytes_stat,transmit_stat); transmit_bytes_stat.close(); // Remember the total bytes transmitted so we can take the difference // between recordings at each time interval. prev_total_bytes = total_bytes; // Convert string to int string::size_type sz; // alias of size_t long int rx_bytes = stoi(receive_stat,&sz); long int tx_bytes = stoi(transmit_stat,&sz); // Get the total bytes transmitted and recevied. This is the total bandwidth used. total_bytes = rx_bytes + tx_bytes; // If we haven't set the value of the previous reading skip. This will never be zero since it is the number of // bytes sent and received since boot. if (prev_total_bytes == 0) return 0; // Get the bytes transmitted and received as a function of time. // This assumes the function is called using the sensor check function. // Perhaps this function should keep track of the time elapsed itself? struct timeval now; gettimeofday(&now, NULL); // compute the elapsed time in seconds with millisecond resolution double elapsedTime = (now.tv_sec - prev_time.tv_sec) * 1000.0; // sec to ms elapsedTime += (now.tv_usec - prev_time.tv_usec) / 1000.0; // us to ms // Now convert milliseconds to seconds elapsedTime /= 1000; // Remember when this was called so we can calculate the delay next // time it is called prev_time = now; float byte_rate = byte_rate = (total_bytes - prev_total_bytes)*1.0f/elapsedTime; // Rate in B/s return byte_rate; } WirelessInfo WirelessDiags::getInfo(){ WirelessInfo sigInfo; // Declare an iwreq (wireless interface request object) for use in IOCTL communication iwreq req; // Allocate space for the request object memset(&req, 0, sizeof(struct iwreq)); // Populate the interface name in the request object strcpy(req.ifr_name, interfaceName.c_str()); // Declare an iw_statistics object to store the IOCTL results in iw_statistics *stats; // Create socket through which to talk to the kernel int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // Allocate space for the iw_statistics object, point to it from the request, // and store the length of the object in the request. req.u.data.pointer = (iw_statistics *)malloc(sizeof(iw_statistics)); req.u.data.length = sizeof(iw_statistics); // Use IOCTL to request the wireless stats. If -1 there was an error. if(ioctl(sockfd, SIOCGIWSTATS, &req) == -1){ string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); // Throw an error throw runtime_error(errorMsg); return sigInfo; } else if(((iw_statistics *)req.u.data.pointer)->qual.updated & IW_QUAL_DBM){ // Opened the socket so read the data sigInfo.level = ((iw_statistics *)req.u.data.pointer)->qual.level - 256; sigInfo.quality=((iw_statistics *)req.u.data.pointer)->qual.qual; sigInfo.noise=((iw_statistics *)req.u.data.pointer)->qual.noise; } //SIOCGIWESSID for ssid char buffer[32]; memset(buffer, 0, 32); req.u.essid.pointer = buffer; req.u.essid.length = 32; //this will gather the SSID of the connected network if(ioctl(sockfd, SIOCGIWESSID, &req) == -1){ // There was an error throw an exception string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); throw runtime_error(errorMsg); } else { // Opened the socket so read the data memcpy(&sigInfo.ssid, req.u.essid.pointer, req.u.essid.length); memset(&sigInfo.ssid[req.u.essid.length],0,1); } //SIOCGIWRATE for bits/sec (convert to mbit) int bitrate=-1; //this will get the claimed bitrate of the link if(ioctl(sockfd, SIOCGIWRATE, &req) == -1){ // There was an error throw an exception string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); throw runtime_error(errorMsg); } else { // Opened the socket so read the data memcpy(&bitrate, &req.u.bitrate, sizeof(int)); sigInfo.bandwidthAvailable=bitrate/1000000; } //SIOCGIFHWADDR for mac addr ifreq req2; strcpy(req2.ifr_name, interfaceName.c_str()); //this will get the mac address of the interface if(ioctl(sockfd, SIOCGIFHWADDR, &req2) == -1){ // There was an error throw an exception string errorMsg = "Unable to open ioctl socket for " + interfaceName + ": "+ string(strerror(errno)); throw runtime_error(errorMsg); } else{ // Opened the socket so read the data sprintf(sigInfo.mac, "%.2X", (unsigned char)req2.ifr_hwaddr.sa_data[0]); for(int s=1; s<6; s++){ sprintf(sigInfo.mac+strlen(sigInfo.mac), ":%.2X", (unsigned char)req2.ifr_hwaddr.sa_data[s]); } } // We are done so clean up close(sockfd); sigInfo.bandwidthUsed = calcBitRate(); return sigInfo; } <|endoftext|>
<commit_before>#include "Utils.hpp" #include <Log.hpp> #include <Mesh.hpp> #include <Model.hpp> #include <sstream> namespace Utils { std::string _mAssetPath; std::vector<std::string> _mAssetPaths; void SetAssetPath(const std::string& path) { //LogInfo("Setting Asset Path: %s\n", path.c_str()); _mAssetPath = path; _mAssetPaths.clear(); } std::string GetAssetPath() { return _mAssetPath; } std::vector<std::string> GetResourcePaths() { if (_mAssetPaths.empty()) { std::stringstream ss(GetAssetPath()); std::string path; while (std::getline(ss, path, ':')) { if (path.empty()) continue; if (path.back() != '/') path.push_back('/'); _mAssetPaths.push_back(path); } _mAssetPaths.push_back(""); reverse(_mAssetPaths.begin(), _mAssetPaths.end()); } return _mAssetPaths; } void CleanSlashes(std::string& path) { for (unsigned int i = 0; i < path.size(); ++i) { if (path[i] == '\\') { path[i] = '/'; } } } std::string GetBasename(std::string path) { CleanSlashes(path); size_t pivot = path.find_last_of('/'); return (pivot == std::string::npos ? std::string() : path.substr(pivot + 1)); } std::string GetDirname(std::string path) { CleanSlashes(path); size_t pivot = path.find_last_of('/'); return (pivot == std::string::npos ? "./" : path.substr(0, pivot)); } std::string GetExtension(std::string path) { size_t pivot = path.find_last_of('.'); return (pivot == std::string::npos ? std::string() : path.substr(pivot + 1)); } Mesh* Get2DMesh(glm::vec4 screenCords, glm::vec4 textureCords) { GLuint vbos[2]; GLuint vao; std::vector<glm::vec3> vertices = { { screenCords[2], screenCords[1], 0 }, { screenCords[2], screenCords[3], 0 }, { screenCords[0], screenCords[3], 0 }, { screenCords[2], screenCords[1], 0 }, { screenCords[0], screenCords[3], 0 }, { screenCords[0], screenCords[1], 0 } }; std::vector<glm::vec2> texCoords = { { textureCords[2], textureCords[3] }, { textureCords[2], textureCords[1] }, { textureCords[0], textureCords[1] }, { textureCords[2], textureCords[3] }, { textureCords[0], textureCords[1] }, { textureCords[0], textureCords[3] } }; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbos[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size() * 3, vertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(AttributeID::POSITION, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(AttributeID::POSITION); glBindBuffer(GL_ARRAY_BUFFER, vbos[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * texCoords.size() * 2, texCoords.data(), GL_STATIC_DRAW); glVertexAttribPointer(AttributeID::TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(AttributeID::TEXCOORD); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); Mesh* m = new Mesh(vao, 0, 0, 0, 0, {}); return m; // std::vector<glm::vec3> Vertices, {}, std::vector<glm::vec2> texCoords, {}, {} /* return new Mesh( { {screenCords[2], screenCords[1], 0}, {screenCords[2], screenCords[3], 0}, {screenCords[0], screenCords[3], 0}, {screenCords[2], screenCords[1], 0}, {screenCords[0], screenCords[3], 0}, {screenCords[0], screenCords[1], 0} }, {}, { {textureCords[2], textureCords[3]}, {textureCords[2], textureCords[1]}, {textureCords[0], textureCords[1]}, {textureCords[2], textureCords[3]}, {textureCords[0], textureCords[1]}, {textureCords[0], textureCords[3]} }, {}, {}); */ } } <commit_msg>fixed reverse to std::reverse.<commit_after>#include "Utils.hpp" #include <Log.hpp> #include <Mesh.hpp> #include <Model.hpp> #include <sstream> namespace Utils { std::string _mAssetPath; std::vector<std::string> _mAssetPaths; void SetAssetPath(const std::string& path) { //LogInfo("Setting Asset Path: %s\n", path.c_str()); _mAssetPath = path; _mAssetPaths.clear(); } std::string GetAssetPath() { return _mAssetPath; } std::vector<std::string> GetResourcePaths() { if (_mAssetPaths.empty()) { std::stringstream ss(GetAssetPath()); std::string path; while (std::getline(ss, path, ':')) { if (path.empty()) continue; if (path.back() != '/') path.push_back('/'); _mAssetPaths.push_back(path); } _mAssetPaths.push_back(""); std::reverse(_mAssetPaths.begin(), _mAssetPaths.end()); } return _mAssetPaths; } void CleanSlashes(std::string& path) { for (unsigned int i = 0; i < path.size(); ++i) { if (path[i] == '\\') { path[i] = '/'; } } } std::string GetBasename(std::string path) { CleanSlashes(path); size_t pivot = path.find_last_of('/'); return (pivot == std::string::npos ? std::string() : path.substr(pivot + 1)); } std::string GetDirname(std::string path) { CleanSlashes(path); size_t pivot = path.find_last_of('/'); return (pivot == std::string::npos ? "./" : path.substr(0, pivot)); } std::string GetExtension(std::string path) { size_t pivot = path.find_last_of('.'); return (pivot == std::string::npos ? std::string() : path.substr(pivot + 1)); } Mesh* Get2DMesh(glm::vec4 screenCords, glm::vec4 textureCords) { GLuint vbos[2]; GLuint vao; std::vector<glm::vec3> vertices = { { screenCords[2], screenCords[1], 0 }, { screenCords[2], screenCords[3], 0 }, { screenCords[0], screenCords[3], 0 }, { screenCords[2], screenCords[1], 0 }, { screenCords[0], screenCords[3], 0 }, { screenCords[0], screenCords[1], 0 } }; std::vector<glm::vec2> texCoords = { { textureCords[2], textureCords[3] }, { textureCords[2], textureCords[1] }, { textureCords[0], textureCords[1] }, { textureCords[2], textureCords[3] }, { textureCords[0], textureCords[1] }, { textureCords[0], textureCords[3] } }; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbos[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertices.size() * 3, vertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(AttributeID::POSITION, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(AttributeID::POSITION); glBindBuffer(GL_ARRAY_BUFFER, vbos[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * texCoords.size() * 2, texCoords.data(), GL_STATIC_DRAW); glVertexAttribPointer(AttributeID::TEXCOORD, 2, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(AttributeID::TEXCOORD); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); Mesh* m = new Mesh(vao, 0, 0, 0, 0, {}); return m; // std::vector<glm::vec3> Vertices, {}, std::vector<glm::vec2> texCoords, {}, {} /* return new Mesh( { {screenCords[2], screenCords[1], 0}, {screenCords[2], screenCords[3], 0}, {screenCords[0], screenCords[3], 0}, {screenCords[2], screenCords[1], 0}, {screenCords[0], screenCords[3], 0}, {screenCords[0], screenCords[1], 0} }, {}, { {textureCords[2], textureCords[3]}, {textureCords[2], textureCords[1]}, {textureCords[0], textureCords[1]}, {textureCords[2], textureCords[3]}, {textureCords[0], textureCords[1]}, {textureCords[0], textureCords[3]} }, {}, {}); */ } } <|endoftext|>
<commit_before> #include <stdio.h> #include <errno.h> #include <iostream> // for MakeDir #include <string> // for MakeDir #include <sys/stat.h> // for MakeDir #if defined _WIN32 || defined(__MINGW32__) #include "direct.h" #include <io.h> #endif // for directoruylistings #include <sys/types.h> #include <sys/dir.h> #include <vector> #include <iostream> #include <fstream> #include "Utils.h" Utils::Utils( void ) { } Utils::~Utils( void ) { } bool Utils::FileExists( std::string strPath ) { FILE * fp; fp = fopen( strPath.c_str(), "rb" ); if( fp ) { fclose( fp ); return true; } return false; } void Utils::FileCopy( std::string fromPath, std::string toPath ) { #define kCopyFileBufSize ((4096) * 64) // HACK: This will break on non-windows, but seems ok for now. //fromPath = Utils::SearchReplace( fromPath, "/", "\\" ); char buf[kCopyFileBufSize]; FILE * inf = fopen( fromPath.c_str(), "rb" ); if( !inf ) { std::cerr << "Unable to open source " << fromPath << " (to " << toPath << ")" << std::endl; return; } FILE * outf = fopen( toPath.c_str(), "wb" ); if( !outf ) { std::cerr << "Unable to open dest " << toPath << std::endl; fclose( inf ); return; }; size_t n = 0; do { n = fread( buf, 1, kCopyFileBufSize, inf ); fwrite( buf, n, 1, outf ); } while( n != 0 ); fclose( outf ); fclose( inf ); } #if defined _WIN32 || defined(__MINGW32__) #define OS_MKDIR( P, M ) \ _mkdir( P ) #else #define OS_MKDIR( P, M ) \ mkdir( P, M ) #endif void Utils::MakeDir( std::string path, int mode ) { // code swiped from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux size_t pre=0,pos; std::string dir; int mdret; if(path[path.size()-1]!='/'){ // force trailing / so we can handle everything in loop path+='/'; } while((pos=path.find_first_of('/',pre))!=std::string::npos){ dir=path.substr(0,pos++); pre=pos; if(dir.size()==0) continue; // if leading / first time is 0 length if((mdret=OS_MKDIR(dir.c_str(),mode)) && errno!=EEXIST){ return; // mdret; } } //return mdret; } bool Utils::DirectoryExists( std::string path ) { struct stat st; if( stat( path.c_str(), &st ) == 0 ) { if( st.st_mode & S_IFDIR != 0 ) { return true; } } return false; } void Utils::DirectoryListing( std::string directory, std::vector<std::string>& listing ) { listing.clear(); #ifdef WINDOWS HANDLE dir; WIN32_FIND_DATA file_data; if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE) return; /* No files found */ do { const std::string file_name = file_data.cFileName; const std::string full_file_name = directory + "/" + file_name; if (file_name[0] == '.') continue; //listing.push_back(full_file_name); listing.push_back(file_name); } while (FindNextFile(dir, &file_data)); FindClose(dir); #else DIR *dir; class dirent *ent; class stat st; dir = opendir(directory.c_str()); while ((ent = readdir(dir)) != NULL) { const std::string file_name = ent->d_name; const std::string full_file_name = directory + "/" + file_name; if (file_name[0] == '.') continue; if (stat(full_file_name.c_str(), &st) == -1) continue; //listing.push_back(full_file_name); listing.push_back(file_name); } closedir(dir); #endif } <commit_msg>Cleaning up llvm warnings/errors<commit_after> #include <stdio.h> #include <errno.h> #include <iostream> // for MakeDir #include <string> // for MakeDir #include <sys/stat.h> // for MakeDir #if defined _WIN32 || defined(__MINGW32__) #include "direct.h" #include <io.h> #endif // for directoruylistings #include <sys/types.h> #include <sys/dir.h> #include <vector> #include <iostream> #include <fstream> #include "Utils.h" Utils::Utils( void ) { } Utils::~Utils( void ) { } bool Utils::FileExists( std::string strPath ) { FILE * fp; fp = fopen( strPath.c_str(), "rb" ); if( fp ) { fclose( fp ); return true; } return false; } void Utils::FileCopy( std::string fromPath, std::string toPath ) { #define kCopyFileBufSize ((4096) * 64) // HACK: This will break on non-windows, but seems ok for now. //fromPath = Utils::SearchReplace( fromPath, "/", "\\" ); char buf[kCopyFileBufSize]; FILE * inf = fopen( fromPath.c_str(), "rb" ); if( !inf ) { std::cerr << "Unable to open source " << fromPath << " (to " << toPath << ")" << std::endl; return; } FILE * outf = fopen( toPath.c_str(), "wb" ); if( !outf ) { std::cerr << "Unable to open dest " << toPath << std::endl; fclose( inf ); return; }; size_t n = 0; do { n = fread( buf, 1, kCopyFileBufSize, inf ); fwrite( buf, n, 1, outf ); } while( n != 0 ); fclose( outf ); fclose( inf ); } #if defined _WIN32 || defined(__MINGW32__) #define OS_MKDIR( P, M ) \ _mkdir( P ) #else #define OS_MKDIR( P, M ) \ mkdir( P, M ) #endif void Utils::MakeDir( std::string path, int mode ) { // code swiped from http://stackoverflow.com/questions/675039/how-can-i-create-directory-tree-in-c-linux size_t pre=0,pos; std::string dir; int mdret; if(path[path.size()-1]!='/'){ // force trailing / so we can handle everything in loop path+='/'; } while((pos=path.find_first_of('/',pre))!=std::string::npos){ dir=path.substr(0,pos++); pre=pos; if(dir.size()==0) continue; // if leading / first time is 0 length if((mdret=OS_MKDIR(dir.c_str(),mode)) && errno!=EEXIST){ return; // mdret; } } //return mdret; } bool Utils::DirectoryExists( std::string path ) { struct stat st; if( stat( path.c_str(), &st ) == 0 ) { if( (st.st_mode & S_IFDIR) != 0 ) { return true; } } return false; } void Utils::DirectoryListing( std::string directory, std::vector<std::string>& listing ) { listing.clear(); #ifdef WINDOWS HANDLE dir; WIN32_FIND_DATA file_data; if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data)) == INVALID_HANDLE_VALUE) return; /* No files found */ do { const std::string file_name = file_data.cFileName; const std::string full_file_name = directory + "/" + file_name; if (file_name[0] == '.') continue; //listing.push_back(full_file_name); listing.push_back(file_name); } while (FindNextFile(dir, &file_data)); FindClose(dir); #else DIR *dir; class dirent *ent; class stat st; dir = opendir(directory.c_str()); while ((ent = readdir(dir)) != NULL) { const std::string file_name = ent->d_name; const std::string full_file_name = directory + "/" + file_name; if (file_name[0] == '.') continue; if (stat(full_file_name.c_str(), &st) == -1) continue; //listing.push_back(full_file_name); listing.push_back(file_name); } closedir(dir); #endif } <|endoftext|>
<commit_before>// Filename: IntValue.cpp #include "IntValue.h" #include <limits> // numeric_limits #include <stdexcept> // invalid_argument #include <typeinfo> // bad_cast #include "../bits/buffers.h" #include "../module/DistributedType.h" using namespace std; namespace bamboo { template<typename T> static inline bool within_limits(int64_t num) { return numeric_limits<T>::min() <= num && num <= numeric_limits<T>::max(); } template<typename T> static inline bool within_limits(uint64_t num) { return num <= numeric_limits<T>::max(); } IntValue::IntValue() { m_unsigned = 0; } IntValue::IntValue(int8_t num) { m_signed = num; } IntValue::IntValue(uint8_t num) { m_unsigned = num; } IntValue::IntValue(int16_t num) { m_signed = num; } IntValue::IntValue(uint16_t num) { m_unsigned = num; } IntValue::IntValue(int32_t num) { m_signed = num; } IntValue::IntValue(uint32_t num) { m_unsigned = num; } IntValue::IntValue(int64_t num) { m_signed = num; } IntValue::IntValue(uint64_t num) { m_unsigned = num; } // pack provides the packed data for the value in native endianness. // Throws: bad_cast vector<uint8_t> IntValue::pack(const DistributedType *type) const { if(type->get_subtype() > kTypeChar) { throw invalid_argument("can't pack integer value as non-integer type."); } switch(type->get_size()) { case sizeof(uint8_t): return as_buffer(uint8_t(m_unsigned)); case sizeof(uint16_t): return as_buffer(uint16_t(m_unsigned)); case sizeof(uint32_t): return as_buffer(uint32_t(m_unsigned)); case sizeof(uint64_t): return as_buffer(uint64_t(m_unsigned)); default: throw invalid_argument("integer type has an invalid bytesize."); } } void IntValue::pack(const DistributedType *type, vector<uint8_t>& buf) const { if(type->get_subtype() > kTypeChar) { throw invalid_argument("can't pack integer value as non-integer type."); } switch(type->get_size()) { case sizeof(uint8_t): pack_value(uint8_t(m_unsigned), buf); case sizeof(uint16_t): pack_value(uint16_t(m_unsigned), buf); case sizeof(uint32_t): pack_value(uint32_t(m_unsigned), buf); case sizeof(uint64_t): pack_value(uint64_t(m_unsigned), buf); default: throw invalid_argument("integer type has an invalid bytesize."); } } char IntValue::as_char() const { if(!within_limits<char>(m_signed)) { throw bad_cast(); } return m_signed; } int8_t IntValue::as_int8() const { if(!within_limits<int8_t>(m_signed)) { throw bad_cast(); } return m_signed; } int16_t IntValue::as_int16() const { if(!within_limits<int16_t>(m_signed)) { throw bad_cast(); } return m_signed; } int32_t IntValue::as_int32() const { if(!within_limits<int32_t>(m_signed)) { throw bad_cast(); } return m_signed; } int64_t IntValue::as_int64() const { if(!within_limits<int64_t>(m_signed)) { throw bad_cast(); } return m_signed; } uint8_t IntValue::as_uint8() const { if(!within_limits<uint8_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } uint16_t IntValue::as_uint16() const { if(!within_limits<uint16_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } uint32_t IntValue::as_uint32() const { if(!within_limits<uint32_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } uint64_t IntValue::as_uint64() const { if(!within_limits<uint64_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } } // close namespace bamboo <commit_msg>Bugfix: Add missing break statements in IntValue.cpp<commit_after>// Filename: IntValue.cpp #include "IntValue.h" #include <limits> // numeric_limits #include <stdexcept> // invalid_argument #include <typeinfo> // bad_cast #include "../bits/buffers.h" #include "../module/DistributedType.h" using namespace std; namespace bamboo { template<typename T> static inline bool within_limits(int64_t num) { return numeric_limits<T>::min() <= num && num <= numeric_limits<T>::max(); } template<typename T> static inline bool within_limits(uint64_t num) { return num <= numeric_limits<T>::max(); } IntValue::IntValue() { m_unsigned = 0; } IntValue::IntValue(int8_t num) { m_signed = num; } IntValue::IntValue(uint8_t num) { m_unsigned = num; } IntValue::IntValue(int16_t num) { m_signed = num; } IntValue::IntValue(uint16_t num) { m_unsigned = num; } IntValue::IntValue(int32_t num) { m_signed = num; } IntValue::IntValue(uint32_t num) { m_unsigned = num; } IntValue::IntValue(int64_t num) { m_signed = num; } IntValue::IntValue(uint64_t num) { m_unsigned = num; } // pack provides the packed data for the value in native endianness. // Throws: bad_cast vector<uint8_t> IntValue::pack(const DistributedType *type) const { if(type->get_subtype() > kTypeChar) { throw invalid_argument("can't pack integer value as non-integer type."); } switch(type->get_size()) { case sizeof(uint8_t): return as_buffer(uint8_t(m_unsigned)); case sizeof(uint16_t): return as_buffer(uint16_t(m_unsigned)); case sizeof(uint32_t): return as_buffer(uint32_t(m_unsigned)); case sizeof(uint64_t): return as_buffer(uint64_t(m_unsigned)); default: throw invalid_argument("integer type has an invalid bytesize."); } } void IntValue::pack(const DistributedType *type, vector<uint8_t>& buf) const { if(type->get_subtype() > kTypeChar) { throw invalid_argument("can't pack integer value as non-integer type."); } switch(type->get_size()) { case sizeof(uint8_t): pack_value(uint8_t(m_unsigned), buf); break; case sizeof(uint16_t): pack_value(uint16_t(m_unsigned), buf); break; case sizeof(uint32_t): pack_value(uint32_t(m_unsigned), buf); break; case sizeof(uint64_t): pack_value(uint64_t(m_unsigned), buf); break; default: throw invalid_argument("integer type has an invalid bytesize."); } } char IntValue::as_char() const { if(!within_limits<char>(m_signed)) { throw bad_cast(); } return m_signed; } int8_t IntValue::as_int8() const { if(!within_limits<int8_t>(m_signed)) { throw bad_cast(); } return m_signed; } int16_t IntValue::as_int16() const { if(!within_limits<int16_t>(m_signed)) { throw bad_cast(); } return m_signed; } int32_t IntValue::as_int32() const { if(!within_limits<int32_t>(m_signed)) { throw bad_cast(); } return m_signed; } int64_t IntValue::as_int64() const { if(!within_limits<int64_t>(m_signed)) { throw bad_cast(); } return m_signed; } uint8_t IntValue::as_uint8() const { if(!within_limits<uint8_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } uint16_t IntValue::as_uint16() const { if(!within_limits<uint16_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } uint32_t IntValue::as_uint32() const { if(!within_limits<uint32_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } uint64_t IntValue::as_uint64() const { if(!within_limits<uint64_t>(m_unsigned)) { throw bad_cast(); } return m_unsigned; } } // close namespace bamboo <|endoftext|>
<commit_before>/** * \file stereoCalibPrep.cpp * * \date Aug 6, 2013 * \author Michał Orynicz */ #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include "Catcher.hpp" #include "ConvenienceFunctions.hpp" const int USER_TRIGGERED_EXIT = 0; void parseCommandline(const int &argc, char **argv, std::string &target, int &leftCapture, int &rightCapture) { boost::program_options::options_description desc; desc.add_options()("help,h", "this help message")("left,l", boost::program_options::value<int>(), "number of /dev/videoX device used as left camera")( "right,r", boost::program_options::value<int>(), "number of /dev/videoX device used as left camera")( "output,o", boost::program_options::value<std::string>(), "output file for list of pictures"); boost::program_options::variables_map vm; boost::program_options::store( boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; throw USER_TRIGGERED_EXIT; } if (vm.count("left")) { leftCapture = vm["left"].as<int>(); } if (vm.count("right")) { rightCapture = vm["right"].as<int>(); } if (vm.count("output")) { target = vm["output"].as<std::string>(); } } int main(int argc, char **argv) { std::string target; int leftDevice; int rightDevice; Catcher leftCapture; Catcher rightCapture; parseCommandline(argc, argv, target, leftDevice, rightDevice); leftCapture.open(leftDevice); rightCapture.open(rightDevice); cv::Size imageSize(leftCapture.get(cv::CAP_PROP_FRAME_WIDTH), leftCapture.get(cv::CAP_PROP_FRAME_HEIGHT)); cv::Mat display(imageSize.height, imageSize.width * 2, CV_8UC3); char c = ' '; cv::Rect leftRoi(cv::Point(imageSize.width, 0), imageSize); cv::Rect rightRoi(cv::Point(0, 0), imageSize); std::cerr << imageSize << std::endl; std::cerr << display.size() << std::endl; std::cerr << leftRoi << std::endl; std::cerr << rightRoi << std::endl; cv::namedWindow("main", cv::WINDOW_NORMAL); cv::FileStorage fs(target + "/imageList.xml", cv::FileStorage::WRITE); if (!fs.isOpened()) { cv::Exception ex(-1, "Could not open FileStorage", __func__, __FILE__, __LINE__); } fs << "images" << "["; int counter = 0; int delay = 300; int dc = 0; do { cv::Mat tL; cv::Mat tR; cv::Mat l = display(leftRoi); cv::Mat r = display(rightRoi); // leftCapture.grab(); // rightCapture.grab(); // leftCapture.retrieve(tL); // rightCapture.retrieve(tR); leftCapture>>tL; rightCapture>>tR; tL.copyTo(l); tR.copyTo(r); imshow("main", display); c = cv::waitKey(1); if (dc >= delay) { std::string leftPath = target + "/left" + std::to_string(counter) + ".png"; std::string rightPath = target + "/right" + std::to_string(counter) + ".png"; cv::imwrite(leftPath, l); cv::imwrite(rightPath, r); fs << leftPath; fs << rightPath; std::cerr << ++counter << std::endl; dc = 0; } ++dc; } while ('q' != c); fs << "]"; fs.release(); } <commit_msg>Removed Catcher as it generated unnecesairy issues<commit_after>/** * \file stereoCalibPrep.cpp * * \date Aug 6, 2013 * \author Michał Orynicz */ #include <boost/program_options.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <string> #include <iostream> #include "ConvenienceFunctions.hpp" const int USER_TRIGGERED_EXIT = 0; void parseCommandline(const int &argc, char **argv, std::string &target, int &leftCapture, int &rightCapture) { boost::program_options::options_description desc; desc.add_options()("help,h", "this help message")("left,l", boost::program_options::value<int>(), "number of /dev/videoX device used as left camera")( "right,r", boost::program_options::value<int>(), "number of /dev/videoX device used as left camera")( "output,o", boost::program_options::value<std::string>(), "output file for list of pictures"); boost::program_options::variables_map vm; boost::program_options::store( boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; throw USER_TRIGGERED_EXIT; } if (vm.count("left")) { leftCapture = vm["left"].as<int>(); } if (vm.count("right")) { rightCapture = vm["right"].as<int>(); } if (vm.count("output")) { target = vm["output"].as<std::string>(); } } int main(int argc, char **argv) { std::string target; int leftDevice; int rightDevice; cv::VideoCapture leftCapture; cv::VideoCapture rightCapture; parseCommandline(argc, argv, target, leftDevice, rightDevice); leftCapture.open(leftDevice); if (!leftCapture.isOpened()) { cv::Exception ex(0, "Didn't open device left", __func__, __FILE__, __LINE__); throw ex; } rightCapture.open(rightDevice); if (!rightCapture.isOpened()) { cv::Exception ex(0, "Didn't open device rightCapture", __func__, __FILE__, __LINE__); throw ex; } cv::Size imageSize(leftCapture.get(CV_CAP_PROP_FRAME_WIDTH), leftCapture.get(CV_CAP_PROP_FRAME_HEIGHT)); cv::Mat display(imageSize.height, imageSize.width * 2, CV_8UC3); char c = ' '; cv::Rect leftRoi(cv::Point(imageSize.width, 0), imageSize); cv::Rect rightRoi(cv::Point(0, 0), imageSize); std::cerr << imageSize << std::endl; std::cerr << display.size() << std::endl; std::cerr << leftRoi << std::endl; std::cerr << rightRoi << std::endl; cv::namedWindow("main", cv::WINDOW_NORMAL); cv::FileStorage fs(target + "/imageList.xml", cv::FileStorage::WRITE); if (!fs.isOpened()) { cv::Exception ex(-1, "Could not open FileStorage", __func__, __FILE__, __LINE__); } fs << "images" << "["; int counter = 0; int delay = 300; int dc = 0; cv::waitKey(1000); do { std::vector<cv::Mat> tmp(2); cv::Mat l = display(leftRoi); cv::Mat r = display(rightRoi); leftCapture.grab(); rightCapture.grab(); leftCapture.retrieve(tmp[0]); rightCapture.retrieve(tmp[1]); tmp[0].copyTo(l); tmp[1].copyTo(r); cv::imshow("main", display); c = cv::waitKey(1); if (dc >= delay) { std::string leftPath = target + "/left" + std::to_string(counter) + ".png"; std::string rightPath = target + "/right" + std::to_string(counter) + ".png"; cv::imwrite(leftPath, l); cv::imwrite(rightPath, r); fs << leftPath; fs << rightPath; dc = 0; } ++dc; } while ('q' != c); fs << "]"; fs.release(); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/transactionfilterproxy.h> #include <qt/transactiontablemodel.h> #include <qt/transactionrecord.h> #include <cstdlib> // Earliest date that can be represented (far in the past) const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0); // Last date that can be represented (far in the future) const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF); TransactionFilterProxy::TransactionFilterProxy(QObject *parent) : QSortFilterProxyModel(parent), dateFrom(MIN_DATE), dateTo(MAX_DATE), m_search_string(), typeFilter(ALL_TYPES), watchOnlyFilter(WatchOnlyFilter_All), minAmount(0), limitRows(-1), showInactive(true) { } bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); int type = index.data(TransactionTableModel::TypeRole).toInt(); QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime(); bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool(); QString address = index.data(TransactionTableModel::AddressRole).toString(); QString label = index.data(TransactionTableModel::LabelRole).toString(); QString txid = index.data(TransactionTableModel::TxHashRole).toString(); qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong()); int status = index.data(TransactionTableModel::StatusRole).toInt(); if(!showInactive && status == TransactionStatus::Conflicted) return false; if(!(TYPE(type) & typeFilter)) return false; if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No) return false; if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes) return false; if(datetime < dateFrom || datetime > dateTo) return false; if (!address.contains(m_search_string, Qt::CaseInsensitive) && ! label.contains(m_search_string, Qt::CaseInsensitive) && ! txid.contains(m_search_string, Qt::CaseInsensitive)) { return false; } if(amount < minAmount) return false; return true; } void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to) { this->dateFrom = from; this->dateTo = to; invalidateFilter(); } void TransactionFilterProxy::setSearchString(const QString &search_string) { if (m_search_string == search_string) return; m_search_string = search_string; invalidateFilter(); } void TransactionFilterProxy::setTypeFilter(quint32 modes) { this->typeFilter = modes; invalidateFilter(); } void TransactionFilterProxy::setMinAmount(const CAmount& minimum) { this->minAmount = minimum; invalidateFilter(); } void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter) { this->watchOnlyFilter = filter; invalidateFilter(); } void TransactionFilterProxy::setLimit(int limit) { this->limitRows = limit; } void TransactionFilterProxy::setShowInactive(bool _showInactive) { this->showInactive = _showInactive; invalidateFilter(); } int TransactionFilterProxy::rowCount(const QModelIndex &parent) const { if(limitRows != -1) { return std::min(QSortFilterProxyModel::rowCount(parent), limitRows); } else { return QSortFilterProxyModel::rowCount(parent); } } <commit_msg>qt: Avoid querying unnecessary model data when filtering transactions<commit_after>// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/transactionfilterproxy.h> #include <qt/transactiontablemodel.h> #include <qt/transactionrecord.h> #include <cstdlib> // Earliest date that can be represented (far in the past) const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0); // Last date that can be represented (far in the future) const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF); TransactionFilterProxy::TransactionFilterProxy(QObject *parent) : QSortFilterProxyModel(parent), dateFrom(MIN_DATE), dateTo(MAX_DATE), m_search_string(), typeFilter(ALL_TYPES), watchOnlyFilter(WatchOnlyFilter_All), minAmount(0), limitRows(-1), showInactive(true) { } bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); int status = index.data(TransactionTableModel::StatusRole).toInt(); if (!showInactive && status == TransactionStatus::Conflicted) return false; int type = index.data(TransactionTableModel::TypeRole).toInt(); if (!(TYPE(type) & typeFilter)) return false; bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool(); if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No) return false; if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes) return false; QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime(); if (datetime < dateFrom || datetime > dateTo) return false; QString address = index.data(TransactionTableModel::AddressRole).toString(); QString label = index.data(TransactionTableModel::LabelRole).toString(); QString txid = index.data(TransactionTableModel::TxHashRole).toString(); if (!address.contains(m_search_string, Qt::CaseInsensitive) && ! label.contains(m_search_string, Qt::CaseInsensitive) && ! txid.contains(m_search_string, Qt::CaseInsensitive)) { return false; } qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong()); if (amount < minAmount) return false; return true; } void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to) { this->dateFrom = from; this->dateTo = to; invalidateFilter(); } void TransactionFilterProxy::setSearchString(const QString &search_string) { if (m_search_string == search_string) return; m_search_string = search_string; invalidateFilter(); } void TransactionFilterProxy::setTypeFilter(quint32 modes) { this->typeFilter = modes; invalidateFilter(); } void TransactionFilterProxy::setMinAmount(const CAmount& minimum) { this->minAmount = minimum; invalidateFilter(); } void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter) { this->watchOnlyFilter = filter; invalidateFilter(); } void TransactionFilterProxy::setLimit(int limit) { this->limitRows = limit; } void TransactionFilterProxy::setShowInactive(bool _showInactive) { this->showInactive = _showInactive; invalidateFilter(); } int TransactionFilterProxy::rowCount(const QModelIndex &parent) const { if(limitRows != -1) { return std::min(QSortFilterProxyModel::rowCount(parent), limitRows); } else { return QSortFilterProxyModel::rowCount(parent); } } <|endoftext|>
<commit_before>#include "SPlotFit2.h" // from STL #include <string> // from ROOT #include "TIterator.h" // from RooFit #include "RooAbsArg.h" #include "RooCategory.h" #include "RooCmdArg.h" #include "RooDataHist.h" #include "RooDataSet.h" #include "RooLinkedListIter.h" #include "RooRealVar.h" #include "RooLinkedListIter.h" #include "RooArgList.h" // from RooFit PDFs #include "RooAbsPdf.h" #include "RooAddPdf.h" #include "RooExtendPdf.h" #include "RooHistPdf.h" #include "RooKeysPdf.h" #include "RooProdPdf.h" // from RooStats #include "RooStats/SPlot.h" // from DooCore #include <doocore/io/MsgStream.h> // from Project using std::cout; using std::endl; using std::map; using std::pair; using namespace RooFit; using namespace doocore::io; namespace doofit { namespace fitter { namespace splot { SPlotFit2::SPlotFit2() : pdf_(NULL), pdf_owned_(false), num_cpu_(4), input_data_(), pdf_disc_full_(NULL), disc_vars_(), cont_vars_(), disc_pdfs_(), cont_pdfs_(), disc_pdfs_extend_(), sweighted_data_(), sweighted_hist_(), use_minos_(true) { } SPlotFit2::SPlotFit2(RooAbsPdf& pdf, RooDataSet& data, RooArgSet yields) : pdf_(&pdf), pdf_owned_(false), yields_(yields), num_cpu_(4), input_data_(&data), pdf_disc_full_(NULL), disc_vars_(), cont_vars_(), disc_pdfs_(), cont_pdfs_(), disc_pdfs_extend_(), sweighted_data_(), sweighted_hist_(), use_minos_(true) { pdf_->Print("v"); yields_.Print(); input_data_->Print(); } SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*> pdfs, RooDataSet& data) : pdf_(NULL), pdf_owned_(true), yields_(), num_cpu_(4), input_data_(&data), pdf_disc_full_(NULL), disc_vars_(), cont_vars_(), disc_pdfs_(), cont_pdfs_(), disc_pdfs_extend_(), sweighted_data_(), sweighted_hist_(), use_minos_(true) { RooArgList pdfs_list; for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin(); it != pdfs.end(); ++it) { pdfs_list.add(**it); RooRealVar* var = new RooRealVar(TString()+(*it)->GetName()+"_yield", TString()+(*it)->GetName()+"_yield", input_data_->sumEntries()/pdfs.size(), 0.0, input_data_->sumEntries()*10); yields_.addOwned(*var); } pdf_ = new RooAddPdf("pdf_splotfit2", "pdf_splotfit2", pdfs_list, yields_); } SPlotFit2::~SPlotFit2(){ if (pdf_owned_ && pdf_ != NULL) delete pdf_; } void SPlotFit2::Fit(RooLinkedList* ext_fit_args) { //========================================================================= // merge our and external fitting arguments RooLinkedList fitting_args; fitting_args.Add((TObject*)(new RooCmdArg(NumCPU(num_cpu_)))); fitting_args.Add((TObject*)(new RooCmdArg(Extended()))); fitting_args.Add((TObject*)(new RooCmdArg(Minos(use_minos_)))); fitting_args.Add((TObject*)(new RooCmdArg(Strategy(2)))); fitting_args.Add((TObject*)(new RooCmdArg(Save(true)))); fitting_args.Add((TObject*)(new RooCmdArg(Verbose(false)))); fitting_args.Add((TObject*)(new RooCmdArg(Timer(true)))); fitting_args.Add((TObject*)(new RooCmdArg(Minimizer("Minuit2","minimize")))); if (ext_fit_args != NULL) { RooLinkedListIter it = ext_fit_args->iterator(); TObject* arg = NULL; while ((arg = it.Next())) { arg->Print(); fitting_args.Add(arg); } } //========================================================================= // fit discriminating pdf pdf_->fitTo(*input_data_, fitting_args); //========================================================================= // create sPlot // get all parameters RooArgSet* par_disc_set = pdf_->getParameters(*input_data_); // remove yields from parameter set par_disc_set->remove(yields_); // Helper pointers RooRealVar* var_iter1 = NULL; // iterate over left over parameters of full disc pdf and set constant RooLinkedListIter* par_disc_set_iterator = (RooLinkedListIter*)par_disc_set->createIterator(); while (var_iter1=(RooRealVar*)par_disc_set_iterator->Next()) { var_iter1->setConstant(); } delete par_disc_set_iterator; // create datasets RooStats::SPlot *sData = new RooStats::SPlot("sData","SPlot",*input_data_,pdf_,yields_); //========================================================================= // create sweighted datasets // iterate over yields RooLinkedListIter* yield_iterator = (RooLinkedListIter*)yields_.createIterator(); while (var_iter1=(RooRealVar*)yield_iterator->Next()) { std::string comp_name = var_iter1->GetName(); sinfo << "SPlotFit2: Adding sweighted dataset with name " << comp_name << endmsg; sweighted_data_[comp_name] = new RooDataSet(input_data_->GetName(),input_data_->GetTitle(),input_data_,*input_data_->get(),0,TString("")+var_iter1->GetName()+"_sw"); } delete yield_iterator; } void SPlotFit2::Run(RooLinkedList* ext_fit_args){ // merge our and external fitting arguments RooLinkedList fitting_args; fitting_args.Add((TObject*)(new RooCmdArg(NumCPU(num_cpu_)))); fitting_args.Add((TObject*)(new RooCmdArg(Extended()))); fitting_args.Add((TObject*)(new RooCmdArg(Minos(use_minos_)))); fitting_args.Add((TObject*)(new RooCmdArg(Strategy(2)))); fitting_args.Add((TObject*)(new RooCmdArg(Save(true)))); fitting_args.Add((TObject*)(new RooCmdArg(Verbose(false)))); fitting_args.Add((TObject*)(new RooCmdArg(Timer(true)))); if (ext_fit_args != NULL) { RooLinkedListIter it = ext_fit_args->iterator(); TObject* arg = NULL; while ((arg = it.Next())) { arg->Print(); fitting_args.Add(arg); } } // Make estimtes on yields (for starting values that are not complete nonsense) double yield_start = input_data_->sumEntries()/disc_pdfs_.size(); double yield_max = 1200*yield_start; //========================================================================= // create discriminating pdfs and fit // prepare iterator map<std::string,RooArgSet>::const_iterator disc_pdfs_it; // iterate over disc_pdfs_ map and create ProdPdfs, yields, and extended PDFs RooArgList pdfs_extend; for (disc_pdfs_it = disc_pdfs_.begin(); disc_pdfs_it != disc_pdfs_.end(); ++disc_pdfs_it){ std::string comp_name = (*disc_pdfs_it).first; RooArgSet pdfs_set = (*disc_pdfs_it).second; RooRealVar* yield = new RooRealVar(TString(comp_name)+"Yield",TString("N_{")+comp_name+"}",yield_start,0,yield_max); RooProdPdf* pdf_prod = new RooProdPdf(TString(comp_name)+"ProdPdf",TString("Product Disc Pdf of ")+comp_name+" Component",pdfs_set); RooExtendPdf* pdf_extend = new RooExtendPdf(TString(comp_name)+"ExtPdf",TString("Extended Disc Pdf of ")+comp_name+" Component",*pdf_prod,*yield); disc_pdfs_extend_[comp_name] = std::pair<RooRealVar*,RooAbsPdf*>(yield,pdf_extend); //pdfs_set.Print(); //pdf_extend->Print("t"); pdfs_extend.add(*pdf_extend); } // create full discriminating pdf by RooAddPdf of component pdfs pdf_disc_full_ = new RooAddPdf("pdfDiscFull","Full discriminating Pdf",pdfs_extend); //Introduced by Tobi for the possibility of giving the fit sane satrting values for hadronic background event yields. //Should not interfer with anything pdf_disc_full_->getParameters(input_data_)->writeToFile("SPlotParams.new"); pdf_disc_full_->getParameters(input_data_)->readFromFile("SPlotParams.txt"); // fit discriminating pdf pdf_disc_full_->fitTo(*input_data_, fitting_args); //Introduced by Tobi ... ^^ pdf_disc_full_->getParameters(input_data_)->writeToFile("SPlotParams_result.txt"); //========================================================================= // create sweighted datasets // set all parameters of discriminating pdf constant except for yields // get all parameters RooArgSet* par_disc_set = pdf_disc_full_->getParameters(*input_data_); // get yields RooArgSet disc_pdfs_yields; map<std::string,std::pair<RooRealVar*,RooAbsPdf*> >::const_iterator disc_pdfs_extend_it; for (disc_pdfs_extend_it = disc_pdfs_extend_.begin(); disc_pdfs_extend_it != disc_pdfs_extend_.end(); ++disc_pdfs_extend_it){ disc_pdfs_yields.add(*((*disc_pdfs_extend_it).second.first)); } // remove yields from parameter set par_disc_set->remove(disc_pdfs_yields); // Helper pointers RooRealVar* var_iter1 = NULL; RooRealVar* var_iter2 = NULL; // iterate over left over parameters of full disc pdf and set constant RooLinkedListIter* par_disc_set_iterator = (RooLinkedListIter*)par_disc_set->createIterator(); while (var_iter1=(RooRealVar*)par_disc_set_iterator->Next()) { var_iter1->setConstant(); } // create datasets RooStats::SPlot *sData = new RooStats::SPlot("sData","SPlot",*input_data_,pdf_disc_full_,disc_pdfs_yields); //========================================================================= // create sweighted datasets for (disc_pdfs_extend_it = disc_pdfs_extend_.begin(); disc_pdfs_extend_it != disc_pdfs_extend_.end(); ++disc_pdfs_extend_it){ std::string comp_name = (*disc_pdfs_extend_it).first; sweighted_data_[comp_name] = new RooDataSet(input_data_->GetName(),input_data_->GetTitle(),input_data_,*input_data_->get(),0,TString("")+(*disc_pdfs_extend_it).second.first->GetName()+"_sw"); } // create sweighted datahists pdf_disc_full_->fitTo(*input_data_, fitting_args); for (disc_pdfs_extend_it = disc_pdfs_extend_.begin(); disc_pdfs_extend_it != disc_pdfs_extend_.end(); ++disc_pdfs_extend_it){ std::string comp_name = (*disc_pdfs_extend_it).first; sweighted_hist_[comp_name] = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_,*(sweighted_data_[comp_name])); } //========================================================================= // Fit // prepare iterator map<std::string,RooArgSet>::const_iterator cont_pdfs_it; for (cont_pdfs_it = cont_pdfs_.begin(); cont_pdfs_it != cont_pdfs_.end(); ++cont_pdfs_it){ std::string comp_name = (*cont_pdfs_it).first; RooArgSet pdfs_set = (*cont_pdfs_it).second; std::string prod_pdf_name = comp_name+"DiscProdPdf"; RooProdPdf* pdf_fit = new RooProdPdf(prod_pdf_name.c_str(), TString("Product Disc Pdf of ")+comp_name+" Component",pdfs_set); cont_pdfs_prod_[comp_name] = pdf_fit; RooDataHist* fit_data = sweighted_hist_[comp_name]; fit_data->Print(); fitting_args.Add((TObject*)(new RooCmdArg(SumW2Error(true)))); pdf_fit->fitTo(*fit_data, fitting_args); } } std::pair<RooHistPdf*,RooDataHist*> SPlotFit2::GetHistPdf(const std::string& pdf_name, const RooArgSet& vars_set, const std::string& comp_name, const std::string& binningName){ RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName)); data_hist->add(*(sweighted_data_[comp_name])); RooHistPdf* pdf_hist = new RooHistPdf(pdf_name.c_str(),pdf_name.c_str(),vars_set,*data_hist); return std::pair<RooHistPdf*,RooDataHist*>(pdf_hist,data_hist); } RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, const std::string& binningName ){ RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName)); data_hist->add(*(sweighted_data_[comp_name])); return data_hist; } RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, RooRealVar * var, const std::string& binningName ){ RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name+var->GetName(),TString("sDataHist")+comp_name+var->GetName(),RooArgList(*var), TString(binningName)); data_hist->add(*(sweighted_data_[comp_name])); return data_hist; } RooKeysPdf& SPlotFit2::GetKeysPdf(const std::string& pdf_name, RooRealVar& var, const std::string& comp_name){ RooKeysPdf* pdf_keys = new RooKeysPdf(pdf_name.c_str(),pdf_name.c_str(),var,*sweighted_data_[comp_name]); return *pdf_keys; } RooDataSet* SPlotFit2::GetSwDataSet(const std::string& comp_name){ return sweighted_data_[comp_name]; } } //namespace splot } //namespace fitter } //namespace doofit <commit_msg>SPlotFit2: printing fit result after fit<commit_after>#include "SPlotFit2.h" // from STL #include <string> // from ROOT #include "TIterator.h" // from RooFit #include "RooAbsArg.h" #include "RooCategory.h" #include "RooCmdArg.h" #include "RooDataHist.h" #include "RooDataSet.h" #include "RooLinkedListIter.h" #include "RooRealVar.h" #include "RooLinkedListIter.h" #include "RooArgList.h" #include "RooFitResult.h" // from RooFit PDFs #include "RooAbsPdf.h" #include "RooAddPdf.h" #include "RooExtendPdf.h" #include "RooHistPdf.h" #include "RooKeysPdf.h" #include "RooProdPdf.h" // from RooStats #include "RooStats/SPlot.h" // from DooCore #include <doocore/io/MsgStream.h> // from Project using std::cout; using std::endl; using std::map; using std::pair; using namespace RooFit; using namespace doocore::io; namespace doofit { namespace fitter { namespace splot { SPlotFit2::SPlotFit2() : pdf_(NULL), pdf_owned_(false), num_cpu_(4), input_data_(), pdf_disc_full_(NULL), disc_vars_(), cont_vars_(), disc_pdfs_(), cont_pdfs_(), disc_pdfs_extend_(), sweighted_data_(), sweighted_hist_(), use_minos_(true) { } SPlotFit2::SPlotFit2(RooAbsPdf& pdf, RooDataSet& data, RooArgSet yields) : pdf_(&pdf), pdf_owned_(false), yields_(yields), num_cpu_(4), input_data_(&data), pdf_disc_full_(NULL), disc_vars_(), cont_vars_(), disc_pdfs_(), cont_pdfs_(), disc_pdfs_extend_(), sweighted_data_(), sweighted_hist_(), use_minos_(true) { pdf_->Print("v"); yields_.Print(); input_data_->Print(); } SPlotFit2::SPlotFit2(std::vector<RooAbsPdf*> pdfs, RooDataSet& data) : pdf_(NULL), pdf_owned_(true), yields_(), num_cpu_(4), input_data_(&data), pdf_disc_full_(NULL), disc_vars_(), cont_vars_(), disc_pdfs_(), cont_pdfs_(), disc_pdfs_extend_(), sweighted_data_(), sweighted_hist_(), use_minos_(true) { RooArgList pdfs_list; for (std::vector<RooAbsPdf*>::const_iterator it = pdfs.begin(); it != pdfs.end(); ++it) { pdfs_list.add(**it); RooRealVar* var = new RooRealVar(TString()+(*it)->GetName()+"_yield", TString()+(*it)->GetName()+"_yield", input_data_->sumEntries()/pdfs.size(), 0.0, input_data_->sumEntries()*10); yields_.addOwned(*var); } pdf_ = new RooAddPdf("pdf_splotfit2", "pdf_splotfit2", pdfs_list, yields_); } SPlotFit2::~SPlotFit2(){ if (pdf_owned_ && pdf_ != NULL) delete pdf_; } void SPlotFit2::Fit(RooLinkedList* ext_fit_args) { //========================================================================= // merge our and external fitting arguments RooLinkedList fitting_args; fitting_args.Add((TObject*)(new RooCmdArg(NumCPU(num_cpu_)))); fitting_args.Add((TObject*)(new RooCmdArg(Extended()))); fitting_args.Add((TObject*)(new RooCmdArg(Minos(use_minos_)))); fitting_args.Add((TObject*)(new RooCmdArg(Strategy(2)))); fitting_args.Add((TObject*)(new RooCmdArg(Save(true)))); fitting_args.Add((TObject*)(new RooCmdArg(Verbose(false)))); fitting_args.Add((TObject*)(new RooCmdArg(Timer(true)))); fitting_args.Add((TObject*)(new RooCmdArg(Minimizer("Minuit2","minimize")))); if (ext_fit_args != NULL) { RooLinkedListIter it = ext_fit_args->iterator(); TObject* arg = NULL; while ((arg = it.Next())) { arg->Print(); fitting_args.Add(arg); } } //========================================================================= // fit discriminating pdf RooFitResult* fit_result = pdf_->fitTo(*input_data_, fitting_args); fit_result->Print("v"); delete fit_result; //========================================================================= // create sPlot // get all parameters RooArgSet* par_disc_set = pdf_->getParameters(*input_data_); // remove yields from parameter set par_disc_set->remove(yields_); // Helper pointers RooRealVar* var_iter1 = NULL; // iterate over left over parameters of full disc pdf and set constant RooLinkedListIter* par_disc_set_iterator = (RooLinkedListIter*)par_disc_set->createIterator(); while (var_iter1=(RooRealVar*)par_disc_set_iterator->Next()) { var_iter1->setConstant(); } delete par_disc_set_iterator; // create datasets RooStats::SPlot *sData = new RooStats::SPlot("sData","SPlot",*input_data_,pdf_,yields_); //========================================================================= // create sweighted datasets // iterate over yields RooLinkedListIter* yield_iterator = (RooLinkedListIter*)yields_.createIterator(); while (var_iter1=(RooRealVar*)yield_iterator->Next()) { std::string comp_name = var_iter1->GetName(); sinfo << "SPlotFit2: Adding sweighted dataset with name " << comp_name << endmsg; sweighted_data_[comp_name] = new RooDataSet(input_data_->GetName(),input_data_->GetTitle(),input_data_,*input_data_->get(),0,TString("")+var_iter1->GetName()+"_sw"); } delete yield_iterator; } void SPlotFit2::Run(RooLinkedList* ext_fit_args){ // merge our and external fitting arguments RooLinkedList fitting_args; fitting_args.Add((TObject*)(new RooCmdArg(NumCPU(num_cpu_)))); fitting_args.Add((TObject*)(new RooCmdArg(Extended()))); fitting_args.Add((TObject*)(new RooCmdArg(Minos(use_minos_)))); fitting_args.Add((TObject*)(new RooCmdArg(Strategy(2)))); fitting_args.Add((TObject*)(new RooCmdArg(Save(true)))); fitting_args.Add((TObject*)(new RooCmdArg(Verbose(false)))); fitting_args.Add((TObject*)(new RooCmdArg(Timer(true)))); if (ext_fit_args != NULL) { RooLinkedListIter it = ext_fit_args->iterator(); TObject* arg = NULL; while ((arg = it.Next())) { arg->Print(); fitting_args.Add(arg); } } // Make estimtes on yields (for starting values that are not complete nonsense) double yield_start = input_data_->sumEntries()/disc_pdfs_.size(); double yield_max = 1200*yield_start; //========================================================================= // create discriminating pdfs and fit // prepare iterator map<std::string,RooArgSet>::const_iterator disc_pdfs_it; // iterate over disc_pdfs_ map and create ProdPdfs, yields, and extended PDFs RooArgList pdfs_extend; for (disc_pdfs_it = disc_pdfs_.begin(); disc_pdfs_it != disc_pdfs_.end(); ++disc_pdfs_it){ std::string comp_name = (*disc_pdfs_it).first; RooArgSet pdfs_set = (*disc_pdfs_it).second; RooRealVar* yield = new RooRealVar(TString(comp_name)+"Yield",TString("N_{")+comp_name+"}",yield_start,0,yield_max); RooProdPdf* pdf_prod = new RooProdPdf(TString(comp_name)+"ProdPdf",TString("Product Disc Pdf of ")+comp_name+" Component",pdfs_set); RooExtendPdf* pdf_extend = new RooExtendPdf(TString(comp_name)+"ExtPdf",TString("Extended Disc Pdf of ")+comp_name+" Component",*pdf_prod,*yield); disc_pdfs_extend_[comp_name] = std::pair<RooRealVar*,RooAbsPdf*>(yield,pdf_extend); //pdfs_set.Print(); //pdf_extend->Print("t"); pdfs_extend.add(*pdf_extend); } // create full discriminating pdf by RooAddPdf of component pdfs pdf_disc_full_ = new RooAddPdf("pdfDiscFull","Full discriminating Pdf",pdfs_extend); //Introduced by Tobi for the possibility of giving the fit sane satrting values for hadronic background event yields. //Should not interfer with anything pdf_disc_full_->getParameters(input_data_)->writeToFile("SPlotParams.new"); pdf_disc_full_->getParameters(input_data_)->readFromFile("SPlotParams.txt"); // fit discriminating pdf pdf_disc_full_->fitTo(*input_data_, fitting_args); //Introduced by Tobi ... ^^ pdf_disc_full_->getParameters(input_data_)->writeToFile("SPlotParams_result.txt"); //========================================================================= // create sweighted datasets // set all parameters of discriminating pdf constant except for yields // get all parameters RooArgSet* par_disc_set = pdf_disc_full_->getParameters(*input_data_); // get yields RooArgSet disc_pdfs_yields; map<std::string,std::pair<RooRealVar*,RooAbsPdf*> >::const_iterator disc_pdfs_extend_it; for (disc_pdfs_extend_it = disc_pdfs_extend_.begin(); disc_pdfs_extend_it != disc_pdfs_extend_.end(); ++disc_pdfs_extend_it){ disc_pdfs_yields.add(*((*disc_pdfs_extend_it).second.first)); } // remove yields from parameter set par_disc_set->remove(disc_pdfs_yields); // Helper pointers RooRealVar* var_iter1 = NULL; RooRealVar* var_iter2 = NULL; // iterate over left over parameters of full disc pdf and set constant RooLinkedListIter* par_disc_set_iterator = (RooLinkedListIter*)par_disc_set->createIterator(); while (var_iter1=(RooRealVar*)par_disc_set_iterator->Next()) { var_iter1->setConstant(); } // create datasets RooStats::SPlot *sData = new RooStats::SPlot("sData","SPlot",*input_data_,pdf_disc_full_,disc_pdfs_yields); //========================================================================= // create sweighted datasets for (disc_pdfs_extend_it = disc_pdfs_extend_.begin(); disc_pdfs_extend_it != disc_pdfs_extend_.end(); ++disc_pdfs_extend_it){ std::string comp_name = (*disc_pdfs_extend_it).first; sweighted_data_[comp_name] = new RooDataSet(input_data_->GetName(),input_data_->GetTitle(),input_data_,*input_data_->get(),0,TString("")+(*disc_pdfs_extend_it).second.first->GetName()+"_sw"); } // create sweighted datahists pdf_disc_full_->fitTo(*input_data_, fitting_args); for (disc_pdfs_extend_it = disc_pdfs_extend_.begin(); disc_pdfs_extend_it != disc_pdfs_extend_.end(); ++disc_pdfs_extend_it){ std::string comp_name = (*disc_pdfs_extend_it).first; sweighted_hist_[comp_name] = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_,*(sweighted_data_[comp_name])); } //========================================================================= // Fit // prepare iterator map<std::string,RooArgSet>::const_iterator cont_pdfs_it; for (cont_pdfs_it = cont_pdfs_.begin(); cont_pdfs_it != cont_pdfs_.end(); ++cont_pdfs_it){ std::string comp_name = (*cont_pdfs_it).first; RooArgSet pdfs_set = (*cont_pdfs_it).second; std::string prod_pdf_name = comp_name+"DiscProdPdf"; RooProdPdf* pdf_fit = new RooProdPdf(prod_pdf_name.c_str(), TString("Product Disc Pdf of ")+comp_name+" Component",pdfs_set); cont_pdfs_prod_[comp_name] = pdf_fit; RooDataHist* fit_data = sweighted_hist_[comp_name]; fit_data->Print(); fitting_args.Add((TObject*)(new RooCmdArg(SumW2Error(true)))); pdf_fit->fitTo(*fit_data, fitting_args); } } std::pair<RooHistPdf*,RooDataHist*> SPlotFit2::GetHistPdf(const std::string& pdf_name, const RooArgSet& vars_set, const std::string& comp_name, const std::string& binningName){ RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName)); data_hist->add(*(sweighted_data_[comp_name])); RooHistPdf* pdf_hist = new RooHistPdf(pdf_name.c_str(),pdf_name.c_str(),vars_set,*data_hist); return std::pair<RooHistPdf*,RooDataHist*>(pdf_hist,data_hist); } RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, const std::string& binningName ){ RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name,TString("sDataHist")+comp_name,cont_vars_, TString(binningName)); data_hist->add(*(sweighted_data_[comp_name])); return data_hist; } RooDataHist* SPlotFit2::GetRooDataHist( const std::string& comp_name, RooRealVar * var, const std::string& binningName ){ RooDataHist* data_hist = new RooDataHist(TString("sDataHist")+comp_name+var->GetName(),TString("sDataHist")+comp_name+var->GetName(),RooArgList(*var), TString(binningName)); data_hist->add(*(sweighted_data_[comp_name])); return data_hist; } RooKeysPdf& SPlotFit2::GetKeysPdf(const std::string& pdf_name, RooRealVar& var, const std::string& comp_name){ RooKeysPdf* pdf_keys = new RooKeysPdf(pdf_name.c_str(),pdf_name.c_str(),var,*sweighted_data_[comp_name]); return *pdf_keys; } RooDataSet* SPlotFit2::GetSwDataSet(const std::string& comp_name){ return sweighted_data_[comp_name]; } } //namespace splot } //namespace fitter } //namespace doofit <|endoftext|>
<commit_before><commit_msg>TODO-606<commit_after><|endoftext|>
<commit_before>#include "tablet.hpp" #include "../core-impl.hpp" #include "../wm.hpp" #include "input-manager.hpp" #include <wayfire/signal-definitions.hpp> #include <linux/input-event-codes.h> extern "C" { #include <wlr/types/wlr_tablet_v2.h> } /* --------------------- Tablet tool implementation ------------------------- */ wf::tablet_tool_t::tablet_tool_t(wlr_tablet_tool *tool, wlr_tablet_v2_tablet *tablet) { this->tablet_v2 = tablet; /* Initialize tool_v2 */ this->tool = tool; this->tool->data = this; auto& core = wf::get_core_impl(); this->tool_v2 = wlr_tablet_tool_create(core.protocols.tablet_v2, core.get_current_seat(), tool); /* Free memory when the tool is destroyed */ this->on_destroy.set_callback([=] (void*) { delete this; }); this->on_destroy.connect(&tool->events.destroy); /* Ungrab surface, and update focused surface if a surface is unmapped, * we don't want to end up with a reference to unfocused or a destroyed * surface. */ on_surface_map_state_changed = [=] (signal_data_t *data) { auto ev = static_cast<_surface_map_state_changed_signal*> (data); if (!ev->surface->is_mapped() && ev->surface == this->grabbed_surface) this->grabbed_surface = nullptr; update_tool_position(); }; wf::get_core().connect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().connect_signal("_surface_unmapped", &on_surface_map_state_changed); /* Just pass cursor set requests to core, but translate them to * regular pointer set requests */ on_set_cursor.set_callback([=] (void *data) { if (!this->is_active) return; auto& input = wf::get_core_impl().input; auto ev = static_cast<wlr_tablet_v2_event_cursor*> (data); // validate request wlr_seat_client *tablet_client = nullptr; if (tool_v2->focused_surface) { tablet_client = wlr_seat_client_for_wl_client(input->seat, wl_resource_get_client(tool_v2->focused_surface->resource)); } if (tablet_client != ev->seat_client) return; wlr_seat_pointer_request_set_cursor_event pev; pev.surface = ev->surface; pev.hotspot_x = ev->hotspot_x; pev.hotspot_y = ev->hotspot_y; pev.serial = ev->serial; pev.seat_client = ev->seat_client; input->cursor->set_cursor(&pev, false); }); on_set_cursor.connect(&tool_v2->events.set_cursor); } wf::tablet_tool_t::~tablet_tool_t() { wf::get_core().disconnect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().disconnect_signal("_surface_unmapped", &on_surface_map_state_changed); tool->data = NULL; } void wf::tablet_tool_t::update_tool_position() { if (!is_active) return; auto& core = wf::get_core_impl(); auto& input = core.input; auto gc = core.get_cursor_position(); /* XXX: tablet input works only with programs, Wayfire itself doesn't do * anything useful with it */ if (core.input->input_grabbed()) return; /* Figure out what surface is under the tool */ wf::pointf_t local; // local to the surface wf::surface_interface_t *surface = nullptr; if (this->grabbed_surface) { surface = this->grabbed_surface; local = get_surface_relative_coords(surface, gc); } else { surface = input->input_surface_at(gc, local); } set_focus(surface); /* If focus is a wlr surface, send position */ wlr_surface *next_focus = surface ? surface->get_wlr_surface() : nullptr; if (next_focus) wlr_tablet_v2_tablet_tool_notify_motion(tool_v2, local.x, local.y); } void wf::tablet_tool_t::set_focus(wf::surface_interface_t *surface) { /* Unfocus old surface */ if (surface != this->proximity_surface && this->proximity_surface) { wlr_tablet_v2_tablet_tool_notify_proximity_out(tool_v2); this->proximity_surface = nullptr; } /* Set the new focus, if it is a wlr surface */ wlr_surface *next_focus = surface ? surface->get_wlr_surface() : nullptr; if (next_focus && wlr_surface_accepts_tablet_v2(tablet_v2, next_focus)) { this->proximity_surface = surface; wlr_tablet_v2_tablet_tool_notify_proximity_in( tool_v2, tablet_v2, next_focus); } } void wf::tablet_tool_t::passthrough_axis(wlr_event_tablet_tool_axis *ev) { if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_PRESSURE) wlr_tablet_v2_tablet_tool_notify_pressure(tool_v2, ev->pressure); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_DISTANCE) wlr_tablet_v2_tablet_tool_notify_distance(tool_v2, ev->distance); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_ROTATION) wlr_tablet_v2_tablet_tool_notify_rotation(tool_v2, ev->rotation); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_SLIDER) wlr_tablet_v2_tablet_tool_notify_slider(tool_v2, ev->slider); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_WHEEL) wlr_tablet_v2_tablet_tool_notify_wheel(tool_v2, ev->wheel_delta, 0); /* Update tilt, use old values if no new values are provided */ if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_X) tilt_x = ev->tilt_x; if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_Y) tilt_y = ev->tilt_y; if (ev->updated_axes & (WLR_TABLET_TOOL_AXIS_TILT_X | WLR_TABLET_TOOL_AXIS_TILT_Y)) { wlr_tablet_v2_tablet_tool_notify_tilt(tool_v2, tilt_x, tilt_y); } } void wf::tablet_tool_t::handle_tip(wlr_event_tablet_tool_tip *ev) { /* Nothing to do without a proximity surface */ if (!this->proximity_surface) return; if (ev->state == WLR_TABLET_TOOL_TIP_DOWN) { wlr_send_tablet_v2_tablet_tool_down(tool_v2); this->grabbed_surface = this->proximity_surface; /* Try to focus the view under the tool */ auto view = dynamic_cast<wf::view_interface_t*> ( this->proximity_surface->get_main_surface()); if (view) { wf::get_core().focus_output(view->get_output()); wm_focus_request data; data.surface = this->proximity_surface; view->get_output()->emit_signal("wm-focus-request", &data); } } else { wlr_send_tablet_v2_tablet_tool_up(tool_v2); this->grabbed_surface = nullptr; } } void wf::tablet_tool_t::handle_button(wlr_event_tablet_tool_button *ev) { wlr_tablet_v2_tablet_tool_notify_button(tool_v2, (zwp_tablet_pad_v2_button_state)ev->button, (zwp_tablet_pad_v2_button_state)ev->state); } void wf::tablet_tool_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { set_focus(nullptr); is_active = false; } else { is_active = true; update_tool_position(); } } /* ----------------------- Tablet implementation ---------------------------- */ wf::tablet_t::tablet_t(wlr_cursor *cursor, wlr_input_device *dev) : wf_input_device_internal(dev) { this->handle = dev->tablet; this->handle->data = this; this->cursor = cursor; auto& core = wf::get_core_impl(); tablet_v2 = wlr_tablet_create(core.protocols.tablet_v2, core.get_current_seat(), dev); wlr_cursor_attach_input_device(cursor, dev); } wf::tablet_t::~tablet_t() { this->handle->data = NULL; } wf::tablet_tool_t *wf::tablet_t::ensure_tool(wlr_tablet_tool *tool) { if (tool->data == NULL) new wf::tablet_tool_t(tool, tablet_v2); return (wf::tablet_tool_t*) tool->data; } void wf::tablet_t::handle_tip(wlr_event_tablet_tool_tip *ev) { auto& input = wf::get_core_impl().input; if (input->input_grabbed()) { /* Simulate buttons, in case some application started moving */ if (input->active_grab->callbacks.pointer.button) { uint32_t state = ev->state == WLR_TABLET_TOOL_TIP_DOWN ? WLR_BUTTON_PRESSED : WLR_BUTTON_RELEASED; input->active_grab->callbacks.pointer.button(BTN_LEFT, state); } return; } auto tool = ensure_tool(ev->tool); tool->handle_tip(ev); } void wf::tablet_t::handle_axis(wlr_event_tablet_tool_axis *ev) { auto& input = wf::get_core_impl().input; /* Update cursor position */ switch(ev->tool->type) { case WLR_TABLET_TOOL_TYPE_MOUSE: wlr_cursor_move(cursor, ev->device, ev->dx, ev->dy); break; default: double x = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_X) ? ev->x : NAN; double y = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_Y) ? ev->y : NAN; wlr_cursor_warp_absolute(cursor, ev->device, x, y); } if (input->input_grabbed()) { /* Simulate movement */ if (input->active_grab->callbacks.pointer.motion) { auto gc = wf::get_core().get_cursor_position(); input->active_grab->callbacks.pointer.motion(gc.x, gc.y); } return; } /* Update focus */ auto tool = ensure_tool(ev->tool); tool->update_tool_position(); tool->passthrough_axis(ev); } void wf::tablet_t::handle_button(wlr_event_tablet_tool_button *ev) { /* Pass to the tool */ ensure_tool(ev->tool)->handle_button(ev); } void wf::tablet_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { ensure_tool(ev->tool)->handle_proximity(ev); auto& impl = wf::get_core_impl(); /* Show appropriate cursor */ if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { impl.set_cursor("default"); impl.input->lpointer->set_enable_focus(true); } else { wf::get_core().set_cursor("crosshair"); impl.input->lpointer->set_enable_focus(false); } } <commit_msg>tablet: reset tool data when freeing wayfire tablet structure<commit_after>#include "tablet.hpp" #include "../core-impl.hpp" #include "../wm.hpp" #include "input-manager.hpp" #include <wayfire/signal-definitions.hpp> #include <linux/input-event-codes.h> extern "C" { #include <wlr/types/wlr_tablet_v2.h> } /* --------------------- Tablet tool implementation ------------------------- */ wf::tablet_tool_t::tablet_tool_t(wlr_tablet_tool *tool, wlr_tablet_v2_tablet *tablet) { this->tablet_v2 = tablet; /* Initialize tool_v2 */ this->tool = tool; this->tool->data = this; auto& core = wf::get_core_impl(); this->tool_v2 = wlr_tablet_tool_create(core.protocols.tablet_v2, core.get_current_seat(), tool); /* Free memory when the tool is destroyed */ this->on_destroy.set_callback([=] (void*) { this->tool->data = nullptr; delete this; }); this->on_destroy.connect(&tool->events.destroy); /* Ungrab surface, and update focused surface if a surface is unmapped, * we don't want to end up with a reference to unfocused or a destroyed * surface. */ on_surface_map_state_changed = [=] (signal_data_t *data) { auto ev = static_cast<_surface_map_state_changed_signal*> (data); if (!ev->surface->is_mapped() && ev->surface == this->grabbed_surface) this->grabbed_surface = nullptr; update_tool_position(); }; wf::get_core().connect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().connect_signal("_surface_unmapped", &on_surface_map_state_changed); /* Just pass cursor set requests to core, but translate them to * regular pointer set requests */ on_set_cursor.set_callback([=] (void *data) { if (!this->is_active) return; auto& input = wf::get_core_impl().input; auto ev = static_cast<wlr_tablet_v2_event_cursor*> (data); // validate request wlr_seat_client *tablet_client = nullptr; if (tool_v2->focused_surface) { tablet_client = wlr_seat_client_for_wl_client(input->seat, wl_resource_get_client(tool_v2->focused_surface->resource)); } if (tablet_client != ev->seat_client) return; wlr_seat_pointer_request_set_cursor_event pev; pev.surface = ev->surface; pev.hotspot_x = ev->hotspot_x; pev.hotspot_y = ev->hotspot_y; pev.serial = ev->serial; pev.seat_client = ev->seat_client; input->cursor->set_cursor(&pev, false); }); on_set_cursor.connect(&tool_v2->events.set_cursor); } wf::tablet_tool_t::~tablet_tool_t() { wf::get_core().disconnect_signal("_surface_mapped", &on_surface_map_state_changed); wf::get_core().disconnect_signal("_surface_unmapped", &on_surface_map_state_changed); tool->data = NULL; } void wf::tablet_tool_t::update_tool_position() { if (!is_active) return; auto& core = wf::get_core_impl(); auto& input = core.input; auto gc = core.get_cursor_position(); /* XXX: tablet input works only with programs, Wayfire itself doesn't do * anything useful with it */ if (core.input->input_grabbed()) return; /* Figure out what surface is under the tool */ wf::pointf_t local; // local to the surface wf::surface_interface_t *surface = nullptr; if (this->grabbed_surface) { surface = this->grabbed_surface; local = get_surface_relative_coords(surface, gc); } else { surface = input->input_surface_at(gc, local); } set_focus(surface); /* If focus is a wlr surface, send position */ wlr_surface *next_focus = surface ? surface->get_wlr_surface() : nullptr; if (next_focus) wlr_tablet_v2_tablet_tool_notify_motion(tool_v2, local.x, local.y); } void wf::tablet_tool_t::set_focus(wf::surface_interface_t *surface) { /* Unfocus old surface */ if (surface != this->proximity_surface && this->proximity_surface) { wlr_tablet_v2_tablet_tool_notify_proximity_out(tool_v2); this->proximity_surface = nullptr; } /* Set the new focus, if it is a wlr surface */ wlr_surface *next_focus = surface ? surface->get_wlr_surface() : nullptr; if (next_focus && wlr_surface_accepts_tablet_v2(tablet_v2, next_focus)) { this->proximity_surface = surface; wlr_tablet_v2_tablet_tool_notify_proximity_in( tool_v2, tablet_v2, next_focus); } } void wf::tablet_tool_t::passthrough_axis(wlr_event_tablet_tool_axis *ev) { if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_PRESSURE) wlr_tablet_v2_tablet_tool_notify_pressure(tool_v2, ev->pressure); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_DISTANCE) wlr_tablet_v2_tablet_tool_notify_distance(tool_v2, ev->distance); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_ROTATION) wlr_tablet_v2_tablet_tool_notify_rotation(tool_v2, ev->rotation); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_SLIDER) wlr_tablet_v2_tablet_tool_notify_slider(tool_v2, ev->slider); if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_WHEEL) wlr_tablet_v2_tablet_tool_notify_wheel(tool_v2, ev->wheel_delta, 0); /* Update tilt, use old values if no new values are provided */ if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_X) tilt_x = ev->tilt_x; if (ev->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_Y) tilt_y = ev->tilt_y; if (ev->updated_axes & (WLR_TABLET_TOOL_AXIS_TILT_X | WLR_TABLET_TOOL_AXIS_TILT_Y)) { wlr_tablet_v2_tablet_tool_notify_tilt(tool_v2, tilt_x, tilt_y); } } void wf::tablet_tool_t::handle_tip(wlr_event_tablet_tool_tip *ev) { /* Nothing to do without a proximity surface */ if (!this->proximity_surface) return; if (ev->state == WLR_TABLET_TOOL_TIP_DOWN) { wlr_send_tablet_v2_tablet_tool_down(tool_v2); this->grabbed_surface = this->proximity_surface; /* Try to focus the view under the tool */ auto view = dynamic_cast<wf::view_interface_t*> ( this->proximity_surface->get_main_surface()); if (view) { wf::get_core().focus_output(view->get_output()); wm_focus_request data; data.surface = this->proximity_surface; view->get_output()->emit_signal("wm-focus-request", &data); } } else { wlr_send_tablet_v2_tablet_tool_up(tool_v2); this->grabbed_surface = nullptr; } } void wf::tablet_tool_t::handle_button(wlr_event_tablet_tool_button *ev) { wlr_tablet_v2_tablet_tool_notify_button(tool_v2, (zwp_tablet_pad_v2_button_state)ev->button, (zwp_tablet_pad_v2_button_state)ev->state); } void wf::tablet_tool_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { set_focus(nullptr); is_active = false; } else { is_active = true; update_tool_position(); } } /* ----------------------- Tablet implementation ---------------------------- */ wf::tablet_t::tablet_t(wlr_cursor *cursor, wlr_input_device *dev) : wf_input_device_internal(dev) { this->handle = dev->tablet; this->handle->data = this; this->cursor = cursor; auto& core = wf::get_core_impl(); tablet_v2 = wlr_tablet_create(core.protocols.tablet_v2, core.get_current_seat(), dev); wlr_cursor_attach_input_device(cursor, dev); } wf::tablet_t::~tablet_t() { this->handle->data = NULL; } wf::tablet_tool_t *wf::tablet_t::ensure_tool(wlr_tablet_tool *tool) { if (tool->data == NULL) new wf::tablet_tool_t(tool, tablet_v2); return (wf::tablet_tool_t*) tool->data; } void wf::tablet_t::handle_tip(wlr_event_tablet_tool_tip *ev) { auto& input = wf::get_core_impl().input; if (input->input_grabbed()) { /* Simulate buttons, in case some application started moving */ if (input->active_grab->callbacks.pointer.button) { uint32_t state = ev->state == WLR_TABLET_TOOL_TIP_DOWN ? WLR_BUTTON_PRESSED : WLR_BUTTON_RELEASED; input->active_grab->callbacks.pointer.button(BTN_LEFT, state); } return; } auto tool = ensure_tool(ev->tool); tool->handle_tip(ev); } void wf::tablet_t::handle_axis(wlr_event_tablet_tool_axis *ev) { auto& input = wf::get_core_impl().input; /* Update cursor position */ switch(ev->tool->type) { case WLR_TABLET_TOOL_TYPE_MOUSE: wlr_cursor_move(cursor, ev->device, ev->dx, ev->dy); break; default: double x = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_X) ? ev->x : NAN; double y = (ev->updated_axes & WLR_TABLET_TOOL_AXIS_Y) ? ev->y : NAN; wlr_cursor_warp_absolute(cursor, ev->device, x, y); } if (input->input_grabbed()) { /* Simulate movement */ if (input->active_grab->callbacks.pointer.motion) { auto gc = wf::get_core().get_cursor_position(); input->active_grab->callbacks.pointer.motion(gc.x, gc.y); } return; } /* Update focus */ auto tool = ensure_tool(ev->tool); tool->update_tool_position(); tool->passthrough_axis(ev); } void wf::tablet_t::handle_button(wlr_event_tablet_tool_button *ev) { /* Pass to the tool */ ensure_tool(ev->tool)->handle_button(ev); } void wf::tablet_t::handle_proximity(wlr_event_tablet_tool_proximity *ev) { ensure_tool(ev->tool)->handle_proximity(ev); auto& impl = wf::get_core_impl(); /* Show appropriate cursor */ if (ev->state == WLR_TABLET_TOOL_PROXIMITY_OUT) { impl.set_cursor("default"); impl.input->lpointer->set_enable_focus(true); } else { wf::get_core().set_cursor("crosshair"); impl.input->lpointer->set_enable_focus(false); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include "SkipListNode.h" #include "RandomHeight.h" template <class Key, class Val> class SkipList { public: SkipList(float, int, Key*); ~SkipList(); bool insert(Key*, Val*); bool remove(Key*); Val* retrieve(Key*); void print(std::ofstream &); private: SkipListNode<Key, Val>* head; SkipListNode<Key, Val>* tail; float probability; int maxHeight; int currentHeight; RandomHeight* randomizer; }; template <class Key, class Val> SkipList<Key, Val>::SkipList(float theProbability, int theMaxHeight, Key* theKey) { currentHeight = 1; maxHeight = theMaxHeight; probability = theProbability; randomizer = new RandomHeight(theMaxHeight, theProbability); head = new SkipListNode<Key, Val>(theMaxHeight); tail = new SkipListNode<Key, Val>(theKey, (Val*)nullptr, theMaxHeight); for (int i = 1; i <= theMaxHeight; ++i) head->next[i] = tail; } template <class Key, class Val> bool SkipList<Key, Val>::insert(Key* theKey, Val* theValue) { int level = 0, h = currentHeight; SkipListNode<Key, Val>** toUpdate = new SkipListNode<Key, Val>*[maxHeight+1]; SkipListNode<Key, Val>* tempNode = head; Key* compareKey; // Check all the height levels for where to insert the new node. for(; h > 0; --h) { compareKey = tempNode->next[h]->getKey(); while(*compareKey < * *theKey) { // We have to go further. tempNode = tempNode->next[h]; compareKey = tempNode->next[h]->getKey(); } // This node at level h will have to be updated after inserting the new one. toUpdate[h] = tempNode; } tempNode = tempNode->next[1]; compareKey = tempNode->getKey(); if(*compareKey == *theKey) { // We already have this key in the set - cannot insert. return false; } // Get a random level for the node to be inserted into. level = randomizer->newLevel(); if(level > currentHeight) { // Create all the levels between the previous and new currentHeight // and add them to the update matrix. for(int i = currentHeight + 1; i <= level; ++i) toUpdate[i] = head; // The default lookup node. currentHeight = level; } tempNode = new SkipListNode<Key, Val>(theKey, theValue, level); // Actually insert the node where it belongs. for (int i = 1; i <= level; ++i) { tempNode->next[i] = toUpdate[i]->next[i]; toUpdate[i]->next[i] = tempNode; } // Success! return true; } template <class Key, class Val> bool SkipList<Key, Val>::remove(Key* theKey) { SkipListNode<Key, Val>** toUpdate = new SkipListNode<Key, Val>*[maxHeight+1]; SkipListNode<Key,Val>* tempNode = head; Key* compareKey; for (int h = currentHeight; h > 0; --h) { compareKey = tempNode->next[h]->getKey(); while(*compareKey < *theKey) { tempNode = tempNode->next[h]; compareKey = tempNode->next[h]->getKey(); } toUpdate[h] = tempNode; } // Get the found node at the base level. tempNode = tempNode->next[1]; compareKey = tempNode->getKey(); if (*compareKey == *theKey) { for (int i = 1; i <= currentHeight; ++i) { if (toUpdate[i]->next[i] != tempNode) break; // The removed node does not exist at this level. toUpdate[i]->next[i] = tempNode->next[i]; // Wire up the pointers. } delete tempNode; // Adjust currentHeight. while ((currentHeight > 1) && (head->next[currentHeight]->getKey() == tail->getKey())) { // If there are no nodes at currentHeight, decrement the value - no need to poke around there. --currentHeight; } // Success! return true; } // Node not found - nothing to remove. return false; } template <class Key, class Val> SkipList<Key, Val>::~SkipList() { SkipListNode<Key, Val> *tempNode = head, *nextNode; while(tempNode) { nextNode = tempNode->next[1]; delete tempNode; tempNode = nextNode; } } <commit_msg>[skip-list] Adding retrieval functionality.<commit_after>#include <iostream> #include <fstream> #include "SkipListNode.h" #include "RandomHeight.h" template <class Key, class Val> class SkipList { public: SkipList(float, int, Key*); ~SkipList(); bool insert(Key*, Val*); bool remove(Key*); Val* retrieve(Key*); void print(std::ofstream &); private: SkipListNode<Key, Val>* head; SkipListNode<Key, Val>* tail; float probability; int maxHeight; int currentHeight; RandomHeight* randomizer; }; template <class Key, class Val> SkipList<Key, Val>::SkipList(float theProbability, int theMaxHeight, Key* theKey) { currentHeight = 1; maxHeight = theMaxHeight; probability = theProbability; randomizer = new RandomHeight(theMaxHeight, theProbability); head = new SkipListNode<Key, Val>(theMaxHeight); tail = new SkipListNode<Key, Val>(theKey, (Val*)nullptr, theMaxHeight); for (int i = 1; i <= theMaxHeight; ++i) head->next[i] = tail; } template <class Key, class Val> bool SkipList<Key, Val>::insert(Key* theKey, Val* theValue) { int level = 0, h = currentHeight; SkipListNode<Key, Val>** toUpdate = new SkipListNode<Key, Val>*[maxHeight+1]; SkipListNode<Key, Val>* tempNode = head; Key* compareKey; // Check all the height levels for where to insert the new node. for(; h > 0; --h) { compareKey = tempNode->next[h]->getKey(); while(*compareKey < * *theKey) { // We have to go further. tempNode = tempNode->next[h]; compareKey = tempNode->next[h]->getKey(); } // This node at level h will have to be updated after inserting the new one. toUpdate[h] = tempNode; } tempNode = tempNode->next[1]; compareKey = tempNode->getKey(); if(*compareKey == *theKey) { // We already have this key in the set - cannot insert. return false; } // Get a random level for the node to be inserted into. level = randomizer->newLevel(); if(level > currentHeight) { // Create all the levels between the previous and new currentHeight // and add them to the update matrix. for(int i = currentHeight + 1; i <= level; ++i) toUpdate[i] = head; // The default lookup node. currentHeight = level; } tempNode = new SkipListNode<Key, Val>(theKey, theValue, level); // Actually insert the node where it belongs. for (int i = 1; i <= level; ++i) { tempNode->next[i] = toUpdate[i]->next[i]; toUpdate[i]->next[i] = tempNode; } // Success! return true; } template <class Key, class Val> bool SkipList<Key, Val>::remove(Key* theKey) { SkipListNode<Key, Val>** toUpdate = new SkipListNode<Key, Val>*[maxHeight+1]; SkipListNode<Key,Val>* tempNode = head; Key* compareKey; // TODO: extract this to a common private function. for (int h = currentHeight; h > 0; --h) { compareKey = tempNode->next[h]->getKey(); while(*compareKey < *theKey) { tempNode = tempNode->next[h]; compareKey = tempNode->next[h]->getKey(); } toUpdate[h] = tempNode; } // Get the found node at the base level. tempNode = tempNode->next[1]; compareKey = tempNode->getKey(); if (*compareKey == *theKey) { for (int i = 1; i <= currentHeight; ++i) { if (toUpdate[i]->next[i] != tempNode) break; // The removed node does not exist at this level. toUpdate[i]->next[i] = tempNode->next[i]; // Wire up the pointers. } delete tempNode; // Adjust currentHeight. while ((currentHeight > 1) && (head->next[currentHeight]->getKey() == tail->getKey())) { // If there are no nodes at currentHeight, decrement the value - no need to poke around there. --currentHeight; } // Success! return true; } // Node not found - nothing to remove. return false; } template <class Key, class Val> Val* SkipList<Key, Val>::retrieve(Key* theKey) { int h = currentHeight; SkipListNode<Key, Val> **toUpdate = new SkipListNode<Key, Val>*[maxHeight+1]; SkipListNode<Key, Val>* tempNode = head; Key* compareKey; for (; h > 0; --h) { compareKey = tempNode->next[h]->getKey(); while(*compareKey < *theKey) { tempNode = tempNode->next[h]; compareKey = tempNode->getKey(); } toUpdate[h] = tempNode; } tempNode = tempNode->next[1]; compareKey = tempNode->getKey(); if (*compareKey == *theKey) { // Success! return tempNode->getVal(); } return (SkipListNode<Key, Val>*)nullptr; } template <class Key, class Val> SkipList<Key, Val>::~SkipList() { SkipListNode<Key, Val> *tempNode = head, *nextNode; while(tempNode) { nextNode = tempNode->next[1]; delete tempNode; tempNode = nextNode; } } <|endoftext|>
<commit_before>#include "Spectrum.h" Spectrum::Spectrum(uint16_t columns, uint16_t rows, uint16_t rowOffset, uint8_t hue, uint8_t saturation, bool invert, uint8_t travel, CRGB * leds) : Visualization(columns, rows, hue, saturation, leds) { this->rowOffset = rowOffset; this->invert = invert; this->travel = travel; } void Spectrum::display(float* intensities) { for (uint8_t y=0; y<this->rows - this->rowOffset; y++) { float intensity = intensities[y+2]; if (intensity < 0.3) { continue; } intensity = (intensity - (0.3)) / 0.7; uint8_t hue = (this->travel * intensity) + this->hue; CRGB c = CHSV(hue, 245, 255); for (uint8_t x=0; x<this->columns; x++) { if (this->invert) { leds[this->xy2Pos(x, this->rowOffset - y)] = c; } else { leds[this->xy2Pos(x, y + this->rowOffset)] = c; } } } } void Spectrum::setTravel(uint8_t travel) { this->travel = travel; } <commit_msg>spectrum: use object saturation<commit_after>#include "Spectrum.h" Spectrum::Spectrum(uint16_t columns, uint16_t rows, uint16_t rowOffset, uint8_t hue, uint8_t saturation, bool invert, uint8_t travel, CRGB * leds) : Visualization(columns, rows, hue, saturation, leds) { this->rowOffset = rowOffset; this->invert = invert; this->travel = travel; } void Spectrum::display(float* intensities) { for (uint8_t y=0; y<this->rows - this->rowOffset; y++) { float intensity = intensities[y+2]; if (intensity < 0.3) { continue; } intensity = (intensity - (0.3)) / 0.7; uint8_t hue = (this->travel * intensity) + this->hue; CRGB c = CHSV(hue, this->saturation, 255); for (uint8_t x=0; x<this->columns; x++) { if (this->invert) { leds[this->xy2Pos(x, this->rowOffset - y)] = c; } else { leds[this->xy2Pos(x, y + this->rowOffset)] = c; } } } } void Spectrum::setTravel(uint8_t travel) { this->travel = travel; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SdGlobalResourceContainer.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2008-04-03 14:53:33 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "tools/SdGlobalResourceContainer.hxx" #include <algorithm> #include <vector> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace sd { //===== SdGlobalResourceContainer::Implementation ============================= class SdGlobalResourceContainer::Implementation { private: friend class SdGlobalResourceContainer; static SdGlobalResourceContainer* mpInstance; ::osl::Mutex maMutex; /** All instances of SdGlobalResource in this vector are owned by the container and will be destroyed when the container is destroyed. */ typedef ::std::vector<SdGlobalResource*> ResourceList; ResourceList maResources; typedef ::std::vector<boost::shared_ptr<SdGlobalResource> > SharedResourceList; SharedResourceList maSharedResources; typedef ::std::vector<Reference<XInterface> > XInterfaceResourceList; XInterfaceResourceList maXInterfaceResources; }; // static SdGlobalResourceContainer& SdGlobalResourceContainer::Instance (void) { DBG_ASSERT(Implementation::mpInstance!=NULL, "SdGlobalResourceContainer::Instance(): instance has been deleted"); // Maybe we should throw an exception when the instance has been deleted. return *Implementation::mpInstance; } SdGlobalResourceContainer* SdGlobalResourceContainer::Implementation::mpInstance = NULL; //===== SdGlobalResourceContainer ============================================= void SdGlobalResourceContainer::AddResource ( ::std::auto_ptr<SdGlobalResource> pResource) { ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::ResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maResources.begin(), mpImpl->maResources.end(), pResource.get()); if (iResource == mpImpl->maResources.end()) mpImpl->maResources.push_back(pResource.get()); else { // Because the given resource is an auto_ptr it is highly unlikely // that we come here. But who knows? DBG_ASSERT (false, "SdGlobalResourceContainer:AddResource(): Resource added twice."); } // We can not put the auto_ptr into the vector so we release the // auto_ptr and document that we take ownership explicitly. pResource.release(); } void SdGlobalResourceContainer::AddResource ( ::boost::shared_ptr<SdGlobalResource> pResource) { ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::SharedResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maSharedResources.begin(), mpImpl->maSharedResources.end(), pResource); if (iResource == mpImpl->maSharedResources.end()) mpImpl->maSharedResources.push_back(pResource); else { DBG_ASSERT (false, "SdGlobalResourceContainer:AddResource(): Resource added twice."); } } void SdGlobalResourceContainer::AddResource (const Reference<XInterface>& rxResource) { ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::XInterfaceResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maXInterfaceResources.begin(), mpImpl->maXInterfaceResources.end(), rxResource); if (iResource == mpImpl->maXInterfaceResources.end()) mpImpl->maXInterfaceResources.push_back(rxResource); else { DBG_ASSERT (false, "SdGlobalResourceContainer:AddResource(): Resource added twice."); } } ::std::auto_ptr<SdGlobalResource> SdGlobalResourceContainer::ReleaseResource ( SdGlobalResource* pResource) { ::std::auto_ptr<SdGlobalResource> pResult (NULL); ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::ResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maResources.begin(), mpImpl->maResources.end(), pResource); if (iResource != mpImpl->maResources.end()) { pResult.reset (*iResource); mpImpl->maResources.erase(iResource); } return pResult; } SdGlobalResourceContainer::SdGlobalResourceContainer (void) : mpImpl (new SdGlobalResourceContainer::Implementation()) { Implementation::mpInstance = this; } SdGlobalResourceContainer::~SdGlobalResourceContainer (void) { ::osl::MutexGuard aGuard (mpImpl->maMutex); // Release the resources in reversed order of their addition to the // container. This is because a resource A added before resource B // may have been created due to a request of B. Thus B depends on A and // should be destroyed first. Implementation::ResourceList::reverse_iterator iResource; for (iResource = mpImpl->maResources.rbegin(); iResource != mpImpl->maResources.rend(); ++iResource) { delete *iResource; } // The SharedResourceList has not to be released manually. We just // assert resources that are still held by someone other than us. Implementation::SharedResourceList::reverse_iterator iSharedResource; for (iSharedResource = mpImpl->maSharedResources.rbegin(); iSharedResource != mpImpl->maSharedResources.rend(); ++iSharedResource) { if ( ! iSharedResource->unique()) { SdGlobalResource* pResource = iSharedResource->get(); OSL_TRACE(" %p %d", pResource, iSharedResource->use_count()); DBG_ASSERT(iSharedResource->unique(), "SdGlobalResource still held in ~SdGlobalResourceContainer"); } } Implementation::XInterfaceResourceList::reverse_iterator iXInterfaceResource; for (iXInterfaceResource = mpImpl->maXInterfaceResources.rbegin(); iXInterfaceResource != mpImpl->maXInterfaceResources.rend(); ++iXInterfaceResource) { Reference<lang::XComponent> xComponent (*iXInterfaceResource, UNO_QUERY); *iXInterfaceResource = NULL; if (xComponent.is()) xComponent->dispose(); } DBG_ASSERT(Implementation::mpInstance == this, "~SdGlobalResourceContainer(): more than one instance of singleton"); Implementation::mpInstance = NULL; } } // end of namespace sd <commit_msg>INTEGRATION: CWS changefileheader (1.6.234); FILE MERGED 2008/03/31 13:59:05 rt 1.6.234.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SdGlobalResourceContainer.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "tools/SdGlobalResourceContainer.hxx" #include <algorithm> #include <vector> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace sd { //===== SdGlobalResourceContainer::Implementation ============================= class SdGlobalResourceContainer::Implementation { private: friend class SdGlobalResourceContainer; static SdGlobalResourceContainer* mpInstance; ::osl::Mutex maMutex; /** All instances of SdGlobalResource in this vector are owned by the container and will be destroyed when the container is destroyed. */ typedef ::std::vector<SdGlobalResource*> ResourceList; ResourceList maResources; typedef ::std::vector<boost::shared_ptr<SdGlobalResource> > SharedResourceList; SharedResourceList maSharedResources; typedef ::std::vector<Reference<XInterface> > XInterfaceResourceList; XInterfaceResourceList maXInterfaceResources; }; // static SdGlobalResourceContainer& SdGlobalResourceContainer::Instance (void) { DBG_ASSERT(Implementation::mpInstance!=NULL, "SdGlobalResourceContainer::Instance(): instance has been deleted"); // Maybe we should throw an exception when the instance has been deleted. return *Implementation::mpInstance; } SdGlobalResourceContainer* SdGlobalResourceContainer::Implementation::mpInstance = NULL; //===== SdGlobalResourceContainer ============================================= void SdGlobalResourceContainer::AddResource ( ::std::auto_ptr<SdGlobalResource> pResource) { ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::ResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maResources.begin(), mpImpl->maResources.end(), pResource.get()); if (iResource == mpImpl->maResources.end()) mpImpl->maResources.push_back(pResource.get()); else { // Because the given resource is an auto_ptr it is highly unlikely // that we come here. But who knows? DBG_ASSERT (false, "SdGlobalResourceContainer:AddResource(): Resource added twice."); } // We can not put the auto_ptr into the vector so we release the // auto_ptr and document that we take ownership explicitly. pResource.release(); } void SdGlobalResourceContainer::AddResource ( ::boost::shared_ptr<SdGlobalResource> pResource) { ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::SharedResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maSharedResources.begin(), mpImpl->maSharedResources.end(), pResource); if (iResource == mpImpl->maSharedResources.end()) mpImpl->maSharedResources.push_back(pResource); else { DBG_ASSERT (false, "SdGlobalResourceContainer:AddResource(): Resource added twice."); } } void SdGlobalResourceContainer::AddResource (const Reference<XInterface>& rxResource) { ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::XInterfaceResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maXInterfaceResources.begin(), mpImpl->maXInterfaceResources.end(), rxResource); if (iResource == mpImpl->maXInterfaceResources.end()) mpImpl->maXInterfaceResources.push_back(rxResource); else { DBG_ASSERT (false, "SdGlobalResourceContainer:AddResource(): Resource added twice."); } } ::std::auto_ptr<SdGlobalResource> SdGlobalResourceContainer::ReleaseResource ( SdGlobalResource* pResource) { ::std::auto_ptr<SdGlobalResource> pResult (NULL); ::osl::MutexGuard aGuard (mpImpl->maMutex); Implementation::ResourceList::iterator iResource; iResource = ::std::find ( mpImpl->maResources.begin(), mpImpl->maResources.end(), pResource); if (iResource != mpImpl->maResources.end()) { pResult.reset (*iResource); mpImpl->maResources.erase(iResource); } return pResult; } SdGlobalResourceContainer::SdGlobalResourceContainer (void) : mpImpl (new SdGlobalResourceContainer::Implementation()) { Implementation::mpInstance = this; } SdGlobalResourceContainer::~SdGlobalResourceContainer (void) { ::osl::MutexGuard aGuard (mpImpl->maMutex); // Release the resources in reversed order of their addition to the // container. This is because a resource A added before resource B // may have been created due to a request of B. Thus B depends on A and // should be destroyed first. Implementation::ResourceList::reverse_iterator iResource; for (iResource = mpImpl->maResources.rbegin(); iResource != mpImpl->maResources.rend(); ++iResource) { delete *iResource; } // The SharedResourceList has not to be released manually. We just // assert resources that are still held by someone other than us. Implementation::SharedResourceList::reverse_iterator iSharedResource; for (iSharedResource = mpImpl->maSharedResources.rbegin(); iSharedResource != mpImpl->maSharedResources.rend(); ++iSharedResource) { if ( ! iSharedResource->unique()) { SdGlobalResource* pResource = iSharedResource->get(); OSL_TRACE(" %p %d", pResource, iSharedResource->use_count()); DBG_ASSERT(iSharedResource->unique(), "SdGlobalResource still held in ~SdGlobalResourceContainer"); } } Implementation::XInterfaceResourceList::reverse_iterator iXInterfaceResource; for (iXInterfaceResource = mpImpl->maXInterfaceResources.rbegin(); iXInterfaceResource != mpImpl->maXInterfaceResources.rend(); ++iXInterfaceResource) { Reference<lang::XComponent> xComponent (*iXInterfaceResource, UNO_QUERY); *iXInterfaceResource = NULL; if (xComponent.is()) xComponent->dispose(); } DBG_ASSERT(Implementation::mpInstance == this, "~SdGlobalResourceContainer(): more than one instance of singleton"); Implementation::mpInstance = NULL; } } // end of namespace sd <|endoftext|>
<commit_before>#include <MockManager.h> #include <orbsvcs/CosNamingC.h> #include <acsutilPorts.h> namespace maci { /** Get a service, activating it if necessary (components). The client represented by id (the handle) must have adequate access rights to access the service. NOTE: a component is also a service, i.e. a service activated by a container. @return Reference to the service. If the service could not be activated, a nil reference is returned, and the status contains an error code detailing the cause of failure (one of the COMPONENT_* constants). */ CORBA::Object_ptr MockManager::get_service (maci::Handle id, const char * curl, CORBA::Boolean activate) throw (CORBA::SystemException, maciErrType::CannotGetComponentEx, maciErrType::ComponentNotAlreadyActivatedEx, maciErrType::ComponentConfigurationNotFoundEx) { // corbaloc::<hostname>:<port>/CDB const char* hostname = 0; hostname = ACSPorts::getIP(); if (hostname == 0) { return CORBA::Object::_nil(); } ACE_TCHAR corbalocRef[240]; ACE_OS::sprintf(corbalocRef, "corbaloc::%s:%s/CDB", hostname, ACSPorts::getCDBPort().c_str()); int nargc = 0; char **nargv = 0; CORBA::ORB_var orb = CORBA::ORB_init (nargc, nargv, ""); CORBA::Object_var object = orb->string_to_object(corbalocRef); return object._retn(); } /* CORBA::Object_ptr MockManager::resolveNameService(CORBA::ORB_ptr orb, int retries, unsigned int secTimeout) { if (CORBA::is_nil(orb)) return CosNaming::NamingContext::_nil(); // use CORBA::ORB::resolve_intial_references try { CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService"); if (!CORBA::is_nil (naming_obj.in ())) { CosNaming::NamingContext_var naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ()); if (naming_context.ptr() != CosNaming::NamingContext::_nil()) return naming_context._retn(); } } catch(...) { ACS_SHORT_LOG((LM_ERROR, "(logging::LoggingHelper::resolveNameService) CORBA exception caught!")); } // Environment variable LOG_NAMESERVICE_REFERENCE ACE_TCHAR * envRef = ACE_OS::getenv (LOG_NAMESERVICE_REFERENCE); if (envRef && *envRef) { //ACS_LOG(0, "logging::LoggingHelper::resolveNameService", // (LM_INFO, "NameService reference obtained via environment: '%s'", envRef)); // return reference return resolveNameService(orb, envRef, retries, secTimeout); } // corbaloc::<hostname>:<port>/NameService const char* hostname = 0; hostname = ACSPorts::getIP(); if (hostname==0) { return CosNaming::NamingContext::_nil(); } ACE_TCHAR corbalocRef[240]; ACE_OS::sprintf(corbalocRef, "corbaloc::%s:%s/NameService", hostname, ACSPorts::getNamingServicePort().c_str()); // return reference return resolveNameService(orb, corbalocRef, retries, secTimeout); } CORBA::Object_ptr MockManager::resolveNameService(CORBA::ORB_ptr orb, const ACE_TCHAR * reference, int retries, unsigned int secTimeout) { if (!reference || CORBA::is_nil(orb)) return CosNaming::NamingContext::_nil(); unsigned int secsToWait = 3, secsWaited = 0; int retried = 0; CosNaming::NamingContext_var ref = CosNaming::NamingContext::_nil(); while (!m_terminate) { try { CORBA::Object_var obj = orb->string_to_object(reference); ref = CosNaming::NamingContext::_narrow(obj.in()); return ref._retn(); } catch(...) { ref = CosNaming::NamingContext::_nil(); } if ( ((secTimeout != 0) && (secsWaited >= secTimeout)) || ((retries > 0) && (retried >= retries))) break; else ACE_OS::sleep(secsToWait); secsWaited += secsToWait; retried++; } return CosNaming::NamingContext::_nil(); } */ } #if 0 CosNaming::NamingContext_var naming_context; int nargc=0; char **nargv=0; const char *hn=ACSPorts::getIP(); ACE_CString iorFile; CORBA::Object_var obj = orb->string_to_object(reference); //ORBOPTS="-ORBDottedDecimalAddresses 1" // ORBOPTS="-ORBDottedDecimalAddresses 1" // -ORBEndpoint iiop://$HOST:$NAMING_SERVICE_PORT -o $NAME_IOR $ORBOPTS & if (argStr.find ("-ORBEndpoint")==ACE_CString::npos) { argStr = argStr + "-ORBEndpoint iiop://" + hn + ":" + ACSPorts::getLogPort().c_str(); } ACS_SHORT_LOG((LM_INFO, "New command line is: %s", argStr.c_str())); ACE_OS::string_to_argv ((ACE_TCHAR*)argStr.c_str(), nargc, nargv); ACE_OS::signal(SIGINT, TerminationSignalHandler); // Ctrl+C ACE_OS::signal(SIGTERM, TerminationSignalHandler); // termination request CORBA::ORB_var orb; try { // Initialize the ORB ACE_OS::printf ("Initialising ORB ... \n"); orb = CORBA::ORB_init (nargc, nargv, 0); ACE_OS::printf ("ORB initialsed !\n"); } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex, "Failed to initalise ORB"); return -1; } if (!ACSError::init(orb.in())) { ACS_SHORT_LOG ((LM_ERROR, "Failed to initalise the ACS Error System")); return -1; } // resolve naming service try { ACS_SHORT_LOG((LM_INFO, "Trying to connect to the Naming Service ....")); CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService"); if (!CORBA::is_nil (naming_obj.in ())) { naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ()); ACS_SHORT_LOG((LM_INFO, "Connected to the Name Service")); } else { ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!")); return -1; } } catch( CORBA::Exception &_ex ) { ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!")); return -1; } // adding ACSLog to NamingService if (!CORBA::is_nil (naming_context.in ())) { // register cdb server in Naming service CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup ("ACSLogSvc"); naming_context->rebind (name, obj.in ()); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc service registered with Naming Services")); } return 0; #endif <commit_msg><commit_after>#include <MockManager.h> #include <orbsvcs/CosNamingC.h> #include <acsutilPorts.h> namespace maci { /** Get a service, activating it if necessary (components). The client represented by id (the handle) must have adequate access rights to access the service. NOTE: a component is also a service, i.e. a service activated by a container. @return Reference to the service. If the service could not be activated, a nil reference is returned, and the status contains an error code detailing the cause of failure (one of the COMPONENT_* constants). */ CORBA::Object_ptr MockManager::get_service (maci::Handle id, const char * curl, CORBA::Boolean activate) throw (CORBA::SystemException, maciErrType::CannotGetComponentEx, maciErrType::ComponentNotAlreadyActivatedEx, maciErrType::ComponentConfigurationNotFoundEx) { // corbaloc::<hostname>:<port>/CDB const char* hostname = 0; hostname = ACSPorts::getIP(); if (hostname == 0) { return CORBA::Object::_nil(); } ACE_TCHAR corbalocRef[240]; ACE_OS::sprintf(corbalocRef, "corbaloc::%s:%s/CDB", hostname, ACSPorts::getCDBPort().c_str()); int nargc = 0; char **nargv = 0; CORBA::ORB_var orb = CORBA::ORB_init (nargc, nargv, ""); CORBA::Object_var object = orb->string_to_object(corbalocRef); return object._retn(); } } <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc++/server.h> #include <utility> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc++/completion_queue.h> #include <grpc++/async_generic_service.h> #include <grpc++/impl/rpc_service_method.h> #include <grpc++/impl/service_type.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/thread_pool_interface.h> #include <grpc++/time.h> #include "src/core/profiling/timers.h" namespace grpc { class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag { public: bool FinalizeResult(void** tag, bool* status) { delete this; return false; } }; class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { public: SyncRequest(RpcServiceMethod* method, void* tag) : method_(method), tag_(tag), in_flight_(false), has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::SERVER_STREAMING), call_details_(nullptr), cq_(nullptr) { grpc_metadata_array_init(&request_metadata_); } ~SyncRequest() { if (call_details_) { delete call_details_; } grpc_metadata_array_destroy(&request_metadata_); } static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { void* tag = nullptr; *ok = false; if (!cq->Next(&tag, ok)) { return nullptr; } auto* mrd = static_cast<SyncRequest*>(tag); GPR_ASSERT(mrd->in_flight_); return mrd; } void SetupRequest() { cq_ = grpc_completion_queue_create(); } void TeardownRequest() { grpc_completion_queue_destroy(cq_); cq_ = nullptr; } void Request(grpc_server* server, grpc_completion_queue* notify_cq) { GPR_ASSERT(cq_ && !in_flight_); in_flight_ = true; if (tag_) { GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call( server, tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, notify_cq, this)); } else { if (!call_details_) { call_details_ = new grpc_call_details; grpc_call_details_init(call_details_); } GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( server, &call_, call_details_, &request_metadata_, cq_, notify_cq, this)); } } bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { if (!*status) { grpc_completion_queue_destroy(cq_); } if (call_details_) { deadline_ = call_details_->deadline; grpc_call_details_destroy(call_details_); grpc_call_details_init(call_details_); } return true; } class CallData GRPC_FINAL { public: explicit CallData(Server* server, SyncRequest* mrd) : cq_(mrd->cq_), call_(mrd->call_, server, &cq_, server->max_message_size_), ctx_(mrd->deadline_, mrd->request_metadata_.metadata, mrd->request_metadata_.count), has_request_payload_(mrd->has_request_payload_), request_payload_(mrd->request_payload_), method_(mrd->method_) { ctx_.set_call(mrd->call_); ctx_.cq_ = &cq_; GPR_ASSERT(mrd->in_flight_); mrd->in_flight_ = false; mrd->request_metadata_.count = 0; } ~CallData() { if (has_request_payload_ && request_payload_) { grpc_byte_buffer_destroy(request_payload_); } } void Run() { ctx_.BeginCompletionOp(&call_); method_->handler()->RunHandler(MethodHandler::HandlerParameter( &call_, &ctx_, request_payload_, call_.max_message_size())); request_payload_ = nullptr; void* ignored_tag; bool ignored_ok; cq_.Shutdown(); GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false); } private: CompletionQueue cq_; Call call_; ServerContext ctx_; const bool has_request_payload_; grpc_byte_buffer* request_payload_; RpcServiceMethod* const method_; }; private: RpcServiceMethod* const method_; void* const tag_; bool in_flight_; const bool has_request_payload_; grpc_call* call_; grpc_call_details* call_details_; gpr_timespec deadline_; grpc_metadata_array request_metadata_; grpc_byte_buffer* request_payload_; grpc_completion_queue* cq_; }; static grpc_server* CreateServer(int max_message_size) { if (max_message_size > 0) { grpc_arg arg; arg.type = GRPC_ARG_INTEGER; arg.key = const_cast<char*>(GRPC_ARG_MAX_MESSAGE_LENGTH); arg.value.integer = max_message_size; grpc_channel_args args = {1, &arg}; return grpc_server_create(&args); } else { return grpc_server_create(nullptr); } } Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, int max_message_size) : max_message_size_(max_message_size), started_(false), shutdown_(false), num_running_cb_(0), sync_methods_(new std::list<SyncRequest>), has_generic_service_(false), server_(CreateServer(max_message_size)), thread_pool_(thread_pool), thread_pool_owned_(thread_pool_owned) { grpc_server_register_completion_queue(server_, cq_.cq()); } Server::~Server() { { grpc::unique_lock<grpc::mutex> lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } } void* got_tag; bool ok; GPR_ASSERT(!cq_.Next(&got_tag, &ok)); grpc_server_destroy(server_); if (thread_pool_owned_) { delete thread_pool_; } delete sync_methods_; } bool Server::RegisterService(const grpc::string *host, RpcService* service) { for (int i = 0; i < service->GetMethodCount(); ++i) { RpcServiceMethod* method = service->GetMethod(i); void* tag = grpc_server_register_method( server_, method->name(), host ? host->c_str() : nullptr); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } SyncRequest request(method, tag); sync_methods_->emplace_back(request); } return true; } bool Server::RegisterAsyncService(const grpc::string* host, AsynchronousService* service) { GPR_ASSERT(service->server_ == nullptr && "Can only register an asynchronous service against one server."); service->server_ = this; service->request_args_ = new void*[service->method_count_]; for (size_t i = 0; i < service->method_count_; ++i) { void* tag = grpc_server_register_method(server_, service->method_names_[i], host ? host->c_str() : nullptr); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", service->method_names_[i]); return false; } service->request_args_[i] = tag; } return true; } void Server::RegisterAsyncGenericService(AsyncGenericService* service) { GPR_ASSERT(service->server_ == nullptr && "Can only register an async generic service against one server."); service->server_ = this; has_generic_service_ = true; } int Server::AddListeningPort(const grpc::string& addr, ServerCredentials* creds) { GPR_ASSERT(!started_); return creds->AddPortToServer(addr, server_); } bool Server::Start() { GPR_ASSERT(!started_); started_ = true; grpc_server_start(server_); if (!has_generic_service_) { unknown_method_.reset(new RpcServiceMethod( "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler)); sync_methods_->emplace_back(SyncRequest(unknown_method_.get(), nullptr)); } // Start processing rpcs. if (!sync_methods_->empty()) { for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) { m->SetupRequest(); m->Request(server_, cq_.cq()); } ScheduleCallback(); } return true; } void Server::Shutdown() { grpc::unique_lock<grpc::mutex> lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest()); cq_.Shutdown(); // Wait for running callbacks to finish. while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } } void Server::Wait() { grpc::unique_lock<grpc::mutex> lock(mu_); while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) { static const size_t MAX_OPS = 8; size_t nops = 0; grpc_op cops[MAX_OPS]; ops->FillOps(cops, &nops); GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call->call(), cops, nops, ops)); } Server::BaseAsyncRequest::BaseAsyncRequest( Server* server, ServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag) : server_(server), context_(context), stream_(stream), call_cq_(call_cq), tag_(tag), call_(nullptr) { memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_)); } Server::BaseAsyncRequest::~BaseAsyncRequest() {} bool Server::BaseAsyncRequest::FinalizeResult(void** tag, bool* status) { if (*status) { for (size_t i = 0; i < initial_metadata_array_.count; i++) { context_->client_metadata_.insert(std::make_pair( grpc::string(initial_metadata_array_.metadata[i].key), grpc::string(initial_metadata_array_.metadata[i].value, initial_metadata_array_.metadata[i].value + initial_metadata_array_.metadata[i].value_length))); } } grpc_metadata_array_destroy(&initial_metadata_array_); context_->set_call(call_); context_->cq_ = call_cq_; Call call(call_, server_, call_cq_, server_->max_message_size_); if (*status && call_) { context_->BeginCompletionOp(&call); } // just the pointers inside call are copied here stream_->BindCall(&call); *tag = tag_; delete this; return true; } Server::RegisteredAsyncRequest::RegisteredAsyncRequest( Server* server, ServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag) : BaseAsyncRequest(server, context, stream, call_cq, tag) {} void Server::RegisteredAsyncRequest::IssueRequest( void* registered_method, grpc_byte_buffer** payload, ServerCompletionQueue* notification_cq) { grpc_server_request_registered_call( server_->server_, registered_method, &call_, &context_->deadline_, &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(), this); } Server::GenericAsyncRequest::GenericAsyncRequest( Server* server, GenericServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, ServerCompletionQueue* notification_cq, void* tag) : BaseAsyncRequest(server, context, stream, call_cq, tag) { grpc_call_details_init(&call_details_); GPR_ASSERT(notification_cq); GPR_ASSERT(call_cq); grpc_server_request_call(server->server_, &call_, &call_details_, &initial_metadata_array_, call_cq->cq(), notification_cq->cq(), this); } bool Server::GenericAsyncRequest::FinalizeResult(void** tag, bool* status) { // TODO(yangg) remove the copy here. if (*status) { static_cast<GenericServerContext*>(context_)->method_ = call_details_.method; static_cast<GenericServerContext*>(context_)->host_ = call_details_.host; } gpr_free(call_details_.method); gpr_free(call_details_.host); return BaseAsyncRequest::FinalizeResult(tag, status); } void Server::ScheduleCallback() { { grpc::unique_lock<grpc::mutex> lock(mu_); num_running_cb_++; } thread_pool_->Add(std::bind(&Server::RunRpc, this)); } void Server::RunRpc() { // Wait for one more incoming rpc. bool ok; auto* mrd = SyncRequest::Wait(&cq_, &ok); if (mrd) { ScheduleCallback(); if (ok) { SyncRequest::CallData cd(this, mrd); { mrd->SetupRequest(); grpc::unique_lock<grpc::mutex> lock(mu_); if (!shutdown_) { mrd->Request(server_, cq_.cq()); } else { // destroy the structure that was created mrd->TeardownRequest(); } } cd.Run(); } } { grpc::unique_lock<grpc::mutex> lock(mu_); num_running_cb_--; if (shutdown_) { callback_cv_.notify_all(); } } } } // namespace grpc <commit_msg>remove redundant ctor<commit_after>/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc++/server.h> #include <utility> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc++/completion_queue.h> #include <grpc++/async_generic_service.h> #include <grpc++/impl/rpc_service_method.h> #include <grpc++/impl/service_type.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/thread_pool_interface.h> #include <grpc++/time.h> #include "src/core/profiling/timers.h" namespace grpc { class Server::ShutdownRequest GRPC_FINAL : public CompletionQueueTag { public: bool FinalizeResult(void** tag, bool* status) { delete this; return false; } }; class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { public: SyncRequest(RpcServiceMethod* method, void* tag) : method_(method), tag_(tag), in_flight_(false), has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::SERVER_STREAMING), call_details_(nullptr), cq_(nullptr) { grpc_metadata_array_init(&request_metadata_); } ~SyncRequest() { if (call_details_) { delete call_details_; } grpc_metadata_array_destroy(&request_metadata_); } static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { void* tag = nullptr; *ok = false; if (!cq->Next(&tag, ok)) { return nullptr; } auto* mrd = static_cast<SyncRequest*>(tag); GPR_ASSERT(mrd->in_flight_); return mrd; } void SetupRequest() { cq_ = grpc_completion_queue_create(); } void TeardownRequest() { grpc_completion_queue_destroy(cq_); cq_ = nullptr; } void Request(grpc_server* server, grpc_completion_queue* notify_cq) { GPR_ASSERT(cq_ && !in_flight_); in_flight_ = true; if (tag_) { GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call( server, tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, notify_cq, this)); } else { if (!call_details_) { call_details_ = new grpc_call_details; grpc_call_details_init(call_details_); } GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( server, &call_, call_details_, &request_metadata_, cq_, notify_cq, this)); } } bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { if (!*status) { grpc_completion_queue_destroy(cq_); } if (call_details_) { deadline_ = call_details_->deadline; grpc_call_details_destroy(call_details_); grpc_call_details_init(call_details_); } return true; } class CallData GRPC_FINAL { public: explicit CallData(Server* server, SyncRequest* mrd) : cq_(mrd->cq_), call_(mrd->call_, server, &cq_, server->max_message_size_), ctx_(mrd->deadline_, mrd->request_metadata_.metadata, mrd->request_metadata_.count), has_request_payload_(mrd->has_request_payload_), request_payload_(mrd->request_payload_), method_(mrd->method_) { ctx_.set_call(mrd->call_); ctx_.cq_ = &cq_; GPR_ASSERT(mrd->in_flight_); mrd->in_flight_ = false; mrd->request_metadata_.count = 0; } ~CallData() { if (has_request_payload_ && request_payload_) { grpc_byte_buffer_destroy(request_payload_); } } void Run() { ctx_.BeginCompletionOp(&call_); method_->handler()->RunHandler(MethodHandler::HandlerParameter( &call_, &ctx_, request_payload_, call_.max_message_size())); request_payload_ = nullptr; void* ignored_tag; bool ignored_ok; cq_.Shutdown(); GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false); } private: CompletionQueue cq_; Call call_; ServerContext ctx_; const bool has_request_payload_; grpc_byte_buffer* request_payload_; RpcServiceMethod* const method_; }; private: RpcServiceMethod* const method_; void* const tag_; bool in_flight_; const bool has_request_payload_; grpc_call* call_; grpc_call_details* call_details_; gpr_timespec deadline_; grpc_metadata_array request_metadata_; grpc_byte_buffer* request_payload_; grpc_completion_queue* cq_; }; static grpc_server* CreateServer(int max_message_size) { if (max_message_size > 0) { grpc_arg arg; arg.type = GRPC_ARG_INTEGER; arg.key = const_cast<char*>(GRPC_ARG_MAX_MESSAGE_LENGTH); arg.value.integer = max_message_size; grpc_channel_args args = {1, &arg}; return grpc_server_create(&args); } else { return grpc_server_create(nullptr); } } Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned, int max_message_size) : max_message_size_(max_message_size), started_(false), shutdown_(false), num_running_cb_(0), sync_methods_(new std::list<SyncRequest>), has_generic_service_(false), server_(CreateServer(max_message_size)), thread_pool_(thread_pool), thread_pool_owned_(thread_pool_owned) { grpc_server_register_completion_queue(server_, cq_.cq()); } Server::~Server() { { grpc::unique_lock<grpc::mutex> lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } } void* got_tag; bool ok; GPR_ASSERT(!cq_.Next(&got_tag, &ok)); grpc_server_destroy(server_); if (thread_pool_owned_) { delete thread_pool_; } delete sync_methods_; } bool Server::RegisterService(const grpc::string *host, RpcService* service) { for (int i = 0; i < service->GetMethodCount(); ++i) { RpcServiceMethod* method = service->GetMethod(i); void* tag = grpc_server_register_method( server_, method->name(), host ? host->c_str() : nullptr); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } SyncRequest request(method, tag); sync_methods_->emplace_back(request); } return true; } bool Server::RegisterAsyncService(const grpc::string* host, AsynchronousService* service) { GPR_ASSERT(service->server_ == nullptr && "Can only register an asynchronous service against one server."); service->server_ = this; service->request_args_ = new void*[service->method_count_]; for (size_t i = 0; i < service->method_count_; ++i) { void* tag = grpc_server_register_method(server_, service->method_names_[i], host ? host->c_str() : nullptr); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", service->method_names_[i]); return false; } service->request_args_[i] = tag; } return true; } void Server::RegisterAsyncGenericService(AsyncGenericService* service) { GPR_ASSERT(service->server_ == nullptr && "Can only register an async generic service against one server."); service->server_ = this; has_generic_service_ = true; } int Server::AddListeningPort(const grpc::string& addr, ServerCredentials* creds) { GPR_ASSERT(!started_); return creds->AddPortToServer(addr, server_); } bool Server::Start() { GPR_ASSERT(!started_); started_ = true; grpc_server_start(server_); if (!has_generic_service_) { unknown_method_.reset(new RpcServiceMethod( "unknown", RpcMethod::BIDI_STREAMING, new UnknownMethodHandler)); sync_methods_->emplace_back(unknown_method_.get(), nullptr); } // Start processing rpcs. if (!sync_methods_->empty()) { for (auto m = sync_methods_->begin(); m != sync_methods_->end(); m++) { m->SetupRequest(); m->Request(server_, cq_.cq()); } ScheduleCallback(); } return true; } void Server::Shutdown() { grpc::unique_lock<grpc::mutex> lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; grpc_server_shutdown_and_notify(server_, cq_.cq(), new ShutdownRequest()); cq_.Shutdown(); // Wait for running callbacks to finish. while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } } void Server::Wait() { grpc::unique_lock<grpc::mutex> lock(mu_); while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } void Server::PerformOpsOnCall(CallOpSetInterface* ops, Call* call) { static const size_t MAX_OPS = 8; size_t nops = 0; grpc_op cops[MAX_OPS]; ops->FillOps(cops, &nops); GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call->call(), cops, nops, ops)); } Server::BaseAsyncRequest::BaseAsyncRequest( Server* server, ServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag) : server_(server), context_(context), stream_(stream), call_cq_(call_cq), tag_(tag), call_(nullptr) { memset(&initial_metadata_array_, 0, sizeof(initial_metadata_array_)); } Server::BaseAsyncRequest::~BaseAsyncRequest() {} bool Server::BaseAsyncRequest::FinalizeResult(void** tag, bool* status) { if (*status) { for (size_t i = 0; i < initial_metadata_array_.count; i++) { context_->client_metadata_.insert(std::make_pair( grpc::string(initial_metadata_array_.metadata[i].key), grpc::string(initial_metadata_array_.metadata[i].value, initial_metadata_array_.metadata[i].value + initial_metadata_array_.metadata[i].value_length))); } } grpc_metadata_array_destroy(&initial_metadata_array_); context_->set_call(call_); context_->cq_ = call_cq_; Call call(call_, server_, call_cq_, server_->max_message_size_); if (*status && call_) { context_->BeginCompletionOp(&call); } // just the pointers inside call are copied here stream_->BindCall(&call); *tag = tag_; delete this; return true; } Server::RegisteredAsyncRequest::RegisteredAsyncRequest( Server* server, ServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, void* tag) : BaseAsyncRequest(server, context, stream, call_cq, tag) {} void Server::RegisteredAsyncRequest::IssueRequest( void* registered_method, grpc_byte_buffer** payload, ServerCompletionQueue* notification_cq) { grpc_server_request_registered_call( server_->server_, registered_method, &call_, &context_->deadline_, &initial_metadata_array_, payload, call_cq_->cq(), notification_cq->cq(), this); } Server::GenericAsyncRequest::GenericAsyncRequest( Server* server, GenericServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* call_cq, ServerCompletionQueue* notification_cq, void* tag) : BaseAsyncRequest(server, context, stream, call_cq, tag) { grpc_call_details_init(&call_details_); GPR_ASSERT(notification_cq); GPR_ASSERT(call_cq); grpc_server_request_call(server->server_, &call_, &call_details_, &initial_metadata_array_, call_cq->cq(), notification_cq->cq(), this); } bool Server::GenericAsyncRequest::FinalizeResult(void** tag, bool* status) { // TODO(yangg) remove the copy here. if (*status) { static_cast<GenericServerContext*>(context_)->method_ = call_details_.method; static_cast<GenericServerContext*>(context_)->host_ = call_details_.host; } gpr_free(call_details_.method); gpr_free(call_details_.host); return BaseAsyncRequest::FinalizeResult(tag, status); } void Server::ScheduleCallback() { { grpc::unique_lock<grpc::mutex> lock(mu_); num_running_cb_++; } thread_pool_->Add(std::bind(&Server::RunRpc, this)); } void Server::RunRpc() { // Wait for one more incoming rpc. bool ok; auto* mrd = SyncRequest::Wait(&cq_, &ok); if (mrd) { ScheduleCallback(); if (ok) { SyncRequest::CallData cd(this, mrd); { mrd->SetupRequest(); grpc::unique_lock<grpc::mutex> lock(mu_); if (!shutdown_) { mrd->Request(server_, cq_.cq()); } else { // destroy the structure that was created mrd->TeardownRequest(); } } cd.Run(); } } { grpc::unique_lock<grpc::mutex> lock(mu_); num_running_cb_--; if (shutdown_) { callback_cv_.notify_all(); } } } } // namespace grpc <|endoftext|>
<commit_before>#include <algorithm> #include <iomanip> #include <sstream> #include "url.h" #include "agent.h" #include "directive.h" namespace { std::string escape_url(Url::Url& url) { return url.defrag().escape().fullpath(); } std::string trim_front(const std::string& str, const char chr) { auto itr = std::find_if(str.begin(), str.end(), [chr](const char c) {return c != chr;}); return std::string(itr, str.end()); } } namespace Rep { Agent& Agent::allow(const std::string& query) { Url::Url url(query); // ignore directives for external URLs if (is_external(url)) { return *this; } // leading wildcard? if (query.front() == '*') { Url::Url trimmed(trim_front(query, '*')); directives_.push_back(Directive(escape_url(trimmed), true)); } directives_.push_back(Directive(escape_url(url), true)); sorted_ = false; return *this; } Agent& Agent::disallow(const std::string& query) { if (query.empty()) { // Special case: "Disallow:" means "Allow: /" directives_.push_back(Directive(query, true)); } else { Url::Url url(query); // ignore directives for external URLs if (is_external(url)) { return *this; } // leading wildcard? if (query.front() == '*') { Url::Url trimmed(trim_front(query, '*')); directives_.push_back(Directive(escape_url(trimmed), false)); } directives_.push_back(Directive(escape_url(url), false)); } sorted_ = false; return *this; } const std::vector<Directive>& Agent::directives() const { if (!sorted_) { std::sort(directives_.begin(), directives_.end(), [](const Directive& a, const Directive& b) { return b.priority() < a.priority(); }); sorted_ = true; } return directives_; } bool Agent::allowed(const std::string& query) const { Url::Url url(query); if (is_external(url)) { return false; } std::string path(escape_url(url)); if (path.compare("/robots.txt") == 0) { return true; } for (const auto& directive : directives()) { if (directive.match(path)) { return directive.allowed(); } } return true; } std::string Agent::str() const { std::stringstream out; if (delay_ > 0) { out << "Crawl-Delay: " << std::setprecision(3) << delay_ << ' '; } out << '['; const auto& d = directives(); auto begin = d.begin(); auto end = d.end(); if (begin != end) { out << "Directive(" << begin->str() << ')'; ++begin; } for (; begin != end; ++begin) { out << ", Directive(" << begin->str() << ')'; } out << ']'; return out.str(); } bool Agent::is_external(const Url::Url& url) const { return !host_.empty() && !url.host().empty() && url.host() != host_; } } <commit_msg>Adding/removing errant blank lines.<commit_after>#include <algorithm> #include <iomanip> #include <sstream> #include "url.h" #include "agent.h" #include "directive.h" namespace { std::string escape_url(Url::Url& url) { return url.defrag().escape().fullpath(); } std::string trim_front(const std::string& str, const char chr) { auto itr = std::find_if(str.begin(), str.end(), [chr](const char c) {return c != chr;}); return std::string(itr, str.end()); } } namespace Rep { Agent& Agent::allow(const std::string& query) { Url::Url url(query); // ignore directives for external URLs if (is_external(url)) { return *this; } // leading wildcard? if (query.front() == '*') { Url::Url trimmed(trim_front(query, '*')); directives_.push_back(Directive(escape_url(trimmed), true)); } directives_.push_back(Directive(escape_url(url), true)); sorted_ = false; return *this; } Agent& Agent::disallow(const std::string& query) { if (query.empty()) { // Special case: "Disallow:" means "Allow: /" directives_.push_back(Directive(query, true)); } else { Url::Url url(query); // ignore directives for external URLs if (is_external(url)) { return *this; } // leading wildcard? if (query.front() == '*') { Url::Url trimmed(trim_front(query, '*')); directives_.push_back(Directive(escape_url(trimmed), false)); } directives_.push_back(Directive(escape_url(url), false)); } sorted_ = false; return *this; } const std::vector<Directive>& Agent::directives() const { if (!sorted_) { std::sort(directives_.begin(), directives_.end(), [](const Directive& a, const Directive& b) { return b.priority() < a.priority(); }); sorted_ = true; } return directives_; } bool Agent::allowed(const std::string& query) const { Url::Url url(query); if (is_external(url)) { return false; } std::string path(escape_url(url)); if (path.compare("/robots.txt") == 0) { return true; } for (const auto& directive : directives()) { if (directive.match(path)) { return directive.allowed(); } } return true; } std::string Agent::str() const { std::stringstream out; if (delay_ > 0) { out << "Crawl-Delay: " << std::setprecision(3) << delay_ << ' '; } out << '['; const auto& d = directives(); auto begin = d.begin(); auto end = d.end(); if (begin != end) { out << "Directive(" << begin->str() << ')'; ++begin; } for (; begin != end; ++begin) { out << ", Directive(" << begin->str() << ')'; } out << ']'; return out.str(); } bool Agent::is_external(const Url::Url& url) const { return !host_.empty() && !url.host().empty() && url.host() != host_; } } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2016 ROBOTIS 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. *******************************************************************************/ /* Authors: Taehoon Lim (Darby) */ #include <ros/ros.h> #include <sensor_msgs/BatteryState.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/MagneticField.h> #include <sensor_msgs/LaserScan.h> #include <diagnostic_msgs/DiagnosticArray.h> #include <turtlebot3_msgs/SensorState.h> #include <turtlebot3_msgs/VersionInfo.h> #define SOFTWARE_VERSION "1.0.0" #define FIRMWARE_VERSION "1.1.0" #define HARDWARE_VERSION "1.0.0" ros::Publisher tb3_diagnostics_pub; diagnostic_msgs::DiagnosticArray tb3_diagnostics; diagnostic_msgs::DiagnosticStatus imu_state; diagnostic_msgs::DiagnosticStatus motor_state; diagnostic_msgs::DiagnosticStatus LDS_state; diagnostic_msgs::DiagnosticStatus battery_state; diagnostic_msgs::DiagnosticStatus button_state; void setDiagnosisMsg(diagnostic_msgs::DiagnosticStatus *diag, uint8_t level, std::string name, std::string message, std::string hardware_id) { diag->level = level; diag->name = name; diag->message = message; diag->hardware_id = hardware_id; } void setIMUDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&imu_state, level, "IMU Sensor", message, "MPU9250"); } void setMotorDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&motor_state, level, "Actuator", message, "DYNAMIXEL X"); } void setBatteryDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&battery_state, level, "Power System", message, "Battery"); } void setLDSDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&LDS_state, level, "Lidar Sensor", message, "HLS-LFCD-LDS"); } void setButtonDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&button_state, level, "Analog Button", message, "OpenCR Button"); } void imuMsgCallback(const sensor_msgs::Imu::ConstPtr &msg) { setIMUDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Good Condition"); } void LDSMsgCallback(const sensor_msgs::LaserScan::ConstPtr &msg) { setLDSDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Good Condition"); } void sensorStateMsgCallback(const turtlebot3_msgs::SensorState::ConstPtr &msg) { if (msg->battery > 11.0) setBatteryDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Good Condition"); else setBatteryDiagnosis(diagnostic_msgs::DiagnosticStatus::WARN, "Charge!!! Charge!!!"); if (msg->button == turtlebot3_msgs::SensorState::BUTTON0) setButtonDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "BUTTON 0 IS PUSHED"); else if (msg->button == turtlebot3_msgs::SensorState::BUTTON1) setButtonDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "BUTTON 1 IS PUSHED"); else setButtonDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Pushed Nothing"); if (msg->torque == true) setMotorDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Torque ON"); else setMotorDiagnosis(diagnostic_msgs::DiagnosticStatus::WARN, "Torque OFF"); } void versionMsgCallback(const turtlebot3_msgs::VersionInfo::ConstPtr &msg) { if (std::string(msg->software) != std::string(SOFTWARE_VERSION)) ROS_WARN("Check turtlebot3 repository and Update your software!!"); if (std::string(msg->hardware) != std::string(HARDWARE_VERSION)) ROS_WARN("Check turtlebot3 wiki page and Update your hardware!!"); if (std::string(msg->firmware) != std::string(FIRMWARE_VERSION)) ROS_WARN("Check OpenCR update and change your firmware!!"); } void msgPub() { tb3_diagnostics.header.stamp = ros::Time::now(); tb3_diagnostics.status.clear(); tb3_diagnostics.status.push_back(imu_state); tb3_diagnostics.status.push_back(motor_state); tb3_diagnostics.status.push_back(LDS_state); tb3_diagnostics.status.push_back(battery_state); tb3_diagnostics.status.push_back(button_state); tb3_diagnostics_pub.publish(tb3_diagnostics); } int main(int argc, char **argv) { ros::init(argc, argv, "turtlebot3_diagnostic"); ros::NodeHandle nh; tb3_diagnostics_pub = nh.advertise<diagnostic_msgs::DiagnosticArray>("diagnostics", 10); ros::Subscriber imu = nh.subscribe("/imu", 10, imuMsgCallback); ros::Subscriber lds = nh.subscribe("/scan", 10, LDSMsgCallback); ros::Subscriber tb3_sensor = nh.subscribe("/sensor_state", 10, sensorStateMsgCallback); ros::Subscriber version = nh.subscribe("/version_info", 10, versionMsgCallback); ros::Rate loop_rate(1); while (ros::ok()) { msgPub(); ros::spinOnce(); loop_rate.sleep(); } return 0; } <commit_msg>update firmware version(1.1.1)<commit_after>/******************************************************************************* * Copyright 2016 ROBOTIS 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. *******************************************************************************/ /* Authors: Taehoon Lim (Darby) */ #include <ros/ros.h> #include <sensor_msgs/BatteryState.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/MagneticField.h> #include <sensor_msgs/LaserScan.h> #include <diagnostic_msgs/DiagnosticArray.h> #include <turtlebot3_msgs/SensorState.h> #include <turtlebot3_msgs/VersionInfo.h> #define SOFTWARE_VERSION "1.0.0" #define FIRMWARE_VERSION "1.1.1" #define HARDWARE_VERSION "1.0.0" ros::Publisher tb3_diagnostics_pub; diagnostic_msgs::DiagnosticArray tb3_diagnostics; diagnostic_msgs::DiagnosticStatus imu_state; diagnostic_msgs::DiagnosticStatus motor_state; diagnostic_msgs::DiagnosticStatus LDS_state; diagnostic_msgs::DiagnosticStatus battery_state; diagnostic_msgs::DiagnosticStatus button_state; void setDiagnosisMsg(diagnostic_msgs::DiagnosticStatus *diag, uint8_t level, std::string name, std::string message, std::string hardware_id) { diag->level = level; diag->name = name; diag->message = message; diag->hardware_id = hardware_id; } void setIMUDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&imu_state, level, "IMU Sensor", message, "MPU9250"); } void setMotorDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&motor_state, level, "Actuator", message, "DYNAMIXEL X"); } void setBatteryDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&battery_state, level, "Power System", message, "Battery"); } void setLDSDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&LDS_state, level, "Lidar Sensor", message, "HLS-LFCD-LDS"); } void setButtonDiagnosis(uint8_t level, std::string message) { setDiagnosisMsg(&button_state, level, "Analog Button", message, "OpenCR Button"); } void imuMsgCallback(const sensor_msgs::Imu::ConstPtr &msg) { setIMUDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Good Condition"); } void LDSMsgCallback(const sensor_msgs::LaserScan::ConstPtr &msg) { setLDSDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Good Condition"); } void sensorStateMsgCallback(const turtlebot3_msgs::SensorState::ConstPtr &msg) { if (msg->battery > 11.0) setBatteryDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Good Condition"); else setBatteryDiagnosis(diagnostic_msgs::DiagnosticStatus::WARN, "Charge!!! Charge!!!"); if (msg->button == turtlebot3_msgs::SensorState::BUTTON0) setButtonDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "BUTTON 0 IS PUSHED"); else if (msg->button == turtlebot3_msgs::SensorState::BUTTON1) setButtonDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "BUTTON 1 IS PUSHED"); else setButtonDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Pushed Nothing"); if (msg->torque == true) setMotorDiagnosis(diagnostic_msgs::DiagnosticStatus::OK, "Torque ON"); else setMotorDiagnosis(diagnostic_msgs::DiagnosticStatus::WARN, "Torque OFF"); } void versionMsgCallback(const turtlebot3_msgs::VersionInfo::ConstPtr &msg) { if (std::string(msg->software) != std::string(SOFTWARE_VERSION)) ROS_WARN("Check turtlebot3 repository and Update your software!!"); if (std::string(msg->hardware) != std::string(HARDWARE_VERSION)) ROS_WARN("Check turtlebot3 wiki page and Update your hardware!!"); if (std::string(msg->firmware) != std::string(FIRMWARE_VERSION)) ROS_WARN("Check OpenCR update and change your firmware!!"); } void msgPub() { tb3_diagnostics.header.stamp = ros::Time::now(); tb3_diagnostics.status.clear(); tb3_diagnostics.status.push_back(imu_state); tb3_diagnostics.status.push_back(motor_state); tb3_diagnostics.status.push_back(LDS_state); tb3_diagnostics.status.push_back(battery_state); tb3_diagnostics.status.push_back(button_state); tb3_diagnostics_pub.publish(tb3_diagnostics); } int main(int argc, char **argv) { ros::init(argc, argv, "turtlebot3_diagnostic"); ros::NodeHandle nh; tb3_diagnostics_pub = nh.advertise<diagnostic_msgs::DiagnosticArray>("diagnostics", 10); ros::Subscriber imu = nh.subscribe("/imu", 10, imuMsgCallback); ros::Subscriber lds = nh.subscribe("/scan", 10, LDSMsgCallback); ros::Subscriber tb3_sensor = nh.subscribe("/sensor_state", 10, sensorStateMsgCallback); ros::Subscriber version = nh.subscribe("/version_info", 10, versionMsgCallback); ros::Rate loop_rate(1); while (ros::ok()) { msgPub(); ros::spinOnce(); loop_rate.sleep(); } return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/BitmapImage.h" #include "platform/SharedBuffer.h" #include "platform/graphics/ImageObserver.h" #include "public/platform/Platform.h" #include "public/platform/WebUnitTestSupport.h" #include <gtest/gtest.h> namespace WebCore { class BitmapImageTest : public ::testing::Test { public: class FakeImageObserver : public ImageObserver { public: FakeImageObserver() : m_lastDecodedSizeChangedDelta(0) { } virtual void decodedSizeChanged(const Image*, int delta) { m_lastDecodedSizeChangedDelta = delta; } virtual void didDraw(const Image*) OVERRIDE { } virtual bool shouldPauseAnimation(const Image*) OVERRIDE { return false; } virtual void animationAdvanced(const Image*) OVERRIDE { } virtual void changedInRect(const Image*, const IntRect&) { } int m_lastDecodedSizeChangedDelta; }; static PassRefPtr<SharedBuffer> readFile(const char* fileName) { String filePath = blink::Platform::current()->unitTestSupport()->webKitRootDir(); filePath.append(fileName); return blink::Platform::current()->unitTestSupport()->readFromFile(filePath); } // Accessors to BitmapImage's protected methods. void destroyDecodedData(bool destroyAll) { m_image->destroyDecodedData(destroyAll); } size_t frameCount() { return m_image->frameCount(); } void setCurrentFrame(size_t frame) { m_image->m_currentFrame = frame; } size_t frameDecodedSize(size_t frame) { return m_image->m_frames[frame].m_frameBytes; } size_t decodedFramesCount() const { return m_image->m_frames.size(); } void loadImage(const char* fileName) { RefPtr<SharedBuffer> imageData = readFile("/LayoutTests/fast/images/resources/animated-10color.gif"); ASSERT_TRUE(imageData.get()); m_image->setData(imageData, true); EXPECT_EQ(0u, decodedSize()); size_t frameCount = m_image->frameCount(); for (size_t i = 0; i < frameCount; ++i) m_image->frameAtIndex(i); } size_t decodedSize() { // In the context of this test, the following loop will give the correct result, but only because the test // forces all frames to be decoded in loadImage() above. There is no general guarantee that frameDecodedSize() // is up-to-date. Because of how multi frame images (like GIF) work, requesting one frame to be decoded may // require other previous frames to be decoded as well. In those cases frameDecodedSize() wouldn't return the // correct thing for the previous frame because the decoded size wouldn't have propagated upwards to the // BitmapImage frame cache. size_t size = 0; for (size_t i = 0; i < decodedFramesCount(); ++i) size += frameDecodedSize(i); return size; } protected: virtual void SetUp() OVERRIDE { m_image = BitmapImage::create(&m_imageObserver); } FakeImageObserver m_imageObserver; RefPtr<BitmapImage> m_image; }; TEST_F(BitmapImageTest, destroyDecodedDataExceptCurrentFrame) { loadImage("/LayoutTests/fast/images/resources/animated-10color.gif"); size_t totalSize = decodedSize(); size_t frame = frameCount() / 2; setCurrentFrame(frame); size_t size = frameDecodedSize(frame); destroyDecodedData(false); EXPECT_LT(m_imageObserver.m_lastDecodedSizeChangedDelta, 0); EXPECT_GE(m_imageObserver.m_lastDecodedSizeChangedDelta, -static_cast<int>(totalSize - size)); } TEST_F(BitmapImageTest, destroyAllDecodedData) { loadImage("/LayoutTests/fast/images/resources/animated-10color.gif"); size_t totalSize = decodedSize(); EXPECT_GT(totalSize, 0u); destroyDecodedData(true); EXPECT_EQ(-static_cast<int>(totalSize), m_imageObserver.m_lastDecodedSizeChangedDelta); EXPECT_EQ(0u, decodedSize()); } } // namespace <commit_msg>Turn off BitmapImageTest on windows<commit_after>/* * Copyright (c) 2013, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/BitmapImage.h" #include "platform/SharedBuffer.h" #include "platform/graphics/ImageObserver.h" #include "public/platform/Platform.h" #include "public/platform/WebUnitTestSupport.h" #include <gtest/gtest.h> namespace WebCore { class BitmapImageTest : public ::testing::Test { public: class FakeImageObserver : public ImageObserver { public: FakeImageObserver() : m_lastDecodedSizeChangedDelta(0) { } virtual void decodedSizeChanged(const Image*, int delta) { m_lastDecodedSizeChangedDelta = delta; } virtual void didDraw(const Image*) OVERRIDE { } virtual bool shouldPauseAnimation(const Image*) OVERRIDE { return false; } virtual void animationAdvanced(const Image*) OVERRIDE { } virtual void changedInRect(const Image*, const IntRect&) { } int m_lastDecodedSizeChangedDelta; }; static PassRefPtr<SharedBuffer> readFile(const char* fileName) { String filePath = blink::Platform::current()->unitTestSupport()->webKitRootDir(); filePath.append(fileName); return blink::Platform::current()->unitTestSupport()->readFromFile(filePath); } // Accessors to BitmapImage's protected methods. void destroyDecodedData(bool destroyAll) { m_image->destroyDecodedData(destroyAll); } size_t frameCount() { return m_image->frameCount(); } void setCurrentFrame(size_t frame) { m_image->m_currentFrame = frame; } size_t frameDecodedSize(size_t frame) { return m_image->m_frames[frame].m_frameBytes; } size_t decodedFramesCount() const { return m_image->m_frames.size(); } void loadImage(const char* fileName) { RefPtr<SharedBuffer> imageData = readFile("/LayoutTests/fast/images/resources/animated-10color.gif"); ASSERT_TRUE(imageData.get()); m_image->setData(imageData, true); EXPECT_EQ(0u, decodedSize()); size_t frameCount = m_image->frameCount(); for (size_t i = 0; i < frameCount; ++i) m_image->frameAtIndex(i); } size_t decodedSize() { // In the context of this test, the following loop will give the correct result, but only because the test // forces all frames to be decoded in loadImage() above. There is no general guarantee that frameDecodedSize() // is up-to-date. Because of how multi frame images (like GIF) work, requesting one frame to be decoded may // require other previous frames to be decoded as well. In those cases frameDecodedSize() wouldn't return the // correct thing for the previous frame because the decoded size wouldn't have propagated upwards to the // BitmapImage frame cache. size_t size = 0; for (size_t i = 0; i < decodedFramesCount(); ++i) size += frameDecodedSize(i); return size; } protected: virtual void SetUp() OVERRIDE { m_image = BitmapImage::create(&m_imageObserver); } FakeImageObserver m_imageObserver; RefPtr<BitmapImage> m_image; }; // Fails on certain XP bots, but passes on others // crbug.com/321184 #if OS(WIN) #define destroyDecodedDataExceptCurrentFrame DISABLED_destroyDecodedDataExceptCurrentFrame #endif TEST_F(BitmapImageTest, destroyDecodedDataExceptCurrentFrame) { loadImage("/LayoutTests/fast/images/resources/animated-10color.gif"); size_t totalSize = decodedSize(); size_t frame = frameCount() / 2; setCurrentFrame(frame); size_t size = frameDecodedSize(frame); destroyDecodedData(false); EXPECT_LT(m_imageObserver.m_lastDecodedSizeChangedDelta, 0); EXPECT_GE(m_imageObserver.m_lastDecodedSizeChangedDelta, -static_cast<int>(totalSize - size)); } // Fails on certain XP bots, but passes on others // crbug.com/321184 #if OS(WIN) #define destroyAllDecodedData DISABLED_destroyAllDecodedData #endif TEST_F(BitmapImageTest, destroyAllDecodedData) { loadImage("/LayoutTests/fast/images/resources/animated-10color.gif"); size_t totalSize = decodedSize(); EXPECT_GT(totalSize, 0u); destroyDecodedData(true); EXPECT_EQ(-static_cast<int>(totalSize), m_imageObserver.m_lastDecodedSizeChangedDelta); EXPECT_EQ(0u, decodedSize()); } } // namespace <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkUSZoneManagementWidget.h" #include "ui_QmitkUSZoneManagementWidget.h" #include "../QmitkUSZonesDataModel.h" #include "../QmitkUSZoneManagementColorDialogDelegate.h" #include "../Interactors/mitkUSZonesInteractor.h" #include "usModuleRegistry.h" #include "usModule.h" #include "mitkGlobalInteraction.h" #include "mitkSurface.h" #include <QLatin1Char> QmitkUSZoneManagementWidget::QmitkUSZoneManagementWidget(QWidget *parent) : QWidget(parent), m_ZonesDataModel(new QmitkUSZonesDataModel(this)), m_Interactor(mitk::USZonesInteractor::New()), m_StateMachineFileName("USZoneInteractions.xml"), ui(new Ui::QmitkUSZoneManagementWidget), m_CurMaxNumOfZones(0) { ui->setupUi(this); ui->CurrentZonesTable->setModel(m_ZonesDataModel); ui->CurrentZonesTable->setItemDelegateForColumn(2, new QmitkUSZoneManagementColorDialogDelegate(this)); connect (ui->CurrentZonesTable->selectionModel(), SIGNAL(selectionChanged(const QItemSelection& , const QItemSelection&)), this, SLOT(OnSelectionChanged(const QItemSelection&, const QItemSelection&))); connect (m_ZonesDataModel, SIGNAL(rowsInserted(const QModelIndex&, int, int )), this, SLOT(OnRowInsertion(QModelIndex,int,int))); connect (m_ZonesDataModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnDataChanged(const QModelIndex&, const QModelIndex&))); // load state machine and event config for data interactor m_Interactor->LoadStateMachine(m_StateMachineFileName, us::ModuleRegistry::GetModule("MitkUS")); m_Interactor->SetEventConfig("globalConfig.xml"); } QmitkUSZoneManagementWidget::~QmitkUSZoneManagementWidget() { delete ui; if ( m_DataStorage.IsNotNull() && m_BaseNode.IsNotNull() ) { m_DataStorage->Remove(m_BaseNode); } } void QmitkUSZoneManagementWidget::SetStateMachineFilename(const std::string& filename) { m_StateMachineFileName = filename; m_Interactor->LoadStateMachine(filename, us::ModuleRegistry::GetModule("MitkUS")); } void QmitkUSZoneManagementWidget::SetDataStorage(mitk::DataStorage::Pointer dataStorage, const char* baseNodeName) { if ( dataStorage.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage must not be null."; mitkThrow() << "DataStorage must not be null."; } mitk::DataNode::Pointer baseNode = dataStorage->GetNamedNode(baseNodeName); if ( baseNode.IsNull() ) { baseNode = mitk::DataNode::New(); baseNode->SetName(baseNodeName); dataStorage->Add(baseNode); } baseNode->SetData(mitk::Surface::New()); m_ZonesDataModel->SetDataStorage(dataStorage, baseNode); m_BaseNode = baseNode; m_DataStorage = dataStorage; } void QmitkUSZoneManagementWidget::SetDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::DataNode::Pointer baseNode) { if ( dataStorage.IsNull() || baseNode.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage and BaseNode must not be null."; mitkThrow() << "DataStorage and BaseNode must not be null."; } if ( ! baseNode->GetData() ) { baseNode->SetData(mitk::Surface::New()); } m_ZonesDataModel->SetDataStorage(dataStorage, baseNode); m_BaseNode = baseNode; m_DataStorage = dataStorage; } mitk::DataStorage::SetOfObjects::ConstPointer QmitkUSZoneManagementWidget::GetZoneNodes() { if ( m_DataStorage.IsNotNull() && m_BaseNode.IsNotNull() ) { return m_DataStorage->GetDerivations(m_BaseNode); } else { MITK_WARN("QWidget")("QmitkUSZoneManagementWidget") << "Data storage or base node is null. Returning empty zone nodes set."; return mitk::DataStorage::SetOfObjects::New().GetPointer(); } } void QmitkUSZoneManagementWidget::RemoveSelectedRows() { QItemSelectionModel* selectionModel = ui->CurrentZonesTable->selectionModel(); if ( ! selectionModel->hasSelection() ) { MITK_WARN("QWidget")("QmitkUSZoneManagementWidget") << "RemoveSelectedRows() called without any row being selected."; return; } QModelIndexList selectedRows = selectionModel->selectedRows(); // sorted indices are assumed QListIterator<QModelIndex> i(selectedRows); i.toBack(); while (i.hasPrevious()) { m_ZonesDataModel->removeRow(i.previous().row()); } emit ZoneRemoved(); } void QmitkUSZoneManagementWidget::OnStartAddingZone() { if ( m_DataStorage.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage must be set before adding the first zone."; mitkThrow() << "DataStorage must be set before adding the first zone."; } // workaround for bug 16407 m_Interactor = mitk::USZonesInteractor::New(); m_Interactor->LoadStateMachine(m_StateMachineFileName, us::ModuleRegistry::GetModule("USNavigationPlugin")); m_Interactor->SetEventConfig("globalConfig.xml"); mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); // zone number is added to zone name (padding one zero) dataNode->SetName((QString("Zone ")+QString("%1").arg(m_CurMaxNumOfZones+1, 2, 10, QLatin1Char('0'))).toStdString()); dataNode->SetColor(0.9, 0.9, 0); m_DataStorage->Add(dataNode, m_BaseNode); m_Interactor->SetDataNode(dataNode); } void QmitkUSZoneManagementWidget::OnAbortAddingZone() { if ( m_DataStorage.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage must be set before aborting adding a zone."; mitkThrow() << "DataStorage must be set before aborting adding a zone."; } m_DataStorage->Remove(m_Interactor->GetDataNode()); } void QmitkUSZoneManagementWidget::OnResetZones() { // remove all zone nodes from the data storage if ( m_DataStorage.IsNotNull() && m_BaseNode.IsNotNull() ) { m_DataStorage->Remove(m_DataStorage->GetDerivations(m_BaseNode)); } m_CurMaxNumOfZones = 0; } void QmitkUSZoneManagementWidget::OnSelectionChanged(const QItemSelection & selected, const QItemSelection & /*deselected*/) { bool somethingSelected = ! selected.empty() && m_ZonesDataModel->rowCount() > 0; ui->ZoneSizeLabel->setEnabled(somethingSelected); ui->ZoneSizeSlider->setEnabled(somethingSelected); ui->DeleteZoneButton->setEnabled(somethingSelected); if (somethingSelected) { ui->ZoneSizeSlider->setValue( m_ZonesDataModel->data(m_ZonesDataModel->index(selected.at(0).top(), 1)).toInt()); } } void QmitkUSZoneManagementWidget::OnZoneSizeSliderValueChanged(int value) { QItemSelectionModel* selection = ui->CurrentZonesTable->selectionModel(); if ( ! selection->hasSelection() ) { return; } m_ZonesDataModel->setData(m_ZonesDataModel->index(selection->selectedRows().at(0).row(), 1), value); } void QmitkUSZoneManagementWidget::OnRowInsertion( const QModelIndex & /*parent*/, int /*start*/, int end ) { // increase zone number for unique names for every zone m_CurMaxNumOfZones++; ui->CurrentZonesTable->selectRow(end); emit ZoneAdded(); } void QmitkUSZoneManagementWidget::OnDataChanged(const QModelIndex& topLeft, const QModelIndex& /*bottomRight*/) { QItemSelectionModel* selection = ui->CurrentZonesTable->selectionModel(); if ( ! selection->hasSelection() || selection->selectedRows().size() < 1 ) { return; } if ( selection->selectedRows().at(0) == topLeft ) { ui->ZoneSizeSlider->setValue( m_ZonesDataModel->data(m_ZonesDataModel->index(topLeft.row(), 1)).toInt()); } } <commit_msg>fixed bug with including state machines: critical structures can now be marked again<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkUSZoneManagementWidget.h" #include "ui_QmitkUSZoneManagementWidget.h" #include "../QmitkUSZonesDataModel.h" #include "../QmitkUSZoneManagementColorDialogDelegate.h" #include "../Interactors/mitkUSZonesInteractor.h" #include "usModuleRegistry.h" #include "usModule.h" #include "mitkGlobalInteraction.h" #include "mitkSurface.h" #include <QLatin1Char> QmitkUSZoneManagementWidget::QmitkUSZoneManagementWidget(QWidget *parent) : QWidget(parent), m_ZonesDataModel(new QmitkUSZonesDataModel(this)), m_Interactor(mitk::USZonesInteractor::New()), m_StateMachineFileName("USZoneInteractions.xml"), ui(new Ui::QmitkUSZoneManagementWidget), m_CurMaxNumOfZones(0) { ui->setupUi(this); ui->CurrentZonesTable->setModel(m_ZonesDataModel); ui->CurrentZonesTable->setItemDelegateForColumn(2, new QmitkUSZoneManagementColorDialogDelegate(this)); connect (ui->CurrentZonesTable->selectionModel(), SIGNAL(selectionChanged(const QItemSelection& , const QItemSelection&)), this, SLOT(OnSelectionChanged(const QItemSelection&, const QItemSelection&))); connect (m_ZonesDataModel, SIGNAL(rowsInserted(const QModelIndex&, int, int )), this, SLOT(OnRowInsertion(QModelIndex,int,int))); connect (m_ZonesDataModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnDataChanged(const QModelIndex&, const QModelIndex&))); // load state machine and event config for data interactor m_Interactor->LoadStateMachine(m_StateMachineFileName, us::ModuleRegistry::GetModule("MitkUS")); m_Interactor->SetEventConfig("globalConfig.xml"); } QmitkUSZoneManagementWidget::~QmitkUSZoneManagementWidget() { delete ui; if ( m_DataStorage.IsNotNull() && m_BaseNode.IsNotNull() ) { m_DataStorage->Remove(m_BaseNode); } } void QmitkUSZoneManagementWidget::SetStateMachineFilename(const std::string& filename) { m_StateMachineFileName = filename; m_Interactor->LoadStateMachine(filename, us::ModuleRegistry::GetModule("MitkUS")); } void QmitkUSZoneManagementWidget::SetDataStorage(mitk::DataStorage::Pointer dataStorage, const char* baseNodeName) { if ( dataStorage.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage must not be null."; mitkThrow() << "DataStorage must not be null."; } mitk::DataNode::Pointer baseNode = dataStorage->GetNamedNode(baseNodeName); if ( baseNode.IsNull() ) { baseNode = mitk::DataNode::New(); baseNode->SetName(baseNodeName); dataStorage->Add(baseNode); } baseNode->SetData(mitk::Surface::New()); m_ZonesDataModel->SetDataStorage(dataStorage, baseNode); m_BaseNode = baseNode; m_DataStorage = dataStorage; } void QmitkUSZoneManagementWidget::SetDataStorage(mitk::DataStorage::Pointer dataStorage, mitk::DataNode::Pointer baseNode) { if ( dataStorage.IsNull() || baseNode.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage and BaseNode must not be null."; mitkThrow() << "DataStorage and BaseNode must not be null."; } if ( ! baseNode->GetData() ) { baseNode->SetData(mitk::Surface::New()); } m_ZonesDataModel->SetDataStorage(dataStorage, baseNode); m_BaseNode = baseNode; m_DataStorage = dataStorage; } mitk::DataStorage::SetOfObjects::ConstPointer QmitkUSZoneManagementWidget::GetZoneNodes() { if ( m_DataStorage.IsNotNull() && m_BaseNode.IsNotNull() ) { return m_DataStorage->GetDerivations(m_BaseNode); } else { MITK_WARN("QWidget")("QmitkUSZoneManagementWidget") << "Data storage or base node is null. Returning empty zone nodes set."; return mitk::DataStorage::SetOfObjects::New().GetPointer(); } } void QmitkUSZoneManagementWidget::RemoveSelectedRows() { QItemSelectionModel* selectionModel = ui->CurrentZonesTable->selectionModel(); if ( ! selectionModel->hasSelection() ) { MITK_WARN("QWidget")("QmitkUSZoneManagementWidget") << "RemoveSelectedRows() called without any row being selected."; return; } QModelIndexList selectedRows = selectionModel->selectedRows(); // sorted indices are assumed QListIterator<QModelIndex> i(selectedRows); i.toBack(); while (i.hasPrevious()) { m_ZonesDataModel->removeRow(i.previous().row()); } emit ZoneRemoved(); } void QmitkUSZoneManagementWidget::OnStartAddingZone() { if ( m_DataStorage.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage must be set before adding the first zone."; mitkThrow() << "DataStorage must be set before adding the first zone."; } // workaround for bug 16407 m_Interactor = mitk::USZonesInteractor::New(); m_Interactor->LoadStateMachine(m_StateMachineFileName, us::ModuleRegistry::GetModule("MitkUS")); m_Interactor->SetEventConfig("globalConfig.xml"); mitk::DataNode::Pointer dataNode = mitk::DataNode::New(); // zone number is added to zone name (padding one zero) dataNode->SetName((QString("Zone ")+QString("%1").arg(m_CurMaxNumOfZones+1, 2, 10, QLatin1Char('0'))).toStdString()); dataNode->SetColor(0.9, 0.9, 0); m_DataStorage->Add(dataNode, m_BaseNode); m_Interactor->SetDataNode(dataNode); } void QmitkUSZoneManagementWidget::OnAbortAddingZone() { if ( m_DataStorage.IsNull() ) { MITK_ERROR("QWidget")("QmitkUSZoneManagementWidget") << "DataStorage must be set before aborting adding a zone."; mitkThrow() << "DataStorage must be set before aborting adding a zone."; } m_DataStorage->Remove(m_Interactor->GetDataNode()); } void QmitkUSZoneManagementWidget::OnResetZones() { // remove all zone nodes from the data storage if ( m_DataStorage.IsNotNull() && m_BaseNode.IsNotNull() ) { m_DataStorage->Remove(m_DataStorage->GetDerivations(m_BaseNode)); } m_CurMaxNumOfZones = 0; } void QmitkUSZoneManagementWidget::OnSelectionChanged(const QItemSelection & selected, const QItemSelection & /*deselected*/) { bool somethingSelected = ! selected.empty() && m_ZonesDataModel->rowCount() > 0; ui->ZoneSizeLabel->setEnabled(somethingSelected); ui->ZoneSizeSlider->setEnabled(somethingSelected); ui->DeleteZoneButton->setEnabled(somethingSelected); if (somethingSelected) { ui->ZoneSizeSlider->setValue( m_ZonesDataModel->data(m_ZonesDataModel->index(selected.at(0).top(), 1)).toInt()); } } void QmitkUSZoneManagementWidget::OnZoneSizeSliderValueChanged(int value) { QItemSelectionModel* selection = ui->CurrentZonesTable->selectionModel(); if ( ! selection->hasSelection() ) { return; } m_ZonesDataModel->setData(m_ZonesDataModel->index(selection->selectedRows().at(0).row(), 1), value); } void QmitkUSZoneManagementWidget::OnRowInsertion( const QModelIndex & /*parent*/, int /*start*/, int end ) { // increase zone number for unique names for every zone m_CurMaxNumOfZones++; ui->CurrentZonesTable->selectRow(end); emit ZoneAdded(); } void QmitkUSZoneManagementWidget::OnDataChanged(const QModelIndex& topLeft, const QModelIndex& /*bottomRight*/) { QItemSelectionModel* selection = ui->CurrentZonesTable->selectionModel(); if ( ! selection->hasSelection() || selection->selectedRows().size() < 1 ) { return; } if ( selection->selectedRows().at(0) == topLeft ) { ui->ZoneSizeSlider->setValue( m_ZonesDataModel->data(m_ZonesDataModel->index(topLeft.row(), 1)).toInt()); } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "libtorrent/pch.hpp" #include "libtorrent/alert.hpp" #include <boost/thread/xtime.hpp> namespace libtorrent { alert::alert() : m_timestamp(time_now()) {} alert::~alert() {} ptime alert::timestamp() const { return m_timestamp; } alert_manager::alert_manager() : m_alert_mask(alert::error_notification) , m_queue_size_limit(queue_size_limit_default) {} alert_manager::~alert_manager() { while (!m_alerts.empty()) { delete m_alerts.front(); m_alerts.pop(); } } alert const* alert_manager::wait_for_alert(time_duration max_wait) { boost::mutex::scoped_lock lock(m_mutex); if (!m_alerts.empty()) return m_alerts.front(); int secs = total_seconds(max_wait); max_wait -= seconds(secs); boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); xt.sec += secs; boost::int64_t nsec = xt.nsec + total_microseconds(max_wait) * 1000; if (nsec > 1000000000) { nsec -= 1000000000; xt.sec += 1; } xt.nsec = boost::xtime::xtime_nsec_t(nsec); // apparently this call can be interrupted // prematurely if there are other signals if (!m_condition.timed_wait(lock, xt)) return 0; if (m_alerts.empty()) return 0; return m_alerts.front(); } void alert_manager::set_dispatch_function(boost::function<void(alert const&)> const& fun) { boost::mutex::scoped_lock lock(m_mutex); m_dispatch = fun; while (!m_alerts.empty()) { m_dispatch(*m_alerts.front()); delete m_alerts.front(); m_alerts.pop(); } } void alert_manager::post_alert(const alert& alert_) { boost::mutex::scoped_lock lock(m_mutex); if (m_dispatch) { TORRENT_ASSERT(m_alerts.empty()); m_dispatch(alert_); return; } if (m_alerts.size() >= m_queue_size_limit) return; m_alerts.push(alert_.clone().release()); m_condition.notify_all(); } std::auto_ptr<alert> alert_manager::get() { boost::mutex::scoped_lock lock(m_mutex); TORRENT_ASSERT(!m_alerts.empty()); alert* result = m_alerts.front(); m_alerts.pop(); return std::auto_ptr<alert>(result); } bool alert_manager::pending() const { boost::mutex::scoped_lock lock(m_mutex); return !m_alerts.empty(); } size_t alert_manager::set_alert_queue_size_limit(size_t queue_size_limit_) { boost::mutex::scoped_lock lock(m_mutex); std::swap(m_queue_size_limit, queue_size_limit_); return queue_size_limit_; } } // namespace libtorrent <commit_msg>added missing include statement<commit_after>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "libtorrent/pch.hpp" #include "libtorrent/alert.hpp" #include <boost/thread/xtime.hpp> #include <boost/function.hpp> namespace libtorrent { alert::alert() : m_timestamp(time_now()) {} alert::~alert() {} ptime alert::timestamp() const { return m_timestamp; } alert_manager::alert_manager() : m_alert_mask(alert::error_notification) , m_queue_size_limit(queue_size_limit_default) {} alert_manager::~alert_manager() { while (!m_alerts.empty()) { delete m_alerts.front(); m_alerts.pop(); } } alert const* alert_manager::wait_for_alert(time_duration max_wait) { boost::mutex::scoped_lock lock(m_mutex); if (!m_alerts.empty()) return m_alerts.front(); int secs = total_seconds(max_wait); max_wait -= seconds(secs); boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); xt.sec += secs; boost::int64_t nsec = xt.nsec + total_microseconds(max_wait) * 1000; if (nsec > 1000000000) { nsec -= 1000000000; xt.sec += 1; } xt.nsec = boost::xtime::xtime_nsec_t(nsec); // apparently this call can be interrupted // prematurely if there are other signals if (!m_condition.timed_wait(lock, xt)) return 0; if (m_alerts.empty()) return 0; return m_alerts.front(); } void alert_manager::set_dispatch_function(boost::function<void(alert const&)> const& fun) { boost::mutex::scoped_lock lock(m_mutex); m_dispatch = fun; while (!m_alerts.empty()) { m_dispatch(*m_alerts.front()); delete m_alerts.front(); m_alerts.pop(); } } void alert_manager::post_alert(const alert& alert_) { boost::mutex::scoped_lock lock(m_mutex); if (m_dispatch) { TORRENT_ASSERT(m_alerts.empty()); m_dispatch(alert_); return; } if (m_alerts.size() >= m_queue_size_limit) return; m_alerts.push(alert_.clone().release()); m_condition.notify_all(); } std::auto_ptr<alert> alert_manager::get() { boost::mutex::scoped_lock lock(m_mutex); TORRENT_ASSERT(!m_alerts.empty()); alert* result = m_alerts.front(); m_alerts.pop(); return std::auto_ptr<alert>(result); } bool alert_manager::pending() const { boost::mutex::scoped_lock lock(m_mutex); return !m_alerts.empty(); } size_t alert_manager::set_alert_queue_size_limit(size_t queue_size_limit_) { boost::mutex::scoped_lock lock(m_mutex); std::swap(m_queue_size_limit, queue_size_limit_); return queue_size_limit_; } } // namespace libtorrent <|endoftext|>
<commit_before>#include "TopicWriter.hh" #include <fcntl.h> #include <cassert> #include <cstdio> #include <unistd.h> #include <errno.h> using namespace praline; TopicWriter::TopicWriter(const std::string& topicName, Poco::Logger& logger) : dataFileM(topicName + ".data"), metaFileM(topicName + ".meta"), logM(logger) { } TopicWriter::~TopicWriter() { if (dataStreamM.is_open()) { logM.information("Closing file"); dataStreamM.close(); if (dataStreamM.fail()) { logM.information("Closing file failed!"); } } } bool TopicWriter::open() { logM.information("Opening files '%s' and '%s'", dataFileM, metaFileM); dataStreamM.open(dataFileM, std::ios_base::out | std::ios_base::app); if (dataStreamM.fail()) { logM.error("Opening '%s' failed!", dataFileM); return false; } metaStreamM.open(metaFileM, std::ios_base::out | std::ios_base::app); if (metaStreamM.fail()) { logM.error("Opening '%s' failed!", metaFileM); return false; } logM.information("Opening topic files successful", metaFileM); return true; } bool TopicWriter::write(std::istream& data) { logM.information("Writing to file '%s'", dataFileM); dataStreamM.clear(); dataStreamM << data.rdbuf(); dataStreamM.flush(); if (dataStreamM.bad()) { logM.information("Writing to file '%s' set badbit!", dataFileM); } if (dataStreamM.fail()) { logM.information("Writing to file '%s' set failbit!", dataFileM); } return dataStreamM.good(); } <commit_msg>Note to self<commit_after>#include "TopicWriter.hh" #include <fcntl.h> #include <cassert> #include <cstdio> #include <unistd.h> #include <errno.h> using namespace praline; struct MessagePointer { uint64_t sequenceNumber; uint64_t fileOffset; }; TopicWriter::TopicWriter(const std::string& topicName, Poco::Logger& logger) : dataFileM(topicName + ".data"), metaFileM(topicName + ".meta"), logM(logger) { } TopicWriter::~TopicWriter() { if (dataStreamM.is_open()) { logM.information("Closing file"); dataStreamM.close(); if (dataStreamM.fail()) { logM.information("Closing file failed!"); } } } // Writes: // - Open data file for append // - Open meta file for append // - Read meta file into memory // - All meta write goes both to memory and file // // Reads: // - Find sequence number of message in memory (binary search) // - Seek to offset in data file // - Stream message to consumer // bool TopicWriter::open() { logM.information("Opening files '%s' and '%s'", dataFileM, metaFileM); dataStreamM.open(dataFileM, std::ios_base::out | std::ios_base::binary | std::ios_base::app); if (dataStreamM.fail()) { logM.error("Opening '%s' failed!", dataFileM); return false; } metaStreamM.open(metaFileM, std::ios_base::out | std::ios_base::binary | std::ios_base::app); if (metaStreamM.fail()) { logM.error("Opening '%s' failed!", metaFileM); return false; } logM.information("Opening topic files successful", metaFileM); return true; } bool TopicWriter::write(std::istream& data) { logM.information("Writing to file '%s'", dataFileM); dataStreamM.clear(); dataStreamM << data.rdbuf(); dataStreamM.flush(); if (dataStreamM.bad()) { logM.information("Writing to file '%s' set badbit!", dataFileM); } if (dataStreamM.fail()) { logM.information("Writing to file '%s' set failbit!", dataFileM); } return dataStreamM.good(); } <|endoftext|>
<commit_before>/* * Interface for the widget registry managed by the translation * server. * * author: Max Kellermann <mk@cm4all.com> */ #include "widget_registry.hxx" #include "widget_class.hxx" #include "processor.h" #include "widget.hxx" #include "tcache.hxx" #include "translate_client.hxx" #include "translate_request.hxx" #include "translate_response.hxx" #include "transformation.hxx" #include "pool.hxx" #include <daemon/log.h> #include <glib.h> static void widget_registry_lookup(struct pool &pool, struct tcache &tcache, const char *widget_type, const TranslateHandler &handler, void *ctx, struct async_operation_ref &async_ref) { auto request = NewFromPool<TranslateRequest>(pool); request->Clear(); request->widget_type = widget_type; translate_cache(pool, tcache, *request, handler, ctx, async_ref); } struct widget_class_lookup { struct pool *pool; widget_class_callback_t callback; void *callback_ctx; }; static void widget_translate_response(TranslateResponse &response, void *ctx) { struct widget_class_lookup *lookup = (struct widget_class_lookup *)ctx; assert(response.views != nullptr); if (response.status != 0) { lookup->callback(nullptr, lookup->callback_ctx); return; } auto cls = NewFromPool<WidgetClass>(*lookup->pool); cls->local_uri = response.local_uri; cls->untrusted_host = response.untrusted; cls->untrusted_prefix = response.untrusted_prefix; cls->untrusted_site_suffix = response.untrusted_site_suffix; if (cls->untrusted_host == nullptr) /* compatibility with v0.7.16 */ cls->untrusted_host = response.host; cls->cookie_host = response.cookie_host; cls->group = response.widget_group; cls->container_groups = std::move(response.container_groups); cls->direct_addressing = response.direct_addressing; cls->stateful = response.stateful; cls->anchor_absolute = response.anchor_absolute; cls->info_headers = response.widget_info; cls->dump_headers = response.dump_headers; cls->views.CopyChainFrom(*lookup->pool, *response.views); lookup->callback(cls, lookup->callback_ctx); } static void widget_translate_error(GError *error, void *ctx) { struct widget_class_lookup *lookup = (struct widget_class_lookup *)ctx; daemon_log(2, "widget registry error: %s\n", error->message); g_error_free(error); lookup->callback(nullptr, lookup->callback_ctx); } static const TranslateHandler widget_translate_handler = { .response = widget_translate_response, .error = widget_translate_error, }; void widget_class_lookup(struct pool &pool, struct pool &widget_pool, struct tcache &tcache, const char *widget_type, widget_class_callback_t callback, void *ctx, struct async_operation_ref &async_ref) { struct widget_class_lookup *lookup = NewFromPool<struct widget_class_lookup>(pool); assert(widget_type != nullptr); lookup->pool = &widget_pool; lookup->callback = callback; lookup->callback_ctx = ctx; widget_registry_lookup(pool, tcache, widget_type, widget_translate_handler, lookup, async_ref); } <commit_msg>widget_registry: rename with CamelCase<commit_after>/* * Interface for the widget registry managed by the translation * server. * * author: Max Kellermann <mk@cm4all.com> */ #include "widget_registry.hxx" #include "widget_class.hxx" #include "processor.h" #include "widget.hxx" #include "tcache.hxx" #include "translate_client.hxx" #include "translate_request.hxx" #include "translate_response.hxx" #include "transformation.hxx" #include "pool.hxx" #include <daemon/log.h> #include <glib.h> static void widget_registry_lookup(struct pool &pool, struct tcache &tcache, const char *widget_type, const TranslateHandler &handler, void *ctx, struct async_operation_ref &async_ref) { auto request = NewFromPool<TranslateRequest>(pool); request->Clear(); request->widget_type = widget_type; translate_cache(pool, tcache, *request, handler, ctx, async_ref); } struct WidgetRegistryLookup { struct pool *pool; widget_class_callback_t callback; void *callback_ctx; }; static void widget_translate_response(TranslateResponse &response, void *ctx) { const auto lookup = (WidgetRegistryLookup *)ctx; assert(response.views != nullptr); if (response.status != 0) { lookup->callback(nullptr, lookup->callback_ctx); return; } auto cls = NewFromPool<WidgetClass>(*lookup->pool); cls->local_uri = response.local_uri; cls->untrusted_host = response.untrusted; cls->untrusted_prefix = response.untrusted_prefix; cls->untrusted_site_suffix = response.untrusted_site_suffix; if (cls->untrusted_host == nullptr) /* compatibility with v0.7.16 */ cls->untrusted_host = response.host; cls->cookie_host = response.cookie_host; cls->group = response.widget_group; cls->container_groups = std::move(response.container_groups); cls->direct_addressing = response.direct_addressing; cls->stateful = response.stateful; cls->anchor_absolute = response.anchor_absolute; cls->info_headers = response.widget_info; cls->dump_headers = response.dump_headers; cls->views.CopyChainFrom(*lookup->pool, *response.views); lookup->callback(cls, lookup->callback_ctx); } static void widget_translate_error(GError *error, void *ctx) { const auto lookup = (WidgetRegistryLookup *)ctx; daemon_log(2, "widget registry error: %s\n", error->message); g_error_free(error); lookup->callback(nullptr, lookup->callback_ctx); } static const TranslateHandler widget_translate_handler = { .response = widget_translate_response, .error = widget_translate_error, }; void widget_class_lookup(struct pool &pool, struct pool &widget_pool, struct tcache &tcache, const char *widget_type, widget_class_callback_t callback, void *ctx, struct async_operation_ref &async_ref) { auto lookup = NewFromPool<WidgetRegistryLookup>(pool); assert(widget_type != nullptr); lookup->pool = &widget_pool; lookup->callback = callback; lookup->callback_ctx = ctx; widget_registry_lookup(pool, tcache, widget_type, widget_translate_handler, lookup, async_ref); } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <locale> #include <string> #include <vector> #include <iv/stringpiece.h> #include <iv/ustringpiece.h> #include <iv/about.h> #include <iv/cmdline.h> #include <iv/lv5/lv5.h> #include <iv/lv5/teleporter/interactive.h> #include <iv/lv5/railgun/command.h> #include <iv/lv5/railgun/interactive.h> #include <iv/lv5/breaker/command.h> #include <iv/lv5/melt/melt.h> #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) #include <signal.h> #endif namespace { void InitContext(iv::lv5::Context* ctx) { iv::lv5::Error::Dummy dummy; ctx->DefineFunction<&iv::lv5::Print, 1>("print"); ctx->DefineFunction<&iv::lv5::Log, 1>("log"); // this is simply output log function ctx->DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx->DefineFunction<&iv::lv5::CollectGarbage, 0>("gc"); ctx->DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); ctx->DefineFunction<&iv::lv5::railgun::Dis, 1>("dis"); iv::lv5::melt::Console::Export(ctx, &dummy); } #if defined(IV_ENABLE_JIT) int BreakerExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::breaker::Run, 1>("run"); ctx.DefineFunction<&iv::lv5::breaker::Load, 1>("load"); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } ctx.Validate(); return EXIT_SUCCESS; } int BreakerExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::breaker::Run, 1>("run"); ctx.DefineFunction<&iv::lv5::breaker::Load, 1>("load"); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } #endif int RailgunExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::railgun::Run, 0>("run"); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } if (statistics) { ctx.vm()->DumpStatistics(); } ctx.Validate(); return EXIT_SUCCESS; } int RailgunExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::railgun::Run, 0>("run"); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } int DisAssemble(const iv::core::StringPiece& data, const std::string& filename) { iv::lv5::railgun::Context ctx; iv::lv5::Error::Standard e; std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::Code* code = iv::lv5::railgun::CompileInGlobal(&ctx, src, true, &e); if (e) { return EXIT_FAILURE; } iv::lv5::railgun::OutputDisAssembler dis(&ctx, stdout); dis.DisAssembleGlobal(*code); return EXIT_SUCCESS; } int Interpret(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::teleporter::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } ctx.DefineFunction<&iv::lv5::Print, 1>("print"); ctx.DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx.DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); iv::lv5::teleporter::JSScript* const script = iv::lv5::teleporter::JSGlobalScript::New(&ctx, global, &factory, &src); if (ctx.Run(script)) { ctx.error()->Dump(&ctx, stderr); return EXIT_FAILURE; } return EXIT_SUCCESS; } int Ast(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::railgun::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser; ser.Visit(global); const iv::core::UString str = ser.out(); iv::core::unicode::FPutsUTF16(stdout, str.begin(), str.end()); return EXIT_SUCCESS; } } // namespace anonymous int main(int argc, char **argv) { iv::lv5::FPU fpu; iv::lv5::program::Init(argc, argv); iv::lv5::Init(); iv::cmdline::Parser cmd("lv5"); cmd.Add("help", "help", 'h', "print this message"); cmd.Add("version", "version", 'v', "print the version"); cmd.AddList<std::string>( "file", "file", 'f', "script file to load"); cmd.Add("signal", "", 's', "install signal handlers"); cmd.Add<std::string>( "execute", "execute", 'e', "execute command", false); cmd.Add("ast", "ast", 0, "print ast"); cmd.Add("interp", "interp", 0, "use interpreter"); cmd.Add("railgun", "railgun", 0, "force railgun VM"); cmd.Add("dis", "dis", 'd', "print bytecode"); cmd.Add("statistics", "statistics", 0, "print statistics"); cmd.Add("copyright", "copyright", 0, "print the copyright"); cmd.set_footer("[program_file] [arguments]"); const bool cmd_parse_success = cmd.Parse(argc, argv); if (!cmd_parse_success) { std::fprintf(stderr, "%s\n%s", cmd.error().c_str(), cmd.usage().c_str()); return EXIT_FAILURE; } if (cmd.Exist("help")) { std::fputs(cmd.usage().c_str(), stdout); return EXIT_SUCCESS; } if (cmd.Exist("version")) { std::printf("lv5 %s (compiled %s %s)\n", IV_VERSION, __DATE__, __TIME__); return EXIT_SUCCESS; } if (cmd.Exist("copyright")) { std::printf("lv5 - %s\n", IV_COPYRIGHT); return EXIT_SUCCESS; } if (cmd.Exist("signal")) { #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) signal(SIGILL, _exit); signal(SIGFPE, _exit); signal(SIGBUS, _exit); signal(SIGSEGV, _exit); #endif } const std::vector<std::string>& rest = cmd.rest(); if (!rest.empty() || cmd.Exist("file") || cmd.Exist("execute")) { std::vector<char> res; std::string filename; if (cmd.Exist("file")) { const std::vector<std::string>& vec = cmd.GetList<std::string>("file"); if (!cmd.Exist("ast") && !cmd.Exist("dis") && !cmd.Exist("interp")) { if (cmd.Exist("railgun")) { return RailgunExecuteFiles(vec); } #if defined(IV_ENABLE_JIT) return BreakerExecuteFiles(vec); #else return RailgunExecuteFiles(vec); #endif } for (std::vector<std::string>::const_iterator it = vec.begin(), last = vec.end(); it != last; ++it, filename.push_back(' ')) { filename.append(*it); if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } } } else if (cmd.Exist("execute")) { const std::string& com = cmd.Get<std::string>("execute"); filename = "<command>"; res.insert(res.end(), com.begin(), com.end()); } else { filename = rest.front(); if (!iv::core::ReadFile(filename, &res)) { return EXIT_FAILURE; } } const iv::core::StringPiece src(res.data(), res.size()); if (cmd.Exist("ast")) { return Ast(src, filename); } else if (cmd.Exist("dis")) { return DisAssemble(src, filename); } else if (cmd.Exist("interp")) { return Interpret(src, filename); } else if (cmd.Exist("railgun")) { return RailgunExecute(src, filename, cmd.Exist("statistics")); } else { #if defined(IV_ENABLE_JIT) return BreakerExecute(src, filename, cmd.Exist("statistics")); #else return RailgunExecute(src, filename, cmd.Exist("statistics")); #endif } } else { // Interactive Shell Mode if (cmd.Exist("interp")) { iv::lv5::teleporter::Interactive shell; return shell.Run(); } else { iv::lv5::railgun::Interactive shell(cmd.Exist("dis")); return shell.Run(); } } return 0; } <commit_msg>Add JIT check to version text<commit_after>#include <cstdio> #include <cstdlib> #include <locale> #include <string> #include <vector> #include <iv/stringpiece.h> #include <iv/ustringpiece.h> #include <iv/about.h> #include <iv/cmdline.h> #include <iv/lv5/lv5.h> #include <iv/lv5/teleporter/interactive.h> #include <iv/lv5/railgun/command.h> #include <iv/lv5/railgun/interactive.h> #include <iv/lv5/breaker/command.h> #include <iv/lv5/melt/melt.h> #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) #include <signal.h> #endif namespace { void InitContext(iv::lv5::Context* ctx) { iv::lv5::Error::Dummy dummy; ctx->DefineFunction<&iv::lv5::Print, 1>("print"); ctx->DefineFunction<&iv::lv5::Log, 1>("log"); // this is simply output log function ctx->DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx->DefineFunction<&iv::lv5::CollectGarbage, 0>("gc"); ctx->DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); ctx->DefineFunction<&iv::lv5::railgun::Dis, 1>("dis"); iv::lv5::melt::Console::Export(ctx, &dummy); } #if defined(IV_ENABLE_JIT) int BreakerExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::breaker::Run, 1>("run"); ctx.DefineFunction<&iv::lv5::breaker::Load, 1>("load"); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } ctx.Validate(); return EXIT_SUCCESS; } int BreakerExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::breaker::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::breaker::Run, 1>("run"); ctx.DefineFunction<&iv::lv5::breaker::Load, 1>("load"); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::breaker::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } #endif int RailgunExecute(const iv::core::StringPiece& data, const std::string& filename, bool statistics) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::railgun::Run, 0>("run"); std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } if (statistics) { ctx.vm()->DumpStatistics(); } ctx.Validate(); return EXIT_SUCCESS; } int RailgunExecuteFiles(const std::vector<std::string>& filenames) { iv::lv5::Error::Standard e; iv::lv5::railgun::Context ctx; InitContext(&ctx); ctx.DefineFunction<&iv::lv5::railgun::Run, 0>("run"); std::vector<char> res; for (std::vector<std::string>::const_iterator it = filenames.begin(), last = filenames.end(); it != last; ++it) { if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource( iv::core::StringPiece(res.data(), res.size()), *it)); res.clear(); iv::lv5::railgun::ExecuteInGlobal(&ctx, src, &e); if (e) { e.Dump(&ctx, stderr); return EXIT_FAILURE; } } ctx.Validate(); return EXIT_SUCCESS; } int DisAssemble(const iv::core::StringPiece& data, const std::string& filename) { iv::lv5::railgun::Context ctx; iv::lv5::Error::Standard e; std::shared_ptr<iv::core::FileSource> src(new iv::core::FileSource(data, filename)); iv::lv5::railgun::Code* code = iv::lv5::railgun::CompileInGlobal(&ctx, src, true, &e); if (e) { return EXIT_FAILURE; } iv::lv5::railgun::OutputDisAssembler dis(&ctx, stdout); dis.DisAssembleGlobal(*code); return EXIT_SUCCESS; } int Interpret(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::teleporter::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } ctx.DefineFunction<&iv::lv5::Print, 1>("print"); ctx.DefineFunction<&iv::lv5::Quit, 1>("quit"); ctx.DefineFunction<&iv::lv5::HiResTime, 0>("HiResTime"); iv::lv5::teleporter::JSScript* const script = iv::lv5::teleporter::JSGlobalScript::New(&ctx, global, &factory, &src); if (ctx.Run(script)) { ctx.error()->Dump(&ctx, stderr); return EXIT_FAILURE; } return EXIT_SUCCESS; } int Ast(const iv::core::StringPiece& data, const std::string& filename) { iv::core::FileSource src(data, filename); iv::lv5::railgun::Context ctx; iv::lv5::AstFactory factory(&ctx); iv::core::Parser<iv::lv5::AstFactory, iv::core::FileSource> parser(&factory, src, ctx.symbol_table()); const iv::lv5::FunctionLiteral* const global = parser.ParseProgram(); if (!global) { std::fprintf(stderr, "%s\n", parser.error().c_str()); return EXIT_FAILURE; } iv::core::ast::AstSerializer<iv::lv5::AstFactory> ser; ser.Visit(global); const iv::core::UString str = ser.out(); iv::core::unicode::FPutsUTF16(stdout, str.begin(), str.end()); return EXIT_SUCCESS; } } // namespace anonymous int main(int argc, char **argv) { iv::lv5::FPU fpu; iv::lv5::program::Init(argc, argv); iv::lv5::Init(); iv::cmdline::Parser cmd("lv5"); cmd.Add("help", "help", 'h', "print this message"); cmd.Add("version", "version", 'v', "print the version"); cmd.AddList<std::string>( "file", "file", 'f', "script file to load"); cmd.Add("signal", "", 's', "install signal handlers"); cmd.Add<std::string>( "execute", "execute", 'e', "execute command", false); cmd.Add("ast", "ast", 0, "print ast"); cmd.Add("interp", "interp", 0, "use interpreter"); cmd.Add("railgun", "railgun", 0, "force railgun VM"); cmd.Add("dis", "dis", 'd', "print bytecode"); cmd.Add("statistics", "statistics", 0, "print statistics"); cmd.Add("copyright", "copyright", 0, "print the copyright"); cmd.set_footer("[program_file] [arguments]"); const bool cmd_parse_success = cmd.Parse(argc, argv); if (!cmd_parse_success) { std::fprintf(stderr, "%s\n%s", cmd.error().c_str(), cmd.usage().c_str()); return EXIT_FAILURE; } if (cmd.Exist("help")) { std::fputs(cmd.usage().c_str(), stdout); return EXIT_SUCCESS; } if (cmd.Exist("version")) { const char* jit #if defined(IV_ENABLE_JIT) = "on"; #else = "off"; #endif std::printf("lv5 %s (compiled %s %s with JIT [%s])\n", IV_VERSION, __DATE__, __TIME__, jit); return EXIT_SUCCESS; } if (cmd.Exist("copyright")) { std::printf("lv5 - %s\n", IV_COPYRIGHT); return EXIT_SUCCESS; } if (cmd.Exist("signal")) { #if defined(IV_OS_MACOSX) || defined(IV_OS_LINUX) || defined(IV_OS_BSD) signal(SIGILL, _exit); signal(SIGFPE, _exit); signal(SIGBUS, _exit); signal(SIGSEGV, _exit); #endif } const std::vector<std::string>& rest = cmd.rest(); if (!rest.empty() || cmd.Exist("file") || cmd.Exist("execute")) { std::vector<char> res; std::string filename; if (cmd.Exist("file")) { const std::vector<std::string>& vec = cmd.GetList<std::string>("file"); if (!cmd.Exist("ast") && !cmd.Exist("dis") && !cmd.Exist("interp")) { if (cmd.Exist("railgun")) { return RailgunExecuteFiles(vec); } #if defined(IV_ENABLE_JIT) return BreakerExecuteFiles(vec); #else return RailgunExecuteFiles(vec); #endif } for (std::vector<std::string>::const_iterator it = vec.begin(), last = vec.end(); it != last; ++it, filename.push_back(' ')) { filename.append(*it); if (!iv::core::ReadFile(*it, &res)) { return EXIT_FAILURE; } } } else if (cmd.Exist("execute")) { const std::string& com = cmd.Get<std::string>("execute"); filename = "<command>"; res.insert(res.end(), com.begin(), com.end()); } else { filename = rest.front(); if (!iv::core::ReadFile(filename, &res)) { return EXIT_FAILURE; } } const iv::core::StringPiece src(res.data(), res.size()); if (cmd.Exist("ast")) { return Ast(src, filename); } else if (cmd.Exist("dis")) { return DisAssemble(src, filename); } else if (cmd.Exist("interp")) { return Interpret(src, filename); } else if (cmd.Exist("railgun")) { return RailgunExecute(src, filename, cmd.Exist("statistics")); } else { #if defined(IV_ENABLE_JIT) return BreakerExecute(src, filename, cmd.Exist("statistics")); #else return RailgunExecute(src, filename, cmd.Exist("statistics")); #endif } } else { // Interactive Shell Mode if (cmd.Exist("interp")) { iv::lv5::teleporter::Interactive shell; return shell.Run(); } else { iv::lv5::railgun::Interactive shell(cmd.Exist("dis")); return shell.Run(); } } return 0; } <|endoftext|>
<commit_before>#ifndef __STAN__MATH__MATRIX__DISTANCE_HPP__ #define __STAN__MATH__MATRIX__DIST_HPP__ #include <stan/math/matrix/Eigen.hpp> #include <stan/meta/traits.hpp> #include <boost/math/tools/promotion.hpp> #include <stan/math/matrix/squared_distance.hpp> namespace stan { namespace math { /** * Returns the distance between the specified vectors. * * @param v1 First vector. * @param v2 Second vector. * @return Dot product of the vectors. * @throw std::domain_error If the vectors are not the same * size or if they are both not vector dimensioned. */ template<typename T1, int R1,int C1, typename T2, int R2, int C2> inline typename boost::math::tools::promote_args<T1,T1>::type distance(const Eigen::Matrix<T1, R1, C1>& v1, const Eigen::Matrix<T2, R2, C2>& v2) { using std::sqrt; return sqrt(squared_distance(v1,v2)); } } } #endif <commit_msg>Fixed header guard issue.<commit_after>#ifndef __STAN__MATH__MATRIX__DISTANCE_HPP__ #define __STAN__MATH__MATRIX__DISTANCE_HPP__ #include <stan/math/matrix/Eigen.hpp> #include <stan/meta/traits.hpp> #include <boost/math/tools/promotion.hpp> #include <stan/math/matrix/squared_distance.hpp> namespace stan { namespace math { /** * Returns the distance between the specified vectors. * * @param v1 First vector. * @param v2 Second vector. * @return Dot product of the vectors. * @throw std::domain_error If the vectors are not the same * size or if they are both not vector dimensioned. */ template<typename T1, int R1,int C1, typename T2, int R2, int C2> inline typename boost::math::tools::promote_args<T1,T1>::type distance(const Eigen::Matrix<T1, R1, C1>& v1, const Eigen::Matrix<T2, R2, C2>& v2) { using std::sqrt; return sqrt(squared_distance(v1,v2)); } } } #endif <|endoftext|>
<commit_before>/** \file benchmark_main.cpp * * Defines the "vg benchmark" subcommand, which runs and reports on microbenchmarks. */ #include <omp.h> #include <unistd.h> #include <getopt.h> #include <iostream> #include "subcommand.hpp" #include "../benchmark.hpp" #include "../version.hpp" #include "../vg.hpp" #include "../xg.hpp" #include "../algorithms/extract_connecting_graph.hpp" using namespace std; using namespace vg; using namespace vg::subcommand; void help_benchmark(char** argv) { cerr << "usage: " << argv[0] << " benchmark [options] >report.tsv" << endl << "options:" << endl << " -p, --progress show progress" << endl; } int main_benchmark(int argc, char** argv) { bool show_progress = false; int c; optind = 2; // force optind past command positional argument while (true) { static struct option long_options[] = { {"progress", no_argument, 0, 'p'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "ph?", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 'p': show_progress = true; break; case 'h': case '?': /* getopt_long already printed an error message. */ help_benchmark(argv); exit(1); break; default: abort (); } } if (optind != argc) { // Extra arguments found help_benchmark(argv); exit(1); } // Do all benchmarking on one thread omp_set_num_threads(1); // Turn on nested parallelism, so we can parallelize over VCFs and over alignment bands omp_set_nested(1); // Generate a test graph VG vg; for (size_t i = 1; i < 101; i++) { // It will have 100 nodes vg.create_node("ACGTACGT", i); } size_t bits = 1; for (size_t i = 1; i < 101; i++) { for (size_t j = 1; j < 101; j++) { if ((bits ^ (i + (j << 3))) % 50 == 0) { // Make some arbitrary edges vg.create_edge(i, j, false, false); } // Shifts and xors make good PRNGs right? bits = bits ^ (bits << 13) ^ j; } } // And a test XG of it xg::XG xg_index(vg.graph); vector<BenchmarkResult> results; // Do the control against itself results.push_back(run_benchmark("control", 1000, benchmark_control)); results.push_back(run_benchmark("VG::get_node", 1000, [&]() { for (size_t rep = 0; rep < 100; rep++) { for (size_t i = 1; i < 101; i++) { vg.get_node(i); } } })); results.push_back(run_benchmark("algorithms::extract_connecting_graph on xg", 1000, [&]() { pos_t pos_1 = make_pos_t(55, false, 0); pos_t pos_2 = make_pos_t(32, false, 0); int64_t max_len = 5; Graph g; auto trans = algorithms::extract_connecting_graph(xg_index, g, max_len, pos_1, pos_2, false, false, true, true, true); })); results.push_back(run_benchmark("algorithms::extract_connecting_graph on vg", 1000, [&]() { pos_t pos_1 = make_pos_t(55, false, 0); pos_t pos_2 = make_pos_t(32, false, 0); int64_t max_len = 5; Graph g; auto trans = algorithms::extract_connecting_graph(vg, g, max_len, pos_1, pos_2, false, false, true, true, true); })); cout << "# Benchmark results for vg " << VG_VERSION_STRING << endl; cout << "# runs\ttest(us)\tstddev(us)\tcontrol(us)\tstddev(us)\tscore\terr\tname" << endl; for (auto& result : results) { cout << result << endl; } return 0; } // Register subcommand static Subcommand vg_benchmark("benchmark", "run and report on performance benchmarks", main_benchmark); <commit_msg>Up distance again<commit_after>/** \file benchmark_main.cpp * * Defines the "vg benchmark" subcommand, which runs and reports on microbenchmarks. */ #include <omp.h> #include <unistd.h> #include <getopt.h> #include <iostream> #include "subcommand.hpp" #include "../benchmark.hpp" #include "../version.hpp" #include "../vg.hpp" #include "../xg.hpp" #include "../algorithms/extract_connecting_graph.hpp" using namespace std; using namespace vg; using namespace vg::subcommand; void help_benchmark(char** argv) { cerr << "usage: " << argv[0] << " benchmark [options] >report.tsv" << endl << "options:" << endl << " -p, --progress show progress" << endl; } int main_benchmark(int argc, char** argv) { bool show_progress = false; int c; optind = 2; // force optind past command positional argument while (true) { static struct option long_options[] = { {"progress", no_argument, 0, 'p'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long (argc, argv, "ph?", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 'p': show_progress = true; break; case 'h': case '?': /* getopt_long already printed an error message. */ help_benchmark(argv); exit(1); break; default: abort (); } } if (optind != argc) { // Extra arguments found help_benchmark(argv); exit(1); } // Do all benchmarking on one thread omp_set_num_threads(1); // Turn on nested parallelism, so we can parallelize over VCFs and over alignment bands omp_set_nested(1); // Generate a test graph VG vg; for (size_t i = 1; i < 101; i++) { // It will have 100 nodes vg.create_node("ACGTACGT", i); } size_t bits = 1; for (size_t i = 1; i < 101; i++) { for (size_t j = 1; j < 101; j++) { if ((bits ^ (i + (j << 3))) % 50 == 0) { // Make some arbitrary edges vg.create_edge(i, j, false, false); } // Shifts and xors make good PRNGs right? bits = bits ^ (bits << 13) ^ j; } } // And a test XG of it xg::XG xg_index(vg.graph); vector<BenchmarkResult> results; // Do the control against itself results.push_back(run_benchmark("control", 1000, benchmark_control)); results.push_back(run_benchmark("VG::get_node", 1000, [&]() { for (size_t rep = 0; rep < 100; rep++) { for (size_t i = 1; i < 101; i++) { vg.get_node(i); } } })); results.push_back(run_benchmark("algorithms::extract_connecting_graph on xg", 1000, [&]() { pos_t pos_1 = make_pos_t(55, false, 0); pos_t pos_2 = make_pos_t(32, false, 0); int64_t max_len = 500; Graph g; auto trans = algorithms::extract_connecting_graph(xg_index, g, max_len, pos_1, pos_2, false, false, true, true, true); })); results.push_back(run_benchmark("algorithms::extract_connecting_graph on vg", 1000, [&]() { pos_t pos_1 = make_pos_t(55, false, 0); pos_t pos_2 = make_pos_t(32, false, 0); int64_t max_len = 500; Graph g; auto trans = algorithms::extract_connecting_graph(vg, g, max_len, pos_1, pos_2, false, false, true, true, true); })); cout << "# Benchmark results for vg " << VG_VERSION_STRING << endl; cout << "# runs\ttest(us)\tstddev(us)\tcontrol(us)\tstddev(us)\tscore\terr\tname" << endl; for (auto& result : results) { cout << result << endl; } return 0; } // Register subcommand static Subcommand vg_benchmark("benchmark", "run and report on performance benchmarks", main_benchmark); <|endoftext|>
<commit_before>// // main.cpp // HappyDevelopersDay // // Created by Valentine on 12.09.13. // Copyright (c) 2013 silvansky. All rights reserved. // #include <iostream> #include <time.h> #include "Internet.h" #include "Developer.h" int main(int argc, const char * argv[]) { time_t today = time(NULL); struct tm *todayInfo = localtime(&today); if (todayInfo->tm_yday != 0xff) { std::cout << "Today is a usual day..." << std::endl; return 1; } std::cout << "Today is a special day!" << std::endl; std::cout << std::endl; Developer me("Valentine", "Objective-C, C++"); std::cout << "Hello, World! My name is " << me.name() << " and I\'m a " << me.position() << ", I write in " << me.programmingLanguage() << "." << std::endl; std::cout << "Today is 0xFF day, so I want to congrat all the developers! Hooray! =)" << std::endl; std::cout << std::endl; // see http://instacod.es/80286 SpecialPersonsList list; Internet::sharedInstance()->grabAllDevelopers(list); for (size_t i = 0; i < list.size(); i++) { Developer *developer = dynamic_cast<Developer *>(list[i]); if (developer) { me.sayHelloTo(developer); me.giveABeerToDeveloper(developer); } } return 0; } <commit_msg>Memory<commit_after>// // main.cpp // HappyDevelopersDay // // Created by Valentine on 12.09.13. // Copyright (c) 2013 silvansky. All rights reserved. // #include <iostream> #include <time.h> #include "Internet.h" #include "Developer.h" int main(int argc, const char * argv[]) { time_t today = time(NULL); struct tm *todayInfo = localtime(&today); if (todayInfo->tm_yday != 0xFF) { std::cout << "Today is a usual day..." << std::endl; return 1; } std::cout << "Today is a special day!" << std::endl; std::cout << std::endl; Developer me("Valentine", "Objective-C, C++"); std::cout << "Hello, World! My name is " << me.name() << " and I\'m a " << me.position() << ", I write in " << me.programmingLanguage() << "." << std::endl; std::cout << "Today is 0xFF day, so I want to congrat all the developers! Hooray! =)" << std::endl; std::cout << std::endl; // see http://instacod.es/80286 SpecialPersonsList list; Internet::sharedInstance()->grabAllDevelopers(list); for (size_t i = 0; i < list.size(); i++) { Developer *developer = dynamic_cast<Developer *>(list[i]); if (developer) { me.sayHelloTo(developer); me.giveABeerToDeveloper(developer); } delete list[i]; } return 0; } <|endoftext|>
<commit_before>2e8b48d0-2f67-11e5-921b-6c40088e03e4<commit_msg>2e925740-2f67-11e5-a226-6c40088e03e4<commit_after>2e925740-2f67-11e5-a226-6c40088e03e4<|endoftext|>
<commit_before>f1b696e8-ad5a-11e7-b4b4-ac87a332f658<commit_msg>For bobby to integrate at some point<commit_after>f24f6530-ad5a-11e7-8cc0-ac87a332f658<|endoftext|>
<commit_before>efc8b182-327f-11e5-96e8-9cf387a8033e<commit_msg>efcea5bd-327f-11e5-bb06-9cf387a8033e<commit_after>efcea5bd-327f-11e5-bb06-9cf387a8033e<|endoftext|>
<commit_before>dec80414-2e4e-11e5-bac3-28cfe91dbc4b<commit_msg>decf1178-2e4e-11e5-92ac-28cfe91dbc4b<commit_after>decf1178-2e4e-11e5-92ac-28cfe91dbc4b<|endoftext|>
<commit_before>9f23c5ca-ad5c-11e7-b868-ac87a332f658<commit_msg>TODO: Add a beter commit message<commit_after>9f9c2417-ad5c-11e7-8122-ac87a332f658<|endoftext|>
<commit_before>dfcc123a-327f-11e5-b744-9cf387a8033e<commit_msg>dfd7f50a-327f-11e5-85f1-9cf387a8033e<commit_after>dfd7f50a-327f-11e5-85f1-9cf387a8033e<|endoftext|>
<commit_before>9521a999-2e4f-11e5-99f6-28cfe91dbc4b<commit_msg>952827f0-2e4f-11e5-8cad-28cfe91dbc4b<commit_after>952827f0-2e4f-11e5-8cad-28cfe91dbc4b<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <string> #include <fstream> #include <sstream> #include <iomanip> #include <math.h> using namespace std; typedef double real; int main(int argc, char **argv){ vector<string> argList; for (int i=0; i<argc; i++){ argList.push_back(argv[i]); } if (argList.size() != 8){ cout << "Expected 7 args:" << endl << "1) filename" << endl << "2) last File number" << endl << "3) destination filename" << endl << "4) background filename" << endl << "5) sample spec file" << endl << "6) spec intesity of back" << endl << "7) integration check filename" << endl; return -1; } string baseFilename = argList.at(1); int last_file_num = stoi(argList.at(2)); string destinationFilename = argList.at(3); vector<real> background; ifstream background_file; background_file.open(argList.at(4)); string line_b; while (getline(background_file,line_b)){ if (line_b.at(0) == '#'){ continue; } stringstream streamline; streamline.str(line_b); real val1, val2; streamline >> val1; streamline >> val2; background.push_back(val2); } cout << "background: " << background.size() << " datapoints!" << endl; background_file.close(); string::size_type sz; real back_intensity = stod(argList.at(6), &sz); vector<real> spec_int; ifstream spec_int_file; spec_int_file.open(argList.at(5)); string line_mul_b; while (getline(spec_int_file,line_mul_b)){ if (line_mul_b == ""){ continue; } if (line_mul_b.at(0) == '#'){ continue; } stringstream streamline; streamline.str(line_mul_b); real val1, val2; for (int j=0; j<12; j++) streamline >> val1; streamline >> val2; spec_int.push_back(val2); } cout << "background_mul (spec) \"" << argList.at(5) << "\": " << spec_int.size() << " datapoints!" << endl; ofstream int_test_file; int_test_file.open(argList.at(7)); cout << "processing ..." << endl; int i=1; for (; i<last_file_num; i++){ stringstream in_filename; in_filename << baseFilename << setfill('0') << setw(5) << i << ".sm"; stringstream out_filename; out_filename << destinationFilename << setfill('0') << setw(5) << i << ".sm"; ifstream in_f; ofstream out_f; in_f.open(in_filename.str()); out_f.open(out_filename.str()); real sum = 0, sum1 = 0; //cout << "ration measurement: " << spec_int.at(0)/spec_int.at(i) << " ration background: " << spec_int.at(0)/back_intensity << endl; /*int oadfjwe; cin >> oadfjwe;*/ int line_number = 0; string line; while (getline(in_f,line)){ if (line.at(0) == '#'){ continue; } stringstream streamline; streamline.str(line); real val1, val2; streamline >> val1; streamline >> val2; //real val3 = back_intensity * val2 - background.at(line_number) * spec_int.at(i); real val3 = val2 * (spec_int.at(0)/spec_int.at(i)) - background.at(line_number) * (spec_int.at(0)/(back_intensity*4.d)); /*cout << "spec at 0: " << spec_int.at(0) << ", spec int at t:" << spec_int.at(i) << "back at line: " << background.at(line_number) << ", back_intensity: " << back_intensity << endl; cout << "val1: " << val1 << ", val2: " << val2 << ", val3: " << val3 << endl; int oadfjwe; cin >> oadfjwe;*/ out_f << val1 << " " << val3 << " " << val2 << endl; out_f.flush(); sum += val3; sum1 += val2; } if ((i % 50) == 0) cout << "."; cout.flush(); int_test_file << sum << " " << sum1 << endl; in_f.close(); out_f.close(); } int_test_file.close(); cout << "files: " << i << endl; return 0; } <commit_msg>added background multiplier<commit_after>#include <iostream> #include <vector> #include <string> #include <fstream> #include <sstream> #include <iomanip> #include <math.h> using namespace std; typedef double real; int main(int argc, char **argv){ vector<string> argList; for (int i=0; i<argc; i++){ argList.push_back(argv[i]); } if (argList.size() != 9){ cout << "Expected 7 args:" << endl << "1) filename" << endl << "2) last File number" << endl << "3) destination filename" << endl << "4) background filename" << endl << "5) sample spec file" << endl << "6) spec intesity of back" << endl << "7) integration check filename" << endl << "8) Background multiplication factor" << endl; return -1; } string baseFilename = argList.at(1); int last_file_num = stoi(argList.at(2)); string destinationFilename = argList.at(3); vector<real> background; ifstream background_file; background_file.open(argList.at(4)); string line_b; while (getline(background_file,line_b)){ if (line_b.at(0) == '#'){ continue; } stringstream streamline; streamline.str(line_b); real val1, val2; streamline >> val1; streamline >> val2; background.push_back(val2); } cout << "background: " << background.size() << " datapoints!" << endl; background_file.close(); string::size_type sz; real back_intensity = stod(argList.at(6), &sz); real back_mul = stod(argList.at(8), &sz); vector<real> spec_int; ifstream spec_int_file; spec_int_file.open(argList.at(5)); string line_mul_b; while (getline(spec_int_file,line_mul_b)){ if (line_mul_b == ""){ continue; } if (line_mul_b.at(0) == '#'){ continue; } stringstream streamline; streamline.str(line_mul_b); real val1, val2; for (int j=0; j<12; j++) streamline >> val1; streamline >> val2; spec_int.push_back(val2); } cout << "background_mul (spec) \"" << argList.at(5) << "\": " << spec_int.size() << " datapoints!" << endl; ofstream int_test_file; int_test_file.open(argList.at(7)); cout << "processing ..." << endl; int i=1; for (; i<last_file_num; i++){ stringstream in_filename; in_filename << baseFilename << setfill('0') << setw(5) << i << ".sm"; stringstream out_filename; out_filename << destinationFilename << setfill('0') << setw(5) << i << ".sm"; ifstream in_f; ofstream out_f; in_f.open(in_filename.str()); out_f.open(out_filename.str()); real sum = 0, sum1 = 0; //cout << "ration measurement: " << spec_int.at(0)/spec_int.at(i) << " ration background: " << spec_int.at(0)/back_intensity << endl; /*int oadfjwe; cin >> oadfjwe;*/ int line_number = 0; string line; while (getline(in_f,line)){ if (line.at(0) == '#'){ continue; } stringstream streamline; streamline.str(line); real val1, val2; streamline >> val1; streamline >> val2; //real val3 = back_intensity * val2 - background.at(line_number) * spec_int.at(i); real val3 = /*spec_int.at(0) * */( val2 / spec_int.at(i) - back_mul * background.at(line_number) / back_intensity); /*cout << "spec at 0: " << spec_int.at(0) << ", spec int at t:" << spec_int.at(i) << "back at line: " << background.at(line_number) << ", back_intensity: " << back_intensity << endl; cout << "val1: " << val1 << ", val2: " << val2 << ", val3: " << val3 << endl; int oadfjwe; cin >> oadfjwe;*/ out_f << val1 << " " << val3 << " " << val2 << endl; out_f.flush(); sum += val3; sum1 += val2; } if ((i % 50) == 0) cout << "."; cout.flush(); int_test_file << sum << " " << sum1 << endl; in_f.close(); out_f.close(); } int_test_file.close(); cout << "files: " << i << endl; return 0; } <|endoftext|>
<commit_before>f85feb2c-585a-11e5-8daf-6c40088e03e4<commit_msg>f866c174-585a-11e5-9ef8-6c40088e03e4<commit_after>f866c174-585a-11e5-9ef8-6c40088e03e4<|endoftext|>
<commit_before>#include <stdio.h> #include "serial.h" #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #include "config.h" #include "lut.h" botPacket command; Serial sPort; Leg_Config makeLeg(int theta1,int theta2,int theta3,int theta4) { Leg_Config leg; leg.theta[0] = theta1; leg.theta[1] = theta2; leg.theta[2] = theta3; leg.theta[3] = theta4; return leg; } Robot_Config makeRobot(Leg_Config leg1,Leg_Config leg2,Leg_Config leg3,Leg_Config leg4) { Robot_Config myRobot; myRobot.leg[0] = leg1; myRobot.leg[1] = leg2; myRobot.leg[2] = leg3; myRobot.leg[3] = leg4; return myRobot; } void sendCommand(Robot_Config myRobot) { command.preamble = 0xaa; command.info_byte = 0b00000000; command.myRobot = myRobot; sPort.Write(&command, sizeof(botPacket)); } void sendBrokenPacket(Robot_Config myRobot) { Robot_Config newRobot; int angle[4]; Leg_Config leg[4]; newRobot.leg[0].theta[0] =72; newRobot.leg[1].theta[0] =75; newRobot.leg[2].theta[0] =75; newRobot.leg[3].theta[0] =80; for(int i=0;i<4;i++) { for(int j=1;j<4;j++) { newRobot.leg[i].theta[j] =0; } leg[i] = makeLeg(newRobot.leg[i].theta[0],newRobot.leg[i].theta[1],newRobot.leg[i].theta[2],newRobot.leg[i].theta[3]); } newRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); for(int i=0;i<10;i++) { for(int i=0;i<4;i++) { for(int j=1;j<4;j++) { newRobot.leg[i].theta[j] += (myRobot.leg[i].theta[j]/10); } leg[i] = makeLeg(newRobot.leg[i].theta[0],newRobot.leg[i].theta[1],newRobot.leg[i].theta[2],newRobot.leg[i].theta[3]); } Robot_Config sendRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); sendCommand(sendRobot); //usleep(1500000); } for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { newRobot.leg[i].theta[j] += (myRobot.leg[i].theta[j]%10); } leg[i] = makeLeg(newRobot.leg[i].theta[0],newRobot.leg[i].theta[1],newRobot.leg[i].theta[2],newRobot.leg[i].theta[3]); } Robot_Config sendRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); sendCommand(sendRobot); } int main(int argc, char **argv) { if(!sPort.Open("/dev/ttyUSB0", 57600)) { perror("Could not Open Serial Port s0 :"); exit(0); } int angle[4]; Leg_Config leg[4]; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { scanf("%d",&angle[j]); } leg[i] = makeLeg(angle[0],angle[1],angle[2],angle[3]); } Robot_Config myRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); // sendCommand(myRobot); sendBrokenPacket(myRobot); // printf("%d",getAngle(153)); return 0; } <commit_msg>rotation gait<commit_after>#include <stdio.h> #include "serial.h" #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #include "config.h" #include "lut.h" botPacket command; Serial sPort; Leg_Config makeLeg(int theta1,int theta2,int theta3,int theta4) { Leg_Config leg; leg.theta[0] = theta1; leg.theta[1] = theta2; leg.theta[2] = theta3; leg.theta[3] = theta4; return leg; } Robot_Config makeRobot(Leg_Config leg1,Leg_Config leg2,Leg_Config leg3,Leg_Config leg4) { Robot_Config myRobot; myRobot.leg[0] = leg1; myRobot.leg[1] = leg2; myRobot.leg[2] = leg3; myRobot.leg[3] = leg4; return myRobot; } void sendCommand(Robot_Config myRobot) { command.preamble = 0xaa; command.info_byte = 0b00000000; command.myRobot = myRobot; sPort.Write(&command, sizeof(botPacket)); } void sendBrokenPacket(Robot_Config myRobot) { Robot_Config newRobot; int angle[4]; Leg_Config leg[4]; newRobot.leg[0].theta[0] =72; newRobot.leg[1].theta[0] =75; newRobot.leg[2].theta[0] =75; newRobot.leg[3].theta[0] =80; for(int i=0;i<4;i++) { for(int j=1;j<4;j++) { newRobot.leg[i].theta[j] =0; } leg[i] = makeLeg(newRobot.leg[i].theta[0],newRobot.leg[i].theta[1],newRobot.leg[i].theta[2],newRobot.leg[i].theta[3]); } newRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); for(int i=0;i<10;i++) { for(int i=0;i<4;i++) { for(int j=1;j<4;j++) { newRobot.leg[i].theta[j] += (myRobot.leg[i].theta[j]/10); } leg[i] = makeLeg(newRobot.leg[i].theta[0],newRobot.leg[i].theta[1],newRobot.leg[i].theta[2],newRobot.leg[i].theta[3]); } Robot_Config sendRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); sendCommand(sendRobot); //usleep(1500000); } for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { newRobot.leg[i].theta[j] += (myRobot.leg[i].theta[j]%10); } leg[i] = makeLeg(newRobot.leg[i].theta[0],newRobot.leg[i].theta[1],newRobot.leg[i].theta[2],newRobot.leg[i].theta[3]); } Robot_Config sendRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); sendCommand(sendRobot); } int main(int argc, char **argv) { if(!sPort.Open("/dev/ttyUSB0", 57600)) { perror("Could not Open Serial Port s0 :"); exit(0); } int angle[4]; Leg_Config leg[4]; for (int k = 0; k < 9; k++) { for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { scanf("%d",&angle[j]); } leg[i] = makeLeg(angle[0],angle[1],angle[2],angle[3]); } Robot_Config myRobot = makeRobot(leg[0],leg[1],leg[2],leg[3]); sendCommand(myRobot); //sendBrokenPacket(myRobot); usleep(700000); } // printf("%d",getAngle(153)); return 0; } <|endoftext|>
<commit_before>a6685aa6-327f-11e5-a555-9cf387a8033e<commit_msg>a66e6d11-327f-11e5-9fd6-9cf387a8033e<commit_after>a66e6d11-327f-11e5-9fd6-9cf387a8033e<|endoftext|>
<commit_before>#include "Engine.h" #include "interface.h" #include "GameMain.h" #include "Console.h" #include "direct.h" #include "HMDWrapper.h" #include "EngineConsole.h" #include "FileSystem.h" int main(int argc, char* argv[]) { #ifdef USE_HMD g_pHMD->Init(); int useHmd = g_pHMD->GetUseHMD(); if (useHmd) { //ͷ3d render_stereo = 2; //Զ崰ڷֱ ͷֱһֱ video_mode = -1; video_width = 2160; video_height = 1200; // ȫʽ 0 1ȫ video_fullscreen = 0; video_resizable = 0; video_vsync = 0; } else { //ͷ render_stereo = 0; //Զ崰ڷֱ video_mode = -1; video_fullscreen = 0; video_width = 1280; video_height = 720; video_resizable = 0; video_vsync = 0; } #else render_stereo = 0; video_mode = -1; video_fullscreen = 0; video_width = 1280; video_height = 720; video_resizable = 0; video_vsync = 0; #endif char pAppPath[260]; getcwd(pAppPath, 260); strcat(pAppPath, "\\"); CGameMain t_Game; CInterfaceBase *pInit = MakeInterface(&t_Game, &CGameMain::Init); CInterfaceBase *pUpdate = MakeInterface(&t_Game, &CGameMain::Update); CInterfaceBase *pShutdown = MakeInterface(&t_Game, &CGameMain::ShutDown); CInterfaceBase *pRender = MakeInterface(&t_Game, &CGameMain::Render); }<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h" #include "interface.h" #include "GameMain.h" #include "Console.h" #include "direct.h" #include "HMDWrapper.h" #include "EngineConsole.h" #include "FileSystem.h" int main(int argc, char* argv[]) { #ifdef USE_HMD g_pHMD->Init(); int useHmd = g_pHMD->GetUseHMD(); if (useHmd) { //ͷ3d render_stereo = 2; //Զ崰ڷֱ ͷֱһֱ video_mode = -1; video_width = 2160; video_height = 1200; // ȫʽ 0 1ȫ video_fullscreen = 0; video_resizable = 0; video_vsync = 0; } else { //ͷ render_stereo = 0; //Զ崰ڷֱ video_mode = -1; video_fullscreen = 0; video_width = 1280; video_height = 720; video_resizable = 0; video_vsync = 0; } #else render_stereo = 0; video_mode = -1; video_fullscreen = 0; video_width = 1280; video_height = 720; video_resizable = 0; video_vsync = 0; #endif char pAppPath[260]; getcwd(pAppPath, 260); strcat(pAppPath, "\\"); CGameMain t_Game; CInterfaceBase *pInit = MakeInterface(&t_Game, &CGameMain::Init); CInterfaceBase *pUpdate = MakeInterface(&t_Game, &CGameMain::Update); CInterfaceBase *pShutdown = MakeInterface(&t_Game, &CGameMain::ShutDown); CInterfaceBase *pRender = MakeInterface(&t_Game, &CGameMain::Render); char *pArg[3] = { NULL, "-engine_config", "data/TestProject.cfg" }; //ʲôõģ g_Engine.pEngine = new CEngine(NULL, pAppPath, NULL, NULL, 3, pArg, NULL, "1123581321", pInit); //CEngineijʼԼֵ }<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <list> #include "opencv.hpp" using namespace cv; using namespace std; using namespace flann; static const double PI = 3.1415926536; struct Options { int threshold; double subsample; // 0..1 -> size on load }; struct Star { double x, y; double r; Star(double x, double y, double r) { this->x = x; this->y = y; this->r = r; } Star(const Star &s) : x(s.x), y(s.y), r(s.r) { } }; struct Blob { double x, y; double S; }; Blob operator+(const Blob & l, const Blob & r) { Blob q; q.S = l.S + r.S; q.x = (l.S*l.x + r.S*r.x) / q.S; q.y = (l.S*l.y + r.S*r.y) / q.S; } Blob & operator+=(Blob & blob, const Blob & x) { double S = blob.S + x.S; blob.x = (blob.S*blob.x + x.S*x.x) / S; blob.y = (blob.S*blob.y + x.S*x.y) / S; blob.S = S; } bool operator<(const Star & l, const Star & r) { if (l.r < r.r) return true; if (l.r > r.r) return false; return (l.x < r.x); } typedef vector<Star> Stars; typedef vector<Blob> Blobs; void die(const string & msg) { cerr << "Error: " << msg << endl; exit(1); } inline double sqr(double x) { return x*x; } Point2f controlPoint(const Point2f & u, const Point2f & v) { double dx = v.x - u.x; double dy = v.y - u.y; return Point2f(u.x - dy, u.y + dx); } struct Line { Star a, b; double length; Line(const Star & a_, const Star & b_) : a(a_), b(b_) { length = sqrt(sqr(a.x-b.x) + sqr(a.y - b.y)); } Line(const Line& x) : a(x.a), b(x.b), length(x.length) { } }; bool operator<(const Line & l, const Line & r) { return (l.length < r.length); } void getLines(const Stars & stars, vector<Line> & lines) { for (int i = 0; i < stars.size(); ++i) { for (int j = i+1; j < stars.size(); ++j) { lines.push_back(Line(stars[i], stars[j])); } } } Mat getLineTransform(const Line & a, const Line & b) { Point2f xp[3], yp[3]; xp[0] = Point2f(a.a.x, a.a.y); xp[1] = Point2f(a.b.x, a.b.y); xp[2] = controlPoint(xp[0], xp[1]); yp[0] = Point2f(b.a.x, b.a.y); yp[1] = Point2f(b.b.x, b.b.y); yp[2] = controlPoint(yp[0], yp[1]); return getAffineTransform(xp, yp); } struct ScanItem { Blob blob; int l, r; ScanItem(int _l, int _r, const Blob & _b) : l(_l), r(_r), blob(_b) {} }; double evaluate(const Mat & trans, const Stars & xs, Index_<double> & yindex) { Mat q(3, xs.size(), CV_64F); for (int x = 0; x < xs.size(); ++x) { q.at<double>(0, x) = xs[x].x; q.at<double>(1, x) = xs[x].y; q.at<double>(2, x) = 1; } Mat query = trans * q; Mat indices(xs.size(), 1, CV_32S), dists(xs.size(), 1, CV_32F); yindex.knnSearch(query.t(), indices, dists, 1, SearchParams()); int cnt = 0; double sum = 0; float CLOSE_ENOUGH = 100; int ENOUGH_STARS = 2 * xs.size() / 3; for (int i = 0; i < dists.rows; ++i) { float dist = dists.at<float>(i, 0); if (dist < CLOSE_ENOUGH) { ++cnt; sum += dist; } } if (cnt < ENOUGH_STARS) { cout << "Not enough stars: " << cnt << endl; return 0; } return CLOSE_ENOUGH - sum/cnt; } bool getTransform(const Stars & xs, const Stars & ys, Mat & bestTrans) { static const double LENGTH_TOLERANCE = 5; // precompute NN search index Mat ymat(ys.size(), 2, CV_64F); for (int y = 0; y < ys.size(); ++y) { ymat.at<double>(y, 0) = ys[y].x; ymat.at<double>(y, 1) = ys[y].y; } Index_<double> yindex(ymat, AutotunedIndexParams()); // find all lines vector<Line> xl, yl; getLines(xs, xl); getLines(ys, yl); // sort the lines sort(xl.rbegin(), xl.rend()); sort(yl.begin(), yl.end()); // cout << "X lines: " << xl.size() << ", Y lines: " << yl.size() << endl; bestTrans = Mat::eye(2, 3, CV_64F); double bestScore = 0; for (int i = 0; i < xl.size(); ++i) { const Line & xline = xl[i]; double xlen = xline.length; // allow up to 10% tolerance if (xlen < LENGTH_TOLERANCE * 10) { cout << "Length tolerance threshold reached." << endl; break; } // bisect -> find estimate int lo = 0; int hi = yl.size() - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (xlen < yl[mid].length) hi = mid; else lo = mid+1; } // find upper && lower bound int estimate = lo; int estlo = estimate, esthi = estimate; while (estlo >= 0 && yl[estlo].length + LENGTH_TOLERANCE >= xlen) --estlo; while (esthi < yl.size() && yl[esthi].length - LENGTH_TOLERANCE <= xlen) ++esthi; hi = lo+1; while (lo > estlo || hi < esthi) { if (lo > estlo) { Mat trans = getLineTransform(xline, yl[lo]); double score = evaluate(trans, xs, yindex); if (score > bestScore) { bestScore = score; bestTrans = trans; } } if (hi < esthi) { Mat trans = getLineTransform(xline, yl[hi]); double score = evaluate(trans, xs, yindex); if (score > bestScore) { bestScore = score; bestTrans = trans; } } --lo; ++hi; } } cout << "Best score is: " << bestScore << endl; return (bestScore > 0); }; void findBlobs(const Mat & mat, Blobs & blobs) { /* namedWindow("foo"); imshow("foo", mat); waitKey(1000); */ //cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl; list<ScanItem> scan, newscan; for (int y = 0; y < mat.rows; ++y) { const uint8_t * row = mat.ptr<uint8_t>(y); list<ScanItem>::iterator it = scan.begin(); int l = 0; for (int x = 0; x < mat.cols; ++x) { // skip blanks while (it != scan.end() && it->r < x) { blobs.push_back(it->blob); ++it; } // find the end of the white segment while (x < mat.cols && row[x]) ++x; // if white segment found if (row[l]) { //cout << "rowscan at " << l << ".." << x << "," << y << endl; Blob cur = {(x+l-1)/2.0, y, x-l}; while (it != scan.end() && it->l < x) { cur += it->blob; ++it; } newscan.push_back(ScanItem(l,x-1,cur)); } l = ++x; } scan = newscan; newscan.clear(); } for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it) { blobs.push_back(it->blob); } } void findStars(const Mat & srcimg, Stars & stars, int thresh) { // threshold the image Mat image; threshold(srcimg, image, thresh, 255, THRESH_BINARY); // find the blobs Blobs blobs; findBlobs(image, blobs); // traverse the blobs stars.clear(); for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it) { stars.push_back(Star(it->x, it->y, sqrt(it->S / PI))); } } inline uint8_t clamp(int x) { return (x < 0) ? 0 : ((x > 255) ? 255 : x); } #define FOREACH(st) \ for (int y = 0; y < mat.rows; ++y) \ { \ uint8_t * row = mat.ptr<uint8_t>(y); \ const uint8_t * end = row + mat.cols; \ while (row < end) { \ st; \ ++row; \ } \ } void normalize(Mat & mat) { int sum = 0; FOREACH(sum += *row); int N = mat.rows * mat.cols; int avg = sum / N; int sqdiff = 0; FOREACH(sqdiff += (avg-*row) * (avg-*row)); int var = sqdiff / N; int sigma = lround(sqrt(var)); FOREACH(*row = clamp(255 * ((int) *row - (int) avg) / (16 * sigma))); } Mat merge(const vector<string> & fn, int a, int b, const Options & opt) { if (a+1 >= b) { cout << "Loading " << fn[a] << endl; Mat full = imread(fn[a], CV_LOAD_IMAGE_GRAYSCALE); Mat subsampled; resize(full, subsampled, Size(0,0), opt.subsample, opt.subsample); normalize(subsampled); return subsampled; } // merge recursively int mid = (a + b) / 2; Mat l = merge(fn, a, mid, opt); Mat r = merge(fn, mid, b, opt); // align the images Stars lstars, rstars; findStars(l, lstars, opt.threshold); findStars(r, rstars, opt.threshold); Mat trans; bool ret = getTransform(lstars, rstars, trans); if (!ret) { cout << "Could not align images!" << endl; return l; // no transform could be found -> return (arbitrarily) the left child } // remap Mat lremap; warpAffine(l, lremap, trans, r.size()); // merge return (0.5*lremap + 0.5*r); } int main(int argc, char ** argv) { char ** end = argv + argc; ++argv; // skip the name of the executable // some default options Options opt; opt.threshold = 128; opt.subsample = 0.3; // get the options while (argv < end) { // end of options if (**argv != '-') break; string opt = *argv++; // no options will follow if (opt == "--") break; die("unknown option " + opt); } // get the list of images vector<string> imgNames; while (argv < end) imgNames.push_back(*argv++); // perform some sanity checks if (imgNames.size() < 2) die("no point in aligning less than two images"); // stack the images Mat stack = merge(imgNames, 0, imgNames.size(), opt); namedWindow("preview"); imshow("preview", stack); waitKey(0); return 0; } <commit_msg>Better parametrization.<commit_after>#include <iostream> #include <string> #include <vector> #include <list> #include "opencv.hpp" using namespace cv; using namespace std; using namespace flann; static const double PI = 3.1415926536; struct Options { int threshold; double subsample; // 0..1 -> size on load }; struct Star { double x, y; double r; Star(double x, double y, double r) { this->x = x; this->y = y; this->r = r; } Star(const Star &s) : x(s.x), y(s.y), r(s.r) { } }; struct Blob { double x, y; double S; }; Blob operator+(const Blob & l, const Blob & r) { Blob q; q.S = l.S + r.S; q.x = (l.S*l.x + r.S*r.x) / q.S; q.y = (l.S*l.y + r.S*r.y) / q.S; } Blob & operator+=(Blob & blob, const Blob & x) { double S = blob.S + x.S; blob.x = (blob.S*blob.x + x.S*x.x) / S; blob.y = (blob.S*blob.y + x.S*x.y) / S; blob.S = S; } bool operator<(const Star & l, const Star & r) { if (l.r < r.r) return true; if (l.r > r.r) return false; return (l.x < r.x); } typedef vector<Star> Stars; typedef vector<Blob> Blobs; void die(const string & msg) { cerr << "Error: " << msg << endl; exit(1); } inline double sqr(double x) { return x*x; } Point2f controlPoint(const Point2f & u, const Point2f & v) { double dx = v.x - u.x; double dy = v.y - u.y; return Point2f(u.x - dy, u.y + dx); } struct Line { Star a, b; double length; Line(const Star & a_, const Star & b_) : a(a_), b(b_) { length = sqrt(sqr(a.x-b.x) + sqr(a.y - b.y)); } Line(const Line& x) : a(x.a), b(x.b), length(x.length) { } }; bool operator<(const Line & l, const Line & r) { return (l.length < r.length); } void getLines(const Stars & stars, vector<Line> & lines) { for (int i = 0; i < stars.size(); ++i) { for (int j = i+1; j < stars.size(); ++j) { lines.push_back(Line(stars[i], stars[j])); } } } Mat getLineTransform(const Line & a, const Line & b) { Point2f xp[3], yp[3]; xp[0] = Point2f(a.a.x, a.a.y); xp[1] = Point2f(a.b.x, a.b.y); xp[2] = controlPoint(xp[0], xp[1]); yp[0] = Point2f(b.a.x, b.a.y); yp[1] = Point2f(b.b.x, b.b.y); yp[2] = controlPoint(yp[0], yp[1]); return getAffineTransform(xp, yp); } struct ScanItem { Blob blob; int l, r; ScanItem(int _l, int _r, const Blob & _b) : l(_l), r(_r), blob(_b) {} }; double evaluate(const Mat & trans, const Stars & xs, Index_<double> & yindex) { Mat q(3, xs.size(), CV_64F); for (int x = 0; x < xs.size(); ++x) { q.at<double>(0, x) = xs[x].x; q.at<double>(1, x) = xs[x].y; q.at<double>(2, x) = 1; } Mat query = trans * q; Mat indices(xs.size(), 1, CV_32S), dists(xs.size(), 1, CV_32F); yindex.knnSearch(query.t(), indices, dists, 1, SearchParams()); int cnt = 0; double sum = 0; float CLOSE_ENOUGH = 100; int ENOUGH_STARS = xs.size() / 2; for (int i = 0; i < dists.rows; ++i) { float dist = dists.at<float>(i, 0); if (dist < CLOSE_ENOUGH) { ++cnt; sum += dist; } } if (cnt < ENOUGH_STARS) { // cout << "Not enough stars: " << cnt << endl; return 0; } return CLOSE_ENOUGH - sum/cnt; } bool getTransform(const Stars & xs, const Stars & ys, Mat & bestTrans) { static const double LENGTH_TOLERANCE = 0.05; static const double MIN_LENGTH = 100; // precompute NN search index Mat ymat(ys.size(), 2, CV_64F); for (int y = 0; y < ys.size(); ++y) { ymat.at<double>(y, 0) = ys[y].x; ymat.at<double>(y, 1) = ys[y].y; } Index_<double> yindex(ymat, AutotunedIndexParams()); // find all lines vector<Line> xl, yl; getLines(xs, xl); getLines(ys, yl); // sort the lines sort(xl.rbegin(), xl.rend()); sort(yl.begin(), yl.end()); // cout << "X lines: " << xl.size() << ", Y lines: " << yl.size() << endl; bestTrans = Mat::eye(2, 3, CV_64F); double bestScore = 0; int bestOfs = 0; for (int i = 0; i < xl.size(); ++i) { const Line & xline = xl[i]; double xlen = xline.length; if (xlen < MIN_LENGTH) break; // bisect -> find estimate int lo = 0; int hi = yl.size() - 1; while (lo < hi) { int mid = (lo + hi) / 2; if (xlen < yl[mid].length) hi = mid; else lo = mid+1; } // find upper && lower bound int estimate = lo; int estlo = estimate, esthi = estimate; double tolerance = xlen * LENGTH_TOLERANCE; while (estlo >= 0 && yl[estlo].length + tolerance >= xlen) --estlo; while (esthi < yl.size() && yl[esthi].length - tolerance <= xlen) ++esthi; hi = lo+1; // cout << " within (" << estlo-estimate << "," << esthi-estimate << ")" << endl; while (lo > estlo || hi < esthi) { if (lo > estlo) { Mat trans = getLineTransform(xline, yl[lo]); double score = evaluate(trans, xs, yindex); if (score > bestScore) { bestScore = score; bestTrans = trans; bestOfs = lo - estimate; } } if (hi < esthi) { Mat trans = getLineTransform(xline, yl[hi]); double score = evaluate(trans, xs, yindex); if (score > bestScore) { bestScore = score; bestTrans = trans; bestOfs = hi - estimate; } } --lo; ++hi; } } cout << "Best score is " << 100-bestScore << " at offset " << bestOfs << endl; return (bestScore > 0); }; void findBlobs(const Mat & mat, Blobs & blobs) { /* namedWindow("foo"); imshow("foo", mat); waitKey(1000); */ //cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl; list<ScanItem> scan, newscan; for (int y = 0; y < mat.rows; ++y) { const uint8_t * row = mat.ptr<uint8_t>(y); list<ScanItem>::iterator it = scan.begin(); int l = 0; for (int x = 0; x < mat.cols; ++x) { // skip blanks while (it != scan.end() && it->r < x) { blobs.push_back(it->blob); ++it; } // find the end of the white segment while (x < mat.cols && row[x]) ++x; // if white segment found if (row[l]) { //cout << "rowscan at " << l << ".." << x << "," << y << endl; Blob cur = {(x+l-1)/2.0, y, x-l}; while (it != scan.end() && it->l < x) { cur += it->blob; ++it; } newscan.push_back(ScanItem(l,x-1,cur)); } l = ++x; } scan = newscan; newscan.clear(); } for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it) { blobs.push_back(it->blob); } } void findStars(const Mat & srcimg, Stars & stars, int thresh) { // threshold the image Mat image; threshold(srcimg, image, thresh, 255, THRESH_BINARY); // find the blobs Blobs blobs; findBlobs(image, blobs); // traverse the blobs stars.clear(); for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it) { stars.push_back(Star(it->x, it->y, sqrt(it->S / PI))); } } inline uint8_t clamp(int x) { return (x < 0) ? 0 : ((x > 255) ? 255 : x); } #define FOREACH(st) \ for (int y = 0; y < mat.rows; ++y) \ { \ uint8_t * row = mat.ptr<uint8_t>(y); \ const uint8_t * end = row + mat.cols; \ while (row < end) { \ st; \ ++row; \ } \ } void normalize(Mat & mat) { int sum = 0; FOREACH(sum += *row); int N = mat.rows * mat.cols; int avg = sum / N; int sqdiff = 0; FOREACH(sqdiff += (avg-*row) * (avg-*row)); int var = sqdiff / N; int sigma = lround(sqrt(var)); FOREACH(*row = clamp(255 * ((int) *row - (int) avg) / (16 * sigma))); } Mat merge(const vector<string> & fn, int a, int b, const Options & opt) { if (a+1 >= b) { cout << "Loading " << fn[a] << endl; Mat full = imread(fn[a], CV_LOAD_IMAGE_GRAYSCALE); Mat subsampled; resize(full, subsampled, Size(0,0), opt.subsample, opt.subsample); normalize(subsampled); return subsampled; } // merge recursively int mid = (a + b) / 2; Mat l = merge(fn, a, mid, opt); Mat r = merge(fn, mid, b, opt); // align the images Stars lstars, rstars; findStars(l, lstars, opt.threshold); findStars(r, rstars, opt.threshold); Mat trans; bool ret = getTransform(lstars, rstars, trans); if (!ret) { cout << "Could not align images!" << endl; return l; // no transform could be found -> return (arbitrarily) the left child } // remap Mat lremap; warpAffine(l, lremap, trans, r.size()); // merge return (0.5*lremap + 0.5*r); } int main(int argc, char ** argv) { char ** end = argv + argc; ++argv; // skip the name of the executable // some default options Options opt; opt.threshold = 128; opt.subsample = 0.3; // get the options while (argv < end) { // end of options if (**argv != '-') break; string opt = *argv++; // no options will follow if (opt == "--") break; die("unknown option " + opt); } // get the list of images vector<string> imgNames; while (argv < end) imgNames.push_back(*argv++); // perform some sanity checks if (imgNames.size() < 2) die("no point in aligning less than two images"); // stack the images Mat stack = merge(imgNames, 0, imgNames.size(), opt); namedWindow("preview"); imshow("preview", stack); waitKey(0); return 0; } <|endoftext|>
<commit_before>4d50afb3-2e4f-11e5-9c1f-28cfe91dbc4b<commit_msg>4d57110c-2e4f-11e5-8574-28cfe91dbc4b<commit_after>4d57110c-2e4f-11e5-8574-28cfe91dbc4b<|endoftext|>
<commit_before>9101ae28-2d14-11e5-af21-0401358ea401<commit_msg>9101ae29-2d14-11e5-af21-0401358ea401<commit_after>9101ae29-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>65f850f4-2fa5-11e5-bf3c-00012e3d3f12<commit_msg>65fa4cc6-2fa5-11e5-9526-00012e3d3f12<commit_after>65fa4cc6-2fa5-11e5-9526-00012e3d3f12<|endoftext|>
<commit_before>759e1e70-2d53-11e5-baeb-247703a38240<commit_msg>759e9c74-2d53-11e5-baeb-247703a38240<commit_after>759e9c74-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>792a212e-2d53-11e5-baeb-247703a38240<commit_msg>792aaba8-2d53-11e5-baeb-247703a38240<commit_after>792aaba8-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>923345ca-4b02-11e5-831e-28cfe9171a43<commit_msg>more fixes<commit_after>92413c85-4b02-11e5-b484-28cfe9171a43<|endoftext|>
<commit_before>#include "clang/AST/ASTConsumer.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "clang/Lex/Preprocessor.h" #include <iostream> #include <sstream> using namespace clang; using namespace clang::tooling; std::string escapeString(std::string const& input) { std::ostringstream ss; for (auto c : input) { switch (c) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: ss << c; break; } } return ss.str(); } class DumpVisitor : public RecursiveASTVisitor<DumpVisitor> { public: explicit DumpVisitor(ASTContext* context) : context(context) {} void TraverseNewScope(Stmt* stmt) { if (!isa<CompoundStmt>(stmt)) { depth++; WriteDepth(); } TraverseStmt(stmt); if (!isa<CompoundStmt>(stmt)) { std::cout << "\n"; depth--; } } bool TraverseStmt(Stmt* stmt) { if (!stmt) return RecursiveASTVisitor::TraverseStmt(stmt); if (auto compoundStmt = dyn_cast<CompoundStmt>(stmt)) { depth++; for (auto stmt : compoundStmt->body()) { if (!stmt) continue; WriteDepth(); TraverseStmt(stmt); std::cout << "\n"; } depth--; return true; } if (auto callExpr = dyn_cast<CallExpr>(stmt)) { TraverseStmt(callExpr->getCallee()); bool first = true; std::cout << "("; for (auto param : callExpr->arguments()) { if (!first) std::cout << ", "; TraverseStmt(param); first = false; } std::cout << ")"; return true; } if (auto ifStmt = dyn_cast<IfStmt>(stmt)) { std::cout << "if "; TraverseStmt(ifStmt->getCond()); std::cout << " then\n"; TraverseNewScope(ifStmt->getThen()); WriteDepth(); std::cout << "end"; return true; } if (auto arraySubscriptExpr = dyn_cast<ArraySubscriptExpr>(stmt)) { TraverseStmt(arraySubscriptExpr->getBase()); std::cout << "["; TraverseStmt(arraySubscriptExpr->getIdx()); // Add 1 to compensate for 1-based indexing std::cout << "+1]"; return true; } if (auto binaryOperator = dyn_cast<BinaryOperator>(stmt)) { TraverseStmt(binaryOperator->getLHS()); std::cout << " " << binaryOperator->getOpcodeStr().str() << " "; TraverseStmt(binaryOperator->getRHS()); return true; } if (auto parenExpr = dyn_cast<ParenExpr>(stmt)) { std::cout << "("; TraverseStmt(parenExpr->getSubExpr()); std::cout << ")"; return true; } return RecursiveASTVisitor::TraverseStmt(stmt); } bool TraverseDecl(Decl* decl) { if (auto functionDecl = dyn_cast<FunctionDecl>(decl)) { if (functionDecl->isMain()) foundMain = true; WriteDepth(); std::cout << "function " << functionDecl->getNameAsString(); std::cout << "("; bool first = true; for (auto param : functionDecl->params()) { if (!first) std::cout << ", "; std::cout << param->getNameAsString(); first = false; } std::cout << ")"; std::cout << "\n"; if (functionDecl->hasBody()) TraverseStmt(functionDecl->getBody()); WriteDepth(); std::cout << "end\n"; return true; } return RecursiveASTVisitor::TraverseDecl(decl); } bool VisitStmt(Stmt* stmt) { if (auto stringLiteral = dyn_cast<StringLiteral>(stmt)) { std::cout << '"' << escapeString(stringLiteral->getString().str()) << '"'; return true; } if (auto integerLiteral = dyn_cast<IntegerLiteral>(stmt)) { std::cout << integerLiteral->getValue().toString(10, true); return true; } if (auto declRefExpr = dyn_cast<DeclRefExpr>(stmt)) { std::cout << declRefExpr->getDecl()->getNameAsString(); return true; } if (auto returnStmt = dyn_cast<ReturnStmt>(stmt)) { std::cout << "return"; if (returnStmt->getRetValue()) std::cout << " "; return true; } return true; } bool VisitDecl(Decl* decl) { if (auto varDecl = dyn_cast<VarDecl>(decl)) { auto name = varDecl->getNameAsString(); if (name.empty()) return true; std::cout << "local " << name; if (varDecl->hasInit()) std::cout << " = "; } return true; } void WriteDepth() { for (uint32_t i = 0; i < depth * 4; ++i) std::cout << ' '; } bool HasFoundMain() { return foundMain; } private: ASTContext* context; uint32_t depth = 0; bool foundMain = false; }; class DumpConsumer : public ASTConsumer { public: explicit DumpConsumer(CompilerInstance& compiler) : visitor(&compiler.getASTContext()), sourceManager(compiler.getSourceManager()) { } virtual void HandleTranslationUnit(ASTContext& context) override { auto decls = context.getTranslationUnitDecl()->decls(); for (auto decl : decls) { auto const& fileId = sourceManager.getFileID(decl->getLocation()); if (fileId != sourceManager.getMainFileID()) continue; visitor.TraverseDecl(decl); } // Pass args to main(), and call it if (visitor.HasFoundMain()) { std::cout << "return (function() " << "table.insert(arg, 1, arg[0]); " << "return main(#arg, arg) end)()\n"; } } private: DumpVisitor visitor; SourceManager& sourceManager; }; class DumpAction : public ASTFrontendAction { public: virtual bool BeginSourceFileAction(CompilerInstance& compiler, StringRef) override { class PrintIncludes : public PPCallbacks { virtual void InclusionDirective(SourceLocation, Token const&, StringRef fileName, bool isAngled, CharSourceRange, FileEntry const*, StringRef, StringRef, Module const*) override { auto newFileName = fileName.str(); newFileName = newFileName.substr(0, newFileName.find_last_of('.')); newFileName += ".lua"; if (isAngled) newFileName = "shim/lua/" + newFileName; std::cout << "dofile \"" << newFileName << "\"\n"; } }; std::unique_ptr<PrintIncludes> callback(new PrintIncludes); auto& preprocessor = compiler.getPreprocessor(); preprocessor.addPPCallbacks(std::move(callback)); return true; } virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance& compiler, llvm::StringRef inFile) override { return std::unique_ptr<ASTConsumer>(new DumpConsumer(compiler)); } }; int main(int argc, char const** argv) { llvm::cl::OptionCategory category("irradiant"); // Ugly hack to get around there being no easy way of adding arguments std::vector<char const*> arguments(argv, argv + argc); if (strcmp(arguments.back(), "--") == 0) arguments.pop_back(); arguments.push_back("-extra-arg=-fno-builtin"); arguments.push_back("-extra-arg=-nostdlib"); arguments.push_back("-extra-arg=-nostdinc"); arguments.push_back("-extra-arg=-Ishim/c"); arguments.push_back("--"); int size = arguments.size(); CommonOptionsParser parser(size, arguments.data(), category); ClangTool tool(parser.getCompilations(), parser.getSourcePathList()); return tool.run(newFrontendActionFactory<DumpAction>().get()); } <commit_msg>Fixed bug where function definitions would be written out for declarations<commit_after>#include "clang/AST/ASTConsumer.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Tooling/Tooling.h" #include "clang/Lex/Preprocessor.h" #include <iostream> #include <sstream> using namespace clang; using namespace clang::tooling; std::string escapeString(std::string const& input) { std::ostringstream ss; for (auto c : input) { switch (c) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: ss << c; break; } } return ss.str(); } class DumpVisitor : public RecursiveASTVisitor<DumpVisitor> { public: explicit DumpVisitor(ASTContext* context) : context(context) {} void TraverseNewScope(Stmt* stmt) { if (!isa<CompoundStmt>(stmt)) { depth++; WriteDepth(); } TraverseStmt(stmt); if (!isa<CompoundStmt>(stmt)) { std::cout << "\n"; depth--; } } bool TraverseStmt(Stmt* stmt) { if (!stmt) return RecursiveASTVisitor::TraverseStmt(stmt); if (auto compoundStmt = dyn_cast<CompoundStmt>(stmt)) { depth++; for (auto stmt : compoundStmt->body()) { if (!stmt) continue; WriteDepth(); TraverseStmt(stmt); std::cout << "\n"; } depth--; return true; } if (auto callExpr = dyn_cast<CallExpr>(stmt)) { TraverseStmt(callExpr->getCallee()); bool first = true; std::cout << "("; for (auto param : callExpr->arguments()) { if (!first) std::cout << ", "; TraverseStmt(param); first = false; } std::cout << ")"; return true; } if (auto ifStmt = dyn_cast<IfStmt>(stmt)) { std::cout << "if "; TraverseStmt(ifStmt->getCond()); std::cout << " then\n"; TraverseNewScope(ifStmt->getThen()); WriteDepth(); std::cout << "end"; return true; } if (auto arraySubscriptExpr = dyn_cast<ArraySubscriptExpr>(stmt)) { TraverseStmt(arraySubscriptExpr->getBase()); std::cout << "["; TraverseStmt(arraySubscriptExpr->getIdx()); // Add 1 to compensate for 1-based indexing std::cout << "+1]"; return true; } if (auto binaryOperator = dyn_cast<BinaryOperator>(stmt)) { TraverseStmt(binaryOperator->getLHS()); std::cout << " " << binaryOperator->getOpcodeStr().str() << " "; TraverseStmt(binaryOperator->getRHS()); return true; } if (auto parenExpr = dyn_cast<ParenExpr>(stmt)) { std::cout << "("; TraverseStmt(parenExpr->getSubExpr()); std::cout << ")"; return true; } return RecursiveASTVisitor::TraverseStmt(stmt); } bool TraverseDecl(Decl* decl) { if (auto functionDecl = dyn_cast<FunctionDecl>(decl)) { // Skip over function declarations if (!functionDecl->doesThisDeclarationHaveABody()) return true; if (functionDecl->isMain()) foundMain = true; WriteDepth(); std::cout << "function " << functionDecl->getNameAsString(); std::cout << "("; bool first = true; for (auto param : functionDecl->params()) { if (!first) std::cout << ", "; std::cout << param->getNameAsString(); first = false; } std::cout << ")"; std::cout << "\n"; if (functionDecl->hasBody()) TraverseStmt(functionDecl->getBody()); WriteDepth(); std::cout << "end\n"; return true; } return RecursiveASTVisitor::TraverseDecl(decl); } bool VisitStmt(Stmt* stmt) { if (auto stringLiteral = dyn_cast<StringLiteral>(stmt)) { std::cout << '"' << escapeString(stringLiteral->getString().str()) << '"'; return true; } if (auto integerLiteral = dyn_cast<IntegerLiteral>(stmt)) { std::cout << integerLiteral->getValue().toString(10, true); return true; } if (auto declRefExpr = dyn_cast<DeclRefExpr>(stmt)) { std::cout << declRefExpr->getDecl()->getNameAsString(); return true; } if (auto returnStmt = dyn_cast<ReturnStmt>(stmt)) { std::cout << "return"; if (returnStmt->getRetValue()) std::cout << " "; return true; } return true; } bool VisitDecl(Decl* decl) { if (auto varDecl = dyn_cast<VarDecl>(decl)) { auto name = varDecl->getNameAsString(); if (name.empty()) return true; std::cout << "local " << name; if (varDecl->hasInit()) std::cout << " = "; } return true; } void WriteDepth() { for (uint32_t i = 0; i < depth * 4; ++i) std::cout << ' '; } bool HasFoundMain() { return foundMain; } private: ASTContext* context; uint32_t depth = 0; bool foundMain = false; }; class DumpConsumer : public ASTConsumer { public: explicit DumpConsumer(CompilerInstance& compiler) : visitor(&compiler.getASTContext()), sourceManager(compiler.getSourceManager()) { } virtual void HandleTranslationUnit(ASTContext& context) override { auto decls = context.getTranslationUnitDecl()->decls(); for (auto decl : decls) { auto const& fileId = sourceManager.getFileID(decl->getLocation()); if (fileId != sourceManager.getMainFileID()) continue; visitor.TraverseDecl(decl); } // Pass args to main(), and call it if (visitor.HasFoundMain()) { std::cout << "return (function() " << "table.insert(arg, 1, arg[0]); " << "return main(#arg, arg) end)()\n"; } } private: DumpVisitor visitor; SourceManager& sourceManager; }; class DumpAction : public ASTFrontendAction { public: virtual bool BeginSourceFileAction(CompilerInstance& compiler, StringRef) override { class PrintIncludes : public PPCallbacks { virtual void InclusionDirective(SourceLocation, Token const&, StringRef fileName, bool isAngled, CharSourceRange, FileEntry const*, StringRef, StringRef, Module const*) override { auto newFileName = fileName.str(); newFileName = newFileName.substr(0, newFileName.find_last_of('.')); newFileName += ".lua"; if (isAngled) newFileName = "shim/lua/" + newFileName; std::cout << "dofile \"" << newFileName << "\"\n"; } }; std::unique_ptr<PrintIncludes> callback(new PrintIncludes); auto& preprocessor = compiler.getPreprocessor(); preprocessor.addPPCallbacks(std::move(callback)); return true; } virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance& compiler, llvm::StringRef inFile) override { return std::unique_ptr<ASTConsumer>(new DumpConsumer(compiler)); } }; int main(int argc, char const** argv) { llvm::cl::OptionCategory category("irradiant"); // Ugly hack to get around there being no easy way of adding arguments std::vector<char const*> arguments(argv, argv + argc); if (strcmp(arguments.back(), "--") == 0) arguments.pop_back(); arguments.push_back("-extra-arg=-fno-builtin"); arguments.push_back("-extra-arg=-nostdlib"); arguments.push_back("-extra-arg=-nostdinc"); arguments.push_back("-extra-arg=-Ishim/c"); arguments.push_back("--"); int size = arguments.size(); CommonOptionsParser parser(size, arguments.data(), category); ClangTool tool(parser.getCompilations(), parser.getSourcePathList()); return tool.run(newFrontendActionFactory<DumpAction>().get()); } <|endoftext|>
<commit_before>86936f6a-2d15-11e5-af21-0401358ea401<commit_msg>86936f6b-2d15-11e5-af21-0401358ea401<commit_after>86936f6b-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>f1793d7e-585a-11e5-a2a7-6c40088e03e4<commit_msg>f18021c8-585a-11e5-ae03-6c40088e03e4<commit_after>f18021c8-585a-11e5-ae03-6c40088e03e4<|endoftext|>
<commit_before>3b65d882-2e3a-11e5-9da7-c03896053bdd<commit_msg>3b72fa46-2e3a-11e5-887b-c03896053bdd<commit_after>3b72fa46-2e3a-11e5-887b-c03896053bdd<|endoftext|>
<commit_before>408a5ba6-2d3d-11e5-8a33-c82a142b6f9b<commit_msg>40ff5b5e-2d3d-11e5-ba59-c82a142b6f9b<commit_after>40ff5b5e-2d3d-11e5-ba59-c82a142b6f9b<|endoftext|>
<commit_before>65d43f6e-2e3a-11e5-a5c3-c03896053bdd<commit_msg>65e3d2a8-2e3a-11e5-ad86-c03896053bdd<commit_after>65e3d2a8-2e3a-11e5-ad86-c03896053bdd<|endoftext|>
<commit_before>2f9af4d2-2f67-11e5-ac19-6c40088e03e4<commit_msg>2fa3a7e4-2f67-11e5-bb03-6c40088e03e4<commit_after>2fa3a7e4-2f67-11e5-bb03-6c40088e03e4<|endoftext|>
<commit_before>cbcbac78-2d3c-11e5-b61d-c82a142b6f9b<commit_msg>cc3059e8-2d3c-11e5-ab2d-c82a142b6f9b<commit_after>cc3059e8-2d3c-11e5-ab2d-c82a142b6f9b<|endoftext|>
<commit_before>cf8b1562-35ca-11e5-858c-6c40088e03e4<commit_msg>cf953fcc-35ca-11e5-83fe-6c40088e03e4<commit_after>cf953fcc-35ca-11e5-83fe-6c40088e03e4<|endoftext|>
<commit_before>8e44baca-2e4f-11e5-9f99-28cfe91dbc4b<commit_msg>8e4c6ed4-2e4f-11e5-b2ed-28cfe91dbc4b<commit_after>8e4c6ed4-2e4f-11e5-b2ed-28cfe91dbc4b<|endoftext|>
<commit_before>78db18c2-2d53-11e5-baeb-247703a38240<commit_msg>78db98d8-2d53-11e5-baeb-247703a38240<commit_after>78db98d8-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>2be846b8-5216-11e5-b1e0-6c40088e03e4<commit_msg>2befb128-5216-11e5-abf3-6c40088e03e4<commit_after>2befb128-5216-11e5-abf3-6c40088e03e4<|endoftext|>
<commit_before>a1558eab-2e4f-11e5-99ae-28cfe91dbc4b<commit_msg>a15be680-2e4f-11e5-ace6-28cfe91dbc4b<commit_after>a15be680-2e4f-11e5-ace6-28cfe91dbc4b<|endoftext|>
<commit_before>71fe4568-2e4f-11e5-b9b5-28cfe91dbc4b<commit_msg>7204dcf3-2e4f-11e5-a99f-28cfe91dbc4b<commit_after>7204dcf3-2e4f-11e5-a99f-28cfe91dbc4b<|endoftext|>
<commit_before>0455e0b4-585b-11e5-991c-6c40088e03e4<commit_msg>0460282e-585b-11e5-b65b-6c40088e03e4<commit_after>0460282e-585b-11e5-b65b-6c40088e03e4<|endoftext|>
<commit_before>e82d8a4c-2e4e-11e5-a71b-28cfe91dbc4b<commit_msg>e835b1de-2e4e-11e5-8e43-28cfe91dbc4b<commit_after>e835b1de-2e4e-11e5-8e43-28cfe91dbc4b<|endoftext|>
<commit_before>c072023e-35ca-11e5-a72c-6c40088e03e4<commit_msg>c0787b52-35ca-11e5-9a73-6c40088e03e4<commit_after>c0787b52-35ca-11e5-9a73-6c40088e03e4<|endoftext|>
<commit_before>e6f08a57-2747-11e6-b2ce-e0f84713e7b8<commit_msg>OKAY this time it should work<commit_after>e6fecd28-2747-11e6-a1d7-e0f84713e7b8<|endoftext|>
<commit_before>//c and posix #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> //c++ #include <string> #include <fstream> #include <iostream> #include <thread> #include <vector> #include <queue> #include <mutex> #include <condition_variable> #include <future> class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool(); private: // need to keep track of threads so we can join them std::vector< std::thread > workers; // the task queue std::queue< std::function<void()> > tasks; // synchronization std::mutex queue_mutex; std::condition_variable condition; bool stop; }; // the constructor just launches some amount of workers inline ThreadPool::ThreadPool(size_t threads) : stop(false) { for(size_t i = 0;i<threads;++i) workers.emplace_back( [this] { for(;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this]{ return this->stop || !this->tasks.empty(); }); if(this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } } ); } // add new work item to the pool template<class F, class... Args> auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared< std::packaged_task<return_type()> >( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); // don't allow enqueueing after stopping the pool if(stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task](){ (*task)(); }); } condition.notify_one(); return res; } // the destructor joins all threads inline ThreadPool::~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for(std::thread &worker: workers) worker.join(); } template <typename Socket> void send_file(std::string const& filename, Socket const& socket) { std::ifstream ifs{ filename }; for(std::string str; ifs >> str; ) { auto msg = str + "\r\n"; send(socket, msg.c_str(), msg.size(), 0); } } // Define the port number to identify this process #define MYPORT 3490 int main() { struct sockaddr_in my_addr; const std::string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; // Construct address information my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); my_addr.sin_addr.s_addr = INADDR_ANY; memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero) ); // Create a socket and bind it the port MYPORT auto soc = socket(PF_INET,SOCK_STREAM, 0); bind(soc, (struct sockaddr *)&my_addr, sizeof(my_addr)); printf("%d", my_addr.sin_port); // Allow up to 10 incoming connections const auto limit = 10; ThreadPool pool{ limit }; listen(soc,limit); std::cout << "listenning\n"; while(1) { auto request_handler = [&] (int socket){ char data[512]; char filename[256]; auto n = recv(socket, data, 512, 0); // recieve the request using fd data[n] = 0; // NUL terminate it sscanf(data, "GET /%s ", filename); // get the name of the file send(socket, header.c_str(), header.size(), 0); std::this_thread::sleep_for(std::chrono::seconds(10)); send_file(filename, socket); close(socket); // close the socket }; pool.enqueue(request_handler, accept(soc, NULL, NULL)); } } <commit_msg>add namespace<commit_after>//c and posix #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> //c++ #include <string> #include <fstream> #include <iostream> #include <thread> #include <vector> #include <queue> #include <mutex> #include <condition_variable> #include <future> namespace ccur { class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool(); private: // need to keep track of threads so we can join them std::vector<std::thread> workers; // the task queue std::queue<std::function<void()> > tasks; // synchronization std::mutex queue_mutex; std::condition_variable condition; bool stop; }; // the constructor just launches some amount of workers inline ThreadPool::ThreadPool(size_t threads) : stop(false) { for (size_t i = 0; i < threads; ++i) workers.emplace_back( [this] { for (; ;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->queue_mutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } } ); } // add new work item to the pool template<class F, class... Args> auto ThreadPool::enqueue(F &&f, Args &&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()> >( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<return_type> res = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); // don't allow enqueueing after stopping the pool if (stop) throw std::runtime_error("enqueue on stopped ThreadPool"); tasks.emplace([task]() { (*task)(); }); } condition.notify_one(); return res; } // the destructor joins all threads inline ThreadPool::~ThreadPool() { { std::unique_lock<std::mutex> lock(queue_mutex); stop = true; } condition.notify_all(); for (std::thread &worker: workers) worker.join(); } template<typename Socket> void send_file(std::string const &filename, Socket const &socket) { std::ifstream ifs{filename}; for (std::string str; ifs >> str;) { auto msg = str + "\r\n"; send(socket, msg.c_str(), msg.size(), 0); } } } // Define the port number to identify this process #define MYPORT 3490 int main() { struct sockaddr_in my_addr; const std::string header = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; // Construct address information my_addr.sin_family = AF_INET; my_addr.sin_port = htons(MYPORT); my_addr.sin_addr.s_addr = INADDR_ANY; memset(my_addr.sin_zero, '\0', sizeof(my_addr.sin_zero) ); // Create a socket and bind it the port MYPORT auto soc = socket(PF_INET,SOCK_STREAM, 0); bind(soc, (struct sockaddr *)&my_addr, sizeof(my_addr)); printf("%d", my_addr.sin_port); // Allow up to 10 incoming connections const auto limit = 10; ccur::ThreadPool pool{ limit }; listen(soc,limit); std::cout << "listenning\n"; while(1) { auto request_handler = [&] (int socket){ char data[512]; char filename[256]; auto size = recv(socket, data, 512, 0); // recieve the request using fd data[size] = 0; // NUL terminate it sscanf(data, "GET /%s ", filename); // get the name of the file send(socket, header.c_str(), header.size(), 0); std::this_thread::sleep_for(std::chrono::seconds(10)); ccur::send_file(filename, socket); close(socket); // close the socket }; pool.enqueue(request_handler, accept(soc, NULL, NULL)); } } <|endoftext|>
<commit_before>5794e3a4-2e3a-11e5-8977-c03896053bdd<commit_msg>57a141f8-2e3a-11e5-bd50-c03896053bdd<commit_after>57a141f8-2e3a-11e5-bd50-c03896053bdd<|endoftext|>
<commit_before>975b0a5a-35ca-11e5-88bb-6c40088e03e4<commit_msg>9766089a-35ca-11e5-bf49-6c40088e03e4<commit_after>9766089a-35ca-11e5-bf49-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <sched.h> #include <stdlib.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <sys/utsname.h> #include <string> int run(void* arg) { const std::string name = "funny-name"; struct utsname uts; sethostname((const char *) name.c_str(), name.size()); std::cout << "This is child" << std::endl; uname(&uts); std::cout << "This is a child's nodename: " << uts.nodename << std::endl; return 0; } int main() { struct utsname uts; char *stack = (char*) malloc(1024*1024); std::cout << "This is parent" << std::endl; pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, NULL); if (pid == -1) { std::cout << "Creating new namespace failed. Error number: " << errno; } sleep(1); uname(&uts); std::cout << "This is a parent's nodename: " << uts.nodename << std::endl; waitpid(pid, NULL, 0); } <commit_msg>Exec command in namespace<commit_after>#include <iostream> #include <sched.h> #include <stdlib.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <sys/utsname.h> #include <string> int run(void* arg) { char **argv = (char**) arg; const std::string name = "funny-name"; struct utsname uts; sethostname((const char *) name.c_str(), name.size()); std::cout << "This is child" << std::endl; uname(&uts); std::cout << "This is a child's nodename: " << uts.nodename << std::endl; pid_t pid = fork(); if (pid == 0) { std::cout << "About to spin a new task" << std::endl; std::cout << argv[1] << std::endl; execvp(argv[1], &argv[1]); } else if (pid > 0) { // parent process waitpid(pid, NULL, 0); } else { std::cout << "Forking failed" << std::endl; return 1; } return 0; } int main(int argc, char *argv[]) { struct utsname uts; char *stack = (char*) malloc(1024*1024); std::cout << "This is parent" << std::endl; pid_t pid = clone(run, (stack + 1024*1024), CLONE_NEWUTS | SIGCHLD, argv); if (pid == -1) { std::cout << "Creating new namespace failed. Error number: " << errno; } sleep(1); uname(&uts); std::cout << "This is a parent's nodename: " << uts.nodename << std::endl; waitpid(pid, NULL, 0); } <|endoftext|>
<commit_before>5db81792-5216-11e5-b280-6c40088e03e4<commit_msg>5dbe98ae-5216-11e5-86a4-6c40088e03e4<commit_after>5dbe98ae-5216-11e5-86a4-6c40088e03e4<|endoftext|>
<commit_before>a7092f02-35ca-11e5-8b64-6c40088e03e4<commit_msg>a70fbe6c-35ca-11e5-b6e0-6c40088e03e4<commit_after>a70fbe6c-35ca-11e5-b6e0-6c40088e03e4<|endoftext|>
<commit_before>7b0b5d90-5216-11e5-9152-6c40088e03e4<commit_msg>7b11d2ba-5216-11e5-89fa-6c40088e03e4<commit_after>7b11d2ba-5216-11e5-89fa-6c40088e03e4<|endoftext|>
<commit_before>feaad5f5-2e4e-11e5-bb15-28cfe91dbc4b<commit_msg>feb17abd-2e4e-11e5-8364-28cfe91dbc4b<commit_after>feb17abd-2e4e-11e5-8364-28cfe91dbc4b<|endoftext|>
<commit_before>ab000061-2747-11e6-9bcc-e0f84713e7b8<commit_msg>fixed bug<commit_after>abc035ba-2747-11e6-bf79-e0f84713e7b8<|endoftext|>
<commit_before>608d8f59-2e4f-11e5-9df6-28cfe91dbc4b<commit_msg>60949891-2e4f-11e5-a0d4-28cfe91dbc4b<commit_after>60949891-2e4f-11e5-a0d4-28cfe91dbc4b<|endoftext|>
<commit_before>42df6ac6-2e3a-11e5-b443-c03896053bdd<commit_msg>42ecdab0-2e3a-11e5-8da1-c03896053bdd<commit_after>42ecdab0-2e3a-11e5-8da1-c03896053bdd<|endoftext|>
<commit_before>81cf0e33-2d15-11e5-af21-0401358ea401<commit_msg>81cf0e34-2d15-11e5-af21-0401358ea401<commit_after>81cf0e34-2d15-11e5-af21-0401358ea401<|endoftext|>