text
stringlengths
54
60.6k
<commit_before><commit_msg>Add "learn more" link to privacy settings.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/history/in_memory_url_index_types.h" #include <algorithm> #include "base/i18n/break_iterator.h" #include "base/i18n/case_conversion.h" #include "base/string_util.h" namespace history { // Matches within URL and Title Strings ---------------------------------------- TermMatches MatchTermInString(const string16& term, const string16& string, int term_num) { const size_t kMaxCompareLength = 2048; const string16& short_string = (string.length() > kMaxCompareLength) ? string.substr(0, kMaxCompareLength) : string; TermMatches matches; for (size_t location = short_string.find(term); location != string16::npos; location = short_string.find(term, location + 1)) matches.push_back(TermMatch(term_num, location, term.length())); return matches; } // Comparison function for sorting TermMatches by their offsets. bool MatchOffsetLess(const TermMatch& m1, const TermMatch& m2) { return m1.offset < m2.offset; } TermMatches SortAndDeoverlapMatches(const TermMatches& matches) { if (matches.empty()) return matches; TermMatches sorted_matches = matches; std::sort(sorted_matches.begin(), sorted_matches.end(), MatchOffsetLess); TermMatches clean_matches; TermMatch last_match; for (TermMatches::const_iterator iter = sorted_matches.begin(); iter != sorted_matches.end(); ++iter) { if (iter->offset >= last_match.offset + last_match.length) { last_match = *iter; clean_matches.push_back(last_match); } } return clean_matches; } std::vector<size_t> OffsetsFromTermMatches(const TermMatches& matches) { std::vector<size_t> offsets; for (TermMatches::const_iterator i = matches.begin(); i != matches.end(); ++i) offsets.push_back(i->offset); return offsets; } TermMatches ReplaceOffsetsInTermMatches(const TermMatches& matches, const std::vector<size_t>& offsets) { DCHECK_EQ(matches.size(), offsets.size()); TermMatches new_matches; std::vector<size_t>::const_iterator offset_iter = offsets.begin(); for (TermMatches::const_iterator term_iter = matches.begin(); term_iter != matches.end(); ++term_iter, ++offset_iter) { if (*offset_iter != string16::npos) { TermMatch new_match(*term_iter); new_match.offset = *offset_iter; new_matches.push_back(new_match); } } return new_matches; } // ScoredHistoryMatch ---------------------------------------------------------- ScoredHistoryMatch::ScoredHistoryMatch() : raw_score(0), can_inline(false) {} ScoredHistoryMatch::ScoredHistoryMatch(const URLRow& url_info) : HistoryMatch(url_info, 0, false, false), raw_score(0), can_inline(false) {} ScoredHistoryMatch::~ScoredHistoryMatch() {} // Comparison function for sorting ScoredMatches by their scores. bool ScoredHistoryMatch::MatchScoreGreater(const ScoredHistoryMatch& m1, const ScoredHistoryMatch& m2) { return m1.raw_score >= m2.raw_score; } // InMemoryURLIndex's Private Data --------------------------------------------- URLIndexPrivateData::URLIndexPrivateData() {} URLIndexPrivateData::~URLIndexPrivateData() {} void URLIndexPrivateData::Clear() { word_list_.clear(); available_words_.clear(); word_map_.clear(); char_word_map_.clear(); word_id_history_map_.clear(); history_id_word_map_.clear(); history_info_map_.clear(); } void URLIndexPrivateData::AddToHistoryIDWordMap(HistoryID history_id, WordID word_id) { HistoryIDWordMap::iterator iter = history_id_word_map_.find(history_id); if (iter != history_id_word_map_.end()) { WordIDSet& word_id_set(iter->second); word_id_set.insert(word_id); } else { WordIDSet word_id_set; word_id_set.insert(word_id); history_id_word_map_[history_id] = word_id_set; } } WordIDSet URLIndexPrivateData::WordIDSetForTermChars( const Char16Set& term_chars) { WordIDSet word_id_set; for (Char16Set::const_iterator c_iter = term_chars.begin(); c_iter != term_chars.end(); ++c_iter) { CharWordIDMap::iterator char_iter = char_word_map_.find(*c_iter); if (char_iter == char_word_map_.end()) { // A character was not found so there are no matching results: bail. word_id_set.clear(); break; } WordIDSet& char_word_id_set(char_iter->second); // It is possible for there to no longer be any words associated with // a particular character. Give up in that case. if (char_word_id_set.empty()) { word_id_set.clear(); break; } if (c_iter == term_chars.begin()) { // First character results becomes base set of results. word_id_set = char_word_id_set; } else { // Subsequent character results get intersected in. WordIDSet new_word_id_set; std::set_intersection(word_id_set.begin(), word_id_set.end(), char_word_id_set.begin(), char_word_id_set.end(), std::inserter(new_word_id_set, new_word_id_set.begin())); word_id_set.swap(new_word_id_set); } } return word_id_set; } // Utility Functions ----------------------------------------------------------- String16Set String16SetFromString16(const string16& uni_string) { const size_t kMaxWordLength = 64; String16Vector words = String16VectorFromString16(uni_string, false); String16Set word_set; for (String16Vector::const_iterator iter = words.begin(); iter != words.end(); ++iter) word_set.insert(base::i18n::ToLower(*iter).substr(0, kMaxWordLength)); return word_set; } String16Vector String16VectorFromString16(const string16& uni_string, bool break_on_space) { base::i18n::BreakIterator iter(uni_string, break_on_space ? base::i18n::BreakIterator::BREAK_SPACE : base::i18n::BreakIterator::BREAK_WORD); String16Vector words; if (!iter.Init()) return words; while (iter.Advance()) { if (break_on_space || iter.IsWord()) { string16 word = iter.GetString(); if (break_on_space) TrimWhitespace(word, TRIM_ALL, &word); if (!word.empty()) words.push_back(word); } } return words; } Char16Set Char16SetFromString16(const string16& term) { Char16Set characters; for (string16::const_iterator iter = term.begin(); iter != term.end(); ++iter) characters.insert(*iter); return characters; } } // namespace history <commit_msg>Fix MSVC 2010 compile following http://crrev.com/105678<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/history/in_memory_url_index_types.h" #include <algorithm> #include <iterator> #include "base/i18n/break_iterator.h" #include "base/i18n/case_conversion.h" #include "base/string_util.h" namespace history { // Matches within URL and Title Strings ---------------------------------------- TermMatches MatchTermInString(const string16& term, const string16& string, int term_num) { const size_t kMaxCompareLength = 2048; const string16& short_string = (string.length() > kMaxCompareLength) ? string.substr(0, kMaxCompareLength) : string; TermMatches matches; for (size_t location = short_string.find(term); location != string16::npos; location = short_string.find(term, location + 1)) matches.push_back(TermMatch(term_num, location, term.length())); return matches; } // Comparison function for sorting TermMatches by their offsets. bool MatchOffsetLess(const TermMatch& m1, const TermMatch& m2) { return m1.offset < m2.offset; } TermMatches SortAndDeoverlapMatches(const TermMatches& matches) { if (matches.empty()) return matches; TermMatches sorted_matches = matches; std::sort(sorted_matches.begin(), sorted_matches.end(), MatchOffsetLess); TermMatches clean_matches; TermMatch last_match; for (TermMatches::const_iterator iter = sorted_matches.begin(); iter != sorted_matches.end(); ++iter) { if (iter->offset >= last_match.offset + last_match.length) { last_match = *iter; clean_matches.push_back(last_match); } } return clean_matches; } std::vector<size_t> OffsetsFromTermMatches(const TermMatches& matches) { std::vector<size_t> offsets; for (TermMatches::const_iterator i = matches.begin(); i != matches.end(); ++i) offsets.push_back(i->offset); return offsets; } TermMatches ReplaceOffsetsInTermMatches(const TermMatches& matches, const std::vector<size_t>& offsets) { DCHECK_EQ(matches.size(), offsets.size()); TermMatches new_matches; std::vector<size_t>::const_iterator offset_iter = offsets.begin(); for (TermMatches::const_iterator term_iter = matches.begin(); term_iter != matches.end(); ++term_iter, ++offset_iter) { if (*offset_iter != string16::npos) { TermMatch new_match(*term_iter); new_match.offset = *offset_iter; new_matches.push_back(new_match); } } return new_matches; } // ScoredHistoryMatch ---------------------------------------------------------- ScoredHistoryMatch::ScoredHistoryMatch() : raw_score(0), can_inline(false) {} ScoredHistoryMatch::ScoredHistoryMatch(const URLRow& url_info) : HistoryMatch(url_info, 0, false, false), raw_score(0), can_inline(false) {} ScoredHistoryMatch::~ScoredHistoryMatch() {} // Comparison function for sorting ScoredMatches by their scores. bool ScoredHistoryMatch::MatchScoreGreater(const ScoredHistoryMatch& m1, const ScoredHistoryMatch& m2) { return m1.raw_score >= m2.raw_score; } // InMemoryURLIndex's Private Data --------------------------------------------- URLIndexPrivateData::URLIndexPrivateData() {} URLIndexPrivateData::~URLIndexPrivateData() {} void URLIndexPrivateData::Clear() { word_list_.clear(); available_words_.clear(); word_map_.clear(); char_word_map_.clear(); word_id_history_map_.clear(); history_id_word_map_.clear(); history_info_map_.clear(); } void URLIndexPrivateData::AddToHistoryIDWordMap(HistoryID history_id, WordID word_id) { HistoryIDWordMap::iterator iter = history_id_word_map_.find(history_id); if (iter != history_id_word_map_.end()) { WordIDSet& word_id_set(iter->second); word_id_set.insert(word_id); } else { WordIDSet word_id_set; word_id_set.insert(word_id); history_id_word_map_[history_id] = word_id_set; } } WordIDSet URLIndexPrivateData::WordIDSetForTermChars( const Char16Set& term_chars) { WordIDSet word_id_set; for (Char16Set::const_iterator c_iter = term_chars.begin(); c_iter != term_chars.end(); ++c_iter) { CharWordIDMap::iterator char_iter = char_word_map_.find(*c_iter); if (char_iter == char_word_map_.end()) { // A character was not found so there are no matching results: bail. word_id_set.clear(); break; } WordIDSet& char_word_id_set(char_iter->second); // It is possible for there to no longer be any words associated with // a particular character. Give up in that case. if (char_word_id_set.empty()) { word_id_set.clear(); break; } if (c_iter == term_chars.begin()) { // First character results becomes base set of results. word_id_set = char_word_id_set; } else { // Subsequent character results get intersected in. WordIDSet new_word_id_set; std::set_intersection(word_id_set.begin(), word_id_set.end(), char_word_id_set.begin(), char_word_id_set.end(), std::inserter(new_word_id_set, new_word_id_set.begin())); word_id_set.swap(new_word_id_set); } } return word_id_set; } // Utility Functions ----------------------------------------------------------- String16Set String16SetFromString16(const string16& uni_string) { const size_t kMaxWordLength = 64; String16Vector words = String16VectorFromString16(uni_string, false); String16Set word_set; for (String16Vector::const_iterator iter = words.begin(); iter != words.end(); ++iter) word_set.insert(base::i18n::ToLower(*iter).substr(0, kMaxWordLength)); return word_set; } String16Vector String16VectorFromString16(const string16& uni_string, bool break_on_space) { base::i18n::BreakIterator iter(uni_string, break_on_space ? base::i18n::BreakIterator::BREAK_SPACE : base::i18n::BreakIterator::BREAK_WORD); String16Vector words; if (!iter.Init()) return words; while (iter.Advance()) { if (break_on_space || iter.IsWord()) { string16 word = iter.GetString(); if (break_on_space) TrimWhitespace(word, TRIM_ALL, &word); if (!word.empty()) words.push_back(word); } } return words; } Char16Set Char16SetFromString16(const string16& term) { Char16Set characters; for (string16::const_iterator iter = term.begin(); iter != term.end(); ++iter) characters.insert(*iter); return characters; } } // namespace history <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/spellchecker/spellcheck_host_impl.h" #include <set> #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_split.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/spellchecker/spellcheck_host_metrics.h" #include "chrome/browser/spellchecker/spellcheck_profile_provider.h" #include "chrome/browser/spellchecker/spellchecker_platform_engine.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "chrome/common/spellcheck_common.h" #include "chrome/common/spellcheck_messages.h" #include "content/browser/renderer_host/render_process_host.h" #include "content/common/notification_service.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request_context_getter.h" #include "third_party/hunspell/google/bdict.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_MACOSX) #include "base/metrics/histogram.h" #endif namespace { FilePath GetFirstChoiceFilePath(const std::string& language) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath dict_dir; PathService::Get(chrome::DIR_APP_DICTIONARIES, &dict_dir); return SpellCheckCommon::GetVersionedFileName(language, dict_dir); } #if defined(OS_MACOSX) // Collect metrics on how often Hunspell is used on OS X vs the native // spellchecker. void RecordSpellCheckStats(bool native_spellchecker_used, const std::string& language) { static std::set<std::string> languages_seen; // Only count a language code once for each session.. if (languages_seen.find(language) != languages_seen.end()) { return; } languages_seen.insert(language); enum { SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED = 0, SPELLCHECK_HUNSPELL_USED = 1 }; bool engine_used = native_spellchecker_used ? SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED : SPELLCHECK_HUNSPELL_USED; UMA_HISTOGRAM_COUNTS("SpellCheck.OSXEngineUsed", engine_used); } #endif #if defined(OS_WIN) FilePath GetFallbackFilePath(const FilePath& first_choice) { FilePath dict_dir; PathService::Get(chrome::DIR_USER_DATA, &dict_dir); return dict_dir.Append(first_choice.BaseName()); } #endif } // namespace // Constructed on UI thread. SpellCheckHostImpl::SpellCheckHostImpl( SpellCheckProfileProvider* profile, const std::string& language, net::URLRequestContextGetter* request_context_getter, SpellCheckHostMetrics* metrics) : profile_(profile), language_(language), file_(base::kInvalidPlatformFileValue), tried_to_download_(false), use_platform_spellchecker_(false), request_context_getter_(request_context_getter), metrics_(metrics) { DCHECK(profile_); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FilePath personal_file_directory; PathService::Get(chrome::DIR_USER_DATA, &personal_file_directory); custom_dictionary_file_ = personal_file_directory.Append(chrome::kCustomDictionaryFileName); registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED, NotificationService::AllSources()); } SpellCheckHostImpl::~SpellCheckHostImpl() { if (file_ != base::kInvalidPlatformFileValue) base::ClosePlatformFile(file_); } void SpellCheckHostImpl::Initialize() { if (SpellCheckerPlatform::SpellCheckerAvailable() && SpellCheckerPlatform::PlatformSupportsLanguage(language_)) { #if defined(OS_MACOSX) RecordSpellCheckStats(true, language_); #endif use_platform_spellchecker_ = true; SpellCheckerPlatform::SetLanguage(language_); MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InformProfileOfInitialization)); return; } #if defined(OS_MACOSX) RecordSpellCheckStats(false, language_); #endif BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InitializeDictionaryLocation)); } void SpellCheckHostImpl::UnsetProfile() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); profile_ = NULL; request_context_getter_ = NULL; fetcher_.reset(); registrar_.RemoveAll(); } void SpellCheckHostImpl::InitForRenderer(RenderProcessHost* process) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); Profile* profile = Profile::FromBrowserContext(process->browser_context()); PrefService* prefs = profile->GetPrefs(); IPC::PlatformFileForTransit file; if (GetDictionaryFile() != base::kInvalidPlatformFileValue) { #if defined(OS_POSIX) file = base::FileDescriptor(GetDictionaryFile(), false); #elif defined(OS_WIN) ::DuplicateHandle(::GetCurrentProcess(), GetDictionaryFile(), process->GetHandle(), &file, 0, false, DUPLICATE_SAME_ACCESS); #endif } process->Send(new SpellCheckMsg_Init( file, profile_ ? profile_->GetCustomWords() : CustomWordList(), GetLanguage(), prefs->GetBoolean(prefs::kEnableAutoSpellCorrect))); } void SpellCheckHostImpl::AddWord(const std::string& word) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (profile_) profile_->CustomWordAddedLocally(word); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::WriteWordToCustomDictionary, word)); for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { i.GetCurrentValue()->Send(new SpellCheckMsg_WordAdded(word)); } } void SpellCheckHostImpl::InitializeDictionaryLocation() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Initialize the BDICT path. This initialization should be in the FILE thread // because it checks if there is a "Dictionaries" directory and create it. if (bdict_file_path_.empty()) bdict_file_path_ = GetFirstChoiceFilePath(language_); #if defined(OS_WIN) // Check if the dictionary exists in the fallback location. If so, use it // rather than downloading anew. FilePath fallback = GetFallbackFilePath(bdict_file_path_); if (!file_util::PathExists(bdict_file_path_) && file_util::PathExists(fallback)) { bdict_file_path_ = fallback; } #endif InitializeInternal(); } void SpellCheckHostImpl::InitializeInternal() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!profile_) return; if (!VerifyBDict(bdict_file_path_)) { DCHECK_EQ(file_, base::kInvalidPlatformFileValue); file_util::Delete(bdict_file_path_, false); // Notify browser tests that this dictionary is corrupted. We also skip // downloading the dictionary when we run this function on browser tests. if (SignalStatusEvent(BDICT_CORRUPTED)) tried_to_download_ = true; } else { file_ = base::CreatePlatformFile( bdict_file_path_, base::PLATFORM_FILE_READ | base::PLATFORM_FILE_OPEN, NULL, NULL); } // File didn't exist. Download it. if (file_ == base::kInvalidPlatformFileValue && !tried_to_download_ && request_context_getter_) { // We download from the ui thread because we need to know that // |request_context_getter_| is still valid before initiating the download. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::DownloadDictionary)); return; } request_context_getter_ = NULL; scoped_ptr<CustomWordList> custom_words(new CustomWordList()); if (file_ != base::kInvalidPlatformFileValue) { // Load custom dictionary. std::string contents; file_util::ReadFileToString(custom_dictionary_file_, &contents); CustomWordList list_of_words; base::SplitString(contents, '\n', &list_of_words); for (size_t i = 0; i < list_of_words.size(); ++i) custom_words->push_back(list_of_words[i]); } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &SpellCheckHostImpl::InformProfileOfInitializationWithCustomWords, custom_words.release())); } void SpellCheckHostImpl::InitializeOnFileThread() { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::FILE)); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::Initialize)); } void SpellCheckHostImpl::InformProfileOfInitialization() { InformProfileOfInitializationWithCustomWords(NULL); } void SpellCheckHostImpl::InformProfileOfInitializationWithCustomWords( CustomWordList* custom_words) { // Non-null |custom_words| should be given only if the profile is available // for simplifying the life-cycle management of the word list. DCHECK(profile_ || !custom_words); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (profile_) profile_->SpellCheckHostInitialized(custom_words); for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { RenderProcessHost* process = i.GetCurrentValue(); if (process) InitForRenderer(process); } } void SpellCheckHostImpl::DownloadDictionary() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!request_context_getter_) { InitializeOnFileThread(); return; } // Determine URL of file to download. static const char kDownloadServerUrl[] = "http://cache.pack.google.com/edgedl/chrome/dict/"; std::string bdict_file = bdict_file_path_.BaseName().MaybeAsASCII(); if (bdict_file.empty()) { NOTREACHED(); return; } GURL url = GURL(std::string(kDownloadServerUrl) + StringToLowerASCII(bdict_file)); fetcher_.reset(new URLFetcher(url, URLFetcher::GET, this)); fetcher_->set_request_context(request_context_getter_); tried_to_download_ = true; fetcher_->Start(); request_context_getter_ = NULL; } void SpellCheckHostImpl::WriteWordToCustomDictionary(const std::string& word) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Stored in UTF-8. std::string word_to_add(word + "\n"); FILE* f = file_util::OpenFile(custom_dictionary_file_, "a+"); if (f) fputs(word_to_add.c_str(), f); file_util::CloseFile(f); } void SpellCheckHostImpl::OnURLFetchComplete(const URLFetcher* source, const GURL& url, const net::URLRequestStatus& status, int response_code, const net::ResponseCookies& cookies, const std::string& data) { DCHECK(source); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); fetcher_.reset(); if ((response_code / 100) != 2) { // Initialize will not try to download the file a second time. LOG(ERROR) << "Failure to download dictionary."; InitializeOnFileThread(); return; } // Basic sanity check on the dictionary. // There's the small chance that we might see a 200 status code for a body // that represents some form of failure. if (data.size() < 4 || data[0] != 'B' || data[1] != 'D' || data[2] != 'i' || data[3] != 'c') { LOG(ERROR) << "Failure to download dictionary."; InitializeOnFileThread(); return; } data_ = data; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::SaveDictionaryData)); } void SpellCheckHostImpl::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == content::NOTIFICATION_RENDERER_PROCESS_CREATED); RenderProcessHost* process = Source<RenderProcessHost>(source).ptr(); InitForRenderer(process); } void SpellCheckHostImpl::SaveDictionaryData() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // To prevent corrupted dictionary data from causing a renderer crash, scan // the dictionary data and verify it is sane before save it to a file. bool verified = hunspell::BDict::Verify(data_.data(), data_.size()); if (metrics_) metrics_->RecordDictionaryCorruptionStats(!verified); if (!verified) { LOG(ERROR) << "Failure to verify the downloaded dictionary."; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InformProfileOfInitialization)); return; } size_t bytes_written = file_util::WriteFile(bdict_file_path_, data_.data(), data_.length()); if (bytes_written != data_.length()) { bool success = false; #if defined(OS_WIN) bdict_file_path_ = GetFallbackFilePath(bdict_file_path_); bytes_written = file_util::WriteFile(GetFallbackFilePath(bdict_file_path_), data_.data(), data_.length()); if (bytes_written == data_.length()) success = true; #endif data_.clear(); if (!success) { LOG(ERROR) << "Failure to save dictionary."; file_util::Delete(bdict_file_path_, false); // To avoid trying to load a partially saved dictionary, shortcut the // Initialize() call. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InformProfileOfInitialization)); return; } } data_.clear(); Initialize(); } bool SpellCheckHostImpl::VerifyBDict(const FilePath& path) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Read the dictionary file and scan its data. We need to close this file // after scanning its data so we can delete it and download a new dictionary // from our dictionary-download server if it is corrupted. file_util::MemoryMappedFile map; if (!map.Initialize(path)) return false; return hunspell::BDict::Verify( reinterpret_cast<const char*>(map.data()), map.length()); } SpellCheckHostMetrics* SpellCheckHostImpl::GetMetrics() const { return metrics_; } bool SpellCheckHostImpl::IsReady() const { return GetDictionaryFile() != base::kInvalidPlatformFileValue || IsUsingPlatformChecker(); } const base::PlatformFile& SpellCheckHostImpl::GetDictionaryFile() const { return file_; } const std::string& SpellCheckHostImpl::GetLanguage() const { return language_; } bool SpellCheckHostImpl::IsUsingPlatformChecker() const { return use_platform_spellchecker_; } <commit_msg>Fix sending garbage descriptor if there's no spellcheck dictionary file.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/spellchecker/spellcheck_host_impl.h" #include <set> #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_split.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/spellchecker/spellcheck_host_metrics.h" #include "chrome/browser/spellchecker/spellcheck_profile_provider.h" #include "chrome/browser/spellchecker/spellchecker_platform_engine.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/pref_names.h" #include "chrome/common/spellcheck_common.h" #include "chrome/common/spellcheck_messages.h" #include "content/browser/renderer_host/render_process_host.h" #include "content/common/notification_service.h" #include "googleurl/src/gurl.h" #include "net/url_request/url_request_context_getter.h" #include "third_party/hunspell/google/bdict.h" #include "ui/base/l10n/l10n_util.h" #if defined(OS_MACOSX) #include "base/metrics/histogram.h" #endif namespace { FilePath GetFirstChoiceFilePath(const std::string& language) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); FilePath dict_dir; PathService::Get(chrome::DIR_APP_DICTIONARIES, &dict_dir); return SpellCheckCommon::GetVersionedFileName(language, dict_dir); } #if defined(OS_MACOSX) // Collect metrics on how often Hunspell is used on OS X vs the native // spellchecker. void RecordSpellCheckStats(bool native_spellchecker_used, const std::string& language) { static std::set<std::string> languages_seen; // Only count a language code once for each session.. if (languages_seen.find(language) != languages_seen.end()) { return; } languages_seen.insert(language); enum { SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED = 0, SPELLCHECK_HUNSPELL_USED = 1 }; bool engine_used = native_spellchecker_used ? SPELLCHECK_OSX_NATIVE_SPELLCHECKER_USED : SPELLCHECK_HUNSPELL_USED; UMA_HISTOGRAM_COUNTS("SpellCheck.OSXEngineUsed", engine_used); } #endif #if defined(OS_WIN) FilePath GetFallbackFilePath(const FilePath& first_choice) { FilePath dict_dir; PathService::Get(chrome::DIR_USER_DATA, &dict_dir); return dict_dir.Append(first_choice.BaseName()); } #endif } // namespace // Constructed on UI thread. SpellCheckHostImpl::SpellCheckHostImpl( SpellCheckProfileProvider* profile, const std::string& language, net::URLRequestContextGetter* request_context_getter, SpellCheckHostMetrics* metrics) : profile_(profile), language_(language), file_(base::kInvalidPlatformFileValue), tried_to_download_(false), use_platform_spellchecker_(false), request_context_getter_(request_context_getter), metrics_(metrics) { DCHECK(profile_); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); FilePath personal_file_directory; PathService::Get(chrome::DIR_USER_DATA, &personal_file_directory); custom_dictionary_file_ = personal_file_directory.Append(chrome::kCustomDictionaryFileName); registrar_.Add(this, content::NOTIFICATION_RENDERER_PROCESS_CREATED, NotificationService::AllSources()); } SpellCheckHostImpl::~SpellCheckHostImpl() { if (file_ != base::kInvalidPlatformFileValue) base::ClosePlatformFile(file_); } void SpellCheckHostImpl::Initialize() { if (SpellCheckerPlatform::SpellCheckerAvailable() && SpellCheckerPlatform::PlatformSupportsLanguage(language_)) { #if defined(OS_MACOSX) RecordSpellCheckStats(true, language_); #endif use_platform_spellchecker_ = true; SpellCheckerPlatform::SetLanguage(language_); MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InformProfileOfInitialization)); return; } #if defined(OS_MACOSX) RecordSpellCheckStats(false, language_); #endif BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InitializeDictionaryLocation)); } void SpellCheckHostImpl::UnsetProfile() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); profile_ = NULL; request_context_getter_ = NULL; fetcher_.reset(); registrar_.RemoveAll(); } void SpellCheckHostImpl::InitForRenderer(RenderProcessHost* process) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); Profile* profile = Profile::FromBrowserContext(process->browser_context()); PrefService* prefs = profile->GetPrefs(); IPC::PlatformFileForTransit file = IPC::InvalidPlatformFileForTransit(); if (GetDictionaryFile() != base::kInvalidPlatformFileValue) { #if defined(OS_POSIX) file = base::FileDescriptor(GetDictionaryFile(), false); #elif defined(OS_WIN) ::DuplicateHandle(::GetCurrentProcess(), GetDictionaryFile(), process->GetHandle(), &file, 0, false, DUPLICATE_SAME_ACCESS); #endif } process->Send(new SpellCheckMsg_Init( file, profile_ ? profile_->GetCustomWords() : CustomWordList(), GetLanguage(), prefs->GetBoolean(prefs::kEnableAutoSpellCorrect))); } void SpellCheckHostImpl::AddWord(const std::string& word) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (profile_) profile_->CustomWordAddedLocally(word); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::WriteWordToCustomDictionary, word)); for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { i.GetCurrentValue()->Send(new SpellCheckMsg_WordAdded(word)); } } void SpellCheckHostImpl::InitializeDictionaryLocation() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Initialize the BDICT path. This initialization should be in the FILE thread // because it checks if there is a "Dictionaries" directory and create it. if (bdict_file_path_.empty()) bdict_file_path_ = GetFirstChoiceFilePath(language_); #if defined(OS_WIN) // Check if the dictionary exists in the fallback location. If so, use it // rather than downloading anew. FilePath fallback = GetFallbackFilePath(bdict_file_path_); if (!file_util::PathExists(bdict_file_path_) && file_util::PathExists(fallback)) { bdict_file_path_ = fallback; } #endif InitializeInternal(); } void SpellCheckHostImpl::InitializeInternal() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!profile_) return; if (!VerifyBDict(bdict_file_path_)) { DCHECK_EQ(file_, base::kInvalidPlatformFileValue); file_util::Delete(bdict_file_path_, false); // Notify browser tests that this dictionary is corrupted. We also skip // downloading the dictionary when we run this function on browser tests. if (SignalStatusEvent(BDICT_CORRUPTED)) tried_to_download_ = true; } else { file_ = base::CreatePlatformFile( bdict_file_path_, base::PLATFORM_FILE_READ | base::PLATFORM_FILE_OPEN, NULL, NULL); } // File didn't exist. Download it. if (file_ == base::kInvalidPlatformFileValue && !tried_to_download_ && request_context_getter_) { // We download from the ui thread because we need to know that // |request_context_getter_| is still valid before initiating the download. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::DownloadDictionary)); return; } request_context_getter_ = NULL; scoped_ptr<CustomWordList> custom_words(new CustomWordList()); if (file_ != base::kInvalidPlatformFileValue) { // Load custom dictionary. std::string contents; file_util::ReadFileToString(custom_dictionary_file_, &contents); CustomWordList list_of_words; base::SplitString(contents, '\n', &list_of_words); for (size_t i = 0; i < list_of_words.size(); ++i) custom_words->push_back(list_of_words[i]); } BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod( this, &SpellCheckHostImpl::InformProfileOfInitializationWithCustomWords, custom_words.release())); } void SpellCheckHostImpl::InitializeOnFileThread() { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::FILE)); BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::Initialize)); } void SpellCheckHostImpl::InformProfileOfInitialization() { InformProfileOfInitializationWithCustomWords(NULL); } void SpellCheckHostImpl::InformProfileOfInitializationWithCustomWords( CustomWordList* custom_words) { // Non-null |custom_words| should be given only if the profile is available // for simplifying the life-cycle management of the word list. DCHECK(profile_ || !custom_words); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (profile_) profile_->SpellCheckHostInitialized(custom_words); for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator()); !i.IsAtEnd(); i.Advance()) { RenderProcessHost* process = i.GetCurrentValue(); if (process) InitForRenderer(process); } } void SpellCheckHostImpl::DownloadDictionary() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (!request_context_getter_) { InitializeOnFileThread(); return; } // Determine URL of file to download. static const char kDownloadServerUrl[] = "http://cache.pack.google.com/edgedl/chrome/dict/"; std::string bdict_file = bdict_file_path_.BaseName().MaybeAsASCII(); if (bdict_file.empty()) { NOTREACHED(); return; } GURL url = GURL(std::string(kDownloadServerUrl) + StringToLowerASCII(bdict_file)); fetcher_.reset(new URLFetcher(url, URLFetcher::GET, this)); fetcher_->set_request_context(request_context_getter_); tried_to_download_ = true; fetcher_->Start(); request_context_getter_ = NULL; } void SpellCheckHostImpl::WriteWordToCustomDictionary(const std::string& word) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Stored in UTF-8. std::string word_to_add(word + "\n"); FILE* f = file_util::OpenFile(custom_dictionary_file_, "a+"); if (f) fputs(word_to_add.c_str(), f); file_util::CloseFile(f); } void SpellCheckHostImpl::OnURLFetchComplete(const URLFetcher* source, const GURL& url, const net::URLRequestStatus& status, int response_code, const net::ResponseCookies& cookies, const std::string& data) { DCHECK(source); DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); fetcher_.reset(); if ((response_code / 100) != 2) { // Initialize will not try to download the file a second time. LOG(ERROR) << "Failure to download dictionary."; InitializeOnFileThread(); return; } // Basic sanity check on the dictionary. // There's the small chance that we might see a 200 status code for a body // that represents some form of failure. if (data.size() < 4 || data[0] != 'B' || data[1] != 'D' || data[2] != 'i' || data[3] != 'c') { LOG(ERROR) << "Failure to download dictionary."; InitializeOnFileThread(); return; } data_ = data; BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::SaveDictionaryData)); } void SpellCheckHostImpl::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == content::NOTIFICATION_RENDERER_PROCESS_CREATED); RenderProcessHost* process = Source<RenderProcessHost>(source).ptr(); InitForRenderer(process); } void SpellCheckHostImpl::SaveDictionaryData() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // To prevent corrupted dictionary data from causing a renderer crash, scan // the dictionary data and verify it is sane before save it to a file. bool verified = hunspell::BDict::Verify(data_.data(), data_.size()); if (metrics_) metrics_->RecordDictionaryCorruptionStats(!verified); if (!verified) { LOG(ERROR) << "Failure to verify the downloaded dictionary."; BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InformProfileOfInitialization)); return; } size_t bytes_written = file_util::WriteFile(bdict_file_path_, data_.data(), data_.length()); if (bytes_written != data_.length()) { bool success = false; #if defined(OS_WIN) bdict_file_path_ = GetFallbackFilePath(bdict_file_path_); bytes_written = file_util::WriteFile(GetFallbackFilePath(bdict_file_path_), data_.data(), data_.length()); if (bytes_written == data_.length()) success = true; #endif data_.clear(); if (!success) { LOG(ERROR) << "Failure to save dictionary."; file_util::Delete(bdict_file_path_, false); // To avoid trying to load a partially saved dictionary, shortcut the // Initialize() call. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &SpellCheckHostImpl::InformProfileOfInitialization)); return; } } data_.clear(); Initialize(); } bool SpellCheckHostImpl::VerifyBDict(const FilePath& path) const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); // Read the dictionary file and scan its data. We need to close this file // after scanning its data so we can delete it and download a new dictionary // from our dictionary-download server if it is corrupted. file_util::MemoryMappedFile map; if (!map.Initialize(path)) return false; return hunspell::BDict::Verify( reinterpret_cast<const char*>(map.data()), map.length()); } SpellCheckHostMetrics* SpellCheckHostImpl::GetMetrics() const { return metrics_; } bool SpellCheckHostImpl::IsReady() const { return GetDictionaryFile() != base::kInvalidPlatformFileValue || IsUsingPlatformChecker(); } const base::PlatformFile& SpellCheckHostImpl::GetDictionaryFile() const { return file_; } const std::string& SpellCheckHostImpl::GetLanguage() const { return language_; } bool SpellCheckHostImpl::IsUsingPlatformChecker() const { return use_platform_spellchecker_; } <|endoftext|>
<commit_before>#include <libdariadb/utils/crc.h> #include <benchmark/benchmark_api.h> const size_t CRC_SMALL_BENCHMARK_BUFFER = 1024; const size_t CRC_BIG_BENCHMARK_BUFFER = CRC_SMALL_BENCHMARK_BUFFER * 10; class CrcFixture : public benchmark::Fixture { virtual void SetUp(const ::benchmark::State &st) { buffer = new char[st.range(0)]; size = st.range(0); } virtual void TearDown() { delete[] buffer; size = 0; } public: char *buffer; size_t size; }; BENCHMARK_DEFINE_F(CrcFixture, BufferParam)(benchmark::State &st) { while (st.KeepRunning()) { benchmark::DoNotOptimize(dariadb::utils::crc32(buffer, size)); } } BENCHMARK_REGISTER_F(CrcFixture, BufferParam)->Arg(CRC_SMALL_BENCHMARK_BUFFER); BENCHMARK_REGISTER_F(CrcFixture, BufferParam)->Arg(CRC_BIG_BENCHMARK_BUFFER);<commit_msg>microbenchmark: crcfixture => CRC<commit_after>#include <libdariadb/utils/crc.h> #include <benchmark/benchmark_api.h> const size_t CRC_SMALL_BENCHMARK_BUFFER = 1024; const size_t CRC_BIG_BENCHMARK_BUFFER = CRC_SMALL_BENCHMARK_BUFFER * 10; class CRC : public benchmark::Fixture { virtual void SetUp(const ::benchmark::State &st) { buffer = new char[st.range(0)]; size = st.range(0); } virtual void TearDown() { delete[] buffer; size = 0; } public: char *buffer; size_t size; }; BENCHMARK_DEFINE_F(CRC, BufferParam)(benchmark::State &st) { while (st.KeepRunning()) { benchmark::DoNotOptimize(dariadb::utils::crc32(buffer, size)); } } BENCHMARK_REGISTER_F(CRC, BufferParam)->Arg(CRC_SMALL_BENCHMARK_BUFFER); BENCHMARK_REGISTER_F(CRC, BufferParam)->Arg(CRC_BIG_BENCHMARK_BUFFER);<|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" #include "OpenGLMaterial.h" #include "OpenGLGState.h" #include "SceneRenderer.h" // // OpenGLMaterial::Rep // OpenGLMaterial::Rep* OpenGLMaterial::Rep::head = NULL; OpenGLMaterial::Rep* OpenGLMaterial::Rep::getRep( const GLfloat* specular, const GLfloat* emissive, GLfloat shininess) { // see if we've already got an identical material for (Rep* scan = head; scan; scan = scan->next) { if (shininess != scan->shininess) continue; const GLfloat* c1 = specular; const GLfloat* c2 = scan->specular; if (c1[0] != c2[0] || c1[1] != c2[1] || c1[2] != c2[2]) continue; c1 = emissive; c2 = scan->emissive; if (c1[0] != c2[0] || c1[1] != c2[1] || c1[2] != c2[2]) continue; scan->ref(); return scan; } // nope, make a new one return new Rep(specular, emissive, shininess); } OpenGLMaterial::Rep::Rep(const GLfloat* _specular, const GLfloat* _emissive, GLfloat _shininess) : refCount(1), shininess(_shininess) { list = INVALID_GL_LIST_ID; prev = NULL; next = head; head = this; if (next) next->prev = this; specular[0] = _specular[0]; specular[1] = _specular[1]; specular[2] = _specular[2]; specular[3] = 1.0f; emissive[0] = _emissive[0]; emissive[1] = _emissive[1]; emissive[2] = _emissive[2]; emissive[3] = 1.0f; OpenGLGState::registerContextInitializer(freeContext, initContext, (void*)this); } OpenGLMaterial::Rep::~Rep() { OpenGLGState::unregisterContextInitializer(freeContext, initContext, (void*)this); // free OpenGL display list if (list != INVALID_GL_LIST_ID) { glDeleteLists(list, 1); list = INVALID_GL_LIST_ID; } // remove me from material list if (next != NULL) next->prev = prev; if (prev != NULL) prev->next = next; else head = next; } void OpenGLMaterial::Rep::ref() { refCount++; } void OpenGLMaterial::Rep::unref() { if (--refCount == 0) delete this; } void OpenGLMaterial::Rep::execute() { if (list != INVALID_GL_LIST_ID) { glCallList(list); } else { list = glGenLists(1); glNewList(list, GL_COMPILE_AND_EXECUTE); { glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess); if (RENDERER.useQuality() > 0) { if ((specular[0] > 0.0f) || (specular[1] > 0.0f) || (specular[2] > 0.0f)) { // accurate specular highlighting (more GPU intensive) glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); } else { // speed up the lighting calcs be simplifying glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE); } } } glEndList(); } return; } void OpenGLMaterial::Rep::freeContext(void* self) { GLuint& list = ((Rep*)self)->list; if (list != INVALID_GL_LIST_ID) { glDeleteLists(list, 1); list = INVALID_GL_LIST_ID; } return; } void OpenGLMaterial::Rep::initContext(void* /*self*/) { // the next execute() call will rebuild the list return; } // // OpenGLMaterial // OpenGLMaterial::OpenGLMaterial() { rep = NULL; } OpenGLMaterial::OpenGLMaterial(const GLfloat* specular, const GLfloat* emissive, GLfloat shininess) { rep = Rep::getRep(specular, emissive, shininess); } OpenGLMaterial::OpenGLMaterial(const OpenGLMaterial& m) { rep = m.rep; if (rep) rep->ref(); } OpenGLMaterial::~OpenGLMaterial() { if (rep) rep->unref(); } OpenGLMaterial& OpenGLMaterial::operator=(const OpenGLMaterial& m) { if (rep != m.rep) { if (rep) rep->unref(); rep = m.rep; if (rep) rep->ref(); } return *this; } bool OpenGLMaterial::operator==(const OpenGLMaterial& m) const { return rep == m.rep; } bool OpenGLMaterial::operator!=(const OpenGLMaterial& m) const { return rep != m.rep; } bool OpenGLMaterial::operator<(const OpenGLMaterial& m) const { if (rep == m.rep) return false; if (!m.rep) return false; if (!rep) return true; return (rep->list < m.rep->list); } bool OpenGLMaterial::isValid() const { return (rep != NULL); } void OpenGLMaterial::execute() const { if (rep) rep->execute(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>typo<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "common.h" #include "OpenGLMaterial.h" #include "OpenGLGState.h" #include "SceneRenderer.h" // // OpenGLMaterial::Rep // OpenGLMaterial::Rep* OpenGLMaterial::Rep::head = NULL; OpenGLMaterial::Rep* OpenGLMaterial::Rep::getRep( const GLfloat* specular, const GLfloat* emissive, GLfloat shininess) { // see if we've already got an identical material for (Rep* scan = head; scan; scan = scan->next) { if (shininess != scan->shininess) continue; const GLfloat* c1 = specular; const GLfloat* c2 = scan->specular; if (c1[0] != c2[0] || c1[1] != c2[1] || c1[2] != c2[2]) continue; c1 = emissive; c2 = scan->emissive; if (c1[0] != c2[0] || c1[1] != c2[1] || c1[2] != c2[2]) continue; scan->ref(); return scan; } // nope, make a new one return new Rep(specular, emissive, shininess); } OpenGLMaterial::Rep::Rep(const GLfloat* _specular, const GLfloat* _emissive, GLfloat _shininess) : refCount(1), shininess(_shininess) { list = INVALID_GL_LIST_ID; prev = NULL; next = head; head = this; if (next) next->prev = this; specular[0] = _specular[0]; specular[1] = _specular[1]; specular[2] = _specular[2]; specular[3] = 1.0f; emissive[0] = _emissive[0]; emissive[1] = _emissive[1]; emissive[2] = _emissive[2]; emissive[3] = 1.0f; OpenGLGState::registerContextInitializer(freeContext, initContext, (void*)this); } OpenGLMaterial::Rep::~Rep() { OpenGLGState::unregisterContextInitializer(freeContext, initContext, (void*)this); // free OpenGL display list if (list != INVALID_GL_LIST_ID) { glDeleteLists(list, 1); list = INVALID_GL_LIST_ID; } // remove me from material list if (next != NULL) next->prev = prev; if (prev != NULL) prev->next = next; else head = next; } void OpenGLMaterial::Rep::ref() { refCount++; } void OpenGLMaterial::Rep::unref() { if (--refCount == 0) delete this; } void OpenGLMaterial::Rep::execute() { if (list != INVALID_GL_LIST_ID) { glCallList(list); } else { list = glGenLists(1); glNewList(list, GL_COMPILE_AND_EXECUTE); { glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess); if (RENDERER.useQuality() > 0) { if ((specular[0] > 0.0f) || (specular[1] > 0.0f) || (specular[2] > 0.0f)) { // accurate specular highlighting (more GPU intensive) glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); } else { // speed up the lighting calcs by simplifying glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE); } } } glEndList(); } return; } void OpenGLMaterial::Rep::freeContext(void* self) { GLuint& list = ((Rep*)self)->list; if (list != INVALID_GL_LIST_ID) { glDeleteLists(list, 1); list = INVALID_GL_LIST_ID; } return; } void OpenGLMaterial::Rep::initContext(void* /*self*/) { // the next execute() call will rebuild the list return; } // // OpenGLMaterial // OpenGLMaterial::OpenGLMaterial() { rep = NULL; } OpenGLMaterial::OpenGLMaterial(const GLfloat* specular, const GLfloat* emissive, GLfloat shininess) { rep = Rep::getRep(specular, emissive, shininess); } OpenGLMaterial::OpenGLMaterial(const OpenGLMaterial& m) { rep = m.rep; if (rep) rep->ref(); } OpenGLMaterial::~OpenGLMaterial() { if (rep) rep->unref(); } OpenGLMaterial& OpenGLMaterial::operator=(const OpenGLMaterial& m) { if (rep != m.rep) { if (rep) rep->unref(); rep = m.rep; if (rep) rep->ref(); } return *this; } bool OpenGLMaterial::operator==(const OpenGLMaterial& m) const { return rep == m.rep; } bool OpenGLMaterial::operator!=(const OpenGLMaterial& m) const { return rep != m.rep; } bool OpenGLMaterial::operator<(const OpenGLMaterial& m) const { if (rep == m.rep) return false; if (!m.rep) return false; if (!rep) return true; return (rep->list < m.rep->list); } bool OpenGLMaterial::isValid() const { return (rep != NULL); } void OpenGLMaterial::execute() const { if (rep) rep->execute(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_IMGCODECS_HPP__ #define __OPENCV_IMGCODECS_HPP__ #include "opencv2/core.hpp" /** @defgroup imgcodecs Image file reading and writing @{ @defgroup imgcodecs_c C API @defgroup imgcodecs_ios iOS glue @} */ //////////////////////////////// image codec //////////////////////////////// namespace cv { //! @addtogroup imgcodecs //! @{ //! Imread flags enum ImreadModes { IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image. IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image. IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. IMREAD_REDUCED_COLOR_8 = 65 //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. }; //! Imwrite flags enum ImwriteFlags { IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is 0 - don't use. IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is 0 - don't use. IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3. IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_DEFAULT. IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. IMWRITE_WEBP_QUALITY = 64 //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. }; //! Imwrite PNG specific flags used to tune the compression algorithm. /** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. - The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. - IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data. - The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. - IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. */ enum ImwritePNGFlags { IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. }; /** @brief Loads an image from a file. @anchor imread The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ). Currently, the following file formats are supported: - Windows bitmaps - \*.bmp, \*.dib (always supported) - JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Notes* section) - JPEG 2000 files - \*.jp2 (see the *Notes* section) - Portable Network Graphics - \*.png (see the *Notes* section) - WebP - \*.webp (see the *Notes* section) - Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported) - Sun rasters - \*.sr, \*.ras (always supported) - TIFF files - \*.tiff, \*.tif (see the *Notes* section) - OpenEXR Image files - \*.exr (see the *Notes* section) - Radiance HDR - \*.hdr, \*.pic (always supported) - Raster and Vector geospatial data supported by Gdal (see the *Notes* section) @note - The function determines the type of an image by the content, not by the file extension. - In the case of color images, the decoded images will have the channels stored in **B G R** order. - On Microsoft Windows\* OS and MacOSX\*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX. - On Linux\*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian\* and Ubuntu\*) to get the codec support or turn on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. - In the case you set *WITH_GDAL* flag to true in CMake and @ref IMREAD_LOAD_GDAL to load the image, then [GDAL](http://www.gdal.org) driver will be used in order to decode the image by supporting the following formats: [Raster](http://www.gdal.org/formats_list.html), [Vector](http://www.gdal.org/ogr_formats.html). @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes */ CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR ); /** @brief Loads a multi-page image from a file. The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. @param mats A vector of Mat objects holding each page, if more than one. @sa cv::imread */ CV_EXPORTS_W bool imreadmulti(const String& filename, std::vector<Mat>& mats, int flags = IMREAD_ANYCOLOR); /** @brief Saves an image to a specified file. The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo , and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format. It is possible to store PNG images with an alpha channel using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535. The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom compression parameters : @code #include <vector> #include <stdio.h> #include <opencv2/opencv.hpp> using namespace cv; using namespace std; void createAlphaMat(Mat &mat) { CV_Assert(mat.channels() == 4); for (int i = 0; i < mat.rows; ++i) { for (int j = 0; j < mat.cols; ++j) { Vec4b& bgra = mat.at<Vec4b>(i, j); bgra[0] = UCHAR_MAX; // Blue bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha } } } int main(int argv, char **argc) { // Create mat with alpha channel Mat mat(480, 640, CV_8UC4); createAlphaMat(mat); vector<int> compression_params; compression_params.push_back(IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); try { imwrite("alpha.png", mat, compression_params); } catch (runtime_error& ex) { fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what()); return 1; } fprintf(stdout, "Saved PNG file with alpha data.\n"); return 0; } @endcode @param filename Name of the file. @param img Image to be saved. @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags */ CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, const std::vector<int>& params = std::vector<int>()); /** @brief Reads an image from a buffer in memory. The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). See cv::imread for the list of supported formats and flags description. @note In the case of color images, the decoded images will have the channels stored in **B G R** order. @param buf Input array or vector of bytes. @param flags The same flags as in cv::imread, see cv::ImreadModes. */ CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); /** @overload @param buf @param flags @param dst The optional output placeholder for the decoded matrix. It can save the image reallocations when the function is called repeatedly for images of the same size. */ CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); /** @brief Encodes an image into a memory buffer. The function imencode compresses the image and stores it in the memory buffer that is resized to fit the result. See cv::imwrite for the list of supported formats and flags description. @param ext File extension that defines the output format. @param img Image to be written. @param buf Output buffer resized to fit the compressed image. @param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. */ CV_EXPORTS_W bool imencode( const String& ext, InputArray img, CV_OUT std::vector<uchar>& buf, const std::vector<int>& params = std::vector<int>()); //! @} imgcodecs } // cv #endif //__OPENCV_IMGCODECS_HPP__ <commit_msg>Update imgcodecs.hpp<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_IMGCODECS_HPP__ #define __OPENCV_IMGCODECS_HPP__ #include "opencv2/core.hpp" /** @defgroup imgcodecs Image file reading and writing @{ @defgroup imgcodecs_c C API @defgroup imgcodecs_ios iOS glue @} */ //////////////////////////////// image codec //////////////////////////////// namespace cv { //! @addtogroup imgcodecs //! @{ //! Imread flags enum ImreadModes { IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image. IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image. IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. IMREAD_REDUCED_COLOR_8 = 65 //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. }; //! Imwrite flags enum ImwriteFlags { IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is 0 - don't use. IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is 0 - don't use. IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3. IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_DEFAULT. IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. IMWRITE_WEBP_QUALITY = 64 //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. }; //! Imwrite PNG specific flags used to tune the compression algorithm. /** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. - The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. - IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data. - The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. - IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. */ enum ImwritePNGFlags { IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. }; /** @brief Loads an image from a file. @anchor imread The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ). Currently, the following file formats are supported: - Windows bitmaps - \*.bmp, \*.dib (always supported) - JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Notes* section) - JPEG 2000 files - \*.jp2 (see the *Notes* section) - Portable Network Graphics - \*.png (see the *Notes* section) - WebP - \*.webp (see the *Notes* section) - Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported) - Sun rasters - \*.sr, \*.ras (always supported) - TIFF files - \*.tiff, \*.tif (see the *Notes* section) - OpenEXR Image files - \*.exr (see the *Notes* section) - Radiance HDR - \*.hdr, \*.pic (always supported) - Raster and Vector geospatial data supported by Gdal (see the *Notes* section) @note - The function determines the type of an image by the content, not by the file extension. - In the case of color images, the decoded images will have the channels stored in **B G R** order. - On Microsoft Windows\* OS and MacOSX\*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX. - On Linux\*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian\* and Ubuntu\*) to get the codec support or turn on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. - In the case you set *WITH_GDAL* flag to true in CMake and @ref IMREAD_LOAD_GDAL to load the image, then [GDAL](http://www.gdal.org) driver will be used in order to decode the image by supporting the following formats: [Raster](http://www.gdal.org/formats_list.html), [Vector](http://www.gdal.org/ogr_formats.html). @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes */ CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR ); /** @brief Loads a multi-page image from a file. The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. @param mats A vector of Mat objects holding each page, if more than one. @sa cv::imread */ CV_EXPORTS_W bool imreadmulti(const String& filename, std::vector<Mat>& mats, int flags = IMREAD_ANYCOLOR); /** @brief Saves an image to a specified file. The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo , and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format. It is possible to store PNG images with an alpha channel using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535. The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom compression parameters : @code #include <opencv2/opencv.hpp> using namespace cv; using namespace std; void createAlphaMat(Mat &mat) { CV_Assert(mat.channels() == 4); for (int i = 0; i < mat.rows; ++i) { for (int j = 0; j < mat.cols; ++j) { Vec4b& bgra = mat.at<Vec4b>(i, j); bgra[0] = UCHAR_MAX; // Blue bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha } } } int main(int argv, char **argc) { // Create mat with alpha channel Mat mat(480, 640, CV_8UC4); createAlphaMat(mat); vector<int> compression_params; compression_params.push_back(IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); try { imwrite("alpha.png", mat, compression_params); } catch (cv::Exception& ex) { fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what()); return 1; } fprintf(stdout, "Saved PNG file with alpha data.\n"); return 0; } @endcode @param filename Name of the file. @param img Image to be saved. @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags */ CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, const std::vector<int>& params = std::vector<int>()); /** @brief Reads an image from a buffer in memory. The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). See cv::imread for the list of supported formats and flags description. @note In the case of color images, the decoded images will have the channels stored in **B G R** order. @param buf Input array or vector of bytes. @param flags The same flags as in cv::imread, see cv::ImreadModes. */ CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); /** @overload @param buf @param flags @param dst The optional output placeholder for the decoded matrix. It can save the image reallocations when the function is called repeatedly for images of the same size. */ CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); /** @brief Encodes an image into a memory buffer. The function imencode compresses the image and stores it in the memory buffer that is resized to fit the result. See cv::imwrite for the list of supported formats and flags description. @param ext File extension that defines the output format. @param img Image to be written. @param buf Output buffer resized to fit the compressed image. @param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. */ CV_EXPORTS_W bool imencode( const String& ext, InputArray img, CV_OUT std::vector<uchar>& buf, const std::vector<int>& params = std::vector<int>()); //! @} imgcodecs } // cv #endif //__OPENCV_IMGCODECS_HPP__ <|endoftext|>
<commit_before>#include "system/printer.hpp" #include "math.hpp" #include <iostream> #include <sstream> int main(int argc, const char **argv) { using namespace System; using namespace Math; quat<int> r0 = {0,0,0,0}, r1 = {1,0,0,0}, ri = {0,1,0,0}, rj = {0,0,1,0}, rk = {0,0,0,1}; dual<int> d10 = {r1, r0}, di0 = {ri, r0}, dj0 = {rj, r0}, dk0 = {rk, r0}, d01 = {r0, r1}, d0i = {r0, ri}, d0j = {r0, rj}, d0k = {r0, rk}, duals[]{d10, di0, dj0, dk0, d01, d0i, d0j, d0k}; Printer<10> printer; std::string rows[10], cols[8]; dual<int> cells[64]; rows[0] = rows[9] = ""; int row = 0; for(auto lhs : duals) { std::ostringstream oss; oss << lhs; rows[row+1] = cols[row] = oss.str(); int col = 0; for(auto rhs : duals) { cells[row*8+col] = lhs * rhs; col++; } row++; } printer.push(&rows[0], &rows[0]+10) .push<dual<int>, 8, 8>(cells, &cols[0], &cols[8]).level(); std::cout << printer << std::endl; } <commit_msg>Added sample uses of dual<commit_after>#include "system/printer.hpp" #include "math.hpp" #include <iostream> #include <sstream> template<typename T> std::string pad(const T &t) { using namespace System; return Printer_Base::align(t, 14, Printer_Base::CENTER); } template<typename T> std::string paren(const T &t) { return "(" + pad(t) + ")"; } template<typename T> std::string transforms(const T &outer, const T &inner) { return paren(outer) + "*" + paren(inner) + "*" + paren(~outer) + " = " + pad(outer(inner)); } int main(int argc, const char **argv) { using namespace System; using namespace Math; quat<float> r0 = {0,0,0,0}, r1 = {1,0,0,0}, ri = {0,1,0,0}, rj = {0,0,1,0}, rk = {0,0,0,1}; dual<float> d10 = {r1, r0}, di0 = {ri, r0}, dj0 = {rj, r0}, dk0 = {rk, r0}, d01 = {r0, r1}, d0i = {r0, ri}, d0j = {r0, rj}, d0k = {r0, rk}, duals[]{d10, di0, dj0, dk0, d01, d0i, d0j, d0k}; Printer<10> printer; std::string rows[10], cols[8]; dual<float> cells[64]; rows[0] = rows[9] = ""; int row = 0; for(auto lhs : duals) { std::ostringstream oss; oss << lhs; rows[row+1] = cols[row] = oss.str(); int col = 0; for(auto rhs : duals) { cells[row*8+col] = lhs * rhs; col++; } row++; } printer.push(&rows[0], &rows[0]+10) .push<dual<float>, 8, 8>(cells, &cols[0], &cols[8]).level(); std::cout << printer << std::endl; std::cout << transforms(d10+d0i, d10+d0j) << std::endl; std::cout << transforms(dj0, d10+d0i) << std::endl; std::cout << transforms(d10+d0j, d10+d0i) << std::endl; } <|endoftext|>
<commit_before> // PlayerDoc.cpp : implementation of the CPlayerDoc class // #include "stdafx.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "Player.h" #endif #include "PlayerDoc.h" #include "AudioPlayerImpl.h" #include "AudioPlayerWasapi.h" #include "DialogOpenURL.h" #include <propkey.h> #include <memory> #include <boost/icl/interval_map.hpp> #include <fstream> #include <VersionHelpers.h> #ifdef _DEBUG #define new DEBUG_NEW #endif class CPlayerDoc::SubtitlesMap : public boost::icl::interval_map<double, std::string> {}; // CPlayerDoc IMPLEMENT_DYNCREATE(CPlayerDoc, CDocument) BEGIN_MESSAGE_MAP(CPlayerDoc, CDocument) ON_COMMAND_RANGE(ID_TRACK1, ID_TRACK4, OnAudioTrack) ON_UPDATE_COMMAND_UI_RANGE(ID_TRACK1, ID_TRACK4, OnUpdateAudioTrack) END_MESSAGE_MAP() // CPlayerDoc construction/destruction CPlayerDoc::CPlayerDoc() : m_frameDecoder( IsWindowsVistaOrGreater() ? GetFrameDecoder(std::make_unique<AudioPlayerWasapi>()) : GetFrameDecoder(std::make_unique<AudioPlayerImpl>())) , m_unicodeSubtitles(false) { m_frameDecoder->setDecoderListener(this); } CPlayerDoc::~CPlayerDoc() { ASSERT(framePositionChanged.empty()); ASSERT(totalTimeUpdated.empty()); ASSERT(currentTimeUpdated.empty()); } BOOL CPlayerDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // (SDI documents will reuse this document) if (AfxGetApp()->m_pMainWnd) // false if the document is being initialized for the first time { CDialogOpenURL dlg; if (dlg.DoModal() == IDOK && !dlg.m_URL.IsEmpty()) { m_frameDecoder->close(); UpdateAllViews(nullptr, UPDATE_HINT_CLOSING, nullptr); const std::string url(dlg.m_URL.GetString(), dlg.m_URL.GetString() + dlg.m_URL.GetLength()); if (m_frameDecoder->openUrl(url)) { m_frameDecoder->play(); } } } return TRUE; } // CPlayerDoc serialization void CPlayerDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } #ifdef SHARED_HANDLERS // Support for thumbnails void CPlayerDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // Modify this code to draw the document's data dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // Support for Search Handlers void CPlayerDoc::InitializeSearchContent() { CString strSearchContent; // Set search contents from document's data. // The content parts should be separated by ";" // For example: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void CPlayerDoc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // CPlayerDoc diagnostics #ifdef _DEBUG void CPlayerDoc::AssertValid() const { CDocument::AssertValid(); } void CPlayerDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CPlayerDoc commands BOOL CPlayerDoc::OnOpenDocument(LPCTSTR lpszPathName) { //if (!CDocument::OnOpenDocument(lpszPathName)) // return FALSE; m_frameDecoder->close(); UpdateAllViews(nullptr, UPDATE_HINT_CLOSING, nullptr); if (m_frameDecoder->openFile(lpszPathName)) { if (!OpenSubRipFile(lpszPathName)) OpenSubStationAlphaFile(lpszPathName); m_frameDecoder->play(); return TRUE; } return FALSE; } void CPlayerDoc::OnCloseDocument() { m_frameDecoder->close(); m_subtitles.reset(); CDocument::OnCloseDocument(); } void CPlayerDoc::changedFramePosition(long long start, long long frame, long long total) { framePositionChanged(frame - start, total - start); const double currentTime = m_frameDecoder->getDurationSecs(frame); m_currentTime = currentTime; totalTimeUpdated(m_frameDecoder->getDurationSecs(total)); currentTimeUpdated(currentTime); } bool CPlayerDoc::pauseResume() { return m_frameDecoder->pauseResume(); } bool CPlayerDoc::seekByPercent(double percent) { return m_frameDecoder->seekByPercent(percent); } void CPlayerDoc::setVolume(double volume) { m_frameDecoder->setVolume(volume); } bool CPlayerDoc::isPlaying() const { return m_frameDecoder->isPlaying(); } bool CPlayerDoc::isPaused() const { return m_frameDecoder->isPaused(); } double CPlayerDoc::soundVolume() const { return m_frameDecoder->volume(); } bool CPlayerDoc::OpenSubRipFile(LPCTSTR lpszVideoPathName) { m_subtitles.reset(); CString subRipPathName(lpszVideoPathName); PathRemoveExtension(subRipPathName.GetBuffer()); subRipPathName.ReleaseBuffer(); subRipPathName += _T(".srt"); std::ifstream s(subRipPathName); if (!s) return false; auto map(std::make_unique<SubtitlesMap>()); std::string buffer; bool first = true; while (std::getline(s, buffer)) { if (first) { m_unicodeSubtitles = buffer.length() > 2 && buffer[0] == char(0xEF) && buffer[1] == char(0xBB) && buffer[2] == char(0xBF); first = false; } if (!std::getline(s, buffer)) break; int startHr, startMin, startSec, startMsec; int endHr, endMin, endSec, endMsec; if (sscanf( buffer.c_str(), "%d:%d:%d,%d --> %d:%d:%d,%d", &startHr, &startMin, &startSec, &startMsec, &endHr, &endMin, &endSec, &endMsec) != 8) { break; } const double start = startHr * 3600 + startMin * 60 + startSec + startMsec / 1000.; const double end = endHr * 3600 + endMin * 60 + endSec + endMsec / 1000.; std::string subtitle; while (std::getline(s, buffer) && !buffer.empty()) { subtitle += buffer; subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any) } if (!subtitle.empty()) { map->add(std::make_pair(boost::icl::interval<double>::closed(start, end), subtitle)); } } if (!map->empty()) { m_subtitles = std::move(map); } return true; } bool CPlayerDoc::OpenSubStationAlphaFile(LPCTSTR lpszVideoPathName) { m_subtitles.reset(); CString subRipPathName(lpszVideoPathName); PathRemoveExtension(subRipPathName.GetBuffer()); subRipPathName.ReleaseBuffer(); subRipPathName += _T(".ass"); std::ifstream s(subRipPathName); if (!s) return false; auto map(std::make_unique<SubtitlesMap>()); std::string buffer; bool first = true; while (std::getline(s, buffer)) { if (first) { m_unicodeSubtitles = buffer.length() > 2 && buffer[0] == char(0xEF) && buffer[1] == char(0xBB) && buffer[2] == char(0xBF); first = false; } std::istringstream ss(buffer); std::getline(ss, buffer, ':'); if (buffer != "Dialogue") continue; double start, end; for (int i = 0; i < 9; ++i) { std::getline(ss, buffer, ','); if (i == 1 || i == 2) { int hr, min, sec, msec; if (sscanf( buffer.c_str(), "%d:%d:%d.%d", &hr, &min, &sec, &msec) != 4) { return true; } ((i == 1)? start : end) = hr * 3600 + min * 60 + sec + msec / 1000.; } } std::string subtitle; if (!std::getline(ss, subtitle, '\\')) continue; while (std::getline(ss, buffer, '\\')) { subtitle += (buffer[0] == 'N' || buffer[0] == 'n')? '\n' + buffer.substr(1) : '\\' + buffer; } if (!subtitle.empty()) { subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any) map->add(std::make_pair(boost::icl::interval<double>::closed(start, end), subtitle)); } } if (!map->empty()) { m_subtitles = std::move(map); } return true; } std::string CPlayerDoc::getSubtitle() { std::string result; if (m_subtitles) { auto it = m_subtitles->find(m_currentTime); if (it != m_subtitles->end()) { result = it->second; } } return result; } void CPlayerDoc::OnAudioTrack(UINT id) { m_frameDecoder->setAudioTrack(id - ID_TRACK1); } void CPlayerDoc::OnUpdateAudioTrack(CCmdUI* pCmdUI) { const int idx = pCmdUI->m_nID - ID_TRACK1; pCmdUI->Enable(idx < m_frameDecoder->getNumAudioTracks()); pCmdUI->SetCheck(idx == m_frameDecoder->getAudioTrack()); } <commit_msg>some fixes for SSA subtitles<commit_after> // PlayerDoc.cpp : implementation of the CPlayerDoc class // #include "stdafx.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "Player.h" #endif #include "PlayerDoc.h" #include "AudioPlayerImpl.h" #include "AudioPlayerWasapi.h" #include "DialogOpenURL.h" #include <propkey.h> #include <memory> #include <boost/icl/interval_map.hpp> #include <fstream> #include <VersionHelpers.h> #ifdef _DEBUG #define new DEBUG_NEW #endif class CPlayerDoc::SubtitlesMap : public boost::icl::interval_map<double, std::string> {}; // CPlayerDoc IMPLEMENT_DYNCREATE(CPlayerDoc, CDocument) BEGIN_MESSAGE_MAP(CPlayerDoc, CDocument) ON_COMMAND_RANGE(ID_TRACK1, ID_TRACK4, OnAudioTrack) ON_UPDATE_COMMAND_UI_RANGE(ID_TRACK1, ID_TRACK4, OnUpdateAudioTrack) END_MESSAGE_MAP() // CPlayerDoc construction/destruction CPlayerDoc::CPlayerDoc() : m_frameDecoder( IsWindowsVistaOrGreater() ? GetFrameDecoder(std::make_unique<AudioPlayerWasapi>()) : GetFrameDecoder(std::make_unique<AudioPlayerImpl>())) , m_unicodeSubtitles(false) { m_frameDecoder->setDecoderListener(this); } CPlayerDoc::~CPlayerDoc() { ASSERT(framePositionChanged.empty()); ASSERT(totalTimeUpdated.empty()); ASSERT(currentTimeUpdated.empty()); } BOOL CPlayerDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // (SDI documents will reuse this document) if (AfxGetApp()->m_pMainWnd) // false if the document is being initialized for the first time { CDialogOpenURL dlg; if (dlg.DoModal() == IDOK && !dlg.m_URL.IsEmpty()) { m_frameDecoder->close(); UpdateAllViews(nullptr, UPDATE_HINT_CLOSING, nullptr); const std::string url(dlg.m_URL.GetString(), dlg.m_URL.GetString() + dlg.m_URL.GetLength()); if (m_frameDecoder->openUrl(url)) { m_frameDecoder->play(); } } } return TRUE; } // CPlayerDoc serialization void CPlayerDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } #ifdef SHARED_HANDLERS // Support for thumbnails void CPlayerDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // Modify this code to draw the document's data dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // Support for Search Handlers void CPlayerDoc::InitializeSearchContent() { CString strSearchContent; // Set search contents from document's data. // The content parts should be separated by ";" // For example: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void CPlayerDoc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // CPlayerDoc diagnostics #ifdef _DEBUG void CPlayerDoc::AssertValid() const { CDocument::AssertValid(); } void CPlayerDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CPlayerDoc commands BOOL CPlayerDoc::OnOpenDocument(LPCTSTR lpszPathName) { //if (!CDocument::OnOpenDocument(lpszPathName)) // return FALSE; m_frameDecoder->close(); UpdateAllViews(nullptr, UPDATE_HINT_CLOSING, nullptr); if (m_frameDecoder->openFile(lpszPathName)) { if (!OpenSubRipFile(lpszPathName)) OpenSubStationAlphaFile(lpszPathName); m_frameDecoder->play(); return TRUE; } return FALSE; } void CPlayerDoc::OnCloseDocument() { m_frameDecoder->close(); m_subtitles.reset(); CDocument::OnCloseDocument(); } void CPlayerDoc::changedFramePosition(long long start, long long frame, long long total) { framePositionChanged(frame - start, total - start); const double currentTime = m_frameDecoder->getDurationSecs(frame); m_currentTime = currentTime; totalTimeUpdated(m_frameDecoder->getDurationSecs(total)); currentTimeUpdated(currentTime); } bool CPlayerDoc::pauseResume() { return m_frameDecoder->pauseResume(); } bool CPlayerDoc::seekByPercent(double percent) { return m_frameDecoder->seekByPercent(percent); } void CPlayerDoc::setVolume(double volume) { m_frameDecoder->setVolume(volume); } bool CPlayerDoc::isPlaying() const { return m_frameDecoder->isPlaying(); } bool CPlayerDoc::isPaused() const { return m_frameDecoder->isPaused(); } double CPlayerDoc::soundVolume() const { return m_frameDecoder->volume(); } bool CPlayerDoc::OpenSubRipFile(LPCTSTR lpszVideoPathName) { m_subtitles.reset(); CString subRipPathName(lpszVideoPathName); PathRemoveExtension(subRipPathName.GetBuffer()); subRipPathName.ReleaseBuffer(); subRipPathName += _T(".srt"); std::ifstream s(subRipPathName); if (!s) return false; auto map(std::make_unique<SubtitlesMap>()); std::string buffer; bool first = true; while (std::getline(s, buffer)) { if (first) { m_unicodeSubtitles = buffer.length() > 2 && buffer[0] == char(0xEF) && buffer[1] == char(0xBB) && buffer[2] == char(0xBF); first = false; } if (!std::getline(s, buffer)) break; int startHr, startMin, startSec, startMsec; int endHr, endMin, endSec, endMsec; if (sscanf( buffer.c_str(), "%d:%d:%d,%d --> %d:%d:%d,%d", &startHr, &startMin, &startSec, &startMsec, &endHr, &endMin, &endSec, &endMsec) != 8) { break; } const double start = startHr * 3600 + startMin * 60 + startSec + startMsec / 1000.; const double end = endHr * 3600 + endMin * 60 + endSec + endMsec / 1000.; std::string subtitle; while (std::getline(s, buffer) && !buffer.empty()) { subtitle += buffer; subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any) } if (!subtitle.empty()) { map->add(std::make_pair(boost::icl::interval<double>::closed(start, end), subtitle)); } } if (!map->empty()) { m_subtitles = std::move(map); } return true; } bool CPlayerDoc::OpenSubStationAlphaFile(LPCTSTR lpszVideoPathName) { m_subtitles.reset(); CString subRipPathName(lpszVideoPathName); PathRemoveExtension(subRipPathName.GetBuffer()); subRipPathName.ReleaseBuffer(); subRipPathName += _T(".ass"); std::ifstream s(subRipPathName); if (!s) return false; auto map(std::make_unique<SubtitlesMap>()); std::string buffer; bool first = true; while (std::getline(s, buffer)) { if (first) { m_unicodeSubtitles = buffer.length() > 2 && buffer[0] == char(0xEF) && buffer[1] == char(0xBB) && buffer[2] == char(0xBF); first = false; } std::istringstream ss(buffer); std::getline(ss, buffer, ':'); if (buffer != "Dialogue") continue; double start, end; bool skip = false; for (int i = 0; i < 9; ++i) // TODO indices from Format? { std::getline(ss, buffer, ','); if (i == 1 || i == 2) { int hr, min, sec; char msecString[10] {}; if (sscanf( buffer.c_str(), "%d:%d:%d.%9s", &hr, &min, &sec, msecString) != 4) { return true; } double msec = 0; if (const auto msecStringLen = strlen(msecString)) { msec = atoi(msecString) / pow(10, msecStringLen); } ((i == 1)? start : end) = hr * 3600 + min * 60 + sec + msec; } else if (i == 3 && buffer == "OP_kar") { skip = true; break; } } if (skip) continue; std::string subtitle; if (!std::getline(ss, subtitle, '\\')) continue; while (std::getline(ss, buffer, '\\')) { subtitle += (buffer[0] == 'N' || buffer[0] == 'n')? '\n' + buffer.substr(1) : '\\' + buffer; } if (!subtitle.empty()) { subtitle += '\n'; // The last '\n' is for aggregating overlapped subtitles (if any) map->add(std::make_pair(boost::icl::interval<double>::closed(start, end), subtitle)); } } if (!map->empty()) { m_subtitles = std::move(map); } return true; } std::string CPlayerDoc::getSubtitle() { std::string result; if (m_subtitles) { auto it = m_subtitles->find(m_currentTime); if (it != m_subtitles->end()) { result = it->second; } } return result; } void CPlayerDoc::OnAudioTrack(UINT id) { m_frameDecoder->setAudioTrack(id - ID_TRACK1); } void CPlayerDoc::OnUpdateAudioTrack(CCmdUI* pCmdUI) { const int idx = pCmdUI->m_nID - ID_TRACK1; pCmdUI->Enable(idx < m_frameDecoder->getNumAudioTracks()); pCmdUI->SetCheck(idx == m_frameDecoder->getAudioTrack()); } <|endoftext|>
<commit_before>/* * raft_if, Go layer of libraft * Copyright (C) 2015 Clayton Wheeler * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <algorithm> #include <chrono> #include <cinttypes> #include <cstdio> #include <unistd.h> #include <thread> #include <vector> #include "raft_go_if.h" #include "raft_shm.h" #include "queue.h" extern "C" { #include "_cgo_export.h" } using namespace raft; using boost::interprocess::anonymous_instance; using boost::interprocess::unique_instance; namespace { zlog_category_t* go_cat; void run_worker(); void take_call(); #define api_call(name, arg_t, has_ret) \ void dispatch_ ## name(api::name::slot_t& slot); #include "raft_api_calls.h" #undef api_call const static uint32_t N_WORKERS = 4; std::vector<std::thread> workers; } void raft_ready() { workers.reserve(N_WORKERS); for (uint32_t i = 0; i < N_WORKERS; ++i) { workers.emplace_back(run_worker); } raft::scoreboard->is_raft_running = true; } namespace { void raft_reply_(BaseSlot& slot, RaftError error); void run_worker() { zlog_debug(go_cat, "Starting worker."); try { for (;;) { take_call(); } } catch (queue::queue_closed&) { zlog_debug(go_cat, "API queue closed, Go worker exiting."); return; } } void take_call() { auto rec = scoreboard->api_queue.take(); auto recv_ts = Timings::clock::now(); CallTag tag = rec.first; BaseSlot::pointer slot = rec.second; raft::mutex_lock l(slot->owned); slot->timings.record("call received", recv_ts); slot->timings.record("call locked"); zlog_debug(go_cat, "API call received, tag %d, call %p.", tag, slot.get()); assert(slot->state == raft::CallState::Pending); switch (tag) { #define api_call(name, arg_t, has_ret) \ case api::name::tag: \ dispatch_ ## name((api::name::slot_t&) *slot); \ break; #include "raft_api_calls.h" #undef api_call default: zlog_fatal(go_cat, "Unhandled call type: %d", tag); abort(); } //slot->state = raft::CallState::Dispatched; } uintptr_t shm_offset(void* ptr) { uintptr_t shm_base = (uintptr_t) shm.get_address(); uintptr_t shm_end = (uintptr_t) shm_base + shm.get_size(); uintptr_t address = (uintptr_t) ptr; assert(address >= shm_base && address < shm_end); return address - shm_base; } void dispatch_Apply(api::Apply::slot_t& slot) { assert(slot.tag == api::Apply::tag); size_t cmd_offset = shm_offset(slot.args.cmd_buf.get()); RaftApply(&slot, cmd_offset, slot.args.cmd_len, slot.args.timeout_ns); } void dispatch_Barrier(api::Barrier::slot_t& slot) { RaftBarrier(&slot, slot.args.timeout_ns); } void dispatch_VerifyLeader(api::VerifyLeader::slot_t& slot) { RaftVerifyLeader(&slot); } void dispatch_GetState(api::GetState::slot_t& slot) { RaftGetState(&slot); } void dispatch_LastContact(api::LastContact::slot_t& slot) { RaftLastContact(&slot); } void dispatch_LastIndex(api::LastIndex::slot_t& slot) { RaftLastIndex(&slot); } void dispatch_GetLeader(api::GetLeader::slot_t& slot) { RaftGetLeader(&slot); } void dispatch_Snapshot(api::Snapshot::slot_t& slot) { assert(slot.tag == CallTag::Snapshot); RaftSnapshot(&slot); } void dispatch_AddPeer(api::AddPeer::slot_t& slot) { assert(slot.tag == CallTag::AddPeer); RaftAddPeer(&slot, (char*) slot.args.host, slot.args.port); } void dispatch_RemovePeer(api::RemovePeer::slot_t& slot) { assert(slot.tag == CallTag::RemovePeer); RaftRemovePeer(&slot, (char*) slot.args.host, slot.args.port); } void dispatch_Shutdown(api::Shutdown::slot_t& slot) { assert(slot.tag == CallTag::Shutdown); slot.state = raft::CallState::Dispatched; RaftShutdown(&slot); } } void raft_reply(raft_call call_p, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); raft_reply_(*slot, error); } void raft_reply_immed(raft_call call_p, RaftError error) { raft_reply_(*(BaseSlot*) call_p, error); } void raft_reply_apply(raft_call call_p, uint64_t retval, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); slot->timings.record("RaftApply return"); assert(slot->tag == CallTag::Apply); if (!error) { slot->reply(retval); } else { zlog_error(go_cat, "Sending error response from RaftApply: %d", error); slot->reply(error); } } namespace { /** * Send reply IFF we already hold the lock on slot! */ void raft_reply_(BaseSlot& slot, RaftError error) { slot.timings.record("Raft call return"); slot.reply(error); } } void raft_reply_value(raft_call call, uint64_t retval) { // TODO: check that this has a return value... auto* slot = (BaseSlot*) call; mutex_lock lock(slot->owned); slot->timings.record("Raft call return"); slot->reply(retval); } uint64_t raft_fsm_apply(uint64_t index, uint64_t term, RaftLogType type, char* cmd_buf, size_t cmd_len) { shm_handle cmd_handle; char* shm_buf = nullptr; if (in_shm_bounds(cmd_buf)) { cmd_handle = raft::shm.get_handle_from_address(cmd_buf); } else { shm_buf = (char*) raft::shm.allocate(cmd_len); assert(shm_buf); zlog_debug(go_cat, "Allocated %lu-byte buffer for log command at %p.", cmd_len, shm_buf); memcpy(shm_buf, cmd_buf, cmd_len); cmd_handle = raft::shm.get_handle_from_address(shm_buf); } auto* slot = send_fsm_request<api::FSMApply>(index, term, type, cmd_handle, cmd_len); slot->wait(); assert(slot->state == raft::CallState::Success); assert(slot->error == RAFT_SUCCESS); zlog_debug(go_cat, "FSM response %#" PRIx64 , slot->retval); if (shm_buf) shm.deallocate(shm_buf); //slot->timings.print(); //fprintf(stderr, "====================\n"); auto rv = slot->retval; slot->dispose(); return rv; } int raft_fsm_snapshot(char *path) { auto* slot = send_fsm_request<api::FSMSnapshot>(path); free(path); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } int raft_fsm_restore(char *path) { auto* slot = send_fsm_request<api::FSMRestore>(path); free(path); zlog_info(go_cat, "Sent restore request to FSM."); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } void raft_set_leader(bool val) { zlog_info(go_cat, "Leadership state change: %s", val ? "is leader" : "not leader"); raft::scoreboard->is_leader = val; } void* raft_shm_init(const char *shm_path) { raft::shm_init(shm_path, false, nullptr); free((void*) shm_path); go_cat = zlog_get_category("raft_go"); return raft::shm.get_address(); } size_t raft_shm_size() { return raft::shm.get_size(); } uint64_t raft_shm_string(const char *str, size_t len) { char* buf = (char*) raft::shm.allocate(len+1); assert(raft::in_shm_bounds((void*) buf)); memcpy(buf, str, len); free((void*) str); buf[len] = '\0'; return (uint64_t) raft::shm.get_handle_from_address(buf); } RaftConfig* raft_get_config() { return raft::shm.find<RaftConfig>(unique_instance).first; } <commit_msg>Add knob for API worker threads.<commit_after>/* * raft_if, Go layer of libraft * Copyright (C) 2015 Clayton Wheeler * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <algorithm> #include <chrono> #include <cinttypes> #include <cstdio> #include <unistd.h> #include <thread> #include <vector> #include "raft_go_if.h" #include "raft_shm.h" #include "queue.h" extern "C" { #include "_cgo_export.h" } using namespace raft; using boost::interprocess::anonymous_instance; using boost::interprocess::unique_instance; namespace { zlog_category_t* go_cat; void run_worker(); void take_call(); #define api_call(name, arg_t, has_ret) \ void dispatch_ ## name(api::name::slot_t& slot); #include "raft_api_calls.h" #undef api_call std::vector<std::thread> workers; } void raft_ready() { uint32_t n_workers = raft::scoreboard->config.api_workers; if (n_workers == 0) { zlog_warn(go_cat, "Must run more than 0 API workers, defaulting to 4."); n_workers = 4; } workers.reserve(n_workers); for (uint32_t i = 0; i < n_workers; ++i) { workers.emplace_back(run_worker); } raft::scoreboard->is_raft_running = true; } namespace { void raft_reply_(BaseSlot& slot, RaftError error); void run_worker() { zlog_debug(go_cat, "Starting worker."); try { for (;;) { take_call(); } } catch (queue::queue_closed&) { zlog_debug(go_cat, "API queue closed, Go worker exiting."); return; } } void take_call() { auto rec = scoreboard->api_queue.take(); auto recv_ts = Timings::clock::now(); CallTag tag = rec.first; BaseSlot::pointer slot = rec.second; raft::mutex_lock l(slot->owned); slot->timings.record("call received", recv_ts); slot->timings.record("call locked"); zlog_debug(go_cat, "API call received, tag %d, call %p.", tag, slot.get()); assert(slot->state == raft::CallState::Pending); switch (tag) { #define api_call(name, arg_t, has_ret) \ case api::name::tag: \ dispatch_ ## name((api::name::slot_t&) *slot); \ break; #include "raft_api_calls.h" #undef api_call default: zlog_fatal(go_cat, "Unhandled call type: %d", tag); abort(); } //slot->state = raft::CallState::Dispatched; } uintptr_t shm_offset(void* ptr) { uintptr_t shm_base = (uintptr_t) shm.get_address(); uintptr_t shm_end = (uintptr_t) shm_base + shm.get_size(); uintptr_t address = (uintptr_t) ptr; assert(address >= shm_base && address < shm_end); return address - shm_base; } void dispatch_Apply(api::Apply::slot_t& slot) { assert(slot.tag == api::Apply::tag); size_t cmd_offset = shm_offset(slot.args.cmd_buf.get()); RaftApply(&slot, cmd_offset, slot.args.cmd_len, slot.args.timeout_ns); } void dispatch_Barrier(api::Barrier::slot_t& slot) { RaftBarrier(&slot, slot.args.timeout_ns); } void dispatch_VerifyLeader(api::VerifyLeader::slot_t& slot) { RaftVerifyLeader(&slot); } void dispatch_GetState(api::GetState::slot_t& slot) { RaftGetState(&slot); } void dispatch_LastContact(api::LastContact::slot_t& slot) { RaftLastContact(&slot); } void dispatch_LastIndex(api::LastIndex::slot_t& slot) { RaftLastIndex(&slot); } void dispatch_GetLeader(api::GetLeader::slot_t& slot) { RaftGetLeader(&slot); } void dispatch_Snapshot(api::Snapshot::slot_t& slot) { assert(slot.tag == CallTag::Snapshot); RaftSnapshot(&slot); } void dispatch_AddPeer(api::AddPeer::slot_t& slot) { assert(slot.tag == CallTag::AddPeer); RaftAddPeer(&slot, (char*) slot.args.host, slot.args.port); } void dispatch_RemovePeer(api::RemovePeer::slot_t& slot) { assert(slot.tag == CallTag::RemovePeer); RaftRemovePeer(&slot, (char*) slot.args.host, slot.args.port); } void dispatch_Shutdown(api::Shutdown::slot_t& slot) { assert(slot.tag == CallTag::Shutdown); slot.state = raft::CallState::Dispatched; RaftShutdown(&slot); } } void raft_reply(raft_call call_p, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); raft_reply_(*slot, error); } void raft_reply_immed(raft_call call_p, RaftError error) { raft_reply_(*(BaseSlot*) call_p, error); } void raft_reply_apply(raft_call call_p, uint64_t retval, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); slot->timings.record("RaftApply return"); assert(slot->tag == CallTag::Apply); if (!error) { slot->reply(retval); } else { zlog_error(go_cat, "Sending error response from RaftApply: %d", error); slot->reply(error); } } namespace { /** * Send reply IFF we already hold the lock on slot! */ void raft_reply_(BaseSlot& slot, RaftError error) { slot.timings.record("Raft call return"); slot.reply(error); } } void raft_reply_value(raft_call call, uint64_t retval) { // TODO: check that this has a return value... auto* slot = (BaseSlot*) call; mutex_lock lock(slot->owned); slot->timings.record("Raft call return"); slot->reply(retval); } uint64_t raft_fsm_apply(uint64_t index, uint64_t term, RaftLogType type, char* cmd_buf, size_t cmd_len) { shm_handle cmd_handle; char* shm_buf = nullptr; if (in_shm_bounds(cmd_buf)) { cmd_handle = raft::shm.get_handle_from_address(cmd_buf); } else { shm_buf = (char*) raft::shm.allocate(cmd_len); assert(shm_buf); zlog_debug(go_cat, "Allocated %lu-byte buffer for log command at %p.", cmd_len, shm_buf); memcpy(shm_buf, cmd_buf, cmd_len); cmd_handle = raft::shm.get_handle_from_address(shm_buf); } auto* slot = send_fsm_request<api::FSMApply>(index, term, type, cmd_handle, cmd_len); slot->wait(); assert(slot->state == raft::CallState::Success); assert(slot->error == RAFT_SUCCESS); zlog_debug(go_cat, "FSM response %#" PRIx64 , slot->retval); if (shm_buf) shm.deallocate(shm_buf); //slot->timings.print(); //fprintf(stderr, "====================\n"); auto rv = slot->retval; slot->dispose(); return rv; } int raft_fsm_snapshot(char *path) { auto* slot = send_fsm_request<api::FSMSnapshot>(path); free(path); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } int raft_fsm_restore(char *path) { auto* slot = send_fsm_request<api::FSMRestore>(path); free(path); zlog_info(go_cat, "Sent restore request to FSM."); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } void raft_set_leader(bool val) { zlog_info(go_cat, "Leadership state change: %s", val ? "is leader" : "not leader"); raft::scoreboard->is_leader = val; } void* raft_shm_init(const char *shm_path) { raft::shm_init(shm_path, false, nullptr); free((void*) shm_path); go_cat = zlog_get_category("raft_go"); return raft::shm.get_address(); } size_t raft_shm_size() { return raft::shm.get_size(); } uint64_t raft_shm_string(const char *str, size_t len) { char* buf = (char*) raft::shm.allocate(len+1); assert(raft::in_shm_bounds((void*) buf)); memcpy(buf, str, len); free((void*) str); buf[len] = '\0'; return (uint64_t) raft::shm.get_handle_from_address(buf); } RaftConfig* raft_get_config() { return raft::shm.find<RaftConfig>(unique_instance).first; } <|endoftext|>
<commit_before>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "policy_container.h" using namespace org::xtreemfs::client; #include "org/xtreemfs/interfaces/exceptions.h" #ifdef _WIN32 #include "yield/platform/windows.h" #include <lm.h> #pragma comment( lib, "Netapi32.lib" ) #else #include "yieldfs.h" #include <errno.h> #include <unistd.h> #include <pwd.h> #define PWD_BUF_LEN 256 #include <grp.h> #define GRP_BUF_LEN 1024 #endif namespace org { namespace xtreemfs { namespace client { class PolicyContainerreaddirCallback : public YIELD::Volume::readdirCallback { public: PolicyContainerreaddirCallback( PolicyContainer& policy_container, const YIELD::Path& root_dir_path ) : policy_container( policy_container ), root_dir_path( root_dir_path ) { } // YIELD::Volume::readdirCallback bool operator()( const YIELD::Path& name, const YIELD::Stat& stbuf ) { std::string::size_type dll_pos = name.get_host_charset_path().find( SHLIBSUFFIX ); if ( dll_pos != std::string::npos && dll_pos != 0 && name.get_host_charset_path()[dll_pos-1] == '.' ) policy_container.loadPolicySharedLibrary( root_dir_path + name ); return true; } private: PolicyContainer& policy_container; YIELD::Path root_dir_path; }; }; }; }; PolicyContainer::PolicyContainer() { this->get_user_credentials_from_passwd = NULL; this->get_passwd_from_user_credentials = NULL; loadPolicySharedLibraries( "policies" ); loadPolicySharedLibraries( "lib" ); loadPolicySharedLibraries( YIELD::Path() ); } PolicyContainer::~PolicyContainer() { for ( std::vector<YIELD::SharedLibrary*>::iterator policy_shared_library_i = policy_shared_libraries.begin(); policy_shared_library_i != policy_shared_libraries.end(); policy_shared_library_i++ ) delete *policy_shared_library_i; for ( YIELD::STLHashMap<YIELD::STLHashMap<std::pair<int,int>*>*>::iterator i = user_credentials_to_passwd_cache.begin(); i != user_credentials_to_passwd_cache.end(); i++ ) { for ( YIELD::STLHashMap<std::pair<int,int>*>::iterator j = i->second->begin(); j != i->second->end(); j++ ) delete j->second; delete i->second; } for ( YIELD::STLHashMap<YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>*>::iterator i = passwd_to_user_credentials_cache.begin(); i != passwd_to_user_credentials_cache.end(); i++ ) { for ( YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>::iterator j = i->second->begin(); j != i->second->end(); j++ ) delete j->second; delete i->second; } } void PolicyContainer::loadPolicySharedLibraries( const YIELD::Path& policy_shared_libraries_dir_path ) { PolicyContainerreaddirCallback readdir_callback( *this, policy_shared_libraries_dir_path ); YIELD::Volume().readdir( policy_shared_libraries_dir_path, readdir_callback ); } void PolicyContainer::loadPolicySharedLibrary( const YIELD::Path& policy_shared_library_file_path ) { YIELD::SharedLibrary* policy_shared_library = YIELD::SharedLibrary::open( policy_shared_library_file_path ); if ( policy_shared_library ) { get_passwd_from_user_credentials_t get_passwd_from_user_credentials = ( get_passwd_from_user_credentials_t )policy_shared_library->getFunction( "get_passwd_from_user_credentials" ); if ( get_passwd_from_user_credentials ) this->get_passwd_from_user_credentials = get_passwd_from_user_credentials; get_user_credentials_from_passwd_t get_user_credentials_from_passwd = ( get_user_credentials_from_passwd_t )policy_shared_library->getFunction( "get_user_credentials_from_passwd" ); if ( get_user_credentials_from_passwd ) this->get_user_credentials_from_passwd = get_user_credentials_from_passwd; policy_shared_libraries.push_back( policy_shared_library ); } } void PolicyContainer::getCurrentUserCredentials( org::xtreemfs::interfaces::UserCredentials& out_user_credentials ) { #ifdef _WIN32 if ( get_user_credentials_from_passwd ) getUserCredentialsFrompasswd( -1, -1, out_user_credentials ); else { DWORD dwLevel = 1; LPWKSTA_USER_INFO_1 user_info = NULL; if ( NetWkstaUserGetInfo( NULL, dwLevel, (LPBYTE *)&user_info ) == NERR_Success ) { if ( user_info !=NULL ) { size_t username_wcslen = wcslen( user_info->wkui1_username ); size_t username_strlen = WideCharToMultiByte( GetACP(), 0, user_info->wkui1_username, username_wcslen, NULL, 0, 0, NULL ); char* user_id = new char[username_strlen+1]; WideCharToMultiByte( GetACP(), 0, user_info->wkui1_username, username_wcslen, user_id, username_strlen+1, 0, NULL ); out_user_credentials.set_user_id( user_id, username_strlen ); delete [] user_id; size_t logon_domain_wcslen = wcslen( user_info->wkui1_logon_domain ); size_t logon_domain_strlen = WideCharToMultiByte( GetACP(), 0, user_info->wkui1_logon_domain, logon_domain_wcslen, NULL, 0, 0, NULL ); char* group_id = new char[logon_domain_strlen+1]; WideCharToMultiByte( GetACP(), 0, user_info->wkui1_logon_domain, logon_domain_wcslen, group_id, logon_domain_strlen+1, 0, NULL ); std::string group_id_str( group_id, logon_domain_strlen ); delete [] group_id; org::xtreemfs::interfaces::StringSet group_ids; group_ids.push_back( group_id_str ); out_user_credentials.set_group_ids( group_ids ); NetApiBufferFree( user_info ); return; } } throw YIELD::PlatformException( ERROR_ACCESS_DENIED, "could not retrieve user_id and group_id" ); } #else // int caller_uid = yieldfs::FUSE::geteuid(); // if ( caller_uid < 0 ) caller_uid = ::geteuid(); // int caller_gid = yieldfs::FUSE::getegid(); // if ( caller_gid < 0 ) caller_gid = ::getegid(); int caller_uid = ::geteuid(); int caller_gid = ::getegid(); getUserCredentialsFrompasswd( caller_uid, caller_gid, out_user_credentials ); #endif } void PolicyContainer::getpasswdFromUserCredentials( const std::string& user_id, const std::string& group_id, int& out_uid, int& out_gid ) { out_uid = 0; out_gid = 0; uint32_t user_id_hash = YIELD::string_hash( user_id.c_str() ); uint32_t group_id_hash = YIELD::string_hash( group_id.c_str() ); YIELD::STLHashMap<std::pair<int, int>*>* user_id_to_passwd_cache = user_credentials_to_passwd_cache.find( group_id_hash ); if ( user_id_to_passwd_cache != NULL ) { std::pair<int,int>* passwd = user_id_to_passwd_cache->find( user_id_hash ); if ( passwd != NULL ) { out_uid = passwd->first; out_gid = passwd->second; return; } } if ( get_passwd_from_user_credentials ) { int get_passwd_from_user_credentials_ret = get_passwd_from_user_credentials( user_id.c_str(), group_id.c_str(), &out_uid, &out_gid ); if ( get_passwd_from_user_credentials_ret < 0 ) throw YIELD::PlatformException( get_passwd_from_user_credentials_ret * -1 ); } else { #ifdef _WIN32 YIELD::DebugBreak(); #else struct passwd pwd, *pwd_res; char pwd_buf[PWD_BUF_LEN]; int pwd_buf_len = sizeof( pwd_buf ); struct group grp, *grp_res; char grp_buf[GRP_BUF_LEN]; int grp_buf_len = sizeof( grp_buf ); if ( getpwnam_r( user_id.c_str(), &pwd, pwd_buf, pwd_buf_len, &pwd_res ) == 0 && pwd_res != NULL && getgrnam_r( group_id.c_str(), &grp, grp_buf, grp_buf_len, &grp_res ) == 0 && grp_res != NULL ) { out_uid = pwd_res->pw_uid; out_gid = grp_res->gr_gid; } else { // throw YIELD::PlatformException(); out_uid = 0; out_gid = 0; } #endif } if ( user_id_to_passwd_cache == NULL ) { user_id_to_passwd_cache = new YIELD::STLHashMap<std::pair<int,int>*>; user_credentials_to_passwd_cache.insert( group_id_hash, user_id_to_passwd_cache ); } user_id_to_passwd_cache->insert( user_id_hash, new std::pair<int,int>( out_uid, out_gid ) ); } void PolicyContainer::getUserCredentialsFrompasswd( int uid, int gid, org::xtreemfs::interfaces::UserCredentials& out_user_credentials ) { YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>* uid_to_user_credentials_cache = passwd_to_user_credentials_cache.find( static_cast<uint32_t>( gid ) ); if ( uid_to_user_credentials_cache != NULL ) { org::xtreemfs::interfaces::UserCredentials* user_credentials = uid_to_user_credentials_cache->find( static_cast<uint32_t>( uid ) ); if ( user_credentials != NULL ) { out_user_credentials = *user_credentials; return; } } if ( get_user_credentials_from_passwd ) { size_t user_id_len = 0, group_ids_len = 0; int get_user_credentials_from_passwd_ret = get_user_credentials_from_passwd( uid, gid, NULL, &user_id_len, NULL, &group_ids_len ); if ( get_user_credentials_from_passwd_ret >= 0 ) { if ( user_id_len > 0 && group_ids_len > 0 ) { char* user_id = new char[user_id_len]; char* group_ids = new char[group_ids_len]; get_user_credentials_from_passwd_ret = get_user_credentials_from_passwd( uid, gid, user_id, &user_id_len, group_ids, &group_ids_len ); if ( get_user_credentials_from_passwd_ret >= 0 ) { out_user_credentials.set_user_id( user_id ); char* group_ids_p = group_ids; org::xtreemfs::interfaces::StringSet group_ids_ss; while ( static_cast<size_t>( group_ids_p - group_ids ) < group_ids_len ) { group_ids_ss.push_back( group_ids_p ); group_ids_p += group_ids_ss.back().size() + 1; } out_user_credentials.set_group_ids( group_ids_ss ); } else throw YIELD::PlatformException( get_user_credentials_from_passwd_ret * -1 ); } } else throw YIELD::PlatformException( get_user_credentials_from_passwd_ret * -1 ); } else { #ifdef _WIN32 YIELD::DebugBreak(); #else struct passwd pwd, *pwd_res; char pwd_buf[PWD_BUF_LEN]; int pwd_buf_len = sizeof( pwd_buf ); struct group grp, *grp_res; char grp_buf[GRP_BUF_LEN]; int grp_buf_len = sizeof( grp_buf ); if ( getpwuid_r( uid, &pwd, pwd_buf, pwd_buf_len, &pwd_res ) == 0 && pwd_res != NULL && pwd_res->pw_name != NULL && getgrgid_r( gid, &grp, grp_buf, grp_buf_len, &grp_res ) == 0 && grp_res != NULL && grp_res->gr_name != NULL ) { out_user_credentials.set_user_id( pwd_res->pw_name ); out_user_credentials.set_group_ids( org::xtreemfs::interfaces::StringSet( grp_res->gr_name ) ); } else throw YIELD::PlatformException(); #endif } if ( uid_to_user_credentials_cache == NULL ) { uid_to_user_credentials_cache = new YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>; passwd_to_user_credentials_cache.insert( static_cast<uint32_t>( gid ), uid_to_user_credentials_cache ); } uid_to_user_credentials_cache->insert( static_cast<uint32_t>( uid ), new org::xtreemfs::interfaces::UserCredentials( out_user_credentials ) ); } <commit_msg>client: policy_container: fixed lookup of invalid uid/gid<commit_after>// Copyright 2009 Minor Gordon. // This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions). #include "policy_container.h" using namespace org::xtreemfs::client; #include "org/xtreemfs/interfaces/exceptions.h" #ifdef _WIN32 #include "yield/platform/windows.h" #include <lm.h> #pragma comment( lib, "Netapi32.lib" ) #else #include "yieldfs.h" #include <errno.h> #include <unistd.h> #include <pwd.h> #define PWD_BUF_LEN 256 #include <grp.h> #define GRP_BUF_LEN 1024 #endif namespace org { namespace xtreemfs { namespace client { class PolicyContainerreaddirCallback : public YIELD::Volume::readdirCallback { public: PolicyContainerreaddirCallback( PolicyContainer& policy_container, const YIELD::Path& root_dir_path ) : policy_container( policy_container ), root_dir_path( root_dir_path ) { } // YIELD::Volume::readdirCallback bool operator()( const YIELD::Path& name, const YIELD::Stat& stbuf ) { std::string::size_type dll_pos = name.get_host_charset_path().find( SHLIBSUFFIX ); if ( dll_pos != std::string::npos && dll_pos != 0 && name.get_host_charset_path()[dll_pos-1] == '.' ) policy_container.loadPolicySharedLibrary( root_dir_path + name ); return true; } private: PolicyContainer& policy_container; YIELD::Path root_dir_path; }; }; }; }; PolicyContainer::PolicyContainer() { this->get_user_credentials_from_passwd = NULL; this->get_passwd_from_user_credentials = NULL; loadPolicySharedLibraries( "policies" ); loadPolicySharedLibraries( "lib" ); loadPolicySharedLibraries( YIELD::Path() ); } PolicyContainer::~PolicyContainer() { for ( std::vector<YIELD::SharedLibrary*>::iterator policy_shared_library_i = policy_shared_libraries.begin(); policy_shared_library_i != policy_shared_libraries.end(); policy_shared_library_i++ ) delete *policy_shared_library_i; for ( YIELD::STLHashMap<YIELD::STLHashMap<std::pair<int,int>*>*>::iterator i = user_credentials_to_passwd_cache.begin(); i != user_credentials_to_passwd_cache.end(); i++ ) { for ( YIELD::STLHashMap<std::pair<int,int>*>::iterator j = i->second->begin(); j != i->second->end(); j++ ) delete j->second; delete i->second; } for ( YIELD::STLHashMap<YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>*>::iterator i = passwd_to_user_credentials_cache.begin(); i != passwd_to_user_credentials_cache.end(); i++ ) { for ( YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>::iterator j = i->second->begin(); j != i->second->end(); j++ ) delete j->second; delete i->second; } } void PolicyContainer::loadPolicySharedLibraries( const YIELD::Path& policy_shared_libraries_dir_path ) { PolicyContainerreaddirCallback readdir_callback( *this, policy_shared_libraries_dir_path ); YIELD::Volume().readdir( policy_shared_libraries_dir_path, readdir_callback ); } void PolicyContainer::loadPolicySharedLibrary( const YIELD::Path& policy_shared_library_file_path ) { YIELD::SharedLibrary* policy_shared_library = YIELD::SharedLibrary::open( policy_shared_library_file_path ); if ( policy_shared_library ) { get_passwd_from_user_credentials_t get_passwd_from_user_credentials = ( get_passwd_from_user_credentials_t )policy_shared_library->getFunction( "get_passwd_from_user_credentials" ); if ( get_passwd_from_user_credentials ) this->get_passwd_from_user_credentials = get_passwd_from_user_credentials; get_user_credentials_from_passwd_t get_user_credentials_from_passwd = ( get_user_credentials_from_passwd_t )policy_shared_library->getFunction( "get_user_credentials_from_passwd" ); if ( get_user_credentials_from_passwd ) this->get_user_credentials_from_passwd = get_user_credentials_from_passwd; policy_shared_libraries.push_back( policy_shared_library ); } } void PolicyContainer::getCurrentUserCredentials( org::xtreemfs::interfaces::UserCredentials& out_user_credentials ) { #ifdef _WIN32 if ( get_user_credentials_from_passwd ) getUserCredentialsFrompasswd( -1, -1, out_user_credentials ); else { DWORD dwLevel = 1; LPWKSTA_USER_INFO_1 user_info = NULL; if ( NetWkstaUserGetInfo( NULL, dwLevel, (LPBYTE *)&user_info ) == NERR_Success ) { if ( user_info !=NULL ) { size_t username_wcslen = wcslen( user_info->wkui1_username ); size_t username_strlen = WideCharToMultiByte( GetACP(), 0, user_info->wkui1_username, username_wcslen, NULL, 0, 0, NULL ); char* user_id = new char[username_strlen+1]; WideCharToMultiByte( GetACP(), 0, user_info->wkui1_username, username_wcslen, user_id, username_strlen+1, 0, NULL ); out_user_credentials.set_user_id( user_id, username_strlen ); delete [] user_id; size_t logon_domain_wcslen = wcslen( user_info->wkui1_logon_domain ); size_t logon_domain_strlen = WideCharToMultiByte( GetACP(), 0, user_info->wkui1_logon_domain, logon_domain_wcslen, NULL, 0, 0, NULL ); char* group_id = new char[logon_domain_strlen+1]; WideCharToMultiByte( GetACP(), 0, user_info->wkui1_logon_domain, logon_domain_wcslen, group_id, logon_domain_strlen+1, 0, NULL ); std::string group_id_str( group_id, logon_domain_strlen ); delete [] group_id; org::xtreemfs::interfaces::StringSet group_ids; group_ids.push_back( group_id_str ); out_user_credentials.set_group_ids( group_ids ); NetApiBufferFree( user_info ); return; } } throw YIELD::PlatformException( ERROR_ACCESS_DENIED, "could not retrieve user_id and group_id" ); } #else // int caller_uid = yieldfs::FUSE::geteuid(); // if ( caller_uid < 0 ) caller_uid = ::geteuid(); // int caller_gid = yieldfs::FUSE::getegid(); // if ( caller_gid < 0 ) caller_gid = ::getegid(); int caller_uid = ::geteuid(); int caller_gid = ::getegid(); getUserCredentialsFrompasswd( caller_uid, caller_gid, out_user_credentials ); #endif } void PolicyContainer::getpasswdFromUserCredentials( const std::string& user_id, const std::string& group_id, int& out_uid, int& out_gid ) { out_uid = 0; out_gid = 0; uint32_t user_id_hash = YIELD::string_hash( user_id.c_str() ); uint32_t group_id_hash = YIELD::string_hash( group_id.c_str() ); YIELD::STLHashMap<std::pair<int, int>*>* user_id_to_passwd_cache = user_credentials_to_passwd_cache.find( group_id_hash ); if ( user_id_to_passwd_cache != NULL ) { std::pair<int,int>* passwd = user_id_to_passwd_cache->find( user_id_hash ); if ( passwd != NULL ) { out_uid = passwd->first; out_gid = passwd->second; return; } } if ( get_passwd_from_user_credentials ) { int get_passwd_from_user_credentials_ret = get_passwd_from_user_credentials( user_id.c_str(), group_id.c_str(), &out_uid, &out_gid ); if ( get_passwd_from_user_credentials_ret < 0 ) throw YIELD::PlatformException( get_passwd_from_user_credentials_ret * -1 ); } else { #ifdef _WIN32 YIELD::DebugBreak(); #else struct passwd pwd, *pwd_res; char pwd_buf[PWD_BUF_LEN]; int pwd_buf_len = sizeof( pwd_buf ); struct group grp, *grp_res; char grp_buf[GRP_BUF_LEN]; int grp_buf_len = sizeof( grp_buf ); if ( getpwnam_r( user_id.c_str(), &pwd, pwd_buf, pwd_buf_len, &pwd_res ) == 0 && pwd_res != NULL && getgrnam_r( group_id.c_str(), &grp, grp_buf, grp_buf_len, &grp_res ) == 0 && grp_res != NULL ) { out_uid = pwd_res->pw_uid; out_gid = grp_res->gr_gid; } else { // throw YIELD::PlatformException(); out_uid = 0; out_gid = 0; } #endif } if ( user_id_to_passwd_cache == NULL ) { user_id_to_passwd_cache = new YIELD::STLHashMap<std::pair<int,int>*>; user_credentials_to_passwd_cache.insert( group_id_hash, user_id_to_passwd_cache ); } user_id_to_passwd_cache->insert( user_id_hash, new std::pair<int,int>( out_uid, out_gid ) ); } void PolicyContainer::getUserCredentialsFrompasswd( int uid, int gid, org::xtreemfs::interfaces::UserCredentials& out_user_credentials ) { YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>* uid_to_user_credentials_cache = passwd_to_user_credentials_cache.find( static_cast<uint32_t>( gid ) ); if ( uid_to_user_credentials_cache != NULL ) { org::xtreemfs::interfaces::UserCredentials* user_credentials = uid_to_user_credentials_cache->find( static_cast<uint32_t>( uid ) ); if ( user_credentials != NULL ) { out_user_credentials = *user_credentials; return; } } if ( get_user_credentials_from_passwd ) { size_t user_id_len = 0, group_ids_len = 0; int get_user_credentials_from_passwd_ret = get_user_credentials_from_passwd( uid, gid, NULL, &user_id_len, NULL, &group_ids_len ); if ( get_user_credentials_from_passwd_ret >= 0 ) { if ( user_id_len > 0 && group_ids_len > 0 ) { char* user_id = new char[user_id_len]; char* group_ids = new char[group_ids_len]; get_user_credentials_from_passwd_ret = get_user_credentials_from_passwd( uid, gid, user_id, &user_id_len, group_ids, &group_ids_len ); if ( get_user_credentials_from_passwd_ret >= 0 ) { out_user_credentials.set_user_id( user_id ); char* group_ids_p = group_ids; org::xtreemfs::interfaces::StringSet group_ids_ss; while ( static_cast<size_t>( group_ids_p - group_ids ) < group_ids_len ) { group_ids_ss.push_back( group_ids_p ); group_ids_p += group_ids_ss.back().size() + 1; } out_user_credentials.set_group_ids( group_ids_ss ); } else throw YIELD::PlatformException( get_user_credentials_from_passwd_ret * -1 ); } } else throw YIELD::PlatformException( get_user_credentials_from_passwd_ret * -1 ); } else { #ifdef _WIN32 YIELD::DebugBreak(); #else struct passwd pwd, *pwd_res; char pwd_buf[PWD_BUF_LEN]; int pwd_buf_len = sizeof( pwd_buf ); struct group grp, *grp_res; char grp_buf[GRP_BUF_LEN]; int grp_buf_len = sizeof( grp_buf ); if ( getpwuid_r( uid, &pwd, pwd_buf, pwd_buf_len, &pwd_res ) == 0 ) { if ( pwd_res != NULL && pwd_res->pw_name != NULL ) { if ( getgrgid_r( gid, &grp, grp_buf, grp_buf_len, &grp_res ) == 0 ) { if ( grp_res != NULL && grp_res->gr_name != NULL ) { out_user_credentials.set_user_id( pwd_res->pw_name ); out_user_credentials.set_group_ids( org::xtreemfs::interfaces::StringSet( grp_res->gr_name ) ); } else throw YIELD::PlatformException( EINVAL, "no such gid" ); } else throw YIELD::PlatformException(); } else throw YIELD::PlatformException( EINVAL, "no such uid" ); } else throw YIELD::PlatformException(); #endif } if ( uid_to_user_credentials_cache == NULL ) { uid_to_user_credentials_cache = new YIELD::STLHashMap<org::xtreemfs::interfaces::UserCredentials*>; passwd_to_user_credentials_cache.insert( static_cast<uint32_t>( gid ), uid_to_user_credentials_cache ); } uid_to_user_credentials_cache->insert( static_cast<uint32_t>( uid ), new org::xtreemfs::interfaces::UserCredentials( out_user_credentials ) ); } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * DataManReader.cpp * * Created on: Feb 21, 2017 * Author: Jason Wang */ #include "DataManReader.tcc" #include "adios2/helper/adiosString.h" namespace adios2 { namespace core { namespace engine { DataManReader::DataManReader(IO &io, const std::string &name, const Mode openMode, helper::Comm comm) : Engine("DataManReader", io, name, openMode, std::move(comm)), m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)), m_RequesterThreadActive(true), m_SubscriberThreadActive(true), m_FinalStep(std::numeric_limits<size_t>::max()) { m_MpiRank = m_Comm.Rank(); m_MpiSize = m_Comm.Size(); helper::GetParameter(m_IO.m_Parameters, "IPAddress", m_IPAddress); helper::GetParameter(m_IO.m_Parameters, "Port", m_Port); helper::GetParameter(m_IO.m_Parameters, "Timeout", m_Timeout); helper::GetParameter(m_IO.m_Parameters, "Verbose", m_Verbosity); helper::GetParameter(m_IO.m_Parameters, "Threading", m_Threading); helper::GetParameter(m_IO.m_Parameters, "Monitor", m_MonitorActive); helper::GetParameter(m_IO.m_Parameters, "MaxStepBufferSize", m_ReceiverBufferSize); if (m_IPAddress.empty()) { throw(std::invalid_argument( "IP address not specified in wide area staging")); } std::string requesterAddress = "tcp://" + m_IPAddress + ":" + std::to_string(m_Port); std::string subscriberAddress = "tcp://" + m_IPAddress + ":" + std::to_string(m_Port + 1); m_Requester.OpenRequester(requesterAddress, m_Timeout, m_ReceiverBufferSize); auto timeBeforeRequest = std::chrono::system_clock::now(); auto reply = m_Requester.Request("Handshake", 9); auto timeAfterRequest = std::chrono::system_clock::now(); auto roundLatency = std::chrono::duration_cast<std::chrono::milliseconds>( timeAfterRequest - timeBeforeRequest) .count(); auto startTime = std::chrono::system_clock::now(); while (reply == nullptr or reply->empty()) { reply = m_Requester.Request("Handshake", 9); auto nowTime = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>( nowTime - startTime); roundLatency = duration.count() * 1000; if (duration.count() > m_Timeout) { m_InitFailed = true; return; } } nlohmann::json message = nlohmann::json::parse(reply->data()); m_TransportMode = message["Transport"]; if (m_MonitorActive) { m_Monitor.SetClockError(roundLatency, message["TimeStamp"]); m_Monitor.AddTransport(m_TransportMode); if (m_Threading) { m_Monitor.SetReaderThreading(); } bool writerThreading = message["Threading"]; if (writerThreading) { m_Monitor.SetWriterThreading(); } m_Monitor.SetRequiredAccuracy( stof(message["FloatAccuracy"].get<std::string>())); } if (m_TransportMode == "fast") { m_Subscriber.OpenSubscriber(subscriberAddress, m_ReceiverBufferSize); m_SubscriberThread = std::thread(&DataManReader::SubscribeThread, this); } else if (m_TransportMode == "reliable") { } else { throw(std::invalid_argument("unknown transport mode")); } m_Requester.Request("Ready", 5); if (m_TransportMode == "reliable") { m_RequesterThread = std::thread(&DataManReader::RequestThread, this); } } DataManReader::~DataManReader() { if (not m_IsClosed) { DoClose(); } if (m_Verbosity >= 5) { std::cout << "DataManReader::~DataManReader() Rank " << m_MpiRank << ", Step " << m_CurrentStep << std::endl; } } StepStatus DataManReader::BeginStep(StepMode stepMode, const float timeoutSeconds) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() begin, Rank " << m_MpiRank << ", Step " << m_CurrentStep << std::endl; } float timeout = timeoutSeconds; if (timeout <= 0) { timeout = m_Timeout; } if (m_InitFailed) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep(), Rank " << m_MpiRank << " returned EndOfStream due " "to initialization failure" << std::endl; } return StepStatus::EndOfStream; } if (m_CurrentStep >= m_FinalStep and m_CurrentStep >= 0) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank << " returned EndOfStream, " "final step is " << m_FinalStep << std::endl; } return StepStatus::EndOfStream; } m_CurrentStepMetadata = m_Serializer.GetEarliestLatestStep(m_CurrentStep, 1, timeout, false); if (m_CurrentStepMetadata == nullptr) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank << " returned EndOfStream due " "to timeout" << std::endl; } return StepStatus::EndOfStream; } m_Serializer.GetAttributes(m_IO); for (const auto &i : *m_CurrentStepMetadata) { if (i.step == m_CurrentStep) { if (i.type == DataType::None) { throw("unknown data type"); } #define declare_type(T) \ else if (i.type == helper::GetDataType<T>()) \ { \ CheckIOVariable<T>(i.name, i.shape, i.start, i.count); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type else { throw("unknown data type"); } } } if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() end, Rank " << m_MpiRank << ", Step " << m_CurrentStep << std::endl; } if (m_MonitorActive) { m_Monitor.BeginStep(m_CurrentStep); } return StepStatus::OK; } size_t DataManReader::CurrentStep() const { return m_CurrentStep; } void DataManReader::PerformGets() {} void DataManReader::EndStep() { m_Serializer.Erase(m_CurrentStep, true); m_CurrentStepMetadata = nullptr; if (m_MonitorActive) { auto comMap = m_Serializer.GetOperatorMap(); for (const auto &i : comMap) { std::string method, accuracy; auto it = i.second.find("accuracy"); if (it != i.second.end()) { accuracy = it->second; } it = i.second.find("method"); if (it != i.second.end()) { method = it->second; } m_Monitor.AddCompression(method, std::stof(accuracy)); } m_Monitor.EndStep(m_CurrentStep); } } void DataManReader::Flush(const int transportIndex) {} // PRIVATE void DataManReader::RequestThread() { while (m_RequesterThreadActive) { std::string request = "Step"; auto buffer = m_Requester.Request(request.data(), request.size()); if (buffer != nullptr && buffer->size() > 0) { if (buffer->size() < 64) { try { auto jmsg = nlohmann::json::parse(buffer->data()); m_FinalStep = jmsg["FinalStep"].get<size_t>(); return; } catch (...) { } } m_Serializer.PutPack(buffer, m_Threading); if (m_MonitorActive) { size_t combiningSteps = m_Serializer.GetCombiningSteps(); if (combiningSteps < 20) { m_Monitor.SetAverageSteps(40); } else { m_Monitor.SetAverageSteps(combiningSteps * 2); } auto timeStamps = m_Serializer.GetTimeStamps(); for (const auto &timeStamp : timeStamps) { m_Monitor.AddLatencyMilliseconds(timeStamp); } } } } } void DataManReader::SubscribeThread() { while (m_SubscriberThreadActive) { auto buffer = m_Subscriber.Receive(); if (buffer != nullptr && buffer->size() > 0) { if (buffer->size() < 64) { try { auto jmsg = nlohmann::json::parse(buffer->data()); m_FinalStep = jmsg["FinalStep"].get<size_t>(); continue; } catch (...) { } } m_Serializer.PutPack(buffer, m_Threading); if (m_MonitorActive) { size_t combiningSteps = m_Serializer.GetCombiningSteps(); if (combiningSteps < 20) { m_Monitor.SetAverageSteps(40); } else { m_Monitor.SetAverageSteps(combiningSteps * 2); } auto timeStamps = m_Serializer.GetTimeStamps(); for (const auto &timeStamp : timeStamps) { m_Monitor.AddLatencyMilliseconds(timeStamp); } } } } } #define declare_type(T) \ void DataManReader::DoGetSync(Variable<T> &variable, T *data) \ { \ GetSyncCommon(variable, data); \ } \ void DataManReader::DoGetDeferred(Variable<T> &variable, T *data) \ { \ GetDeferredCommon(variable, data); \ } \ std::map<size_t, std::vector<typename Variable<T>::Info>> \ DataManReader::DoAllStepsBlocksInfo(const Variable<T> &variable) const \ { \ return AllStepsBlocksInfoCommon(variable); \ } \ std::vector<typename Variable<T>::Info> DataManReader::DoBlocksInfo( \ const Variable<T> &variable, const size_t step) const \ { \ return BlocksInfoCommon(variable, step); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type void DataManReader::DoClose(const int transportIndex) { m_SubscriberThreadActive = false; m_RequesterThreadActive = false; if (m_SubscriberThread.joinable()) { m_SubscriberThread.join(); } if (m_RequesterThread.joinable()) { m_RequesterThread.join(); } m_IsClosed = true; if (m_MonitorActive) { m_Monitor.OutputJson(m_Name); } } } // end namespace engine } // end namespace core } // end namespace adios2 <commit_msg>added checking for json value<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * DataManReader.cpp * * Created on: Feb 21, 2017 * Author: Jason Wang */ #include "DataManReader.tcc" #include "adios2/helper/adiosString.h" namespace adios2 { namespace core { namespace engine { DataManReader::DataManReader(IO &io, const std::string &name, const Mode openMode, helper::Comm comm) : Engine("DataManReader", io, name, openMode, std::move(comm)), m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)), m_RequesterThreadActive(true), m_SubscriberThreadActive(true), m_FinalStep(std::numeric_limits<size_t>::max()) { m_MpiRank = m_Comm.Rank(); m_MpiSize = m_Comm.Size(); helper::GetParameter(m_IO.m_Parameters, "IPAddress", m_IPAddress); helper::GetParameter(m_IO.m_Parameters, "Port", m_Port); helper::GetParameter(m_IO.m_Parameters, "Timeout", m_Timeout); helper::GetParameter(m_IO.m_Parameters, "Verbose", m_Verbosity); helper::GetParameter(m_IO.m_Parameters, "Threading", m_Threading); helper::GetParameter(m_IO.m_Parameters, "Monitor", m_MonitorActive); helper::GetParameter(m_IO.m_Parameters, "MaxStepBufferSize", m_ReceiverBufferSize); if (m_IPAddress.empty()) { throw(std::invalid_argument( "IP address not specified in wide area staging")); } std::string requesterAddress = "tcp://" + m_IPAddress + ":" + std::to_string(m_Port); std::string subscriberAddress = "tcp://" + m_IPAddress + ":" + std::to_string(m_Port + 1); m_Requester.OpenRequester(requesterAddress, m_Timeout, m_ReceiverBufferSize); auto timeBeforeRequest = std::chrono::system_clock::now(); auto reply = m_Requester.Request("Handshake", 9); auto timeAfterRequest = std::chrono::system_clock::now(); auto roundLatency = std::chrono::duration_cast<std::chrono::milliseconds>( timeAfterRequest - timeBeforeRequest) .count(); auto startTime = std::chrono::system_clock::now(); while (reply == nullptr or reply->empty()) { reply = m_Requester.Request("Handshake", 9); auto nowTime = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>( nowTime - startTime); roundLatency = duration.count() * 1000; if (duration.count() > m_Timeout) { m_InitFailed = true; return; } } nlohmann::json message = nlohmann::json::parse(reply->data()); m_TransportMode = message["Transport"]; if (m_MonitorActive) { m_Monitor.SetClockError(roundLatency, message["TimeStamp"]); m_Monitor.AddTransport(m_TransportMode); if (m_Threading) { m_Monitor.SetReaderThreading(); } bool writerThreading = message["Threading"]; if (writerThreading) { m_Monitor.SetWriterThreading(); } auto it = message.find("FloatAccuracy"); if (it != message.end() && !it->get<std::string>().empty()) { m_Monitor.SetRequiredAccuracy(stof(it->get<std::string>())); } } if (m_TransportMode == "fast") { m_Subscriber.OpenSubscriber(subscriberAddress, m_ReceiverBufferSize); m_SubscriberThread = std::thread(&DataManReader::SubscribeThread, this); } else if (m_TransportMode == "reliable") { } else { throw(std::invalid_argument("unknown transport mode")); } m_Requester.Request("Ready", 5); if (m_TransportMode == "reliable") { m_RequesterThread = std::thread(&DataManReader::RequestThread, this); } } DataManReader::~DataManReader() { if (not m_IsClosed) { DoClose(); } if (m_Verbosity >= 5) { std::cout << "DataManReader::~DataManReader() Rank " << m_MpiRank << ", Step " << m_CurrentStep << std::endl; } } StepStatus DataManReader::BeginStep(StepMode stepMode, const float timeoutSeconds) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() begin, Rank " << m_MpiRank << ", Step " << m_CurrentStep << std::endl; } float timeout = timeoutSeconds; if (timeout <= 0) { timeout = m_Timeout; } if (m_InitFailed) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep(), Rank " << m_MpiRank << " returned EndOfStream due " "to initialization failure" << std::endl; } return StepStatus::EndOfStream; } if (m_CurrentStep >= m_FinalStep and m_CurrentStep >= 0) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank << " returned EndOfStream, " "final step is " << m_FinalStep << std::endl; } return StepStatus::EndOfStream; } m_CurrentStepMetadata = m_Serializer.GetEarliestLatestStep(m_CurrentStep, 1, timeout, false); if (m_CurrentStepMetadata == nullptr) { if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() Rank " << m_MpiRank << " returned EndOfStream due " "to timeout" << std::endl; } return StepStatus::EndOfStream; } m_Serializer.GetAttributes(m_IO); for (const auto &i : *m_CurrentStepMetadata) { if (i.step == m_CurrentStep) { if (i.type == DataType::None) { throw("unknown data type"); } #define declare_type(T) \ else if (i.type == helper::GetDataType<T>()) \ { \ CheckIOVariable<T>(i.name, i.shape, i.start, i.count); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type else { throw("unknown data type"); } } } if (m_Verbosity >= 5) { std::cout << "DataManReader::BeginStep() end, Rank " << m_MpiRank << ", Step " << m_CurrentStep << std::endl; } if (m_MonitorActive) { m_Monitor.BeginStep(m_CurrentStep); } return StepStatus::OK; } size_t DataManReader::CurrentStep() const { return m_CurrentStep; } void DataManReader::PerformGets() {} void DataManReader::EndStep() { m_Serializer.Erase(m_CurrentStep, true); m_CurrentStepMetadata = nullptr; if (m_MonitorActive) { auto comMap = m_Serializer.GetOperatorMap(); for (const auto &i : comMap) { std::string method, accuracy; auto it = i.second.find("accuracy"); if (it != i.second.end()) { accuracy = it->second; } it = i.second.find("method"); if (it != i.second.end()) { method = it->second; } m_Monitor.AddCompression(method, std::stof(accuracy)); } m_Monitor.EndStep(m_CurrentStep); } } void DataManReader::Flush(const int transportIndex) {} // PRIVATE void DataManReader::RequestThread() { while (m_RequesterThreadActive) { std::string request = "Step"; auto buffer = m_Requester.Request(request.data(), request.size()); if (buffer != nullptr && buffer->size() > 0) { if (buffer->size() < 64) { try { auto jmsg = nlohmann::json::parse(buffer->data()); m_FinalStep = jmsg["FinalStep"].get<size_t>(); return; } catch (...) { } } m_Serializer.PutPack(buffer, m_Threading); if (m_MonitorActive) { size_t combiningSteps = m_Serializer.GetCombiningSteps(); if (combiningSteps < 20) { m_Monitor.SetAverageSteps(40); } else { m_Monitor.SetAverageSteps(combiningSteps * 2); } auto timeStamps = m_Serializer.GetTimeStamps(); for (const auto &timeStamp : timeStamps) { m_Monitor.AddLatencyMilliseconds(timeStamp); } } } } } void DataManReader::SubscribeThread() { while (m_SubscriberThreadActive) { auto buffer = m_Subscriber.Receive(); if (buffer != nullptr && buffer->size() > 0) { if (buffer->size() < 64) { try { auto jmsg = nlohmann::json::parse(buffer->data()); m_FinalStep = jmsg["FinalStep"].get<size_t>(); continue; } catch (...) { } } m_Serializer.PutPack(buffer, m_Threading); if (m_MonitorActive) { size_t combiningSteps = m_Serializer.GetCombiningSteps(); if (combiningSteps < 20) { m_Monitor.SetAverageSteps(40); } else { m_Monitor.SetAverageSteps(combiningSteps * 2); } auto timeStamps = m_Serializer.GetTimeStamps(); for (const auto &timeStamp : timeStamps) { m_Monitor.AddLatencyMilliseconds(timeStamp); } } } } } #define declare_type(T) \ void DataManReader::DoGetSync(Variable<T> &variable, T *data) \ { \ GetSyncCommon(variable, data); \ } \ void DataManReader::DoGetDeferred(Variable<T> &variable, T *data) \ { \ GetDeferredCommon(variable, data); \ } \ std::map<size_t, std::vector<typename Variable<T>::Info>> \ DataManReader::DoAllStepsBlocksInfo(const Variable<T> &variable) const \ { \ return AllStepsBlocksInfoCommon(variable); \ } \ std::vector<typename Variable<T>::Info> DataManReader::DoBlocksInfo( \ const Variable<T> &variable, const size_t step) const \ { \ return BlocksInfoCommon(variable, step); \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type void DataManReader::DoClose(const int transportIndex) { m_SubscriberThreadActive = false; m_RequesterThreadActive = false; if (m_SubscriberThread.joinable()) { m_SubscriberThread.join(); } if (m_RequesterThread.joinable()) { m_RequesterThread.join(); } m_IsClosed = true; if (m_MonitorActive) { m_Monitor.OutputJson(m_Name); } } } // end namespace engine } // end namespace core } // end namespace adios2 <|endoftext|>
<commit_before>#include "PrimaryTreeIndex.h" void PrimaryTreeIndex::buildIndex(Table & table, int column) { int rowno = 0; for(auto &currentRow : table) { index.emplace(currentRow[column], rowno++); } } int PrimaryTreeIndex::size() const { return index.size(); } int PrimaryTreeIndex::lookup(const std::string& key) { auto bounds = index.equal_range(key); auto lower_bound = bounds.first; if(lower_bound->first == key) { return lower_bound->second; } } <commit_msg>Added Exact and Best match logic<commit_after>#include "PrimaryTreeIndex.h" void PrimaryTreeIndex::buildIndex(Table & table, int column) { int rowno = 0; for(auto &currentRow : table) { index.emplace(currentRow[column], rowno++); } } int PrimaryTreeIndex::size() const { return index.size(); } int PrimaryTreeIndex::lookup(const std::string& key) { auto bounds = index.equal_range(key); auto lower_bound = bounds.first; auto upper_bound = bounds.second; if(lower_bound == index.end()) { std::map<std::string,int>::const_reverse_iterator rbegin(upper_bound); std::map<std::string,int>::const_reverse_iterator rend(index.begin()); for(auto it = rbegin; it!=rend; it++) { auto idx = key.find(it->first); if(idx != std::string::npos) { return it->second; } } } if(lower_bound->first == key) { return lower_bound->second; } } <|endoftext|>
<commit_before>#include "./qimage_drawer.h" #include <QPainter> #include <vector> namespace Graphics { QImageDrawer::QImageDrawer(int width, int height) { image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8); } void drawPolygon(QPainter &painter, std::vector<QPointF> &points) { if (points.size() < 3) return; QPointF triangle[3]; triangle[0] = points[0]; for (size_t i = 2; i < points.size(); ++i) { triangle[1] = points[i - 1]; triangle[2] = points[i]; painter.drawConvexPolygon(triangle, 3); } points.clear(); } void QImageDrawer::drawElementVector(std::vector<float> positions, float color) { QPainter painter; painter.begin(image.get()); QColor brushColor = QColor::fromRgbF(color, color, color, color); painter.setBrush(QBrush(brushColor)); painter.setPen(color); std::vector<QPointF> points; size_t i = 0; if (positions[0] == positions[2] && positions[1] == positions[3]) i = 1; for (; i < positions.size() / 2; ++i) { float x = positions[i * 2]; float y = image->height() - positions[i * 2 + 1]; if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] && y == positions[i * 2 + 3]) { drawPolygon(painter, points); points.clear(); i += 2; } points.push_back(QPointF(x, y)); } drawPolygon(painter, points); painter.end(); } void QImageDrawer::clear() { image->fill(Qt::GlobalColor::black); } } // namespace Graphics <commit_msg>Fix pen color in QImageDrawer.<commit_after>#include "./qimage_drawer.h" #include <QPainter> #include <vector> namespace Graphics { QImageDrawer::QImageDrawer(int width, int height) { image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8); } void drawPolygon(QPainter &painter, std::vector<QPointF> &points) { if (points.size() < 3) return; QPointF triangle[3]; triangle[0] = points[0]; for (size_t i = 2; i < points.size(); ++i) { triangle[1] = points[i - 1]; triangle[2] = points[i]; painter.drawConvexPolygon(triangle, 3); } points.clear(); } void QImageDrawer::drawElementVector(std::vector<float> positions, float color) { QPainter painter; painter.begin(image.get()); QColor brushColor = QColor::fromRgbF(color, color, color, color); painter.setBrush(QBrush(brushColor)); painter.setPen(brushColor); std::vector<QPointF> points; size_t i = 0; if (positions[0] == positions[2] && positions[1] == positions[3]) i = 1; for (; i < positions.size() / 2; ++i) { float x = positions[i * 2]; float y = image->height() - positions[i * 2 + 1]; if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] && y == positions[i * 2 + 3]) { drawPolygon(painter, points); points.clear(); i += 2; } points.push_back(QPointF(x, y)); } drawPolygon(painter, points); painter.end(); } void QImageDrawer::clear() { image->fill(Qt::GlobalColor::black); } } // namespace Graphics <|endoftext|>
<commit_before>#include "./qimage_drawer.h" #include <QPainter> #include <vector> namespace Graphics { QImageDrawer::QImageDrawer(int width, int height) { image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8); } void QImageDrawer::drawElementVector(std::vector<float> positions) { QPainter painter; painter.begin(image.get()); painter.setBrush(QBrush(Qt::GlobalColor::white)); painter.setPen(Qt::GlobalColor::white); std::vector<QPointF> points; size_t i = 0; if (positions[0] == positions[2] && positions[1] == positions[3]) i = 1; for (; i < positions.size() / 2; ++i) { float x = positions[i * 2]; float y = positions[i * 2 + 1]; if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] && y == positions[i * 2 + 3]) { painter.drawConvexPolygon(points.data(), points.size()); points.clear(); i += 2; } points.push_back(QPointF(x, y)); } painter.drawConvexPolygon(points.data(), points.size()); painter.end(); } void QImageDrawer::clear() { image->fill(Qt::GlobalColor::black); } } // namespace Graphics <commit_msg>Invert y in QImageDrawer to fix Labeller test.<commit_after>#include "./qimage_drawer.h" #include <QPainter> #include <vector> namespace Graphics { QImageDrawer::QImageDrawer(int width, int height) { image = std::make_shared<QImage>(width, height, QImage::Format_Grayscale8); } void QImageDrawer::drawElementVector(std::vector<float> positions) { QPainter painter; painter.begin(image.get()); painter.setBrush(QBrush(Qt::GlobalColor::white)); painter.setPen(Qt::GlobalColor::white); std::vector<QPointF> points; size_t i = 0; if (positions[0] == positions[2] && positions[1] == positions[3]) i = 1; for (; i < positions.size() / 2; ++i) { float x = positions[i * 2]; float y = image->height() - positions[i * 2 + 1]; if (i * 2 + 3 < positions.size() && x == positions[i * 2 + 2] && y == positions[i * 2 + 3]) { painter.drawConvexPolygon(points.data(), points.size()); points.clear(); i += 2; } points.push_back(QPointF(x, y)); } painter.drawConvexPolygon(points.data(), points.size()); painter.end(); } void QImageDrawer::clear() { image->fill(Qt::GlobalColor::black); } } // namespace Graphics <|endoftext|>
<commit_before>#pragma once #include "LevelList.hpp" #include "GridMap.hpp" #include "../tools/Overlap.hpp" namespace maps { namespace grid { template <class P> class MultiLevelGridMap : public GridMap<LevelList<P> > { public: typedef LevelList<P> CellType; MultiLevelGridMap(const Vector2ui &num_cells, const Eigen::Vector2d &resolution, const boost::shared_ptr<LocalMapData> &data) : GridMap<LevelList<P> >(num_cells, resolution, LevelList<P>(), data) {} MultiLevelGridMap(const Vector2ui &num_cells, const Eigen::Vector2d &resolution) : GridMap<LevelList<P> >(num_cells, resolution, LevelList<P>()) {} MultiLevelGridMap() {} class View : public GridMap<LevelList<const P *> > { public: View(const Vector2ui &num_cells, const Eigen::Vector2d &resolution) : GridMap<LevelList<const P *> >(num_cells, resolution, LevelList<const P *>()) { }; View() : GridMap<LevelList<const P *> >() { }; }; View intersectCuboid(const Eigen::AlignedBox3d& box) const { double minHeight = box.min().z(); double maxHeight = box.max().z(); Index minIdx; Index maxIdx; if(!this->toGrid(box.min(), minIdx)) { return View(); } if(!this->toGrid(box.max(), maxIdx)) { return View(); } Index newSize(maxIdx-minIdx); View ret(Vector2ui(newSize.x(), newSize.y()) , this->getResolution()); for(size_t x = minIdx.x();x < maxIdx.x(); x++) { for(size_t y = minIdx.y(); y < maxIdx.y(); y++) { Index curIdx(x,y); LevelList<const P *> &retList(ret.at(Index(curIdx - minIdx))); for(const P &p: this->at(curIdx)) { if(::maps::tools::overlap(p.getMin(), p.getMax(), minHeight, maxHeight)) { retList.insert(&p); } } } } return ret; } }; }} <commit_msg>Added intersectCuboid()<commit_after>#pragma once #include "LevelList.hpp" #include "GridMap.hpp" #include "../tools/Overlap.hpp" namespace maps { namespace grid { template <class P> class MultiLevelGridMap : public GridMap<LevelList<P> > { public: typedef LevelList<P> CellType; MultiLevelGridMap(const Vector2ui &num_cells, const Eigen::Vector2d &resolution, const boost::shared_ptr<LocalMapData> &data) : GridMap<LevelList<P> >(num_cells, resolution, LevelList<P>(), data) {} MultiLevelGridMap(const Vector2ui &num_cells, const Eigen::Vector2d &resolution) : GridMap<LevelList<P> >(num_cells, resolution, LevelList<P>()) {} MultiLevelGridMap() {} class View : public GridMap<LevelList<const P *> > { public: View(const Vector2ui &num_cells, const Eigen::Vector2d &resolution) : GridMap<LevelList<const P *> >(num_cells, resolution, LevelList<const P *>()) { }; View() : GridMap<LevelList<const P *> >() { }; }; View intersectCuboid(const Eigen::AlignedBox3d& box) const { size_t ignore; return intersectCuboid(box, ignore); } /** @param outNumIntersections contains the number of mls patches that intersected the @p box*/ View intersectCuboid(const Eigen::AlignedBox3d& box, size_t& outNumIntersections) const { double minHeight = box.min().z(); double maxHeight = box.max().z(); outNumIntersections = 0; Index minIdx; Index maxIdx; if(!this->toGrid(box.min(), minIdx)) { return View(); } if(!this->toGrid(box.max(), maxIdx)) { return View(); } Index newSize(maxIdx-minIdx); View ret(Vector2ui(newSize.x(), newSize.y()) , this->getResolution()); for(size_t x = minIdx.x();x < maxIdx.x(); x++) { for(size_t y = minIdx.y(); y < maxIdx.y(); y++) { Index curIdx(x,y); LevelList<const P *> &retList(ret.at(Index(curIdx - minIdx))); for(const P &p: this->at(curIdx)) { if(::maps::tools::overlap(p.getMin(), p.getMax(), minHeight, maxHeight)) { retList.insert(&p); ++outNumIntersections; } } } } return ret; } }; }} <|endoftext|>
<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "main.hh" #include "strings.hh" #include "thread.hh" #include "configbits.cc" #include <string.h> #include <algorithm> #include <glib.h> namespace Rapicorn { String rapicorn_version () { return RAPICORN_VERSION; } String rapicorn_buildid () { return RAPICORN_BUILDID; } // === initialization hooks === static InitHook *init_hooks = NULL; InitHook::InitHook (const String &fname, InitHookFunc func) : next (NULL), hook (func), m_name (fname) { next = init_hooks; init_hooks = this; } static int init_hook_cmp (const InitHook *const &v1, const InitHook *const &v2) { static const char *levels[] = { "core/", "threading/", "ui/" }; uint l1 = UINT_MAX, l2 = UINT_MAX; for (uint i = 0; i < RAPICORN_ARRAY_SIZE (levels); i++) { const uint len = strlen (levels[i]); if (l1 == UINT_MAX && strncmp (levels[i], v1->name().c_str(), len) == 0) { l1 = i; if (l2 != UINT_MAX) break; } if (l2 == UINT_MAX && strncmp (levels[i], v2->name().c_str(), len) == 0) { l2 = i; if (l1 != UINT_MAX) break; } } if (l1 != l2) return l1 < l2 ? -1 : l2 > l1; return strverscmp (v1->name().c_str(), v2->name().c_str()) < 0; } static StringVector *init_hook_main_args = NULL; StringVector InitHook::main_args () const { return *init_hook_main_args; } void InitHook::invoke_hooks (const String &kind, int *argcp, char **argv, const StringVector &args) { std::vector<InitHook*> hv; for (InitHook *ihook = init_hooks; ihook; ihook = ihook->next) hv.push_back (ihook); stable_sort (hv.begin(), hv.end(), init_hook_cmp); StringVector main_args; for (uint i = 1; i < uint (*argcp); i++) main_args.push_back (argv[i]); init_hook_main_args = &main_args; for (std::vector<InitHook*>::iterator it = hv.begin(); it != hv.end(); it++) { String name = (*it)->name(); if (name.size() > kind.size() && strncmp (name.data(), kind.data(), kind.size()) == 0) { RAPICORN_DEBUG ("InitHook: %s", name.c_str()); (*it)->hook (args); } } init_hook_main_args = NULL; } // === arg parsers === /** * Try to parse argument @a arg at position @a i in @a argv. * If successfull, @a i is incremented and the argument * is set to NULL. * @returns true if successfull. */ bool arg_parse_option (uint argc, char **argv, size_t *i, const char *arg) { if (strcmp (argv[*i], arg) == 0) { argv[*i] = NULL; return true; } return false; } /** * Try to parse argument @a arg at position @a i in @a argv. * If successfull, @a i is incremented and the argument and possibly * the next option argument are set to NULL. * @returns true if successfull and the string option in @a strp. */ bool arg_parse_string_option (uint argc, char **argv, size_t *i, const char *arg, const char **strp) { const size_t length = strlen (arg); if (strncmp (argv[*i], arg, length) == 0) { const char *equal = argv[*i] + length; if (*equal == '=') // -x=VAL *strp = equal + 1; else if (*equal) // -xVAL *strp = equal; else if (*i + 1 < argc) // -x VAL { argv[(*i)++] = NULL; *strp = argv[*i]; } else *strp = NULL; argv[*i] = NULL; if (*strp) return true; } return false; } /** * Collapse @a argv by eliminating NULL strings. * @returns Number of collapsed arguments. */ int arg_parse_collapse (int *argcp, char **argv) { // collapse args const uint argc = *argcp; uint e = 1; for (uint i = 1; i < argc; i++) if (argv[i]) { argv[e++] = argv[i]; if (i >= e) argv[i] = NULL; } const int collapsed = *argcp - e; *argcp = e; return collapsed; } static bool parse_bool_option (const String &s, const char *arg, bool *boolp) { const size_t length = strlen (arg); if (s.size() > length && s[length] == '=' && strncmp (&s[0], arg, length) == 0) { *boolp = string_to_bool (s.substr (length + 1)); return true; } return false; } // === initialization === struct VInitSettings : InitSettings { bool& autonomous() { return m_autonomous; } uint& test_codes() { return m_test_codes; } VInitSettings() { m_autonomous = false; m_test_codes = 0; } } static vsettings; static VInitSettings vinit_settings; const InitSettings *InitSettings::sis = &vinit_settings; static void parse_settings_and_args (VInitSettings &vsettings, const StringVector &args, int *argcp, char **argv) { bool b = 0, pta = false; // apply init settings for (StringVector::const_iterator it = args.begin(); it != args.end(); it++) if (parse_bool_option (*it, "autonomous", &b)) vsettings.autonomous() = b; else if (parse_bool_option (*it, "parse-testargs", &b)) pta = b; else if (parse_bool_option (*it, "test-verbose", &b)) vsettings.test_codes() |= 0x1; else if (parse_bool_option (*it, "test-log", &b)) vsettings.test_codes() |= 0x2; else if (parse_bool_option (*it, "test-slow", &b)) vsettings.test_codes() |= 0x4; // parse command line args const size_t argc = *argcp; for (size_t i = 1; i < argc; i++) { if ( arg_parse_option (*argcp, argv, &i, "--fatal-warnings") || arg_parse_option (*argcp, argv, &i, "--g-fatal-warnings")) // legacy option support { debug_configure ("fatal-warnings"); const uint fatal_mask = g_log_set_always_fatal (GLogLevelFlags (G_LOG_FATAL_MASK)); g_log_set_always_fatal (GLogLevelFlags (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL)); } else if (pta && arg_parse_option (*argcp, argv, &i, "--test-verbose")) vsettings.test_codes() |= 0x1; else if (pta && arg_parse_option (*argcp, argv, &i, "--test-log")) vsettings.test_codes() |= 0x2; else if (pta && arg_parse_option (*argcp, argv, &i, "--test-slow")) vsettings.test_codes() |= 0x4; else if (pta && strcmp ("--verbose", argv[i]) == 0) { vsettings.test_codes() |= 0x1; /* interpret --verbose for GLib compat but don't delete the argument * since regular non-test programs may need this. could be fixed by * having a separate test program argument parser. */ } } // collapse NULL arguments arg_parse_collapse (argcp, argv); } static String program_argv0 = ""; static String program_app_ident = ""; static String program_cwd0 = ""; /** * File name of the current process as set in argv[0] at startup. */ String program_file () { return program_argv0; } /** * Provides a short name for the current process, usually the last part of argv[0]. * See also GNU Libc program_invocation_short_name. */ String program_alias () { #ifdef _GNU_SOURCE return program_invocation_short_name; #else const char *last = strrchr (program_argv0.c_str(), '/'); return last ? last + 1 : ""; #endif } /** * The program identifier @a app_ident as specified during initialization of Rapicorn. */ String program_ident () { return program_app_ident; } /** * The current working directory during startup. */ String program_cwd () { return program_cwd0; } static struct __StaticCTorTest { int v; __StaticCTorTest() : v (0x12affe16) { v++; ThreadInfo::self().name ("MainThread"); } } __staticctortest; /** * @param app_ident Application identifier, used to associate persistent resources * @param argcp location of the 'argc' argument to main() * @param argv location of the 'argv' arguments to main() * @param args program specific initialization values * * Initialize the Rapicorn toolkit, including threading, CPU detection, loading resource libraries, etc. * The arguments passed in @a argcp and @a argv are parsed and any Rapicorn specific arguments * are stripped. * Supported command line arguments are: * - @c --test-verbose - execute test cases verbosely. * - @c --test-log - execute logtest test cases. * - @c --test-slow - execute slow test cases. * - @c --verbose - behaves like @c --test-verbose, this option is recognized but not stripped. * . * Additional initialization arguments can be passed in @a args, currently supported are: * - @c autonomous - For test programs to request a self-contained runtime environment. * - @c cpu-affinity - CPU# to bind rapicorn thread to. * - @c parse-testargs - Used by init_core_test() internally. * - @c test-verbose - acts like --test-verbose. * - @c test-log - acts like --test-log. * - @c test-slow - acts like --test-slow. * . * Additionally, the @c $RAPICORN environment variable affects toolkit behaviour. It supports * multiple colon (':') separated options (options can be prfixed with 'no-' to disable): * - @c debug - Enables verbose debugging output (default=off). * - @c fatal-syslog - Fatal program conditions that lead to aborting are recorded via syslog (default=on). * - @c syslog - Critical and warning conditions are recorded via syslog (default=off). * - @c fatal-warnings - Critical and warning conditions are treated as fatal conditions (default=off). * - @c logfile=FILENAME - Record all messages and conditions into FILENAME. * . */ void init_core (const String &app_ident, int *argcp, char **argv, const StringVector &args) { assert_return (app_ident.empty() == false); // assert global_ctors work if (__staticctortest.v != 0x12affe17) fatal ("librapicorncore: link error: C++ constructors have not been executed"); // guard against double initialization if (program_app_ident.empty() == false) fatal ("librapicorncore: multiple calls to Rapicorn::init_app()"); program_app_ident = app_ident; // mandatory threading initialization if (!g_threads_got_initialized) g_thread_init (NULL); // setup program and application name if (program_argv0.empty() && argcp && *argcp && argv && argv[0] && argv[0][0] != 0) program_argv0 = argv[0]; if (program_cwd0.empty()) program_cwd0 = Path::cwd(); if (!g_get_prgname() && !program_argv0.empty()) g_set_prgname (Path::basename (program_argv0).c_str()); if (!g_get_application_name() || g_get_application_name() == g_get_prgname()) g_set_application_name (program_app_ident.c_str()); if (!program_argv0.empty()) ThreadInfo::self().name (string_printf ("%s-MainThread", Path::basename (program_argv0).c_str())); // ensure logging is fully initialized debug_configure (""); const char *env_rapicorn = getenv ("RAPICORN"); RAPICORN_DEBUG ("Startup; RAPICORN=%s", env_rapicorn ? env_rapicorn : ""); // setup init settings parse_settings_and_args (vinit_settings, args, argcp, argv); // initialize sub systems struct InitHookCaller : public InitHook { static void invoke (const String &kind, int *argcp, char **argv, const StringVector &args) { invoke_hooks (kind, argcp, argv, args); } }; InitHookCaller::invoke ("core/", argcp, argv, args); InitHookCaller::invoke ("threading/", argcp, argv, args); } } // Rapicorn <commit_msg>RCORE: init_core: ensure locale is fully initialized<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html #include "main.hh" #include "strings.hh" #include "thread.hh" #include "configbits.cc" #include <string.h> #include <algorithm> #include <glib.h> namespace Rapicorn { String rapicorn_version () { return RAPICORN_VERSION; } String rapicorn_buildid () { return RAPICORN_BUILDID; } // === initialization hooks === static InitHook *init_hooks = NULL; InitHook::InitHook (const String &fname, InitHookFunc func) : next (NULL), hook (func), m_name (fname) { next = init_hooks; init_hooks = this; } static int init_hook_cmp (const InitHook *const &v1, const InitHook *const &v2) { static const char *levels[] = { "core/", "threading/", "ui/" }; uint l1 = UINT_MAX, l2 = UINT_MAX; for (uint i = 0; i < RAPICORN_ARRAY_SIZE (levels); i++) { const uint len = strlen (levels[i]); if (l1 == UINT_MAX && strncmp (levels[i], v1->name().c_str(), len) == 0) { l1 = i; if (l2 != UINT_MAX) break; } if (l2 == UINT_MAX && strncmp (levels[i], v2->name().c_str(), len) == 0) { l2 = i; if (l1 != UINT_MAX) break; } } if (l1 != l2) return l1 < l2 ? -1 : l2 > l1; return strverscmp (v1->name().c_str(), v2->name().c_str()) < 0; } static StringVector *init_hook_main_args = NULL; StringVector InitHook::main_args () const { return *init_hook_main_args; } void InitHook::invoke_hooks (const String &kind, int *argcp, char **argv, const StringVector &args) { std::vector<InitHook*> hv; for (InitHook *ihook = init_hooks; ihook; ihook = ihook->next) hv.push_back (ihook); stable_sort (hv.begin(), hv.end(), init_hook_cmp); StringVector main_args; for (uint i = 1; i < uint (*argcp); i++) main_args.push_back (argv[i]); init_hook_main_args = &main_args; for (std::vector<InitHook*>::iterator it = hv.begin(); it != hv.end(); it++) { String name = (*it)->name(); if (name.size() > kind.size() && strncmp (name.data(), kind.data(), kind.size()) == 0) { RAPICORN_DEBUG ("InitHook: %s", name.c_str()); (*it)->hook (args); } } init_hook_main_args = NULL; } // === arg parsers === /** * Try to parse argument @a arg at position @a i in @a argv. * If successfull, @a i is incremented and the argument * is set to NULL. * @returns true if successfull. */ bool arg_parse_option (uint argc, char **argv, size_t *i, const char *arg) { if (strcmp (argv[*i], arg) == 0) { argv[*i] = NULL; return true; } return false; } /** * Try to parse argument @a arg at position @a i in @a argv. * If successfull, @a i is incremented and the argument and possibly * the next option argument are set to NULL. * @returns true if successfull and the string option in @a strp. */ bool arg_parse_string_option (uint argc, char **argv, size_t *i, const char *arg, const char **strp) { const size_t length = strlen (arg); if (strncmp (argv[*i], arg, length) == 0) { const char *equal = argv[*i] + length; if (*equal == '=') // -x=VAL *strp = equal + 1; else if (*equal) // -xVAL *strp = equal; else if (*i + 1 < argc) // -x VAL { argv[(*i)++] = NULL; *strp = argv[*i]; } else *strp = NULL; argv[*i] = NULL; if (*strp) return true; } return false; } /** * Collapse @a argv by eliminating NULL strings. * @returns Number of collapsed arguments. */ int arg_parse_collapse (int *argcp, char **argv) { // collapse args const uint argc = *argcp; uint e = 1; for (uint i = 1; i < argc; i++) if (argv[i]) { argv[e++] = argv[i]; if (i >= e) argv[i] = NULL; } const int collapsed = *argcp - e; *argcp = e; return collapsed; } static bool parse_bool_option (const String &s, const char *arg, bool *boolp) { const size_t length = strlen (arg); if (s.size() > length && s[length] == '=' && strncmp (&s[0], arg, length) == 0) { *boolp = string_to_bool (s.substr (length + 1)); return true; } return false; } // === initialization === struct VInitSettings : InitSettings { bool& autonomous() { return m_autonomous; } uint& test_codes() { return m_test_codes; } VInitSettings() { m_autonomous = false; m_test_codes = 0; } } static vsettings; static VInitSettings vinit_settings; const InitSettings *InitSettings::sis = &vinit_settings; static void parse_settings_and_args (VInitSettings &vsettings, const StringVector &args, int *argcp, char **argv) { bool b = 0, pta = false; // apply init settings for (StringVector::const_iterator it = args.begin(); it != args.end(); it++) if (parse_bool_option (*it, "autonomous", &b)) vsettings.autonomous() = b; else if (parse_bool_option (*it, "parse-testargs", &b)) pta = b; else if (parse_bool_option (*it, "test-verbose", &b)) vsettings.test_codes() |= 0x1; else if (parse_bool_option (*it, "test-log", &b)) vsettings.test_codes() |= 0x2; else if (parse_bool_option (*it, "test-slow", &b)) vsettings.test_codes() |= 0x4; // parse command line args const size_t argc = *argcp; for (size_t i = 1; i < argc; i++) { if ( arg_parse_option (*argcp, argv, &i, "--fatal-warnings") || arg_parse_option (*argcp, argv, &i, "--g-fatal-warnings")) // legacy option support { debug_configure ("fatal-warnings"); const uint fatal_mask = g_log_set_always_fatal (GLogLevelFlags (G_LOG_FATAL_MASK)); g_log_set_always_fatal (GLogLevelFlags (fatal_mask | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL)); } else if (pta && arg_parse_option (*argcp, argv, &i, "--test-verbose")) vsettings.test_codes() |= 0x1; else if (pta && arg_parse_option (*argcp, argv, &i, "--test-log")) vsettings.test_codes() |= 0x2; else if (pta && arg_parse_option (*argcp, argv, &i, "--test-slow")) vsettings.test_codes() |= 0x4; else if (pta && strcmp ("--verbose", argv[i]) == 0) { vsettings.test_codes() |= 0x1; /* interpret --verbose for GLib compat but don't delete the argument * since regular non-test programs may need this. could be fixed by * having a separate test program argument parser. */ } } // collapse NULL arguments arg_parse_collapse (argcp, argv); } static String program_argv0 = ""; static String program_app_ident = ""; static String program_cwd0 = ""; /** * File name of the current process as set in argv[0] at startup. */ String program_file () { return program_argv0; } /** * Provides a short name for the current process, usually the last part of argv[0]. * See also GNU Libc program_invocation_short_name. */ String program_alias () { #ifdef _GNU_SOURCE return program_invocation_short_name; #else const char *last = strrchr (program_argv0.c_str(), '/'); return last ? last + 1 : ""; #endif } /** * The program identifier @a app_ident as specified during initialization of Rapicorn. */ String program_ident () { return program_app_ident; } /** * The current working directory during startup. */ String program_cwd () { return program_cwd0; } static struct __StaticCTorTest { int v; __StaticCTorTest() : v (0x12affe16) { v++; ThreadInfo::self().name ("MainThread"); } } __staticctortest; static const char* sgetenv (const char *var) { const char *str = getenv (var); return str ? str : ""; } /** * @param app_ident Application identifier, used to associate persistent resources * @param argcp location of the 'argc' argument to main() * @param argv location of the 'argv' arguments to main() * @param args program specific initialization values * * Initialize the Rapicorn toolkit, including threading, CPU detection, loading resource libraries, etc. * The arguments passed in @a argcp and @a argv are parsed and any Rapicorn specific arguments * are stripped. * Supported command line arguments are: * - @c --test-verbose - execute test cases verbosely. * - @c --test-log - execute logtest test cases. * - @c --test-slow - execute slow test cases. * - @c --verbose - behaves like @c --test-verbose, this option is recognized but not stripped. * . * Additional initialization arguments can be passed in @a args, currently supported are: * - @c autonomous - For test programs to request a self-contained runtime environment. * - @c cpu-affinity - CPU# to bind rapicorn thread to. * - @c parse-testargs - Used by init_core_test() internally. * - @c test-verbose - acts like --test-verbose. * - @c test-log - acts like --test-log. * - @c test-slow - acts like --test-slow. * . * Additionally, the @c $RAPICORN environment variable affects toolkit behaviour. It supports * multiple colon (':') separated options (options can be prfixed with 'no-' to disable): * - @c debug - Enables verbose debugging output (default=off). * - @c fatal-syslog - Fatal program conditions that lead to aborting are recorded via syslog (default=on). * - @c syslog - Critical and warning conditions are recorded via syslog (default=off). * - @c fatal-warnings - Critical and warning conditions are treated as fatal conditions (default=off). * - @c logfile=FILENAME - Record all messages and conditions into FILENAME. * . */ void init_core (const String &app_ident, int *argcp, char **argv, const StringVector &args) { assert_return (app_ident.empty() == false); // assert global_ctors work if (__staticctortest.v != 0x12affe17) fatal ("librapicorncore: link error: C++ constructors have not been executed"); // guard against double initialization if (program_app_ident.empty() == false) fatal ("librapicorncore: multiple calls to Rapicorn::init_app()"); program_app_ident = app_ident; // mandatory threading initialization if (!g_threads_got_initialized) g_thread_init (NULL); // setup program and application name if (program_argv0.empty() && argcp && *argcp && argv && argv[0] && argv[0][0] != 0) program_argv0 = argv[0]; if (program_cwd0.empty()) program_cwd0 = Path::cwd(); if (!g_get_prgname() && !program_argv0.empty()) g_set_prgname (Path::basename (program_argv0).c_str()); if (!g_get_application_name() || g_get_application_name() == g_get_prgname()) g_set_application_name (program_app_ident.c_str()); if (!program_argv0.empty()) ThreadInfo::self().name (string_printf ("%s-MainThread", Path::basename (program_argv0).c_str())); // ensure logging is fully initialized debug_configure (""); const char *env_rapicorn = getenv ("RAPICORN"); RAPICORN_DEBUG ("Startup; RAPICORN=%s", env_rapicorn ? env_rapicorn : ""); // full locale initialization is needed by X11, etc if (!setlocale (LC_ALL,"")) { String lv = string_printf ("LANGUAGE=%s;LC_ALL=%s;LC_MONETARY=%s;LC_MESSAGES=%s;LC_COLLATE=%s;LC_CTYPE=%s;LC_TIME=%s;LANG=%s", sgetenv ("LANGUAGE"), sgetenv ("LC_ALL"), sgetenv ("LC_MONETARY"), sgetenv ("LC_MESSAGES"), sgetenv ("LC_COLLATE"), sgetenv ("LC_CTYPE"), sgetenv ("LC_TIME"), sgetenv ("LANG")); DEBUG ("environment: %s", lv.c_str()); setlocale (LC_ALL, "C"); DEBUG ("failed to initialize locale, falling back to \"C\""); } // setup init settings parse_settings_and_args (vinit_settings, args, argcp, argv); // initialize sub systems struct InitHookCaller : public InitHook { static void invoke (const String &kind, int *argcp, char **argv, const StringVector &args) { invoke_hooks (kind, argcp, argv, args); } }; InitHookCaller::invoke ("core/", argcp, argv, args); InitHookCaller::invoke ("threading/", argcp, argv, args); } } // Rapicorn <|endoftext|>
<commit_before><commit_msg>Agregada solucion sucia al segundo problema<commit_after>#include <iostream> #include <vector> #include <queue> #include <fstream> #include <cmath> using namespace std; vector < pair <int,int> > arcos; class Arco { public: int padre, hijo; Arco(){}; Arco(int p, int h){ this->padre = p; this->hijo = h; } }; class CompareArco { public: bool operator()(const Arco left, const Arco right) const{ return left.padre <= right.padre; } }; priority_queue < Arco, vector<Arco>, CompareArco> cola; int dfs(int nodo, vector<int>* hijos, int* componentes){ if(hijos[nodo].empty()){ componentes[nodo]=1; }else{ int acum = 0; for(int i=0;i<hijos[nodo].size();i++){ acum += dfs(hijos[nodo][i],hijos,componentes); } componentes[nodo] = acum + 1; } return componentes[nodo]; } int main( int argc, char *argv[] ){ int casos, numNodo, desc; if(scanf("%i",&casos)!=1) cout<<"welp"<<endl; // else // cout<<casos<<endl; // scanf(""); if(scanf("%i",&numNodo)!=1) cout<<"welp"<<endl; // else // cout<<numNodo<<endl; for(int l=0;l<casos;l++){ // cout<<">>>>>>>>>>>>>>>>>>>>>> : "<<l<<endl; int x,y; for(int i=0;i<numNodo-1;i++) if(scanf("%i %i",&x,&y)!=2) cout<<"welp"<<endl; else{ // cola.push(Arco(x-1,y-1)); arcos.push_back(make_pair(x-1,y-1)); } // for(int i=0;i<numNodo-1;i++){ // // cout<<cola.top().padre<<" , "<<cola.top().hijo<<endl; // // cola.pop(); // cout<<arcos[i].first<<" , "<<arcos[i].second<<endl; // } int padre[numNodo]; for(int i=0;i<numNodo;i++) padre[i]=-1; vector<int> hijos[numNodo]; int componentes[numNodo]; componentes[0]=numNodo; Arco dummy; int acum; for(int i=0;i<numNodo-1;i++){ padre[arcos[i].second] = arcos[i].first; hijos[arcos[i].first].push_back(arcos[i].second); // dummy = cola.top(); // cola.pop(); // padre[dummy.hijo] = dummy.padre; // hijos[dummy.padre].push_back(dummy.hijo); } // for(int i=0;i<numNodo;i++){ // cout<<i<<": "<<padre[i]<<endl; // } // for(int i=0;i<numNodo;i++){ // cout<<i<<"-> "; // for(int j=0;j<hijos[i].size();j++) // cout<<hijos[i][j]<<" , "; // cout<<endl; // } componentes[0] = dfs(0,hijos,componentes); // for(int i=0;i<numNodo;i++){ // cout<<i<<"% "<<componentes[i]<<endl; // } if(scanf("%i",&desc)!=1) cout<<"welp"<<endl; // cout<<"desc: "<<desc<<endl; vector<int> leader; leader.push_back(0); char c = '&'; int d; for(int i=0;i<desc;i++){ d = -1; scanf(" %c %i",&c,&d); // cout<<i<<": "<<c<<" "<<d<<endl; if(c=='Q') if(leader.size()==1) cout<<0<<endl; else{ int acum = 0; for(int h=0;h<leader.size();h++) for(int j=h+1;j<leader.size();j++){ acum += componentes[leader[h]]*componentes[leader[j]]; // cout<<"\t"<<acum<<endl; } // acum /= 2; cout<<acum<<endl; if(d!= -1) numNodo = d; } else if(c=='R'){ // cout << arcos[d-1].first<<" , "<<arcos[d-1].second<<endl; int dpadre=arcos[d-1].first, dhijo=arcos[d-1].second; padre[arcos[d-1].second] = -1; leader.push_back(arcos[d-1].second); while(dpadre != -1){ componentes[dpadre] -= componentes[arcos[d-1].second]; dhijo = dpadre; dpadre = padre[dpadre]; } // for(int i=0;i<numNodo;i++){ // cout<<i<<": "<<padre[i]<<endl; // } // for(int i=0;i<numNodo;i++){ // cout<<i<<"% "<<componentes[i]<<endl; // } // for(int i=0;i<leader.size();i++){ // cout<<i<<"$ "<<leader[i]<<endl; // } } // cout<<c<<" "<<d<<endl; } cout<<endl; } } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <vector> #include <algorithm> #include <iostream> #include "xarray/xarray.hpp" #include "xarray/xio.hpp" namespace qs { TEST(xio, simple) { xshape<size_t> shape = {3, 4}; xarray<double> a(shape); std::vector<double> data {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; std::copy(data.begin(), data.end(), a.storage_begin()); std::cout << a; } } <commit_msg>xio does not compile yet<commit_after>#include "gtest/gtest.h" #include <vector> #include <algorithm> #include <iostream> #include "xarray/xarray.hpp" #include "xarray/xio.hpp" namespace qs { TEST(xio, simple) { //xshape<size_t> shape = {3, 4}; //xarray<double> a(shape); //std::vector<double> data {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; //std::copy(data.begin(), data.end(), a.storage_begin()); //std::cout << a; } } <|endoftext|>
<commit_before>// TCP receiver // Author: Max Schwarz <max.schwarz@uni-bonn.de> #include "tcp_receiver.h" #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include "tcp_packet.h" #include "../topic_info.h" #include <topic_tools/shape_shifter.h> #include <bzlib.h> #include <nimbro_topic_transport/CompressedMsg.h> namespace nimbro_topic_transport { static bool sureRead(int fd, void* dest, ssize_t size) { uint8_t* destWPtr = (uint8_t*)dest; while(size != 0) { ssize_t ret = read(fd, destWPtr, size); if(ret < 0) { ROS_ERROR("Could not read(): %s", strerror(errno)); return false; } if(ret == 0) { // Client has closed connection (ignore silently) return false; } size -= ret; destWPtr += ret; } return true; } TCPReceiver::TCPReceiver() : m_nh("~") , m_receivedBytesInStatsInterval(0) { m_fd = socket(AF_INET, SOCK_STREAM, 0); if(m_fd < 0) { ROS_FATAL("Could not create socket: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } int port; m_nh.param("port", port, 5050); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); int on = 1; if(setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0) { ROS_FATAL("Could not enable SO_REUSEADDR: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } ROS_DEBUG("Binding to :%d", port); if(bind(m_fd, (sockaddr*)&addr, sizeof(addr)) != 0) { ROS_FATAL("Could not bind socket: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } if(listen(m_fd, 10) != 0) { ROS_FATAL("Could not listen: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } m_nh.param("keep_compressed", m_keepCompressed, false); char hostnameBuf[256]; gethostname(hostnameBuf, sizeof(hostnameBuf)); hostnameBuf[sizeof(hostnameBuf)-1] = 0; m_stats.node = ros::this_node::getName(); m_stats.protocol = "TCP"; m_stats.host = hostnameBuf; m_stats.local_port = port; m_stats.fec = false; m_nh.param("label", m_stats.label, std::string()); m_pub_stats = m_nh.advertise<ReceiverStats>("/network/receiver_stats", 1); m_statsInterval = ros::WallDuration(2.0); m_statsTimer = m_nh.createWallTimer(m_statsInterval, boost::bind(&TCPReceiver::updateStats, this) ); } TCPReceiver::~TCPReceiver() { } void TCPReceiver::run() { fd_set fds; while(ros::ok()) { ros::spinOnce(); // Clean up any exited threads std::list<ClientHandler*>::iterator it = m_handlers.begin(); while(it != m_handlers.end()) { if(!(*it)->isRunning()) { delete *it; it = m_handlers.erase(it); } else it++; } FD_ZERO(&fds); FD_SET(m_fd, &fds); timeval timeout; timeout.tv_usec = 0; timeout.tv_sec = 1; int ret = select(m_fd+1, &fds, 0, 0, &timeout); if(ret < 0) { if(errno == EINTR || errno == EAGAIN) continue; ROS_ERROR("Could not select(): %s", strerror(errno)); throw std::runtime_error("Could not select"); } if(ret == 0) continue; sockaddr_storage remoteAddr; socklen_t remoteAddrLen = sizeof(remoteAddr); int client_fd = accept(m_fd, (sockaddr*)&remoteAddr, &remoteAddrLen); { // Perform reverse lookup char nameBuf[256]; char serviceBuf[256]; ros::WallTime startLookup = ros::WallTime::now(); if(getnameinfo((sockaddr*)&remoteAddr, remoteAddrLen, nameBuf, sizeof(nameBuf), serviceBuf, sizeof(serviceBuf), NI_NUMERICSERV) != 0) { ROS_ERROR("Could not resolve remote address to name"); } ros::WallTime endLookup = ros::WallTime::now(); // Warn if lookup takes up time (otherwise the user does not know // what is going on) if(endLookup - startLookup > ros::WallDuration(1.0)) { ROS_WARN("Reverse address lookup took more than a second. Consider adding '%s' to /etc/hosts", nameBuf); } ROS_INFO("New remote: %s:%s", nameBuf, serviceBuf); m_stats.remote = nameBuf; m_stats.remote_port = atoi(serviceBuf); } ClientHandler* handler = new ClientHandler(client_fd); handler->setKeepCompressed(m_keepCompressed); m_handlers.push_back(handler); } } TCPReceiver::ClientHandler::ClientHandler(int fd) : m_fd(fd) , m_uncompressBuf(1024) , m_running(true) , m_keepCompressed(false) { m_thread = boost::thread(boost::bind(&ClientHandler::start, this)); } TCPReceiver::ClientHandler::~ClientHandler() { close(m_fd); } class VectorStream { public: VectorStream(std::vector<uint8_t>* vector) : m_vector(vector) {} inline const uint8_t* getData() { return m_vector->data(); } inline size_t getLength() { return m_vector->size(); } private: std::vector<uint8_t>* m_vector; }; void TCPReceiver::ClientHandler::start() { run(); m_running = false; } void TCPReceiver::ClientHandler::run() { while(1) { TCPHeader header; if(!sureRead(m_fd, &header, sizeof(header))) return; std::vector<char> buf(header.topic_len + 1); if(!sureRead(m_fd, buf.data(), header.topic_len)) return; buf[buf.size()-1] = 0; std::string topic(buf.data()); buf.resize(header.type_len+1); if(!sureRead(m_fd, buf.data(), header.type_len)) return; buf[buf.size()-1] = 0; std::string type(buf.data()); std::string md5; topic_info::unpackMD5(header.topic_md5sum, &md5); std::vector<uint8_t> data(header.data_len); if(!sureRead(m_fd, data.data(), header.data_len)) return; ROS_DEBUG("Got msg with flags: %d", header.flags()); if(m_keepCompressed && (header.flags() & TCP_FLAG_COMPRESSED)) { CompressedMsg compressed; compressed.type = type; memcpy(compressed.md5.data(), header.topic_md5sum, sizeof(header.topic_md5sum)); compressed.data.swap(data); std::map<std::string, ros::Publisher>::iterator it = m_pub.find(topic); if(it == m_pub.end()) { ros::NodeHandle nh; ros::Publisher pub = nh.advertise<CompressedMsg>(topic, 2); m_pub[topic] = pub; pub.publish(compressed); } else it->second.publish(compressed); } else { topic_tools::ShapeShifter shifter; if(header.flags() & TCP_FLAG_COMPRESSED) { int ret = 0; unsigned int len = m_uncompressBuf.size(); while(1) { ret = BZ2_bzBuffToBuffDecompress((char*)m_uncompressBuf.data(), &len, (char*)data.data(), data.size(), 0, 0); if(ret == BZ_OUTBUFF_FULL) { len = 4 * m_uncompressBuf.size(); ROS_INFO("Increasing buffer size to %d KiB", (int)len / 1024); m_uncompressBuf.resize(len); continue; } else break; } if(ret != BZ_OK) { ROS_ERROR("Could not decompress bz2 data (reason %d), dropping msg", ret); continue; } ROS_INFO("decompress %d KiB (%d) to %d KiB (%d)", (int)data.size() / 1024, (int)data.size(), (int)len / 1024, (int)len); m_uncompressBuf.resize(len); VectorStream stream(&m_uncompressBuf); shifter.read(stream); } else { VectorStream stream(&data); shifter.read(stream); } ROS_DEBUG("Got message from topic '%s' (type '%s', md5 '%s')", topic.c_str(), type.c_str(), md5.c_str()); shifter.morph(md5, type, "", ""); std::map<std::string, ros::Publisher>::iterator it = m_pub.find(topic); if(it == m_pub.end()) { ROS_DEBUG("Advertising new topic '%s'", topic.c_str()); std::string msgDef = topic_info::getMsgDef(type); ros::NodeHandle nh; ros::AdvertiseOptions options( topic, 2, md5, type, topic_info::getMsgDef(type) ); // It will take subscribers some time to connect to our publisher. // Therefore, latch messages so they will not be lost. // No, this is often unexpected. Instead, wait before publishing. // options.latch = true; m_pub[topic] = nh.advertise(options); it = m_pub.find(topic); sleep(1); } it->second.publish(shifter); } uint8_t ack = 1; if(write(m_fd, &ack, 1) != 1) { ROS_ERROR("Could not write(): %s", strerror(errno)); return; } } } bool TCPReceiver::ClientHandler::isRunning() const { return m_running; } void TCPReceiver::updateStats() { m_stats.header.stamp = ros::Time::now(); uint64_t totalBytes = 0; for(auto handler : m_handlers) { totalBytes += handler->bytesReceived(); handler->resetByteCounter(); } m_stats.bandwidth = totalBytes / m_statsInterval.toSec(); m_stats.drop_rate = 0; m_pub_stats.publish(m_stats); } } int main(int argc, char** argv) { ros::init(argc, argv, "tcp_receiver"); nimbro_topic_transport::TCPReceiver recv; recv.run(); return 0; } <commit_msg>nimbro_topic_transport: tcp: don't send stats before receiving first msg<commit_after>// TCP receiver // Author: Max Schwarz <max.schwarz@uni-bonn.de> #include "tcp_receiver.h" #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include "tcp_packet.h" #include "../topic_info.h" #include <topic_tools/shape_shifter.h> #include <bzlib.h> #include <nimbro_topic_transport/CompressedMsg.h> namespace nimbro_topic_transport { static bool sureRead(int fd, void* dest, ssize_t size) { uint8_t* destWPtr = (uint8_t*)dest; while(size != 0) { ssize_t ret = read(fd, destWPtr, size); if(ret < 0) { ROS_ERROR("Could not read(): %s", strerror(errno)); return false; } if(ret == 0) { // Client has closed connection (ignore silently) return false; } size -= ret; destWPtr += ret; } return true; } TCPReceiver::TCPReceiver() : m_nh("~") , m_receivedBytesInStatsInterval(0) { m_fd = socket(AF_INET, SOCK_STREAM, 0); if(m_fd < 0) { ROS_FATAL("Could not create socket: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } int port; m_nh.param("port", port, 5050); sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); int on = 1; if(setsockopt(m_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) != 0) { ROS_FATAL("Could not enable SO_REUSEADDR: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } ROS_DEBUG("Binding to :%d", port); if(bind(m_fd, (sockaddr*)&addr, sizeof(addr)) != 0) { ROS_FATAL("Could not bind socket: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } if(listen(m_fd, 10) != 0) { ROS_FATAL("Could not listen: %s", strerror(errno)); throw std::runtime_error(strerror(errno)); } m_nh.param("keep_compressed", m_keepCompressed, false); char hostnameBuf[256]; gethostname(hostnameBuf, sizeof(hostnameBuf)); hostnameBuf[sizeof(hostnameBuf)-1] = 0; m_stats.node = ros::this_node::getName(); m_stats.protocol = "TCP"; m_stats.host = hostnameBuf; m_stats.local_port = port; m_stats.fec = false; m_nh.param("label", m_stats.label, std::string()); m_pub_stats = m_nh.advertise<ReceiverStats>("/network/receiver_stats", 1); m_statsInterval = ros::WallDuration(2.0); m_statsTimer = m_nh.createWallTimer(m_statsInterval, boost::bind(&TCPReceiver::updateStats, this) ); } TCPReceiver::~TCPReceiver() { } void TCPReceiver::run() { fd_set fds; while(ros::ok()) { ros::spinOnce(); // Clean up any exited threads std::list<ClientHandler*>::iterator it = m_handlers.begin(); while(it != m_handlers.end()) { if(!(*it)->isRunning()) { delete *it; it = m_handlers.erase(it); } else it++; } FD_ZERO(&fds); FD_SET(m_fd, &fds); timeval timeout; timeout.tv_usec = 0; timeout.tv_sec = 1; int ret = select(m_fd+1, &fds, 0, 0, &timeout); if(ret < 0) { if(errno == EINTR || errno == EAGAIN) continue; ROS_ERROR("Could not select(): %s", strerror(errno)); throw std::runtime_error("Could not select"); } if(ret == 0) continue; sockaddr_storage remoteAddr; socklen_t remoteAddrLen = sizeof(remoteAddr); int client_fd = accept(m_fd, (sockaddr*)&remoteAddr, &remoteAddrLen); { // Perform reverse lookup char nameBuf[256]; char serviceBuf[256]; ros::WallTime startLookup = ros::WallTime::now(); if(getnameinfo((sockaddr*)&remoteAddr, remoteAddrLen, nameBuf, sizeof(nameBuf), serviceBuf, sizeof(serviceBuf), NI_NUMERICSERV) != 0) { ROS_ERROR("Could not resolve remote address to name"); } ros::WallTime endLookup = ros::WallTime::now(); // Warn if lookup takes up time (otherwise the user does not know // what is going on) if(endLookup - startLookup > ros::WallDuration(1.0)) { ROS_WARN("Reverse address lookup took more than a second. Consider adding '%s' to /etc/hosts", nameBuf); } ROS_INFO("New remote: %s:%s", nameBuf, serviceBuf); m_stats.remote = nameBuf; m_stats.remote_port = atoi(serviceBuf); } ClientHandler* handler = new ClientHandler(client_fd); handler->setKeepCompressed(m_keepCompressed); m_handlers.push_back(handler); } } TCPReceiver::ClientHandler::ClientHandler(int fd) : m_fd(fd) , m_uncompressBuf(1024) , m_running(true) , m_keepCompressed(false) { m_thread = boost::thread(boost::bind(&ClientHandler::start, this)); } TCPReceiver::ClientHandler::~ClientHandler() { close(m_fd); } class VectorStream { public: VectorStream(std::vector<uint8_t>* vector) : m_vector(vector) {} inline const uint8_t* getData() { return m_vector->data(); } inline size_t getLength() { return m_vector->size(); } private: std::vector<uint8_t>* m_vector; }; void TCPReceiver::ClientHandler::start() { run(); m_running = false; } void TCPReceiver::ClientHandler::run() { while(1) { TCPHeader header; if(!sureRead(m_fd, &header, sizeof(header))) return; std::vector<char> buf(header.topic_len + 1); if(!sureRead(m_fd, buf.data(), header.topic_len)) return; buf[buf.size()-1] = 0; std::string topic(buf.data()); buf.resize(header.type_len+1); if(!sureRead(m_fd, buf.data(), header.type_len)) return; buf[buf.size()-1] = 0; std::string type(buf.data()); std::string md5; topic_info::unpackMD5(header.topic_md5sum, &md5); std::vector<uint8_t> data(header.data_len); if(!sureRead(m_fd, data.data(), header.data_len)) return; ROS_DEBUG("Got msg with flags: %d", header.flags()); if(m_keepCompressed && (header.flags() & TCP_FLAG_COMPRESSED)) { CompressedMsg compressed; compressed.type = type; memcpy(compressed.md5.data(), header.topic_md5sum, sizeof(header.topic_md5sum)); compressed.data.swap(data); std::map<std::string, ros::Publisher>::iterator it = m_pub.find(topic); if(it == m_pub.end()) { ros::NodeHandle nh; ros::Publisher pub = nh.advertise<CompressedMsg>(topic, 2); m_pub[topic] = pub; pub.publish(compressed); } else it->second.publish(compressed); } else { topic_tools::ShapeShifter shifter; if(header.flags() & TCP_FLAG_COMPRESSED) { int ret = 0; unsigned int len = m_uncompressBuf.size(); while(1) { ret = BZ2_bzBuffToBuffDecompress((char*)m_uncompressBuf.data(), &len, (char*)data.data(), data.size(), 0, 0); if(ret == BZ_OUTBUFF_FULL) { len = 4 * m_uncompressBuf.size(); ROS_INFO("Increasing buffer size to %d KiB", (int)len / 1024); m_uncompressBuf.resize(len); continue; } else break; } if(ret != BZ_OK) { ROS_ERROR("Could not decompress bz2 data (reason %d), dropping msg", ret); continue; } ROS_INFO("decompress %d KiB (%d) to %d KiB (%d)", (int)data.size() / 1024, (int)data.size(), (int)len / 1024, (int)len); m_uncompressBuf.resize(len); VectorStream stream(&m_uncompressBuf); shifter.read(stream); } else { VectorStream stream(&data); shifter.read(stream); } ROS_DEBUG("Got message from topic '%s' (type '%s', md5 '%s')", topic.c_str(), type.c_str(), md5.c_str()); shifter.morph(md5, type, "", ""); std::map<std::string, ros::Publisher>::iterator it = m_pub.find(topic); if(it == m_pub.end()) { ROS_DEBUG("Advertising new topic '%s'", topic.c_str()); std::string msgDef = topic_info::getMsgDef(type); ros::NodeHandle nh; ros::AdvertiseOptions options( topic, 2, md5, type, topic_info::getMsgDef(type) ); // It will take subscribers some time to connect to our publisher. // Therefore, latch messages so they will not be lost. // No, this is often unexpected. Instead, wait before publishing. // options.latch = true; m_pub[topic] = nh.advertise(options); it = m_pub.find(topic); sleep(1); } it->second.publish(shifter); } uint8_t ack = 1; if(write(m_fd, &ack, 1) != 1) { ROS_ERROR("Could not write(): %s", strerror(errno)); return; } } } bool TCPReceiver::ClientHandler::isRunning() const { return m_running; } void TCPReceiver::updateStats() { m_stats.header.stamp = ros::Time::now(); uint64_t totalBytes = 0; for(auto handler : m_handlers) { totalBytes += handler->bytesReceived(); handler->resetByteCounter(); } m_stats.bandwidth = totalBytes / m_statsInterval.toSec(); m_stats.drop_rate = 0; // If there is no connection yet, drop the stats msg if(m_handlers.empty()) return; m_pub_stats.publish(m_stats); } } int main(int argc, char** argv) { ros::init(argc, argv, "tcp_receiver"); nimbro_topic_transport::TCPReceiver recv; recv.run(); return 0; } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX24T グループ・ペリフェラル @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ペリフェラル種別 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class peripheral { CMT0, CMT1, CMT2, CMT3, RIIC0, SCI1, SCI5, SCI6, RSPI0, }; } <commit_msg>update MTU<commit_after>#pragma once //=====================================================================// /*! @file @brief RX24T グループ・ペリフェラル @n Copyright 2016 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include <cstdint> namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief ペリフェラル種別 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class peripheral { CMT0, ///< コンペアマッチタイマー0 CMT1, ///< コンペアマッチタイマー1 CMT2, ///< コンペアマッチタイマー2 CMT3, ///< コンペアマッチタイマー3 RIIC0, ///< I 2 C バスインタフェース0 SCI1, ///< シリアルコミュニケーションインタフェース0 SCI5, ///< シリアルコミュニケーションインタフェース5 SCI6, ///< シリアルコミュニケーションインタフェース6 RSPI0, ///< シリアルペリフェラルインタフェース0 MTU0, ///< マルチファンクションタイマパルスユニット0 MTU1, ///< マルチファンクションタイマパルスユニット1 MTU2, ///< マルチファンクションタイマパルスユニット2 MTU3, ///< マルチファンクションタイマパルスユニット3 MTU4, ///< マルチファンクションタイマパルスユニット4 MTU5, ///< マルチファンクションタイマパルスユニット5 MTU6, ///< マルチファンクションタイマパルスユニット6 MTU7, ///< マルチファンクションタイマパルスユニット7 MTU9, ///< マルチファンクションタイマパルスユニット9 }; } <|endoftext|>
<commit_before>#include "unit_tests/suite/lumix_unit_tests.h" #include "core/mt/lock_free_fixed_queue.h" #include "core/mt/task.h" #include "core/mt/thread.h" namespace { struct Test { Test() : value(1) {} ~Test() { value = 2; } int32 value; }; typedef Lumix::MT::LockFreeFixedQueue<Test, 16> Queue; class TestTaskConsumer : public Lumix::MT::Task { public: TestTaskConsumer(Queue* queue, Lumix::IAllocator& allocator) : Lumix::MT::Task(allocator) , m_queue(queue) , m_sum(0) {} ~TestTaskConsumer() {} int task() { while (!m_queue->isAborted()) { Test* test = m_queue->pop(true); if (NULL == test) break; m_sum += test->value; test->value++; m_queue->dealoc(test); } return 0; } int32 getSum() { return m_sum; } private: Queue* m_queue; int32 m_sum; }; void UT_fixed_lock_queue_non_trivial_constructors(const char* params) { Lumix::DefaultAllocator allocator; Queue queue; TestTaskConsumer testTaskConsumer(&queue, allocator); testTaskConsumer.create("TestTaskConsumer_Task"); testTaskConsumer.run(); const int RUN_COUNT = 512; for (int i = 0; i < RUN_COUNT; i++) { Test* test = queue.alloc(true); queue.push(test, true); } while (!queue.isEmpty()) { Lumix::MT::yield(); } queue.abort(); testTaskConsumer.destroy(); LUMIX_EXPECT_EQ(RUN_COUNT, testTaskConsumer.getSum()); }; class TestTaskPodConsumer : public Lumix::MT::Task { public: TestTaskPodConsumer(Queue* queue, Lumix::IAllocator& allocator) : Lumix::MT::Task(allocator) , m_queue(queue) , m_sum(0) {} ~TestTaskPodConsumer() {} int task() { while (!m_queue->isAborted()) { Test* test = m_queue->pop(true); if (NULL == test) break; m_sum += test->value; test->value++; m_queue->dealoc(test); } return 0; } int32 getSum() { return m_sum; } private: Queue* m_queue; int32 m_sum; }; void UT_fixed_lock_queue_trivial_constructors(const char* params) { Lumix::DefaultAllocator allocator; Queue queue; TestTaskPodConsumer testTaskPodConsumer(&queue, allocator); testTaskPodConsumer.create("TestTaskPodConsumer_Task"); testTaskPodConsumer.run(); const int RUN_COUNT = 512; for (int i = 0; i < RUN_COUNT; i++) { Test* test = queue.alloc(true); queue.push(test, true); } while (!queue.isEmpty()) { Lumix::MT::yield(); } queue.abort(); testTaskPodConsumer.destroy(); LUMIX_EXPECT_EQ(8448, testTaskPodConsumer.getSum()); }; } REGISTER_TEST("unit_tests/core/multi_thread/fixed_lock_queue_non_trivial_constructors", UT_fixed_lock_queue_non_trivial_constructors, ""); REGISTER_TEST("unit_tests/core/multi_thread/fixed_lock_queue_trivial_constructors", UT_fixed_lock_queue_trivial_constructors, "");<commit_msg>removed unit test which is not relevant anymore<commit_after>#include "unit_tests/suite/lumix_unit_tests.h" #include "core/mt/lock_free_fixed_queue.h" #include "core/mt/task.h" #include "core/mt/thread.h" namespace { struct Test { Test() : value(1) {} ~Test() { value = 2; } int32 value; }; typedef Lumix::MT::LockFreeFixedQueue<Test, 16> Queue; class TestTaskConsumer : public Lumix::MT::Task { public: TestTaskConsumer(Queue* queue, Lumix::IAllocator& allocator) : Lumix::MT::Task(allocator) , m_queue(queue) , m_sum(0) {} ~TestTaskConsumer() {} int task() { while (!m_queue->isAborted()) { Test* test = m_queue->pop(true); if (NULL == test) break; m_sum += test->value; test->value++; m_queue->dealoc(test); } return 0; } int32 getSum() { return m_sum; } private: Queue* m_queue; int32 m_sum; }; void UT_fixed_lock_queue(const char* params) { Lumix::DefaultAllocator allocator; Queue queue; TestTaskConsumer testTaskConsumer(&queue, allocator); testTaskConsumer.create("TestTaskConsumer_Task"); testTaskConsumer.run(); const int RUN_COUNT = 512; for (int i = 0; i < RUN_COUNT; i++) { Test* test = queue.alloc(true); queue.push(test, true); } while (!queue.isEmpty()) { Lumix::MT::yield(); } queue.abort(); testTaskConsumer.destroy(); LUMIX_EXPECT_EQ(RUN_COUNT, testTaskConsumer.getSum()); }; } REGISTER_TEST("unit_tests/core/multi_thread/fixed_lock_queue", UT_fixed_lock_queue, ""); <|endoftext|>
<commit_before>/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include <Windows.h> #include <cassert> #include <cfgmgr32.h> #include <devpkey.h> #include <devguid.h> #include <iostream> #include <sstream> #include <string> namespace loader { std::vector<DriverLibraryPath> discoverDriversBasedOnDisplayAdapters(); std::vector<DriverLibraryPath> discoverEnabledDrivers() { DWORD envBufferSize = 65535; std::string altDrivers; altDrivers.resize(envBufferSize); // ZE_ENABLE_ALT_DRIVERS is for development/debug only envBufferSize = GetEnvironmentVariable("ZE_ENABLE_ALT_DRIVERS", &altDrivers[0], envBufferSize); if (!envBufferSize) { return discoverDriversBasedOnDisplayAdapters(); } else { std::vector<DriverLibraryPath> enabledDrivers; std::stringstream ss(altDrivers.c_str()); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } return enabledDrivers; } } bool isDeviceAvailable(DEVINST devnode) { ULONG devStatus = {}; ULONG devProblem = {}; auto configErr = CM_Get_DevNode_Status(&devStatus, &devProblem, devnode, 0); if (CR_SUCCESS != configErr) { assert(false && "CM_Get_DevNode_Status failed"); return false; } bool isInInvalidState = (devStatus & DN_HAS_PROBLEM) && (devProblem == CM_PROB_NEED_RESTART); isInInvalidState |= (DN_NEED_RESTART == (devStatus & DN_NEED_RESTART)); isInInvalidState |= (devStatus & DN_HAS_PROBLEM) && (devProblem == CM_PROB_DISABLED); return false == isInInvalidState; } DriverLibraryPath readDriverPathForDisplayAdapter(DEVINST dnDevNode) { static constexpr char levelZeroDriverPathKey[] = "LevelZeroDriverPath"; HKEY hkey = {}; CONFIGRET configErr = CM_Open_DevNode_Key(dnDevNode, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hkey, CM_REGISTRY_SOFTWARE); if (CR_SUCCESS != configErr) { assert(false && "CM_Open_DevNode_Key failed"); return ""; } DWORD regValueType = {}; DWORD pathSize = {}; LSTATUS regOpStatus = RegQueryValueExA(hkey, levelZeroDriverPathKey, NULL, &regValueType, NULL, &pathSize); std::string driverPath; if ((ERROR_SUCCESS == regOpStatus) && (REG_SZ == regValueType)) { driverPath.resize(pathSize); regOpStatus = RegQueryValueExA(hkey, levelZeroDriverPathKey, NULL, &regValueType, (LPBYTE) & *driverPath.begin(), &pathSize); if (ERROR_SUCCESS != regOpStatus) { assert(false && "RegQueryValueExA failed"); driverPath.clear(); } } regOpStatus = RegCloseKey(hkey); assert((ERROR_SUCCESS == regOpStatus) && "RegCloseKey failed"); return driverPath; } std::wstring readDisplayAdaptersDeviceIdsList() { OLECHAR displayGuidStr[MAX_GUID_STRING_LEN]; int strFromGuidErr = StringFromGUID2(GUID_DEVCLASS_DISPLAY, displayGuidStr, MAX_GUID_STRING_LEN); if (MAX_GUID_STRING_LEN != strFromGuidErr) { assert(false && "StringFromGUID2 failed"); return L""; } std::wstring deviceIdList; CONFIGRET getDeviceIdListErr = CR_BUFFER_SMALL; while (CR_BUFFER_SMALL == getDeviceIdListErr) { ULONG deviceIdListSize = {}; ULONG deviceIdListFlags = CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT; auto getDeviceIdListSizeErr = CM_Get_Device_ID_List_SizeW(&deviceIdListSize, displayGuidStr, deviceIdListFlags); if (CR_SUCCESS != getDeviceIdListSizeErr) { assert(false && "CM_Get_Device_ID_List_size failed"); break; } deviceIdList.resize(deviceIdListSize); getDeviceIdListErr = CM_Get_Device_ID_ListW(displayGuidStr, &*deviceIdList.begin(), deviceIdListSize, deviceIdListFlags); } return deviceIdList; } std::vector<DriverLibraryPath> discoverDriversBasedOnDisplayAdapters() { std::vector<DriverLibraryPath> enabledDrivers; auto deviceIdList = readDisplayAdaptersDeviceIdsList(); if (deviceIdList.empty()) { return enabledDrivers; } auto isNotDeviceListEnd = [](wchar_t *it) { return '\0' != it[0]; }; auto getNextDeviceInList = [](wchar_t *it) { return it + wcslen(it) + 1; }; auto deviceIdIt = &*deviceIdList.begin(); for (; isNotDeviceListEnd(deviceIdIt); deviceIdIt = getNextDeviceInList(deviceIdIt)) { DEVINST devinst = {}; if (CR_SUCCESS != CM_Locate_DevNodeW(&devinst, deviceIdIt, 0)) { assert(false && "CM_Locate_DevNodeW failed"); continue; } if (false == isDeviceAvailable(devinst)) { continue; } auto driverPath = readDriverPathForDisplayAdapter(devinst); if (driverPath.empty()) { continue; } bool alreadyOnTheList = (enabledDrivers.end() != std::find(enabledDrivers.begin(), enabledDrivers.end(), driverPath)); if (alreadyOnTheList) { continue; } enabledDrivers.push_back(std::move(driverPath)); } return enabledDrivers; } } // namespace loader <commit_msg>Enumerate Compute Accelerators<commit_after>/* * * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "source/loader/driver_discovery.h" #include <Windows.h> #include <cassert> #include <cfgmgr32.h> #include <devpkey.h> #include <devguid.h> #include <iostream> #include <sstream> #include <string> namespace loader { std::vector<DriverLibraryPath> discoverDriversBasedOnDisplayAdapters(const GUID rguid); std::vector<DriverLibraryPath> discoverEnabledDrivers() { std::vector<DriverLibraryPath> enabledDrivers; DWORD envBufferSize = 65535; std::string altDrivers; altDrivers.resize(envBufferSize); // ZE_ENABLE_ALT_DRIVERS is for development/debug only envBufferSize = GetEnvironmentVariable("ZE_ENABLE_ALT_DRIVERS", &altDrivers[0], envBufferSize); if (!envBufferSize) { auto displayDrivers = discoverDriversBasedOnDisplayAdapters(GUID_DEVCLASS_DISPLAY); auto computeDrivers = discoverDriversBasedOnDisplayAdapters(GUID_DEVCLASS_COMPUTEACCELERATOR); enabledDrivers.insert(enabledDrivers.end(), displayDrivers.begin(), displayDrivers.end()); enabledDrivers.insert(enabledDrivers.end(), computeDrivers.begin(), computeDrivers.end()); } else { std::stringstream ss(altDrivers.c_str()); while (ss.good()) { std::string substr; getline(ss, substr, ','); enabledDrivers.emplace_back(substr); } } return enabledDrivers; } bool isDeviceAvailable(DEVINST devnode) { ULONG devStatus = {}; ULONG devProblem = {}; auto configErr = CM_Get_DevNode_Status(&devStatus, &devProblem, devnode, 0); if (CR_SUCCESS != configErr) { assert(false && "CM_Get_DevNode_Status failed"); return false; } bool isInInvalidState = (devStatus & DN_HAS_PROBLEM) && (devProblem == CM_PROB_NEED_RESTART); isInInvalidState |= (DN_NEED_RESTART == (devStatus & DN_NEED_RESTART)); isInInvalidState |= (devStatus & DN_HAS_PROBLEM) && (devProblem == CM_PROB_DISABLED); return false == isInInvalidState; } DriverLibraryPath readDriverPathForDisplayAdapter(DEVINST dnDevNode) { static constexpr char levelZeroDriverPathKey[] = "LevelZeroDriverPath"; HKEY hkey = {}; CONFIGRET configErr = CM_Open_DevNode_Key(dnDevNode, KEY_QUERY_VALUE, 0, RegDisposition_OpenExisting, &hkey, CM_REGISTRY_SOFTWARE); if (CR_SUCCESS != configErr) { assert(false && "CM_Open_DevNode_Key failed"); return ""; } DWORD regValueType = {}; DWORD pathSize = {}; LSTATUS regOpStatus = RegQueryValueExA(hkey, levelZeroDriverPathKey, NULL, &regValueType, NULL, &pathSize); std::string driverPath; if ((ERROR_SUCCESS == regOpStatus) && (REG_SZ == regValueType)) { driverPath.resize(pathSize); regOpStatus = RegQueryValueExA(hkey, levelZeroDriverPathKey, NULL, &regValueType, (LPBYTE) & *driverPath.begin(), &pathSize); if (ERROR_SUCCESS != regOpStatus) { assert(false && "RegQueryValueExA failed"); driverPath.clear(); } } regOpStatus = RegCloseKey(hkey); assert((ERROR_SUCCESS == regOpStatus) && "RegCloseKey failed"); return driverPath; } std::wstring readDisplayAdaptersDeviceIdsList(const GUID rguid) { OLECHAR displayGuidStr[MAX_GUID_STRING_LEN]; int strFromGuidErr = StringFromGUID2(rguid, displayGuidStr, MAX_GUID_STRING_LEN); if (MAX_GUID_STRING_LEN != strFromGuidErr) { assert(false && "StringFromGUID2 failed"); return L""; } std::wstring deviceIdList; CONFIGRET getDeviceIdListErr = CR_BUFFER_SMALL; while (CR_BUFFER_SMALL == getDeviceIdListErr) { ULONG deviceIdListSize = {}; ULONG deviceIdListFlags = CM_GETIDLIST_FILTER_CLASS | CM_GETIDLIST_FILTER_PRESENT; auto getDeviceIdListSizeErr = CM_Get_Device_ID_List_SizeW(&deviceIdListSize, displayGuidStr, deviceIdListFlags); if (CR_SUCCESS != getDeviceIdListSizeErr) { assert(false && "CM_Get_Device_ID_List_size failed"); break; } deviceIdList.resize(deviceIdListSize); getDeviceIdListErr = CM_Get_Device_ID_ListW(displayGuidStr, &*deviceIdList.begin(), deviceIdListSize, deviceIdListFlags); } return deviceIdList; } std::vector<DriverLibraryPath> discoverDriversBasedOnDisplayAdapters(const GUID rguid) { std::vector<DriverLibraryPath> enabledDrivers; auto deviceIdList = readDisplayAdaptersDeviceIdsList(rguid); if (deviceIdList.empty()) { return enabledDrivers; } auto isNotDeviceListEnd = [](wchar_t *it) { return '\0' != it[0]; }; auto getNextDeviceInList = [](wchar_t *it) { return it + wcslen(it) + 1; }; auto deviceIdIt = &*deviceIdList.begin(); for (; isNotDeviceListEnd(deviceIdIt); deviceIdIt = getNextDeviceInList(deviceIdIt)) { DEVINST devinst = {}; if (CR_SUCCESS != CM_Locate_DevNodeW(&devinst, deviceIdIt, 0)) { assert(false && "CM_Locate_DevNodeW failed"); continue; } if (false == isDeviceAvailable(devinst)) { continue; } auto driverPath = readDriverPathForDisplayAdapter(devinst); if (driverPath.empty()) { continue; } bool alreadyOnTheList = (enabledDrivers.end() != std::find(enabledDrivers.begin(), enabledDrivers.end(), driverPath)); if (alreadyOnTheList) { continue; } enabledDrivers.push_back(std::move(driverPath)); } return enabledDrivers; } } // namespace loader <|endoftext|>
<commit_before>#include "SysConfig.h" #if(HAS_STD_LIGHTS) // Includes #include <Arduino.h> #include "CLights.h" #include "NCommManager.h" namespace { // 1% per 10ms const float kPowerDelta = 0.01f; inline uint32_t PercentToAnalog( float x ) { if( x < 0.0f ) { return 0; } else if( x < 0.33f ) { // Linear region, 0-80 return static_cast<uint32_t>( 242.424f * x ); } else { // Parabolic region 80-255 return static_cast<uint32_t>( ( 308.571f * x * x ) - ( 147.426f * x ) + 95.0f ); } } } CLights::CLights( uint32_t pinIn ) : m_pin( pinIn, CPin::kAnalog, CPin::kOutput ) { } void CLights::Initialize() { // Reset pin m_pin.Reset(); m_pin.Write( 0 ); // Reset timers m_controlTimer.Reset(); m_telemetryTimer.Reset(); } void CLights::Update( CCommand& commandIn ) { // Check for messages if( !NCommManager::m_isCommandAvailable ) { return; } // Handle messages if( commandIn.Equals( "lights_tpow" ) ) { // Update the target position m_targetPower = orutil::Decode1K( commandIn.m_arguments[1] ); // TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism // Acknowledge target position Serial.print( F( "lights_tpow:" ) ); Serial.print( commandIn.m_arguments[1] ); Serial.println( ';' ); // Pass through linearization function m_targetPower_an = PercentToAnalog( m_targetPower ); // Apply ceiling if( m_targetPower_an > 255 ) { m_targetPower_an = 255; } // Directly move to target power m_currentPower = m_targetPower; m_currentPower_an = m_targetPower_an; // Write the power value to the pin m_pin.Write( m_currentPower_an ); // Emit current power Serial.print( F( "lights_pow:" ) ); Serial.print( orutil::Encode1K( m_currentPower ) ); Serial.print( ';' ); } } #endif <commit_msg>Added greeting capability to lights module<commit_after>#include "SysConfig.h" #if(HAS_STD_LIGHTS) // Includes #include <Arduino.h> #include "CLights.h" #include "NCommManager.h" namespace { // 1% per 10ms const float kPowerDelta = 0.01f; bool isGreeting = false; bool greetState = false; int greetCycle = 0; const int cycleCount = 6; const int greetDelay_ms = 600; inline uint32_t PercentToAnalog( float x ) { if( x < 0.0f ) { return 0; } else if( x < 0.33f ) { // Linear region, 0-80 return static_cast<uint32_t>( 242.424f * x ); } else { // Parabolic region 80-255 return static_cast<uint32_t>( ( 308.571f * x * x ) - ( 147.426f * x ) + 95.0f ); } } } CLights::CLights( uint32_t pinIn ) : m_pin( pinIn, CPin::kAnalog, CPin::kOutput ) { } void CLights::Initialize() { // Reset pin m_pin.Reset(); m_pin.Write( 0 ); // Reset timers m_controlTimer.Reset(); m_telemetryTimer.Reset(); } void CLights::Update( CCommand& commandIn ) { // Check for messages if( !NCommManager::m_isCommandAvailable ) { return; } // Handle messages if( commandIn.Equals( "lights_tpow" ) ) { // Update the target position m_targetPower = orutil::Decode1K( commandIn.m_arguments[1] ); // TODO: Ideally this unit would have the ability to autonomously set its own target and ack receipt with a separate mechanism // Acknowledge target position Serial.print( F( "lights_tpow:" ) ); Serial.print( commandIn.m_arguments[1] ); Serial.println( ';' ); // Pass through linearization function m_targetPower_an = PercentToAnalog( m_targetPower ); // Apply ceiling if( m_targetPower_an > 255 ) { m_targetPower_an = 255; } // Directly move to target power m_currentPower = m_targetPower; m_currentPower_an = m_targetPower_an; // Write the power value to the pin m_pin.Write( m_currentPower_an ); // Emit current power Serial.print( F( "lights_pow:" ) ); Serial.print( orutil::Encode1K( m_currentPower ) ); Serial.print( ';' ); } else if( command.Equals( "wake" ) ) { // Set greeting state to true and reset timer isGreeting = true; m_controlTimer.Reset(); // Set light state to off greetState = false; m_pin.Write( 0 ); } if( isGreeting ) { if( controltime.HasElapsed( greetDelay_ms ) ) { // Set to opposite state if( greetState ) { greetState = false; m_pin.Write( 0 ); } else { greetState = true; m_pin.Write( 1 ); } greetCycle++; if( greetCycle >= cycleCount ) { // Done blinking isGreeting = false; // Reset pin back to its original value m_pin.Write( m_currentPower_an ); } } } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tools.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2005-03-10 13:56:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SLIDESHOW_TOOLS_HXX #define _SLIDESHOW_TOOLS_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #ifndef _BGFX_RANGE_B2DRECTANGLE_HXX #include <basegfx/range/b2drectangle.hxx> #endif #ifndef _BGFX_TUPLE_B2DTUPLE_HXX #include <basegfx/tuple/b2dtuple.hxx> #endif #ifndef _BGFX_VECTOR_B2DSIZE_HXX #include <basegfx/vector/b2dsize.hxx> #endif #ifndef BOOST_BIND_HPP_INCLUDED #include <boost/bind.hpp> #endif #ifndef BOOST_SHARED_PTR_HPP_INCLUDED #include <boost/shared_ptr.hpp> #endif #include <shapeattributelayer.hxx> #include <string.h> // for strcmp #include <algorithm> #include <shape.hxx> #include <rgbcolor.hxx> #include <hslcolor.hxx> #include <layermanager.hxx> #include "boost/optional.hpp" #include <cstdlib> namespace com { namespace sun { namespace star { namespace beans { struct NamedValue; } } } } /* Definition of some animation tools */ namespace presentation { namespace internal { // Value extraction from Any // ========================= /// extract unary double value from Any bool extractValue( double& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract enum/constant group value from Any bool extractValue( sal_Int16& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract color value from Any bool extractValue( RGBColor& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract color value from Any bool extractValue( HSLColor& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract plain string from Any bool extractValue( ::rtl::OUString& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract bool value from Any bool extractValue( bool& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract double 2-tuple from Any bool extractValue( ::basegfx::B2DTuple& o_rPair, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /** Search a sequence of NamedValues for a given element. @return true, if the sequence contains the specified element. */ bool findNamedValue( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rSequence, const ::com::sun::star::beans::NamedValue& rSearchKey ); /** Search a sequence of NamedValues for an element with a given name. @param o_pRet If non-NULL, receives the full NamedValue found (if it was found, that is). @return true, if the sequence contains the specified element. */ bool findNamedValue( ::com::sun::star::beans::NamedValue* o_pRet, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rSequence, const ::rtl::OUString& rSearchString ); template< typename ValueType > class ValueMap { public: struct MapEntry { const char* maKey; ValueType maValue; }; ValueMap( const MapEntry* pMap, ::std::size_t nEntries, bool bCaseSensitive ) : mpMap( pMap ), mnEntries( nEntries ), mbCaseSensitive( bCaseSensitive ) { #ifdef DBG_UTIL // Ensure that map entries are sorted (and all lowercase, if this // map is case insensitive) const ::rtl::OString aStr( pMap->maKey ); if( !mbCaseSensitive && aStr != aStr.toAsciiLowerCase() ) { OSL_TRACE("ValueMap::ValueMap(): Key %s is not lowercase", pMap->maKey); OSL_ENSURE( false, "ValueMap::ValueMap(): Key is not lowercase" ); } if( mnEntries > 1 ) { for( ::std::size_t i=0; i<mnEntries-1; ++i, ++pMap ) { if( !mapComparator(pMap[0], pMap[1]) && mapComparator(pMap[1], pMap[0]) ) { OSL_TRACE("ValueMap::ValueMap(): Map is not sorted, keys %s and %s are wrong", pMap[0].maKey, pMap[1].maKey); OSL_ENSURE( false, "ValueMap::ValueMap(): Map is not sorted" ); } const ::rtl::OString aStr( pMap[1].maKey ); if( !mbCaseSensitive && aStr != aStr.toAsciiLowerCase() ) { OSL_TRACE("ValueMap::ValueMap(): Key %s is not lowercase", pMap[1].maKey); OSL_ENSURE( false, "ValueMap::ValueMap(): Key is not lowercase" ); } } } #endif } bool lookup( const ::rtl::OUString& rName, ValueType& o_rResult ) const { // rName is required to contain only ASCII characters. // TODO(Q1): Enforce this at upper layers ::rtl::OString aKey( ::rtl::OUStringToOString( mbCaseSensitive ? rName : rName.toAsciiLowerCase(), RTL_TEXTENCODING_ASCII_US ) ); MapEntry aSearchKey = { aKey.getStr(), ValueType() }; const MapEntry* pRes; const MapEntry* pEnd = mpMap+mnEntries; if( (pRes=::std::lower_bound( mpMap, pEnd, aSearchKey, &mapComparator )) != pEnd ) { // place to _insert before_ found - is it equal to // the search key? if( strcmp( pRes->maKey, aSearchKey.maKey ) == 0 ) { // yep, correct entry found o_rResult = pRes->maValue; return true; } } // not found return false; } private: static bool mapComparator( const MapEntry& rLHS, const MapEntry& rRHS ) { return strcmp( rLHS.maKey, rRHS.maKey ) < 0; } const MapEntry* mpMap; ::std::size_t mnEntries; bool mbCaseSensitive; }; inline ::basegfx::B2DRectangle calcRelativeShapeBounds( const ::basegfx::B2DRectangle& rPageBounds, const ::basegfx::B2DRectangle& rShapeBounds ) { return ::basegfx::B2DRectangle( rShapeBounds.getMinX() / rPageBounds.getWidth(), rShapeBounds.getMinY() / rPageBounds.getHeight(), rShapeBounds.getMaxX() / rPageBounds.getWidth(), rShapeBounds.getMaxY() / rPageBounds.getHeight() ); } /** Get the shape transformation from the attribute set @param rBounds Shape bound rect @param pAttr Attribute set. Might be NULL @param bWithTranslation Whether the transformation should contain translation to shape output position, or not (e.g. for sprites) */ ::basegfx::B2DHomMatrix getShapeTransformation( const ::basegfx::B2DRectangle& rOrigBounds, const ::basegfx::B2DRectangle& rBounds, const ShapeAttributeLayerSharedPtr& pAttr, bool bWithTranslation ); /** Calc update area for a shape. This method calculates the 'covered' area for the shape, i.e. the rectangle that is affected when rendering the shape. @param rShapeBounds Bound rect of the shape (without any transformations taken into account). @param rShapeTransform Transformation matrix the shape should undergo. @param pAttr Current shape attributes */ ::basegfx::B2DRectangle getShapeUpdateArea( const ::basegfx::B2DRectangle& rShapeBounds, const ::basegfx::B2DHomMatrix& rShapeTransform, const ShapeAttributeLayerSharedPtr& pAttr ); /** Convert a plain UNO API 32 bit int to RGBColor */ RGBColor unoColor2RGBColor( sal_Int32 ); /// Gets a random ordinal [0,n) inline ::std::size_t getRandomOrdinal( const ::std::size_t n ) { return static_cast< ::std::size_t >( double(n) * rand() / (RAND_MAX + 1.0) ); } /// To work around ternary operator in initializer lists /// (Solaris compiler problems) template <typename T> inline T const & ternary_op( const bool cond, T const & arg1, T const & arg2 ) { if (cond) return arg1; else return arg2; } } } #endif /* _SLIDESHOW_TOOLS_HXX */ <commit_msg>INTEGRATION: CWS presfixes03 (1.3.10); FILE MERGED 2005/04/11 17:42:36 thb 1.3.10.2: #i36190# #i44807# Implemented reduction of subset animations to the actual subset bounding box: relegated some common code to tools.cxx; completely overhauled viewshape.cxx; removed duplicate subset vector entry from DrawShapeSubsetting; corrected auto-reverse mode (fixed broken 'put on the brakes' effect); fixed AnimationSetNode deactivate behaviour (made the sequence activate->process activity->deactivate explicit (was by chance before and currently actually broken)) 2005/04/01 16:34:27 thb 1.3.10.1: #i46224# Now rendering OLE and graphic shapes as bitmaps (even if they are metafiles); Fixed the extra white line around slides problem by clearing the slide bitmap first black (full size), and then white, but one pixel smaller.<commit_after>/************************************************************************* * * $RCSfile: tools.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2005-04-18 09:52:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SLIDESHOW_TOOLS_HXX #define _SLIDESHOW_TOOLS_HXX #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX #include <basegfx/matrix/b2dhommatrix.hxx> #endif #ifndef _BGFX_RANGE_B2DRECTANGLE_HXX #include <basegfx/range/b2drectangle.hxx> #endif #ifndef _BGFX_TUPLE_B2DTUPLE_HXX #include <basegfx/tuple/b2dtuple.hxx> #endif #ifndef _BGFX_VECTOR_B2DSIZE_HXX #include <basegfx/vector/b2dsize.hxx> #endif #ifndef BOOST_BIND_HPP_INCLUDED #include <boost/bind.hpp> #endif #ifndef BOOST_SHARED_PTR_HPP_INCLUDED #include <boost/shared_ptr.hpp> #endif #include <shapeattributelayer.hxx> #include <string.h> // for strcmp #include <algorithm> #include <shape.hxx> #include <rgbcolor.hxx> #include <hslcolor.hxx> #include <layermanager.hxx> #include "boost/optional.hpp" #include <cstdlib> namespace com { namespace sun { namespace star { namespace beans { struct NamedValue; } } } } /* Definition of some animation tools */ namespace presentation { namespace internal { // Value extraction from Any // ========================= /// extract unary double value from Any bool extractValue( double& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract enum/constant group value from Any bool extractValue( sal_Int16& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract color value from Any bool extractValue( RGBColor& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract color value from Any bool extractValue( HSLColor& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract plain string from Any bool extractValue( ::rtl::OUString& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract bool value from Any bool extractValue( bool& o_rValue, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /// extract double 2-tuple from Any bool extractValue( ::basegfx::B2DTuple& o_rPair, const ::com::sun::star::uno::Any& rSourceAny, const ShapeSharedPtr& rShape, const LayerManagerSharedPtr& rLayerManager ); /** Search a sequence of NamedValues for a given element. @return true, if the sequence contains the specified element. */ bool findNamedValue( ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rSequence, const ::com::sun::star::beans::NamedValue& rSearchKey ); /** Search a sequence of NamedValues for an element with a given name. @param o_pRet If non-NULL, receives the full NamedValue found (if it was found, that is). @return true, if the sequence contains the specified element. */ bool findNamedValue( ::com::sun::star::beans::NamedValue* o_pRet, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rSequence, const ::rtl::OUString& rSearchString ); template< typename ValueType > class ValueMap { public: struct MapEntry { const char* maKey; ValueType maValue; }; ValueMap( const MapEntry* pMap, ::std::size_t nEntries, bool bCaseSensitive ) : mpMap( pMap ), mnEntries( nEntries ), mbCaseSensitive( bCaseSensitive ) { #ifdef DBG_UTIL // Ensure that map entries are sorted (and all lowercase, if this // map is case insensitive) const ::rtl::OString aStr( pMap->maKey ); if( !mbCaseSensitive && aStr != aStr.toAsciiLowerCase() ) { OSL_TRACE("ValueMap::ValueMap(): Key %s is not lowercase", pMap->maKey); OSL_ENSURE( false, "ValueMap::ValueMap(): Key is not lowercase" ); } if( mnEntries > 1 ) { for( ::std::size_t i=0; i<mnEntries-1; ++i, ++pMap ) { if( !mapComparator(pMap[0], pMap[1]) && mapComparator(pMap[1], pMap[0]) ) { OSL_TRACE("ValueMap::ValueMap(): Map is not sorted, keys %s and %s are wrong", pMap[0].maKey, pMap[1].maKey); OSL_ENSURE( false, "ValueMap::ValueMap(): Map is not sorted" ); } const ::rtl::OString aStr( pMap[1].maKey ); if( !mbCaseSensitive && aStr != aStr.toAsciiLowerCase() ) { OSL_TRACE("ValueMap::ValueMap(): Key %s is not lowercase", pMap[1].maKey); OSL_ENSURE( false, "ValueMap::ValueMap(): Key is not lowercase" ); } } } #endif } bool lookup( const ::rtl::OUString& rName, ValueType& o_rResult ) const { // rName is required to contain only ASCII characters. // TODO(Q1): Enforce this at upper layers ::rtl::OString aKey( ::rtl::OUStringToOString( mbCaseSensitive ? rName : rName.toAsciiLowerCase(), RTL_TEXTENCODING_ASCII_US ) ); MapEntry aSearchKey = { aKey.getStr(), ValueType() }; const MapEntry* pRes; const MapEntry* pEnd = mpMap+mnEntries; if( (pRes=::std::lower_bound( mpMap, pEnd, aSearchKey, &mapComparator )) != pEnd ) { // place to _insert before_ found - is it equal to // the search key? if( strcmp( pRes->maKey, aSearchKey.maKey ) == 0 ) { // yep, correct entry found o_rResult = pRes->maValue; return true; } } // not found return false; } private: static bool mapComparator( const MapEntry& rLHS, const MapEntry& rRHS ) { return strcmp( rLHS.maKey, rRHS.maKey ) < 0; } const MapEntry* mpMap; ::std::size_t mnEntries; bool mbCaseSensitive; }; inline ::basegfx::B2DRectangle calcRelativeShapeBounds( const ::basegfx::B2DRectangle& rPageBounds, const ::basegfx::B2DRectangle& rShapeBounds ) { return ::basegfx::B2DRectangle( rShapeBounds.getMinX() / rPageBounds.getWidth(), rShapeBounds.getMinY() / rPageBounds.getHeight(), rShapeBounds.getMaxX() / rPageBounds.getWidth(), rShapeBounds.getMaxY() / rPageBounds.getHeight() ); } /** Get the shape transformation from the attribute set @param rBounds Original shape bound rect (to substitute default attribute layer values) @param pAttr Attribute set. Might be NULL (then, rBounds is used to set a simple scale and translate of the unit rect to rBounds). */ ::basegfx::B2DHomMatrix getShapeTransformation( const ::basegfx::B2DRectangle& rBounds, const ShapeAttributeLayerSharedPtr& pAttr ); /** Get a shape's sprite transformation from the attribute set @param rPixelSize Pixel size of the sprite @param rOrigSize Original shape size (i.e. the size of the actual sprite content, in the user coordinate system) @param pAttr Attribute set. Might be NULL (then, rBounds is used to set a simple scale and translate of the unit rect to rBounds). @return the transformation to be applied to the sprite. */ ::basegfx::B2DHomMatrix getSpriteTransformation( const ::basegfx::B2DSize& rPixelSize, const ::basegfx::B2DSize& rOrigSize, const ShapeAttributeLayerSharedPtr& pAttr ); /** Calc update area for a shape. This method calculates the 'covered' area for the shape, i.e. the rectangle that is affected when rendering the shape. Apart from applying the given transformation to the shape rectangle, this method also takes attributes into account, which further scale the output (e.g. character sizes). @param rUnitBounds Shape bounds, in the unit rect coordinate space @param rShapeTransform Transformation matrix the shape should undergo. @param pAttr Current shape attributes */ ::basegfx::B2DRectangle getShapeUpdateArea( const ::basegfx::B2DRectangle& rUnitBounds, const ::basegfx::B2DHomMatrix& rShapeTransform, const ShapeAttributeLayerSharedPtr& pAttr ); /** Calc update area for a shape. This method calculates the 'covered' area for the shape, i.e. the rectangle that is affected when rendering the shape. The difference from the other getShapeUpdateArea() method is the fact that this one works without ShapeAttributeLayer, and only scales up the given shape user coordinate bound rect. The method is typically used to retrieve user coordinate system bound rects for shapes which are smaller than the default unit bound rect (because e.g. of subsetting) @param rUnitBounds Shape bounds, in the unit rect coordinate space @param rShapeBounds Current shape bounding box in user coordinate space. */ ::basegfx::B2DRectangle getShapeUpdateArea( const ::basegfx::B2DRectangle& rUnitBounds, const ::basegfx::B2DRectangle& rShapeBounds ); /** Calc output position and size of shape, according to given attribute layer. Rotations, shears etc. and not taken into account, i.e. the returned rectangle is NOT the bounding box. Use it as if aBounds.getMinimum() is the output position and aBounds.getRange() the scaling of the shape. */ ::basegfx::B2DRectangle getShapePosSize( const ::basegfx::B2DRectangle& rOrigBounds, const ShapeAttributeLayerSharedPtr& pAttr ); /** Convert a plain UNO API 32 bit int to RGBColor */ RGBColor unoColor2RGBColor( sal_Int32 ); /** Init canvas with default background (white) */ void initSlideBackground( const ::cppcanvas::CanvasSharedPtr& rCanvas, const ::basegfx::B2ISize& rSize ); /// Gets a random ordinal [0,n) inline ::std::size_t getRandomOrdinal( const ::std::size_t n ) { return static_cast< ::std::size_t >( double(n) * rand() / (RAND_MAX + 1.0) ); } /// To work around ternary operator in initializer lists /// (Solaris compiler problems) template <typename T> inline T const & ternary_op( const bool cond, T const & arg1, T const & arg2 ) { if (cond) return arg1; else return arg2; } } } #endif /* _SLIDESHOW_TOOLS_HXX */ <|endoftext|>
<commit_before>#include <Arduino.h> #include <SPI.h> #include <math.h> #include "Heater.h" // E0 Main extruder const int E0_enable = 26; // low == enabled const int E0_step = 34; const int E0_dir = 43; const int E0_MS1 = 65; const int E0_MS2 = 66; const int E0_digipot_channel = 0; const float E0_steps_per_mm = 38.197; const int E0_heater_pin = 9; const int E0_digipot_setting = 100; const bool E0_EXTRUDE = 0; const bool E0_RETRACT = 1; const int E0_thermistor = 0; const int BETA_NOZZLE = 4267; // Semitec 104GT-2 Thermistor const long R_ZERO = 100000; // Resistance at 25C const int E0_SAMPLE_TIME = 500; // milliseconds const int LED_PIN = 13; const int MINIMUM_VELOCITY = 10; // Based on testing the motor does not perfrom // When moving slower than this const int MAX_VELOCITY = 10430; // 0.3183 increments/cycle * 2^15 = 10430 const int MAX_ACCELERATION = 3; // From testing any value higher than 4 doesn't work reliably const float VELOCITY_CONVERSION = 2.0861; // The desired speed in mm/min * EXTRDUER_CONVERSION // puts us into increment math const int MM_TO_STEPS = 38.197; // mm of extrusion * MM_TO_STEPS gives you the // the required number of steps to move that many mm. const int PROGRAM_FEED_RATE = 30 * VELOCITY_CONVERSION; const int MANUAL_EX_RATE = 75 * VELOCITY_CONVERSION; int E0_acceleration = 0; int E0_velocity = 0; signed int E0_position = 0; int target_velocity = 0; unsigned long motor_test_time = 0; int micro_step_scale = 1; // The micro step scale can be 1, 2, 4, or 16 based on // the stepper driver data sheet // Digipot const int slave_select_pin = 38; // Fans const int small_fan = 5; const int large_fan = 8; unsigned long last_fan_time = 0; const int FAN_SAMPLE_TIME = 2000; // Bed Heater const int bed_heater_pin = 3; const int BETA_BED = 3950; // Not sure this is correct const int bed_thermistor = 1; const int bed_sample_time = 1000; // milliseconds Heater bed_heater(bed_heater_pin, bed_thermistor, BETA_BED, R_ZERO, bed_sample_time, "Bed"); // Nozzle Heater Heater E0_heater(E0_heater_pin, E0_thermistor, BETA_NOZZLE, R_ZERO, E0_SAMPLE_TIME, "E0"); const int NOZZLE_TEMP = 220; // Hard coded temp in C for nozzle const int BED_TEMP = 70; // Hard coded temp in C for bed // betweenLayerRetract const int retract_dist = 4*MM_TO_STEPS; // retract this many steps between layers long num_steps = 0; bool bet_layer_retract_done = true; bool prev_bet_layer_retract = true; bool S_retract = 0, S_between_layer = 0, S_extrude = 0, S_wait = 0, S_printing = 0, S_manual_extrude = 0, S_ALL_STOP = 0, S0 = 1, D1 = 0, D2 = 0, D3 = 0; int direction = 0; String currState = ""; // Inputs from robot const int MAN_EXTRUDE = 84, HEAT_BED = 83, HEAT_NOZZLE = 82, PROG_FEED = 81, BETWEEN_LAYER_RETRACT = 80, ALL_STOP = 79; bool man_extrude, heat_bed, heat_nozzle, prog_feed, between_layer_retract, all_stop; // Outputs to robot const int BED_AT_TEMP = 71, NOZZLE_AT_TEMP = 72; // Report unsigned long last_report_time = 0; void setup() { // put your setup code here, to run once: pinMode(E0_enable, OUTPUT); pinMode(E0_step, OUTPUT); pinMode(E0_dir, OUTPUT); pinMode(E0_MS1, OUTPUT); pinMode(E0_MS2, OUTPUT); pinMode(slave_select_pin, OUTPUT); pinMode(small_fan, OUTPUT); pinMode(large_fan, OUTPUT); // Inputs from robot pinMode(MAN_EXTRUDE, INPUT_PULLUP); pinMode(HEAT_BED, INPUT_PULLUP); pinMode(HEAT_NOZZLE, INPUT_PULLUP); pinMode(PROG_FEED, INPUT_PULLUP); pinMode(BETWEEN_LAYER_RETRACT, INPUT_PULLUP); pinMode(ALL_STOP, INPUT_PULLUP); // Outputs to robot pinMode(BED_AT_TEMP, OUTPUT); pinMode(NOZZLE_AT_TEMP, OUTPUT); pinMode(LED_PIN, OUTPUT); Serial.begin(9600); /* The Rambo board has programmable potentiometers or 'digipots' for tuning each individual stepper motor. the following code handles that */ SPI.begin(); digitalWrite(slave_select_pin, LOW); SPI.transfer(E0_digipot_channel); SPI.transfer(E0_digipot_setting); SPI.end(); digitalWrite(slave_select_pin, HIGH); digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); digitalWrite(E0_dir, LOW); E0_heater.setTunings(50, 1, 9); // Initial Nozzle PID parameters E0_heater.setTargetTemp(100); bed_heater.setTunings(50, 0.5, 9); // Initial Bed PID Values bed_heater.setTargetTemp(35); // initialize timer 3 for the stepper motor interrupts noInterrupts(); // clear current bit selections TCCR3A = 0; TCCR3B = 0; TCNT3 = 0; OCR3A = 1600; // compare match register 10kHz TCCR3B |= (1 << WGM12); // CTC mode TCCR3B |= (1 << CS10); // No prescaling TIMSK3 |= (1 << OCIE3A); // enable timer compare interrupt interrupts(); // enable global interupts } /** scaleMicroStep() checks the current commanded velocity and determines if it is within one of the available micro step ranges. Using micro steps enables better lower speed performance and more reliable accelerations from zero. The available micro steps are 1 (full speed) 2, 4, and 16. */ void scaleMicroStep(){ int holdScale = MAX_VELOCITY/abs(E0_velocity); if(holdScale >= 16){ micro_step_scale = 16; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 4){ micro_step_scale = 4; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 2){ micro_step_scale = 2; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, LOW); } else{ micro_step_scale = 1; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); } delayMicroseconds(2); } ISR(TIMER3_COMPA_vect){ noInterrupts(); int velocity_error = target_velocity - E0_velocity; if(abs(target_velocity) < MINIMUM_VELOCITY){ // If we are not supposed to be moving // Note: This code does not decelerate to 0 if target_velocity == 0 E0_velocity = 0; E0_acceleration = 0; } else if(abs(velocity_error)*2 <= MAX_ACCELERATION){ // If we are within 1/2 of an acceleration step of our target velocity then // stop accelerating and assign the target velocity E0_acceleration = 0; E0_velocity = target_velocity; } else if(velocity_error > 0){ // We need to speed up E0_acceleration = MAX_ACCELERATION; } else{ // We need to slow down E0_acceleration = -MAX_ACCELERATION; } E0_velocity += E0_acceleration; if(E0_velocity > MAX_VELOCITY){ E0_velocity = MAX_VELOCITY; } else if(E0_velocity < -MAX_VELOCITY){ E0_velocity = -MAX_VELOCITY; } if(E0_velocity < 0){ // Retract filament digitalWrite(E0_dir, HIGH); } else{ // Extrude filament digitalWrite(E0_dir, LOW); } scaleMicroStep(); E0_position += E0_velocity*micro_step_scale; if(SREG & 0b00001000){ // The third bit in SREG is the overflow flag. If we overflow // Then we know we should increment the stepper E0_position -= 0x8000; // Subtract a 1 in 16bit math digitalWrite(E0_step, HIGH); delayMicroseconds(2); digitalWrite(E0_step, LOW); num_steps += 1; } if(target_velocity - E0_velocity > MAX_ACCELERATION){ E0_acceleration = MAX_ACCELERATION; } else if(E0_velocity - target_velocity > MAX_ACCELERATION){ E0_acceleration = -MAX_ACCELERATION; } else{ E0_acceleration = 0; } interrupts(); } void checkStates(){ man_extrude = !digitalRead(MAN_EXTRUDE); heat_bed = !digitalRead(HEAT_BED); heat_nozzle = !digitalRead(HEAT_NOZZLE); prog_feed = !digitalRead(PROG_FEED); between_layer_retract = !digitalRead(BETWEEN_LAYER_RETRACT); all_stop = !digitalRead(ALL_STOP); S0 = (S0 || D1 || D2 || D3) && !(S_manual_extrude || S_printing); S_manual_extrude = (S_manual_extrude || (S0 && man_extrude)) && !D1; D1 = (D1 || (S_manual_extrude && !man_extrude)) && !S0; S_printing = (S_printing || (S0 && prog_feed) || (S_extrude && (num_steps >= retract_dist))) && !(D2 || S_retract); S_retract = (S_retract || (S_printing && between_layer_retract)) && !S_wait; S_wait = (S_wait || (S_retract && (num_steps >= retract_dist))) && !(S_extrude || D2); S_extrude = (S_extrude || (S_wait && !between_layer_retract)) && !S_printing; D2 = (D2 ||((S_wait || S_printing) && !prog_feed)) && !S0; D3 = (D3 || (S_ALL_STOP && !(prog_feed || heat_bed || heat_nozzle || between_layer_retract || all_stop))) && !S0; S_ALL_STOP = (S_ALL_STOP || all_stop) && !D3; if(S_ALL_STOP){ S0 = 0; S_manual_extrude = 0; D1 = 0; S_printing = 0; S_retract = 0; S_wait = 0; S_extrude = 0; D2 = 0; D3 = 0; E0_heater.setTargetTemp(0); bed_heater.setTargetTemp(0); target_velocity = 0; currState = "ALL_STOP"; } else{ if(S0 && !(S_manual_extrude || S_printing)){ target_velocity = 0; currState = "S0"; } else if(S_manual_extrude && !D1){ target_velocity = 100 * VELOCITY_CONVERSION; // Manual extrude speed currState = "Manul Extrude"; } else if(S_printing && !(D2 || S_retract)){ num_steps = 0; target_velocity = PROGRAM_FEED_RATE; currState = "Printing"; } else if(S_retract && !S_wait){ target_velocity = -MAX_VELOCITY; currState = "Retract"; } else if(S_wait && !(S_extrude || D2)){ num_steps = 0; target_velocity = 0; currState = "Wait"; } else if(S_extrude && !S_printing){ target_velocity = MAX_VELOCITY; currState = "Extrude"; } if(heat_nozzle){ E0_heater.setTargetTemp(190); if(E0_heater.atTemp()){ digitalWrite(NOZZLE_AT_TEMP, HIGH); } else{ digitalWrite(NOZZLE_AT_TEMP, LOW); } } else{ E0_heater.setTargetTemp(0); } if(heat_bed){ bed_heater.setTargetTemp(50); if(bed_heater.atTemp()){ digitalWrite(BED_AT_TEMP, HIGH); } else{ digitalWrite(BED_AT_TEMP, LOW); } } else{ bed_heater.setTargetTemp(0); } } } void setFans(){ /* Tests the current temperature of the nozzle and then turns on the fans if they are above their temperatures. */ unsigned long now = millis(); if(now - last_fan_time > FAN_SAMPLE_TIME){ float currTemp = E0_heater.getCurrTemp(); if (currTemp > 50) { analogWrite(small_fan, 255); } if(currTemp > 180){ analogWrite(large_fan, 255); } last_fan_time = now; } } void report(){ unsigned long now = millis(); if(now - last_report_time > 1000){ Serial.print("velocity target: "); Serial.print(target_velocity); Serial.print("\tE0_velocity: "); Serial.println(E0_velocity); Serial.print("Accel: "); Serial.println(E0_acceleration); Serial.print("Curr State: "); Serial.println(currState); Serial.print("Noz Targ Temp: "); Serial.print(E0_heater.getTargetTemp()); Serial.print("\tCurr Temp: "); Serial.println(E0_heater.getCurrTemp()); Serial.print("Bed Targ Temp: "); Serial.print(bed_heater.getTargetTemp()); Serial.print("\tCurr Temp: "); Serial.print(bed_heater.getCurrTemp()); Serial.print("\tOutput: "); Serial.println(bed_heater.getOutput()); Serial.println(); last_report_time = now; } } void loop() { E0_heater.compute(); bed_heater.compute(); checkStates(); setFans(); report(); } <commit_msg>man_extrude was missing from the state transtion requirements.<commit_after>#include <Arduino.h> #include <SPI.h> #include <math.h> #include "Heater.h" // E0 Main extruder const int E0_enable = 26; // low == enabled const int E0_step = 34; const int E0_dir = 43; const int E0_MS1 = 65; const int E0_MS2 = 66; const int E0_digipot_channel = 0; const float E0_steps_per_mm = 38.197; const int E0_heater_pin = 9; const int E0_digipot_setting = 100; const bool E0_EXTRUDE = 0; const bool E0_RETRACT = 1; const int E0_thermistor = 0; const int BETA_NOZZLE = 4267; // Semitec 104GT-2 Thermistor const long R_ZERO = 100000; // Resistance at 25C const int E0_SAMPLE_TIME = 500; // milliseconds const int LED_PIN = 13; const int MINIMUM_VELOCITY = 10; // Based on testing the motor does not perfrom // When moving slower than this const int MAX_VELOCITY = 10430; // 0.3183 increments/cycle * 2^15 = 10430 const int MAX_ACCELERATION = 3; // From testing any value higher than 4 doesn't work reliably const float VELOCITY_CONVERSION = 2.0861; // The desired speed in mm/min * EXTRDUER_CONVERSION // puts us into increment math const int MM_TO_STEPS = 38.197; // mm of extrusion * MM_TO_STEPS gives you the // the required number of steps to move that many mm. const int PROGRAM_FEED_RATE = 30 * VELOCITY_CONVERSION; const int MANUAL_EX_RATE = 75 * VELOCITY_CONVERSION; int E0_acceleration = 0; int E0_velocity = 0; signed int E0_position = 0; int target_velocity = 0; unsigned long motor_test_time = 0; int micro_step_scale = 1; // The micro step scale can be 1, 2, 4, or 16 based on // the stepper driver data sheet // Digipot const int slave_select_pin = 38; // Fans const int small_fan = 5; const int large_fan = 8; unsigned long last_fan_time = 0; const int FAN_SAMPLE_TIME = 2000; // Bed Heater const int bed_heater_pin = 3; const int BETA_BED = 3950; // Not sure this is correct const int bed_thermistor = 1; const int bed_sample_time = 1000; // milliseconds Heater bed_heater(bed_heater_pin, bed_thermistor, BETA_BED, R_ZERO, bed_sample_time, "Bed"); // Nozzle Heater Heater E0_heater(E0_heater_pin, E0_thermistor, BETA_NOZZLE, R_ZERO, E0_SAMPLE_TIME, "E0"); const int NOZZLE_TEMP = 220; // Hard coded temp in C for nozzle const int BED_TEMP = 70; // Hard coded temp in C for bed // betweenLayerRetract const int retract_dist = 4*MM_TO_STEPS; // retract this many steps between layers long num_steps = 0; bool bet_layer_retract_done = true; bool prev_bet_layer_retract = true; bool S_retract = 0, S_between_layer = 0, S_extrude = 0, S_wait = 0, S_printing = 0, S_manual_extrude = 0, S_ALL_STOP = 0, S0 = 1, D1 = 0, D2 = 0, D3 = 0; int direction = 0; String currState = ""; // Inputs from robot const int MAN_EXTRUDE = 84, HEAT_BED = 83, HEAT_NOZZLE = 82, PROG_FEED = 81, BETWEEN_LAYER_RETRACT = 80, ALL_STOP = 79; bool man_extrude, heat_bed, heat_nozzle, prog_feed, between_layer_retract, all_stop; // Outputs to robot const int BED_AT_TEMP = 71, NOZZLE_AT_TEMP = 72; // Report unsigned long last_report_time = 0; void setup() { // put your setup code here, to run once: pinMode(E0_enable, OUTPUT); pinMode(E0_step, OUTPUT); pinMode(E0_dir, OUTPUT); pinMode(E0_MS1, OUTPUT); pinMode(E0_MS2, OUTPUT); pinMode(slave_select_pin, OUTPUT); pinMode(small_fan, OUTPUT); pinMode(large_fan, OUTPUT); // Inputs from robot pinMode(MAN_EXTRUDE, INPUT_PULLUP); pinMode(HEAT_BED, INPUT_PULLUP); pinMode(HEAT_NOZZLE, INPUT_PULLUP); pinMode(PROG_FEED, INPUT_PULLUP); pinMode(BETWEEN_LAYER_RETRACT, INPUT_PULLUP); pinMode(ALL_STOP, INPUT_PULLUP); // Outputs to robot pinMode(BED_AT_TEMP, OUTPUT); pinMode(NOZZLE_AT_TEMP, OUTPUT); pinMode(LED_PIN, OUTPUT); Serial.begin(9600); /* The Rambo board has programmable potentiometers or 'digipots' for tuning each individual stepper motor. the following code handles that */ SPI.begin(); digitalWrite(slave_select_pin, LOW); SPI.transfer(E0_digipot_channel); SPI.transfer(E0_digipot_setting); SPI.end(); digitalWrite(slave_select_pin, HIGH); digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); digitalWrite(E0_dir, LOW); E0_heater.setTunings(50, 1, 9); // Initial Nozzle PID parameters E0_heater.setTargetTemp(100); bed_heater.setTunings(50, 0.5, 9); // Initial Bed PID Values bed_heater.setTargetTemp(35); // initialize timer 3 for the stepper motor interrupts noInterrupts(); // clear current bit selections TCCR3A = 0; TCCR3B = 0; TCNT3 = 0; OCR3A = 1600; // compare match register 10kHz TCCR3B |= (1 << WGM12); // CTC mode TCCR3B |= (1 << CS10); // No prescaling TIMSK3 |= (1 << OCIE3A); // enable timer compare interrupt interrupts(); // enable global interupts } /** scaleMicroStep() checks the current commanded velocity and determines if it is within one of the available micro step ranges. Using micro steps enables better lower speed performance and more reliable accelerations from zero. The available micro steps are 1 (full speed) 2, 4, and 16. */ void scaleMicroStep(){ int holdScale = MAX_VELOCITY/abs(E0_velocity); if(holdScale >= 16){ micro_step_scale = 16; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 4){ micro_step_scale = 4; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, HIGH); } else if (holdScale >= 2){ micro_step_scale = 2; digitalWrite(E0_MS1, HIGH); digitalWrite(E0_MS2, LOW); } else{ micro_step_scale = 1; digitalWrite(E0_MS1, LOW); digitalWrite(E0_MS2, LOW); } delayMicroseconds(2); } ISR(TIMER3_COMPA_vect){ noInterrupts(); int velocity_error = target_velocity - E0_velocity; if(abs(target_velocity) < MINIMUM_VELOCITY){ // If we are not supposed to be moving // Note: This code does not decelerate to 0 if target_velocity == 0 E0_velocity = 0; E0_acceleration = 0; } else if(abs(velocity_error)*2 <= MAX_ACCELERATION){ // If we are within 1/2 of an acceleration step of our target velocity then // stop accelerating and assign the target velocity E0_acceleration = 0; E0_velocity = target_velocity; } else if(velocity_error > 0){ // We need to speed up E0_acceleration = MAX_ACCELERATION; } else{ // We need to slow down E0_acceleration = -MAX_ACCELERATION; } E0_velocity += E0_acceleration; if(E0_velocity > MAX_VELOCITY){ E0_velocity = MAX_VELOCITY; } else if(E0_velocity < -MAX_VELOCITY){ E0_velocity = -MAX_VELOCITY; } if(E0_velocity < 0){ // Retract filament digitalWrite(E0_dir, HIGH); } else{ // Extrude filament digitalWrite(E0_dir, LOW); } scaleMicroStep(); E0_position += E0_velocity*micro_step_scale; if(SREG & 0b00001000){ // The third bit in SREG is the overflow flag. If we overflow // Then we know we should increment the stepper E0_position -= 0x8000; // Subtract a 1 in 16bit math digitalWrite(E0_step, HIGH); delayMicroseconds(2); digitalWrite(E0_step, LOW); num_steps += 1; } if(target_velocity - E0_velocity > MAX_ACCELERATION){ E0_acceleration = MAX_ACCELERATION; } else if(E0_velocity - target_velocity > MAX_ACCELERATION){ E0_acceleration = -MAX_ACCELERATION; } else{ E0_acceleration = 0; } interrupts(); } void checkStates(){ man_extrude = !digitalRead(MAN_EXTRUDE); heat_bed = !digitalRead(HEAT_BED); heat_nozzle = !digitalRead(HEAT_NOZZLE); prog_feed = !digitalRead(PROG_FEED); between_layer_retract = !digitalRead(BETWEEN_LAYER_RETRACT); all_stop = !digitalRead(ALL_STOP); S0 = (S0 || D1 || D2 || D3) && !(S_manual_extrude || S_printing); S_manual_extrude = (S_manual_extrude || (S0 && man_extrude)) && !D1; D1 = (D1 || (S_manual_extrude && !man_extrude)) && !S0; S_printing = (S_printing || (S0 && prog_feed) || (S_extrude && (num_steps >= retract_dist))) && !(D2 || S_retract); S_retract = (S_retract || (S_printing && between_layer_retract)) && !S_wait; S_wait = (S_wait || (S_retract && (num_steps >= retract_dist))) && !(S_extrude || D2); S_extrude = (S_extrude || (S_wait && !between_layer_retract)) && !S_printing; D2 = (D2 ||((S_wait || S_printing) && !prog_feed)) && !S0; D3 = (D3 || (S_ALL_STOP && !(prog_feed || heat_bed || heat_nozzle || between_layer_retract || all_stop || man_extrude))) && !S0; S_ALL_STOP = (S_ALL_STOP || all_stop) && !D3; if(S_ALL_STOP){ S0 = 0; S_manual_extrude = 0; D1 = 0; S_printing = 0; S_retract = 0; S_wait = 0; S_extrude = 0; D2 = 0; D3 = 0; E0_heater.setTargetTemp(0); bed_heater.setTargetTemp(0); target_velocity = 0; currState = "ALL_STOP"; } else{ if(S0 && !(S_manual_extrude || S_printing)){ target_velocity = 0; currState = "S0"; } else if(S_manual_extrude && !D1){ target_velocity = 100 * VELOCITY_CONVERSION; // Manual extrude speed currState = "Manul Extrude"; } else if(S_printing && !(D2 || S_retract)){ num_steps = 0; target_velocity = PROGRAM_FEED_RATE; currState = "Printing"; } else if(S_retract && !S_wait){ target_velocity = -MAX_VELOCITY; currState = "Retract"; } else if(S_wait && !(S_extrude || D2)){ num_steps = 0; target_velocity = 0; currState = "Wait"; } else if(S_extrude && !S_printing){ target_velocity = MAX_VELOCITY; currState = "Extrude"; } if(heat_nozzle){ E0_heater.setTargetTemp(190); if(E0_heater.atTemp()){ digitalWrite(NOZZLE_AT_TEMP, HIGH); } else{ digitalWrite(NOZZLE_AT_TEMP, LOW); } } else{ E0_heater.setTargetTemp(0); } if(heat_bed){ bed_heater.setTargetTemp(50); if(bed_heater.atTemp()){ digitalWrite(BED_AT_TEMP, HIGH); } else{ digitalWrite(BED_AT_TEMP, LOW); } } else{ bed_heater.setTargetTemp(0); } } } void setFans(){ /* Tests the current temperature of the nozzle and then turns on the fans if they are above their temperatures. */ unsigned long now = millis(); if(now - last_fan_time > FAN_SAMPLE_TIME){ float currTemp = E0_heater.getCurrTemp(); if (currTemp > 50) { analogWrite(small_fan, 255); } if(currTemp > 180){ analogWrite(large_fan, 255); } last_fan_time = now; } } void report(){ unsigned long now = millis(); if(now - last_report_time > 1000){ Serial.print("velocity target: "); Serial.print(target_velocity); Serial.print("\tE0_velocity: "); Serial.println(E0_velocity); Serial.print("Accel: "); Serial.println(E0_acceleration); Serial.print("Curr State: "); Serial.println(currState); Serial.print("Noz Targ Temp: "); Serial.print(E0_heater.getTargetTemp()); Serial.print("\tCurr Temp: "); Serial.println(E0_heater.getCurrTemp()); Serial.print("Bed Targ Temp: "); Serial.print(bed_heater.getTargetTemp()); Serial.print("\tCurr Temp: "); Serial.print(bed_heater.getCurrTemp()); Serial.print("\tOutput: "); Serial.println(bed_heater.getOutput()); Serial.println(); last_report_time = now; } } void loop() { E0_heater.compute(); bed_heater.compute(); checkStates(); setFans(); report(); } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: Emanuele * * Created on 29 July 2014, 17:25 */ #include <cstdlib> #include "RankingTable.hpp" using namespace std; int main(int argc, char** argv) { RankingTable<int> table; table.insert(0); table.insert(1); table.insert(2); const auto rightMap = table.getRightMap(); table.printRanking(); cout << endl << "Hit at element 2" << endl; table.hit(2); cout << endl << "Hit at element 2" << endl; table.hit(2); table.printRanking(); cout << endl << "Hit at element 0" << endl; table.hit(0); table.printRanking(); cout << endl << "Erasing element 1" << endl; table.erase(1); table.printRanking(); cout << endl << "Inserting element 3" << endl; table.insert(3); table.printRanking(); cout << endl << "2xHit at element 3" << endl; table.hit(3); table.hit(3); table.printRanking(); return 0; } <commit_msg>Deleted the rudimental test I had added by mistake<commit_after><|endoftext|>
<commit_before>/* * ProbeActivityLinear.cpp * * Created on: Mar 7, 2009 * Author: rasmussn */ #include "LinearActivityProbe.hpp" namespace PV { /** * @hc * @dim * @kLoc * @f */ LinearActivityProbe::LinearActivityProbe(HyPerCol * hc, PVDimType dim, int linePos, int f) : LayerProbe() { this->parent = hc; this->dim = dim; this->linePos = linePos; this->f = f; } /** * @filename * @hc * @dim * @kLoc * @f */ LinearActivityProbe::LinearActivityProbe(const char * filename, HyPerCol * hc, PVDimType dim, int linePos, int f) : LayerProbe(filename) { this->parent = hc; this->dim = dim; this->linePos = linePos; this->f = f; } /** * @time * @l */ int LinearActivityProbe::outputState(float time, HyPerLayer * l) { int width, sLine, k, kex; float * line; const PVLayer * clayer = l->clayer; float * activity = clayer->activity->data; const int nx = clayer->loc.nx; const int ny = clayer->loc.ny; const int nf = clayer->numFeatures; const int marginWidth = clayer->loc.nPad; float dt = parent->getDeltaTime(); double sum = 0.0; float freq; if (dim == DimX) { width = nx + 2*marginWidth; line = clayer->activity->data + (linePos+marginWidth) * width * nf; sLine = nf; } else { width = ny + 2*marginWidth; line = clayer->activity->data + (linePos+marginWidth)*nf; sLine = nf * (nx + 2*marginWidth); } for (int k = 0; k < width; k++) { float a = line[f + k * sLine]; sum += a; } freq = sum / (width * dt * 0.001); fprintf(fp, "t=%6.1f sum=%3d f=%6.1f Hz :", time, (int)sum, freq); for (int k = 0; k < width; k++) { float a = line[f + k * sLine]; if (a > 0.0) fprintf(fp, "*"); else fprintf(fp, " "); } fprintf(fp, ":\n"); fflush(fp); return 0; } } // namespace PV <commit_msg>Removed unused variable to get rid of compiler warnings.<commit_after>/* * ProbeActivityLinear.cpp * * Created on: Mar 7, 2009 * Author: rasmussn */ #include "LinearActivityProbe.hpp" namespace PV { /** * @hc * @dim * @kLoc * @f */ LinearActivityProbe::LinearActivityProbe(HyPerCol * hc, PVDimType dim, int linePos, int f) : LayerProbe() { this->parent = hc; this->dim = dim; this->linePos = linePos; this->f = f; } /** * @filename * @hc * @dim * @kLoc * @f */ LinearActivityProbe::LinearActivityProbe(const char * filename, HyPerCol * hc, PVDimType dim, int linePos, int f) : LayerProbe(filename) { this->parent = hc; this->dim = dim; this->linePos = linePos; this->f = f; } /** * @time * @l */ int LinearActivityProbe::outputState(float time, HyPerLayer * l) { int width, sLine; float * line; const PVLayer * clayer = l->clayer; float * activity = clayer->activity->data; const int nx = clayer->loc.nx; const int ny = clayer->loc.ny; const int nf = clayer->numFeatures; const int marginWidth = clayer->loc.nPad; float dt = parent->getDeltaTime(); double sum = 0.0; float freq; if (dim == DimX) { width = nx + 2*marginWidth; line = activity + (linePos+marginWidth) * width * nf; sLine = nf; } else { width = ny + 2*marginWidth; line = activity + (linePos+marginWidth)*nf; sLine = nf * (nx + 2*marginWidth); } for (int k = 0; k < width; k++) { float a = line[f + k * sLine]; sum += a; } freq = sum / (width * dt * 0.001); fprintf(fp, "t=%6.1f sum=%3d f=%6.1f Hz :", time, (int)sum, freq); for (int k = 0; k < width; k++) { float a = line[f + k * sLine]; if (a > 0.0) fprintf(fp, "*"); else fprintf(fp, " "); } fprintf(fp, ":\n"); fflush(fp); return 0; } } // namespace PV <|endoftext|>
<commit_before>/* Copyright (c) 2014-2017 AscEmu Team <http://www.ascemu.org/> This file is released under the MIT license. See README-MIT for more information. */ #include "Units/Players/Player.h" #include "Server/World.Legacy.h" #include "Server/World.h" #include "Spell/Definitions/AuraInterruptFlags.h" #include "Objects/ObjectMgr.h" void Player::sendForceMovePacket(UnitSpeedType speed_type, float speed) { WorldPacket data(60); switch (speed_type) { case TYPE_WALK: { data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_WALK_SPEED_CHANGE, speed); break; } case TYPE_RUN: { data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_RUN_SPEED_CHANGE, speed); break; } case TYPE_RUN_BACK: { data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_RUN_BACK_SPEED_CHANGE, speed); break; } case TYPE_SWIM: { data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_SWIM_SPEED_CHANGE, speed); break; } case TYPE_SWIM_BACK: { data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, speed); break; } case TYPE_TURN_RATE: { data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE); //movement_info.Write(data, SMSG_FORCE_TURN_RATE_CHANGE, speed); break; } case TYPE_FLY: { data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_FLIGHT_SPEED_CHANGE, speed); break; } case TYPE_FLY_BACK: { data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE); //movement_info.Write(data, SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, speed); break; } case TYPE_PITCH_RATE: { data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE); //movement_info.Write(data, SMSG_FORCE_PITCH_RATE_CHANGE, speed); break; } } SendMessageToSet(&data, true); } void Player::sendMoveSetSpeedPaket(UnitSpeedType speed_type, float speed) { WorldPacket data; ObjectGuid guid = GetGUID(); switch (speed_type) { case TYPE_WALK: { data.Initialize(MSG_MOVE_SET_WALK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_WALK_SPEED, speed); break; } case TYPE_RUN: { data.Initialize(MSG_MOVE_SET_RUN_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_RUN_SPEED, speed); break; } case TYPE_RUN_BACK: { data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_RUN_BACK_SPEED, speed); break; } case TYPE_SWIM: { data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_SWIM_SPEED, speed); break; } case TYPE_SWIM_BACK: { data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_SWIM_BACK_SPEED, speed); break; } case TYPE_TURN_RATE: { data.Initialize(MSG_MOVE_SET_TURN_RATE, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_TURN_RATE, speed); break; } case TYPE_FLY: { data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_FLIGHT_SPEED, speed); break; } case TYPE_FLY_BACK: { data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_FLIGHT_BACK_SPEED, speed); break; } case TYPE_PITCH_RATE: { data.Initialize(MSG_MOVE_SET_PITCH_RATE, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_PITCH_RATE, speed); break; } } SendMessageToSet(&data, true); } void Player::handleFall(MovementInfo const& movement_info) { if (!z_axisposition) { z_axisposition = movement_info.getPosition()->z; } uint32 falldistance = float2int32(z_axisposition - movement_info.getPosition()->z); if (z_axisposition <= movement_info.getPosition()->z) { falldistance = 1; } if (static_cast<int>(falldistance) > m_safeFall) { falldistance -= m_safeFall; } else { falldistance = 1; } if (isAlive() && !bInvincible && (falldistance > 12) && !m_noFallDamage && ((!GodModeCheat && (UNIXTIME >= m_fallDisabledUntil)))) { auto health_loss = static_cast<uint32_t>(GetHealth() * (falldistance - 12) * 0.017f); if (health_loss >= GetHealth()) { health_loss = GetHealth(); } else if ((falldistance >= 65)) { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, falldistance, GetDrunkenstateByValue(GetDrunkValue()), 0); } SendEnvironmentalDamageLog(GetGUID(), DAMAGE_FALL, health_loss); DealDamage(this, health_loss, 0, 0, 0); } z_axisposition = 0.0f; } bool Player::isPlayerJumping(MovementInfo const& movement_info, uint16_t opcode) { if (opcode == MSG_MOVE_FALL_LAND || movement_info.hasMovementFlag(MOVEFLAG_SWIMMING)) { jumping = false; return false; } if (!jumping && (opcode == MSG_MOVE_JUMP || movement_info.hasMovementFlag(MOVEFLAG_FALLING))) { jumping = true; return true; } return false; } void Player::handleBreathing(MovementInfo& movement_info, WorldSession* session) { if (!worldConfig.server.enableBreathing || FlyCheat || m_bUnlimitedBreath || !isAlive() || GodModeCheat) { if (m_UnderwaterState & UNDERWATERSTATE_SWIMMING) m_UnderwaterState &= ~UNDERWATERSTATE_SWIMMING; if (m_UnderwaterState & UNDERWATERSTATE_UNDERWATER) { m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, -1); } if (session->m_bIsWLevelSet) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_LEAVE_WATER); session->m_bIsWLevelSet = false; } } return; } if (movement_info.hasMovementFlag(MOVEFLAG_SWIMMING) && !(m_UnderwaterState & UNDERWATERSTATE_SWIMMING)) { RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_ENTER_WATER); if (!session->m_bIsWLevelSet) { session->m_wLevel = movement_info.getPosition()->z + m_noseLevel * 0.95f; session->m_bIsWLevelSet = true; } m_UnderwaterState |= UNDERWATERSTATE_SWIMMING; } if (!(movement_info.hasMovementFlag(MOVEFLAG_SWIMMING)) && (movement_info.hasMovementFlag(MOVEFLAG_NONE)) && (m_UnderwaterState & UNDERWATERSTATE_SWIMMING)) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_LEAVE_WATER); session->m_bIsWLevelSet = false; m_UnderwaterState &= ~UNDERWATERSTATE_SWIMMING; } } if (m_UnderwaterState & UNDERWATERSTATE_SWIMMING && !(m_UnderwaterState & UNDERWATERSTATE_UNDERWATER)) { if ((movement_info.getPosition()->z + m_noseLevel) < session->m_wLevel) { m_UnderwaterState |= UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, -1); } } if (m_UnderwaterState & UNDERWATERSTATE_SWIMMING && m_UnderwaterState & UNDERWATERSTATE_UNDERWATER) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, 10); } } if (!(m_UnderwaterState & UNDERWATERSTATE_SWIMMING) && m_UnderwaterState & UNDERWATERSTATE_UNDERWATER) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, 10); } } } static const uint32_t LanguageSkills[NUM_LANGUAGES] = { 0, // UNIVERSAL 0x00 109, // ORCISH 0x01 113, // DARNASSIAN 0x02 115, // TAURAHE 0x03 0, // - 0x04 0, // - 0x05 111, // DWARVISH 0x06 98, // COMMON 0x07 139, // DEMON TONGUE 0x08 140, // TITAN 0x09 137, // THALSSIAN 0x0A 138, // DRACONIC 0x0B 0, // KALIMAG 0x0C 313, // GNOMISH 0x0D 315, // TROLL 0x0E 0, // - 0x0F 0, // - 0x10 0, // - 0x11 0, // - 0x12 0, // - 0x13 0, // - 0x14 0, // - 0x15 0, // - 0x16 0, // - 0x17 0, // - 0x18 0, // - 0x19 0, // - 0x1A 0, // - 0x1B 0, // - 0x1C 0, // - 0x1D 0, // - 0x1E 0, // - 0x1F 0, // - 0x20 673, // GUTTERSPEAK 0x21 0, // - 0x22 759, // DRAENEI 0x23 0, // ZOMBIE 0x24 0, // GNOMISH_BINAR 0x25 0, // GOBLIN_BINARY 0x26 791, // WORGEN 0x27 792, // GOBLIN 0x28 }; bool Player::hasSkilledSkill(uint32_t skill) { return (m_skills.find(skill) != m_skills.end()); } bool Player::hasLanguage(uint32_t language) { return hasSkilledSkill(LanguageSkills[language]); } WorldPacket Player::buildChatMessagePacket(Player* targetPlayer, uint32_t type, uint32_t language, const char* message, uint64_t guid, uint8_t flag) { Player* senderPlayer = objmgr.GetPlayer(guid); uint32_t messageLength = (uint32_t)strlen(message) + 1; WorldPacket data(SMSG_MESSAGECHAT, messageLength + 60); data << uint8_t(type); if (targetPlayer->hasLanguage(language) || targetPlayer->isGMFlagSet() || (senderPlayer && senderPlayer->isGMFlagSet()) || worldConfig.player.isInterfactionChatEnabled) { data << 0; } else { data << language; } data << guid; data << uint32_t(0); data << targetPlayer->GetGUID(); data << messageLength; data << message; data << uint8_t(flag); return data; } void Player::sendChatPacket(uint32_t type, uint32_t language, const char* message, uint64_t guid, uint8_t flag) { if (IsInWorld() == false) { return; } uint32_t senderPhase = GetPhase(); for (std::set<Object*>::iterator itr = m_inRangePlayers.begin(); itr != m_inRangePlayers.end(); ++itr) { Player* p = static_cast<Player*>(*itr); if (p->GetSession() && !p->Social_IsIgnoring(GetLowGUID()) && (p->GetPhase() & senderPhase) != 0) { WorldPacket data = p->buildChatMessagePacket(p, type, language, message, guid, flag); p->SendPacket(&data); } } // send to self WorldPacket selfData = buildChatMessagePacket(this, type, language, message, guid, flag); this->SendPacket(&selfData); } <commit_msg>Cata: Removed obsolete checks in player buildChatMessagePacket<commit_after>/* Copyright (c) 2014-2017 AscEmu Team <http://www.ascemu.org/> This file is released under the MIT license. See README-MIT for more information. */ #include "Units/Players/Player.h" #include "Server/World.Legacy.h" #include "Server/World.h" #include "Spell/Definitions/AuraInterruptFlags.h" #include "Chat/ChatDefines.hpp" #include "Objects/ObjectMgr.h" void Player::sendForceMovePacket(UnitSpeedType speed_type, float speed) { WorldPacket data(60); switch (speed_type) { case TYPE_WALK: { data.Initialize(SMSG_FORCE_WALK_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_WALK_SPEED_CHANGE, speed); break; } case TYPE_RUN: { data.Initialize(SMSG_FORCE_RUN_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_RUN_SPEED_CHANGE, speed); break; } case TYPE_RUN_BACK: { data.Initialize(SMSG_FORCE_RUN_BACK_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_RUN_BACK_SPEED_CHANGE, speed); break; } case TYPE_SWIM: { data.Initialize(SMSG_FORCE_SWIM_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_SWIM_SPEED_CHANGE, speed); break; } case TYPE_SWIM_BACK: { data.Initialize(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_SWIM_BACK_SPEED_CHANGE, speed); break; } case TYPE_TURN_RATE: { data.Initialize(SMSG_FORCE_TURN_RATE_CHANGE); //movement_info.Write(data, SMSG_FORCE_TURN_RATE_CHANGE, speed); break; } case TYPE_FLY: { data.Initialize(SMSG_FORCE_FLIGHT_SPEED_CHANGE); movement_info.writeMovementInfo(data, SMSG_FORCE_FLIGHT_SPEED_CHANGE, speed); break; } case TYPE_FLY_BACK: { data.Initialize(SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE); //movement_info.Write(data, SMSG_FORCE_FLIGHT_BACK_SPEED_CHANGE, speed); break; } case TYPE_PITCH_RATE: { data.Initialize(SMSG_FORCE_PITCH_RATE_CHANGE); //movement_info.Write(data, SMSG_FORCE_PITCH_RATE_CHANGE, speed); break; } } SendMessageToSet(&data, true); } void Player::sendMoveSetSpeedPaket(UnitSpeedType speed_type, float speed) { WorldPacket data; ObjectGuid guid = GetGUID(); switch (speed_type) { case TYPE_WALK: { data.Initialize(MSG_MOVE_SET_WALK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_WALK_SPEED, speed); break; } case TYPE_RUN: { data.Initialize(MSG_MOVE_SET_RUN_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_RUN_SPEED, speed); break; } case TYPE_RUN_BACK: { data.Initialize(MSG_MOVE_SET_RUN_BACK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_RUN_BACK_SPEED, speed); break; } case TYPE_SWIM: { data.Initialize(MSG_MOVE_SET_SWIM_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_SWIM_SPEED, speed); break; } case TYPE_SWIM_BACK: { data.Initialize(MSG_MOVE_SET_SWIM_BACK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_SWIM_BACK_SPEED, speed); break; } case TYPE_TURN_RATE: { data.Initialize(MSG_MOVE_SET_TURN_RATE, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_TURN_RATE, speed); break; } case TYPE_FLY: { data.Initialize(MSG_MOVE_SET_FLIGHT_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_FLIGHT_SPEED, speed); break; } case TYPE_FLY_BACK: { data.Initialize(MSG_MOVE_SET_FLIGHT_BACK_SPEED, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_FLIGHT_BACK_SPEED, speed); break; } case TYPE_PITCH_RATE: { data.Initialize(MSG_MOVE_SET_PITCH_RATE, 1 + 8 + 4 + 4); movement_info.writeMovementInfo(data, MSG_MOVE_SET_PITCH_RATE, speed); break; } } SendMessageToSet(&data, true); } void Player::handleFall(MovementInfo const& movement_info) { if (!z_axisposition) { z_axisposition = movement_info.getPosition()->z; } uint32 falldistance = float2int32(z_axisposition - movement_info.getPosition()->z); if (z_axisposition <= movement_info.getPosition()->z) { falldistance = 1; } if (static_cast<int>(falldistance) > m_safeFall) { falldistance -= m_safeFall; } else { falldistance = 1; } if (isAlive() && !bInvincible && (falldistance > 12) && !m_noFallDamage && ((!GodModeCheat && (UNIXTIME >= m_fallDisabledUntil)))) { auto health_loss = static_cast<uint32_t>(GetHealth() * (falldistance - 12) * 0.017f); if (health_loss >= GetHealth()) { health_loss = GetHealth(); } else if ((falldistance >= 65)) { GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, falldistance, GetDrunkenstateByValue(GetDrunkValue()), 0); } SendEnvironmentalDamageLog(GetGUID(), DAMAGE_FALL, health_loss); DealDamage(this, health_loss, 0, 0, 0); } z_axisposition = 0.0f; } bool Player::isPlayerJumping(MovementInfo const& movement_info, uint16_t opcode) { if (opcode == MSG_MOVE_FALL_LAND || movement_info.hasMovementFlag(MOVEFLAG_SWIMMING)) { jumping = false; return false; } if (!jumping && (opcode == MSG_MOVE_JUMP || movement_info.hasMovementFlag(MOVEFLAG_FALLING))) { jumping = true; return true; } return false; } void Player::handleBreathing(MovementInfo& movement_info, WorldSession* session) { if (!worldConfig.server.enableBreathing || FlyCheat || m_bUnlimitedBreath || !isAlive() || GodModeCheat) { if (m_UnderwaterState & UNDERWATERSTATE_SWIMMING) m_UnderwaterState &= ~UNDERWATERSTATE_SWIMMING; if (m_UnderwaterState & UNDERWATERSTATE_UNDERWATER) { m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, -1); } if (session->m_bIsWLevelSet) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_LEAVE_WATER); session->m_bIsWLevelSet = false; } } return; } if (movement_info.hasMovementFlag(MOVEFLAG_SWIMMING) && !(m_UnderwaterState & UNDERWATERSTATE_SWIMMING)) { RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_ENTER_WATER); if (!session->m_bIsWLevelSet) { session->m_wLevel = movement_info.getPosition()->z + m_noseLevel * 0.95f; session->m_bIsWLevelSet = true; } m_UnderwaterState |= UNDERWATERSTATE_SWIMMING; } if (!(movement_info.hasMovementFlag(MOVEFLAG_SWIMMING)) && (movement_info.hasMovementFlag(MOVEFLAG_NONE)) && (m_UnderwaterState & UNDERWATERSTATE_SWIMMING)) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_LEAVE_WATER); session->m_bIsWLevelSet = false; m_UnderwaterState &= ~UNDERWATERSTATE_SWIMMING; } } if (m_UnderwaterState & UNDERWATERSTATE_SWIMMING && !(m_UnderwaterState & UNDERWATERSTATE_UNDERWATER)) { if ((movement_info.getPosition()->z + m_noseLevel) < session->m_wLevel) { m_UnderwaterState |= UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, -1); } } if (m_UnderwaterState & UNDERWATERSTATE_SWIMMING && m_UnderwaterState & UNDERWATERSTATE_UNDERWATER) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, 10); } } if (!(m_UnderwaterState & UNDERWATERSTATE_SWIMMING) && m_UnderwaterState & UNDERWATERSTATE_UNDERWATER) { if ((movement_info.getPosition()->z + m_noseLevel) > session->m_wLevel) { m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER; SendMirrorTimer(MIRROR_TYPE_BREATH, m_UnderwaterTime, m_UnderwaterMaxTime, 10); } } } static const uint32_t LanguageSkills[NUM_LANGUAGES] = { 0, // UNIVERSAL 0x00 109, // ORCISH 0x01 113, // DARNASSIAN 0x02 115, // TAURAHE 0x03 0, // - 0x04 0, // - 0x05 111, // DWARVISH 0x06 98, // COMMON 0x07 139, // DEMON TONGUE 0x08 140, // TITAN 0x09 137, // THALSSIAN 0x0A 138, // DRACONIC 0x0B 0, // KALIMAG 0x0C 313, // GNOMISH 0x0D 315, // TROLL 0x0E 0, // - 0x0F 0, // - 0x10 0, // - 0x11 0, // - 0x12 0, // - 0x13 0, // - 0x14 0, // - 0x15 0, // - 0x16 0, // - 0x17 0, // - 0x18 0, // - 0x19 0, // - 0x1A 0, // - 0x1B 0, // - 0x1C 0, // - 0x1D 0, // - 0x1E 0, // - 0x1F 0, // - 0x20 673, // GUTTERSPEAK 0x21 0, // - 0x22 759, // DRAENEI 0x23 0, // ZOMBIE 0x24 0, // GNOMISH_BINAR 0x25 0, // GOBLIN_BINARY 0x26 791, // WORGEN 0x27 792, // GOBLIN 0x28 }; bool Player::hasSkilledSkill(uint32_t skill) { return (m_skills.find(skill) != m_skills.end()); } bool Player::hasLanguage(uint32_t language) { return hasSkilledSkill(LanguageSkills[language]); } WorldPacket Player::buildChatMessagePacket(Player* targetPlayer, uint32_t type, uint32_t language, const char* message, uint64_t guid, uint8_t flag) { Player* senderPlayer = objmgr.GetPlayer(guid); uint32_t messageLength = (uint32_t)strlen(message) + 1; WorldPacket data(SMSG_MESSAGECHAT, messageLength + 60); data << uint8_t(type); if (targetPlayer->hasLanguage(language) || targetPlayer->isGMFlagSet()) { data << LANG_UNIVERSAL; } else { data << language; } data << guid; data << uint32_t(0); data << targetPlayer->GetGUID(); data << messageLength; data << message; data << uint8_t(flag); return data; } void Player::sendChatPacket(uint32_t type, uint32_t language, const char* message, uint64_t guid, uint8_t flag) { if (IsInWorld() == false) { return; } uint32_t senderPhase = GetPhase(); for (std::set<Object*>::iterator itr = m_inRangePlayers.begin(); itr != m_inRangePlayers.end(); ++itr) { Player* p = static_cast<Player*>(*itr); if (p->GetSession() && !p->Social_IsIgnoring(GetLowGUID()) && (p->GetPhase() & senderPhase) != 0) { WorldPacket data = p->buildChatMessagePacket(p, type, language, message, guid, flag); p->SendPacket(&data); } } // send to self WorldPacket selfData = buildChatMessagePacket(this, type, language, message, guid, flag); this->SendPacket(&selfData); } <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naessn and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naessn a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Guichan 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/irrlicht/irrlichtimage.hpp" #include "guichan/exception.hpp" namespace gcn { IrrlichtImage::IrrlichtImage(irr::video::IImage* image, irr::video::IVideoDriver* driver, const std::string& name, bool autoFree, bool convertToDisplayFormat) { mTexture = NULL; mImage = image; mDriver = driver; mName = name; mAutoFree = autoFree; if (mDriver) { driver->grab(); } if (convertToDisplayFormat) { IrrlichtImage::convertToDisplayFormat(); } } IrrlichtImage::~IrrlichtImage() { if (mAutoFree) { free(); } if (mDriver) { mDriver->drop(); } } irr::video::ITexture* IrrlichtImage::getTexture() const { return mTexture; } int IrrlichtImage::getWidth() const { if (mTexture) { return mTexture->getSize().Width; } else if (mImage) { return mImage->getDimension().Width; } throw GCN_EXCEPTION("Trying to get the width of a non loaded image."); } int IrrlichtImage::getHeight() const { if (mTexture) { return mTexture->getSize().Height; } else if (mImage) { return mImage->getDimension().Height; } throw GCN_EXCEPTION("Trying to get the height of a non loaded image."); } Color IrrlichtImage::getPixel(int x, int y) { if (mImage == NULL) { throw GCN_EXCEPTION("Image has been converted to display format."); } irr::video::SColor color = mImage->getPixel(x, y); return Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } void IrrlichtImage::putPixel(int x, int y, const Color& color) { if (mImage == NULL) { throw GCN_EXCEPTION("Image has been converted to display format."); } mImage->setPixel(x, y, irr::video::SColor(color.a, color.r, color.g, color.b)); } void IrrlichtImage::convertToDisplayFormat() { if (mTexture != NULL) { return; } if (mImage == NULL) { throw GCN_EXCEPTION("Trying to convert a non loaded image to display format."); } mTexture = mDriver->addTexture(mName.c_str(), mImage); if (mTexture == NULL) { throw GCN_EXCEPTION("Unable to convert image to display format!"); } mDriver->makeColorKeyTexture(mTexture, irr::video::SColor(0,255,0,255)); mImage->drop(); mImage = NULL; } void IrrlichtImage::free() { if (mImage != NULL) { mImage->drop(); } } } <commit_msg>http://code.google.com/p/guichan/issues/detail?id=103<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 - 2008 Olof Naess�n and Per Larsson * * * Per Larsson a.k.a finalman * Olof Naess�n a.k.a jansem/yakslem * * Visit: http://guichan.sourceforge.net * * License: (BSD) * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Guichan 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/irrlicht/irrlichtimage.hpp" #include "guichan/exception.hpp" namespace gcn { IrrlichtImage::IrrlichtImage(irr::video::IImage* image, irr::video::IVideoDriver* driver, const std::string& name, bool autoFree, bool convertToDisplayFormat) { mTexture = NULL; mImage = image; mDriver = driver; mName = name; mAutoFree = autoFree; if (mDriver) { driver->grab(); } if (convertToDisplayFormat) { IrrlichtImage::convertToDisplayFormat(); } } IrrlichtImage::~IrrlichtImage() { if (mAutoFree) { free(); } if (mDriver) { mDriver->drop(); } } irr::video::ITexture* IrrlichtImage::getTexture() const { return mTexture; } int IrrlichtImage::getWidth() const { if (mTexture) { return mTexture->getSize().Width; } else if (mImage) { return mImage->getDimension().Width; } throw GCN_EXCEPTION("Trying to get the width of a non loaded image."); } int IrrlichtImage::getHeight() const { if (mTexture) { return mTexture->getSize().Height; } else if (mImage) { return mImage->getDimension().Height; } throw GCN_EXCEPTION("Trying to get the height of a non loaded image."); } Color IrrlichtImage::getPixel(int x, int y) { if (mImage == NULL) { throw GCN_EXCEPTION("Image has been converted to display format."); } irr::video::SColor color = mImage->getPixel(x, y); return Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()); } void IrrlichtImage::putPixel(int x, int y, const Color& color) { if (mImage == NULL) { throw GCN_EXCEPTION("Image has been converted to display format."); } mImage->setPixel(x, y, irr::video::SColor(color.a, color.r, color.g, color.b)); } void IrrlichtImage::convertToDisplayFormat() { if (mTexture != NULL) { return; } if (mImage == NULL) { throw GCN_EXCEPTION("Trying to convert a non loaded image to display format."); } bool hasPink = false; irr::video::SColor pink(255, 255, 0, 255); for (int i = 0; i < mImage->getDimension().Width; ++i) { for (int j = 0; j < mImage->getDimension().Height; ++j) { if(mImage->getPixel(i, j) == pink) { hasPink = true; break; } } } mTexture = mDriver->addTexture(mName.c_str(), mImage); if (mTexture == NULL) { throw GCN_EXCEPTION("Unable to convert image to display format!"); } if(hasPink == true) { mDriver->makeColorKeyTexture(mTexture, irr::video::SColor(0,255,0,255)); } mImage->drop(); mImage = NULL; } void IrrlichtImage::free() { if (mImage != NULL) { mImage->drop(); } } } <|endoftext|>
<commit_before>/*************************************************************************** * io/wbtl_file.cpp * * a write-buffered-translation-layer pseudo file * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2008-2009 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <iomanip> #include <stxxl/bits/io/wbtl_file.h> #include <stxxl/bits/io/io.h> #include <stxxl/bits/common/debug.h> #include <stxxl/bits/parallel.h> #include <stxxl/aligned_alloc> #ifndef STXXL_VERBOSE_WBTL #define STXXL_VERBOSE_WBTL STXXL_VERBOSE0 #endif __STXXL_BEGIN_NAMESPACE wbtl_file::wbtl_file( file * backend_file, size_type write_buffer_size, int write_buffers, int disk) : file_request_basic(disk), storage(backend_file), sz(0), write_block_size(write_buffer_size), free_bytes(0), curbuf(1), curpos(write_block_size) { assert(write_buffers == 2); // currently hardcoded write_buffer[0] = static_cast<char *>(stxxl::aligned_alloc<BLOCK_ALIGN>(write_block_size)); write_buffer[1] = static_cast<char *>(stxxl::aligned_alloc<BLOCK_ALIGN>(write_block_size)); buffer_address[0] = offset_type(-1); buffer_address[1] = offset_type(-1); } wbtl_file::~wbtl_file() { stxxl::aligned_dealloc<BLOCK_ALIGN>(write_buffer[1]); stxxl::aligned_dealloc<BLOCK_ALIGN>(write_buffer[0]); delete storage; storage = 0; } void wbtl_file::serve(const stxxl::request* req) throw(io_error) { assert(req->get_file() == this); offset_type offset = req->get_offset(); void * buffer = req->get_buffer(); size_type bytes = req->get_size(); request::request_type type = req->get_type(); if (type == request::READ) { //stats::scoped_read_timer read_timer(size()); sread(buffer, offset, bytes); } else { //stats::scoped_write_timer write_timer(size()); swrite(buffer, offset, bytes); } } void wbtl_file::lock() { storage->lock(); } wbtl_file::offset_type wbtl_file::size() { return sz; } void wbtl_file::set_size(offset_type newsize) { scoped_mutex_lock mapping_lock(mapping_mutex); assert(sz <= newsize); // may not shrink if (sz < newsize) { _add_free_region(sz, newsize - sz); storage->set_size(newsize); sz = newsize; assert(sz == storage->size()); } } request_ptr wbtl_file::aread( void * buffer, offset_type pos, size_t bytes, completion_handler on_cmpl) { scoped_mutex_lock mapping_lock(mapping_mutex); if (address_mapping.find(pos) == address_mapping.end()) { STXXL_THROW2(io_error, "wbtl_aread of unmapped memory"); } return file_request_basic::aread(buffer, pos, bytes, on_cmpl); } #define FMT_A_S(_addr_,_size_) "0x" << std::hex << std::setfill('0') << std::setw(8) << (_addr_) << "/0x" << std::setw(8) << (_size_) #define FMT_A_C(_addr_,_size_) "0x" << std::setw(8) << (_addr_) << "(" << std::dec << (_size_) << ")" #define FMT_A(_addr_) "0x" << std::setw(8) << (_addr_) // logical address void wbtl_file::delete_region(offset_type offset, size_type size) { scoped_mutex_lock mapping_lock(mapping_mutex); sortseq::iterator physical = address_mapping.find(offset); STXXL_VERBOSE_WBTL("wbtl:delreg l" << FMT_A_S(offset, size) << " @ p" << FMT_A(physical != address_mapping.end() ? physical->second : 0xffffffff)); if (physical == address_mapping.end()) { // could be OK if the block was never written ... STXXL_ERRMSG("delete_region: mapping not found: " << FMT_A_S(offset, size) << " ==> " << "???"); } else { offset_type physical_offset = physical->second; address_mapping.erase(physical); _add_free_region(physical_offset, size); place_map::iterator reverse = reverse_mapping.find(physical_offset); if (reverse == reverse_mapping.end()) { STXXL_ERRMSG("delete_region: reverse mapping not found: " << FMT_A_S(offset, size) << " ==> " << "???"); } else { assert(offset == (reverse->second).first); reverse_mapping.erase(reverse); } storage->delete_region(physical_offset, size); } } // physical address void wbtl_file::_add_free_region(offset_type offset, offset_type size) { // mapping_lock has to be aquired by caller STXXL_VERBOSE_WBTL("wbtl:addfre p" << FMT_A_S(offset, size) << " F <= f" << FMT_A_C(free_bytes, free_space.size())); size_type region_pos = offset; size_type region_size = size; if (!free_space.empty()) { sortseq::iterator succ = free_space.upper_bound(region_pos); sortseq::iterator pred = succ; pred--; check_corruption(region_pos, region_size, pred, succ); if (succ == free_space.end()) { if (pred == free_space.end()) { //dump(); assert(pred != free_space.end()); } if ((*pred).first + (*pred).second == region_pos) { // coalesce with predecessor region_size += (*pred).second; region_pos = (*pred).first; free_space.erase(pred); } } else { if (free_space.size() > 1) { bool succ_is_not_the_first = (succ != free_space.begin()); if ((*succ).first == region_pos + region_size) { // coalesce with successor region_size += (*succ).second; free_space.erase(succ); } if (succ_is_not_the_first) { if (pred == free_space.end()) { //dump(); assert(pred != free_space.end()); } if ((*pred).first + (*pred).second == region_pos) { // coalesce with predecessor region_size += (*pred).second; region_pos = (*pred).first; free_space.erase(pred); } } } else { if ((*succ).first == region_pos + region_size) { // coalesce with successor region_size += (*succ).second; free_space.erase(succ); } } } } free_space[region_pos] = region_size; free_bytes += size; STXXL_VERBOSE_WBTL("wbtl:free p" << FMT_A_S(region_pos, region_size) << " F => f" << FMT_A_C(free_bytes, free_space.size())); } void wbtl_file::sread(void * buffer, offset_type offset, size_type bytes) { scoped_mutex_lock buffer_lock(buffer_mutex); int cached = -1; offset_type physical_offset; // map logical to physical address { scoped_mutex_lock mapping_lock(mapping_mutex); sortseq::iterator physical = address_mapping.find(offset); if (physical == address_mapping.end()) { STXXL_ERRMSG("wbtl_read: mapping not found: " << FMT_A_S(offset, bytes) << " ==> " << "???"); //STXXL_THROW2(io_error, "wbtl_read of unmapped memory"); physical_offset = 0xffffffff; } else { physical_offset = physical->second; } } if (buffer_address[curbuf] <= physical_offset && physical_offset < buffer_address[curbuf] + write_block_size) { // block is in current write buffer assert(physical_offset + bytes <= buffer_address[curbuf] + write_block_size); memcpy(buffer, write_buffer[curbuf] + (physical_offset - buffer_address[curbuf]), bytes); cached = curbuf; } else if (buffer_address[1 - curbuf] <= physical_offset && physical_offset < buffer_address[1 - curbuf] + write_block_size) { // block is in previous write buffer assert(physical_offset + bytes <= buffer_address[1 - curbuf] + write_block_size); memcpy(buffer, write_buffer[1 - curbuf] + (physical_offset - buffer_address[1 - curbuf]), bytes); cached = curbuf; } else { // block is not cached request_ptr req = storage->aread(buffer, physical_offset, bytes, default_completion_handler()); req->wait(); } STXXL_VERBOSE_WBTL("wbtl:sread l" << FMT_A_S(offset, bytes) << " @ p" << FMT_A(physical_offset) << " " << std::dec << cached); } void wbtl_file::swrite(void * buffer, offset_type offset, size_type bytes) { scoped_mutex_lock buffer_lock(buffer_mutex); // is the block already mapped? { scoped_mutex_lock mapping_lock(mapping_mutex); sortseq::iterator physical = address_mapping.find(offset); STXXL_VERBOSE_WBTL("wbtl:swrite l" << FMT_A_S(offset, bytes) << " @ <= p" << FMT_A_C(physical != address_mapping.end() ? physical->second : 0xffffffff, address_mapping.size())); if (physical != address_mapping.end()) { mapping_lock.unlock(); // FIXME: special case if we can replace it in the current writing block delete_region(offset, bytes); } } if (bytes > write_block_size - curpos) { // not enough space in the current write buffer if (buffer_address[curbuf] != offset_type(-1)) { STXXL_VERBOSE_WBTL("wbtl:w2disk p" << FMT_A_S(buffer_address[curbuf], write_block_size)); // mark remaining part as free if (curpos < write_block_size) _add_free_region(buffer_address[curbuf] + curpos, write_block_size - curpos); if (backend_request.get()) { backend_request->wait(); } backend_request = storage->awrite(write_buffer[curbuf], buffer_address[curbuf], write_block_size, default_completion_handler()); } curbuf = 1 - curbuf; buffer_address[curbuf] = get_next_write_block(); curpos = 0; } assert(bytes <= write_block_size - curpos); // write block into buffer memcpy(write_buffer[curbuf] + curpos, buffer, bytes); scoped_mutex_lock mapping_lock(mapping_mutex); address_mapping[offset] = buffer_address[curbuf] + curpos; reverse_mapping[buffer_address[curbuf] + curpos] = place(offset, bytes); STXXL_VERBOSE_WBTL("wbtl:swrite l" << FMT_A_S(offset, bytes) << " @ => p" << FMT_A_C(buffer_address[curbuf] + curpos, address_mapping.size())); curpos += bytes; } wbtl_file::offset_type wbtl_file::get_next_write_block() { // mapping_lock has to be aquired by caller sortseq::iterator space = std::find_if(free_space.begin(), free_space.end(), bind2nd(FirstFit(), write_block_size)); if (space != free_space.end()) { offset_type region_pos = (*space).first; offset_type region_size = (*space).second; free_space.erase(space); if (region_size > write_block_size) free_space[region_pos + write_block_size] = region_size - write_block_size; free_bytes -= write_block_size; STXXL_VERBOSE_WBTL("wbtl:nextwb p" << FMT_A_S(region_pos, write_block_size) << " F f" << FMT_A_C(free_bytes, free_space.size())); return region_pos; } STXXL_THROW2(io_error, "OutOfSpace, probably fragmented"); return -1; } void wbtl_file::check_corruption(offset_type region_pos, offset_type region_size, sortseq::iterator pred, sortseq::iterator succ) { if (pred != free_space.end()) { if (pred->first <= region_pos && pred->first + pred->second > region_pos) { STXXL_THROW(bad_ext_alloc, "DiskAllocator::check_corruption", "Error: double deallocation of external memory " << "System info: P " << pred->first << " " << pred->second << " " << region_pos); } } if (succ != free_space.end()) { if (region_pos <= succ->first && region_pos + region_size > succ->first) { STXXL_THROW(bad_ext_alloc, "DiskAllocator::check_corruption", "Error: double deallocation of external memory " << "System info: S " << region_pos << " " << region_size << " " << succ->first); } } } const char * wbtl_file::io_type() const { return "wbtl"; } __STXXL_END_NAMESPACE // vim: et:ts=4:sw=4 <commit_msg>count cached reads/writes, don't count wait time twice<commit_after>/*************************************************************************** * io/wbtl_file.cpp * * a write-buffered-translation-layer pseudo file * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2008-2009 Andreas Beckmann <beckmann@cs.uni-frankfurt.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <iomanip> #include <stxxl/bits/io/wbtl_file.h> #include <stxxl/bits/io/io.h> #include <stxxl/bits/common/debug.h> #include <stxxl/bits/parallel.h> #include <stxxl/aligned_alloc> #ifndef STXXL_VERBOSE_WBTL #define STXXL_VERBOSE_WBTL STXXL_VERBOSE0 #endif __STXXL_BEGIN_NAMESPACE wbtl_file::wbtl_file( file * backend_file, size_type write_buffer_size, int write_buffers, int disk) : file_request_basic(disk), storage(backend_file), sz(0), write_block_size(write_buffer_size), free_bytes(0), curbuf(1), curpos(write_block_size) { assert(write_buffers == 2); // currently hardcoded write_buffer[0] = static_cast<char *>(stxxl::aligned_alloc<BLOCK_ALIGN>(write_block_size)); write_buffer[1] = static_cast<char *>(stxxl::aligned_alloc<BLOCK_ALIGN>(write_block_size)); buffer_address[0] = offset_type(-1); buffer_address[1] = offset_type(-1); } wbtl_file::~wbtl_file() { stxxl::aligned_dealloc<BLOCK_ALIGN>(write_buffer[1]); stxxl::aligned_dealloc<BLOCK_ALIGN>(write_buffer[0]); delete storage; storage = 0; } void wbtl_file::serve(const stxxl::request* req) throw(io_error) { assert(req->get_file() == this); offset_type offset = req->get_offset(); void * buffer = req->get_buffer(); size_type bytes = req->get_size(); request::request_type type = req->get_type(); if (type == request::READ) { //stats::scoped_read_timer read_timer(size()); sread(buffer, offset, bytes); } else { //stats::scoped_write_timer write_timer(size()); swrite(buffer, offset, bytes); } } void wbtl_file::lock() { storage->lock(); } wbtl_file::offset_type wbtl_file::size() { return sz; } void wbtl_file::set_size(offset_type newsize) { scoped_mutex_lock mapping_lock(mapping_mutex); assert(sz <= newsize); // may not shrink if (sz < newsize) { _add_free_region(sz, newsize - sz); storage->set_size(newsize); sz = newsize; assert(sz == storage->size()); } } request_ptr wbtl_file::aread( void * buffer, offset_type pos, size_t bytes, completion_handler on_cmpl) { scoped_mutex_lock mapping_lock(mapping_mutex); if (address_mapping.find(pos) == address_mapping.end()) { STXXL_THROW2(io_error, "wbtl_aread of unmapped memory"); } return file_request_basic::aread(buffer, pos, bytes, on_cmpl); } #define FMT_A_S(_addr_,_size_) "0x" << std::hex << std::setfill('0') << std::setw(8) << (_addr_) << "/0x" << std::setw(8) << (_size_) #define FMT_A_C(_addr_,_size_) "0x" << std::setw(8) << (_addr_) << "(" << std::dec << (_size_) << ")" #define FMT_A(_addr_) "0x" << std::setw(8) << (_addr_) // logical address void wbtl_file::delete_region(offset_type offset, size_type size) { scoped_mutex_lock mapping_lock(mapping_mutex); sortseq::iterator physical = address_mapping.find(offset); STXXL_VERBOSE_WBTL("wbtl:delreg l" << FMT_A_S(offset, size) << " @ p" << FMT_A(physical != address_mapping.end() ? physical->second : 0xffffffff)); if (physical == address_mapping.end()) { // could be OK if the block was never written ... STXXL_ERRMSG("delete_region: mapping not found: " << FMT_A_S(offset, size) << " ==> " << "???"); } else { offset_type physical_offset = physical->second; address_mapping.erase(physical); _add_free_region(physical_offset, size); place_map::iterator reverse = reverse_mapping.find(physical_offset); if (reverse == reverse_mapping.end()) { STXXL_ERRMSG("delete_region: reverse mapping not found: " << FMT_A_S(offset, size) << " ==> " << "???"); } else { assert(offset == (reverse->second).first); reverse_mapping.erase(reverse); } storage->delete_region(physical_offset, size); } } // physical address void wbtl_file::_add_free_region(offset_type offset, offset_type size) { // mapping_lock has to be aquired by caller STXXL_VERBOSE_WBTL("wbtl:addfre p" << FMT_A_S(offset, size) << " F <= f" << FMT_A_C(free_bytes, free_space.size())); size_type region_pos = offset; size_type region_size = size; if (!free_space.empty()) { sortseq::iterator succ = free_space.upper_bound(region_pos); sortseq::iterator pred = succ; pred--; check_corruption(region_pos, region_size, pred, succ); if (succ == free_space.end()) { if (pred == free_space.end()) { //dump(); assert(pred != free_space.end()); } if ((*pred).first + (*pred).second == region_pos) { // coalesce with predecessor region_size += (*pred).second; region_pos = (*pred).first; free_space.erase(pred); } } else { if (free_space.size() > 1) { bool succ_is_not_the_first = (succ != free_space.begin()); if ((*succ).first == region_pos + region_size) { // coalesce with successor region_size += (*succ).second; free_space.erase(succ); } if (succ_is_not_the_first) { if (pred == free_space.end()) { //dump(); assert(pred != free_space.end()); } if ((*pred).first + (*pred).second == region_pos) { // coalesce with predecessor region_size += (*pred).second; region_pos = (*pred).first; free_space.erase(pred); } } } else { if ((*succ).first == region_pos + region_size) { // coalesce with successor region_size += (*succ).second; free_space.erase(succ); } } } } free_space[region_pos] = region_size; free_bytes += size; STXXL_VERBOSE_WBTL("wbtl:free p" << FMT_A_S(region_pos, region_size) << " F => f" << FMT_A_C(free_bytes, free_space.size())); } void wbtl_file::sread(void * buffer, offset_type offset, size_type bytes) { scoped_mutex_lock buffer_lock(buffer_mutex); int cached = -1; offset_type physical_offset; // map logical to physical address { scoped_mutex_lock mapping_lock(mapping_mutex); sortseq::iterator physical = address_mapping.find(offset); if (physical == address_mapping.end()) { STXXL_ERRMSG("wbtl_read: mapping not found: " << FMT_A_S(offset, bytes) << " ==> " << "???"); //STXXL_THROW2(io_error, "wbtl_read of unmapped memory"); physical_offset = 0xffffffff; } else { physical_offset = physical->second; } } if (buffer_address[curbuf] <= physical_offset && physical_offset < buffer_address[curbuf] + write_block_size) { // block is in current write buffer assert(physical_offset + bytes <= buffer_address[curbuf] + write_block_size); memcpy(buffer, write_buffer[curbuf] + (physical_offset - buffer_address[curbuf]), bytes); stats::get_instance()->read_cached(bytes); cached = curbuf; } else if (buffer_address[1 - curbuf] <= physical_offset && physical_offset < buffer_address[1 - curbuf] + write_block_size) { // block is in previous write buffer assert(physical_offset + bytes <= buffer_address[1 - curbuf] + write_block_size); memcpy(buffer, write_buffer[1 - curbuf] + (physical_offset - buffer_address[1 - curbuf]), bytes); stats::get_instance()->read_cached(bytes); cached = curbuf; } else { // block is not cached request_ptr req = storage->aread(buffer, physical_offset, bytes, default_completion_handler()); req->wait(false); } STXXL_VERBOSE_WBTL("wbtl:sread l" << FMT_A_S(offset, bytes) << " @ p" << FMT_A(physical_offset) << " " << std::dec << cached); } void wbtl_file::swrite(void * buffer, offset_type offset, size_type bytes) { scoped_mutex_lock buffer_lock(buffer_mutex); // is the block already mapped? { scoped_mutex_lock mapping_lock(mapping_mutex); sortseq::iterator physical = address_mapping.find(offset); STXXL_VERBOSE_WBTL("wbtl:swrite l" << FMT_A_S(offset, bytes) << " @ <= p" << FMT_A_C(physical != address_mapping.end() ? physical->second : 0xffffffff, address_mapping.size())); if (physical != address_mapping.end()) { mapping_lock.unlock(); // FIXME: special case if we can replace it in the current writing block delete_region(offset, bytes); } } if (bytes > write_block_size - curpos) { // not enough space in the current write buffer if (buffer_address[curbuf] != offset_type(-1)) { STXXL_VERBOSE_WBTL("wbtl:w2disk p" << FMT_A_S(buffer_address[curbuf], write_block_size)); // mark remaining part as free if (curpos < write_block_size) _add_free_region(buffer_address[curbuf] + curpos, write_block_size - curpos); if (backend_request.get()) { backend_request->wait(false); } backend_request = storage->awrite(write_buffer[curbuf], buffer_address[curbuf], write_block_size, default_completion_handler()); } curbuf = 1 - curbuf; buffer_address[curbuf] = get_next_write_block(); curpos = 0; } assert(bytes <= write_block_size - curpos); // write block into buffer memcpy(write_buffer[curbuf] + curpos, buffer, bytes); stats::get_instance()->write_cached(bytes); scoped_mutex_lock mapping_lock(mapping_mutex); address_mapping[offset] = buffer_address[curbuf] + curpos; reverse_mapping[buffer_address[curbuf] + curpos] = place(offset, bytes); STXXL_VERBOSE_WBTL("wbtl:swrite l" << FMT_A_S(offset, bytes) << " @ => p" << FMT_A_C(buffer_address[curbuf] + curpos, address_mapping.size())); curpos += bytes; } wbtl_file::offset_type wbtl_file::get_next_write_block() { // mapping_lock has to be aquired by caller sortseq::iterator space = std::find_if(free_space.begin(), free_space.end(), bind2nd(FirstFit(), write_block_size)); if (space != free_space.end()) { offset_type region_pos = (*space).first; offset_type region_size = (*space).second; free_space.erase(space); if (region_size > write_block_size) free_space[region_pos + write_block_size] = region_size - write_block_size; free_bytes -= write_block_size; STXXL_VERBOSE_WBTL("wbtl:nextwb p" << FMT_A_S(region_pos, write_block_size) << " F f" << FMT_A_C(free_bytes, free_space.size())); return region_pos; } STXXL_THROW2(io_error, "OutOfSpace, probably fragmented"); return -1; } void wbtl_file::check_corruption(offset_type region_pos, offset_type region_size, sortseq::iterator pred, sortseq::iterator succ) { if (pred != free_space.end()) { if (pred->first <= region_pos && pred->first + pred->second > region_pos) { STXXL_THROW(bad_ext_alloc, "DiskAllocator::check_corruption", "Error: double deallocation of external memory " << "System info: P " << pred->first << " " << pred->second << " " << region_pos); } } if (succ != free_space.end()) { if (region_pos <= succ->first && region_pos + region_size > succ->first) { STXXL_THROW(bad_ext_alloc, "DiskAllocator::check_corruption", "Error: double deallocation of external memory " << "System info: S " << region_pos << " " << region_size << " " << succ->first); } } } const char * wbtl_file::io_type() const { return "wbtl"; } __STXXL_END_NAMESPACE // vim: et:ts=4:sw=4 <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: biosdev.cc,v 1.2 2002/04/24 07:39:47 cbothamy Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Here are the virtual ports use to display messages from the bioses : // // 0x0400 : rombios Panic port with message // 0x0401 : rombios Panic port with line number // 0x0402 : rombios Info port with message // 0xfff0 : rombios Info port with message (legacy port) // 0x0403 : rombios Debug port with message // // 0x0500 : vgabios Info port with message // 0x0501 : vgabios Panic port with message // 0x0502 : vgabios Panic port with line number // 0x0503 : vgabios Debug port with message #include "bochs.h" bx_biosdev_c bx_biosdev; #if BX_USE_BIOS_SMF #define this (&bx_biosdev) #endif logfunctions *bioslog; logfunctions *vgabioslog; bx_biosdev_c::bx_biosdev_c(void) { bioslog = new logfunctions(); bioslog->put("BIOS"); bioslog->settype(BIOSLOG); s.bios_message_i = 0; vgabioslog = new logfunctions(); vgabioslog->put("VBIOS"); vgabioslog->settype(BIOSLOG); s.vgabios_message_i = 0; } bx_biosdev_c::~bx_biosdev_c(void) { if ( bioslog != NULL ) { delete bioslog; bioslog = NULL; } if ( vgabioslog != NULL ) { delete vgabioslog; vgabioslog = NULL; } } void bx_biosdev_c::init(bx_devices_c *d) { BX_BIOS_THIS devices = d; BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0400, "Bios Panic Port 1"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0401, "Bios Panic Port 2"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0403, "Bios Debug Port"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0402, "Bios Info Port"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0xfff0, "Bios Info Port (legacy)"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0501, "VGABios Panic Port 1"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0502, "VGABios Panic Port 2"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0503, "VGABios Debug Port"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0500, "VGABios Info Port"); } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_biosdev_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_BIOS_SMF bx_biosdev_c *class_ptr = (bx_biosdev_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_biosdev_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_BIOS_SMF UNUSED(io_len); switch (address) { // 0x400-0x401 are used as panic ports for the rombios case 0x0401: if (BX_BIOS_THIS s.bios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.bios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i] = 0; BX_BIOS_THIS s.bios_message_i = 0; bioslog->panic("%s", BX_BIOS_THIS s.bios_message); break; } case 0x0400: bioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0xfff0 is used as the info port for the rombios // 0x0402 is used as the info port for the rombios // 0x0403 is used as the debug port for the rombios case 0x0402: case 0x0403: BX_BIOS_THIS s.bios_message[BX_BIOS_THIS s.bios_message_i] = (Bit8u) value; BX_BIOS_THIS s.bios_message_i ++; if ( BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.bios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i - 1 ] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } break; // 0x501-0x502 are used as panic ports for the vgabios case 0x0502: if (BX_BIOS_THIS s.vgabios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.vgabios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; vgabioslog->panic("%s", BX_BIOS_THIS s.vgabios_message); break; } case 0x0501: vgabioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0x0500 is used as the message port for the vgabios case 0x0500: case 0x0503: BX_BIOS_THIS s.vgabios_message[BX_BIOS_THIS s.vgabios_message_i] = (Bit8u) value; BX_BIOS_THIS s.vgabios_message_i ++; if ( BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i - 1 ] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } break; default: break; } } <commit_msg>- i forgot to keep the 0xfff0 port management for older bioses. fixed<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: biosdev.cc,v 1.3 2002/04/24 11:52:13 cbothamy Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Here are the virtual ports use to display messages from the bioses : // // 0x0400 : rombios Panic port with message // 0x0401 : rombios Panic port with line number // 0x0402 : rombios Info port with message // 0xfff0 : rombios Info port with message (legacy port) // 0x0403 : rombios Debug port with message // // 0x0500 : vgabios Info port with message // 0x0501 : vgabios Panic port with message // 0x0502 : vgabios Panic port with line number // 0x0503 : vgabios Debug port with message #include "bochs.h" bx_biosdev_c bx_biosdev; #if BX_USE_BIOS_SMF #define this (&bx_biosdev) #endif logfunctions *bioslog; logfunctions *vgabioslog; bx_biosdev_c::bx_biosdev_c(void) { bioslog = new logfunctions(); bioslog->put("BIOS"); bioslog->settype(BIOSLOG); s.bios_message_i = 0; vgabioslog = new logfunctions(); vgabioslog->put("VBIOS"); vgabioslog->settype(BIOSLOG); s.vgabios_message_i = 0; } bx_biosdev_c::~bx_biosdev_c(void) { if ( bioslog != NULL ) { delete bioslog; bioslog = NULL; } if ( vgabioslog != NULL ) { delete vgabioslog; vgabioslog = NULL; } } void bx_biosdev_c::init(bx_devices_c *d) { BX_BIOS_THIS devices = d; BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0400, "Bios Panic Port 1"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0401, "Bios Panic Port 2"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0403, "Bios Debug Port"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0402, "Bios Info Port"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0xfff0, "Bios Info Port (legacy)"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0501, "VGABios Panic Port 1"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0502, "VGABios Panic Port 2"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0503, "VGABios Debug Port"); BX_BIOS_THIS devices->register_io_write_handler(this, write_handler, 0x0500, "VGABios Info Port"); } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_biosdev_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_BIOS_SMF bx_biosdev_c *class_ptr = (bx_biosdev_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_biosdev_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_BIOS_SMF UNUSED(io_len); switch (address) { // 0x400-0x401 are used as panic ports for the rombios case 0x0401: if (BX_BIOS_THIS s.bios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.bios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i] = 0; BX_BIOS_THIS s.bios_message_i = 0; bioslog->panic("%s", BX_BIOS_THIS s.bios_message); break; } case 0x0400: bioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0xfff0 is used as the info port for the rombios // 0x0402 is used as the info port for the rombios // 0x0403 is used as the debug port for the rombios case 0xfff0: case 0x0402: case 0x0403: BX_BIOS_THIS s.bios_message[BX_BIOS_THIS s.bios_message_i] = (Bit8u) value; BX_BIOS_THIS s.bios_message_i ++; if ( BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.bios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i - 1 ] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } break; // 0x501-0x502 are used as panic ports for the vgabios case 0x0502: if (BX_BIOS_THIS s.vgabios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.vgabios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; vgabioslog->panic("%s", BX_BIOS_THIS s.vgabios_message); break; } case 0x0501: vgabioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0x0500 is used as the message port for the vgabios case 0x0500: case 0x0503: BX_BIOS_THIS s.vgabios_message[BX_BIOS_THIS s.vgabios_message_i] = (Bit8u) value; BX_BIOS_THIS s.vgabios_message_i ++; if ( BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i - 1 ] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } break; default: break; } } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // $Id: biosdev.cc,v 1.6 2003/07/31 15:29:34 vruppert Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Here are the virtual ports use to display messages from the bioses : // // 0x0400 : rombios Panic port with message // 0x0401 : rombios Panic port with line number // 0x0402 : rombios Info port with message // 0xfff0 : rombios Info port with message (legacy port) // 0x0403 : rombios Debug port with message // // 0x0500 : vgabios Info port with message // 0x0501 : vgabios Panic port with message // 0x0502 : vgabios Panic port with line number // 0x0503 : vgabios Debug port with message // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE #include "bochs.h" bx_biosdev_c *theBiosDevice; int libbiosdev_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[]) { theBiosDevice = new bx_biosdev_c (); bx_devices.pluginBiosDevice = theBiosDevice; BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theBiosDevice, BX_PLUGIN_BIOSDEV); return(0); // Success } void libbiosdev_LTX_plugin_fini(void) { } logfunctions *bioslog; logfunctions *vgabioslog; bx_biosdev_c::bx_biosdev_c(void) { bioslog = new logfunctions(); bioslog->put("BIOS"); bioslog->settype(BIOSLOG); s.bios_message_i = 0; vgabioslog = new logfunctions(); vgabioslog->put("VBIOS"); vgabioslog->settype(BIOSLOG); s.vgabios_message_i = 0; } bx_biosdev_c::~bx_biosdev_c(void) { if ( bioslog != NULL ) { delete bioslog; bioslog = NULL; } if ( vgabioslog != NULL ) { delete vgabioslog; vgabioslog = NULL; } } void bx_biosdev_c::init(void) { DEV_register_iowrite_handler(this, write_handler, 0x0400, "Bios Panic Port 1", 3); DEV_register_iowrite_handler(this, write_handler, 0x0401, "Bios Panic Port 2", 3); DEV_register_iowrite_handler(this, write_handler, 0x0403, "Bios Debug Port", 1); DEV_register_iowrite_handler(this, write_handler, 0x0402, "Bios Info Port", 1); DEV_register_iowrite_handler(this, write_handler, 0xfff0, "Bios Info Port (legacy)", 1); DEV_register_iowrite_handler(this, write_handler, 0x0501, "VGABios Panic Port 1", 3); DEV_register_iowrite_handler(this, write_handler, 0x0502, "VGABios Panic Port 2", 3); DEV_register_iowrite_handler(this, write_handler, 0x0503, "VGABios Debug Port", 1); DEV_register_iowrite_handler(this, write_handler, 0x0500, "VGABios Info Port", 1); } void bx_biosdev_c::reset(unsigned type) { } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_biosdev_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_BIOS_SMF bx_biosdev_c *class_ptr = (bx_biosdev_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_biosdev_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_BIOS_SMF UNUSED(io_len); switch (address) { // 0x400-0x401 are used as panic ports for the rombios case 0x0401: if (BX_BIOS_THIS s.bios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.bios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i] = 0; BX_BIOS_THIS s.bios_message_i = 0; bioslog->panic("%s", BX_BIOS_THIS s.bios_message); break; } case 0x0400: bioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0xfff0 is used as the info port for the rombios // 0x0402 is used as the info port for the rombios // 0x0403 is used as the debug port for the rombios case 0xfff0: case 0x0402: case 0x0403: BX_BIOS_THIS s.bios_message[BX_BIOS_THIS s.bios_message_i] = (Bit8u) value; BX_BIOS_THIS s.bios_message_i ++; if ( BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.bios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i - 1 ] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } break; // 0x501-0x502 are used as panic ports for the vgabios case 0x0502: if (BX_BIOS_THIS s.vgabios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.vgabios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; vgabioslog->panic("%s", BX_BIOS_THIS s.vgabios_message); break; } case 0x0501: vgabioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0x0500 is used as the message port for the vgabios case 0x0500: case 0x0503: BX_BIOS_THIS s.vgabios_message[BX_BIOS_THIS s.vgabios_message_i] = (Bit8u) value; BX_BIOS_THIS s.vgabios_message_i ++; if ( BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i - 1 ] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } break; default: break; } } <commit_msg>Applied patch to remove 0xfff0 legacy port.<commit_after>///////////////////////////////////////////////////////////////////////// // $Id: biosdev.cc,v 1.7 2003/12/08 19:36:23 danielg4 Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2002 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Here are the virtual ports use to display messages from the bioses : // // 0x0400 : rombios Panic port with message // 0x0401 : rombios Panic port with line number // 0x0402 : rombios Info port with message // 0x0403 : rombios Debug port with message // // 0x0500 : vgabios Info port with message // 0x0501 : vgabios Panic port with message // 0x0502 : vgabios Panic port with line number // 0x0503 : vgabios Debug port with message // Define BX_PLUGGABLE in files that can be compiled into plugins. For // platforms that require a special tag on exported symbols, BX_PLUGGABLE // is used to know when we are exporting symbols and when we are importing. #define BX_PLUGGABLE #include "bochs.h" bx_biosdev_c *theBiosDevice; int libbiosdev_LTX_plugin_init(plugin_t *plugin, plugintype_t type, int argc, char *argv[]) { theBiosDevice = new bx_biosdev_c (); bx_devices.pluginBiosDevice = theBiosDevice; BX_REGISTER_DEVICE_DEVMODEL(plugin, type, theBiosDevice, BX_PLUGIN_BIOSDEV); return(0); // Success } void libbiosdev_LTX_plugin_fini(void) { } logfunctions *bioslog; logfunctions *vgabioslog; bx_biosdev_c::bx_biosdev_c(void) { bioslog = new logfunctions(); bioslog->put("BIOS"); bioslog->settype(BIOSLOG); s.bios_message_i = 0; vgabioslog = new logfunctions(); vgabioslog->put("VBIOS"); vgabioslog->settype(BIOSLOG); s.vgabios_message_i = 0; } bx_biosdev_c::~bx_biosdev_c(void) { if ( bioslog != NULL ) { delete bioslog; bioslog = NULL; } if ( vgabioslog != NULL ) { delete vgabioslog; vgabioslog = NULL; } } void bx_biosdev_c::init(void) { DEV_register_iowrite_handler(this, write_handler, 0x0400, "Bios Panic Port 1", 3); DEV_register_iowrite_handler(this, write_handler, 0x0401, "Bios Panic Port 2", 3); DEV_register_iowrite_handler(this, write_handler, 0x0403, "Bios Debug Port", 1); DEV_register_iowrite_handler(this, write_handler, 0x0402, "Bios Info Port", 1); DEV_register_iowrite_handler(this, write_handler, 0x0501, "VGABios Panic Port 1", 3); DEV_register_iowrite_handler(this, write_handler, 0x0502, "VGABios Panic Port 2", 3); DEV_register_iowrite_handler(this, write_handler, 0x0503, "VGABios Debug Port", 1); DEV_register_iowrite_handler(this, write_handler, 0x0500, "VGABios Info Port", 1); } void bx_biosdev_c::reset(unsigned type) { } // static IO port write callback handler // redirects to non-static class handler to avoid virtual functions void bx_biosdev_c::write_handler(void *this_ptr, Bit32u address, Bit32u value, unsigned io_len) { #if !BX_USE_BIOS_SMF bx_biosdev_c *class_ptr = (bx_biosdev_c *) this_ptr; class_ptr->write(address, value, io_len); } void bx_biosdev_c::write(Bit32u address, Bit32u value, unsigned io_len) { #else UNUSED(this_ptr); #endif // !BX_USE_BIOS_SMF UNUSED(io_len); switch (address) { // 0x400-0x401 are used as panic ports for the rombios case 0x0401: if (BX_BIOS_THIS s.bios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.bios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i] = 0; BX_BIOS_THIS s.bios_message_i = 0; bioslog->panic("%s", BX_BIOS_THIS s.bios_message); break; } case 0x0400: bioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0x0402 is used as the info port for the rombios // 0x0403 is used as the debug port for the rombios case 0x0402: case 0x0403: BX_BIOS_THIS s.bios_message[BX_BIOS_THIS s.bios_message_i] = (Bit8u) value; BX_BIOS_THIS s.bios_message_i ++; if ( BX_BIOS_THIS s.bios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.bios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.bios_message[ BX_BIOS_THIS s.bios_message_i - 1 ] = 0; BX_BIOS_THIS s.bios_message_i = 0; if (address==0x403) bioslog->ldebug("%s", BX_BIOS_THIS s.bios_message); else bioslog->info("%s", BX_BIOS_THIS s.bios_message); } break; // 0x501-0x502 are used as panic ports for the vgabios case 0x0502: if (BX_BIOS_THIS s.vgabios_message_i > 0) { // if there are bits of message in the buffer, print them as the // panic message. Otherwise fall into the next case. if (BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE) BX_BIOS_THIS s.vgabios_message_i = BX_BIOS_MESSAGE_SIZE-1; BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; vgabioslog->panic("%s", BX_BIOS_THIS s.vgabios_message); break; } case 0x0501: vgabioslog->panic("BIOS panic at rombios.c, line %d", value); break; // 0x0500 is used as the message port for the vgabios case 0x0500: case 0x0503: BX_BIOS_THIS s.vgabios_message[BX_BIOS_THIS s.vgabios_message_i] = (Bit8u) value; BX_BIOS_THIS s.vgabios_message_i ++; if ( BX_BIOS_THIS s.vgabios_message_i >= BX_BIOS_MESSAGE_SIZE ) { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_MESSAGE_SIZE - 1] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } else if ((value & 0xff) == '\n') { BX_BIOS_THIS s.vgabios_message[ BX_BIOS_THIS s.vgabios_message_i - 1 ] = 0; BX_BIOS_THIS s.vgabios_message_i = 0; if (address==0x503) vgabioslog->ldebug("%s", BX_BIOS_THIS s.vgabios_message); else vgabioslog->info("%s", BX_BIOS_THIS s.vgabios_message); } break; default: break; } } <|endoftext|>
<commit_before>#include "gen.h" #include <cstdio> #include <algorithm> #include <tuple> #include <vector> #include <numeric> using namespace std; struct BiEdge { vid_t from, to; weight_t w; bool operator<(const BiEdge& o) const { return tie(w, from, to) < tie(o.w, o.from, o.to); } }; struct { vector<vid_t> cmp; void init(vid_t n) { cmp = vector<vid_t>(n, 0); iota(cmp.begin(), cmp.end(), 0); } vid_t get(vid_t v) { return cmp[v] == v ? v : cmp[v] = get(cmp[v]); } void merge(vid_t v, vid_t u) { if (rand()&1) swap(v, u); cmp[v] = u; } } snm; int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s input\n", argv[0]); return 1; } readAll(argv[1]); int64_t prepareTime = -currentNanoTime(); vector<BiEdge> es; es.reserve(edgesCount / 2); for (vid_t v = 0; v < vertexCount; ++v) { for (eid_t i = edgesIds[v]; i < edgesIds[v + 1]; ++i) { vid_t u = edges[i].dest; if (u <= v) continue; weight_t w = edges[i].weight; es.push_back(BiEdge{v, u, w}); } } prepareTime += currentNanoTime(); int64_t calcTime = -currentNanoTime(); sort(es.begin(), es.end()); weight_t result = 0.0; snm.init(vertexCount); for (const BiEdge& e : es) { int cv = snm.get(e.from); int cu = snm.get(e.to); if (cv != cu) { result += e.w; snm.merge(cv, cu); } } calcTime += currentNanoTime(); printf("%.10lf\n", double(result)); fprintf(stderr, "%.3lf\n%.3lf\n", double(prepareTime) / 1e9, double(calcTime) / 1e9); return 0; } <commit_msg>Reference: move edge sorting to prepare stage.<commit_after>#include "gen.h" #include <cstdio> #include <algorithm> #include <tuple> #include <vector> #include <numeric> using namespace std; struct BiEdge { vid_t from, to; weight_t w; bool operator<(const BiEdge& o) const { return tie(w, from, to) < tie(o.w, o.from, o.to); } }; struct { vector<vid_t> cmp; void init(vid_t n) { cmp = vector<vid_t>(n, 0); iota(cmp.begin(), cmp.end(), 0); } vid_t get(vid_t v) { return cmp[v] == v ? v : cmp[v] = get(cmp[v]); } void merge(vid_t v, vid_t u) { if (rand()&1) swap(v, u); cmp[v] = u; } } snm; int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Usage: %s input\n", argv[0]); return 1; } readAll(argv[1]); int64_t prepareTime = -currentNanoTime(); vector<BiEdge> es; es.reserve(edgesCount / 2); for (vid_t v = 0; v < vertexCount; ++v) { for (eid_t i = edgesIds[v]; i < edgesIds[v + 1]; ++i) { vid_t u = edges[i].dest; if (u <= v) continue; weight_t w = edges[i].weight; es.push_back(BiEdge{v, u, w}); } } sort(es.begin(), es.end()); prepareTime += currentNanoTime(); int64_t calcTime = -currentNanoTime(); weight_t result = 0.0; snm.init(vertexCount); for (const BiEdge& e : es) { int cv = snm.get(e.from); int cu = snm.get(e.to); if (cv != cu) { result += e.w; snm.merge(cv, cu); } } calcTime += currentNanoTime(); printf("%.10lf\n", double(result)); fprintf(stderr, "%.3lf\n%.3lf\n", double(prepareTime) / 1e9, double(calcTime) / 1e9); return 0; } <|endoftext|>
<commit_before>/* =============================================================================== FILE: laszip.cpp CONTENTS: see corresponding header file PROGRAMMERS: martin.isenburg@gmail.com COPYRIGHT: (c) 2011, Martin Isenburg, LASSO - tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: see corresponding header file =============================================================================== */ #include "laszip.hpp" LASzip::LASzip() { algorithm = POINT_BY_POINT_RAW; version_major = 1; version_minor = 0; version_revision = 0; options = 0; num_items = 0; num_chunks = 1; num_points = -1; num_bytes = -1; items = 0; } LASzip::~LASzip() { if (items) delete [] items; } void LASitem::set(LASitem::Type t, unsigned short number) { switch (t) { case LASitem::POINT10: type = LASitem::POINT10; size = 20; version = 1; break; case LASitem::GPSTIME11: type = LASitem::GPSTIME11; size = 8; version = 1; break; case LASitem::RGB12: type = LASitem::RGB12; size = 6; version = 1; break; case LASitem::WAVEPACKET13: type = LASitem::WAVEPACKET13; size = 29; version = 0; break; case LASitem::BYTE: type = LASitem::BYTE; size = number; version = 1; break; default: throw 0; // BUG } return; } bool LASitem::is_type(LASitem::Type t) const { if (t != type) return false; switch (t) { case POINT10: if (size != 20) return false; break; case GPSTIME11: if (size != 8) return false; break; case RGB12: if (size != 6) return false; break; case WAVEPACKET13: if (size != 29) return false; break; case BYTE: if (size < 1) return false; break; default: return false; } return true; } bool LASitem::supported_type() const { switch (type) { case POINT10: case GPSTIME11: case RGB12: case WAVEPACKET13: case BYTE: return true; break; default: return false; } return false; } bool LASitem::supported_size() const { switch (type) { case POINT10: if (size != 20) return false; break; case GPSTIME11: if (size != 8) return false; break; case RGB12: if (size != 6) return false; break; case WAVEPACKET13: if (size != 29) return false; break; case BYTE: if (size < 1) return false; break; default: return false; } return true; } bool LASitem::supported_version() const { switch (type) { case POINT10: if (version > 1) return false; break; case GPSTIME11: if (version > 1) return false; break; case RGB12: if (version > 1) return false; break; case WAVEPACKET13: if (version > 1) return false; break; case BYTE: if (version > 1) return false; break; default: return false; } return true; } bool LASitem::supported() const { switch (type) { case POINT10: if (size != 20) return false; if (version > 1) return false; break; case GPSTIME11: if (size != 8) return false; if (version > 1) return false; break; case RGB12: if (size != 6) return false; if (version > 1) return false; break; case WAVEPACKET13: if (size != 29) return false; if (version > 1) return false; break; case BYTE: if (size < 1) return false; if (version > 1) return false; break; default: return false; } return true; } <commit_msg>VS2010 lint<commit_after>/* =============================================================================== FILE: laszip.cpp CONTENTS: see corresponding header file PROGRAMMERS: martin.isenburg@gmail.com COPYRIGHT: (c) 2011, Martin Isenburg, LASSO - tools to catch reality This is free software; you can redistribute and/or modify it under the terms of the GNU Lesser General Licence as published by the Free Software Foundation. See the COPYING file for more information. This software is distributed WITHOUT ANY WARRANTY and without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. CHANGE HISTORY: see corresponding header file =============================================================================== */ #include "laszip.hpp" LASzip::LASzip() { algorithm = POINT_BY_POINT_RAW; version_major = 1; version_minor = 0; version_revision = 0; options = 0; num_items = 0; num_chunks = 1; num_points = -1; num_bytes = -1; items = 0; } LASzip::~LASzip() { if (items) delete [] items; } void LASitem::set(LASitem::Type t, unsigned short number) { switch (t) { case LASitem::POINT10: type = LASitem::POINT10; size = 20; version = 1; break; case LASitem::GPSTIME11: type = LASitem::GPSTIME11; size = 8; version = 1; break; case LASitem::RGB12: type = LASitem::RGB12; size = 6; version = 1; break; case LASitem::WAVEPACKET13: type = LASitem::WAVEPACKET13; size = 29; version = 0; break; case LASitem::BYTE: type = LASitem::BYTE; size = number; version = 1; break; default: throw 0; // BUG } return; } bool LASitem::is_type(LASitem::Type t) const { if (t != type) return false; switch (t) { case POINT10: if (size != 20) return false; break; case GPSTIME11: if (size != 8) return false; break; case RGB12: if (size != 6) return false; break; case WAVEPACKET13: if (size != 29) return false; break; case BYTE: if (size < 1) return false; break; default: return false; } return true; } bool LASitem::supported_type() const { switch (type) { case POINT10: case GPSTIME11: case RGB12: case WAVEPACKET13: case BYTE: return true; break; } return false; } bool LASitem::supported_size() const { switch (type) { case POINT10: if (size != 20) return false; break; case GPSTIME11: if (size != 8) return false; break; case RGB12: if (size != 6) return false; break; case WAVEPACKET13: if (size != 29) return false; break; case BYTE: if (size < 1) return false; break; default: return false; } return true; } bool LASitem::supported_version() const { switch (type) { case POINT10: if (version > 1) return false; break; case GPSTIME11: if (version > 1) return false; break; case RGB12: if (version > 1) return false; break; case WAVEPACKET13: if (version > 1) return false; break; case BYTE: if (version > 1) return false; break; default: return false; } return true; } bool LASitem::supported() const { switch (type) { case POINT10: if (size != 20) return false; if (version > 1) return false; break; case GPSTIME11: if (size != 8) return false; if (version > 1) return false; break; case RGB12: if (size != 6) return false; if (version > 1) return false; break; case WAVEPACKET13: if (size != 29) return false; if (version > 1) return false; break; case BYTE: if (size < 1) return false; if (version > 1) return false; break; default: return false; } return true; } <|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 "mitkPlaneGeometryDataMapper2D.h" //mitk includes #include "mitkVtkPropRenderer.h" #include <mitkProperties.h> #include <mitkDataNode.h> #include <mitkPointSet.h> #include <mitkPlaneGeometry.h> #include <mitkPlaneOrientationProperty.h> #include <mitkLine.h> #include <mitkAbstractTransformGeometry.h> #include <mitkResliceMethodProperty.h> #include <mitkSlicedGeometry3D.h> //vtk includes #include <mitkIPropertyAliases.h> #include <vtkActor.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkLine.h> #include <vtkPoints.h> #include <vtkPolyData.h> mitk::PlaneGeometryDataMapper2D::AllInstancesContainer mitk::PlaneGeometryDataMapper2D::s_AllInstances; // input for this mapper ( = PlaneGeometryData) const mitk::PlaneGeometryData* mitk::PlaneGeometryDataMapper2D::GetInput() const { return static_cast< PlaneGeometryData * >(GetDataNode()->GetData()); } mitk::PlaneGeometryDataMapper2D::PlaneGeometryDataMapper2D() : m_RenderOrientationArrows( false ), m_ArrowOrientationPositive( true ), m_DepthValue(1.0f) { s_AllInstances.insert(this); } mitk::PlaneGeometryDataMapper2D::~PlaneGeometryDataMapper2D() { s_AllInstances.erase(this); } vtkProp* mitk::PlaneGeometryDataMapper2D::GetVtkProp(mitk::BaseRenderer * renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_CrosshairAssembly; } void mitk::PlaneGeometryDataMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); // The PlaneGeometryDataMapper2D mapper is special in that the rendering of // OTHER PlaneGeometryDatas affects how we render THIS PlaneGeometryData // (for the gap at the point where they intersect). A change in any of the // other PlaneGeometryData nodes could mean that we render ourself // differently, so we check for that here. bool generateDataRequired = false; for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it) { generateDataRequired = ls->IsGenerateDataRequired(renderer, this, (*it)->GetDataNode()); if (generateDataRequired) break; } ls->UpdateGenerateDataTime(); // Collect all other PlaneGeometryDatas that are being mapped by this mapper m_OtherPlaneGeometries.clear(); for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it) { Self *otherInstance = *it; // Skip ourself if (otherInstance == this) continue; mitk::DataNode *otherNode = otherInstance->GetDataNode(); if (!otherNode) continue; // Skip other PlaneGeometryData nodes that are not visible on this renderer if (!otherNode->IsVisible(renderer)) continue; PlaneGeometryData* otherData = dynamic_cast<PlaneGeometryData*>(otherNode->GetData()); if (!otherData) continue; PlaneGeometry* otherGeometry = dynamic_cast<PlaneGeometry*>(otherData->GetPlaneGeometry()); if ( otherGeometry && !dynamic_cast<AbstractTransformGeometry*>(otherData->GetPlaneGeometry()) ) { m_OtherPlaneGeometries.push_back(otherNode); } } CreateVtkCrosshair(renderer); ApplyAllProperties(renderer); } void mitk::PlaneGeometryDataMapper2D::CreateVtkCrosshair(mitk::BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if(!visible) return; PlaneGeometryData::Pointer input = const_cast< PlaneGeometryData * >(this->GetInput()); mitk::DataNode* geometryDataNode = renderer->GetCurrentWorldPlaneGeometryNode(); const PlaneGeometryData* rendererWorldPlaneGeometryData = dynamic_cast< PlaneGeometryData * >(geometryDataNode->GetData()); // intersecting with ourself? if ( input.IsNull() || input.GetPointer() == rendererWorldPlaneGeometryData) { return; //nothing to do in this case } const PlaneGeometry *inputPlaneGeometry = dynamic_cast< const PlaneGeometry * >( input->GetPlaneGeometry() ); const PlaneGeometry* worldPlaneGeometry = dynamic_cast< const PlaneGeometry* >( rendererWorldPlaneGeometryData->GetPlaneGeometry() ); if ( worldPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(worldPlaneGeometry)==NULL && inputPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(input->GetPlaneGeometry() )==NULL && inputPlaneGeometry->GetReferenceGeometry() ) { const BaseGeometry *referenceGeometry = inputPlaneGeometry->GetReferenceGeometry(); // calculate intersection of the plane data with the border of the // world geometry rectangle Point3D point1, point2; Line3D crossLine; // Calculate the intersection line of the input plane with the world plane if ( worldPlaneGeometry->IntersectionLine( inputPlaneGeometry, crossLine ) ) { Point3D boundingBoxMin, boundingBoxMax; boundingBoxMin = referenceGeometry->GetBoundingBox()->GetMinimum(); boundingBoxMax = referenceGeometry->GetBoundingBox()->GetMaximum(); referenceGeometry->IndexToWorld(boundingBoxMin,boundingBoxMin); referenceGeometry->IndexToWorld(boundingBoxMax,boundingBoxMax); // Then, clip this line with the (transformed) bounding box of the // reference geometry. crossLine.BoxLineIntersection( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2], boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2], crossLine.GetPoint(), crossLine.GetDirection(), point1, point2 ); crossLine.SetPoints(point1,point2); vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New(); // Now iterate through all other lines displayed in this window and // calculate the positions of intersection with the line to be // rendered; these positions will be stored in lineParams to form a // gap afterwards. NodesVectorType::iterator otherPlanesIt = m_OtherPlaneGeometries.begin(); NodesVectorType::iterator otherPlanesEnd = m_OtherPlaneGeometries.end(); std::vector<Point3D> intersections; intersections.push_back(point1); otherPlanesIt = m_OtherPlaneGeometries.begin(); int gapsize = 32; this->GetDataNode()->GetPropertyValue( "Crosshair.Gap Size",gapsize, NULL ); ScalarType lineLength = point1.EuclideanDistanceTo(point2); DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry(); ScalarType gapinmm = gapsize * displayGeometry->GetScaleFactorMMPerDisplayUnit(); float gapSizeParam = gapinmm / lineLength; while ( otherPlanesIt != otherPlanesEnd ) { PlaneGeometry *otherPlane = static_cast< PlaneGeometry * >( static_cast< PlaneGeometryData * >((*otherPlanesIt)->GetData() )->GetPlaneGeometry() ); if (otherPlane != inputPlaneGeometry && otherPlane != worldPlaneGeometry) { Point3D planeIntersection; otherPlane->IntersectionPoint(crossLine,planeIntersection); ScalarType sectionLength = point1.EuclideanDistanceTo(planeIntersection); ScalarType lineValue = sectionLength/lineLength; if(lineValue-gapSizeParam > 0.0) intersections.push_back(crossLine.GetPoint(lineValue-gapSizeParam)); else intersections.pop_back(); if(lineValue+gapSizeParam < 1.0) intersections.push_back(crossLine.GetPoint(lineValue+gapSizeParam)); } ++otherPlanesIt; } if(intersections.size()%2 == 1) intersections.push_back(point2); if(intersections.empty()) { this->DrawLine(point1,point2,lines,points); } else for(unsigned int i = 0 ; i< intersections.size()-1 ; i+=2) { this->DrawLine(intersections[i],intersections[i+1],lines,points); } // Add the points to the dataset linesPolyData->SetPoints(points); // Add the lines to the dataset linesPolyData->SetLines(lines); // Visualize vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(linesPolyData); LocalStorage* ls = m_LSH.GetLocalStorage(renderer); ls->m_CrosshairActor->SetMapper(mapper); // Determine if we should draw the area covered by the thick slicing, default is false. // This will also show the area of slices that do not have thick slice mode enabled bool showAreaOfThickSlicing = false; GetDataNode()->GetBoolProperty( "reslice.thickslices.showarea", showAreaOfThickSlicing ); // get the normal of the inputPlaneGeometry Vector3D normal = inputPlaneGeometry->GetNormal(); // determine the pixelSpacing in that direction double thickSliceDistance = SlicedGeometry3D::CalculateSpacing( referenceGeometry->GetSpacing(), normal ); IntProperty *intProperty=0; if( GetDataNode()->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) thickSliceDistance *= intProperty->GetValue()+0.5; else showAreaOfThickSlicing = false; // not the nicest place to do it, but we have the width of the visible bloc in MM here // so we store it in this fancy property GetDataNode()->SetFloatProperty( "reslice.thickslices.sizeinmm", thickSliceDistance*2 ); if ( showAreaOfThickSlicing ) { vtkSmartPointer<vtkCellArray> helperlines = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPolyData> helperlinesPolyData = vtkSmartPointer<vtkPolyData>::New(); // vectorToHelperLine defines how to reach the helperLine from the mainLine Vector3D vectorToHelperLine; vectorToHelperLine = normal; vectorToHelperLine.Normalize(); // got the right direction, so we multiply the width vectorToHelperLine *= thickSliceDistance; this->DrawLine(point1 - vectorToHelperLine, point2 - vectorToHelperLine,helperlines,points); this->DrawLine(point1 + vectorToHelperLine, point2 + vectorToHelperLine,helperlines,points); // Add the points to the dataset helperlinesPolyData->SetPoints(points); // Add the lines to the dataset helperlinesPolyData->SetLines(helperlines); // Visualize vtkSmartPointer<vtkPolyDataMapper> helperLinesmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); helperLinesmapper->SetInputData(helperlinesPolyData); ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xf0f0); ls->m_CrosshairActor->GetProperty()->SetLineStippleRepeatFactor(1); ls->m_CrosshairHelperLineActor->SetMapper(helperLinesmapper); ls->m_CrosshairAssembly->AddPart(ls->m_CrosshairHelperLineActor); } else { ls->m_CrosshairAssembly->RemovePart(ls->m_CrosshairHelperLineActor); ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xffff); } } } } void mitk::PlaneGeometryDataMapper2D::DrawLine( mitk::Point3D p0,mitk::Point3D p1, vtkCellArray* lines, vtkPoints* points ) { vtkIdType pidStart = points->InsertNextPoint(p0[0],p0[1], p0[2]); vtkIdType pidEnd = points->InsertNextPoint(p1[0],p1[1], p1[2]); vtkSmartPointer<vtkLine> lineVtk = vtkSmartPointer<vtkLine>::New(); lineVtk->GetPointIds()->SetId(0,pidStart); lineVtk->GetPointIds()->SetId(1,pidEnd); lines->InsertNextCell(lineVtk); } int mitk::PlaneGeometryDataMapper2D::DetermineThickSliceMode( DataNode * dn, int &thickSlicesNum ) { int thickSlicesMode = 0; // determine the state and the extend of the thick-slice mode mitk::ResliceMethodProperty *resliceMethodEnumProperty=0; if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty ) thickSlicesMode = resliceMethodEnumProperty->GetValueAsId(); IntProperty *intProperty=0; if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) { thickSlicesNum = intProperty->GetValue(); if(thickSlicesNum < 1) thickSlicesNum=0; if(thickSlicesNum > 10) thickSlicesNum=10; } if ( thickSlicesMode == 0 ) thickSlicesNum = 0; return thickSlicesMode; } void mitk::PlaneGeometryDataMapper2D::ApplyAllProperties( BaseRenderer *renderer ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairActor); Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairHelperLineActor); float thickness; this->GetDataNode()->GetFloatProperty("Line width",thickness,renderer); ls->m_CrosshairActor->GetProperty()->SetLineWidth(thickness); ls->m_CrosshairHelperLineActor->GetProperty()->SetLineWidth(thickness); PlaneOrientationProperty* decorationProperty; this->GetDataNode()->GetProperty( decorationProperty, "decoration", renderer ); if ( decorationProperty != NULL ) { if ( decorationProperty->GetPlaneDecoration() == PlaneOrientationProperty::PLANE_DECORATION_POSITIVE_ORIENTATION ) { m_RenderOrientationArrows = true; m_ArrowOrientationPositive = true; } else if ( decorationProperty->GetPlaneDecoration() == PlaneOrientationProperty::PLANE_DECORATION_NEGATIVE_ORIENTATION ) { m_RenderOrientationArrows = true; m_ArrowOrientationPositive = false; } else { m_RenderOrientationArrows = false; } } } void mitk::PlaneGeometryDataMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { mitk::IPropertyAliases* aliases = mitk::CoreServices::GetPropertyAliases(); node->AddProperty( "Line width", mitk::FloatProperty::New(1), renderer, overwrite ); aliases->AddAlias( "line width", "Crosshair.Line Width", ""); node->AddProperty( "Crosshair.Gap Size", mitk::IntProperty::New(32), renderer, overwrite ); node->AddProperty( "decoration", mitk::PlaneOrientationProperty ::New(PlaneOrientationProperty::PLANE_DECORATION_NONE), renderer, overwrite ); aliases->AddAlias( "decoration", "Crosshair.Orientation Decoration", ""); Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::PlaneGeometryDataMapper2D::UpdateVtkTransform(mitk::BaseRenderer* /*renderer*/) { } mitk::PlaneGeometryDataMapper2D::LocalStorage::LocalStorage() { m_CrosshairAssembly = vtkSmartPointer <vtkPropAssembly>::New(); m_CrosshairActor = vtkSmartPointer <vtkActor>::New(); m_CrosshairHelperLineActor = vtkSmartPointer <vtkActor>::New(); m_CrosshairAssembly->AddPart(m_CrosshairActor); m_CrosshairAssembly->AddPart(m_CrosshairHelperLineActor); } mitk::PlaneGeometryDataMapper2D::LocalStorage::~LocalStorage() { } <commit_msg>use cornerpoint instead of bounds for the crosshair as it takes 0.5 offset into account<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 "mitkPlaneGeometryDataMapper2D.h" //mitk includes #include "mitkVtkPropRenderer.h" #include <mitkProperties.h> #include <mitkDataNode.h> #include <mitkPointSet.h> #include <mitkPlaneGeometry.h> #include <mitkPlaneOrientationProperty.h> #include <mitkLine.h> #include <mitkAbstractTransformGeometry.h> #include <mitkResliceMethodProperty.h> #include <mitkSlicedGeometry3D.h> //vtk includes #include <mitkIPropertyAliases.h> #include <vtkActor.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkLine.h> #include <vtkPoints.h> #include <vtkPolyData.h> mitk::PlaneGeometryDataMapper2D::AllInstancesContainer mitk::PlaneGeometryDataMapper2D::s_AllInstances; // input for this mapper ( = PlaneGeometryData) const mitk::PlaneGeometryData* mitk::PlaneGeometryDataMapper2D::GetInput() const { return static_cast< PlaneGeometryData * >(GetDataNode()->GetData()); } mitk::PlaneGeometryDataMapper2D::PlaneGeometryDataMapper2D() : m_RenderOrientationArrows( false ), m_ArrowOrientationPositive( true ), m_DepthValue(1.0f) { s_AllInstances.insert(this); } mitk::PlaneGeometryDataMapper2D::~PlaneGeometryDataMapper2D() { s_AllInstances.erase(this); } vtkProp* mitk::PlaneGeometryDataMapper2D::GetVtkProp(mitk::BaseRenderer * renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_CrosshairAssembly; } void mitk::PlaneGeometryDataMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); // The PlaneGeometryDataMapper2D mapper is special in that the rendering of // OTHER PlaneGeometryDatas affects how we render THIS PlaneGeometryData // (for the gap at the point where they intersect). A change in any of the // other PlaneGeometryData nodes could mean that we render ourself // differently, so we check for that here. bool generateDataRequired = false; for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it) { generateDataRequired = ls->IsGenerateDataRequired(renderer, this, (*it)->GetDataNode()); if (generateDataRequired) break; } ls->UpdateGenerateDataTime(); // Collect all other PlaneGeometryDatas that are being mapped by this mapper m_OtherPlaneGeometries.clear(); for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it) { Self *otherInstance = *it; // Skip ourself if (otherInstance == this) continue; mitk::DataNode *otherNode = otherInstance->GetDataNode(); if (!otherNode) continue; // Skip other PlaneGeometryData nodes that are not visible on this renderer if (!otherNode->IsVisible(renderer)) continue; PlaneGeometryData* otherData = dynamic_cast<PlaneGeometryData*>(otherNode->GetData()); if (!otherData) continue; PlaneGeometry* otherGeometry = dynamic_cast<PlaneGeometry*>(otherData->GetPlaneGeometry()); if ( otherGeometry && !dynamic_cast<AbstractTransformGeometry*>(otherData->GetPlaneGeometry()) ) { m_OtherPlaneGeometries.push_back(otherNode); } } CreateVtkCrosshair(renderer); ApplyAllProperties(renderer); } void mitk::PlaneGeometryDataMapper2D::CreateVtkCrosshair(mitk::BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if(!visible) return; PlaneGeometryData::Pointer input = const_cast< PlaneGeometryData * >(this->GetInput()); mitk::DataNode* geometryDataNode = renderer->GetCurrentWorldPlaneGeometryNode(); const PlaneGeometryData* rendererWorldPlaneGeometryData = dynamic_cast< PlaneGeometryData * >(geometryDataNode->GetData()); // intersecting with ourself? if ( input.IsNull() || input.GetPointer() == rendererWorldPlaneGeometryData) { return; //nothing to do in this case } const PlaneGeometry *inputPlaneGeometry = dynamic_cast< const PlaneGeometry * >( input->GetPlaneGeometry() ); const PlaneGeometry* worldPlaneGeometry = dynamic_cast< const PlaneGeometry* >( rendererWorldPlaneGeometryData->GetPlaneGeometry() ); if ( worldPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(worldPlaneGeometry)==NULL && inputPlaneGeometry && dynamic_cast<const AbstractTransformGeometry*>(input->GetPlaneGeometry() )==NULL && inputPlaneGeometry->GetReferenceGeometry() ) { const BaseGeometry *referenceGeometry = inputPlaneGeometry->GetReferenceGeometry(); // calculate intersection of the plane data with the border of the // world geometry rectangle Point3D point1, point2; Line3D crossLine; // Calculate the intersection line of the input plane with the world plane if ( worldPlaneGeometry->IntersectionLine( inputPlaneGeometry, crossLine ) ) { Point3D boundingBoxMin, boundingBoxMax; boundingBoxMin = referenceGeometry->GetCornerPoint(0); boundingBoxMax = referenceGeometry->GetCornerPoint(7); // Then, clip this line with the (transformed) bounding box of the // reference geometry. crossLine.BoxLineIntersection( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2], boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2], crossLine.GetPoint(), crossLine.GetDirection(), point1, point2 ); crossLine.SetPoints(point1,point2); vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkPolyData> linesPolyData = vtkSmartPointer<vtkPolyData>::New(); // Now iterate through all other lines displayed in this window and // calculate the positions of intersection with the line to be // rendered; these positions will be stored in lineParams to form a // gap afterwards. NodesVectorType::iterator otherPlanesIt = m_OtherPlaneGeometries.begin(); NodesVectorType::iterator otherPlanesEnd = m_OtherPlaneGeometries.end(); std::vector<Point3D> intersections; intersections.push_back(point1); otherPlanesIt = m_OtherPlaneGeometries.begin(); int gapsize = 32; this->GetDataNode()->GetPropertyValue( "Crosshair.Gap Size",gapsize, NULL ); ScalarType lineLength = point1.EuclideanDistanceTo(point2); DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry(); ScalarType gapinmm = gapsize * displayGeometry->GetScaleFactorMMPerDisplayUnit(); float gapSizeParam = gapinmm / lineLength; while ( otherPlanesIt != otherPlanesEnd ) { PlaneGeometry *otherPlane = static_cast< PlaneGeometry * >( static_cast< PlaneGeometryData * >((*otherPlanesIt)->GetData() )->GetPlaneGeometry() ); if (otherPlane != inputPlaneGeometry && otherPlane != worldPlaneGeometry) { Point3D planeIntersection; otherPlane->IntersectionPoint(crossLine,planeIntersection); ScalarType sectionLength = point1.EuclideanDistanceTo(planeIntersection); ScalarType lineValue = sectionLength/lineLength; if(lineValue-gapSizeParam > 0.0) intersections.push_back(crossLine.GetPoint(lineValue-gapSizeParam)); else intersections.pop_back(); if(lineValue+gapSizeParam < 1.0) intersections.push_back(crossLine.GetPoint(lineValue+gapSizeParam)); } ++otherPlanesIt; } if(intersections.size()%2 == 1) intersections.push_back(point2); if(intersections.empty()) { this->DrawLine(point1,point2,lines,points); } else for(unsigned int i = 0 ; i< intersections.size()-1 ; i+=2) { this->DrawLine(intersections[i],intersections[i+1],lines,points); } // Add the points to the dataset linesPolyData->SetPoints(points); // Add the lines to the dataset linesPolyData->SetLines(lines); // Visualize vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper->SetInputData(linesPolyData); LocalStorage* ls = m_LSH.GetLocalStorage(renderer); ls->m_CrosshairActor->SetMapper(mapper); // Determine if we should draw the area covered by the thick slicing, default is false. // This will also show the area of slices that do not have thick slice mode enabled bool showAreaOfThickSlicing = false; GetDataNode()->GetBoolProperty( "reslice.thickslices.showarea", showAreaOfThickSlicing ); // get the normal of the inputPlaneGeometry Vector3D normal = inputPlaneGeometry->GetNormal(); // determine the pixelSpacing in that direction double thickSliceDistance = SlicedGeometry3D::CalculateSpacing( referenceGeometry->GetSpacing(), normal ); IntProperty *intProperty=0; if( GetDataNode()->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) thickSliceDistance *= intProperty->GetValue()+0.5; else showAreaOfThickSlicing = false; // not the nicest place to do it, but we have the width of the visible bloc in MM here // so we store it in this fancy property GetDataNode()->SetFloatProperty( "reslice.thickslices.sizeinmm", thickSliceDistance*2 ); if ( showAreaOfThickSlicing ) { vtkSmartPointer<vtkCellArray> helperlines = vtkSmartPointer<vtkCellArray>::New(); vtkSmartPointer<vtkPolyData> helperlinesPolyData = vtkSmartPointer<vtkPolyData>::New(); // vectorToHelperLine defines how to reach the helperLine from the mainLine Vector3D vectorToHelperLine; vectorToHelperLine = normal; vectorToHelperLine.Normalize(); // got the right direction, so we multiply the width vectorToHelperLine *= thickSliceDistance; this->DrawLine(point1 - vectorToHelperLine, point2 - vectorToHelperLine,helperlines,points); this->DrawLine(point1 + vectorToHelperLine, point2 + vectorToHelperLine,helperlines,points); // Add the points to the dataset helperlinesPolyData->SetPoints(points); // Add the lines to the dataset helperlinesPolyData->SetLines(helperlines); // Visualize vtkSmartPointer<vtkPolyDataMapper> helperLinesmapper = vtkSmartPointer<vtkPolyDataMapper>::New(); helperLinesmapper->SetInputData(helperlinesPolyData); ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xf0f0); ls->m_CrosshairActor->GetProperty()->SetLineStippleRepeatFactor(1); ls->m_CrosshairHelperLineActor->SetMapper(helperLinesmapper); ls->m_CrosshairAssembly->AddPart(ls->m_CrosshairHelperLineActor); } else { ls->m_CrosshairAssembly->RemovePart(ls->m_CrosshairHelperLineActor); ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xffff); } } } } void mitk::PlaneGeometryDataMapper2D::DrawLine( mitk::Point3D p0,mitk::Point3D p1, vtkCellArray* lines, vtkPoints* points ) { vtkIdType pidStart = points->InsertNextPoint(p0[0],p0[1], p0[2]); vtkIdType pidEnd = points->InsertNextPoint(p1[0],p1[1], p1[2]); vtkSmartPointer<vtkLine> lineVtk = vtkSmartPointer<vtkLine>::New(); lineVtk->GetPointIds()->SetId(0,pidStart); lineVtk->GetPointIds()->SetId(1,pidEnd); lines->InsertNextCell(lineVtk); } int mitk::PlaneGeometryDataMapper2D::DetermineThickSliceMode( DataNode * dn, int &thickSlicesNum ) { int thickSlicesMode = 0; // determine the state and the extend of the thick-slice mode mitk::ResliceMethodProperty *resliceMethodEnumProperty=0; if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty ) thickSlicesMode = resliceMethodEnumProperty->GetValueAsId(); IntProperty *intProperty=0; if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) { thickSlicesNum = intProperty->GetValue(); if(thickSlicesNum < 1) thickSlicesNum=0; if(thickSlicesNum > 10) thickSlicesNum=10; } if ( thickSlicesMode == 0 ) thickSlicesNum = 0; return thickSlicesMode; } void mitk::PlaneGeometryDataMapper2D::ApplyAllProperties( BaseRenderer *renderer ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairActor); Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairHelperLineActor); float thickness; this->GetDataNode()->GetFloatProperty("Line width",thickness,renderer); ls->m_CrosshairActor->GetProperty()->SetLineWidth(thickness); ls->m_CrosshairHelperLineActor->GetProperty()->SetLineWidth(thickness); PlaneOrientationProperty* decorationProperty; this->GetDataNode()->GetProperty( decorationProperty, "decoration", renderer ); if ( decorationProperty != NULL ) { if ( decorationProperty->GetPlaneDecoration() == PlaneOrientationProperty::PLANE_DECORATION_POSITIVE_ORIENTATION ) { m_RenderOrientationArrows = true; m_ArrowOrientationPositive = true; } else if ( decorationProperty->GetPlaneDecoration() == PlaneOrientationProperty::PLANE_DECORATION_NEGATIVE_ORIENTATION ) { m_RenderOrientationArrows = true; m_ArrowOrientationPositive = false; } else { m_RenderOrientationArrows = false; } } } void mitk::PlaneGeometryDataMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { mitk::IPropertyAliases* aliases = mitk::CoreServices::GetPropertyAliases(); node->AddProperty( "Line width", mitk::FloatProperty::New(1), renderer, overwrite ); aliases->AddAlias( "line width", "Crosshair.Line Width", ""); node->AddProperty( "Crosshair.Gap Size", mitk::IntProperty::New(32), renderer, overwrite ); node->AddProperty( "decoration", mitk::PlaneOrientationProperty ::New(PlaneOrientationProperty::PLANE_DECORATION_NONE), renderer, overwrite ); aliases->AddAlias( "decoration", "Crosshair.Orientation Decoration", ""); Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::PlaneGeometryDataMapper2D::UpdateVtkTransform(mitk::BaseRenderer* /*renderer*/) { } mitk::PlaneGeometryDataMapper2D::LocalStorage::LocalStorage() { m_CrosshairAssembly = vtkSmartPointer <vtkPropAssembly>::New(); m_CrosshairActor = vtkSmartPointer <vtkActor>::New(); m_CrosshairHelperLineActor = vtkSmartPointer <vtkActor>::New(); m_CrosshairAssembly->AddPart(m_CrosshairActor); m_CrosshairAssembly->AddPart(m_CrosshairHelperLineActor); } mitk::PlaneGeometryDataMapper2D::LocalStorage::~LocalStorage() { } <|endoftext|>
<commit_before>/* * THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit * COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE: * https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md */ #include "chronotext/cinder/CinderSketchSimple.h" #include "chronotext/cinder/CinderApp.h" using namespace std; using namespace ci; using namespace app; namespace chronotext { CinderSketchSimple::CinderSketchSimple(void *context, void *delegate) : CinderSketchBase(), context(static_cast<AppNative*>(context)), delegate(static_cast<CinderApp*>(delegate)), mClock(new FrameClock()), mTimeline(Timeline::create()) {} int CinderSketchSimple::getWindowWidth() const { return getWindowInfo().size.x; } int CinderSketchSimple::getWindowHeight() const { return getWindowInfo().size.y; } Vec2f CinderSketchSimple::getWindowCenter() const { const auto &size = getWindowInfo().size; return size * 0.5f; } Vec2i CinderSketchSimple::getWindowSize() const { return getWindowInfo().size; } float CinderSketchSimple::getWindowAspectRatio() const { const auto &size = getWindowInfo().size; return size.x / (float)size.y; } Area CinderSketchSimple::getWindowBounds() const { const auto &size = getWindowInfo().size; return Area(0, 0, size.x, size.y); } float CinderSketchSimple::getWindowContentScale() const { return getWindowInfo().contentScale; } WindowInfo CinderSketchSimple::getWindowInfo() const { WindowInfo info = SystemInfo::instance().getWindowInfo(); if (info.size == Vec2i::zero()) { info.size = getWindowSize(); } if (info.contentScale == 0) { info.contentScale = getWindowContentScale(); } switch (static_pointer_cast<RendererGl>(context->getRenderer())->getAntiAliasing()) { case RendererGl::AA_NONE: info.aaLevel = 0; break; case RendererGl::AA_MSAA_2: info.aaLevel = 2; break; case RendererGl::AA_MSAA_4: info.aaLevel = 4; break; case RendererGl::AA_MSAA_6: info.aaLevel = 6; break; case RendererGl::AA_MSAA_8: info.aaLevel = 8; break; case RendererGl::AA_MSAA_16: info.aaLevel = 16; break; case RendererGl::AA_MSAA_32: info.aaLevel = 32; break; } return info; } void CinderSketchSimple::sendMessageToDelegate(int what, const string &body) { if (delegate) { delegate->receiveMessageFromSketch(what, body); } } } <commit_msg>FIXING RECENTLY-INTRODUCED BUG IN “NON EMULATED SKETCHES” ON DESKTOP<commit_after>/* * THE NEW CHRONOTEXT TOOLKIT: https://github.com/arielm/new-chronotext-toolkit * COPYRIGHT (C) 2012-2014, ARIEL MALKA ALL RIGHTS RESERVED. * * THE FOLLOWING SOURCE-CODE IS DISTRIBUTED UNDER THE MODIFIED BSD LICENSE: * https://github.com/arielm/new-chronotext-toolkit/blob/master/LICENSE.md */ #include "chronotext/cinder/CinderSketchSimple.h" #include "chronotext/cinder/CinderApp.h" using namespace std; using namespace ci; using namespace app; namespace chronotext { CinderSketchSimple::CinderSketchSimple(void *context, void *delegate) : CinderSketchBase(), context(static_cast<AppNative*>(context)), delegate(static_cast<CinderApp*>(delegate)), mClock(new FrameClock()), mTimeline(Timeline::create()) {} int CinderSketchSimple::getWindowWidth() const { return getWindowInfo().size.x; } int CinderSketchSimple::getWindowHeight() const { return getWindowInfo().size.y; } Vec2f CinderSketchSimple::getWindowCenter() const { const auto &size = getWindowInfo().size; return size * 0.5f; } Vec2i CinderSketchSimple::getWindowSize() const { return getWindowInfo().size; } float CinderSketchSimple::getWindowAspectRatio() const { const auto &size = getWindowInfo().size; return size.x / (float)size.y; } Area CinderSketchSimple::getWindowBounds() const { const auto &size = getWindowInfo().size; return Area(0, 0, size.x, size.y); } float CinderSketchSimple::getWindowContentScale() const { return getWindowInfo().contentScale; } WindowInfo CinderSketchSimple::getWindowInfo() const { WindowInfo info = SystemInfo::instance().getWindowInfo(); if (info.size == Vec2i::zero()) { info.size = context->getWindowSize(); } if (info.contentScale == 0) { info.contentScale = context->getWindowContentScale(); } switch (static_pointer_cast<RendererGl>(context->getRenderer())->getAntiAliasing()) { case RendererGl::AA_NONE: info.aaLevel = 0; break; case RendererGl::AA_MSAA_2: info.aaLevel = 2; break; case RendererGl::AA_MSAA_4: info.aaLevel = 4; break; case RendererGl::AA_MSAA_6: info.aaLevel = 6; break; case RendererGl::AA_MSAA_8: info.aaLevel = 8; break; case RendererGl::AA_MSAA_16: info.aaLevel = 16; break; case RendererGl::AA_MSAA_32: info.aaLevel = 32; break; } return info; } void CinderSketchSimple::sendMessageToDelegate(int what, const string &body) { if (delegate) { delegate->receiveMessageFromSketch(what, body); } } } <|endoftext|>
<commit_before>//****************************************************************************** // FILE : function_matrix.hpp // // LAST MODIFIED : 23 February 2005 // // DESCRIPTION : //============================================================================== #if !defined (__FUNCTION_MATRIX_HPP__) #define __FUNCTION_MATRIX_HPP__ #include <list> #include <utility> #include "computed_variable/function.hpp" EXPORT template<typename Value_type> class Function_matrix : public Function //****************************************************************************** // LAST MODIFIED : 23 February 2005 // // DESCRIPTION : // An identity function whose input/output is a matrix //============================================================================== { template<class Value_type_1,class Value_type_2> friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &, boost::intrusive_ptr<Value_type_2> const &); public: // constructor Function_matrix(ublas::matrix<Value_type,ublas::column_major>& values); // destructor ~Function_matrix(); // inherited public: virtual string_handle get_string_representation(); virtual Function_variable_handle input(); virtual Function_variable_handle output(); // additional public: // get the matrix values const ublas::matrix<Value_type,ublas::column_major>& matrix(); // get a matrix entry variable virtual Function_variable_handle entry(Function_size_type, Function_size_type); // get a matrix entry value. NB. row and column start from 1 virtual Value_type& operator()(Function_size_type row, Function_size_type column); // get the specified sub-matrix virtual boost::intrusive_ptr< Function_matrix<Value_type> > sub_matrix(Function_size_type row_low, Function_size_type row_high,Function_size_type column_low, Function_size_type column_high) const; virtual Function_size_type number_of_rows() const; virtual Function_size_type number_of_columns() const; // solve a system of linear equations boost::intrusive_ptr< Function_matrix<Value_type> > solve( const boost::intrusive_ptr< Function_matrix<Value_type> >&); // calculate the determinant (zero for non-square matrix) virtual bool determinant(Value_type&); private: #if defined (EVALUATE_RETURNS_VALUE) virtual Function_handle evaluate(Function_variable_handle atomic_variable); #else // defined (EVALUATE_RETURNS_VALUE) virtual bool evaluate(Function_variable_handle atomic_variable); #endif // defined (EVALUATE_RETURNS_VALUE) virtual bool evaluate_derivative(Scalar& derivative, Function_variable_handle atomic_variable, std::list<Function_variable_handle>& atomic_independent_variables); virtual bool set_value(Function_variable_handle atomic_variable, Function_variable_handle atomic_value); virtual Function_handle get_value(Function_variable_handle atomic_variable); protected: // copy constructor Function_matrix(const Function_matrix&); private: // assignment Function_matrix& operator=(const Function_matrix&); // equality virtual bool operator==(const Function&) const; protected: ublas::matrix<Value_type,ublas::column_major> values; }; #if defined (OLD_CODE) #if !defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED) #include "computed_variable/function_matrix_implementation.cpp" #endif // !defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED) #endif // defined (OLD_CODE) #endif /* !defined (__FUNCTION_MATRIX_HPP__) */ <commit_msg>Changed OLD_CODE to DO_NOT_EXPLICITLY_INCLUDE_function_matrix_implementation<commit_after>//****************************************************************************** // FILE : function_matrix.hpp // // LAST MODIFIED : 28 June 2005 // // DESCRIPTION : //============================================================================== #if !defined (__FUNCTION_MATRIX_HPP__) #define __FUNCTION_MATRIX_HPP__ //#define DO_NOT_EXPLICITLY_INCLUDE_function_matrix_implementation #include <list> #include <utility> #include "computed_variable/function.hpp" EXPORT template<typename Value_type> class Function_matrix : public Function //****************************************************************************** // LAST MODIFIED : 23 February 2005 // // DESCRIPTION : // An identity function whose input/output is a matrix //============================================================================== { template<class Value_type_1,class Value_type_2> friend bool equivalent(boost::intrusive_ptr<Value_type_1> const &, boost::intrusive_ptr<Value_type_2> const &); public: // constructor Function_matrix(ublas::matrix<Value_type,ublas::column_major>& values); // destructor ~Function_matrix(); // inherited public: virtual string_handle get_string_representation(); virtual Function_variable_handle input(); virtual Function_variable_handle output(); // additional public: // get the matrix values const ublas::matrix<Value_type,ublas::column_major>& matrix(); // get a matrix entry variable virtual Function_variable_handle entry(Function_size_type, Function_size_type); // get a matrix entry value. NB. row and column start from 1 virtual Value_type& operator()(Function_size_type row, Function_size_type column); // get the specified sub-matrix virtual boost::intrusive_ptr< Function_matrix<Value_type> > sub_matrix(Function_size_type row_low, Function_size_type row_high,Function_size_type column_low, Function_size_type column_high) const; virtual Function_size_type number_of_rows() const; virtual Function_size_type number_of_columns() const; // solve a system of linear equations boost::intrusive_ptr< Function_matrix<Value_type> > solve( const boost::intrusive_ptr< Function_matrix<Value_type> >&); // calculate the determinant (zero for non-square matrix) virtual bool determinant(Value_type&); private: #if defined (EVALUATE_RETURNS_VALUE) virtual Function_handle evaluate(Function_variable_handle atomic_variable); #else // defined (EVALUATE_RETURNS_VALUE) virtual bool evaluate(Function_variable_handle atomic_variable); #endif // defined (EVALUATE_RETURNS_VALUE) virtual bool evaluate_derivative(Scalar& derivative, Function_variable_handle atomic_variable, std::list<Function_variable_handle>& atomic_independent_variables); virtual bool set_value(Function_variable_handle atomic_variable, Function_variable_handle atomic_value); virtual Function_handle get_value(Function_variable_handle atomic_variable); protected: // copy constructor Function_matrix(const Function_matrix&); private: // assignment Function_matrix& operator=(const Function_matrix&); // equality virtual bool operator==(const Function&) const; protected: ublas::matrix<Value_type,ublas::column_major> values; }; #if defined (DO_NOT_EXPLICITLY_INCLUDE_function_matrix_implementation) #if !defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED) #include "computed_variable/function_matrix_implementation.cpp" #endif // !defined (ONE_TEMPLATE_DEFINITION_IMPLEMENTED) #endif // defined (DO_NOT_EXPLICITLY_INCLUDE_function_matrix_implementation) #endif /* !defined (__FUNCTION_MATRIX_HPP__) */ <|endoftext|>
<commit_before>//----------------------------------*-C++-*----------------------------------// /*! * \file spn/test/tstFixed_Source_Solver.cc * \author Thomas M. Evans * \date Sun Nov 18 19:05:06 2012 * \brief Test of Fixed_Source_Solver class. * \note Copyright (C) 2012 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include <vector> #include "gtest/utils_gtest.hh" #include "Teuchos_StandardCatchMacros.hpp" #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" #include "utils/Definitions.hh" #include "mesh/Partitioner.hh" #include "../Dimensions.hh" #include "../Fixed_Source_Solver.hh" #include "Test_XS.hh" using namespace std; //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// class Inf_Med_Solver_FVTest : public testing::Test { protected: typedef profugus::Fixed_Source_Solver Fixed_Source_Solver; typedef Teuchos::RCP<Fixed_Source_Solver> RCP_Linear_Solver; typedef Fixed_Source_Solver::RCP_ParameterList RCP_ParameterList; typedef Fixed_Source_Solver::RCP_Mat_DB RCP_Mat_DB; typedef Fixed_Source_Solver::RCP_Dimensions RCP_Dimensions; typedef Fixed_Source_Solver::RCP_Mesh RCP_Mesh; typedef Fixed_Source_Solver::RCP_Indexer RCP_Indexer; typedef Fixed_Source_Solver::RCP_Global_Data RCP_Global_Data; typedef Fixed_Source_Solver::Matrix_t Matrix_t; typedef Fixed_Source_Solver::Vector_t Vector_t; typedef Fixed_Source_Solver::Linear_System_t Linear_System_t; typedef profugus::Partitioner Partitioner; typedef Fixed_Source_Solver::State_t State; typedef Teuchos::RCP<State> RCP_State; typedef Linear_System_t::Array_Dbl Array_Dbl; protected: void SetUp() { node = profugus::node(); nodes = profugus::nodes(); } void build(int order, int Ng) { num_groups = Ng; eqn_order = order; // build 4x4x4 mesh RCP_ParameterList db = Teuchos::rcp(new Teuchos::ParameterList("test")); if (cx.size() == 0) { db->set("delta_x", 1.0); db->set("delta_y", 1.0); db->set("delta_z", 1.0); db->set("num_cells_i", 3); db->set("num_cells_j", 3); db->set("num_cells_k", 3); } else { db->set("x_edges", cx); db->set("y_edges", cy); db->set("z_edges", cz); } db->set("num_groups", Ng); if (nodes == 2) { db->set("num_blocks_i", 2); } if (nodes == 4) { db->set("num_blocks_i", 2); db->set("num_blocks_j", 2); } db->set("tolerance",1.0e-8); Partitioner p(db); p.build(); mesh = p.get_mesh(); indexer = p.get_indexer(); data = p.get_global_data(); solver = Teuchos::rcp(new Fixed_Source_Solver(db)); if (num_groups == 1) mat = one_grp::make_mat(3, mesh->num_cells()); else if (num_groups == 2) mat = two_grp::make_mat(3, mesh->num_cells()); else mat = three_grp::make_mat(3, mesh->num_cells()); EXPECT_FALSE(mat.is_null()); EXPECT_FALSE(mesh.is_null()); EXPECT_FALSE(indexer.is_null()); EXPECT_FALSE(data.is_null()); bool success = true, verbose = true; try { dim = Teuchos::rcp(new profugus::Dimensions(eqn_order)); solver->setup(dim, mat, mesh, indexer, data); } TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success); // make a state object state = Teuchos::rcp(new State(mesh, Ng)); } protected: RCP_Mesh mesh; RCP_Indexer indexer; RCP_Global_Data data; RCP_Mat_DB mat; RCP_Dimensions dim; RCP_Linear_Solver solver; RCP_State state; int num_groups, eqn_order; int node, nodes; Array_Dbl cx, cy, cz; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// #if 0 TEST_F(Inf_Med_Solver_FVTest, 1Grp_SP1) { build(1, 1); EXPECT_EQ(1, dim->num_equations()); // make the source denovo::General_Source_DB q(mesh->num_cells()); { q.set_num(1, 1); denovo::General_Source_DB::Vec_Qe q0(3); q0[0] = new denovo::Isotropic(1.2); q.assign(q0[0], 0, 0); q.assign(0); } solver->solve(q); const Vector_t &x = solver->get_LHS(); for (int i = 0; i < x.MyLength(); ++i) { EXPECT_SOFTEQ(2.0, x[i], 1.0e-6); } } //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 1Grp_SP3) { build(3, 1); EXPECT_EQ(2, dim->num_equations()); // make the source denovo::General_Source_DB q(mesh->num_cells()); { q.set_num(1, 1); denovo::General_Source_DB::Vec_Qe q0(3); q0[0] = new denovo::Isotropic(1.2); q.assign(q0[0], 0, 0); q.assign(0); } solver->solve(q); const Vector_t &x = solver->get_LHS(); for (int cell = 0; cell < mesh->num_cells(); ++cell) { double phi_0 = x[cell*2] - 2.0/3.0 * x[1 + cell*2]; EXPECT_SOFTEQ(2.0, phi_0, 1.0e-6); } } //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 3Grp_SP1) { build(1, 3); EXPECT_EQ(1, dim->num_equations()); // make the source denovo::General_Source_DB q(mesh->num_cells()); { q.set_num(1, 3); denovo::General_Source_DB::Vec_Qe q0(3); q0[0] = new denovo::Isotropic(1.2); q0[1] = new denovo::Isotropic(1.3); q0[2] = new denovo::Isotropic(1.4); q.assign(q0[0], 0, 0); q.assign(q0[1], 1, 0); q.assign(q0[2], 2, 0); q.assign(0); } solver->solve(q); const Linear_System_t &system = solver->get_linear_system(); const Vector_t &x = solver->get_LHS(); for (int cell = 0; cell < mesh->num_cells(); ++cell) { int g0 = 0 + 0 * 3 + cell * 3 * 1; int g1 = 1 + 0 * 3 + cell * 3 * 1; int g2 = 2 + 0 * 3 + cell * 3 * 1; EXPECT_EQ(g0, system.index(0, 0, cell)); EXPECT_EQ(g1, system.index(1, 0, cell)); EXPECT_EQ(g2, system.index(2, 0, cell)); double phi_0 = x[g0]; double phi_1 = x[g1]; double phi_2 = x[g2]; EXPECT_SOFTEQ(23.376775173864782, phi_0, 1.0e-6); EXPECT_SOFTEQ(26.285032257831212, phi_1, 1.0e-6); EXPECT_SOFTEQ(21.044148232485092, phi_2, 1.0e-6); } } //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 3Grp_SP5) { build(5, 3); EXPECT_EQ(3, dim->num_equations()); // make the source denovo::General_Source_DB q(mesh->num_cells()); { q.set_num(1, 3); denovo::General_Source_DB::Vec_Qe q0(3); q0[0] = new denovo::Isotropic(1.2); q0[1] = new denovo::Isotropic(1.3); q0[2] = new denovo::Isotropic(1.4); q.assign(q0[0], 0, 0); q.assign(q0[1], 1, 0); q.assign(q0[2], 2, 0); q.assign(0); } solver->solve(q); const Linear_System_t &system = solver->get_linear_system(); const Vector_t &x = solver->get_LHS(); double eps = 1.0e-4; for (int cell = 0; cell < mesh->num_cells(); ++cell) { int g00 = 0 + 0 * 3 + cell * 3 * 3; int g10 = 1 + 0 * 3 + cell * 3 * 3; int g20 = 2 + 0 * 3 + cell * 3 * 3; EXPECT_EQ(g00, system.index(0, 0, cell)); EXPECT_EQ(g10, system.index(1, 0, cell)); EXPECT_EQ(g20, system.index(2, 0, cell)); int g01 = 0 + 1 * 3 + cell * 3 * 3; int g11 = 1 + 1 * 3 + cell * 3 * 3; int g21 = 2 + 1 * 3 + cell * 3 * 3; EXPECT_EQ(g01, system.index(0, 1, cell)); EXPECT_EQ(g11, system.index(1, 1, cell)); EXPECT_EQ(g21, system.index(2, 1, cell)); int g02 = 0 + 2 * 3 + cell * 3 * 3; int g12 = 1 + 2 * 3 + cell * 3 * 3; int g22 = 2 + 2 * 3 + cell * 3 * 3; EXPECT_EQ(g02, system.index(0, 2, cell)); EXPECT_EQ(g12, system.index(1, 2, cell)); EXPECT_EQ(g22, system.index(2, 2, cell)); double phi_0 = x[g00] - 2.0/3.0*x[g01] + 8.0/15.0*x[g02]; double phi_1 = x[g10] - 2.0/3.0*x[g11] + 8.0/15.0*x[g12]; double phi_2 = x[g20] - 2.0/3.0*x[g21] + 8.0/15.0*x[g22]; EXPECT_SOFTEQ(23.376775173864782, phi_0, eps); EXPECT_SOFTEQ(26.285032257831212, phi_1, eps); EXPECT_SOFTEQ(21.044148232485092, phi_2, eps); } // fill the state solver->write_state(*state); State::View_Field phi = state->moments(); EXPECT_EQ(mesh->num_cells() * 3 * 4, phi.size()); // the state is set for // Pn = 1; 4 moments - // SPN only writes into // the scalar flux // moment of the state for (int cell = 0; cell < mesh->num_cells(); ++cell) { int g0 = 0 + cell * 4 + 0 * mesh->num_cells() * 4; int g1 = 0 + cell * 4 + 1 * mesh->num_cells() * 4; int g2 = 0 + cell * 4 + 2 * mesh->num_cells() * 4; EXPECT_SOFTEQ(23.376775173864782, phi[g0], eps); EXPECT_SOFTEQ(26.285032257831212, phi[g1], eps); EXPECT_SOFTEQ(21.044148232485092, phi[g2], eps); } // check the equation traits State::const_View_Field phi_0 = state->moments(0); for (int cell = 0; cell < mesh->num_cells(); ++cell) { EXPECT_SOFTEQ(23.376775173864782, Eqn_Traits::scalar_flux(cell, phi_0), eps); } } #endif //---------------------------------------------------------------------------// // end of tstFixed_Source_Solver.cc //---------------------------------------------------------------------------// <commit_msg>Finished fixed source implementation.<commit_after>//----------------------------------*-C++-*----------------------------------// /*! * \file spn/test/tstFixed_Source_Solver.cc * \author Thomas M. Evans * \date Sun Nov 18 19:05:06 2012 * \brief Test of Fixed_Source_Solver class. * \note Copyright (C) 2012 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include <vector> #include "gtest/utils_gtest.hh" #include "Teuchos_StandardCatchMacros.hpp" #include "Teuchos_RCP.hpp" #include "Teuchos_ParameterList.hpp" #include "utils/Definitions.hh" #include "mesh/Partitioner.hh" #include "../Dimensions.hh" #include "../Fixed_Source_Solver.hh" #include "Test_XS.hh" using namespace std; //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// class Inf_Med_Solver_FVTest : public testing::Test { protected: typedef profugus::Fixed_Source_Solver Fixed_Source_Solver; typedef Teuchos::RCP<Fixed_Source_Solver> RCP_Linear_Solver; typedef Fixed_Source_Solver::RCP_ParameterList RCP_ParameterList; typedef Fixed_Source_Solver::RCP_Mat_DB RCP_Mat_DB; typedef Fixed_Source_Solver::RCP_Dimensions RCP_Dimensions; typedef Fixed_Source_Solver::RCP_Mesh RCP_Mesh; typedef Fixed_Source_Solver::RCP_Indexer RCP_Indexer; typedef Fixed_Source_Solver::RCP_Global_Data RCP_Global_Data; typedef Fixed_Source_Solver::Matrix_t Matrix_t; typedef Fixed_Source_Solver::Vector_t Vector_t; typedef Fixed_Source_Solver::Linear_System_t Linear_System_t; typedef profugus::Partitioner Partitioner; typedef Fixed_Source_Solver::State_t State; typedef Teuchos::RCP<State> RCP_State; typedef Linear_System_t::Array_Dbl Array_Dbl; typedef Fixed_Source_Solver::External_Source External_Source; typedef External_Source::Source_Shapes Source_Shapes; typedef External_Source::Shape Shape; typedef External_Source::Source_Field Source_Field; typedef External_Source::ID_Field ID_Field; protected: void SetUp() { node = profugus::node(); nodes = profugus::nodes(); } void build(int order, int Ng) { num_groups = Ng; eqn_order = order; // build 4x4x4 mesh RCP_ParameterList db = Teuchos::rcp(new Teuchos::ParameterList("test")); if (cx.size() == 0) { db->set("delta_x", 1.0); db->set("delta_y", 1.0); db->set("delta_z", 1.0); db->set("num_cells_i", 3); db->set("num_cells_j", 3); db->set("num_cells_k", 3); } else { db->set("x_edges", cx); db->set("y_edges", cy); db->set("z_edges", cz); } db->set("num_groups", Ng); if (nodes == 2) { db->set("num_blocks_i", 2); } if (nodes == 4) { db->set("num_blocks_i", 2); db->set("num_blocks_j", 2); } db->set("tolerance",1.0e-8); Partitioner p(db); p.build(); mesh = p.get_mesh(); indexer = p.get_indexer(); data = p.get_global_data(); solver = Teuchos::rcp(new Fixed_Source_Solver(db)); if (num_groups == 1) mat = one_grp::make_mat(3, mesh->num_cells()); else if (num_groups == 2) mat = two_grp::make_mat(3, mesh->num_cells()); else mat = three_grp::make_mat(3, mesh->num_cells()); EXPECT_FALSE(mat.is_null()); EXPECT_FALSE(mesh.is_null()); EXPECT_FALSE(indexer.is_null()); EXPECT_FALSE(data.is_null()); bool success = true, verbose = true; try { dim = Teuchos::rcp(new profugus::Dimensions(eqn_order)); solver->setup(dim, mat, mesh, indexer, data); } TEUCHOS_STANDARD_CATCH_STATEMENTS(verbose, std::cerr, success); // make a state object state = Teuchos::rcp(new State(mesh, Ng)); } protected: RCP_Mesh mesh; RCP_Indexer indexer; RCP_Global_Data data; RCP_Mat_DB mat; RCP_Dimensions dim; RCP_Linear_Solver solver; RCP_State state; int num_groups, eqn_order; int node, nodes; Array_Dbl cx, cy, cz; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 1Grp_SP1) { build(1, 1); EXPECT_EQ(1, dim->num_equations()); // make the source External_Source q(mesh->num_cells()); { Source_Shapes shapes(1, Shape(1, 1.2)); ID_Field srcids(mesh->num_cells(), 0); Source_Field source(mesh->num_cells(), 1.0); q.set(srcids, shapes, source); } solver->solve(q); const Vector_t &x = solver->get_LHS(); for (int i = 0; i < x.MyLength(); ++i) { EXPECT_SOFTEQ(2.0, x[i], 1.0e-6); } } //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 1Grp_SP3) { build(3, 1); EXPECT_EQ(2, dim->num_equations()); // make the source External_Source q(mesh->num_cells()); { Source_Shapes shapes(1, Shape(1, 1.2)); ID_Field srcids(mesh->num_cells(), 0); Source_Field source(mesh->num_cells(), 1.0); q.set(srcids, shapes, source); } solver->solve(q); const Vector_t &x = solver->get_LHS(); for (int cell = 0; cell < mesh->num_cells(); ++cell) { double phi_0 = x[cell*2] - 2.0/3.0 * x[1 + cell*2]; EXPECT_SOFTEQ(2.0, phi_0, 1.0e-6); } } //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 3Grp_SP1) { build(1, 3); EXPECT_EQ(1, dim->num_equations()); // make the source External_Source q(mesh->num_cells()); { Source_Shapes shapes(1, Shape(3, 0.0)); shapes[0][0] = 1.2; shapes[0][1] = 1.3; shapes[0][2] = 1.4; ID_Field srcids(mesh->num_cells(), 0); Source_Field source(mesh->num_cells(), 1.0); q.set(srcids, shapes, source); } solver->solve(q); const Linear_System_t &system = solver->get_linear_system(); const Vector_t &x = solver->get_LHS(); for (int cell = 0; cell < mesh->num_cells(); ++cell) { int g0 = 0 + 0 * 3 + cell * 3 * 1; int g1 = 1 + 0 * 3 + cell * 3 * 1; int g2 = 2 + 0 * 3 + cell * 3 * 1; EXPECT_EQ(g0, system.index(0, 0, cell)); EXPECT_EQ(g1, system.index(1, 0, cell)); EXPECT_EQ(g2, system.index(2, 0, cell)); double phi_0 = x[g0]; double phi_1 = x[g1]; double phi_2 = x[g2]; EXPECT_SOFTEQ(23.376775173864782, phi_0, 1.0e-6); EXPECT_SOFTEQ(26.285032257831212, phi_1, 1.0e-6); EXPECT_SOFTEQ(21.044148232485092, phi_2, 1.0e-6); } } //---------------------------------------------------------------------------// TEST_F(Inf_Med_Solver_FVTest, 3Grp_SP5) { build(5, 3); EXPECT_EQ(3, dim->num_equations()); // make the source External_Source q(mesh->num_cells()); { Source_Shapes shapes(1, Shape(3, 0.0)); shapes[0][0] = 1.2; shapes[0][1] = 1.3; shapes[0][2] = 1.4; ID_Field srcids(mesh->num_cells(), 0); Source_Field source(mesh->num_cells(), 1.0); q.set(srcids, shapes, source); } solver->solve(q); const Linear_System_t &system = solver->get_linear_system(); const Vector_t &x = solver->get_LHS(); double eps = 1.0e-4; for (int cell = 0; cell < mesh->num_cells(); ++cell) { int g00 = 0 + 0 * 3 + cell * 3 * 3; int g10 = 1 + 0 * 3 + cell * 3 * 3; int g20 = 2 + 0 * 3 + cell * 3 * 3; EXPECT_EQ(g00, system.index(0, 0, cell)); EXPECT_EQ(g10, system.index(1, 0, cell)); EXPECT_EQ(g20, system.index(2, 0, cell)); int g01 = 0 + 1 * 3 + cell * 3 * 3; int g11 = 1 + 1 * 3 + cell * 3 * 3; int g21 = 2 + 1 * 3 + cell * 3 * 3; EXPECT_EQ(g01, system.index(0, 1, cell)); EXPECT_EQ(g11, system.index(1, 1, cell)); EXPECT_EQ(g21, system.index(2, 1, cell)); int g02 = 0 + 2 * 3 + cell * 3 * 3; int g12 = 1 + 2 * 3 + cell * 3 * 3; int g22 = 2 + 2 * 3 + cell * 3 * 3; EXPECT_EQ(g02, system.index(0, 2, cell)); EXPECT_EQ(g12, system.index(1, 2, cell)); EXPECT_EQ(g22, system.index(2, 2, cell)); double phi_0 = x[g00] - 2.0/3.0*x[g01] + 8.0/15.0*x[g02]; double phi_1 = x[g10] - 2.0/3.0*x[g11] + 8.0/15.0*x[g12]; double phi_2 = x[g20] - 2.0/3.0*x[g21] + 8.0/15.0*x[g22]; EXPECT_SOFTEQ(23.376775173864782, phi_0, eps); EXPECT_SOFTEQ(26.285032257831212, phi_1, eps); EXPECT_SOFTEQ(21.044148232485092, phi_2, eps); } // fill the state solver->write_state(*state); State::View_Field phi = state->flux(); EXPECT_EQ(mesh->num_cells() * 3, phi.size()); for (int cell = 0; cell < mesh->num_cells(); ++cell) { int g0 = cell + 0 * mesh->num_cells(); int g1 = cell + 1 * mesh->num_cells(); int g2 = cell + 2 * mesh->num_cells(); EXPECT_SOFTEQ(23.376775173864782, phi[g0], eps); EXPECT_SOFTEQ(26.285032257831212, phi[g1], eps); EXPECT_SOFTEQ(21.044148232485092, phi[g2], eps); } } //---------------------------------------------------------------------------// // end of tstFixed_Source_Solver.cc //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>#include <boost/any.hpp> #include <ir/index_manager/index/BTreeIndex.h> using namespace std; using namespace izenelib::util; using namespace izenelib::ir::indexmanager; namespace izenelib{ namespace ir{ namespace indexmanager{ template <> void BTreeIndex<IndexKeyType<String> >::getSuffix(const IndexKeyType<String>& key, BitVector& result) { String str("",String::UTF_8); IndexKeyType<String> strkey(key.cid,key.fid,str); myKeyType ikey(strkey, 0); myValueType ival; IndexSDBCursor locn= this->_sdb.search(ikey); do { if(this->_sdb.get(locn, ikey, ival) ) { if(ikey.key.fid == key.fid) { if ( IsSuffix(key.value, ikey.key.value) ) { for (size_t i=0; i<ival.size(); i++) result.set(ival[i]); } } else break; } }while(this->_sdb.seq(locn)); } template <> void BTreeIndex<IndexKeyType<String> >::getSubString(const IndexKeyType<String>& key, BitVector& result) { String str("",String::UTF_8); IndexKeyType<String> strkey(key.cid,key.fid,str); myKeyType ikey(strkey, 0); myValueType ival; IndexSDBCursor locn; this->_sdb.search(ikey,locn); do { if(this->_sdb.get(locn, ikey, ival) ) { if(ikey.key.fid == key.fid) { if ( IsSubString(key.value, ikey.key.value) ) { for (size_t i=0; i<ival.size(); i++) result.set(ival[i]); } } else break; } }while (this->_sdb.seq(locn)); } template<typename T> BTreeIndex<IndexKeyType<T> >* BTreeIndexer::getIndexer() { return NULL; } template<> BTreeIndex<IndexKeyType<int64_t> >* BTreeIndexer::getIndexer() { return pBTreeIntIndexer_; } template<> BTreeIndex<IndexKeyType<uint64_t> >* BTreeIndexer::getIndexer() { return pBTreeUIntIndexer_; } template<> BTreeIndex<IndexKeyType<float> >* BTreeIndexer::getIndexer() { return pBTreeFloatIndexer_; } template<> BTreeIndex<IndexKeyType<double> >* BTreeIndexer::getIndexer() { return pBTreeDoubleIndexer_; } template<> BTreeIndex<IndexKeyType<String> >* BTreeIndexer::getIndexer() { return pBTreeUStrIndexer_; } template<> void add_visitor::operator()(BTreeIndexer* pIndexer, collectionid_t colid,fieldid_t fid, String& v, docid_t docid) { trim(v); IndexKeyType<String> key(colid, fid, v); pIndexer->getIndexer<String>()->add_nodup(key, docid); //BTreeIndexer::getTrieIndexer()->add_suffix(v, fid, docid); }; }}} BTreeIndexer::BTreeIndexer(string location, int degree, size_t cacheSize, size_t maxDataSize) { string path(location); path.append("/int.bti"); pBTreeIntIndexer_ = new BTreeIndex<IndexKeyType<int64_t> >(path); pBTreeIntIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/uint.bti"; pBTreeUIntIndexer_ = new BTreeIndex<IndexKeyType<uint64_t> >(path); pBTreeUIntIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/float.bti"; pBTreeFloatIndexer_ = new BTreeIndex<IndexKeyType<float> >(path); pBTreeFloatIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/double.bti"; pBTreeDoubleIndexer_ = new BTreeIndex<IndexKeyType<double> >( path); pBTreeDoubleIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/ustr.bti"; pBTreeUStrIndexer_ = new BTreeIndex<IndexKeyType<String> >(path); pBTreeUStrIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); /* path.clear(); path = location+"/usuf.bti"; pBTreeUStrSuffixIndexer_ = new BTreeTrieIndex<String>( path); pBTreeUStrSuffixIndexer_->open(); */ } BTreeIndexer::~BTreeIndexer() { flush(); if (pBTreeIntIndexer_) { delete pBTreeIntIndexer_; pBTreeIntIndexer_ = NULL; } if (pBTreeUIntIndexer_) { delete pBTreeUIntIndexer_; pBTreeUIntIndexer_ = NULL; } if (pBTreeFloatIndexer_) { delete pBTreeFloatIndexer_; pBTreeFloatIndexer_ = NULL; } if (pBTreeDoubleIndexer_) { delete pBTreeDoubleIndexer_; pBTreeDoubleIndexer_ = NULL; } if (pBTreeUStrIndexer_) { delete pBTreeUStrIndexer_; pBTreeUStrIndexer_ = NULL; } /* if (pBTreeUStrSuffixIndexer_) { delete pBTreeUStrSuffixIndexer_; pBTreeUStrSuffixIndexer_ = NULL; } */ } void BTreeIndexer::setFilter(boost::shared_ptr<BitVector> pBitVector) { pFilter_ = pBitVector; } boost::shared_ptr<BitVector> BTreeIndexer::getFilter() { return pFilter_; } void BTreeIndexer::add(collectionid_t colID, fieldid_t fid, PropertyType& value, docid_t docid) { izenelib::util::boost_variant_visit(boost::bind(add_visitor(), this, colID, fid, _1, docid), value); } void BTreeIndexer::remove(collectionid_t colID, fieldid_t fid, PropertyType& value, docid_t docid) { izenelib::util::boost_variant_visit(boost::bind(remove_visitor(), this, colID, fid, _1, docid), value); } void BTreeIndexer::getValue(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if (pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValue(collectionid_t colID, fieldid_t fid, PropertyType& value,std::vector<docid_t>& docList) { izenelib::util::boost_variant_visit(boost::bind(get_back_visitor(), this, colID, fid, _1, boost::ref(docList)), value); } void BTreeIndexer::getValueNotEqual(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_without_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueBetween(collectionid_t colID, fieldid_t fid, PropertyType& value1, PropertyType& value2, BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_between_visitor(), this, colID, fid, _1, _2, boost::ref(docs)),value1,value2); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueLess(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_less_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueLessEqual(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_less_equal_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueGreat(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_great_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueGreatEqual(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_great_equal_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueIn(collectionid_t colID, fieldid_t fid, vector<PropertyType>& values,BitVector& docs) { for (size_t i = 0; i < values.size(); i++) izenelib::util::boost_variant_visit(boost::bind(get_visitor(), this, colID, fid, _1, boost::ref(docs)), values[i]); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueNotIn(collectionid_t colID, fieldid_t fid, vector<PropertyType>& values,BitVector& docs) { for (size_t i = 0; i < values.size(); i++) getValue(colID, fid, values[i], docs); docs.toggle(); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValueStart(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { try { IndexKeyType<String> key(colID,fid,boost::get<String>(value)); pBTreeUStrIndexer_->getPrefix(key,docs); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } catch (...) { SF1V5_THROW(ERROR_UNSUPPORTED,"unsupported operation"); } } void BTreeIndexer::getValueEnd(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { try { //pBTreeUStrSuffixIndexer_->getValueSuffix(boost::get<String>(value),fid, docs); IndexKeyType<String> key(colID,fid,boost::get<String>(value)); pBTreeUStrIndexer_->getSuffix(key,docs); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } catch (...) { SF1V5_THROW(ERROR_UNSUPPORTED,"unsupported operation"); } } void BTreeIndexer::getValueSubString(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { try { //pBTreeUStrSuffixIndexer_->getValuePrefix(boost::get<String>(value), fid, docs); IndexKeyType<String> key(colID,fid,boost::get<String>(value)); pBTreeUStrIndexer_->getSubString(key,docs); if(pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } catch (...) { SF1V5_THROW(ERROR_UNSUPPORTED,"unsupported operation"); } } void BTreeIndexer::flush() { if (pBTreeIntIndexer_) pBTreeIntIndexer_->commit(); if (pBTreeUIntIndexer_) pBTreeUIntIndexer_->commit(); if (pBTreeFloatIndexer_) pBTreeFloatIndexer_->commit(); if (pBTreeDoubleIndexer_) pBTreeDoubleIndexer_->commit(); if (pBTreeUStrIndexer_) pBTreeUStrIndexer_->commit(); //if (pBTreeUStrSuffixIndexer_) pBTreeUStrSuffixIndexer_->flush(); } void BTreeIndexer::delDocument(size_t max_doc, docid_t docId) { if(!pFilter_) { pFilter_.reset(new BitVector(max_doc)); } pFilter_->set(docId); } <commit_msg>little fix<commit_after>#include <boost/any.hpp> #include <ir/index_manager/index/BTreeIndex.h> using namespace std; using namespace izenelib::util; using namespace izenelib::ir::indexmanager; namespace izenelib{ namespace ir{ namespace indexmanager{ template <> void BTreeIndex<IndexKeyType<String> >::getSuffix(const IndexKeyType<String>& key, BitVector& result) { String str("",String::UTF_8); IndexKeyType<String> strkey(key.cid,key.fid,str); myKeyType ikey(strkey, 0); myValueType ival; IndexSDBCursor locn= this->_sdb.search(ikey); do { if(this->_sdb.get(locn, ikey, ival) ) { if(ikey.key.fid == key.fid) { if ( IsSuffix(key.value, ikey.key.value) ) { for (size_t i=0; i<ival.size(); i++) result.set(ival[i]); } } else break; } }while(this->_sdb.seq(locn)); } template <> void BTreeIndex<IndexKeyType<String> >::getSubString(const IndexKeyType<String>& key, BitVector& result) { String str("",String::UTF_8); IndexKeyType<String> strkey(key.cid,key.fid,str); myKeyType ikey(strkey, 0); myValueType ival; IndexSDBCursor locn; this->_sdb.search(ikey,locn); do { if(this->_sdb.get(locn, ikey, ival) ) { if(ikey.key.fid == key.fid) { if ( IsSubString(key.value, ikey.key.value) ) { for (size_t i=0; i<ival.size(); i++) result.set(ival[i]); } } else break; } }while (this->_sdb.seq(locn)); } template<typename T> BTreeIndex<IndexKeyType<T> >* BTreeIndexer::getIndexer() { return NULL; } template<> BTreeIndex<IndexKeyType<int64_t> >* BTreeIndexer::getIndexer() { return pBTreeIntIndexer_; } template<> BTreeIndex<IndexKeyType<uint64_t> >* BTreeIndexer::getIndexer() { return pBTreeUIntIndexer_; } template<> BTreeIndex<IndexKeyType<float> >* BTreeIndexer::getIndexer() { return pBTreeFloatIndexer_; } template<> BTreeIndex<IndexKeyType<double> >* BTreeIndexer::getIndexer() { return pBTreeDoubleIndexer_; } template<> BTreeIndex<IndexKeyType<String> >* BTreeIndexer::getIndexer() { return pBTreeUStrIndexer_; } template<> void add_visitor::operator()(BTreeIndexer* pIndexer, collectionid_t colid,fieldid_t fid, String& v, docid_t docid) { trim(v); IndexKeyType<String> key(colid, fid, v); pIndexer->getIndexer<String>()->add_nodup(key, docid); //BTreeIndexer::getTrieIndexer()->add_suffix(v, fid, docid); }; }}} BTreeIndexer::BTreeIndexer(string location, int degree, size_t cacheSize, size_t maxDataSize) { string path(location); path.append("/int.bti"); pBTreeIntIndexer_ = new BTreeIndex<IndexKeyType<int64_t> >(path); pBTreeIntIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/uint.bti"; pBTreeUIntIndexer_ = new BTreeIndex<IndexKeyType<uint64_t> >(path); pBTreeUIntIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/float.bti"; pBTreeFloatIndexer_ = new BTreeIndex<IndexKeyType<float> >(path); pBTreeFloatIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/double.bti"; pBTreeDoubleIndexer_ = new BTreeIndex<IndexKeyType<double> >( path); pBTreeDoubleIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); path.clear(); path = location+"/ustr.bti"; pBTreeUStrIndexer_ = new BTreeIndex<IndexKeyType<String> >(path); pBTreeUStrIndexer_->initialize(maxDataSize/10, degree, maxDataSize, cacheSize); /* path.clear(); path = location+"/usuf.bti"; pBTreeUStrSuffixIndexer_ = new BTreeTrieIndex<String>( path); pBTreeUStrSuffixIndexer_->open(); */ } BTreeIndexer::~BTreeIndexer() { flush(); if (pBTreeIntIndexer_) { delete pBTreeIntIndexer_; pBTreeIntIndexer_ = NULL; } if (pBTreeUIntIndexer_) { delete pBTreeUIntIndexer_; pBTreeUIntIndexer_ = NULL; } if (pBTreeFloatIndexer_) { delete pBTreeFloatIndexer_; pBTreeFloatIndexer_ = NULL; } if (pBTreeDoubleIndexer_) { delete pBTreeDoubleIndexer_; pBTreeDoubleIndexer_ = NULL; } if (pBTreeUStrIndexer_) { delete pBTreeUStrIndexer_; pBTreeUStrIndexer_ = NULL; } /* if (pBTreeUStrSuffixIndexer_) { delete pBTreeUStrSuffixIndexer_; pBTreeUStrSuffixIndexer_ = NULL; } */ } void BTreeIndexer::setFilter(boost::shared_ptr<BitVector> pBitVector) { pFilter_ = pBitVector; } boost::shared_ptr<BitVector> BTreeIndexer::getFilter() { return pFilter_; } void BTreeIndexer::add(collectionid_t colID, fieldid_t fid, PropertyType& value, docid_t docid) { izenelib::util::boost_variant_visit(boost::bind(add_visitor(), this, colID, fid, _1, docid), value); } void BTreeIndexer::remove(collectionid_t colID, fieldid_t fid, PropertyType& value, docid_t docid) { izenelib::util::boost_variant_visit(boost::bind(remove_visitor(), this, colID, fid, _1, docid), value); } void BTreeIndexer::getValue(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_visitor(), this, colID, fid, _1, boost::ref(docs)), value); if (pFilter_) { boost::shared_ptr<BitVector> filterNot(new BitVector(pFilter_->size())); pFilter_->logicalnot(*filterNot); docs &= *filterNot; } } void BTreeIndexer::getValue(collectionid_t colID, fieldid_t fid, PropertyType& value,std::vector<docid_t>& docList) { izenelib::util::boost_variant_visit(boost::bind(get_back_visitor(), this, colID, fid, _1, boost::ref(docList)), value); } void BTreeIndexer::getValueNotEqual(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_without_visitor(), this, colID, fid, _1, boost::ref(docs)), value); } void BTreeIndexer::getValueBetween(collectionid_t colID, fieldid_t fid, PropertyType& value1, PropertyType& value2, BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_between_visitor(), this, colID, fid, _1, _2, boost::ref(docs)),value1,value2); } void BTreeIndexer::getValueLess(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_less_visitor(), this, colID, fid, _1, boost::ref(docs)), value); } void BTreeIndexer::getValueLessEqual(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_less_equal_visitor(), this, colID, fid, _1, boost::ref(docs)), value); } void BTreeIndexer::getValueGreat(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_great_visitor(), this, colID, fid, _1, boost::ref(docs)), value); } void BTreeIndexer::getValueGreatEqual(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { izenelib::util::boost_variant_visit(boost::bind(get_great_equal_visitor(), this, colID, fid, _1, boost::ref(docs)), value); } void BTreeIndexer::getValueIn(collectionid_t colID, fieldid_t fid, vector<PropertyType>& values,BitVector& docs) { for (size_t i = 0; i < values.size(); i++) izenelib::util::boost_variant_visit(boost::bind(get_visitor(), this, colID, fid, _1, boost::ref(docs)), values[i]); } void BTreeIndexer::getValueNotIn(collectionid_t colID, fieldid_t fid, vector<PropertyType>& values,BitVector& docs) { for (size_t i = 0; i < values.size(); i++) getValue(colID, fid, values[i], docs); docs.toggle(); } void BTreeIndexer::getValueStart(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { try { IndexKeyType<String> key(colID,fid,boost::get<String>(value)); pBTreeUStrIndexer_->getPrefix(key,docs); } catch (...) { SF1V5_THROW(ERROR_UNSUPPORTED,"unsupported operation"); } } void BTreeIndexer::getValueEnd(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { try { //pBTreeUStrSuffixIndexer_->getValueSuffix(boost::get<String>(value),fid, docs); IndexKeyType<String> key(colID,fid,boost::get<String>(value)); pBTreeUStrIndexer_->getSuffix(key,docs); } catch (...) { SF1V5_THROW(ERROR_UNSUPPORTED,"unsupported operation"); } } void BTreeIndexer::getValueSubString(collectionid_t colID, fieldid_t fid, PropertyType& value,BitVector& docs) { try { //pBTreeUStrSuffixIndexer_->getValuePrefix(boost::get<String>(value), fid, docs); IndexKeyType<String> key(colID,fid,boost::get<String>(value)); pBTreeUStrIndexer_->getSubString(key,docs); } catch (...) { SF1V5_THROW(ERROR_UNSUPPORTED,"unsupported operation"); } } void BTreeIndexer::flush() { if (pBTreeIntIndexer_) pBTreeIntIndexer_->commit(); if (pBTreeUIntIndexer_) pBTreeUIntIndexer_->commit(); if (pBTreeFloatIndexer_) pBTreeFloatIndexer_->commit(); if (pBTreeDoubleIndexer_) pBTreeDoubleIndexer_->commit(); if (pBTreeUStrIndexer_) pBTreeUStrIndexer_->commit(); //if (pBTreeUStrSuffixIndexer_) pBTreeUStrSuffixIndexer_->flush(); } void BTreeIndexer::delDocument(size_t max_doc, docid_t docId) { if(!pFilter_) { pFilter_.reset(new BitVector(max_doc)); } pFilter_->set(docId); } <|endoftext|>
<commit_before>#include <getopt.h> #include <string> #include <math.h> #include <boost/lexical_cast.hpp> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <libwatcher/client.h> #include <libwatcher/gpsMessage.h> #include <libwatcher/labelMessage.h> #include <libwatcher/edgeMessage.h> #include <libwatcher/watcherColors.h> #include "logger.h" #include "sendMessageHandler.h" using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; #define PI (3.141592653589793) // Isn't this #DEFINEd somewhere? void usage(const char *progName) { fprintf(stderr, "Usage: %s [args]\n", basename(progName)); fprintf(stderr, "Args:\n"); fprintf(stderr, " -s, --server=address The addres of the node running watcherd\n"); fprintf(stderr, "\n"); fprintf(stderr, "Optional args:\n"); fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n"); fprintf(stderr, " -r, --radius The radius of the circle in some unknown unit\n"); fprintf(stderr, "\n"); fprintf(stderr, " -h, --help Show this message\n"); exit(1); } int main(int argc, char **argv) { TRACE_ENTER(); int c; string server; string logProps(string(basename(argv[0]))+string(".log.properties")); double radius=50.0; while (true) { int option_index = 0; static struct option long_options[] = { {"server", required_argument, 0, 's'}, {"logProps", required_argument, 0, 'p'}, {"radius", required_argument, 0, 'r'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "r:s:p:hH?", long_options, &option_index); if (c == -1) break; switch(c) { case 's': server=optarg; break; case 'p': logProps=optarg; break; case 'r': radius=lexical_cast<double>(optarg); break; case 'h': case 'H': case '?': default: usage(argv[0]); break; } } if (server=="") { usage(argv[0]); exit(1); } // // Now do some actual work. // LOAD_LOG_PROPS(logProps); Client client(server); LOG_INFO("Connecting to " << server << " and sending message."); // Do not add empty handler - default Client handler does not close connection. // client.addMessageHandler(SendMessageHandler::create()); unsigned int loopTime=1; // Create hour, min, sec, and center nodes. NodeIdentifier centerId=NodeIdentifier::from_string("192.168.1.100"); NodeIdentifier hourId=NodeIdentifier::from_string("192.168.1.101"); NodeIdentifier minId=NodeIdentifier::from_string("192.168.1.102"); NodeIdentifier secId=NodeIdentifier::from_string("192.168.1.103"); const GUILayer layer("Clock"); const double step=(2*PI)/60; struct { double theta; NodeIdentifier *id; const char *label; Color color; double length; } nodeData[]= { { 0, &hourId, "hour", Color::red, radius }, { 0, &minId, "min", Color::blue, radius*.8 }, { 0, &secId, "sec", Color::green, radius}, }; while (true) // draw everything all the time as we don't know when watcher will start { // Draw center node GPSMessagePtr gpsMess(new GPSMessage(radius, radius, 0)); gpsMess->layer=layer; gpsMess->fromNodeID=centerId; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } // draw hour, min, and second nodes, connecting them to center. for (unsigned int i=0; i<sizeof(nodeData)/sizeof(nodeData[0]); i++) { // update location offsets by current time. time_t nowInSecs=time(NULL); struct tm *now=localtime(&nowInSecs); if (*nodeData[i].id==hourId) nodeData[i].theta=step*((now->tm_hour*(60/12))+(now->tm_min/12)); else if(*nodeData[i].id==minId) nodeData[i].theta=step*now->tm_min; else if(*nodeData[i].id==secId) nodeData[i].theta=step*now->tm_sec; // Move hour. min, and sec nodes to appropriate locations. GPSMessagePtr gpsMess(new GPSMessage( (sin(nodeData[i].theta)*nodeData[i].length)+radius, (cos(nodeData[i].theta)*nodeData[i].length)+radius, (double)i)); gpsMess->layer=layer; gpsMess->fromNodeID=*nodeData[i].id; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } LabelMessagePtr labMess(new LabelMessage(nodeData[i].label)); labMess->layer=layer; labMess->expiration=loopTime*2000; // 2000 to stop blinking EdgeMessagePtr edgeMess(new EdgeMessage(centerId, *nodeData[i].id, layer, nodeData[i].color, 2)); edgeMess->middleLabel=labMess; if(!client.sendMessage(edgeMess)) { LOG_ERROR("Error sending edge message: " << *edgeMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } // add nodes at clock face number locations. double theta=(2*PI)/12; for (unsigned int i=0; i<12; i++, theta+=(2*PI)/12) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.2." + lexical_cast<string>(i+1)); GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*radius)+radius, (cos(theta)*radius)+radius, 0.0)); gpsMess->layer=layer; gpsMess->fromNodeID=thisId; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } // add nodes at clock face second locations. theta=(2*PI)/60; for (unsigned int i=0; i<60; i++, theta+=(2*PI)/60) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.3." + lexical_cast<string>(i+1)); double faceRad=radius*1.15; GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*faceRad)+radius, (cos(theta)*faceRad)+radius, 0.0)); gpsMess->layer=layer; gpsMess->fromNodeID=thisId; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } sleep(loopTime); } client.wait(); TRACE_EXIT_RET(EXIT_SUCCESS); return EXIT_SUCCESS; } <commit_msg>branch merge commit<commit_after>#include <getopt.h> #include <string> #include <math.h> #include <boost/lexical_cast.hpp> #include <boost/asio.hpp> #include <boost/lexical_cast.hpp> #include <libwatcher/client.h> #include <libwatcher/gpsMessage.h> #include <libwatcher/labelMessage.h> #include <libwatcher/edgeMessage.h> #include <libwatcher/watcherColors.h> #include "logger.h" #include "sendMessageHandler.h" using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; #define PI (3.141592653589793) // Isn't this #DEFINEd somewhere? void usage(const char *progName) { fprintf(stderr, "Usage: %s [args]\n", basename(progName)); fprintf(stderr, "Args:\n"); fprintf(stderr, " -s, --server=address The addres of the node running watcherd\n"); fprintf(stderr, "\n"); fprintf(stderr, "Optional args:\n"); fprintf(stderr, " -p, --logProps log.properties file, which controls logging for this program\n"); fprintf(stderr, " -r, --radius The radius of the circle in some unknown unit\n"); fprintf(stderr, " -S, --hideSecondRing Don't send message to draw the outer, second hand ring\n"); fprintf(stderr, " -H, --hideHourRing Don't send message to draw the inner, hour hand ring\n"); fprintf(stderr, "\n"); fprintf(stderr, " -h, --help Show this message\n"); exit(1); } int main(int argc, char **argv) { TRACE_ENTER(); int c; string server; string logProps(string(basename(argv[0]))+string(".log.properties")); double radius=50.0; bool showSecondRing=true, showHourRing=true; while (true) { int option_index = 0; static struct option long_options[] = { {"server", required_argument, 0, 's'}, {"logProps", required_argument, 0, 'p'}, {"radius", no_argument, 0, 'r'}, {"hideSecondRing", required_argument, 0, 'S'}, {"hideHourRing", required_argument, 0, 'H'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; c = getopt_long(argc, argv, "r:s:p:SHh?", long_options, &option_index); if (c == -1) break; switch(c) { case 's': server=optarg; break; case 'p': logProps=optarg; break; case 'r': radius=lexical_cast<double>(optarg); break; case 'S': showSecondRing=false; break; case 'H': showHourRing=false; break; case 'h': case '?': default: usage(argv[0]); break; } } if (server=="") { usage(argv[0]); exit(1); } // // Now do some actual work. // LOAD_LOG_PROPS(logProps); Client client(server); LOG_INFO("Connecting to " << server << " and sending message."); // Do not add empty handler - default Client handler does not close connection. // client.addMessageHandler(SendMessageHandler::create()); unsigned int loopTime=1; // Create hour, min, sec, and center nodes. NodeIdentifier centerId=NodeIdentifier::from_string("192.168.1.100"); NodeIdentifier hourId=NodeIdentifier::from_string("192.168.1.101"); NodeIdentifier minId=NodeIdentifier::from_string("192.168.1.102"); NodeIdentifier secId=NodeIdentifier::from_string("192.168.1.103"); const GUILayer layer("Clock"); const double step=(2*PI)/60; struct { double theta; NodeIdentifier *id; const char *label; Color color; double length; } nodeData[]= { { 0, &hourId, "hour", Color::red, radius }, { 0, &minId, "min", Color::blue, radius*.8 }, { 0, &secId, "sec", Color::green, radius}, }; while (true) // draw everything all the time as we don't know when watcher will start { // Draw center node GPSMessagePtr gpsMess(new GPSMessage(radius, radius, 0)); gpsMess->layer=layer; gpsMess->fromNodeID=centerId; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } // draw hour, min, and second nodes, connecting them to center. for (unsigned int i=0; i<sizeof(nodeData)/sizeof(nodeData[0]); i++) { // update location offsets by current time. time_t nowInSecs=time(NULL); struct tm *now=localtime(&nowInSecs); if (*nodeData[i].id==hourId) nodeData[i].theta=step*((now->tm_hour*(60/12))+(now->tm_min/12)); else if(*nodeData[i].id==minId) nodeData[i].theta=step*now->tm_min; else if(*nodeData[i].id==secId) nodeData[i].theta=step*now->tm_sec; // Move hour. min, and sec nodes to appropriate locations. GPSMessagePtr gpsMess(new GPSMessage( (sin(nodeData[i].theta)*nodeData[i].length)+radius, (cos(nodeData[i].theta)*nodeData[i].length)+radius, (double)i)); gpsMess->layer=layer; gpsMess->fromNodeID=*nodeData[i].id; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } LabelMessagePtr labMess(new LabelMessage(nodeData[i].label)); labMess->layer=layer; labMess->expiration=loopTime*2000; // 2000 to stop blinking EdgeMessagePtr edgeMess(new EdgeMessage(centerId, *nodeData[i].id, layer, nodeData[i].color, 2)); edgeMess->middleLabel=labMess; if(!client.sendMessage(edgeMess)) { LOG_ERROR("Error sending edge message: " << *edgeMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } if (showHourRing) { // add nodes at clock face number locations. double theta=(2*PI)/12; for (unsigned int i=0; i<12; i++, theta+=(2*PI)/12) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.2." + lexical_cast<string>(i+1)); GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*radius)+radius, (cos(theta)*radius)+radius, 0.0)); gpsMess->layer=layer; gpsMess->fromNodeID=thisId; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } } if (showSecondRing) { // add nodes at clock face second locations. double theta=(2*PI)/60; for (unsigned int i=0; i<60; i++, theta+=(2*PI)/60) { NodeIdentifier thisId=NodeIdentifier::from_string("192.168.3." + lexical_cast<string>(i+1)); double faceRad=radius*1.15; GPSMessagePtr gpsMess(new GPSMessage((sin(theta)*faceRad)+radius, (cos(theta)*faceRad)+radius, 0.0)); gpsMess->layer=layer; gpsMess->fromNodeID=thisId; if(!client.sendMessage(gpsMess)) { LOG_ERROR("Error sending gps message: " << *gpsMess); TRACE_EXIT_RET(EXIT_FAILURE); return EXIT_FAILURE; } } } sleep(loopTime); } client.wait(); TRACE_EXIT_RET(EXIT_SUCCESS); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdxmlexp_impl.hxx,v $ * * $Revision: 1.26 $ * * last change: $Author: rt $ $Date: 2005-09-09 13:49:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDXMLEXP_IMPL_HXX #define _SDXMLEXP_IMPL_HXX #ifndef _XMLOFF_XMLEXP_HXX #include "xmlexp.hxx" #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_ #include <com/sun/star/task/XStatusIndicator.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_ #include <com/sun/star/drawing/XDrawPage.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif ////////////////////////////////////////////////////////////////////////////// class SvXMLUnitConverter; class SvXMLExportItemMapper; class SfxPoolItem; class SfxItemSet; class OUStrings_Impl; class OUStringsSort_Impl; class Rectangle; class ImpPresPageDrawStylePropMapper; class ImpXMLEXPPageMasterList; class ImpXMLEXPPageMasterInfo; class ImpXMLDrawPageInfoList; class ImpXMLAutoLayoutInfoList; class SvXMLAutoStylePoolP; class XMLSdPropHdlFactory; class ImpXMLShapeStyleInfo; class XMLShapeExportPropertyMapper; class XMLPageExportPropertyMapper; ////////////////////////////////////////////////////////////////////////////// enum XmlPlaceholder { XmlPlaceholderTitle, XmlPlaceholderOutline, XmlPlaceholderSubtitle, XmlPlaceholderText, XmlPlaceholderGraphic, XmlPlaceholderObject, XmlPlaceholderChart, XmlPlaceholderOrgchart, XmlPlaceholderTable, XmlPlaceholderPage, XmlPlaceholderNotes, XmlPlaceholderHandout, XmlPlaceholderVerticalTitle, XmlPlaceholderVerticalOutline }; DECLARE_STL_STDKEY_SET( sal_Int32, SdXMLFormatMap ); ////////////////////////////////////////////////////////////////////////////// struct HeaderFooterPageSettingsImpl { rtl::OUString maStrHeaderDeclName; rtl::OUString maStrFooterDeclName; rtl::OUString maStrDateTimeDeclName; }; struct DateTimeDeclImpl { rtl::OUString maStrText; sal_Bool mbFixed; sal_Int32 mnFormat; }; ////////////////////////////////////////////////////////////////////////////// class SdXMLExport : public SvXMLExport { com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > mxDocStyleFamilies; com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocMasterPages; com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocDrawPages; sal_Int32 mnDocMasterPageCount; sal_Int32 mnDocDrawPageCount; sal_uInt32 mnShapeStyleInfoIndex; sal_uInt32 mnObjectCount; // temporary infos ImpXMLEXPPageMasterList* mpPageMasterInfoList; ImpXMLEXPPageMasterList* mpPageMasterUsageList; ImpXMLEXPPageMasterList* mpNotesPageMasterUsageList; ImpXMLEXPPageMasterInfo* mpHandoutPageMaster; ImpXMLAutoLayoutInfoList* mpAutoLayoutInfoList; com::sun::star::uno::Sequence< ::rtl::OUString > maDrawPagesAutoLayoutNames; ::std::vector< ::rtl::OUString > maDrawPagesStyleNames; ::std::vector< ::rtl::OUString > maDrawNotesPagesStyleNames; ::std::vector< ::rtl::OUString > maMasterPagesStyleNames; ::rtl::OUString maHandoutMasterStyleName; ::std::vector< HeaderFooterPageSettingsImpl > maDrawPagesHeaderFooterSettings; ::std::vector< HeaderFooterPageSettingsImpl > maDrawNotesPagesHeaderFooterSettings; ::std::vector< ::rtl::OUString > maHeaderDeclsVector; ::std::vector< ::rtl::OUString > maFooterDeclsVector; ::std::vector< DateTimeDeclImpl > maDateTimeDeclsVector; HeaderFooterPageSettingsImpl maHandoutPageHeaderFooterSettings; XMLSdPropHdlFactory* mpSdPropHdlFactory; XMLShapeExportPropertyMapper* mpPropertySetMapper; XMLPageExportPropertyMapper* mpPresPagePropsMapper; SdXMLFormatMap maUsedDateStyles; // this is a vector with the used formatings for date fields SdXMLFormatMap maUsedTimeStyles; // this is a vector with the used formatings for time fields sal_Bool mbIsDraw; sal_Bool mbFamilyGraphicUsed; sal_Bool mbFamilyPresentationUsed; const rtl::OUString msZIndex; const rtl::OUString msEmptyPres; const rtl::OUString msModel; const rtl::OUString msStartShape; const rtl::OUString msEndShape; const rtl::OUString msPageLayoutNames; virtual void _ExportStyles(BOOL bUsed); virtual void _ExportAutoStyles(); virtual void _ExportMasterStyles(); virtual void _ExportContent(); // #82003# virtual void _ExportMeta(); ImpXMLEXPPageMasterInfo* ImpGetOrCreatePageMasterInfo( com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > xMasterPage ); void ImpPrepPageMasterInfos(); void ImpPrepDrawMasterInfos(); void ImpWritePageMasterInfos(); void ImpPrepAutoLayoutInfos(); HeaderFooterPageSettingsImpl ImpPrepDrawPageHeaderFooterDecls( const com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage >& xDrawPage ); ImpXMLEXPPageMasterInfo* ImpGetPageMasterInfoByName(const rtl::OUString& rName); void ImpPrepDrawPageInfos(); void ImpPrepMasterPageInfos(); void ImpWritePresentationStyles(); ::rtl::OUString ImpCreatePresPageStyleName( com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage> xDrawPage, bool bExportBackground = true ); BOOL ImpPrepAutoLayoutInfo(const com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage >& xPage, rtl::OUString& rName); void ImpWriteAutoLayoutInfos(); void ImpWriteAutoLayoutPlaceholder(XmlPlaceholder ePl, const Rectangle& rRect); void ImpWriteHeaderFooterDecls(); void ImplExportHeaderFooterDeclAttributes( const HeaderFooterPageSettingsImpl& aSettings ); void exportFormsElement( com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > xDrawPage ); void exportPresentationSettings(); // #82003# helper function for recursive object count sal_uInt32 ImpRecursiveObjectCount( com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > xShapes); protected: virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); public: // #110680# SdXMLExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, sal_Bool bIsDraw, sal_uInt16 nExportFlags = EXPORT_ALL ); virtual ~SdXMLExport(); void SetProgress(sal_Int32 nProg); // XExporter virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // get factories and mappers XMLSdPropHdlFactory* GetSdPropHdlFactory() const { return mpSdPropHdlFactory; } XMLShapeExportPropertyMapper* GetPropertySetMapper() const { return mpPropertySetMapper; } XMLPageExportPropertyMapper* GetPresPagePropsMapper() const { return mpPresPagePropsMapper; } BOOL IsDraw() const { return mbIsDraw; } BOOL IsImpress() const { return !mbIsDraw; } BOOL IsFamilyGraphicUsed() const { return mbFamilyGraphicUsed; } void SetFamilyGraphicUsed() { mbFamilyGraphicUsed = TRUE; } BOOL IsFamilyPresentationUsed() const { return mbFamilyPresentationUsed; } void SetFamilyPresentationUsed() { mbFamilyPresentationUsed = TRUE; } virtual void addDataStyle(const sal_Int32 nNumberFormat, sal_Bool bTimeFormat = sal_False ); virtual void exportDataStyles(); virtual void exportAutoDataStyles(); virtual rtl::OUString getDataStyleName(const sal_Int32 nNumberFormat, sal_Bool bTimeFormat = sal_False ) const; // XServiceInfo ( : SvXMLExport ) virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); }; #endif // _SDXMLEXP_HXX <commit_msg>INTEGRATION: CWS vgbugs07 (1.26.276); FILE MERGED 2007/06/04 13:23:24 vg 1.26.276.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sdxmlexp_impl.hxx,v $ * * $Revision: 1.27 $ * * last change: $Author: hr $ $Date: 2007-06-27 15:05:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDXMLEXP_IMPL_HXX #define _SDXMLEXP_IMPL_HXX #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_ #include <com/sun/star/task/XStatusIndicator.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_XDRAWPAGE_HPP_ #include <com/sun/star/drawing/XDrawPage.hpp> #endif #ifndef _COMPHELPER_STLTYPES_HXX_ #include <comphelper/stl_types.hxx> #endif ////////////////////////////////////////////////////////////////////////////// class SvXMLUnitConverter; class SvXMLExportItemMapper; class SfxPoolItem; class SfxItemSet; class OUStrings_Impl; class OUStringsSort_Impl; class Rectangle; class ImpPresPageDrawStylePropMapper; class ImpXMLEXPPageMasterList; class ImpXMLEXPPageMasterInfo; class ImpXMLDrawPageInfoList; class ImpXMLAutoLayoutInfoList; class SvXMLAutoStylePoolP; class XMLSdPropHdlFactory; class ImpXMLShapeStyleInfo; class XMLShapeExportPropertyMapper; class XMLPageExportPropertyMapper; ////////////////////////////////////////////////////////////////////////////// enum XmlPlaceholder { XmlPlaceholderTitle, XmlPlaceholderOutline, XmlPlaceholderSubtitle, XmlPlaceholderText, XmlPlaceholderGraphic, XmlPlaceholderObject, XmlPlaceholderChart, XmlPlaceholderOrgchart, XmlPlaceholderTable, XmlPlaceholderPage, XmlPlaceholderNotes, XmlPlaceholderHandout, XmlPlaceholderVerticalTitle, XmlPlaceholderVerticalOutline }; DECLARE_STL_STDKEY_SET( sal_Int32, SdXMLFormatMap ); ////////////////////////////////////////////////////////////////////////////// struct HeaderFooterPageSettingsImpl { rtl::OUString maStrHeaderDeclName; rtl::OUString maStrFooterDeclName; rtl::OUString maStrDateTimeDeclName; }; struct DateTimeDeclImpl { rtl::OUString maStrText; sal_Bool mbFixed; sal_Int32 mnFormat; }; ////////////////////////////////////////////////////////////////////////////// class SdXMLExport : public SvXMLExport { com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > mxDocStyleFamilies; com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocMasterPages; com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > mxDocDrawPages; sal_Int32 mnDocMasterPageCount; sal_Int32 mnDocDrawPageCount; sal_uInt32 mnShapeStyleInfoIndex; sal_uInt32 mnObjectCount; // temporary infos ImpXMLEXPPageMasterList* mpPageMasterInfoList; ImpXMLEXPPageMasterList* mpPageMasterUsageList; ImpXMLEXPPageMasterList* mpNotesPageMasterUsageList; ImpXMLEXPPageMasterInfo* mpHandoutPageMaster; ImpXMLAutoLayoutInfoList* mpAutoLayoutInfoList; com::sun::star::uno::Sequence< ::rtl::OUString > maDrawPagesAutoLayoutNames; ::std::vector< ::rtl::OUString > maDrawPagesStyleNames; ::std::vector< ::rtl::OUString > maDrawNotesPagesStyleNames; ::std::vector< ::rtl::OUString > maMasterPagesStyleNames; ::rtl::OUString maHandoutMasterStyleName; ::std::vector< HeaderFooterPageSettingsImpl > maDrawPagesHeaderFooterSettings; ::std::vector< HeaderFooterPageSettingsImpl > maDrawNotesPagesHeaderFooterSettings; ::std::vector< ::rtl::OUString > maHeaderDeclsVector; ::std::vector< ::rtl::OUString > maFooterDeclsVector; ::std::vector< DateTimeDeclImpl > maDateTimeDeclsVector; HeaderFooterPageSettingsImpl maHandoutPageHeaderFooterSettings; XMLSdPropHdlFactory* mpSdPropHdlFactory; XMLShapeExportPropertyMapper* mpPropertySetMapper; XMLPageExportPropertyMapper* mpPresPagePropsMapper; SdXMLFormatMap maUsedDateStyles; // this is a vector with the used formatings for date fields SdXMLFormatMap maUsedTimeStyles; // this is a vector with the used formatings for time fields sal_Bool mbIsDraw; sal_Bool mbFamilyGraphicUsed; sal_Bool mbFamilyPresentationUsed; const rtl::OUString msZIndex; const rtl::OUString msEmptyPres; const rtl::OUString msModel; const rtl::OUString msStartShape; const rtl::OUString msEndShape; const rtl::OUString msPageLayoutNames; virtual void _ExportStyles(BOOL bUsed); virtual void _ExportAutoStyles(); virtual void _ExportMasterStyles(); virtual void _ExportContent(); // #82003# virtual void _ExportMeta(); ImpXMLEXPPageMasterInfo* ImpGetOrCreatePageMasterInfo( com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > xMasterPage ); void ImpPrepPageMasterInfos(); void ImpPrepDrawMasterInfos(); void ImpWritePageMasterInfos(); void ImpPrepAutoLayoutInfos(); HeaderFooterPageSettingsImpl ImpPrepDrawPageHeaderFooterDecls( const com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage >& xDrawPage ); ImpXMLEXPPageMasterInfo* ImpGetPageMasterInfoByName(const rtl::OUString& rName); void ImpPrepDrawPageInfos(); void ImpPrepMasterPageInfos(); void ImpWritePresentationStyles(); ::rtl::OUString ImpCreatePresPageStyleName( com::sun::star::uno::Reference<com::sun::star::drawing::XDrawPage> xDrawPage, bool bExportBackground = true ); BOOL ImpPrepAutoLayoutInfo(const com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage >& xPage, rtl::OUString& rName); void ImpWriteAutoLayoutInfos(); void ImpWriteAutoLayoutPlaceholder(XmlPlaceholder ePl, const Rectangle& rRect); void ImpWriteHeaderFooterDecls(); void ImplExportHeaderFooterDeclAttributes( const HeaderFooterPageSettingsImpl& aSettings ); void exportFormsElement( com::sun::star::uno::Reference< com::sun::star::drawing::XDrawPage > xDrawPage ); void exportPresentationSettings(); // #82003# helper function for recursive object count sal_uInt32 ImpRecursiveObjectCount( com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > xShapes); protected: virtual void GetViewSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); virtual void GetConfigurationSettings(com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aProps); public: // #110680# SdXMLExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory, sal_Bool bIsDraw, sal_uInt16 nExportFlags = EXPORT_ALL ); virtual ~SdXMLExport(); void SetProgress(sal_Int32 nProg); // XExporter virtual void SAL_CALL setSourceDocument( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent >& xDoc ) throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); // get factories and mappers XMLSdPropHdlFactory* GetSdPropHdlFactory() const { return mpSdPropHdlFactory; } XMLShapeExportPropertyMapper* GetPropertySetMapper() const { return mpPropertySetMapper; } XMLPageExportPropertyMapper* GetPresPagePropsMapper() const { return mpPresPagePropsMapper; } BOOL IsDraw() const { return mbIsDraw; } BOOL IsImpress() const { return !mbIsDraw; } BOOL IsFamilyGraphicUsed() const { return mbFamilyGraphicUsed; } void SetFamilyGraphicUsed() { mbFamilyGraphicUsed = TRUE; } BOOL IsFamilyPresentationUsed() const { return mbFamilyPresentationUsed; } void SetFamilyPresentationUsed() { mbFamilyPresentationUsed = TRUE; } virtual void addDataStyle(const sal_Int32 nNumberFormat, sal_Bool bTimeFormat = sal_False ); virtual void exportDataStyles(); virtual void exportAutoDataStyles(); virtual rtl::OUString getDataStyleName(const sal_Int32 nNumberFormat, sal_Bool bTimeFormat = sal_False ) const; // XServiceInfo ( : SvXMLExport ) virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); }; #endif // _SDXMLEXP_HXX <|endoftext|>
<commit_before>#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> #include <unistd.h> #include <execinfo.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" #include "../lcd/LcdDisplay.h" #include "MockScannerView.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "/var/run/scannerd.STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); fflush(stdout); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(beacon_info * info) { #if 1 printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(*info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop); fflush(stdout); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; static ScannerView *getDisplayInstance() { ScannerView *view = nullptr; #ifdef HAVE_LCD_DISPLAY LcdDisplay *lcd = LcdDisplay::getLcdDisplayInstance(); lcd->init(); view = lcd; #else view = new MockScannerView(); #endif } void printStacktrace() { void *array[20]; int size = backtrace(array, sizeof(array) / sizeof(array[0])); backtrace_symbols_fd(array, size, STDERR_FILENO); } static void terminateHandler() { std::exception_ptr exptr = std::current_exception(); if (exptr != nullptr) { // the only useful feature of std::exception_ptr is that it can be rethrown... try { std::rethrow_exception(exptr); } catch (std::exception &ex) { std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what()); } catch (...) { std::fprintf(stderr, "Terminated due to unknown exception\n"); } } else { std::fprintf(stderr, "Terminated due to unknown reason :(\n"); } printStacktrace(); exit(100); } /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); for(int n = 0; n < argc; n ++) { printf(" argv[%d] = %s\n", n, argv[n]); } fflush(stdout); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events. If this is a string with a comma separated list of names, the scanner will cycle through them.", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672", false, "tcp://localhost:5672", "string", cmd); TCLAP::ValueArg<std::string> destinationName("t", "destinationName", "Specify the name of the destination on the message broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow", "Specify the number of seconds in the analyzeMode time window", false, 1, "int", cmd); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); TCLAP::ValueArg<std::string> bcastAddress("", "bcastAddress", "Address to broadcast scanner status to as backup to statusQueue if non-empty; default empty", false, "", "string", cmd); TCLAP::ValueArg<int> bcastPort("", "bcastPort", "Port to broadcast scanner status to as backup to statusQueue if non-empty; default empty", false, 12345, "int", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); TCLAP::ValueArg<int> statusInterval("I", "statusInterval", "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30", false, 30, "int", cmd); TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply", "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1", false, -1, "int", cmd); TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue", "Specify the name of the status health queue destination; default scannerHealth", false, "scannerHealth", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat", "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.", false); TCLAP::SwitchArg analzyeMode("", "analzyeMode", "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window", false); TCLAP::SwitchArg generateTestData("T", "generateTestData", "Indicate that test data should be generated", false); TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect", "Don't try to reconnect to the broker on failure, just exit", false); TCLAP::SwitchArg batteryTestMode("", "batteryTestMode", "Simply monitor the raw heartbeat beacon events and publish them to the destinationName", false); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); cmd.add(skipHeartbeat); cmd.add(analzyeMode); cmd.add(generateTestData); cmd.add(noBrokerReconnect); cmd.add(batteryTestMode); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } // Validate the system time as unless the network time has syncd, just exit to wait for it to happen int64_t nowMS = EventsWindow::currentMilliseconds(); // 1434954728562 = 2015-06-21 23:32:08.562 if(nowMS < 1434954728562) { fprintf(stderr, "currentMilliseconds(%ld) < 1434954728562 = 2015-06-21 23:32:08.562", nowMS); exit(1); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), destinationName.getValue()); command.setUseQueues(useQueues.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setSkipHeartbeat(skipHeartbeat.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setAnalyzeMode(analzyeMode.getValue()); command.setAnalyzeWindow(analyzeWindow.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); command.setStatusInterval(statusInterval.getValue()); command.setStatusQueue(statusQueue.getValue()); command.setGenerateTestData(generateTestData.getValue()); command.setBatteryTestMode(batteryTestMode.getValue()); command.setUsername(username.getValue()); command.setPassword(password.getValue()); command.setBcastAddress(bcastAddress.getValue()); command.setBcastPort(bcastPort.getValue()); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } // Install default terminate handler to make sure we exit with non-zero status std::set_terminate(terminateHandler); // Create a beacon mapping instance shared_ptr<BeaconMapper> beaconMapper(new BeaconMapper()); printf("Loading the beacon to user mapping...\n"); beaconMapper->refresh(); // Get the scanner view implementation shared_ptr<ScannerView> lcd(getDisplayInstance()); // Set the scanner view display's beacon mapper to display the minorID to name correctly lcd->setBeaconMapper(beaconMapper); parserLogic.setScannerView(lcd); char cwd[256]; getcwd(cwd, sizeof(cwd)); printf("Begin scanning, cwd=%s...\n", cwd); fflush(stdout); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); fflush(stdout); return 0; } <commit_msg>Add flag to skip scanner view display of closest beacon<commit_after>#include <cstdio> #include <string> #include <regex> #include <fstream> #include <sys/stat.h> #include <unistd.h> #include <execinfo.h> // http://tclap.sourceforge.net/manual.html #include "tclap/CmdLine.h" #include "HCIDumpParser.h" #include "MsgPublisherTypeConstraint.h" #include "../lcd/LcdDisplay.h" #include "MockScannerView.h" static HCIDumpParser parserLogic; #define STOP_MARKER_FILE "/var/run/scannerd.STOP" inline bool stopMarkerExists() { struct stat buffer; bool stop = (stat (STOP_MARKER_FILE, &buffer) == 0); if(stop) { printf("Found STOP marker file, will exit...\n"); fflush(stdout); } return stop; } static long eventCount = 0; static long maxEventCount = 0; static int64_t lastMarkerCheckTime = 0; /** * Callback invoked by the hdidumpinternal.c code when a LE_ADVERTISING_REPORT event is seen on the stack */ extern "C" bool beacon_event_callback(beacon_info * info) { #if 1 printf("beacon_event_callback(%ld: %s, code=%d, time=%lld)\n", eventCount, info->uuid, info->code, info->time); #endif parserLogic.beaconEvent(*info); eventCount ++; // Check for a termination marker every 1000 events or 5 seconds bool stop = false; int64_t elapsed = info->time - lastMarkerCheckTime; if((eventCount % 1000) == 0 || elapsed > 5000) { lastMarkerCheckTime = info->time; stop = stopMarkerExists(); printf("beacon_event_callback, status eventCount=%ld, stop=%d\n", eventCount, stop); fflush(stdout); } // Check max event count limit if(maxEventCount > 0 && eventCount >= maxEventCount) stop = true; return stop; } using namespace std; static ScannerView *getDisplayInstance() { ScannerView *view = nullptr; #ifdef HAVE_LCD_DISPLAY LcdDisplay *lcd = LcdDisplay::getLcdDisplayInstance(); lcd->init(); view = lcd; #else view = new MockScannerView(); #endif } void printStacktrace() { void *array[20]; int size = backtrace(array, sizeof(array) / sizeof(array[0])); backtrace_symbols_fd(array, size, STDERR_FILENO); } static void terminateHandler() { std::exception_ptr exptr = std::current_exception(); if (exptr != nullptr) { // the only useful feature of std::exception_ptr is that it can be rethrown... try { std::rethrow_exception(exptr); } catch (std::exception &ex) { std::fprintf(stderr, "Terminated due to exception: %s\n", ex.what()); } catch (...) { std::fprintf(stderr, "Terminated due to unknown exception\n"); } } else { std::fprintf(stderr, "Terminated due to unknown reason :(\n"); } printStacktrace(); exit(100); } /** * A version of the native scanner that directly integrates with the bluez stack hcidump command rather than parsing * the hcidump output. */ int main(int argc, const char **argv) { printf("NativeScanner starting up...\n"); for(int n = 0; n < argc; n ++) { printf(" argv[%d] = %s\n", n, argv[n]); } fflush(stdout); TCLAP::CmdLine cmd("NativeScanner command line options", ' ', "0.1"); // TCLAP::ValueArg<std::string> scannerID("s", "scannerID", "Specify the ID of the scanner reading the beacon events. If this is a string with a comma separated list of names, the scanner will cycle through them.", true, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> heartbeatUUID("H", "heartbeatUUID", "Specify the UUID of the beacon used to signal the scanner heartbeat event", false, "DEFAULT", "string", cmd); TCLAP::ValueArg<std::string> rawDumpFile("d", "rawDumpFile", "Specify a path to an hcidump file to parse for testing", false, "", "string", cmd); TCLAP::ValueArg<std::string> clientID("c", "clientID", "Specify the clientID to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> username("u", "username", "Specify the username to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> password("p", "password", "Specify the password to connect to the MQTT broker with", false, "", "string", cmd); TCLAP::ValueArg<std::string> brokerURL("b", "brokerURL", "Specify the brokerURL to connect to the message broker with; default tcp://localhost:5672", false, "tcp://localhost:5672", "string", cmd); TCLAP::ValueArg<std::string> destinationName("t", "destinationName", "Specify the name of the destination on the message broker to publish to; default beaconEvents", false, "beaconEvents", "string", cmd); TCLAP::ValueArg<int> analyzeWindow("W", "analyzeWindow", "Specify the number of seconds in the analyzeMode time window", false, 1, "int", cmd); TCLAP::ValueArg<std::string> hciDev("D", "hciDev", "Specify the name of the host controller interface to use; default hci0", false, "hci0", "string", cmd); TCLAP::ValueArg<std::string> bcastAddress("", "bcastAddress", "Address to broadcast scanner status to as backup to statusQueue if non-empty; default empty", false, "", "string", cmd); TCLAP::ValueArg<int> bcastPort("", "bcastPort", "Port to broadcast scanner status to as backup to statusQueue if non-empty; default empty", false, 12345, "int", cmd); MsgPublisherTypeConstraint pubTypeConstraint; TCLAP::ValueArg<std::string> pubType("P", "pubType", "Specify the MsgPublisherType enum for the publisher implementation to use; default AMQP_QPID", false, "AMQP_QPID", &pubTypeConstraint, cmd, nullptr); TCLAP::ValueArg<int> maxCount("C", "maxCount", "Specify a maxium number of events the scanner should process before exiting; default 0 means no limit", false, 0, "int", cmd); TCLAP::ValueArg<int> batchCount("B", "batchCount", "Specify a maxium number of events the scanner should combine before sending to broker; default 0 means no batching", false, 0, "int", cmd); TCLAP::ValueArg<int> statusInterval("I", "statusInterval", "Specify the interval in seconds between health status messages, <= 0 means no messages; default 30", false, 30, "int", cmd); TCLAP::ValueArg<int> rebootAfterNoReply("r", "rebootAfterNoReply", "Specify the interval in seconds after which a failure to hear our own heartbeat triggers a reboot, <= 0 means no reboot; default -1", false, -1, "int", cmd); TCLAP::ValueArg<std::string> statusQueue("q", "statusQueue", "Specify the name of the status health queue destination; default scannerHealth", false, "scannerHealth", "string", cmd); TCLAP::SwitchArg skipPublish("S", "skipPublish", "Indicate that the parsed beacons should not be published", false); TCLAP::SwitchArg asyncMode("A", "asyncMode", "Indicate that the parsed beacons should be published using async delivery mode", false); TCLAP::SwitchArg useQueues("Q", "useQueues", "Indicate that the destination type is a queue. If not given the default type is a topic.", false); TCLAP::SwitchArg skipHeartbeat("K", "skipHeartbeat", "Don't publish the heartbeat messages. Useful to limit the noise when testing the scanner.", false); TCLAP::SwitchArg analzyeMode("", "analzyeMode", "Run the scanner in a mode that simply collects beacon readings and reports unique beacons seen in a time window", false); TCLAP::SwitchArg generateTestData("T", "generateTestData", "Indicate that test data should be generated", false); TCLAP::SwitchArg noBrokerReconnect("", "noBrokerReconnect", "Don't try to reconnect to the broker on failure, just exit", false); TCLAP::SwitchArg skipScannerView("", "skipScannerView", "Skip the scanner view display of closest beacon", false); TCLAP::SwitchArg batteryTestMode("", "batteryTestMode", "Simply monitor the raw heartbeat beacon events and publish them to the destinationName", false); try { // Add the flag arguments cmd.add(skipPublish); cmd.add(asyncMode); cmd.add(useQueues); cmd.add(skipHeartbeat); cmd.add(analzyeMode); cmd.add(generateTestData); cmd.add(noBrokerReconnect); cmd.add(batteryTestMode); cmd.add(skipScannerView); // Parse the argv array. printf("Parsing command line...\n"); cmd.parse( argc, argv ); printf("done\n"); } catch (TCLAP::ArgException &e) { fprintf(stderr, "error: %s for arg: %s\n", e.error().c_str(), e.argId().c_str()); } // Remove any stop marker file if(remove(STOP_MARKER_FILE) == 0) { printf("Removed existing %s marker file\n", STOP_MARKER_FILE); } // Validate the system time as unless the network time has syncd, just exit to wait for it to happen int64_t nowMS = EventsWindow::currentMilliseconds(); // 1434954728562 = 2015-06-21 23:32:08.562 if(nowMS < 1434954728562) { fprintf(stderr, "currentMilliseconds(%ld) < 1434954728562 = 2015-06-21 23:32:08.562", nowMS); exit(1); } HCIDumpCommand command(scannerID.getValue(), brokerURL.getValue(), clientID.getValue(), destinationName.getValue()); command.setUseQueues(useQueues.getValue()); command.setSkipPublish(skipPublish.getValue()); command.setSkipHeartbeat(skipHeartbeat.getValue()); command.setHciDev(hciDev.getValue()); command.setAsyncMode(asyncMode.getValue()); command.setAnalyzeMode(analzyeMode.getValue()); command.setAnalyzeWindow(analyzeWindow.getValue()); command.setPubType(pubTypeConstraint.toType(pubType.getValue())); command.setStatusInterval(statusInterval.getValue()); command.setStatusQueue(statusQueue.getValue()); command.setGenerateTestData(generateTestData.getValue()); command.setBatteryTestMode(batteryTestMode.getValue()); command.setUsername(username.getValue()); command.setPassword(password.getValue()); command.setBcastAddress(bcastAddress.getValue()); command.setBcastPort(bcastPort.getValue()); if(maxCount.getValue() > 0) { maxEventCount = maxCount.getValue(); printf("Set maxEventCount: %ld\n", maxEventCount); } parserLogic.setBatchCount(batchCount.getValue()); if(heartbeatUUID.isSet()) { parserLogic.setScannerUUID(heartbeatUUID.getValue()); printf("Set heartbeatUUID: %s\n", heartbeatUUID.getValue().c_str()); } // Install default terminate handler to make sure we exit with non-zero status std::set_terminate(terminateHandler); // Create a beacon mapping instance shared_ptr<BeaconMapper> beaconMapper(new BeaconMapper()); printf("Loading the beacon to user mapping...\n"); beaconMapper->refresh(); if(!skipScannerView.getValue()) { // Get the scanner view implementation shared_ptr<ScannerView> lcd(getDisplayInstance()); // Set the scanner view display's beacon mapper to display the minorID to name correctly lcd->setBeaconMapper(beaconMapper); parserLogic.setScannerView(lcd); } char cwd[256]; getcwd(cwd, sizeof(cwd)); printf("Begin scanning, cwd=%s...\n", cwd); fflush(stdout); parserLogic.processHCI(command); parserLogic.cleanup(); printf("End scanning\n"); fflush(stdout); return 0; } <|endoftext|>
<commit_before>/*********************************************************************** ssx/genv2.cpp - Walks the SSQLS v2 parse result, writing back out the equivalent SSQLS v2 DSL code. This is useful for testing that our parser has correctly understood a given piece of code. It is also something like the preprocessor mode of a C++ compiler, emitting a digested version of its input. Copyright (c) 2009 by Warren Young. Others may also hold copyrights on code in this file. See the CREDITS.txt file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "genv2.h" #include "parsev2.h" #include <iostream> #include <fstream> #include <typeinfo> using namespace std; //// generate_ssqls2 /////////////////////////////////////////////////// // 2 versions: second checks its arguments and opens the named file, // calling the second to actually generate the SSQLS v2 output from // the parse result only if we were given sane parameters. static bool generate_ssqls2(ofstream&, const ParseV2* pparse) { for (ParseV2::LineListIt it = pparse->begin(); it != pparse->end(); ++it) { cout << "TRACE: write " << typeid(*it).name() << " line." << endl; } return true; } bool generate_ssqls2(const char* file_name, const ParseV2* pparse) { if (pparse) { ofstream ofs(file_name); if (ofs) { cout << "TRACE: Generating SSQLS v2 file " << file_name << " from " << (pparse->end() - pparse->begin()) << " line parse result." << endl; return generate_ssqls2(ofs, pparse); } else { cerr << "Failed to open " << file_name << \ " for writing for -o!" << endl; return false; } } else { cerr << "No parse result given to -o handler!" << endl; return false; } } <commit_msg>- ssqlsxlat -o option now accepts '-' argument, meaning stdout - SSQLS v2 generator is no longer hard-coded to send its output to cout now that we can pass it an option to make this happen, for testing.<commit_after>/*********************************************************************** ssx/genv2.cpp - Walks the SSQLS v2 parse result, writing back out the equivalent SSQLS v2 DSL code. This is useful for testing that our parser has correctly understood a given piece of code. It is also something like the preprocessor mode of a C++ compiler, emitting a digested version of its input. Copyright (c) 2009 by Warren Young and (c) 2009-2010 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS.txt file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "genv2.h" #include "parsev2.h" #include <iostream> #include <fstream> #include <typeinfo> using namespace std; //// generate_ssqls2 /////////////////////////////////////////////////// // 2 versions: second checks its arguments and opens the named file, // calling the second to actually generate the SSQLS v2 output from // the parse result only if we were given sane parameters. static bool generate_ssqls2(ostream& os, const ParseV2* pparse) { ParseV2::LineListIt it; for (it = pparse->begin(); it != pparse->end(); ++it) { os << *it << endl; } return true; } bool generate_ssqls2(const char* file_name, const ParseV2* pparse) { if (pparse) { if (strcmp(file_name, "-") == 0) { return generate_ssqls2(cout, pparse); } else { ofstream ofs(file_name); if (ofs) { cout << "TRACE: Generating SSQLS v2 file " << file_name << " from " << (pparse->end() - pparse->begin()) << " line parse result." << endl; return generate_ssqls2(ofs, pparse); } else { cerr << "Failed to open " << file_name << \ " for writing for -o!" << endl; return false; } } } else { cerr << "No parse result given to -o handler!" << endl; return false; } } <|endoftext|>
<commit_before>/* Copyright (C) 2011 vlc-phonon AUTHORS This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "libvlc.h" #include <QtCore/QByteArray> #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QLibrary> #include <QtCore/QSettings> #include <QtCore/QString> #include <QtCore/QStringBuilder> #include <QtCore/QVarLengthArray> #include <vlc/libvlc.h> #include "debug.h" LibVLC *LibVLC::self; LibVLC::LibVLC() : m_vlcInstance(0) { } LibVLC::~LibVLC() { libvlc_release(m_vlcInstance); vlcUnload(); self = 0; } bool LibVLC::init() { Q_ASSERT_X(!self, "LibVLC", "there should be only one LibVLC object"); LibVLC::self = new LibVLC; QString path = self->vlcPath(); if (!path.isEmpty()) { QList<QByteArray> args; QString pluginsPath = QLatin1Literal("--plugin-path=") % QDir::toNativeSeparators(QFileInfo(self->vlcPath()).dir().path()); #if defined(Q_OS_UNIX) pluginsPath.append("/vlc"); #elif defined(Q_OS_WIN) pluginsPath.append("\\plugins"); #endif args << QFile::encodeName(pluginsPath); // Ends up as something like $HOME/.config/Phonon/vlc.conf const QString configFileName = QSettings("Phonon", "vlc").fileName(); if (QFile::exists(configFileName)) { args << QByteArray("--config=").append(QFile::encodeName(configFileName)); } int debugLevel = 3 - (int) Debug::minimumDebugLevel(); if (debugLevel > 0) { args << QByteArray("--verbose=").append(QString::number(debugLevel)); args << QByteArray("--extraintf=logger"); #ifdef Q_WS_WIN QDir logFilePath(QString(qgetenv("APPDATA")).append("/vlc")); #else QDir logFilePath(QDir::homePath().append("/.vlc")); #endif //Q_WS_WIN logFilePath.mkdir("log"); const QString logFile = logFilePath.path() .append("/log/vlc-log-") .append(QString::number(qApp->applicationPid())) .append(".txt"); args << QByteArray("--logfile=").append(QFile::encodeName(QDir::toNativeSeparators(logFile))); } args << "--reset-plugins-cache"; args << "--no-media-library"; args << "--no-osd"; args << "--no-stats"; args << "--no-video-title-show"; args << "--album-art=0"; args << "--no-xlib"; #ifndef Q_OS_MAC args << "--no-one-instance"; #endif // Build const char* array QVarLengthArray<const char*, 64> vlcArgs(args.size()); for (int i = 0; i < args.size(); ++i) { vlcArgs[i] = args.at(i).constData(); } // Create and initialize a libvlc instance (it should be done only once) self->m_vlcInstance = libvlc_new(vlcArgs.size(), vlcArgs.constData()); if (!self->m_vlcInstance) { fatal() << "libVLC:" << LibVLC::errorMessage(); return false; } return true; } return false; } const char *LibVLC::errorMessage() { return libvlc_errmsg(); } #if defined(Q_OS_UNIX) bool LibVLC::libGreaterThan(const QString &lhs, const QString &rhs) { const QStringList lhsparts = lhs.split(QLatin1Char('.')); const QStringList rhsparts = rhs.split(QLatin1Char('.')); Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1); for (int i = 1; i < rhsparts.count(); ++i) { if (lhsparts.count() <= i) { // left hand side is shorter, so it's less than rhs return false; } bool ok = false; int b = 0; int a = lhsparts.at(i).toInt(&ok); if (ok) { b = rhsparts.at(i).toInt(&ok); } if (ok) { // both toInt succeeded if (a == b) { continue; } return a > b; } else { // compare as strings; if (lhsparts.at(i) == rhsparts.at(i)) { continue; } return lhsparts.at(i) > rhsparts.at(i); } } // they compared strictly equally so far // lhs cannot be less than rhs return true; } #endif QStringList LibVLC::findAllLibVlcPaths() { QStringList paths; #ifdef Q_OS_UNIX paths = QString::fromLatin1(qgetenv("LD_LIBRARY_PATH")) .split(QLatin1Char(':'), QString::SkipEmptyParts); paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String("/usr/lib") << QLatin1String("/usr/local/lib"); #if defined(Q_WS_MAC) paths << QCoreApplication::applicationDirPath() << QCoreApplication::applicationDirPath() % QLatin1Literal("/../Frameworks") << QCoreApplication::applicationDirPath() % QLatin1Literal("/../PlugIns") << QCoreApplication::applicationDirPath() % QLatin1Literal("/lib"); #endif QStringList foundVlcs; foreach (const QString & path, paths) { QDir dir = QDir(path); QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.*"), QDir::Files); qSort(entryList.begin(), entryList.end(), LibVLC::libGreaterThan); foreach(const QString & entry, entryList) { if (entry.contains(".debug")) { continue; } foundVlcs << path % QLatin1Char('/') % entry; } } return foundVlcs; #elif defined(Q_OS_WIN) // Current application path has highest priority. // Application could be delivered with own copy of qt, phonon, LibVLC, vlc and vlc plugins. QString appDirVlc = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() % QLatin1Char('\\') % QLatin1Literal("libvlc.dll")); if (QFile::exists(appDirVlc)) { paths << appDirVlc; } // Read VLC version and installation directory from Windows registry QSettings settings(QSettings::SystemScope, "VideoLAN", "VLC"); QString vlcVersion = settings.value("Version").toString(); QString vlcInstallDir = settings.value("InstallDir").toString(); if (vlcVersion.startsWith(QLatin1String("1.1")) && !vlcInstallDir.isEmpty()) { paths << vlcInstallDir % QLatin1Char('\\') % QLatin1Literal("libvlc.dll"); return paths; } else { //If nothing is found in the registry try %PATH% QStringList searchPaths = QString::fromLatin1(qgetenv("PATH")) .split(QLatin1Char(';'), QString::SkipEmptyParts); QStringList foundVlcs; foreach(const QString & sp, searchPaths) { QDir dir = QDir(sp); QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.dll"), QDir::Files); foreach(const QString & entry, entryList){ foundVlcs << sp % QLatin1Char('\\') % entry; } } paths << foundVlcs; return paths; } #endif } QString LibVLC::vlcPath() { static QString path; if (!path.isEmpty()) { return path; } m_vlcLibrary = new QLibrary(); QStringList paths = LibVLC::findAllLibVlcPaths(); foreach(path, paths) { m_vlcLibrary->setFileName(path); if (!m_vlcLibrary->resolve("libvlc_exception_init")) { //"libvlc_exception_init" not contained in 1.1+ return path; } else { debug() << "Cannot resolve the symbol or load VLC library"; } warning() << m_vlcLibrary->errorString(); } vlcUnload(); return QString(); } void LibVLC::vlcUnload() { m_vlcLibrary->unload(); delete m_vlcLibrary; m_vlcLibrary = 0; } <commit_msg>only libvlc_instance if init actually was successful<commit_after>/* Copyright (C) 2011 vlc-phonon AUTHORS This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "libvlc.h" #include <QtCore/QByteArray> #include <QtCore/QCoreApplication> #include <QtCore/QDebug> #include <QtCore/QDir> #include <QtCore/QLibrary> #include <QtCore/QSettings> #include <QtCore/QString> #include <QtCore/QStringBuilder> #include <QtCore/QVarLengthArray> #include <vlc/libvlc.h> #include "debug.h" LibVLC *LibVLC::self; LibVLC::LibVLC() : m_vlcInstance(0) { } LibVLC::~LibVLC() { if (m_vlcInstance) libvlc_release(m_vlcInstance); vlcUnload(); self = 0; } bool LibVLC::init() { Q_ASSERT_X(!self, "LibVLC", "there should be only one LibVLC object"); LibVLC::self = new LibVLC; QString path = self->vlcPath(); if (!path.isEmpty()) { QList<QByteArray> args; QString pluginsPath = QLatin1Literal("--plugin-path=") % QDir::toNativeSeparators(QFileInfo(self->vlcPath()).dir().path()); #if defined(Q_OS_UNIX) pluginsPath.append("/vlc"); #elif defined(Q_OS_WIN) pluginsPath.append("\\plugins"); #endif args << QFile::encodeName(pluginsPath); // Ends up as something like $HOME/.config/Phonon/vlc.conf const QString configFileName = QSettings("Phonon", "vlc").fileName(); if (QFile::exists(configFileName)) { args << QByteArray("--config=").append(QFile::encodeName(configFileName)); } int debugLevel = 3 - (int) Debug::minimumDebugLevel(); if (debugLevel > 0) { args << QByteArray("--verbose=").append(QString::number(debugLevel)); args << QByteArray("--extraintf=logger"); #ifdef Q_WS_WIN QDir logFilePath(QString(qgetenv("APPDATA")).append("/vlc")); #else QDir logFilePath(QDir::homePath().append("/.vlc")); #endif //Q_WS_WIN logFilePath.mkdir("log"); const QString logFile = logFilePath.path() .append("/log/vlc-log-") .append(QString::number(qApp->applicationPid())) .append(".txt"); args << QByteArray("--logfile=").append(QFile::encodeName(QDir::toNativeSeparators(logFile))); } args << "--reset-plugins-cache"; args << "--no-media-library"; args << "--no-osd"; args << "--no-stats"; args << "--no-video-title-show"; args << "--album-art=0"; args << "--no-xlib"; #ifndef Q_OS_MAC args << "--no-one-instance"; #endif // Build const char* array QVarLengthArray<const char*, 64> vlcArgs(args.size()); for (int i = 0; i < args.size(); ++i) { vlcArgs[i] = args.at(i).constData(); } // Create and initialize a libvlc instance (it should be done only once) self->m_vlcInstance = libvlc_new(vlcArgs.size(), vlcArgs.constData()); if (!self->m_vlcInstance) { fatal() << "libVLC:" << LibVLC::errorMessage(); return false; } return true; } return false; } const char *LibVLC::errorMessage() { return libvlc_errmsg(); } #if defined(Q_OS_UNIX) bool LibVLC::libGreaterThan(const QString &lhs, const QString &rhs) { const QStringList lhsparts = lhs.split(QLatin1Char('.')); const QStringList rhsparts = rhs.split(QLatin1Char('.')); Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1); for (int i = 1; i < rhsparts.count(); ++i) { if (lhsparts.count() <= i) { // left hand side is shorter, so it's less than rhs return false; } bool ok = false; int b = 0; int a = lhsparts.at(i).toInt(&ok); if (ok) { b = rhsparts.at(i).toInt(&ok); } if (ok) { // both toInt succeeded if (a == b) { continue; } return a > b; } else { // compare as strings; if (lhsparts.at(i) == rhsparts.at(i)) { continue; } return lhsparts.at(i) > rhsparts.at(i); } } // they compared strictly equally so far // lhs cannot be less than rhs return true; } #endif QStringList LibVLC::findAllLibVlcPaths() { QStringList paths; #ifdef Q_OS_UNIX paths = QString::fromLatin1(qgetenv("LD_LIBRARY_PATH")) .split(QLatin1Char(':'), QString::SkipEmptyParts); paths << QLatin1String(PHONON_LIB_INSTALL_DIR) << QLatin1String("/usr/lib") << QLatin1String("/usr/local/lib"); #if defined(Q_WS_MAC) paths << QCoreApplication::applicationDirPath() << QCoreApplication::applicationDirPath() % QLatin1Literal("/../Frameworks") << QCoreApplication::applicationDirPath() % QLatin1Literal("/../PlugIns") << QCoreApplication::applicationDirPath() % QLatin1Literal("/lib"); #endif QStringList foundVlcs; foreach (const QString & path, paths) { QDir dir = QDir(path); QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.*"), QDir::Files); qSort(entryList.begin(), entryList.end(), LibVLC::libGreaterThan); foreach(const QString & entry, entryList) { if (entry.contains(".debug")) { continue; } foundVlcs << path % QLatin1Char('/') % entry; } } return foundVlcs; #elif defined(Q_OS_WIN) // Current application path has highest priority. // Application could be delivered with own copy of qt, phonon, LibVLC, vlc and vlc plugins. QString appDirVlc = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() % QLatin1Char('\\') % QLatin1Literal("libvlc.dll")); if (QFile::exists(appDirVlc)) { paths << appDirVlc; } // Read VLC version and installation directory from Windows registry QSettings settings(QSettings::SystemScope, "VideoLAN", "VLC"); QString vlcVersion = settings.value("Version").toString(); QString vlcInstallDir = settings.value("InstallDir").toString(); if (vlcVersion.startsWith(QLatin1String("1.1")) && !vlcInstallDir.isEmpty()) { paths << vlcInstallDir % QLatin1Char('\\') % QLatin1Literal("libvlc.dll"); return paths; } else { //If nothing is found in the registry try %PATH% QStringList searchPaths = QString::fromLatin1(qgetenv("PATH")) .split(QLatin1Char(';'), QString::SkipEmptyParts); QStringList foundVlcs; foreach(const QString & sp, searchPaths) { QDir dir = QDir(sp); QStringList entryList = dir.entryList(QStringList() << QLatin1String("libvlc.dll"), QDir::Files); foreach(const QString & entry, entryList){ foundVlcs << sp % QLatin1Char('\\') % entry; } } paths << foundVlcs; return paths; } #endif } QString LibVLC::vlcPath() { static QString path; if (!path.isEmpty()) { return path; } m_vlcLibrary = new QLibrary(); QStringList paths = LibVLC::findAllLibVlcPaths(); foreach(path, paths) { m_vlcLibrary->setFileName(path); if (!m_vlcLibrary->resolve("libvlc_exception_init")) { //"libvlc_exception_init" not contained in 1.1+ return path; } else { debug() << "Cannot resolve the symbol or load VLC library"; } warning() << m_vlcLibrary->errorString(); } vlcUnload(); return QString(); } void LibVLC::vlcUnload() { m_vlcLibrary->unload(); delete m_vlcLibrary; m_vlcLibrary = 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libcdr project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <math.h> #include <stack> #include "CDRStylesCollector.h" #include "CDRInternalStream.h" #include "libcdr_utils.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef DUMP_IMAGE #define DUMP_IMAGE 0 #endif libcdr::CDRStylesCollector::CDRStylesCollector(libcdr::CDRParserState &ps) : m_ps(ps), m_page(8.5, 11.0, -4.25, -5.5), m_charStyles() { } libcdr::CDRStylesCollector::~CDRStylesCollector() { } void libcdr::CDRStylesCollector::collectBmp(unsigned imageId, unsigned colorModel, unsigned width, unsigned height, unsigned bpp, const std::vector<unsigned> &palette, const std::vector<unsigned char> &bitmap) { libcdr::CDRInternalStream stream(bitmap); librevenge::RVNGBinaryData image; unsigned tmpPixelSize = (unsigned)(height * width); if (tmpPixelSize < (unsigned)height) // overflow return; unsigned tmpDIBImageSize = tmpPixelSize * 4; if (tmpPixelSize > tmpDIBImageSize) // overflow !!! return; unsigned tmpDIBOffsetBits = 14 + 40; unsigned tmpDIBFileSize = tmpDIBOffsetBits + tmpDIBImageSize; if (tmpDIBImageSize > tmpDIBFileSize) // overflow !!! return; // Create DIB file header writeU16(image, 0x4D42); // Type writeU32(image, tmpDIBFileSize); // Size writeU16(image, 0); // Reserved1 writeU16(image, 0); // Reserved2 writeU32(image, tmpDIBOffsetBits); // OffsetBits // Create DIB Info header writeU32(image, 40); // Size writeU32(image, width); // Width writeU32(image, height); // Height writeU16(image, 1); // Planes writeU16(image, 32); // BitCount writeU32(image, 0); // Compression writeU32(image, tmpDIBImageSize); // SizeImage writeU32(image, 0); // XPelsPerMeter writeU32(image, 0); // YPelsPerMeter writeU32(image, 0); // ColorsUsed writeU32(image, 0); // ColorsImportant // Cater for eventual padding unsigned lineWidth = bitmap.size() / height; bool storeBMP = true; for (unsigned j = 0; j < height; ++j) { unsigned i = 0; unsigned k = 0; if (colorModel == 6) { while (i <lineWidth && k < width) { unsigned l = 0; unsigned char c = bitmap[j*lineWidth+i]; i++; while (k < width && l < 8) { if (c & 0x80) writeU32(image, 0xffffff); else writeU32(image, 0); c <<= 1; l++; k++; } } } else if (colorModel == 5) { while (i <lineWidth && i < width) { unsigned char c = bitmap[j*lineWidth+i]; i++; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, c))); } } else if (!palette.empty()) { while (i < lineWidth && i < width) { unsigned char c = bitmap[j*lineWidth+i]; i++; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, palette[c]))); } } else if (bpp == 24) { while (i < lineWidth && k < width) { unsigned c = ((unsigned)bitmap[j*lineWidth+i+2] << 16) | ((unsigned)bitmap[j*lineWidth+i+1] << 8) | ((unsigned)bitmap[j*lineWidth+i]); i += 3; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, c))); k++; } } else if (bpp == 32) { while (i < lineWidth && k < width) { unsigned c = (bitmap[j*lineWidth+i+3] << 24) | (bitmap[j*lineWidth+i+2] << 16) | (bitmap[j*lineWidth+i+1] << 8) | (bitmap[j*lineWidth+i]); i += 4; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, c))); k++; } } else storeBMP = false; } if (storeBMP) { #if DUMP_IMAGE librevenge::RVNGString filename; filename.sprintf("bitmap%.8x.bmp", imageId); FILE *f = fopen(filename.cstr(), "wb"); if (f) { const unsigned char *tmpBuffer = image.getDataBuffer(); for (unsigned long k = 0; k < image.size(); k++) fprintf(f, "%c",tmpBuffer[k]); fclose(f); } #endif m_ps.m_bmps[imageId] = image; } } void libcdr::CDRStylesCollector::collectBmp(unsigned imageId, const std::vector<unsigned char> &bitmap) { librevenge::RVNGBinaryData image(&bitmap[0], bitmap.size()); #if DUMP_IMAGE librevenge::RVNGString filename; filename.sprintf("bitmap%.8x.bmp", imageId); FILE *f = fopen(filename.cstr(), "wb"); if (f) { const unsigned char *tmpBuffer = image.getDataBuffer(); for (unsigned long k = 0; k < image.size(); k++) fprintf(f, "%c",tmpBuffer[k]); fclose(f); } #endif m_ps.m_bmps[imageId] = image; } void libcdr::CDRStylesCollector::collectPageSize(double width, double height, double offsetX, double offsetY) { if (m_ps.m_pages.empty()) m_page = CDRPage(width, height, offsetX, offsetY); else m_ps.m_pages.back() = CDRPage(width, height, offsetX, offsetY); } void libcdr::CDRStylesCollector::collectPage(unsigned /* level */) { m_ps.m_pages.push_back(m_page); } void libcdr::CDRStylesCollector::collectBmpf(unsigned patternId, unsigned width, unsigned height, const std::vector<unsigned char> &pattern) { m_ps.m_patterns[patternId] = CDRPattern(width, height, pattern); } void libcdr::CDRStylesCollector::collectColorProfile(const std::vector<unsigned char> &profile) { if (!profile.empty()) m_ps.setColorTransform(profile); } void libcdr::CDRStylesCollector::collectPaletteEntry(unsigned colorId, unsigned /* userId */, const libcdr::CDRColor &color) { m_ps.m_documentPalette[colorId] = color; } void libcdr::CDRStylesCollector::collectText(unsigned textId, unsigned styleId, const std::vector<unsigned char> &data, const std::vector<unsigned char> &charDescriptions, const std::map<unsigned, CDRCharacterStyle> &styleOverrides) { if (data.empty() || charDescriptions.empty()) return; unsigned char tmpCharDescription = 0; unsigned i = 0; unsigned j = 0; std::vector<unsigned char> tmpTextData; CDRCharacterStyle defaultCharStyle, tmpCharStyle; getRecursedStyle(defaultCharStyle, styleId); CDRTextLine line; for (i=0, j=0; i<charDescriptions.size() && j<data.size(); ++i) { tmpCharStyle = defaultCharStyle; std::map<unsigned, CDRCharacterStyle>::const_iterator iter = styleOverrides.find(tmpCharDescription & 0xfe); if (iter != styleOverrides.end()) tmpCharStyle.overrideCharacterStyle(iter->second); if (charDescriptions[i] != tmpCharDescription) { librevenge::RVNGString text; if (!tmpTextData.empty()) { if (tmpCharDescription & 0x01) appendCharacters(text, tmpTextData); else appendCharacters(text, tmpTextData, tmpCharStyle.m_charSet); } line.append(CDRText(text, tmpCharStyle)); tmpTextData.clear(); tmpCharDescription = charDescriptions[i]; } tmpTextData.push_back(data[j++]); if (tmpCharDescription & 0x01) tmpTextData.push_back(data[j++]); } if (!tmpTextData.empty()) { librevenge::RVNGString text; if (tmpCharDescription & 0x01) appendCharacters(text, tmpTextData); else appendCharacters(text, tmpTextData, tmpCharStyle.m_charSet); line.append(CDRText(text, tmpCharStyle)); CDR_DEBUG_MSG(("CDRStylesCollector::collectText - Text: %s\n", text.cstr())); } std::vector<CDRTextLine> &paragraphVector = m_ps.m_texts[textId]; paragraphVector.push_back(line); } void libcdr::CDRStylesCollector::collectStld(unsigned id, const CDRCharacterStyle &charStyle) { m_charStyles[id] = charStyle; } void libcdr::CDRStylesCollector::getRecursedStyle(CDRCharacterStyle &charStyle, unsigned styleId) { std::map<unsigned, CDRCharacterStyle>::const_iterator iter = m_charStyles.find(styleId); if (iter == m_charStyles.end()) return; std::stack<CDRCharacterStyle> styleStack; styleStack.push(iter->second); if (iter->second.m_parentId) { std::map<unsigned, CDRCharacterStyle>::const_iterator iter2 = m_charStyles.find(iter->second.m_parentId); while (iter2 != m_charStyles.end()) { styleStack.push(iter2->second); if (iter2->second.m_parentId) iter2 = m_charStyles.find(iter2->second.m_parentId); else iter2 = m_charStyles.end(); } } while (!styleStack.empty()) { charStyle.overrideCharacterStyle(styleStack.top()); styleStack.pop(); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <commit_msg>avoid out-of-bounds read<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * This file is part of the libcdr project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <math.h> #include <stack> #include "CDRStylesCollector.h" #include "CDRInternalStream.h" #include "libcdr_utils.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef DUMP_IMAGE #define DUMP_IMAGE 0 #endif libcdr::CDRStylesCollector::CDRStylesCollector(libcdr::CDRParserState &ps) : m_ps(ps), m_page(8.5, 11.0, -4.25, -5.5), m_charStyles() { } libcdr::CDRStylesCollector::~CDRStylesCollector() { } void libcdr::CDRStylesCollector::collectBmp(unsigned imageId, unsigned colorModel, unsigned width, unsigned height, unsigned bpp, const std::vector<unsigned> &palette, const std::vector<unsigned char> &bitmap) { libcdr::CDRInternalStream stream(bitmap); librevenge::RVNGBinaryData image; unsigned tmpPixelSize = (unsigned)(height * width); if (tmpPixelSize < (unsigned)height) // overflow return; unsigned tmpDIBImageSize = tmpPixelSize * 4; if (tmpPixelSize > tmpDIBImageSize) // overflow !!! return; unsigned tmpDIBOffsetBits = 14 + 40; unsigned tmpDIBFileSize = tmpDIBOffsetBits + tmpDIBImageSize; if (tmpDIBImageSize > tmpDIBFileSize) // overflow !!! return; // Create DIB file header writeU16(image, 0x4D42); // Type writeU32(image, tmpDIBFileSize); // Size writeU16(image, 0); // Reserved1 writeU16(image, 0); // Reserved2 writeU32(image, tmpDIBOffsetBits); // OffsetBits // Create DIB Info header writeU32(image, 40); // Size writeU32(image, width); // Width writeU32(image, height); // Height writeU16(image, 1); // Planes writeU16(image, 32); // BitCount writeU32(image, 0); // Compression writeU32(image, tmpDIBImageSize); // SizeImage writeU32(image, 0); // XPelsPerMeter writeU32(image, 0); // YPelsPerMeter writeU32(image, 0); // ColorsUsed writeU32(image, 0); // ColorsImportant // Cater for eventual padding unsigned lineWidth = bitmap.size() / height; bool storeBMP = true; for (unsigned j = 0; j < height; ++j) { unsigned i = 0; unsigned k = 0; if (colorModel == 6) { while (i <lineWidth && k < width) { unsigned l = 0; unsigned char c = bitmap[j*lineWidth+i]; i++; while (k < width && l < 8) { if (c & 0x80) writeU32(image, 0xffffff); else writeU32(image, 0); c <<= 1; l++; k++; } } } else if (colorModel == 5) { while (i <lineWidth && i < width) { unsigned char c = bitmap[j*lineWidth+i]; i++; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, c))); } } else if (!palette.empty()) { while (i < lineWidth && i < width) { unsigned char c = bitmap[j*lineWidth+i]; i++; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, palette[c]))); } } else if (bpp == 24) { while (i < lineWidth && k < width) { unsigned c = ((unsigned)bitmap[j*lineWidth+i+2] << 16) | ((unsigned)bitmap[j*lineWidth+i+1] << 8) | ((unsigned)bitmap[j*lineWidth+i]); i += 3; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, c))); k++; } } else if (bpp == 32) { while (i < lineWidth && k < width) { unsigned c = (bitmap[j*lineWidth+i+3] << 24) | (bitmap[j*lineWidth+i+2] << 16) | (bitmap[j*lineWidth+i+1] << 8) | (bitmap[j*lineWidth+i]); i += 4; writeU32(image, m_ps.getBMPColor(libcdr::CDRColor(colorModel, c))); k++; } } else storeBMP = false; } if (storeBMP) { #if DUMP_IMAGE librevenge::RVNGString filename; filename.sprintf("bitmap%.8x.bmp", imageId); FILE *f = fopen(filename.cstr(), "wb"); if (f) { const unsigned char *tmpBuffer = image.getDataBuffer(); for (unsigned long k = 0; k < image.size(); k++) fprintf(f, "%c",tmpBuffer[k]); fclose(f); } #endif m_ps.m_bmps[imageId] = image; } } void libcdr::CDRStylesCollector::collectBmp(unsigned imageId, const std::vector<unsigned char> &bitmap) { librevenge::RVNGBinaryData image(&bitmap[0], bitmap.size()); #if DUMP_IMAGE librevenge::RVNGString filename; filename.sprintf("bitmap%.8x.bmp", imageId); FILE *f = fopen(filename.cstr(), "wb"); if (f) { const unsigned char *tmpBuffer = image.getDataBuffer(); for (unsigned long k = 0; k < image.size(); k++) fprintf(f, "%c",tmpBuffer[k]); fclose(f); } #endif m_ps.m_bmps[imageId] = image; } void libcdr::CDRStylesCollector::collectPageSize(double width, double height, double offsetX, double offsetY) { if (m_ps.m_pages.empty()) m_page = CDRPage(width, height, offsetX, offsetY); else m_ps.m_pages.back() = CDRPage(width, height, offsetX, offsetY); } void libcdr::CDRStylesCollector::collectPage(unsigned /* level */) { m_ps.m_pages.push_back(m_page); } void libcdr::CDRStylesCollector::collectBmpf(unsigned patternId, unsigned width, unsigned height, const std::vector<unsigned char> &pattern) { m_ps.m_patterns[patternId] = CDRPattern(width, height, pattern); } void libcdr::CDRStylesCollector::collectColorProfile(const std::vector<unsigned char> &profile) { if (!profile.empty()) m_ps.setColorTransform(profile); } void libcdr::CDRStylesCollector::collectPaletteEntry(unsigned colorId, unsigned /* userId */, const libcdr::CDRColor &color) { m_ps.m_documentPalette[colorId] = color; } void libcdr::CDRStylesCollector::collectText(unsigned textId, unsigned styleId, const std::vector<unsigned char> &data, const std::vector<unsigned char> &charDescriptions, const std::map<unsigned, CDRCharacterStyle> &styleOverrides) { if (data.empty() || charDescriptions.empty()) return; unsigned char tmpCharDescription = 0; unsigned i = 0; unsigned j = 0; std::vector<unsigned char> tmpTextData; CDRCharacterStyle defaultCharStyle, tmpCharStyle; getRecursedStyle(defaultCharStyle, styleId); CDRTextLine line; for (i=0, j=0; i<charDescriptions.size() && j<data.size(); ++i) { tmpCharStyle = defaultCharStyle; std::map<unsigned, CDRCharacterStyle>::const_iterator iter = styleOverrides.find(tmpCharDescription & 0xfe); if (iter != styleOverrides.end()) tmpCharStyle.overrideCharacterStyle(iter->second); if (charDescriptions[i] != tmpCharDescription) { librevenge::RVNGString text; if (!tmpTextData.empty()) { if (tmpCharDescription & 0x01) appendCharacters(text, tmpTextData); else appendCharacters(text, tmpTextData, tmpCharStyle.m_charSet); } line.append(CDRText(text, tmpCharStyle)); tmpTextData.clear(); tmpCharDescription = charDescriptions[i]; } tmpTextData.push_back(data[j++]); if ((tmpCharDescription & 0x01) && (j < data.size())) tmpTextData.push_back(data[j++]); } if (!tmpTextData.empty()) { librevenge::RVNGString text; if (tmpCharDescription & 0x01) appendCharacters(text, tmpTextData); else appendCharacters(text, tmpTextData, tmpCharStyle.m_charSet); line.append(CDRText(text, tmpCharStyle)); CDR_DEBUG_MSG(("CDRStylesCollector::collectText - Text: %s\n", text.cstr())); } std::vector<CDRTextLine> &paragraphVector = m_ps.m_texts[textId]; paragraphVector.push_back(line); } void libcdr::CDRStylesCollector::collectStld(unsigned id, const CDRCharacterStyle &charStyle) { m_charStyles[id] = charStyle; } void libcdr::CDRStylesCollector::getRecursedStyle(CDRCharacterStyle &charStyle, unsigned styleId) { std::map<unsigned, CDRCharacterStyle>::const_iterator iter = m_charStyles.find(styleId); if (iter == m_charStyles.end()) return; std::stack<CDRCharacterStyle> styleStack; styleStack.push(iter->second); if (iter->second.m_parentId) { std::map<unsigned, CDRCharacterStyle>::const_iterator iter2 = m_charStyles.find(iter->second.m_parentId); while (iter2 != m_charStyles.end()) { styleStack.push(iter2->second); if (iter2->second.m_parentId) iter2 = m_charStyles.find(iter2->second.m_parentId); else iter2 = m_charStyles.end(); } } while (!styleStack.empty()) { charStyle.overrideCharacterStyle(styleStack.top()); styleStack.pop(); } } /* vim:set shiftwidth=2 softtabstop=2 expandtab: */ <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "label.h" #include <QtCore/QDebug> #include <qrutils/outFile.h> using namespace utils; bool Label::init(const QDomElement &element, int index, bool nodeLabel, int width, int height) { mX = initCoordinate(element.attribute("x"), width); mY = initCoordinate(element.attribute("y"), height); auto elem = element.parentNode(); auto check = elem.firstChildElement(); mCenter = element.attribute("center", "false"); mText = element.attribute("text"); mTextBinded = element.attribute("textBinded"); mPrefix = element.attribute("prefix"); mSuffix = element.attribute("suffix"); mReadOnly = element.attribute("readOnly", "false"); mRotation = element.attribute("rotation", "0").toDouble(); if (mTextBinded.contains("##")) { mReadOnly = "true"; } if (mTextBinded.contains('!')) { int cutPosition = mTextBinded.indexOf('!', 0); mLocation = mTextBinded.mid(0, cutPosition); mNameOfPropertyRole = mTextBinded.mid(cutPosition + 1); } mIndex = index; mBackground = element.attribute("background", nodeLabel && mTextBinded.isEmpty() ? "transparent" : "white"); mIsHard = element.attribute("hard", "false").toLower().trimmed() == "true"; mIsPlainText = element.attribute("isPlainText", "false").toLower().trimmed() == "true"; if ((mText.isEmpty() && mTextBinded.isEmpty()) || (mReadOnly != "true" && mReadOnly != "false")) { qWarning() << "ERROR: can't parse label"; return false; } return true; } Label *Label::clone() { Label *returnLabel = new Label(); returnLabel->mX = mX; returnLabel->mY = mY; returnLabel->mCenter = mCenter; returnLabel->mText = mText; returnLabel->mTextBinded = mTextBinded; returnLabel->mReadOnly = mReadOnly; returnLabel->mRotation = mRotation; returnLabel->mIndex = mIndex; returnLabel->mBackground = mBackground; returnLabel->mIsHard = mIsHard; returnLabel->mIsPlainText = mIsPlainText; return returnLabel; } void Label::setRoleName(const QString roleName) { mRoleName = roleName; } QString Label::labelName() const { return "label_" + QString("%1").arg(mIndex); } QString Label::location() const { return mLocation; } void Label::changeIndex(int i) { mIndex = i; } void Label::generateCodeForConstructor(OutFile &out) const { if (mText.isEmpty()) { if (mRoleName.isEmpty()) { // It is binded label, text for it will be fetched from repo. out() << QString("\t\t\tqReal::LabelProperties %1(%2, %3, %4, \"%5\", %6, %7);\n").arg(labelName() , QString::number(mIndex) , QString::number(mX.value()) , QString::number(mY.value()) , mTextBinded, mReadOnly , QString::number(mRotation)); } else { // It is binded label, with role logic. out() << QString("\t\t\tqReal::LabelProperties %1(%2, %3, %4, \"%5\",\"%6\",\"%7\", %8, %9);\n") .arg(labelName() , QString::number(mIndex) , QString::number(mX.value()) , QString::number(mY.value()) , mLocation, mRoleName //roleName , mNameOfPropertyRole , mReadOnly , QString::number(mRotation)); } } else { // It is a static label, text for it is fixed. out() << QString("\t\t\tqReal::LabelProperties %1(%2, %3, %4, QObject::tr(\"%5\"), %6);\n").arg(labelName() , QString::number(mIndex) , QString::number(mX.value()) , QString::number(mY.value()) , mText , QString::number(mRotation)); } out() << QString("\t\t\t%1.setBackground(Qt::%2);\n").arg(labelName(), mBackground); const QString scalingX = mX.isScalable() ? "true" : "false"; const QString scalingY = mY.isScalable() ? "true" : "false"; out() << QString("\t\t\t%1.setScalingX(%2);\n").arg(labelName(), scalingX); out() << QString("\t\t\t%1.setScalingY(%2);\n").arg(labelName(), scalingY); out() << QString("\t\t\t%1.setHard(%2);\n").arg(labelName(), mIsHard ? "true" : "false"); out() << QString("\t\t\t%1.setPlainTextMode(%2);\n").arg(labelName(), mIsPlainText ? "true" : "false"); if (!mPrefix.isEmpty()) { out() << QString("\t\t\t%1.setPrefix(QObject::tr(\"%2\"));\n").arg(labelName(), mPrefix); } if (!mSuffix.isEmpty()) { out() << QString("\t\t\t%1.setSuffix(QObject::tr(\"%2\"));\n").arg(labelName(), mSuffix); } out() << QString("\t\t\taddLabel(%1);\n").arg(labelName()); } <commit_msg>start commit<commit_after>/* Copyright 2007-2015 QReal Research Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "label.h" #include <QtCore/QDebug> #include <qrutils/outFile.h> using namespace utils; bool Label::init(const QDomElement &element, int index, bool nodeLabel, int width, int height) { mX = initCoordinate(element.attribute("x"), width); mY = initCoordinate(element.attribute("y"), height); auto elem = element.parentNode(); auto check = elem.firstChildElement(); mCenter = element.attribute("center", "false"); mText = element.attribute("text"); mTextBinded = element.attribute("textBinded"); mPrefix = element.attribute("prefix"); mSuffix = element.attribute("suffix"); mReadOnly = element.attribute("readOnly", "false"); mRotation = element.attribute("rotation", "0").toDouble(); if (mTextBinded.contains("##")) { mReadOnly = "true"; } if (mTextBinded.contains('!')) { int cutPosition = mTextBinded.indexOf('!', 0); mLocation = mTextBinded.mid(0, cutPosition); mNameOfPropertyRole = mTextBinded.mid(cutPosition + 1); } mIndex = index; mBackground = element.attribute("background", nodeLabel && mTextBinded.isEmpty() ? "transparent" : "white"); mIsHard = element.attribute("hard", "false").toLower().trimmed() == "true"; mIsPlainText = element.attribute("isPlainText", "false").toLower().trimmed() == "true"; if ((mText.isEmpty() && mTextBinded.isEmpty()) || (mReadOnly != "true" && mReadOnly != "false")) { qWarning() << "ERROR: can't parse label"; return false; } return true; } Label *Label::clone() { Label *returnLabel = new Label(); returnLabel->mX = mX; returnLabel->mY = mY; returnLabel->mCenter = mCenter; returnLabel->mText = mText; returnLabel->mTextBinded = mTextBinded; returnLabel->mReadOnly = mReadOnly; returnLabel->mRotation = mRotation; returnLabel->mIndex = mIndex; returnLabel->mBackground = mBackground; returnLabel->mIsHard = mIsHard; returnLabel->mIsPlainText = mIsPlainText; return returnLabel; } void Label::setRoleName(const QString roleName) { mRoleName = roleName; } QString Label::labelName() const { return "label_" + QString("%1").arg(mIndex); } QString Label::location() const { return mLocation; } void Label::changeIndex(int i) { mIndex = i; } void Label::generateCodeForConstructor(OutFile &out) const { if (mText.isEmpty()) { if (mRoleName.isEmpty()) { // It is binded label, text for it will be fetched from repo. out() << QString("\t\t\tqReal::LabelProperties %1(%2, %3, %4, \"%5\", %6, %7);\n").arg(labelName() , QString::number(mIndex) , QString::number(mX.value()) , QString::number(mY.value()) , mTextBinded, mReadOnly , QString::number(mRotation)); } else { // It is binded label, with role logic. out() << QString("\t\t\tqReal::LabelProperties %1(%2, %3, %4, \"%5\",\"%6\",\"%7\", %8, %9);\n") .arg(labelName() , QString::number(mIndex) , QString::number(mX.value()) , QString::number(mY.value()) , mLocation, mRoleName //roleName , mNameOfPropertyRole , mReadOnly , QString::number(mRotation)); } } else { // It is a static label, text for it is fixed. out() << QString("\t\t\tqReal::LabelProperties %1(%2, %3, %4, QObject::tr(\"%5\"), %6);\n").arg(labelName() , QString::number(mIndex) , QString::number(mX.value()) , QString::number(mY.value()) , mText , QString::number(mRotation)); } out() << QString("\t\t\t%1.setBackground(Qt::%2);\n").arg(labelName(), mBackground); const QString scalingX = mX.isScalable() ? "true" : "false"; const QString scalingY = mY.isScalable() ? "true" : "false"; out() << QString("\t\t\t%1.setScalingX(%2);\n").arg(labelName(), scalingX); out() << QString("\t\t\t%1.setScalingY(%2);\n").arg(labelName(), scalingY); out() << QString("\t\t\t%1.setHard(%2);\n").arg(labelName(), mIsHard ? "true" : "false"); out() << QString("\t\t\t%1.setPlainTextMode(%2);\n").arg(labelName(), mIsPlainText ? "true" : "false"); if (!mPrefix.isEmpty()) { out() << QString("\t\t\t%1.setPrefix(QObject::tr(\"%2\"));\n").arg(labelName(), mPrefix); } if (!mSuffix.isEmpty()) { out() << QString("\t\t\t%1.setSuffix(QObject::tr(\"%2\"));\n").arg(labelName(), mSuffix); } out() << QString("\t\t\taddLabel(%1);\n").arg(labelName()); } <|endoftext|>
<commit_before>/** \file add_authority_wikidata_ids.cc * \brief functionality to acquire wikidata id corresponding to their gnds * \author andreas-ub * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #include "StringUtil.h" #include "MARC.h" #include <iostream> #include <fstream> #include <regex> //Scenario 1: // use --create_mapping_file parameter <filepath> to generate the mapping file // of the downloaded dnb authoriy dump (must bei unzipped first) // Download from: https://data.dnb.de/opendata/authorities-person_lds.jsonld.gz // and unzip to e.g. authorities-person_lds_20210613.jsonld // output is stdout //Scenario 2: // use converted file from scenario 1 from cpp/data to create a map during // pipeline processing. The norm_data_input is extended by wikidata ids where possible // and saved to 024 field indicator1:7 where wikidata id is not yet present // file can be taken from /mnt/ZE020150/FID-Entwicklung/ub_tools (gnd_to_wiki.txt) [[noreturn]] void Usage() { ::Usage(" :\n" " invocation modes:\n" " 1.) norm_data_marc_input norm_data_marc_output mapping_txt_file\n" " 2.) --create_mapping_file dnb_input_unzipped_file mapping_txt_file\n"); } void ParseDataDnbFile(std::string input_filename, std::string output_filename) { std::ifstream input_file(input_filename); std::ofstream output_file(output_filename); if (input_file.is_open() and output_file.is_open()) { std::string line; std::string act_gnd; std::string act_name; std::string act_wikidata; std::string act_wikipedia; bool sameAs_reached(false); bool read_preferred_name(false); bool read_gnd_id(false); while (std::getline(input_file, line)) { if (line == "}, {") { if (not act_wikidata.empty() and not act_name.empty() and not act_wikipedia.empty()) { output_file << "Name: " << act_name << " GND: " << act_gnd << " Wikidata: " << act_wikidata << " Wikipedia: " << act_wikipedia << "\n"; } act_gnd = ""; act_name = ""; act_wikidata = ""; act_wikipedia = ""; sameAs_reached = false; read_gnd_id = true; } else if (read_preferred_name) { read_preferred_name = false; act_name = std::regex_replace(line, std::regex("(value|:|\"|@)"), ""); act_name = StringUtil::TrimWhite(act_name); } else if (StringUtil::Contains(line, "info/gnd/") and read_gnd_id) { read_gnd_id = false; std::size_t last_slash = line.find_last_of("/"); act_gnd = line.substr(last_slash + 1); act_gnd = std::regex_replace(act_gnd, std::regex("(\\s|,|\")"), ""); } else if (StringUtil::Contains(line, "www.wikidata.org/entity/") and sameAs_reached) { std::size_t last_slash = line.find_last_of("/"); act_wikidata = line.substr(last_slash + 1); act_wikidata = std::regex_replace(act_wikidata, std::regex("(\\s|,|\")"), ""); } else if (StringUtil::Contains(line, "wikipedia.org/wiki/") and StringUtil::Contains(line, "http") and sameAs_reached) { std::size_t first_http = line.find("http"); act_wikipedia = line.substr(first_http); act_wikipedia = std::regex_replace(act_wikipedia, std::regex("(\\s|,|\")"), ""); } else if (StringUtil::Contains(line, "owl#sameAs")) { sameAs_reached = true; } else if (StringUtil::Contains(line, "preferredNameForThePerson")) { read_preferred_name = true; } } input_file.close(); output_file.close(); } else LOG_ERROR("input or output files could not be opened"); } void ParseGndWikidataMappingFile(std::string filename, std::unordered_map<std::string, std::vector<std::string>> * const gnd_to_wikidataid_and_wikipedia_link) { std::ifstream file(filename); if (file.is_open()) { std::string line; std::string act_gnd; std::string act_wikidata; std::string act_wikipedia; while (std::getline(file, line)) { const std::string NAME = "Name:"; const std::string GND = "GND:"; const std::string WIKIDATA = "Wikidata:"; const std::string WIKIPEDIA = "Wikipedia:"; if (StringUtil::StartsWith(line, NAME) and StringUtil::Contains(line, GND) and StringUtil::Contains(line, WIKIDATA) and StringUtil::Contains(line, WIKIPEDIA)) { act_gnd = line.substr(line.find(GND) + GND.length()); act_gnd = act_gnd.substr(0, act_gnd.find(WIKIDATA)); act_wikidata = line.substr(line.find(WIKIDATA) + WIKIDATA.length()); act_wikidata = act_wikidata.substr(0, act_wikidata.find(WIKIPEDIA)); act_wikipedia = line.substr(line.find(WIKIPEDIA) + WIKIPEDIA.length()); std::vector<std::string> wiki_elements = { StringUtil::TrimWhite(act_wikidata), StringUtil::TrimWhite(act_wikipedia) }; gnd_to_wikidataid_and_wikipedia_link->emplace(StringUtil::TrimWhite(act_gnd), wiki_elements); } } file.close(); } else LOG_ERROR("input or output files could not be opened"); } int Main(int argc, char * argv[]) { if (argc != 4) Usage(); const std::string marc_input_filename_or_create_flag(argv[1]); const std::string marc_output_filename_or_dnb_input(argv[2]); const std::string mapping_txt_filename(argv[3]); if (marc_input_filename_or_create_flag == "--create_mapping_file") { //e.g. "/..../authorities-person_lds_20210613.jsonld" and /usr/local/ub_tools/cpp/data/gnd_to_wiki.txt ParseDataDnbFile(marc_output_filename_or_dnb_input, mapping_txt_filename); return EXIT_SUCCESS; } std::unordered_map<std::string, std::vector<std::string>> gnd_to_wikielements; ParseGndWikidataMappingFile(mapping_txt_filename, &gnd_to_wikielements); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename_or_create_flag)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename_or_dnb_input)); if (unlikely(marc_input_filename_or_create_flag == marc_output_filename_or_dnb_input)) LOG_ERROR("Norm data input file name equals output file name!"); while (MARC::Record record = marc_reader.get()->read()) { // 035|a (DE-588)118562215 std::string record_gnd; std::string wikidata_id; std::string wikipedia_link; std::vector<std::string> wiki_elements; MARC::GetGNDCode(record, &record_gnd); MARC::GetWikidataId(record, &wikidata_id); if (not wikidata_id.empty()) { marc_writer.get()->write(record); continue; } //record lookup if (not record_gnd.empty()) { auto gnd_to_wikielements_iter = gnd_to_wikielements.find(record_gnd); if (gnd_to_wikielements_iter != gnd_to_wikielements.end()) { wiki_elements = gnd_to_wikielements_iter->second; if (wiki_elements.size() > 0) wikidata_id = wiki_elements[0]; if (wiki_elements.size() > 1) wikipedia_link = wiki_elements[1]; } } if (not wikidata_id.empty()) record.insertField("024", { { 'a', wikidata_id }, { '2', "wikidata" }, { '9', "PipeLineGenerated" } }, /*indicator 1*/ '7'); if (not wikipedia_link.empty()) record.insertField("670", { { 'a', "Wikipedia" }, { 'u', wikipedia_link }, { '9', "PipeLineGenerated" } }); marc_writer.get()->write(record); } return EXIT_SUCCESS; } <commit_msg>bugfix wikidata id extraction<commit_after>/** \file add_authority_wikidata_ids.cc * \brief functionality to acquire wikidata id corresponding to their gnds * \author andreas-ub * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "util.h" #include "StringUtil.h" #include "MARC.h" #include <iostream> #include <fstream> #include <regex> //Scenario 1: // use --create_mapping_file parameter <filepath> to generate the mapping file // of the downloaded dnb authoriy dump (must bei unzipped first) // Download from: https://data.dnb.de/opendata/authorities-person_lds.jsonld.gz // and unzip to e.g. authorities-person_lds_20210613.jsonld // output is stdout //Scenario 2: // use converted file from scenario 1 from cpp/data to create a map during // pipeline processing. The norm_data_input is extended by wikidata ids where possible // and saved to 024 field indicator1:7 where wikidata id is not yet present // file can be taken from /mnt/ZE020150/FID-Entwicklung/ub_tools (gnd_to_wiki.txt) [[noreturn]] void Usage() { ::Usage(" :\n" " invocation modes:\n" " 1.) norm_data_marc_input norm_data_marc_output mapping_txt_file\n" " 2.) --create_mapping_file dnb_input_unzipped_file mapping_txt_file\n"); } void ParseDataDnbFile(std::string input_filename, std::string output_filename) { std::ifstream input_file(input_filename); std::ofstream output_file(output_filename); if (input_file.is_open() and output_file.is_open()) { std::string line; std::string act_gnd; std::string act_name; std::string act_wikidata; std::string act_wikipedia; bool sameAs_reached(false); bool read_preferred_name(false); bool read_gnd_id(false); while (std::getline(input_file, line)) { if (line == "}, {") { if (not act_gnd.empty() and not act_name.empty() and not act_wikidata.empty() ) { output_file << "Name: " << act_name << " GND: " << act_gnd << " Wikidata: " << act_wikidata << " Wikipedia: " << act_wikipedia << "\n"; } act_gnd = ""; act_name = ""; act_wikidata = ""; act_wikipedia = ""; sameAs_reached = false; read_gnd_id = true; } else if (read_preferred_name) { read_preferred_name = false; act_name = std::regex_replace(line, std::regex("(value|:|\"|@)"), ""); act_name = StringUtil::TrimWhite(act_name); } else if (StringUtil::Contains(line, "info/gnd/") and read_gnd_id) { read_gnd_id = false; std::size_t last_slash = line.find_last_of("/"); act_gnd = line.substr(last_slash + 1); act_gnd = std::regex_replace(act_gnd, std::regex("(\\s|,|\")"), ""); } else if (StringUtil::Contains(line, "www.wikidata.org/entity/") and sameAs_reached) { std::size_t last_slash = line.find_last_of("/"); act_wikidata = line.substr(last_slash + 1); act_wikidata = std::regex_replace(act_wikidata, std::regex("(\\s|,|\")"), ""); } else if (StringUtil::Contains(line, "wikipedia.org/wiki/") and StringUtil::Contains(line, "http") and sameAs_reached) { std::size_t first_http = line.find("http"); act_wikipedia = line.substr(first_http); act_wikipedia = std::regex_replace(act_wikipedia, std::regex("(\\s|,|\")"), ""); } else if (StringUtil::Contains(line, "owl#sameAs")) { sameAs_reached = true; } else if (StringUtil::Contains(line, "preferredNameForThePerson")) { read_preferred_name = true; } } input_file.close(); output_file.close(); } else LOG_ERROR("input or output files could not be opened"); } void ParseGndWikidataMappingFile(std::string filename, std::unordered_map<std::string, std::vector<std::string>> * const gnd_to_wikidataid_and_wikipedia_link) { std::ifstream file(filename); if (file.is_open()) { std::string line; std::string act_gnd; std::string act_wikidata; std::string act_wikipedia; while (std::getline(file, line)) { const std::string NAME = "Name:"; const std::string GND = "GND:"; const std::string WIKIDATA = "Wikidata:"; const std::string WIKIPEDIA = "Wikipedia:"; if (StringUtil::StartsWith(line, NAME) and StringUtil::Contains(line, GND) and StringUtil::Contains(line, WIKIDATA) and StringUtil::Contains(line, WIKIPEDIA)) { act_gnd = line.substr(line.find(GND) + GND.length()); act_gnd = act_gnd.substr(0, act_gnd.find(WIKIDATA)); act_wikidata = line.substr(line.find(WIKIDATA) + WIKIDATA.length()); act_wikidata = act_wikidata.substr(0, act_wikidata.find(WIKIPEDIA)); act_wikipedia = line.substr(line.find(WIKIPEDIA) + WIKIPEDIA.length()); std::vector<std::string> wiki_elements = { StringUtil::TrimWhite(act_wikidata), StringUtil::TrimWhite(act_wikipedia) }; gnd_to_wikidataid_and_wikipedia_link->emplace(StringUtil::TrimWhite(act_gnd), wiki_elements); } } file.close(); } else LOG_ERROR("input or output files could not be opened"); } int Main(int argc, char * argv[]) { if (argc != 4) Usage(); const std::string marc_input_filename_or_create_flag(argv[1]); const std::string marc_output_filename_or_dnb_input(argv[2]); const std::string mapping_txt_filename(argv[3]); if (marc_input_filename_or_create_flag == "--create_mapping_file") { //e.g. "/..../authorities-person_lds_20210613.jsonld" and /usr/local/ub_tools/cpp/data/gnd_to_wiki.txt ParseDataDnbFile(marc_output_filename_or_dnb_input, mapping_txt_filename); return EXIT_SUCCESS; } std::unordered_map<std::string, std::vector<std::string>> gnd_to_wikielements; ParseGndWikidataMappingFile(mapping_txt_filename, &gnd_to_wikielements); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(marc_input_filename_or_create_flag)); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(marc_output_filename_or_dnb_input)); if (unlikely(marc_input_filename_or_create_flag == marc_output_filename_or_dnb_input)) LOG_ERROR("Norm data input file name equals output file name!"); while (MARC::Record record = marc_reader.get()->read()) { // 035|a (DE-588)118562215 std::string record_gnd; std::string wikidata_id; std::string wikipedia_link; std::vector<std::string> wiki_elements; MARC::GetGNDCode(record, &record_gnd); MARC::GetWikidataId(record, &wikidata_id); if (not wikidata_id.empty()) { marc_writer.get()->write(record); continue; } //record lookup if (not record_gnd.empty()) { auto gnd_to_wikielements_iter = gnd_to_wikielements.find(record_gnd); if (gnd_to_wikielements_iter != gnd_to_wikielements.end()) { wiki_elements = gnd_to_wikielements_iter->second; if (wiki_elements.size() > 0) wikidata_id = wiki_elements[0]; if (wiki_elements.size() > 1) wikipedia_link = wiki_elements[1]; } } if (not wikidata_id.empty()) record.insertField("024", { { 'a', wikidata_id }, { '2', "wikidata" }, { '9', "PipeLineGenerated" } }, /*indicator 1*/ '7'); if (not wikipedia_link.empty()) record.insertField("670", { { 'a', "Wikipedia" }, { 'u', wikipedia_link }, { '9', "PipeLineGenerated" } }); marc_writer.get()->write(record); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** \file augment_canones_references.cc * \brief A tool for adding numerical canon law references to MARC-21 datasets. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2019-2020, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <unordered_map> #include <cstdlib> #include <strings.h> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "RangeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" namespace { enum Codex { CIC1917, CIC1983, CCEO }; Codex DetermineCodex(const std::string &subfield_codex, const std::string &subfield_year, const std::string &ppn) { if (::strcasecmp(subfield_codex.c_str(), "Codex canonum ecclesiarum orientalium") == 0) return CCEO; if (unlikely(subfield_year.empty())) LOG_ERROR("missing year for Codex Iuris Canonici! (PPN: " + ppn + ")"); if (subfield_year == "1917") return CIC1917; else if (subfield_year == "1983") return CIC1983; LOG_ERROR("bad year for Codex Iuris Canonici \"" + subfield_year + "\"! (PPN: " + ppn + ")"); } // To understand this code read https://github.com/ubtue/tuefind/wiki/Codices std::string FieldToCanonLawCode(const std::string &ppn, const Codex codex, const std::string &subfield_part) { unsigned range_start, range_end; if (subfield_part.empty()) { range_start = 0; range_end = 99999999; } else if (not RangeUtil::ParseCanonLawRanges(subfield_part, &range_start, &range_end)) LOG_ERROR("don't know how to parse codex parts \"" + subfield_part + "\"! (PPN: " + ppn + ")"); switch (codex) { case CIC1917: return StringUtil::ToString(100000000 + range_start) + "_" + StringUtil::ToString(100000000 + range_end); case CIC1983: return StringUtil::ToString(200000000 + range_start) + "_" + StringUtil::ToString(200000000 + range_end); case CCEO: return StringUtil::ToString(300000000 + range_start) + "_" + StringUtil::ToString(300000000 + range_end); default: LOG_ERROR("unknown codex: " + std::to_string(codex)); } } std::string CodexToPrefix(const Codex codex) { switch (codex) { case CIC1917: return "CIC17"; case CIC1983: return "CIC83"; case CCEO: return "CCEO"; default: LOG_ERROR("unknown codex: " + std::to_string(codex)); } } void LoadAuthorityData(MARC::Reader * const reader, std::unordered_map<std::string, std::string> * const authority_ppns_to_canon_law_codes_map) { const auto aliases_file(FileUtil::OpenOutputFileOrDie(UBTools::GetTuelibPath() + "canon_law_aliases.map")); unsigned total_count(0); while (auto record = reader->read()) { ++total_count; const auto _110_field(record.findTag("110")); if (_110_field == record.end() or ::strcasecmp(_110_field->getFirstSubfieldWithCode('a').c_str(), "Katholische Kirche") != 0) continue; const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t')); if (::strcasecmp(t_subfield.c_str(),"Codex Iuris Canonici") != 0 and ::strcasecmp(t_subfield.c_str(), "Codex canonum ecclesiarum orientalium") != 0) continue; const Codex codex(DetermineCodex(t_subfield, _110_field->getFirstSubfieldWithCode('f'), record.getControlNumber())); const auto canon_law_code(FieldToCanonLawCode(record.getControlNumber(), codex, _110_field->getFirstSubfieldWithCode('p'))); (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = canon_law_code; for (const auto &_140_field : record.getTagRange("410")) { const auto p_subfield(_140_field.getFirstSubfieldWithCode('p')); if (not p_subfield.empty()) (*aliases_file) << CodexToPrefix(codex) << ' ' << TextUtil::UTF8ToLower(p_subfield) << '=' << canon_law_code << '\n'; } } LOG_INFO("found " + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + " canon law records among " + std::to_string(total_count) + " authority records."); } void CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field, std::vector<std::string> * const authority_ppns) { for (const auto &field : record.getTagRange(linking_field)) { const MARC::Subfields subfields(field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-627)")) authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen("(DE-627)"))); } } } void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::unordered_map<std::string, std::string> &authority_ppns_to_canon_law_codes_map) { static const std::vector<std::string> CANONES_GND_LINKING_TAGS{ "689", "655", "610" }; unsigned total_count(0), augmented_count(0); std::map<std::string, unsigned> reference_counts; while (auto record = reader->read()) { ++total_count; std::vector<std::string> ranges_to_insert; for (const auto &linking_tag : CANONES_GND_LINKING_TAGS) { std::vector<std::string> authority_ppns; CollectAuthorityPPNs(record, linking_tag, &authority_ppns); if (not authority_ppns.empty()) { for (const auto &authority_ppn : authority_ppns) { const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn)); if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) { ranges_to_insert.emplace_back(ppn_and_canon_law_code->second); ++reference_counts[linking_tag]; } } } } if (ranges_to_insert.empty()) { // check if the codex data is embedded directly in the 689 field // apparently, 689$t is repeatable and the first instance (always?) appears to be 'Katholische Kirche' for (const auto &_689_field : record.getTagRange("689")) { if (_689_field.getFirstSubfieldWithCode('a') != "Katholische Kirche") continue; std::string subfield_codex, subfield_year, subfield_part; for (const auto &subfield : _689_field.getSubfields()) { if (subfield.code_ == 't' and subfield.value_ != "Katholische Kirche") subfield_codex = subfield.value_; else if (subfield.code_ == 'f') subfield_year = subfield.value_; else if (subfield.code_ == 'p') subfield_part = subfield.value_; } if (not subfield_codex.empty() and not subfield_year.empty() and not subfield_part.empty()) { const Codex codex(DetermineCodex(subfield_codex, subfield_year, record.getControlNumber())); ranges_to_insert.emplace_back(FieldToCanonLawCode(record.getControlNumber(), codex, subfield_part)); ++reference_counts["689*"]; } } } if (not ranges_to_insert.empty()) { record.insertField("CAL", { { 'a', StringUtil::Join(ranges_to_insert, ',') } }); ++augmented_count; } writer->write(record); } LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records."); LOG_INFO("found " + std::to_string(reference_counts["689"]) + " references in field 689"); LOG_INFO("found " + std::to_string(reference_counts["689*"]) + " direct references in field 689"); LOG_INFO("found " + std::to_string(reference_counts["655"]) + " references in field 655"); } } // unnamed namespace int Main(int argc, char **argv) { if (argc != 4) ::Usage("ixtheo_titles authority_records augmented_ixtheo_titles"); const std::string title_input_filename(argv[1]); const std::string authority_filename(argv[2]); const std::string title_output_filename(argv[3]); if (unlikely(title_input_filename == title_output_filename)) LOG_ERROR("Title input file name equals title output file name!"); if (unlikely(title_input_filename == authority_filename)) LOG_ERROR("Title input file name equals authority file name!"); if (unlikely(title_output_filename == authority_filename)) LOG_ERROR("Title output file name equals authority file name!"); auto authority_reader(MARC::Reader::Factory(authority_filename)); std::unordered_map<std::string, std::string> authority_ppns_to_canon_law_codes_map; LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map); auto title_reader(MARC::Reader::Factory(title_input_filename)); auto title_writer(MARC::Writer::Factory(title_output_filename)); ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map); return EXIT_SUCCESS; } <commit_msg>Don't abort when encountering canon law references which we don't know how to handle!<commit_after>/** \file augment_canones_references.cc * \brief A tool for adding numerical canon law references to MARC-21 datasets. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2019-2021, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <unordered_map> #include <cstdlib> #include <strings.h> #include "Compiler.h" #include "FileUtil.h" #include "MARC.h" #include "RangeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "UBTools.h" #include "util.h" namespace { enum Codex { CIC1917, CIC1983, CCEO }; Codex DetermineCodex(const std::string &subfield_codex, const std::string &subfield_year, const std::string &ppn) { if (::strcasecmp(subfield_codex.c_str(), "Codex canonum ecclesiarum orientalium") == 0) return CCEO; if (unlikely(subfield_year.empty())) LOG_ERROR("missing year for Codex Iuris Canonici! (PPN: " + ppn + ")"); if (subfield_year == "1917") return CIC1917; else if (subfield_year == "1983") return CIC1983; LOG_ERROR("bad year for Codex Iuris Canonici \"" + subfield_year + "\"! (PPN: " + ppn + ")"); } // To understand this code read https://github.com/ubtue/tuefind/wiki/Codices std::string FieldToCanonLawCode(const std::string &ppn, const Codex codex, const std::string &subfield_part) { unsigned range_start, range_end; if (subfield_part.empty()) { range_start = 0; range_end = 99999999; } else if (not RangeUtil::ParseCanonLawRanges(subfield_part, &range_start, &range_end)) { LOG_WARNING("don't know how to parse codex parts \"" + subfield_part + "\"! (PPN: " + ppn + ")"); return ""; } switch (codex) { case CIC1917: return StringUtil::ToString(100000000 + range_start) + "_" + StringUtil::ToString(100000000 + range_end); case CIC1983: return StringUtil::ToString(200000000 + range_start) + "_" + StringUtil::ToString(200000000 + range_end); case CCEO: return StringUtil::ToString(300000000 + range_start) + "_" + StringUtil::ToString(300000000 + range_end); default: LOG_ERROR("unknown codex: " + std::to_string(codex)); } } std::string CodexToPrefix(const Codex codex) { switch (codex) { case CIC1917: return "CIC17"; case CIC1983: return "CIC83"; case CCEO: return "CCEO"; default: LOG_ERROR("unknown codex: " + std::to_string(codex)); } } void LoadAuthorityData(MARC::Reader * const reader, std::unordered_map<std::string, std::string> * const authority_ppns_to_canon_law_codes_map) { const auto aliases_file(FileUtil::OpenOutputFileOrDie(UBTools::GetTuelibPath() + "canon_law_aliases.map")); unsigned total_count(0); while (auto record = reader->read()) { ++total_count; const auto _110_field(record.findTag("110")); if (_110_field == record.end() or ::strcasecmp(_110_field->getFirstSubfieldWithCode('a').c_str(), "Katholische Kirche") != 0) continue; const std::string t_subfield(_110_field->getFirstSubfieldWithCode('t')); if (::strcasecmp(t_subfield.c_str(),"Codex Iuris Canonici") != 0 and ::strcasecmp(t_subfield.c_str(), "Codex canonum ecclesiarum orientalium") != 0) continue; const Codex codex(DetermineCodex(t_subfield, _110_field->getFirstSubfieldWithCode('f'), record.getControlNumber())); const auto canon_law_code( FieldToCanonLawCode(record.getControlNumber(), codex, _110_field->getFirstSubfieldWithCode('p'))); if (unlikely(canon_law_code.empty())) continue; (*authority_ppns_to_canon_law_codes_map)[record.getControlNumber()] = canon_law_code; for (const auto &_140_field : record.getTagRange("410")) { const auto p_subfield(_140_field.getFirstSubfieldWithCode('p')); if (not p_subfield.empty()) (*aliases_file) << CodexToPrefix(codex) << ' ' << TextUtil::UTF8ToLower(p_subfield) << '=' << canon_law_code << '\n'; } } LOG_INFO("found " + std::to_string(authority_ppns_to_canon_law_codes_map->size()) + " canon law records among " + std::to_string(total_count) + " authority records."); } void CollectAuthorityPPNs(const MARC::Record &record, const MARC::Tag &linking_field, std::vector<std::string> * const authority_ppns) { for (const auto &field : record.getTagRange(linking_field)) { const MARC::Subfields subfields(field.getSubfields()); for (const auto &subfield : subfields) { if (subfield.code_ == '0' and StringUtil::StartsWith(subfield.value_, "(DE-627)")) authority_ppns->emplace_back(subfield.value_.substr(__builtin_strlen("(DE-627)"))); } } } void ProcessRecords(MARC::Reader * const reader, MARC::Writer * const writer, const std::unordered_map<std::string, std::string> &authority_ppns_to_canon_law_codes_map) { static const std::vector<std::string> CANONES_GND_LINKING_TAGS{ "689", "655", "610" }; unsigned total_count(0), augmented_count(0); std::map<std::string, unsigned> reference_counts; while (auto record = reader->read()) { ++total_count; std::vector<std::string> ranges_to_insert; for (const auto &linking_tag : CANONES_GND_LINKING_TAGS) { std::vector<std::string> authority_ppns; CollectAuthorityPPNs(record, linking_tag, &authority_ppns); if (not authority_ppns.empty()) { for (const auto &authority_ppn : authority_ppns) { const auto ppn_and_canon_law_code(authority_ppns_to_canon_law_codes_map.find(authority_ppn)); if (ppn_and_canon_law_code != authority_ppns_to_canon_law_codes_map.cend()) { ranges_to_insert.emplace_back(ppn_and_canon_law_code->second); ++reference_counts[linking_tag]; } } } } if (ranges_to_insert.empty()) { // check if the codex data is embedded directly in the 689 field // apparently, 689$t is repeatable and the first instance (always?) appears to be 'Katholische Kirche' for (const auto &_689_field : record.getTagRange("689")) { if (_689_field.getFirstSubfieldWithCode('a') != "Katholische Kirche") continue; std::string subfield_codex, subfield_year, subfield_part; for (const auto &subfield : _689_field.getSubfields()) { if (subfield.code_ == 't' and subfield.value_ != "Katholische Kirche") subfield_codex = subfield.value_; else if (subfield.code_ == 'f') subfield_year = subfield.value_; else if (subfield.code_ == 'p') subfield_part = subfield.value_; } if (not subfield_codex.empty() and not subfield_year.empty() and not subfield_part.empty()) { const Codex codex(DetermineCodex(subfield_codex, subfield_year, record.getControlNumber())); ranges_to_insert.emplace_back(FieldToCanonLawCode(record.getControlNumber(), codex, subfield_part)); ++reference_counts["689*"]; } } } if (not ranges_to_insert.empty()) { record.insertField("CAL", { { 'a', StringUtil::Join(ranges_to_insert, ',') } }); ++augmented_count; } writer->write(record); } LOG_INFO("augmented " + std::to_string(augmented_count) + " of " + std::to_string(total_count) + " records."); LOG_INFO("found " + std::to_string(reference_counts["689"]) + " references in field 689"); LOG_INFO("found " + std::to_string(reference_counts["689*"]) + " direct references in field 689"); LOG_INFO("found " + std::to_string(reference_counts["655"]) + " references in field 655"); } } // unnamed namespace int Main(int argc, char **argv) { if (argc != 4) ::Usage("ixtheo_titles authority_records augmented_ixtheo_titles"); const std::string title_input_filename(argv[1]); const std::string authority_filename(argv[2]); const std::string title_output_filename(argv[3]); if (unlikely(title_input_filename == title_output_filename)) LOG_ERROR("Title input file name equals title output file name!"); if (unlikely(title_input_filename == authority_filename)) LOG_ERROR("Title input file name equals authority file name!"); if (unlikely(title_output_filename == authority_filename)) LOG_ERROR("Title output file name equals authority file name!"); auto authority_reader(MARC::Reader::Factory(authority_filename)); std::unordered_map<std::string, std::string> authority_ppns_to_canon_law_codes_map; LoadAuthorityData(authority_reader.get(), &authority_ppns_to_canon_law_codes_map); auto title_reader(MARC::Reader::Factory(title_input_filename)); auto title_writer(MARC::Writer::Factory(title_output_filename)); ProcessRecords(title_reader.get(), title_writer.get(), authority_ppns_to_canon_law_codes_map); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: dataset.C,v 1.1.4.1 2007/03/25 21:56:35 oliver Exp $ // #include <BALL/VIEW/DATATYPE/dataset.h> #include <BALL/VIEW/WIDGETS/datasetControl.h> #include <BALL/VIEW/KERNEL/common.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/CONCEPT/molecularInformation.h> #include <QtGui/QFileDialog> #include <QtCore/QStringList> using namespace std; namespace BALL { namespace VIEW { Dataset::Dataset() : composite_(0) { } Dataset::Dataset(const Dataset& ds) : composite_(ds.composite_), name_(ds.name_), type_(ds.type_) { } Dataset::~Dataset() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<Dataset>() << endl; #endif } void Dataset::clear() { composite_ = 0; name_ = ""; type_ = ""; } void Dataset::set(const Dataset& ds) { composite_ = ds.composite_; name_ = ds.name_; type_ = ds.type_; } const Dataset& Dataset::operator = (const Dataset& v) { set(v); return *this; } void Dataset::dump(std::ostream& s, Size depth) const { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_STREAM_SUFFIX(s); } //////////////////////////////////////////////////////////////////////// // Controller: DatasetController::DatasetController() : QObject(), Embeddable("DatasetController"), type_("undefined type"), file_formats_(), control_(0) { registerThis(); } DatasetController::DatasetController(DatasetController& dc) : QObject(), Embeddable(dc), type_(dc.type_), file_formats_(dc.file_formats_), control_(dc.control_) { registerThis(); } DatasetController::~DatasetController() throw() { } bool DatasetController::write(Dataset* /*set*/, String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::write() should have been overloaded in derived class!" <<std::endl; return false; } Dataset* DatasetController::open(String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::open() should have been overloaded in derived class!" <<std::endl; return 0; } bool DatasetController::insertDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } QStringList sl; sl << set->getName().c_str(); if (set->getComposite() != 0) { MolecularInformation mi; mi.visit(*set->getComposite()); sl << mi.getName().c_str(); } else { sl << ""; } sl << set->getType().c_str(); QTreeWidgetItem* item = getDatasetControl()->addRow(sl); item_to_dataset_[item] = set; dataset_to_item_[set] = item; return true; } QMenu* DatasetController::buildContextMenu(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; QMenu* menu = new QMenu(control_); menu->addAction("Save as...", this, SLOT(write())); menu->addAction("Delete", this, SLOT(deleteDataset())); return menu; } vector<Dataset*> DatasetController::getDatasets() { vector<Dataset*> result; HashMap<Dataset*, QTreeWidgetItem*>::Iterator it = dataset_to_item_.begin(); for (; +it; ++it) { result.push_back((*it).first); } return result; } vector<Dataset*> DatasetController::getSelectedDatasets() { vector<Dataset*> result; if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return result; } DatasetControl::ItemList il = getDatasetControl()->getSelectedItems(); DatasetControl::ItemList::iterator it = il.begin(); for (; it != il.end(); it++) { if (item_to_dataset_.has(*it)) { result.push_back(item_to_dataset_[*it]); } } return result; } Dataset* DatasetController::getSelectedDataset() { vector<Dataset*> v = getSelectedDatasets(); if (v.size() != 1) return 0; if (getDatasetControl()->getSelectedItems().size() == 1) { return v[0]; } return 0; } bool DatasetController::deleteDatasets() { bool ok = true; vector<Dataset*> sets = getSelectedDatasets(); for (Position p = 0; p < sets.size(); p++) { Dataset* dp = sets[p]; if (dp == 0) { BALLVIEW_DEBUG return false; } ok &= deleteDataset(dp); } return ok; } bool DatasetController::deleteDataset() { Dataset* data = getSelectedDataset(); if (data == 0) return false; return deleteDataset(data); } bool DatasetController::deleteDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } if (!dataset_to_item_.has(set)) { return false; } QTreeWidgetItem* item = dataset_to_item_[set]; dataset_to_item_.erase(set); item_to_dataset_.erase(item); delete item; deleteDataset_(set); return true; } bool DatasetController::createMenuEntries() { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } QAction* action = getDatasetControl()->insertMenuEntry(MainControl::FILE_OPEN, type_, this, SLOT(open())); actions_for_one_set_.insert(action); return true; } String DatasetController::getFileTypes_() { String result(type_); result += " ("; for (Position p = 0; p < file_formats_.size(); p++) { result += "*."; result += file_formats_[p]; } result += ")"; return result; } bool DatasetController::write() { Dataset* set = getSelectedDataset(); if (set == 0) return 0; QString file = QFileDialog::getSaveFileName(0, QString("Save as ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } return write(set, fields[fields.size() - 1], ascii(file)); } bool DatasetController::open() { QString file = QFileDialog::getOpenFileName(0, QString("Open ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } Dataset* set = open(fields[fields.size() - 1], ascii(file)); if (set == 0) return false; return insertDataset(set); } QAction* DatasetController::insertMenuEntry_(Position pid, const String& name, const char* slot, QKeySequence accel) { if (getDatasetControl() == 0) return 0; QAction* action = getDatasetControl()->insertMenuEntry(pid, name, this, slot, accel); actions_.push_back(action); actions_for_one_set_.insert(action); return action; } String DatasetController::getNameFromFileName_(String filename) { Position pos = 0; for (Position p = 0; p < filename.size(); p++) { if (filename[p] == FileSystem::PATH_SEPARATOR) pos = p; } if (pos) pos++; return filename.getSubstring(pos); } void DatasetController::setStatusbarText(const String& text, bool important) { if (getDatasetControl() == 0) return; getDatasetControl()->setStatusbarText(text, important); } void DatasetController::checkMenu(MainControl& mc) { Size selected = getSelectedDatasets().size(); Size all_selected = getDatasetControl()->getSelectionSize(); bool other_selection = selected != all_selected; for (Position p = 0; p < actions_.size(); p++) { QAction& action = *actions_[p]; if (other_selection || mc.isBusy() || selected == 0) { action.setEnabled(false); continue; } if (selected > 1 && actions_for_one_set_.has(&action)) { action.setEnabled(false); continue; } action.setEnabled(true); } } bool DatasetController::handle(DatasetMessage* msg) { DatasetMessage::Type type = msg->getType(); if (type == DatasetMessage::ADD) { insertDataset(msg->getDataset()); return true; } if (type == DatasetMessage::REMOVE) { deleteDataset(msg->getDataset()); return true; } return false; } bool DatasetController::hasDataset(Dataset* set) { return dataset_to_item_.has(set); } bool DatasetController::hasItem(QTreeWidgetItem* item) { return item_to_dataset_.has(item); } Dataset* DatasetController::getDataset(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; return item_to_dataset_[item]; } } // namespace VIEW } // namespace BALL <commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // // $Id: dataset.C,v 1.1.4.2 2007/05/10 21:40:37 amoll Exp $ // #include <BALL/VIEW/DATATYPE/dataset.h> #include <BALL/VIEW/WIDGETS/datasetControl.h> #include <BALL/VIEW/KERNEL/common.h> #include <BALL/VIEW/KERNEL/mainControl.h> #include <BALL/VIEW/KERNEL/message.h> #include <BALL/CONCEPT/molecularInformation.h> #include <QtGui/QFileDialog> #include <QtCore/QStringList> using namespace std; namespace BALL { namespace VIEW { Dataset::Dataset() : composite_(0) { } Dataset::Dataset(const Dataset& ds) : composite_(ds.composite_), name_(ds.name_), type_(ds.type_) { } Dataset::~Dataset() { #ifdef BALL_VIEW_DEBUG cout << "Destructing object " << (void *)this << " of class " << RTTI::getName<Dataset>() << endl; #endif } void Dataset::clear() { composite_ = 0; name_ = ""; type_ = ""; } void Dataset::set(const Dataset& ds) { composite_ = ds.composite_; name_ = ds.name_; type_ = ds.type_; } const Dataset& Dataset::operator = (const Dataset& v) { set(v); return *this; } void Dataset::dump(std::ostream& s, Size depth) const { BALL_DUMP_STREAM_PREFIX(s); BALL_DUMP_DEPTH(s, depth); BALL_DUMP_HEADER(s, this, this); BALL_DUMP_STREAM_SUFFIX(s); } //////////////////////////////////////////////////////////////////////// // Controller: DatasetController::DatasetController() : QObject(), Embeddable("DatasetController"), type_("undefined type"), file_formats_(), control_(0) { registerThis(); } DatasetController::DatasetController(DatasetController& dc) : QObject(), Embeddable(dc), type_(dc.type_), file_formats_(dc.file_formats_), control_(dc.control_) { registerThis(); } DatasetController::~DatasetController() throw() { } bool DatasetController::write(Dataset* /*set*/, String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::write() should have been overloaded in derived class!" <<std::endl; return false; } Dataset* DatasetController::open(String /*filetype*/, String /*filename*/) { Log.error() << "DatasetController::open() should have been overloaded in derived class!" <<std::endl; return 0; } bool DatasetController::insertDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } QStringList sl; sl << set->getName().c_str(); if (set->getComposite() != 0) { MolecularInformation mi; mi.visit(*set->getComposite()); sl << mi.getName().c_str(); } else { sl << ""; } sl << set->getType().c_str(); QTreeWidgetItem* item = getDatasetControl()->addRow(sl); item_to_dataset_[item] = set; dataset_to_item_[set] = item; return true; } QMenu* DatasetController::buildContextMenu(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; QMenu* menu = new QMenu(control_); menu->addAction("Save as...", this, SLOT(write())); menu->addAction("Delete", this, SLOT(deleteDataset())); return menu; } vector<Dataset*> DatasetController::getDatasets() { vector<Dataset*> result; HashMap<Dataset*, QTreeWidgetItem*>::Iterator it = dataset_to_item_.begin(); for (; +it; ++it) { result.push_back((*it).first); } return result; } vector<Dataset*> DatasetController::getSelectedDatasets() { vector<Dataset*> result; if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return result; } DatasetControl::ItemList il = getDatasetControl()->getSelectedItems(); DatasetControl::ItemList::iterator it = il.begin(); for (; it != il.end(); it++) { if (item_to_dataset_.has(*it)) { result.push_back(item_to_dataset_[*it]); } } return result; } Dataset* DatasetController::getSelectedDataset() { vector<Dataset*> v = getSelectedDatasets(); if (v.size() != 1) return 0; if (getDatasetControl()->getSelectedItems().size() == 1) { return v[0]; } return 0; } bool DatasetController::deleteDatasets() { bool ok = true; vector<Dataset*> sets = getSelectedDatasets(); for (Position p = 0; p < sets.size(); p++) { Dataset* dp = sets[p]; if (dp == 0) { BALLVIEW_DEBUG return false; } ok &= deleteDataset(dp); } return ok; } bool DatasetController::deleteDataset() { bool ok = true; vector<Dataset*> v = getSelectedDatasets(); for (Position p = 0; p < v.size(); p++) { Dataset* set = v[p]; if (set == 0) return false; ok &= deleteDataset(set); } return ok; } bool DatasetController::deleteDataset(Dataset* set) { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } if (set == 0) { BALLVIEW_DEBUG return false; } if (!dataset_to_item_.has(set)) { return false; } QTreeWidgetItem* item = dataset_to_item_[set]; dataset_to_item_.erase(set); item_to_dataset_.erase(item); delete item; deleteDataset_(set); return true; } bool DatasetController::createMenuEntries() { if (getDatasetControl() == 0) { BALLVIEW_DEBUG Log.error() << "DatasetController not bound to Dataset!" << std::endl; return false; } QAction* action = getDatasetControl()->insertMenuEntry(MainControl::FILE_OPEN, type_, this, SLOT(open())); actions_for_one_set_.insert(action); return true; } String DatasetController::getFileTypes_() { String result(type_); result += " ("; for (Position p = 0; p < file_formats_.size(); p++) { result += "*."; result += file_formats_[p]; } result += ")"; return result; } bool DatasetController::write() { Dataset* set = getSelectedDataset(); if (set == 0) return 0; QString file = QFileDialog::getSaveFileName(0, QString("Save as ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } return write(set, fields[fields.size() - 1], ascii(file)); } bool DatasetController::open() { QString file = QFileDialog::getOpenFileName(0, QString("Open ") + type_.c_str(), getDatasetControl()->getWorkingDir().c_str(), getFileTypes_().c_str()); if (file == QString::null) return false; vector<String> fields; String s(ascii(file)); s.split(fields, "."); if (fields.size() == 0) { BALLVIEW_DEBUG return false; } Dataset* set = open(fields[fields.size() - 1], ascii(file)); if (set == 0) return false; return insertDataset(set); } QAction* DatasetController::insertMenuEntry_(Position pid, const String& name, const char* slot, QKeySequence accel) { if (getDatasetControl() == 0) return 0; QAction* action = getDatasetControl()->insertMenuEntry(pid, name, this, slot, accel); actions_.push_back(action); actions_for_one_set_.insert(action); return action; } String DatasetController::getNameFromFileName_(String filename) { Position pos = 0; for (Position p = 0; p < filename.size(); p++) { if (filename[p] == FileSystem::PATH_SEPARATOR) pos = p; } if (pos) pos++; return filename.getSubstring(pos); } void DatasetController::setStatusbarText(const String& text, bool important) { if (getDatasetControl() == 0) return; getDatasetControl()->setStatusbarText(text, important); } void DatasetController::checkMenu(MainControl& mc) { Size selected = getSelectedDatasets().size(); Size all_selected = getDatasetControl()->getSelectionSize(); bool other_selection = selected != all_selected; for (Position p = 0; p < actions_.size(); p++) { QAction& action = *actions_[p]; if (other_selection || mc.isBusy() || selected == 0) { action.setEnabled(false); continue; } if (selected > 1 && actions_for_one_set_.has(&action)) { action.setEnabled(false); continue; } action.setEnabled(true); } } bool DatasetController::handle(DatasetMessage* msg) { DatasetMessage::Type type = msg->getType(); if (type == DatasetMessage::ADD) { insertDataset(msg->getDataset()); return true; } if (type == DatasetMessage::REMOVE) { deleteDataset(msg->getDataset()); return true; } return false; } bool DatasetController::hasDataset(Dataset* set) { return dataset_to_item_.has(set); } bool DatasetController::hasItem(QTreeWidgetItem* item) { return item_to_dataset_.has(item); } Dataset* DatasetController::getDataset(QTreeWidgetItem* item) { if (!item_to_dataset_.has(item)) return 0; return item_to_dataset_[item]; } } // namespace VIEW } // namespace BALL <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lineaction.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-17 12:49:25 $ * * 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_cppcanvas.hxx" #include <lineaction.hxx> #include <outdevstate.hxx> #include <rtl/logfile.hxx> #include <com/sun/star/rendering/XCanvas.hpp> #include <tools/gen.hxx> #include <vcl/canvastools.hxx> #include <basegfx/range/b2drange.hxx> #include <basegfx/tools/canvastools.hxx> #include <canvas/canvastools.hxx> #include <boost/utility.hpp> #include <cppcanvas/canvas.hxx> #include <mtftools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace internal { namespace { class LineAction : public Action, private ::boost::noncopyable { public: LineAction( const ::Point&, const ::Point&, const CanvasSharedPtr&, const OutDevState& ); virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual sal_Int32 getActionCount() const; private: Point maStartPoint; Point maEndPoint; CanvasSharedPtr mpCanvas; rendering::RenderState maState; }; LineAction::LineAction( const ::Point& rStartPoint, const ::Point& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : maStartPoint( rStartPoint ), maEndPoint( rEndPoint ), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); maState.DeviceColor = rState.lineColor; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const { RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::LineAction::render()" ); RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::LineAction: 0x%X", this ); rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); mpCanvas->getUNOCanvas()->drawLine( ::vcl::unotools::point2DFromPoint(maStartPoint), ::vcl::unotools::point2DFromPoint(maEndPoint), mpCanvas->getViewState(), aLocalState ); return true; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, fail if subset // requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return false; return render( rTransformation ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const { rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); return tools::calcDevicePixelBounds( ::basegfx::B2DRange( maStartPoint.X(), maStartPoint.Y(), maEndPoint.X(), maEndPoint.Y() ), mpCanvas->getViewState(), aLocalState ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, empty bounds // if subset requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return ::basegfx::B2DRange(); return getBounds( rTransformation ); } sal_Int32 LineAction::getActionCount() const { return 1; } } ActionSharedPtr LineActionFactory::createLineAction( const ::Point& rStartPoint, const ::Point& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new LineAction( rStartPoint, rEndPoint, rCanvas, rState) ); } } } <commit_msg>INTEGRATION: CWS thbpp6 (1.9.14); FILE MERGED 2006/12/21 17:20:53 thb 1.9.14.1: #121806# Now keeping full precision of the mtf logic coordinates across mtf->XCanvas conversion<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: lineaction.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2007-01-22 11:49:54 $ * * 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_cppcanvas.hxx" #include <lineaction.hxx> #include <outdevstate.hxx> #include <rtl/logfile.hxx> #include <com/sun/star/rendering/XCanvas.hpp> #include <tools/gen.hxx> #include <vcl/canvastools.hxx> #include <basegfx/range/b2drange.hxx> #include <basegfx/point/b2dpoint.hxx> #include <basegfx/tools/canvastools.hxx> #include <canvas/canvastools.hxx> #include <boost/utility.hpp> #include <cppcanvas/canvas.hxx> #include <mtftools.hxx> using namespace ::com::sun::star; namespace cppcanvas { namespace internal { namespace { class LineAction : public Action, private ::boost::noncopyable { public: LineAction( const ::basegfx::B2DPoint&, const ::basegfx::B2DPoint&, const CanvasSharedPtr&, const OutDevState& ); virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual bool render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const; virtual ::basegfx::B2DRange getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const; virtual sal_Int32 getActionCount() const; private: ::basegfx::B2DPoint maStartPoint; ::basegfx::B2DPoint maEndPoint; CanvasSharedPtr mpCanvas; rendering::RenderState maState; }; LineAction::LineAction( const ::basegfx::B2DPoint& rStartPoint, const ::basegfx::B2DPoint& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) : maStartPoint( rStartPoint ), maEndPoint( rEndPoint ), mpCanvas( rCanvas ), maState() { tools::initRenderState(maState,rState); maState.DeviceColor = rState.lineColor; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation ) const { RTL_LOGFILE_CONTEXT( aLog, "::cppcanvas::internal::LineAction::render()" ); RTL_LOGFILE_CONTEXT_TRACE1( aLog, "::cppcanvas::internal::LineAction: 0x%X", this ); rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); mpCanvas->getUNOCanvas()->drawLine( ::basegfx::unotools::point2DFromB2DPoint(maStartPoint), ::basegfx::unotools::point2DFromB2DPoint(maEndPoint), mpCanvas->getViewState(), aLocalState ); return true; } bool LineAction::render( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, fail if subset // requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return false; return render( rTransformation ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation ) const { rendering::RenderState aLocalState( maState ); ::canvas::tools::prependToRenderState(aLocalState, rTransformation); return tools::calcDevicePixelBounds( ::basegfx::B2DRange( maStartPoint, maEndPoint ), mpCanvas->getViewState(), aLocalState ); } ::basegfx::B2DRange LineAction::getBounds( const ::basegfx::B2DHomMatrix& rTransformation, const Subset& rSubset ) const { // line only contains a single action, empty bounds // if subset requests different range if( rSubset.mnSubsetBegin != 0 || rSubset.mnSubsetEnd != 1 ) return ::basegfx::B2DRange(); return getBounds( rTransformation ); } sal_Int32 LineAction::getActionCount() const { return 1; } } ActionSharedPtr LineActionFactory::createLineAction( const ::basegfx::B2DPoint& rStartPoint, const ::basegfx::B2DPoint& rEndPoint, const CanvasSharedPtr& rCanvas, const OutDevState& rState ) { return ActionSharedPtr( new LineAction( rStartPoint, rEndPoint, rCanvas, rState) ); } } } <|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : scene/loader/xform.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "loader/xform.hpp" // includes, system #include <boost/intrusive_ptr.hpp> // boost::intrusive_ptr<> #include <boost/tokenizer.hpp> // boost::char_separator<>, boost::tokenizer<> // includes, project #include <scene/file.hpp> #include <scene/node/transform.hpp> #define UKACHULLDCS_USE_TRACE #undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal scene::node::transform* process_xform(std::string& a) { TRACE("scene::file::xform::<unnamed>::process_xform"); static boost::char_separator<char> const token_separator("."); using tokenizer = boost::tokenizer<boost::char_separator<char>>; tokenizer tokens(a, token_separator); using scene::node::transform; transform* result(new transform); // remove '.<float>,<float>,<float>,<float>.rot' // remove '.<float>,<float>,<float>.scale' // remove '.<float>,<float>,<float>,<float>.trans' // apply xform if ("rot" == *tokens.begin()) { } else if ("scale" == *tokens.begin()) { } else if ("trans" == *tokens.begin()) { } else { result->xform = glm::mat4(1); } return result; } } // namespace { namespace scene { namespace file { namespace xform { // variables, exported // functions, exported node::group* load(std::string const& a) { TRACE("scene::file::xform::load"); using scene::node::transform; std::string fname (a); transform* result(process_xform(fname)); result->children += handler::load(fname); return result; } bool save(std::string const& a, node::group* b) { TRACE("scene::file::xform::save"); using scene::node::transform; std::string fname (a); boost::intrusive_ptr<transform> result(process_xform(fname)); result->children += b; return handler::save(fname, result.get()); } } // namespace xform { } // namespace file { } // namespace scene { <commit_msg>preliminary version<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2015 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : scene/loader/xform.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "loader/xform.hpp" // includes, system #include <boost/intrusive_ptr.hpp> // boost::intrusive_ptr<> #include <cctype> // std::isdigit // includes, project #include <scene/file.hpp> #include <scene/node/transform.hpp> #include <support/io_utils.hpp> #define UKACHULLDCS_USE_TRACE //#undef UKACHULLDCS_USE_TRACE #include <support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal scene::node::transform* process_xform(std::string& a) { TRACE("scene::file::xform::<unnamed>::process_xform"); using size_type = std::string::size_type; using pos_list_type = std::vector<size_type>; using float_list_type = std::vector<float>; pos_list_type dots; pos_list_type commas; for (size_type i(0); i < a.size(); ++i) { if ('.' == a[i]) { dots .push_back(i); } else if (',' == a[i]) { commas.push_back(i); } } for (size_type i(commas.size()-1); i > 0; --i) { unsigned count(0); for (auto const& d : dots) { if ((d < commas[i]) && (d > commas[i-1])) { ++count; } } std::cout << support::trace::prefix() << commas[i] << ':' << commas[i-1] << ':' << count << '\n'; if (2 <= count) { count = 0; pos_list_type tmp; for (auto const& d : dots) { if (d > commas[i-1]) { ++count; if (2 <= count) { tmp.push_back(d); } } } std::swap(tmp, dots); } } pos_list_type ranges(commas); ranges.insert (ranges.begin(), *dots.begin()); ranges.push_back(*dots.rbegin()); for (size_type i(*commas.begin()); i > *dots.begin(); --i) { if (('.' == a[i]) && (std::isdigit(a[i+1]) || ('-' == a[i+1]) || ('+' == a[i+1])) && (!std::isdigit(a[i-1]) && ('-' != a[i-1]) && ('+' != a[i-1]))) { ranges[0] = i; } } float_list_type values; for (size_type i(0); i < ranges.size() - 1; ++i) { std::string const tmp(a, ranges[i]+1, ranges[i+1]-ranges[i]-1); float f(0.0f); if (1 == std::sscanf(tmp.c_str(), "%f", &f)) { values.push_back(f); } #if 0 std::cout << support::trace::prefix() << ranges[i] << ":'" << tmp << "' -> " << f << '\n'; #endif } using scene::node::transform; transform* result(new transform); std::string const suffix(a.substr(*dots.rbegin())); if (".rot" == suffix) { using support::ostream::operator<<; std::cout << support::trace::prefix() << "ROT: " << values << "\n"; } else if (".scale" == suffix) { using support::ostream::operator<<; std::cout << support::trace::prefix() << "SCALE: " << values << "\n"; } else if (".trans" == suffix) { using support::ostream::operator<<; std::cout << support::trace::prefix() << "TRANS: " << values << "\n"; } else { result->xform = glm::mat4(1); } std::string tmp = a.substr(0, *ranges.begin()); { using support::ostream::operator<<; std::cout << support::trace::prefix() << "'" << a << "' -> '" << tmp << "'" << "\n" << support::trace::prefix() << "d:" << dots << ", c:" << commas << ", r:" << ranges // << '\n' // << support::trace::prefix() << values << '\n'; } a = tmp; return result; } } // namespace { //dummy.suffix.1.0,2.0,3.0,4.0.rot namespace scene { namespace file { namespace xform { // variables, exported // functions, exported node::group* load(std::string const& a) { TRACE("scene::file::xform::load"); using scene::node::transform; std::string fname (a); transform* result(process_xform(fname)); result->children += handler::load(fname); return result; } bool save(std::string const& a, node::group* b) { TRACE("scene::file::xform::save"); using scene::node::transform; std::string fname (a); boost::intrusive_ptr<transform> result(process_xform(fname)); result->children += b; return handler::save(fname, result.get()); } } // namespace xform { } // namespace file { } // namespace scene { <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/peer/relay_peer.h" #include "base/endian_util.h" #include "base/location.h" #include "base/logging.h" #include "base/crypto/key_pair.h" #include "base/crypto/message_encryptor_openssl.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_asio.h" #include "base/net/network_channel.h" #include "base/strings/unicode.h" #include "proto/relay_peer.pb.h" #include <asio/connect.hpp> #include <asio/write.hpp> namespace base { RelayPeer::RelayPeer() : io_context_(MessageLoop::current()->pumpAsio()->ioContext()), socket_(io_context_), resolver_(io_context_) { // Nothing } RelayPeer::~RelayPeer() { delegate_ = nullptr; std::error_code ignored_code; socket_.cancel(ignored_code); socket_.close(ignored_code); } void RelayPeer::start(const proto::RelayCredentials& credentials, Delegate* delegate) { delegate_ = delegate; DCHECK(delegate_); message_ = authenticationMessage(credentials.key(), credentials.secret()); LOG(LS_INFO) << "Start resolving for " << credentials.host() << ":" << credentials.port(); resolver_.async_resolve(local8BitFromUtf16(utf16FromUtf8(credentials.host())), std::to_string(credentials.port()), [this](const std::error_code& error_code, const asio::ip::tcp::resolver::results_type& endpoints) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } LOG(LS_INFO) << "Start connecting..."; asio::async_connect(socket_, endpoints, [this](const std::error_code& error_code, const asio::ip::tcp::endpoint& /* endpoint */) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } LOG(LS_INFO) << "Connected"; onConnected(); }); }); } void RelayPeer::onConnected() { if (message_.empty()) { onErrorOccurred(FROM_HERE, std::error_code()); return; } message_size_ = base::EndianUtil::toBig(message_.size()); asio::async_write(socket_, asio::const_buffer(&message_size_, sizeof(message_size_)), [this](const std::error_code& error_code, size_t bytes_transferred) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } if (bytes_transferred != sizeof(message_size_)) { onErrorOccurred(FROM_HERE, std::error_code()); return; } asio::async_write(socket_, asio::const_buffer(message_.data(), message_.size()), [this](const std::error_code& error_code, size_t bytes_transferred) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } if (bytes_transferred != message_.size()) { onErrorOccurred(FROM_HERE, std::error_code()); return; } if (delegate_) { delegate_->onRelayConnectionReady( std::unique_ptr<NetworkChannel>(new NetworkChannel(std::move(socket_)))); } }); }); } void RelayPeer::onErrorOccurred(const Location& location, const std::error_code& error_code) { LOG(LS_ERROR) << "Failed to connect to relay server: " << utf16FromLocal8Bit(error_code.message()) << " (" << location.toString() << ")"; if (delegate_) delegate_->onRelayConnectionError(); } // static ByteArray RelayPeer::authenticationMessage(const proto::RelayKey& key, const std::string& secret) { if (key.type() != proto::RelayKey::TYPE_X25519) { LOG(LS_ERROR) << "Unsupported key type: " << key.type(); return ByteArray(); } if (key.encryption() != proto::RelayKey::ENCRYPTION_CHACHA20_POLY1305) { LOG(LS_ERROR) << "Unsupported encryption type: " << key.encryption(); return ByteArray(); } if (key.public_key().empty()) { LOG(LS_ERROR) << "Empty public key"; return ByteArray(); } if (key.iv().empty()) { LOG(LS_ERROR) << "Empty IV"; return ByteArray(); } if (secret.empty()) { LOG(LS_ERROR) << "Empty secret"; return ByteArray(); } KeyPair key_pair = KeyPair::create(KeyPair::Type::X25519); if (!key_pair.isValid()) { LOG(LS_ERROR) << "KeyPair::create failed"; return ByteArray(); } ByteArray session_key = key_pair.sessionKey(fromStdString(key.public_key())); if (session_key.empty()) { LOG(LS_ERROR) << "Failed to create session key"; return ByteArray(); } std::unique_ptr<MessageEncryptor> encryptor = MessageEncryptorOpenssl::createForChaCha20Poly1305(session_key, fromStdString(key.iv())); if (!encryptor) return ByteArray(); std::string encrypted_secret; encrypted_secret.resize(encryptor->encryptedDataSize(secret.size())); if (!encryptor->encrypt(secret.data(), secret.size(), encrypted_secret.data())) return ByteArray(); proto::PeerToRelay message; message.set_key_id(key.key_id()); message.set_public_key(base::toStdString(key_pair.publicKey())); message.set_data(std::move(encrypted_secret)); return serialize(message); } } // namespace base <commit_msg>Fix key calculation.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "base/peer/relay_peer.h" #include "base/endian_util.h" #include "base/location.h" #include "base/logging.h" #include "base/crypto/generic_hash.h" #include "base/crypto/key_pair.h" #include "base/crypto/message_encryptor_openssl.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_asio.h" #include "base/net/network_channel.h" #include "base/strings/unicode.h" #include "proto/relay_peer.pb.h" #include <asio/connect.hpp> #include <asio/write.hpp> namespace base { RelayPeer::RelayPeer() : io_context_(MessageLoop::current()->pumpAsio()->ioContext()), socket_(io_context_), resolver_(io_context_) { // Nothing } RelayPeer::~RelayPeer() { delegate_ = nullptr; std::error_code ignored_code; socket_.cancel(ignored_code); socket_.close(ignored_code); } void RelayPeer::start(const proto::RelayCredentials& credentials, Delegate* delegate) { delegate_ = delegate; DCHECK(delegate_); message_ = authenticationMessage(credentials.key(), credentials.secret()); LOG(LS_INFO) << "Start resolving for " << credentials.host() << ":" << credentials.port(); resolver_.async_resolve(local8BitFromUtf16(utf16FromUtf8(credentials.host())), std::to_string(credentials.port()), [this](const std::error_code& error_code, const asio::ip::tcp::resolver::results_type& endpoints) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } LOG(LS_INFO) << "Start connecting..."; asio::async_connect(socket_, endpoints, [this](const std::error_code& error_code, const asio::ip::tcp::endpoint& /* endpoint */) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } LOG(LS_INFO) << "Connected"; onConnected(); }); }); } void RelayPeer::onConnected() { if (message_.empty()) { onErrorOccurred(FROM_HERE, std::error_code()); return; } message_size_ = base::EndianUtil::toBig(message_.size()); asio::async_write(socket_, asio::const_buffer(&message_size_, sizeof(message_size_)), [this](const std::error_code& error_code, size_t bytes_transferred) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } if (bytes_transferred != sizeof(message_size_)) { onErrorOccurred(FROM_HERE, std::error_code()); return; } asio::async_write(socket_, asio::const_buffer(message_.data(), message_.size()), [this](const std::error_code& error_code, size_t bytes_transferred) { if (error_code) { if (error_code != asio::error::operation_aborted) onErrorOccurred(FROM_HERE, error_code); return; } if (bytes_transferred != message_.size()) { onErrorOccurred(FROM_HERE, std::error_code()); return; } if (delegate_) { delegate_->onRelayConnectionReady( std::unique_ptr<NetworkChannel>(new NetworkChannel(std::move(socket_)))); } }); }); } void RelayPeer::onErrorOccurred(const Location& location, const std::error_code& error_code) { LOG(LS_ERROR) << "Failed to connect to relay server: " << utf16FromLocal8Bit(error_code.message()) << " (" << location.toString() << ")"; if (delegate_) delegate_->onRelayConnectionError(); } // static ByteArray RelayPeer::authenticationMessage(const proto::RelayKey& key, const std::string& secret) { if (key.type() != proto::RelayKey::TYPE_X25519) { LOG(LS_ERROR) << "Unsupported key type: " << key.type(); return ByteArray(); } if (key.encryption() != proto::RelayKey::ENCRYPTION_CHACHA20_POLY1305) { LOG(LS_ERROR) << "Unsupported encryption type: " << key.encryption(); return ByteArray(); } if (key.public_key().empty()) { LOG(LS_ERROR) << "Empty public key"; return ByteArray(); } if (key.iv().empty()) { LOG(LS_ERROR) << "Empty IV"; return ByteArray(); } if (secret.empty()) { LOG(LS_ERROR) << "Empty secret"; return ByteArray(); } KeyPair key_pair = KeyPair::create(KeyPair::Type::X25519); if (!key_pair.isValid()) { LOG(LS_ERROR) << "KeyPair::create failed"; return ByteArray(); } ByteArray temp = key_pair.sessionKey(fromStdString(key.public_key())); if (temp.empty()) { LOG(LS_ERROR) << "Failed to create session key"; return ByteArray(); } ByteArray session_key = base::GenericHash::hash(base::GenericHash::Type::BLAKE2s256, temp); std::unique_ptr<MessageEncryptor> encryptor = MessageEncryptorOpenssl::createForChaCha20Poly1305(session_key, fromStdString(key.iv())); if (!encryptor) return ByteArray(); std::string encrypted_secret; encrypted_secret.resize(encryptor->encryptedDataSize(secret.size())); if (!encryptor->encrypt(secret.data(), secret.size(), encrypted_secret.data())) return ByteArray(); proto::PeerToRelay message; message.set_key_id(key.key_id()); message.set_public_key(base::toStdString(key_pair.publicKey())); message.set_data(std::move(encrypted_secret)); return serialize(message); } } // namespace base <|endoftext|>
<commit_before>/* *************************************** * Asylum3D @ 2014-12-24 *************************************** */ #include "../../asylum.hpp" /*****************************************************************************/ /* Effect */ /*****************************************************************************/ /* Asylum Namespace */ namespace asy { /****************************/ /* Wavefront Effect (Fixed) */ /****************************/ class crh3d9_ffct_wf_fixed : public IEffect { private: bool m_uselt; BOOL* m_onoff; DWORD m_count; int64u m_flags; D3DCOLOR* m_color; D3DLIGHT9* m_light; LPDIRECT3DDEVICE9 m_devcs; public: /* ===================================================================================================================== */ crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light, BOOL* onoff, DWORD count, int64u flags, const crh3d9_main* main) { m_onoff = onoff; m_count = count; m_flags = flags; m_light = light; m_color = ambient; m_devcs = main->get_main()->dev; m_uselt = (m_light != NULL && m_onoff != NULL) ? true : false; } /* ========================== */ virtual ~crh3d9_ffct_wf_fixed () { } public: /* =============== */ virtual void enter () { uint_t fvf = D3DFVF_XYZ; m_devcs->SetRenderState(D3DRS_COLORVERTEX, FALSE); m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL); m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL); if (m_flags & ATTR_TYPE_TRANS) { m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_devcs->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); m_devcs->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); m_devcs->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); } if (m_flags & ATTR_TYPE_NORMAL) { fvf |= D3DFVF_NORMAL; if (m_uselt) { m_devcs->SetRenderState(D3DRS_LIGHTING, TRUE); if (m_flags & ATTR_TYPE_SPECULAR) m_devcs->SetRenderState(D3DRS_SPECULARENABLE, TRUE); } } if (m_flags & ATTR_TYPE_TEXTURE) fvf |= D3DFVF_TEX1; m_devcs->SetFVF(fvf); } /* =============== */ virtual void leave () { m_devcs->SetRenderState(D3DRS_COLORVERTEX, TRUE); m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1); m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2); if (m_flags & ATTR_TYPE_TRANS) m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); if (m_flags & ATTR_TYPE_NORMAL) { if (m_uselt) { m_devcs->SetRenderState(D3DRS_LIGHTING, FALSE); if (m_flags & ATTR_TYPE_SPECULAR) m_devcs->SetRenderState(D3DRS_SPECULARENABLE, FALSE); } } } /* ================ */ virtual void update () { if (m_color != NULL) m_devcs->SetRenderState(D3DRS_AMBIENT, m_color[0]); if (m_uselt) { for (DWORD idx = 0; idx < m_count; idx++) { m_devcs->SetLight(idx, &m_light[idx]); m_devcs->LightEnable(idx, m_onoff[idx]); } } } }; } /* namespace */ /* ================================================================================ */ CR_API asy::IEffect* create_crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light, BOOL* onoff, DWORD count, int64u flags, const asy::crh3d9_main* main) { asy::crh3d9_ffct_wf_fixed* ffct; ffct = new asy::crh3d9_ffct_wf_fixed (ambient, light, onoff, count, flags, main); return ((asy::IEffect*)ffct); } /*****************************************************************************/ /* Attribute */ /*****************************************************************************/ /* Asylum Namespace */ namespace asy { /*******************************/ /* Wavefront Attribute (Fixed) */ /*******************************/ class crh3d9_attr_wf_fixed : public IAttrib { protected: D3DMATERIAL9 m_mtl; crh3d9_texr* m_map_kd; LPDIRECT3DDEVICE9 m_device; public: /* ======================================== */ crh3d9_attr_wf_fixed (const crh3d9_main* main) { m_device = main->get_main()->dev; } /* ========================== */ virtual ~crh3d9_attr_wf_fixed () { } public: /* ===================================================================== */ bool init_ff (const sWAVEFRONT_M* mtl, const map_acs<crh3d9_texr>* texpool) { if (mtl->map_kd != NULL) { m_map_kd = texpool->get(mtl->map_kd); if (m_map_kd == NULL) return (false); } else { m_map_kd = NULL; } m_mtl.Diffuse.r = mtl->kd.x; m_mtl.Diffuse.g = mtl->kd.y; m_mtl.Diffuse.b = mtl->kd.z; m_mtl.Diffuse.a = mtl->d; if (m_mtl.Diffuse.a < 0.0f) m_mtl.Diffuse.a = 0.0f; else if (m_mtl.Diffuse.a > 1.0f) m_mtl.Diffuse.a = 1.0f; m_mtl.Ambient.r = mtl->ka.x; m_mtl.Ambient.g = mtl->ka.y; m_mtl.Ambient.b = mtl->ka.z; m_mtl.Ambient.a = 0.0f; m_mtl.Specular.r = mtl->ks.x; m_mtl.Specular.g = mtl->ks.y; m_mtl.Specular.b = mtl->ks.z; m_mtl.Specular.a = 0.0f; m_mtl.Emissive.r = 0.0f; m_mtl.Emissive.g = 0.0f; m_mtl.Emissive.b = 0.0f; m_mtl.Emissive.a = 0.0f; m_mtl.Power = mtl->ns; m_type = ATTR_TYPE_NORMAL; if (m_mtl.Diffuse.a < 1.0f) m_type |= ATTR_TYPE_TRANS; if (m_map_kd != NULL) m_type |= ATTR_TYPE_TEXTURE; if (m_mtl.Specular.r <= 0.0f && m_mtl.Specular.g <= 0.0f && m_mtl.Specular.b <= 0.0f && m_mtl.Specular.a <= 0.0f) m_type |= ATTR_TYPE_SPECULAR; return (true); } /* ================ */ virtual void commit () { if (m_map_kd != NULL) m_map_kd->apply(0); else m_device->SetTexture(0, NULL); m_device->SetMaterial(&m_mtl); } }; } /* namespace */ /* ==================================================================== */ CR_API asy::IAttrib* create_crh3d9_attr_wf_fixed (const sWAVEFRONT_M* mtl, const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main) { asy::crh3d9_attr_wf_fixed* attr; attr = new asy::crh3d9_attr_wf_fixed (main); if (attr != NULL) { if (!attr->init_ff(mtl, texpool)) { delete attr; attr = NULL; } } return ((asy::IAttrib*)attr); } /*****************************************************************************/ /* Mesh */ /*****************************************************************************/ /* Asylum Namespace */ namespace asy { /**********************************/ /* Wavefront Mesh (Single Stream) */ /**********************************/ class crh3d9_mesh_wf_ss : public IMesh { private: sD3D9_MESH* m_mesh; sD3D9_MAIN* m_main; const sD3D9_CALL* m_call; LPDIRECT3DDEVICE9 m_devs; public: /* ===================================== */ crh3d9_mesh_wf_ss (const crh3d9_main* main) { m_mesh = NULL; m_main = main->get_main(); m_call = main->get_call(); m_devs = m_main->dev; } /* ======================= */ virtual ~crh3d9_mesh_wf_ss () { if (m_mesh != NULL) m_call->release_mesh(m_mesh); } public: /* =========================================== */ bool init2_ss (const sWAVEFRONT* obj, leng_t idx) { leng_t nv, ni, bpv; nv = wfront_gen_mesh2(NULL, NULL, NULL, 0, 0, 0, NULL, &ni, obj, idx); if (nv == 0) return (false); bpv = sizeof(vec3d_t); void_t* vb; void_t* ib; if (obj->p_f[0].idx[2] != 0) bpv += sizeof(vec3d_t); if (obj->p_f[0].idx[1] != 0) bpv += sizeof(vec2d_t); vb = mem_calloc(nv, bpv); if (vb == NULL) return (false); if (nv > 65536) ib = mem_calloc(ni, sizeof(int32u)); else ib = mem_calloc(ni, sizeof(int16u)); if (ib == NULL) { mem_free(vb); return (false); } uint_t fvf; vec3d_t* xyz; vec3d_t* nrm; vec2d_t* uvw; fvf = D3DFVF_XYZ; xyz = (vec3d_t*)vb; if (obj->p_f[0].idx[2] != 0) { fvf |= D3DFVF_NORMAL; nrm = xyz + 1; uvw = (vec2d_t*)(nrm + 1); } else { nrm = NULL; uvw = (vec2d_t*)(xyz + 1); } if (obj->p_f[0].idx[1] != 0) fvf |= D3DFVF_TEX1; else uvw = NULL; wfront_gen_mesh2(xyz, nrm, uvw, bpv, 0, 0, ib, NULL, obj, idx); m_mesh = m_call->create_mesh_vib(m_main, nv, bpv, ni, D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, fvf, vb, ib); mem_free(vb); mem_free(ib); if (m_mesh == NULL) return (false); return (true); } /* ================ */ virtual void commit () { m_devs->SetStreamSource(0, m_mesh->vbuf, 0, m_mesh->nbpv); m_devs->SetIndices(m_mesh->ibuf); m_devs->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_mesh->vnum, 0, m_mesh->ntri); } }; } /* namespace */ /* ========================================================================= */ CR_API asy::IMesh* create_crh3d9_mesh_wf_ss (const sWAVEFRONT* obj, leng_t idx, const asy::crh3d9_main* main) { asy::crh3d9_mesh_wf_ss* mesh; mesh = new asy::crh3d9_mesh_wf_ss (main); if (mesh != NULL) { if (!mesh->init2_ss(obj, idx)) { delete mesh; mesh = NULL; } } return ((asy::IMesh*)mesh); } /*****************************************************************************/ /* Object Base */ /*****************************************************************************/ /* =========================================================================== */ CR_API bool create_crh3d9_base_wf (asy::object_base* base, const sWAVEFRONT* obj, create_crh3d9_attr_wf_t fattr, create_crh3d9_mesh_wf_t fmesh, const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main) { asy::commit_batch cb; base->list.init(); for (leng_t idx = 0; idx < obj->n_m; idx++) { leng_t ii, cnt = 0, cmp = idx + 1; for (ii = 0; ii < obj->n_g; ii++) { if (obj->p_g[ii].attr < cmp) break; if (obj->p_g[ii].attr == cmp) cnt += 1; } if (cnt == 0) continue; cb.attr = fattr(&obj->p_m[idx], texpool, main); if (cb.attr == NULL) goto _failure1; cb.mesh = mem_talloc(cnt + 1, asy::IMesh*); if (cb.mesh == NULL) { delete cb.attr; goto _failure1; } for (cnt = 0, ii = 0; ii < obj->n_g; ii++) { if (obj->p_g[ii].attr < cmp) break; if (obj->p_g[ii].attr == cmp) { cb.mesh[cnt] = fmesh(obj, ii, main); if (cb.mesh[cnt] == NULL) goto _failure2; cnt += 1; } } cb.mesh[cnt] = NULL; if (base->list.append(&cb) == NULL) goto _failure2; } if (base->list.size() == 0) goto _failure1; bound_get_aabb(&base->aabb, obj->p_v, obj->n_v, sizeof(vec3d_t)); bound_get_ball(&base->ball, obj->p_v, obj->n_v, sizeof(vec3d_t)); return (true); _failure2: cb.free(); _failure1: base->free(); return (false); } <commit_msg>Asylum: 去除不需要保存的值<commit_after>/* *************************************** * Asylum3D @ 2014-12-24 *************************************** */ #include "../../asylum.hpp" /*****************************************************************************/ /* Effect */ /*****************************************************************************/ /* Asylum Namespace */ namespace asy { /****************************/ /* Wavefront Effect (Fixed) */ /****************************/ class crh3d9_ffct_wf_fixed : public IEffect { private: bool m_uselt; BOOL* m_onoff; DWORD m_count; int64u m_flags; D3DCOLOR* m_color; D3DLIGHT9* m_light; LPDIRECT3DDEVICE9 m_devcs; public: /* ===================================================================================================================== */ crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light, BOOL* onoff, DWORD count, int64u flags, const crh3d9_main* main) { m_onoff = onoff; m_count = count; m_flags = flags; m_light = light; m_color = ambient; m_devcs = main->get_main()->dev; m_uselt = (m_light != NULL && m_onoff != NULL) ? true : false; } /* ========================== */ virtual ~crh3d9_ffct_wf_fixed () { } public: /* =============== */ virtual void enter () { uint_t fvf = D3DFVF_XYZ; m_devcs->SetRenderState(D3DRS_COLORVERTEX, FALSE); m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL); m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL); if (m_flags & ATTR_TYPE_TRANS) { m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); m_devcs->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); m_devcs->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); m_devcs->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); } if (m_flags & ATTR_TYPE_NORMAL) { fvf |= D3DFVF_NORMAL; if (m_uselt) { m_devcs->SetRenderState(D3DRS_LIGHTING, TRUE); if (m_flags & ATTR_TYPE_SPECULAR) m_devcs->SetRenderState(D3DRS_SPECULARENABLE, TRUE); } } if (m_flags & ATTR_TYPE_TEXTURE) fvf |= D3DFVF_TEX1; m_devcs->SetFVF(fvf); } /* =============== */ virtual void leave () { m_devcs->SetRenderState(D3DRS_COLORVERTEX, TRUE); m_devcs->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1); m_devcs->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_COLOR2); if (m_flags & ATTR_TYPE_TRANS) m_devcs->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); if (m_flags & ATTR_TYPE_NORMAL) { if (m_uselt) { m_devcs->SetRenderState(D3DRS_LIGHTING, FALSE); if (m_flags & ATTR_TYPE_SPECULAR) m_devcs->SetRenderState(D3DRS_SPECULARENABLE, FALSE); } } } /* ================ */ virtual void update () { if (m_color != NULL) m_devcs->SetRenderState(D3DRS_AMBIENT, m_color[0]); if (m_uselt) { for (DWORD idx = 0; idx < m_count; idx++) { m_devcs->SetLight(idx, &m_light[idx]); m_devcs->LightEnable(idx, m_onoff[idx]); } } } }; } /* namespace */ /* ================================================================================ */ CR_API asy::IEffect* create_crh3d9_ffct_wf_fixed (D3DCOLOR* ambient, D3DLIGHT9* light, BOOL* onoff, DWORD count, int64u flags, const asy::crh3d9_main* main) { asy::crh3d9_ffct_wf_fixed* ffct; ffct = new asy::crh3d9_ffct_wf_fixed (ambient, light, onoff, count, flags, main); return ((asy::IEffect*)ffct); } /*****************************************************************************/ /* Attribute */ /*****************************************************************************/ /* Asylum Namespace */ namespace asy { /*******************************/ /* Wavefront Attribute (Fixed) */ /*******************************/ class crh3d9_attr_wf_fixed : public IAttrib { protected: D3DMATERIAL9 m_mtl; crh3d9_texr* m_map_kd; LPDIRECT3DDEVICE9 m_device; public: /* ======================================== */ crh3d9_attr_wf_fixed (const crh3d9_main* main) { m_device = main->get_main()->dev; } /* ========================== */ virtual ~crh3d9_attr_wf_fixed () { } public: /* ===================================================================== */ bool init_ff (const sWAVEFRONT_M* mtl, const map_acs<crh3d9_texr>* texpool) { if (mtl->map_kd != NULL) { m_map_kd = texpool->get(mtl->map_kd); if (m_map_kd == NULL) return (false); } else { m_map_kd = NULL; } m_mtl.Diffuse.r = mtl->kd.x; m_mtl.Diffuse.g = mtl->kd.y; m_mtl.Diffuse.b = mtl->kd.z; m_mtl.Diffuse.a = mtl->d; if (m_mtl.Diffuse.a < 0.0f) m_mtl.Diffuse.a = 0.0f; else if (m_mtl.Diffuse.a > 1.0f) m_mtl.Diffuse.a = 1.0f; m_mtl.Ambient.r = mtl->ka.x; m_mtl.Ambient.g = mtl->ka.y; m_mtl.Ambient.b = mtl->ka.z; m_mtl.Ambient.a = 0.0f; m_mtl.Specular.r = mtl->ks.x; m_mtl.Specular.g = mtl->ks.y; m_mtl.Specular.b = mtl->ks.z; m_mtl.Specular.a = 0.0f; m_mtl.Emissive.r = 0.0f; m_mtl.Emissive.g = 0.0f; m_mtl.Emissive.b = 0.0f; m_mtl.Emissive.a = 0.0f; m_mtl.Power = mtl->ns; m_type = ATTR_TYPE_NORMAL; if (m_mtl.Diffuse.a < 1.0f) m_type |= ATTR_TYPE_TRANS; if (m_map_kd != NULL) m_type |= ATTR_TYPE_TEXTURE; if (m_mtl.Specular.r <= 0.0f && m_mtl.Specular.g <= 0.0f && m_mtl.Specular.b <= 0.0f && m_mtl.Specular.a <= 0.0f) m_type |= ATTR_TYPE_SPECULAR; return (true); } /* ================ */ virtual void commit () { if (m_map_kd != NULL) m_map_kd->apply(0); else m_device->SetTexture(0, NULL); m_device->SetMaterial(&m_mtl); } }; } /* namespace */ /* ==================================================================== */ CR_API asy::IAttrib* create_crh3d9_attr_wf_fixed (const sWAVEFRONT_M* mtl, const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main) { asy::crh3d9_attr_wf_fixed* attr; attr = new asy::crh3d9_attr_wf_fixed (main); if (attr != NULL) { if (!attr->init_ff(mtl, texpool)) { delete attr; attr = NULL; } } return ((asy::IAttrib*)attr); } /*****************************************************************************/ /* Mesh */ /*****************************************************************************/ /* Asylum Namespace */ namespace asy { /**********************************/ /* Wavefront Mesh (Single Stream) */ /**********************************/ class crh3d9_mesh_wf_ss : public IMesh { private: sD3D9_MESH* m_mesh; const sD3D9_CALL* m_call; LPDIRECT3DDEVICE9 m_devs; public: /* ===================================== */ crh3d9_mesh_wf_ss (const crh3d9_main* main) { m_mesh = NULL; m_call = main->get_call(); m_devs = main->get_main()->dev; } /* ======================= */ virtual ~crh3d9_mesh_wf_ss () { if (m_mesh != NULL) m_call->release_mesh(m_mesh); } public: /* ==================================================================== */ bool init2_ss (const sWAVEFRONT* obj, leng_t idx, const crh3d9_main* main) { leng_t nv, ni, bpv; nv = wfront_gen_mesh2(NULL, NULL, NULL, 0, 0, 0, NULL, &ni, obj, idx); if (nv == 0) return (false); bpv = sizeof(vec3d_t); if (obj->p_f[0].idx[2] != 0) bpv += sizeof(vec3d_t); if (obj->p_f[0].idx[1] != 0) bpv += sizeof(vec2d_t); void_t* vb; void_t* ib; vb = mem_calloc(nv, bpv); if (vb == NULL) return (false); if (nv > 65536) ib = mem_calloc(ni, sizeof(int32u)); else ib = mem_calloc(ni, sizeof(int16u)); if (ib == NULL) { mem_free(vb); return (false); } uint_t fvf; vec3d_t* xyz; vec3d_t* nrm; vec2d_t* uvw; fvf = D3DFVF_XYZ; xyz = (vec3d_t*)vb; if (obj->p_f[0].idx[2] != 0) { fvf |= D3DFVF_NORMAL; nrm = xyz + 1; uvw = (vec2d_t*)(nrm + 1); } else { nrm = NULL; uvw = (vec2d_t*)(xyz + 1); } if (obj->p_f[0].idx[1] != 0) fvf |= D3DFVF_TEX1; else uvw = NULL; wfront_gen_mesh2(xyz, nrm, uvw, bpv, 0, 0, ib, NULL, obj, idx); m_mesh = m_call->create_mesh_vib(main->get_main(), nv, bpv, ni, D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, D3DPOOL_MANAGED, D3DUSAGE_WRITEONLY, fvf, vb, ib); mem_free(vb); mem_free(ib); if (m_mesh == NULL) return (false); return (true); } /* ================ */ virtual void commit () { m_devs->SetStreamSource(0, m_mesh->vbuf, 0, m_mesh->nbpv); m_devs->SetIndices(m_mesh->ibuf); m_devs->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, m_mesh->vnum, 0, m_mesh->ntri); } }; } /* namespace */ /* ========================================================================= */ CR_API asy::IMesh* create_crh3d9_mesh_wf_ss (const sWAVEFRONT* obj, leng_t idx, const asy::crh3d9_main* main) { asy::crh3d9_mesh_wf_ss* mesh; mesh = new asy::crh3d9_mesh_wf_ss (main); if (mesh != NULL) { if (!mesh->init2_ss(obj, idx, main)) { delete mesh; mesh = NULL; } } return ((asy::IMesh*)mesh); } /*****************************************************************************/ /* Object Base */ /*****************************************************************************/ /* =========================================================================== */ CR_API bool create_crh3d9_base_wf (asy::object_base* base, const sWAVEFRONT* obj, create_crh3d9_attr_wf_t fattr, create_crh3d9_mesh_wf_t fmesh, const asy::map_acs<asy::crh3d9_texr>* texpool, const asy::crh3d9_main* main) { asy::commit_batch cb; base->list.init(); for (leng_t idx = 0; idx < obj->n_m; idx++) { leng_t ii, cnt = 0, cmp = idx + 1; for (ii = 0; ii < obj->n_g; ii++) { if (obj->p_g[ii].attr < cmp) break; if (obj->p_g[ii].attr == cmp) cnt += 1; } if (cnt == 0) continue; cb.attr = fattr(&obj->p_m[idx], texpool, main); if (cb.attr == NULL) goto _failure1; cb.mesh = mem_talloc(cnt + 1, asy::IMesh*); if (cb.mesh == NULL) { delete cb.attr; goto _failure1; } for (cnt = 0, ii = 0; ii < obj->n_g; ii++) { if (obj->p_g[ii].attr < cmp) break; if (obj->p_g[ii].attr == cmp) { cb.mesh[cnt] = fmesh(obj, ii, main); if (cb.mesh[cnt] == NULL) goto _failure2; cnt += 1; } } cb.mesh[cnt] = NULL; if (base->list.append(&cb) == NULL) goto _failure2; } if (base->list.size() == 0) goto _failure1; bound_get_aabb(&base->aabb, obj->p_v, obj->n_v, sizeof(vec3d_t)); bound_get_ball(&base->ball, obj->p_v, obj->n_v, sizeof(vec3d_t)); return (true); _failure2: cb.free(); _failure1: base->free(); return (false); } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <vistk/pipeline/version.h> #include <vistk/version.h> #include <boost/python/class.hpp> #include <boost/python/def.hpp> #include <boost/python/module.hpp> /** * \file version.cxx * * \brief Python bindings for version. */ using namespace boost::python; class compile { public: typedef vistk::version::version_t version_t; static bool check(version_t major_, version_t minor_, version_t patch_); }; class runtime { }; BOOST_PYTHON_MODULE(version) { class_<compile>("compile" , "Compile-time version information." , no_init) .def_readonly("major", VISTK_VERSION_MAJOR) .def_readonly("minor", VISTK_VERSION_MINOR) .def_readonly("patch", VISTK_VERSION_PATCH) .def_readonly("version_string", VISTK_VERSION) .def_readonly("git_build", #ifdef VISTK_BUILT_FROM_GIT true #else false #endif ) .def_readonly("git_hash", VISTK_GIT_HASH) .def_readonly("git_hash_short", VISTK_GIT_HASH_SHORT) .def_readonly("git_dirty", VISTK_GIT_DIRTY) .def("check", &compile::check , (arg("major"), arg("minor"), arg("patch")) , "Check for a vistk of at least the given version.") .staticmethod("check") ; class_<runtime>("runtime" , "Runtime version information." , no_init) .def_readonly("major", vistk::version::major) .def_readonly("minor", vistk::version::minor) .def_readonly("patch", vistk::version::patch) .def_readonly("version_string", vistk::version::version_string) .def_readonly("git_build", vistk::version::git_build) .def_readonly("git_hash", vistk::version::git_hash) .def_readonly("git_hash_short", vistk::version::git_hash_short) .def_readonly("git_dirty", vistk::version::git_dirty) .def("check", &vistk::version::check , (arg("major"), arg("minor"), arg("patch")) , "Check for a vistk of at least the given version.") .staticmethod("check") ; } bool compile ::check(version_t major_, version_t minor_, version_t patch_) { // If any of the version components are 0, we get compare warnings. Turn // them off here. #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" #endif return VISTK_VERSION_CHECK(major_, minor_, patch_); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif } <commit_msg>Remove some extra whitespace<commit_after>/*ckwg +5 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <vistk/pipeline/version.h> #include <vistk/version.h> #include <boost/python/class.hpp> #include <boost/python/def.hpp> #include <boost/python/module.hpp> /** * \file version.cxx * * \brief Python bindings for version. */ using namespace boost::python; class compile { public: typedef vistk::version::version_t version_t; static bool check(version_t major_, version_t minor_, version_t patch_); }; class runtime { }; BOOST_PYTHON_MODULE(version) { class_<compile>("compile" , "Compile-time version information." , no_init) .def_readonly("major", VISTK_VERSION_MAJOR) .def_readonly("minor", VISTK_VERSION_MINOR) .def_readonly("patch", VISTK_VERSION_PATCH) .def_readonly("version_string", VISTK_VERSION) .def_readonly("git_build", #ifdef VISTK_BUILT_FROM_GIT true #else false #endif ) .def_readonly("git_hash", VISTK_GIT_HASH) .def_readonly("git_hash_short", VISTK_GIT_HASH_SHORT) .def_readonly("git_dirty", VISTK_GIT_DIRTY) .def("check", &compile::check , (arg("major"), arg("minor"), arg("patch")) , "Check for a vistk of at least the given version.") .staticmethod("check") ; class_<runtime>("runtime" , "Runtime version information." , no_init) .def_readonly("major", vistk::version::major) .def_readonly("minor", vistk::version::minor) .def_readonly("patch", vistk::version::patch) .def_readonly("version_string", vistk::version::version_string) .def_readonly("git_build", vistk::version::git_build) .def_readonly("git_hash", vistk::version::git_hash) .def_readonly("git_hash_short", vistk::version::git_hash_short) .def_readonly("git_dirty", vistk::version::git_dirty) .def("check", &vistk::version::check , (arg("major"), arg("minor"), arg("patch")) , "Check for a vistk of at least the given version.") .staticmethod("check") ; } bool compile ::check(version_t major_, version_t minor_, version_t patch_) { // If any of the version components are 0, we get compare warnings. Turn // them off here. #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wtype-limits" #endif return VISTK_VERSION_CHECK(major_, minor_, patch_); #ifdef __GNUC__ #pragma GCC diagnostic pop #endif } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks 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 <cmath> #include "oslops.h" #include "oslexec_pvt.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { class WestinBackscatterClosure : public BSDFClosure { Vec3 m_N; float m_roughness; float m_invroughness; public: CLOSURE_CTOR (WestinBackscatterClosure) : BSDFClosure(side, Labels::GLOSSY) { CLOSURE_FETCH_ARG (m_N, 1); CLOSURE_FETCH_ARG (m_roughness, 2); m_invroughness = m_roughness > 0 ? 1 / m_roughness : 0; } void print_on (std::ostream &out) const { out << "westin_backscatter ("; out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), "; out << m_roughness; out << ")"; } Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { // pdf is implicitly 0 (no indirect sampling) float cosNO = normal_sign * m_N.dot(omega_out); float cosNI = normal_sign * m_N.dot(omega_in); if (cosNO > 0 && cosNI > 0) { float cosine = omega_out.dot(omega_in); pdf = cosine > 0 ? (m_invroughness + 1) * powf(cosine, m_invroughness) : 0; pdf *= 0.5f * float(M_1_PI); return Color3 (pdf, pdf, pdf); } return Color3 (0, 0, 0); } Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { return Color3 (0, 0, 0); } ustring sample (const Vec3 &Ng, const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy, float randu, float randv, Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy, float &pdf, Color3 &eval) const { Vec3 Ngf, Nf; if (!faceforward (omega_out, Ng, m_N, Ngf, Nf)) return Labels::NONE; float cosNO = Nf.dot(omega_out); if (cosNO > 0) { domega_in_dx = domega_out_dx; domega_in_dy = domega_out_dy; Vec3 T, B; make_orthonormals (omega_out, T, B); float phi = 2 * (float) M_PI * randu; float cosTheta = powf(randv, 1 / (m_invroughness + 1)); float sinTheta2 = 1 - cosTheta * cosTheta; float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0; omega_in = (cosf(phi) * sinTheta) * T + (sinf(phi) * sinTheta) * B + ( cosTheta) * omega_out; if (Ngf.dot(omega_in) > 0) { // common terms for pdf and eval float cosNI = Nf.dot(omega_in); // make sure the direction we chose is still in the right hemisphere if (cosNI > 0) { pdf = 0.5f * (float) M_1_PI * powf(cosTheta, m_invroughness); pdf = (m_invroughness + 1) * pdf; eval.setValue(pdf, pdf, pdf); // Since there is some blur to this reflection, make the // derivatives a bit bigger. In theory this varies with the // exponent but the exact relationship is complex and // requires more ops than are practical. domega_in_dx *= 10; domega_in_dy *= 10; } } } return Labels::REFLECT; } }; class WestinSheenClosure : public BSDFClosure { Vec3 m_N; float m_edginess; // float m_normalization; public: CLOSURE_CTOR (WestinSheenClosure) : BSDFClosure(side, Labels::DIFFUSE) { CLOSURE_FETCH_ARG (m_N, 1); CLOSURE_FETCH_ARG (m_edginess, 2); } void print_on (std::ostream &out) const { out << "westin_sheen ("; out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), "; out << m_edginess; out << ")"; } Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { // pdf is implicitly 0 (no indirect sampling) float cosNO = normal_sign * m_N.dot(omega_out); float cosNI = normal_sign * m_N.dot(omega_in); if (cosNO > 0 && cosNI > 0) { float sinNO2 = 1 - cosNO * cosNO; float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * cosNI * float(M_1_PI) : 0; return Color3 (westin, westin, westin); } return Color3 (0, 0, 0); } Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { return Color3 (0, 0, 0); } ustring sample (const Vec3 &Ng, const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy, float randu, float randv, Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy, float &pdf, Color3 &eval) const { Vec3 Ngf, Nf; if (faceforward (omega_out, Ng, m_N, Ngf, Nf)) { // we are viewing the surface from the right side - send a ray out with cosine // distribution over the hemisphere sample_cos_hemisphere (Nf, omega_out, randu, randv, omega_in, pdf); if (Ngf.dot(omega_in) > 0) { // TODO: account for sheen when sampling float cosNO = float(M_PI) * pdf; float sinNO2 = 1 - cosNO * cosNO; float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * pdf : 0; eval.setValue(westin, westin, westin); // TODO: find a better approximation for the diffuse bounce domega_in_dx = (2 * Nf.dot(domega_out_dx)) * Nf - domega_out_dx; domega_in_dy = (2 * Nf.dot(domega_out_dy)) * Nf - domega_out_dy; domega_in_dx *= 125; domega_in_dy *= 125; } else pdf = 0; } return Labels::REFLECT; } }; DECLOP (OP_westin_backscatter) { closure_op_guts<WestinBackscatterClosure, 3> (exec, nargs, args, runflags, beginpoint, endpoint); } DECLOP (OP_westin_sheen) { closure_op_guts<WestinSheenClosure, 3> (exec, nargs, args, runflags, beginpoint, endpoint); } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif <commit_msg>Fixed pdf's for westin closures<commit_after>/* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al. 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 Sony Pictures Imageworks 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 <cmath> #include "oslops.h" #include "oslexec_pvt.h" #ifdef OSL_NAMESPACE namespace OSL_NAMESPACE { #endif namespace OSL { namespace pvt { class WestinBackscatterClosure : public BSDFClosure { Vec3 m_N; float m_roughness; float m_invroughness; public: CLOSURE_CTOR (WestinBackscatterClosure) : BSDFClosure(side, Labels::GLOSSY) { CLOSURE_FETCH_ARG (m_N, 1); CLOSURE_FETCH_ARG (m_roughness, 2); m_invroughness = m_roughness > 0 ? 1 / m_roughness : 0; } void print_on (std::ostream &out) const { out << "westin_backscatter ("; out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), "; out << m_roughness; out << ")"; } Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { // pdf is implicitly 0 (no indirect sampling) float cosNO = normal_sign * m_N.dot(omega_out); float cosNI = normal_sign * m_N.dot(omega_in); if (cosNO > 0 && cosNI > 0) { float cosine = omega_out.dot(omega_in); pdf = cosine > 0 ? (m_invroughness + 1) * powf(cosine, m_invroughness) : 0; pdf *= 0.5f * float(M_1_PI); return Color3 (pdf, pdf, pdf); } return Color3 (0, 0, 0); } Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { return Color3 (0, 0, 0); } ustring sample (const Vec3 &Ng, const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy, float randu, float randv, Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy, float &pdf, Color3 &eval) const { Vec3 Ngf, Nf; if (!faceforward (omega_out, Ng, m_N, Ngf, Nf)) return Labels::NONE; float cosNO = Nf.dot(omega_out); if (cosNO > 0) { domega_in_dx = domega_out_dx; domega_in_dy = domega_out_dy; Vec3 T, B; make_orthonormals (omega_out, T, B); float phi = 2 * (float) M_PI * randu; float cosTheta = powf(randv, 1 / (m_invroughness + 1)); float sinTheta2 = 1 - cosTheta * cosTheta; float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0; omega_in = (cosf(phi) * sinTheta) * T + (sinf(phi) * sinTheta) * B + ( cosTheta) * omega_out; if (Ngf.dot(omega_in) > 0) { // common terms for pdf and eval float cosNI = Nf.dot(omega_in); // make sure the direction we chose is still in the right hemisphere if (cosNI > 0) { pdf = 0.5f * (float) M_1_PI * powf(cosTheta, m_invroughness); pdf = (m_invroughness + 1) * pdf; eval.setValue(pdf, pdf, pdf); // Since there is some blur to this reflection, make the // derivatives a bit bigger. In theory this varies with the // exponent but the exact relationship is complex and // requires more ops than are practical. domega_in_dx *= 10; domega_in_dy *= 10; } } } return Labels::REFLECT; } }; class WestinSheenClosure : public BSDFClosure { Vec3 m_N; float m_edginess; // float m_normalization; public: CLOSURE_CTOR (WestinSheenClosure) : BSDFClosure(side, Labels::DIFFUSE) { CLOSURE_FETCH_ARG (m_N, 1); CLOSURE_FETCH_ARG (m_edginess, 2); } void print_on (std::ostream &out) const { out << "westin_sheen ("; out << "(" << m_N[0] << ", " << m_N[1] << ", " << m_N[2] << "), "; out << m_edginess; out << ")"; } Color3 eval_reflect (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { // pdf is implicitly 0 (no indirect sampling) float cosNO = normal_sign * m_N.dot(omega_out); float cosNI = normal_sign * m_N.dot(omega_in); if (cosNO > 0 && cosNI > 0) { float sinNO2 = 1 - cosNO * cosNO; pdf = cosNI * float(M_1_PI); float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * pdf : 0; return Color3 (westin, westin, westin); } return Color3 (0, 0, 0); } Color3 eval_transmit (const Vec3 &omega_out, const Vec3 &omega_in, float normal_sign, float &pdf) const { return Color3 (0, 0, 0); } ustring sample (const Vec3 &Ng, const Vec3 &omega_out, const Vec3 &domega_out_dx, const Vec3 &domega_out_dy, float randu, float randv, Vec3 &omega_in, Vec3 &domega_in_dx, Vec3 &domega_in_dy, float &pdf, Color3 &eval) const { Vec3 Ngf, Nf; if (faceforward (omega_out, Ng, m_N, Ngf, Nf)) { // we are viewing the surface from the right side - send a ray out with cosine // distribution over the hemisphere sample_cos_hemisphere (Nf, omega_out, randu, randv, omega_in, pdf); if (Ngf.dot(omega_in) > 0) { // TODO: account for sheen when sampling float cosNO = Nf.dot(omega_out); float sinNO2 = 1 - cosNO * cosNO; float westin = sinNO2 > 0 ? powf(sinNO2, 0.5f * m_edginess) * pdf : 0; eval.setValue(westin, westin, westin); // TODO: find a better approximation for the diffuse bounce domega_in_dx = (2 * Nf.dot(domega_out_dx)) * Nf - domega_out_dx; domega_in_dy = (2 * Nf.dot(domega_out_dy)) * Nf - domega_out_dy; domega_in_dx *= 125; domega_in_dy *= 125; } else pdf = 0; } return Labels::REFLECT; } }; DECLOP (OP_westin_backscatter) { closure_op_guts<WestinBackscatterClosure, 3> (exec, nargs, args, runflags, beginpoint, endpoint); } DECLOP (OP_westin_sheen) { closure_op_guts<WestinSheenClosure, 3> (exec, nargs, args, runflags, beginpoint, endpoint); } }; // namespace pvt }; // namespace OSL #ifdef OSL_NAMESPACE }; // end namespace OSL_NAMESPACE #endif <|endoftext|>
<commit_before>#include "cauchy.h" #include "util.hpp" namespace nano { function_cauchy_t::function_cauchy_t(const tensor_size_t dims) : m_dims(dims) { } std::string function_cauchy_t::name() const { return "Cauchy" + std::to_string(m_dims) + "D"; } problem_t function_cauchy_t::problem() const { const auto fn_size = [=] () { return m_dims; }; const auto fn_fval = [=] (const vector_t& x) { return (1.0 + x.array().square()).log().sum(); }; const auto fn_grad = [=] (const vector_t& x, vector_t& gx) { gx = (2 * x.array()) / (1 + x.array().square()); return fn_fval(x); }; return {fn_size, fn_fval, fn_grad}; } bool function_cauchy_t::is_valid(const vector_t& x) const { return util::norm(x) < scalar_t(1); } bool function_cauchy_t::is_minima(const vector_t& x, const scalar_t epsilon) const { return util::distance(x, vector_t::Zero(m_dims)) < epsilon; } bool function_cauchy_t::is_convex() const { return true; // in the [-1, +1] interval } tensor_size_t function_cauchy_t::min_dims() const { return 1; } tensor_size_t function_cauchy_t::max_dims() const { return 100 * 1000; } } <commit_msg>faster Cauchy test function<commit_after>#include "cauchy.h" #include "util.hpp" namespace nano { function_cauchy_t::function_cauchy_t(const tensor_size_t dims) : m_dims(dims) { } std::string function_cauchy_t::name() const { return "Cauchy" + std::to_string(m_dims) + "D"; } problem_t function_cauchy_t::problem() const { const auto fn_size = [=] () { return m_dims; }; const auto fn_fval = [=] (const vector_t& x) { return std::log((1.0 + x.array().square()).prod());//.log().sum(); }; const auto fn_grad = [=] (const vector_t& x, vector_t& gx) { gx = (2 * x.array()) / (1 + x.array().square()); return fn_fval(x); }; return {fn_size, fn_fval, fn_grad}; } bool function_cauchy_t::is_valid(const vector_t& x) const { return util::norm(x) < scalar_t(1); } bool function_cauchy_t::is_minima(const vector_t& x, const scalar_t epsilon) const { return util::distance(x, vector_t::Zero(m_dims)) < epsilon; } bool function_cauchy_t::is_convex() const { return true; // in the [-1, +1] interval } tensor_size_t function_cauchy_t::min_dims() const { return 1; } tensor_size_t function_cauchy_t::max_dims() const { return 100 * 1000; } } <|endoftext|>
<commit_before>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include "qwt_series_data.h" #include "qwt_math.h" static inline QRectF qwtBoundingRect( const QPointF &sample ) { return QRectF( sample.x(), sample.y(), 0.0, 0.0 ); } static inline QRectF qwtBoundingRect( const QwtPoint3D &sample ) { return QRectF( sample.x(), sample.y(), 0.0, 0.0 ); } static inline QRectF qwtBoundingRect( const QwtPointPolar &sample ) { return QRectF( sample.azimuth(), sample.radius(), 0.0, 0.0 ); } static inline QRectF qwtBoundingRect( const QwtIntervalSample &sample ) { return QRectF( sample.interval.minValue(), sample.value, sample.interval.maxValue() - sample.interval.minValue(), 0.0 ); } static inline QRectF qwtBoundingRect( const QwtSetSample &sample ) { double minX = sample.set[0]; double maxX = sample.set[0]; for ( int i = 1; i < sample.set.size(); i++ ) { if ( sample.set[i] < minX ) minX = sample.set[i]; if ( sample.set[i] > maxX ) maxX = sample.set[i]; } double minY = sample.value; double maxY = sample.value; return QRectF( minX, minY, maxX - minX, maxY - minY ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ template <class T> QRectF qwtBoundingRectT( const QwtSeriesData<T>& series, int from, int to ) { QRectF boundingRect( 1.0, 1.0, -2.0, -2.0 ); // invalid; if ( from < 0 ) from = 0; if ( to < 0 ) to = series.size() - 1; if ( to < from ) return boundingRect; int i; for ( i = from; i <= to; i++ ) { const QRectF rect = qwtBoundingRect( series.sample( i ) ); if ( rect.width() >= 0.0 && rect.height() >= 0.0 ) { boundingRect = rect; i++; break; } } for ( ; i <= to; i++ ) { const QRectF rect = qwtBoundingRect( series.sample( i ) ); if ( rect.width() >= 0.0 && rect.height() >= 0.0 ) { boundingRect.setLeft( qMin( boundingRect.left(), rect.left() ) ); boundingRect.setRight( qMax( boundingRect.right(), rect.right() ) ); boundingRect.setTop( qMin( boundingRect.top(), rect.top() ) ); boundingRect.setBottom( qMax( boundingRect.bottom(), rect.bottom() ) ); } } return boundingRect; } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QPointF> &series, int from, int to ) { return qwtBoundingRectT<QPointF>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtPoint3D> &series, int from, int to ) { return qwtBoundingRectT<QwtPoint3D>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset The horizontal coordinates represent the azimuth, the vertical coordinates the radius. Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtPointPolar> &series, int from, int to ) { return qwtBoundingRectT<QwtPointPolar>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtIntervalSample>& series, int from, int to ) { return qwtBoundingRectT<QwtIntervalSample>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtSetSample>& series, int from, int to ) { return qwtBoundingRectT<QwtSetSample>( series, from, to ); } /*! Constructor \param samples Samples */ QwtPointSeriesData::QwtPointSeriesData( const QVector<QPointF> &samples ): QwtArraySeriesData<QPointF>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtPointSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param samples Samples */ QwtPoint3DSeriesData::QwtPoint3DSeriesData( const QVector<QwtPoint3D> &samples ): QwtArraySeriesData<QwtPoint3D>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtPoint3DSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param samples Samples */ QwtIntervalSeriesData::QwtIntervalSeriesData( const QVector<QwtIntervalSample> &samples ): QwtArraySeriesData<QwtIntervalSample>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtIntervalSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param samples Samples */ QwtSetSeriesData::QwtSetSeriesData( const QVector<QwtSetSample> &samples ): QwtArraySeriesData<QwtSetSample>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtSetSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param x Array of x values \param y Array of y values \sa QwtPlotCurve::setData(), QwtPlotCurve::setSamples() */ QwtPointArrayData::QwtPointArrayData( const QVector<double> &x, const QVector<double> &y ): d_x( x ), d_y( y ) { } /*! Constructor \param x Array of x values \param y Array of y values \param size Size of the x and y arrays \sa QwtPlotCurve::setData(), QwtPlotCurve::setSamples() */ QwtPointArrayData::QwtPointArrayData( const double *x, const double *y, size_t size ) { d_x.resize( size ); qMemCopy( d_x.data(), x, size * sizeof( double ) ); d_y.resize( size ); qMemCopy( d_y.data(), y, size * sizeof( double ) ); } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtPointArrayData::boundingRect() const { if ( d_boundingRect.width() < 0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } //! \return Size of the data set size_t QwtPointArrayData::size() const { return qMin( d_x.size(), d_y.size() ); } /*! Return the sample at position i \param i Index \return Sample at position i */ QPointF QwtPointArrayData::sample( size_t i ) const { return QPointF( d_x[int( i )], d_y[int( i )] ); } //! \return Array of the x-values const QVector<double> &QwtPointArrayData::xData() const { return d_x; } //! \return Array of the y-values const QVector<double> &QwtPointArrayData::yData() const { return d_y; } /*! Constructor \param x Array of x values \param y Array of y values \param size Size of the x and y arrays \warning The programmer must assure that the memory blocks referenced by the pointers remain valid during the lifetime of the QwtPlotCPointer object. \sa QwtPlotCurve::setData(), QwtPlotCurve::setRawSamples() */ QwtCPointerData::QwtCPointerData( const double *x, const double *y, size_t size ): d_x( x ), d_y( y ), d_size( size ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtCPointerData::boundingRect() const { if ( d_boundingRect.width() < 0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } //! \return Size of the data set size_t QwtCPointerData::size() const { return d_size; } /*! Return the sample at position i \param i Index \return Sample at position i */ QPointF QwtCPointerData::sample( size_t i ) const { return QPointF( d_x[int( i )], d_y[int( i )] ); } //! \return Array of the x-values const double *QwtCPointerData::xData() const { return d_x; } //! \return Array of the y-values const double *QwtCPointerData::yData() const { return d_y; } /*! Constructor \param size Number of points \param interval Bounding interval for the points \sa setInterval(), setSize() */ QwtSyntheticPointData::QwtSyntheticPointData( size_t size, const QwtInterval &interval ): d_size( size ), d_interval( interval ) { } /*! Change the number of points \param size Number of points \sa size(), setInterval() */ void QwtSyntheticPointData::setSize( size_t size ) { d_size = size; } /*! \return Number of points \sa setSize(), interval() */ size_t QwtSyntheticPointData::size() const { return d_size; } /*! Set the bounding interval \param interval Interval \sa interval(), setSize() */ void QwtSyntheticPointData::setInterval( const QwtInterval &interval ) { d_interval = interval.normalized(); } /*! \return Bounding interval \sa setInterval(), size() */ QwtInterval QwtSyntheticPointData::interval() const { return d_interval; } /*! Set a the "rect of interest" QwtPlotSeriesItem defines the current area of the plot canvas as "rect of interest" ( QwtPlotSeriesItem::updateScaleDiv() ). If interval().isValid() == false the x values are calculated in the interval rect.left() -> rect.right(). \sa rectOfInterest() */ void QwtSyntheticPointData::setRectOfInterest( const QRectF &rect ) { d_rectOfInterest = rect; d_intervalOfInterest = QwtInterval( rect.left(), rect.right() ).normalized(); } /*! \return "rect of interest" \sa setRectOfInterest() */ QRectF QwtSyntheticPointData::rectOfInterest() const { return d_rectOfInterest; } /*! \brief Calculate the bounding rect This implementation iterates over all points, what could often be implemented much faster using the characteristics of the series. When there are many points it is recommended to overload and reimplement this method using the characteristics of the series ( if possible ). \return Bounding rectangle */ QRectF QwtSyntheticPointData::boundingRect() const { if ( d_size == 0 || !( d_interval.isValid() || d_intervalOfInterest.isValid() ) ) { return QRectF( 1.0, 1.0, -2.0, -2.0 ); // something invalid } return qwtBoundingRect( *this ); } /*! Calculate the point from an index \param index Index \return QPointF(x(index), y(x(index))); \warning For invalid indices ( index < 0 || index >= size() ) (0, 0) is returned. */ QPointF QwtSyntheticPointData::sample( size_t index ) const { if ( index >= d_size ) return QPointF( 0, 0 ); const double xValue = x( index ); const double yValue = y( xValue ); return QPointF( xValue, yValue ); } /*! Calculate a x-value from an index x values are calculated by deviding an interval into equidistant steps. If !interval().isValid() the interval is calculated from the "rect of interest". \sa interval(), rectOfInterest(), y() */ double QwtSyntheticPointData::x( uint index ) const { const QwtInterval &interval = d_interval.isValid() ? d_interval : d_intervalOfInterest; if ( !interval.isValid() || d_size == 0 || index >= d_size ) return 0.0; const double dx = interval.width() / d_size; return interval.minValue() + index * dx; } <commit_msg>When updating scales avoid allowing NaN to enter the series<commit_after>/* -*- mode: C++ ; c-file-style: "stroustrup" -*- ***************************** * Qwt Widget Library * Copyright (C) 1997 Josef Wilgen * Copyright (C) 2002 Uwe Rathmann * * This library is free software; you can redistribute it and/or * modify it under the terms of the Qwt License, Version 1.0 *****************************************************************************/ #include "qwt_series_data.h" #include "qwt_math.h" #include <qnumeric.h> static inline QRectF qwtBoundingRect( const QPointF &sample ) { return QRectF( sample.x(), sample.y(), 0.0, 0.0 ); } static inline QRectF qwtBoundingRect( const QwtPoint3D &sample ) { return QRectF( sample.x(), sample.y(), 0.0, 0.0 ); } static inline QRectF qwtBoundingRect( const QwtPointPolar &sample ) { return QRectF( sample.azimuth(), sample.radius(), 0.0, 0.0 ); } static inline QRectF qwtBoundingRect( const QwtIntervalSample &sample ) { return QRectF( sample.interval.minValue(), sample.value, sample.interval.maxValue() - sample.interval.minValue(), 0.0 ); } static inline QRectF qwtBoundingRect( const QwtSetSample &sample ) { double minX = sample.set[0]; double maxX = sample.set[0]; for ( int i = 1; i < sample.set.size(); i++ ) { if ( sample.set[i] < minX ) minX = sample.set[i]; if ( sample.set[i] > maxX ) maxX = sample.set[i]; } double minY = sample.value; double maxY = sample.value; return QRectF( minX, minY, maxX - minX, maxY - minY ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ template <class T> QRectF qwtBoundingRectT( const QwtSeriesData<T>& series, int from, int to ) { QRectF boundingRect( 1.0, 1.0, -2.0, -2.0 ); // invalid; if ( from < 0 ) from = 0; if ( to < 0 ) to = series.size() - 1; if ( to < from ) return boundingRect; int i; for ( i = from; i <= to; i++ ) { const QRectF rect = qwtBoundingRect( series.sample( i ) ); if ( rect.width() >= 0.0 && rect.height() >= 0.0 ) { boundingRect = rect; i++; break; } } for ( ; i <= to; i++ ) { const QRectF rect = qwtBoundingRect( series.sample( i ) ); if ( rect.width() >= 0.0 && rect.height() >= 0.0 ) { if (!qIsNaN(rect.left())) boundingRect.setLeft( qMin( boundingRect.left(), rect.left() ) ); if (!qIsNaN(rect.right())) boundingRect.setRight( qMax( boundingRect.right(), rect.right() ) ); if (!qIsNaN(rect.top())) boundingRect.setTop( qMin( boundingRect.top(), rect.top() ) ); if (!qIsNaN(rect.bottom())) boundingRect.setBottom( qMax( boundingRect.bottom(), rect.bottom() ) ); } } return boundingRect; } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QPointF> &series, int from, int to ) { return qwtBoundingRectT<QPointF>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtPoint3D> &series, int from, int to ) { return qwtBoundingRectT<QwtPoint3D>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset The horizontal coordinates represent the azimuth, the vertical coordinates the radius. Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtPointPolar> &series, int from, int to ) { return qwtBoundingRectT<QwtPointPolar>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtIntervalSample>& series, int from, int to ) { return qwtBoundingRectT<QwtIntervalSample>( series, from, to ); } /*! \brief Calculate the bounding rect of a series subset Slow implementation, that iterates over the series. \param series Series \param from Index of the first sample, <= 0 means from the beginning \param to Index of the last sample, < 0 means to the end \return Bounding rectangle */ QRectF qwtBoundingRect( const QwtSeriesData<QwtSetSample>& series, int from, int to ) { return qwtBoundingRectT<QwtSetSample>( series, from, to ); } /*! Constructor \param samples Samples */ QwtPointSeriesData::QwtPointSeriesData( const QVector<QPointF> &samples ): QwtArraySeriesData<QPointF>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtPointSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param samples Samples */ QwtPoint3DSeriesData::QwtPoint3DSeriesData( const QVector<QwtPoint3D> &samples ): QwtArraySeriesData<QwtPoint3D>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtPoint3DSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param samples Samples */ QwtIntervalSeriesData::QwtIntervalSeriesData( const QVector<QwtIntervalSample> &samples ): QwtArraySeriesData<QwtIntervalSample>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtIntervalSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param samples Samples */ QwtSetSeriesData::QwtSetSeriesData( const QVector<QwtSetSample> &samples ): QwtArraySeriesData<QwtSetSample>( samples ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtSetSeriesData::boundingRect() const { if ( d_boundingRect.width() < 0.0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } /*! Constructor \param x Array of x values \param y Array of y values \sa QwtPlotCurve::setData(), QwtPlotCurve::setSamples() */ QwtPointArrayData::QwtPointArrayData( const QVector<double> &x, const QVector<double> &y ): d_x( x ), d_y( y ) { } /*! Constructor \param x Array of x values \param y Array of y values \param size Size of the x and y arrays \sa QwtPlotCurve::setData(), QwtPlotCurve::setSamples() */ QwtPointArrayData::QwtPointArrayData( const double *x, const double *y, size_t size ) { d_x.resize( size ); qMemCopy( d_x.data(), x, size * sizeof( double ) ); d_y.resize( size ); qMemCopy( d_y.data(), y, size * sizeof( double ) ); } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtPointArrayData::boundingRect() const { if ( d_boundingRect.width() < 0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } //! \return Size of the data set size_t QwtPointArrayData::size() const { return qMin( d_x.size(), d_y.size() ); } /*! Return the sample at position i \param i Index \return Sample at position i */ QPointF QwtPointArrayData::sample( size_t i ) const { return QPointF( d_x[int( i )], d_y[int( i )] ); } //! \return Array of the x-values const QVector<double> &QwtPointArrayData::xData() const { return d_x; } //! \return Array of the y-values const QVector<double> &QwtPointArrayData::yData() const { return d_y; } /*! Constructor \param x Array of x values \param y Array of y values \param size Size of the x and y arrays \warning The programmer must assure that the memory blocks referenced by the pointers remain valid during the lifetime of the QwtPlotCPointer object. \sa QwtPlotCurve::setData(), QwtPlotCurve::setRawSamples() */ QwtCPointerData::QwtCPointerData( const double *x, const double *y, size_t size ): d_x( x ), d_y( y ), d_size( size ) { } /*! \brief Calculate the bounding rect The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. \return Bounding rectangle */ QRectF QwtCPointerData::boundingRect() const { if ( d_boundingRect.width() < 0 ) d_boundingRect = qwtBoundingRect( *this ); return d_boundingRect; } //! \return Size of the data set size_t QwtCPointerData::size() const { return d_size; } /*! Return the sample at position i \param i Index \return Sample at position i */ QPointF QwtCPointerData::sample( size_t i ) const { return QPointF( d_x[int( i )], d_y[int( i )] ); } //! \return Array of the x-values const double *QwtCPointerData::xData() const { return d_x; } //! \return Array of the y-values const double *QwtCPointerData::yData() const { return d_y; } /*! Constructor \param size Number of points \param interval Bounding interval for the points \sa setInterval(), setSize() */ QwtSyntheticPointData::QwtSyntheticPointData( size_t size, const QwtInterval &interval ): d_size( size ), d_interval( interval ) { } /*! Change the number of points \param size Number of points \sa size(), setInterval() */ void QwtSyntheticPointData::setSize( size_t size ) { d_size = size; } /*! \return Number of points \sa setSize(), interval() */ size_t QwtSyntheticPointData::size() const { return d_size; } /*! Set the bounding interval \param interval Interval \sa interval(), setSize() */ void QwtSyntheticPointData::setInterval( const QwtInterval &interval ) { d_interval = interval.normalized(); } /*! \return Bounding interval \sa setInterval(), size() */ QwtInterval QwtSyntheticPointData::interval() const { return d_interval; } /*! Set a the "rect of interest" QwtPlotSeriesItem defines the current area of the plot canvas as "rect of interest" ( QwtPlotSeriesItem::updateScaleDiv() ). If interval().isValid() == false the x values are calculated in the interval rect.left() -> rect.right(). \sa rectOfInterest() */ void QwtSyntheticPointData::setRectOfInterest( const QRectF &rect ) { d_rectOfInterest = rect; d_intervalOfInterest = QwtInterval( rect.left(), rect.right() ).normalized(); } /*! \return "rect of interest" \sa setRectOfInterest() */ QRectF QwtSyntheticPointData::rectOfInterest() const { return d_rectOfInterest; } /*! \brief Calculate the bounding rect This implementation iterates over all points, what could often be implemented much faster using the characteristics of the series. When there are many points it is recommended to overload and reimplement this method using the characteristics of the series ( if possible ). \return Bounding rectangle */ QRectF QwtSyntheticPointData::boundingRect() const { if ( d_size == 0 || !( d_interval.isValid() || d_intervalOfInterest.isValid() ) ) { return QRectF( 1.0, 1.0, -2.0, -2.0 ); // something invalid } return qwtBoundingRect( *this ); } /*! Calculate the point from an index \param index Index \return QPointF(x(index), y(x(index))); \warning For invalid indices ( index < 0 || index >= size() ) (0, 0) is returned. */ QPointF QwtSyntheticPointData::sample( size_t index ) const { if ( index >= d_size ) return QPointF( 0, 0 ); const double xValue = x( index ); const double yValue = y( xValue ); return QPointF( xValue, yValue ); } /*! Calculate a x-value from an index x values are calculated by deviding an interval into equidistant steps. If !interval().isValid() the interval is calculated from the "rect of interest". \sa interval(), rectOfInterest(), y() */ double QwtSyntheticPointData::x( uint index ) const { const QwtInterval &interval = d_interval.isValid() ? d_interval : d_intervalOfInterest; if ( !interval.isValid() || d_size == 0 || index >= d_size ) return 0.0; const double dx = interval.width() / d_size; return interval.minValue() + index * dx; } <|endoftext|>
<commit_before>#include <windows.h> #include "overlay.h" #include <OvRender.h> #include "osd.h" #include "menu.h" #include <stdio.h> BOOLEAN g_FontInited = FALSE; BOOLEAN IsStableFramerate; BOOLEAN IsStableFrametime; BOOLEAN IsLimitedFrametime; BOOLEAN DisableAutoOverclock; UINT16 DiskResponseTime; UINT64 CyclesWaited; HANDLE RenderThreadHandle; UINT32 DisplayFrequency; double FrameTimeAvg; double FrameRate; UINT8 FrameLimit = 80; //80 fps int debugInt = 1; VOID DebugRec(); VOID InitializeKeyboardHook(); double PCFreq = 0.0; __int64 CounterStart = 0; extern "C" LONG __stdcall NtQueryPerformanceCounter( LARGE_INTEGER* PerformanceCounter, LARGE_INTEGER* PerformanceFrequency ); VOID StartCounter() { LARGE_INTEGER perfCount; LARGE_INTEGER frequency; NtQueryPerformanceCounter(&perfCount, &frequency); PCFreq = (double)frequency.QuadPart / 1000.0;; } double GetPerformanceCounter() { LARGE_INTEGER li; NtQueryPerformanceCounter(&li, NULL); return (double)li.QuadPart / PCFreq; } BOOLEAN IsGpuLag() { if (PushSharedMemory->HarwareInformation.DisplayDevice.Load > 95) { return TRUE; } return FALSE; } #define TSAMP 60 double garb[TSAMP]; int addint = 0; double GetAverageFrameTime() { UINT32 i; double total = 0; for (i = 0; i < TSAMP; i++) total += garb[i]; return total / TSAMP; } #include <math.h> bool approximatelyEqual(double a, double b, double epsilon) { return fabs(a - b) < epsilon; } VOID RunFrameStatistics() { static double newTickCount = 0.0, lastTickCount_FrameLimiter = 0.0, oldTick = 0.0, delta = 0.0, oldTickFrameRateStable = 0.0, frameTime = 0.0, acceptableFrameTime = 0.0, lastTickCount; static BOOLEAN inited = FALSE; static BOOLEAN beginThreadDiagnostics = FALSE; if (!inited) { DEVMODE devMode; StartCounter(); inited = TRUE; EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode); DisplayFrequency = devMode.dmDisplayFrequency; acceptableFrameTime = (double)1000 / (double)(devMode.dmDisplayFrequency - 1); if (PushSharedMemory->FrameLimit > 1) { FrameLimit = PushSharedMemory->FrameLimit; if (FrameLimit < DisplayFrequency) acceptableFrameTime = 1000.0f / (double)(FrameLimit - 1); } newTickCount = oldTick = lastTickCount_FrameLimiter = GetPerformanceCounter(); } newTickCount = GetPerformanceCounter(); delta = newTickCount - oldTick; frameTime = newTickCount - lastTickCount; lastTickCount = newTickCount; IsLimitedFrametime = FALSE; garb[addint] = frameTime; addint++; if (addint == TSAMP) addint = 0; FrameTimeAvg = GetAverageFrameTime(); static double OldfFPS = 0.0f; FrameRate = 1000.0f / FrameTimeAvg; FrameRate = FrameRate * 0.1 + OldfFPS * 0.9; OldfFPS = FrameRate; // Every second. if (delta > 1000) { oldTick = newTickCount; //if (PushSharedMemory->ThreadOptimization || PushSharedMemory->OSDFlags & OSD_MTU) //{ PushRefreshThreadMonitor(); //if (PushSharedMemory->OSDFlags & OSD_MTU) PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage = PushGetMaxThreadUsage(); //} RenderThreadHandle = GetCurrentThread(); } // Simple Diagnostics. if (frameTime > acceptableFrameTime) { if (PushSharedMemory->HarwareInformation.Processor.Load > 95) PushSharedMemory->Overloads |= OSD_CPU_LOAD; if (PushSharedMemory->HarwareInformation.Processor.MaxCoreUsage > 95) PushSharedMemory->Overloads |= OSD_MCU; if (IsGpuLag()) PushSharedMemory->Overloads |= OSD_GPU_LOAD; if (PushSharedMemory->HarwareInformation.Memory.Used > PushSharedMemory->HarwareInformation.Memory.Total) PushSharedMemory->Overloads |= OSD_RAM; PushSharedMemory->HarwareInformation.Disk.ResponseTime = DiskResponseTime; if (PushSharedMemory->HarwareInformation.Disk.ResponseTime > 4000) { PushSharedMemory->Overloads |= OSD_DISK_RESPONSE; PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE; } if (beginThreadDiagnostics && PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage >= 99) { PushSharedMemory->Overloads |= OSD_MTU; PushSharedMemory->OSDFlags |= OSD_MTU; } if (PushSharedMemory->AutoLogFileIo) PushSharedMemory->LogFileIo = TRUE; } //lazier check than (frameTime > acceptableFrameTime) if (FrameTimeAvg > acceptableFrameTime) { //reset the timer oldTickFrameRateStable = newTickCount; // Lazy overclock if (debugInt++ % DisplayFrequency == 0) { if (!DisableAutoOverclock && IsGpuLag() && PushSharedMemory->HarwareInformation.DisplayDevice.EngineClock != 0) { PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; PushSharedMemory->Overloads |= OSD_GPU_E_CLK; PushSharedMemory->Overloads |= OSD_GPU_M_CLK; if (PushSharedMemory->HarwareInformation.DisplayDevice.EngineClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.EngineOverclock) ClockStep(OC_ENGINE, Up); if (PushSharedMemory->HarwareInformation.DisplayDevice.MemoryClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.MemoryOverclock) ClockStep(OC_MEMORY, Up); } } } if (newTickCount - oldTickFrameRateStable > 30000) //frame rate has been stable for at least 30 seconds. IsStableFramerate = TRUE; else IsStableFramerate = FALSE; if (newTickCount - oldTickFrameRateStable > 1000) { //frame rate has been stable for at least 1 second. //we put this here to let the game go through it's usual startup routines which normally issues a false positive on thread diagnostics. //this tells the diagnostics to hold off until frameTimeAvg (average frame-time) is stable. beginThreadDiagnostics = TRUE; } double frameTimeDamped = 1000.0f / FrameRate; if (frameTimeDamped > acceptableFrameTime) IsStableFrametime = FALSE; else IsStableFrametime = TRUE; if (PushSharedMemory->FrameLimit) { double frameTimeMin = (double)1000 / (double)FrameLimit; frameTime = newTickCount - lastTickCount_FrameLimiter; if (approximatelyEqual(frameTimeDamped, frameTimeMin, 0.100)) { IsLimitedFrametime = TRUE; } if (frameTime < frameTimeMin) { UINT64 cyclesStart, cyclesStop; RenderThreadHandle = GetCurrentThread(); QueryThreadCycleTime(RenderThreadHandle, &cyclesStart); lastTickCount_FrameLimiter = newTickCount; while (frameTime < frameTimeMin) { newTickCount = GetPerformanceCounter(); frameTime += (newTickCount - lastTickCount_FrameLimiter); lastTickCount_FrameLimiter = newTickCount; } QueryThreadCycleTime(RenderThreadHandle, &cyclesStop); CyclesWaited += cyclesStop - cyclesStart; } lastTickCount_FrameLimiter = newTickCount; } } VOID RnRender( OvOverlay* Overlay ) { static BOOLEAN rendering = FALSE; if (!rendering) { rendering = TRUE; StopImageMonitoring(); InitializeKeyboardHook(); } Osd_Draw( Overlay ); Menu_Render( Overlay ); RunFrameStatistics(); //Overlay->DrawText(L"u can draw anything in this render loop!\n"); } <commit_msg>better variable names<commit_after>#include <windows.h> #include "overlay.h" #include <OvRender.h> #include "osd.h" #include "menu.h" #include <stdio.h> BOOLEAN g_FontInited = FALSE; BOOLEAN IsStableFramerate; BOOLEAN IsStableFrametime; BOOLEAN IsLimitedFrametime; BOOLEAN DisableAutoOverclock; UINT16 DiskResponseTime; UINT64 CyclesWaited; HANDLE RenderThreadHandle; UINT32 DisplayFrequency; double FrameTimeAvg; double FrameRate; UINT8 FrameLimit = 80; //80 fps int debugInt = 1; VOID DebugRec(); VOID InitializeKeyboardHook(); double PCFreq = 0.0; __int64 CounterStart = 0; extern "C" LONG __stdcall NtQueryPerformanceCounter( LARGE_INTEGER* PerformanceCounter, LARGE_INTEGER* PerformanceFrequency ); VOID StartCounter() { LARGE_INTEGER perfCount; LARGE_INTEGER frequency; NtQueryPerformanceCounter(&perfCount, &frequency); PCFreq = (double)frequency.QuadPart / 1000.0;; } double GetPerformanceCounter() { LARGE_INTEGER li; NtQueryPerformanceCounter(&li, NULL); return (double)li.QuadPart / PCFreq; } BOOLEAN IsGpuLag() { if (PushSharedMemory->HarwareInformation.DisplayDevice.Load > 95) { return TRUE; } return FALSE; } #define TSAMPLES 60 double FrameTimesCircularBuffer[TSAMPLES]; int CircularBufferIndex = 0; double GetAverageFrameTime() { UINT32 i; double total = 0; for (i = 0; i < TSAMPLES; i++) total += FrameTimesCircularBuffer[i]; return total / TSAMPLES; } #include <math.h> bool approximatelyEqual(double a, double b, double epsilon) { return fabs(a - b) < epsilon; } VOID RunFrameStatistics() { static double newTickCount = 0.0, lastTickCount_FrameLimiter = 0.0, oldTick = 0.0, delta = 0.0, oldTickFrameRateStable = 0.0, frameTime = 0.0, acceptableFrameTime = 0.0, lastTickCount; static BOOLEAN inited = FALSE; static BOOLEAN beginThreadDiagnostics = FALSE; if (!inited) { DEVMODE devMode; StartCounter(); inited = TRUE; EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode); DisplayFrequency = devMode.dmDisplayFrequency; acceptableFrameTime = (double)1000 / (double)(devMode.dmDisplayFrequency - 1); if (PushSharedMemory->FrameLimit > 1) { FrameLimit = PushSharedMemory->FrameLimit; if (FrameLimit < DisplayFrequency) acceptableFrameTime = 1000.0f / (double)(FrameLimit - 1); } newTickCount = oldTick = lastTickCount_FrameLimiter = GetPerformanceCounter(); } newTickCount = GetPerformanceCounter(); delta = newTickCount - oldTick; frameTime = newTickCount - lastTickCount; lastTickCount = newTickCount; IsLimitedFrametime = FALSE; FrameTimesCircularBuffer[CircularBufferIndex] = frameTime; CircularBufferIndex++; if (CircularBufferIndex == TSAMPLES) CircularBufferIndex = 0; FrameTimeAvg = GetAverageFrameTime(); static double OldfFPS = 0.0f; FrameRate = 1000.0f / FrameTimeAvg; FrameRate = FrameRate * 0.1 + OldfFPS * 0.9; OldfFPS = FrameRate; // Every second. if (delta > 1000) { oldTick = newTickCount; //if (PushSharedMemory->ThreadOptimization || PushSharedMemory->OSDFlags & OSD_MTU) //{ PushRefreshThreadMonitor(); //if (PushSharedMemory->OSDFlags & OSD_MTU) PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage = PushGetMaxThreadUsage(); //} RenderThreadHandle = GetCurrentThread(); } // Simple Diagnostics. if (frameTime > acceptableFrameTime) { if (PushSharedMemory->HarwareInformation.Processor.Load > 95) PushSharedMemory->Overloads |= OSD_CPU_LOAD; if (PushSharedMemory->HarwareInformation.Processor.MaxCoreUsage > 95) PushSharedMemory->Overloads |= OSD_MCU; if (IsGpuLag()) PushSharedMemory->Overloads |= OSD_GPU_LOAD; if (PushSharedMemory->HarwareInformation.Memory.Used > PushSharedMemory->HarwareInformation.Memory.Total) PushSharedMemory->Overloads |= OSD_RAM; PushSharedMemory->HarwareInformation.Disk.ResponseTime = DiskResponseTime; if (PushSharedMemory->HarwareInformation.Disk.ResponseTime > 4000) { PushSharedMemory->Overloads |= OSD_DISK_RESPONSE; PushSharedMemory->OSDFlags |= OSD_DISK_RESPONSE; } if (beginThreadDiagnostics && PushSharedMemory->HarwareInformation.Processor.MaxThreadUsage >= 99) { PushSharedMemory->Overloads |= OSD_MTU; PushSharedMemory->OSDFlags |= OSD_MTU; } if (PushSharedMemory->AutoLogFileIo) PushSharedMemory->LogFileIo = TRUE; } //lazier check than (frameTime > acceptableFrameTime) if (FrameTimeAvg > acceptableFrameTime) { //reset the timer oldTickFrameRateStable = newTickCount; // Lazy overclock if (debugInt++ % DisplayFrequency == 0) { if (!DisableAutoOverclock && IsGpuLag() && PushSharedMemory->HarwareInformation.DisplayDevice.EngineClock != 0) { PushSharedMemory->OSDFlags |= OSD_GPU_E_CLK; PushSharedMemory->OSDFlags |= OSD_GPU_M_CLK; PushSharedMemory->Overloads |= OSD_GPU_E_CLK; PushSharedMemory->Overloads |= OSD_GPU_M_CLK; if (PushSharedMemory->HarwareInformation.DisplayDevice.EngineClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.EngineOverclock) ClockStep(OC_ENGINE, Up); if (PushSharedMemory->HarwareInformation.DisplayDevice.MemoryClockMax < PushSharedMemory->HarwareInformation.DisplayDevice.MemoryOverclock) ClockStep(OC_MEMORY, Up); } } } if (newTickCount - oldTickFrameRateStable > 30000) //frame rate has been stable for at least 30 seconds. IsStableFramerate = TRUE; else IsStableFramerate = FALSE; if (newTickCount - oldTickFrameRateStable > 1000) { //frame rate has been stable for at least 1 second. //we put this here to let the game go through it's usual startup routines which normally issues a false positive on thread diagnostics. //this tells the diagnostics to hold off until frameTimeAvg (average frame-time) is stable. beginThreadDiagnostics = TRUE; } double frameTimeDamped = 1000.0f / FrameRate; if (frameTimeDamped > acceptableFrameTime) IsStableFrametime = FALSE; else IsStableFrametime = TRUE; if (PushSharedMemory->FrameLimit) { double frameTimeMin = (double)1000 / (double)FrameLimit; frameTime = newTickCount - lastTickCount_FrameLimiter; if (approximatelyEqual(frameTimeDamped, frameTimeMin, 0.100)) { IsLimitedFrametime = TRUE; } if (frameTime < frameTimeMin) { UINT64 cyclesStart, cyclesStop; RenderThreadHandle = GetCurrentThread(); QueryThreadCycleTime(RenderThreadHandle, &cyclesStart); lastTickCount_FrameLimiter = newTickCount; while (frameTime < frameTimeMin) { newTickCount = GetPerformanceCounter(); frameTime += (newTickCount - lastTickCount_FrameLimiter); lastTickCount_FrameLimiter = newTickCount; } QueryThreadCycleTime(RenderThreadHandle, &cyclesStop); CyclesWaited += cyclesStop - cyclesStart; } lastTickCount_FrameLimiter = newTickCount; } } VOID RnRender( OvOverlay* Overlay ) { static BOOLEAN rendering = FALSE; if (!rendering) { rendering = TRUE; StopImageMonitoring(); InitializeKeyboardHook(); } Osd_Draw( Overlay ); Menu_Render( Overlay ); RunFrameStatistics(); //Overlay->DrawText(L"u can draw anything in this render loop!\n"); } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTessellatingPathRenderer.h" #include "GrBatchFlushState.h" #include "GrBatchTest.h" #include "GrDefaultGeoProcFactory.h" #include "GrPathUtils.h" #include "GrVertices.h" #include "GrResourceCache.h" #include "GrResourceProvider.h" #include "GrTessellator.h" #include "SkGeometry.h" #include "batches/GrVertexBatch.h" #include <stdio.h> /* * This path renderer tessellates the path into triangles using GrTessellator, uploads the triangles * to a vertex buffer, and renders them with a single draw call. It does not currently do * antialiasing, so it must be used in conjunction with multisampling. */ namespace { struct TessInfo { SkScalar fTolerance; int fCount; }; // When the SkPathRef genID changes, invalidate a corresponding GrResource described by key. class PathInvalidator : public SkPathRef::GenIDChangeListener { public: explicit PathInvalidator(const GrUniqueKey& key) : fMsg(key) {} private: GrUniqueKeyInvalidatedMessage fMsg; void onChange() override { SkMessageBus<GrUniqueKeyInvalidatedMessage>::Post(fMsg); } }; bool cache_match(GrVertexBuffer* vertexBuffer, SkScalar tol, int* actualCount) { if (!vertexBuffer) { return false; } const SkData* data = vertexBuffer->getUniqueKey().getCustomData(); SkASSERT(data); const TessInfo* info = static_cast<const TessInfo*>(data->data()); if (info->fTolerance == 0 || info->fTolerance < 3.0f * tol) { *actualCount = info->fCount; return true; } return false; } class StaticVertexAllocator : public GrTessellator::VertexAllocator { public: StaticVertexAllocator(SkAutoTUnref<GrVertexBuffer>& vertexBuffer, GrResourceProvider* resourceProvider, bool canMapVB) : fVertexBuffer(vertexBuffer) , fResourceProvider(resourceProvider) , fCanMapVB(canMapVB) , fVertices(nullptr) { } SkPoint* lock(int vertexCount) override { size_t size = vertexCount * sizeof(SkPoint); if (!fVertexBuffer.get() || fVertexBuffer->gpuMemorySize() < size) { fVertexBuffer.reset(fResourceProvider->createVertexBuffer( size, GrResourceProvider::kStatic_BufferUsage, 0)); } if (!fVertexBuffer.get()) { return nullptr; } if (fCanMapVB) { fVertices = static_cast<SkPoint*>(fVertexBuffer->map()); } else { fVertices = new SkPoint[vertexCount]; } return fVertices; } void unlock(int actualCount) override { if (fCanMapVB) { fVertexBuffer->unmap(); } else { fVertexBuffer->updateData(fVertices, actualCount * sizeof(SkPoint)); delete[] fVertices; } fVertices = nullptr; } private: SkAutoTUnref<GrVertexBuffer>& fVertexBuffer; GrResourceProvider* fResourceProvider; bool fCanMapVB; SkPoint* fVertices; }; } // namespace GrTessellatingPathRenderer::GrTessellatingPathRenderer() { } bool GrTessellatingPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const { // This path renderer can draw all fill styles, all stroke styles except hairlines, but does // not do antialiasing. It can do convex and concave paths, but we'll leave the convex ones to // simpler algorithms. return !IsStrokeHairlineOrEquivalent(*args.fStroke, *args.fViewMatrix, nullptr) && !args.fAntiAlias && !args.fPath->isConvex(); } class TessellatingPathBatch : public GrVertexBatch { public: DEFINE_BATCH_CLASS_ID static GrDrawBatch* Create(const GrColor& color, const SkPath& path, const GrStrokeInfo& stroke, const SkMatrix& viewMatrix, SkRect clipBounds) { return new TessellatingPathBatch(color, path, stroke, viewMatrix, clipBounds); } const char* name() const override { return "TessellatingPathBatch"; } void computePipelineOptimizations(GrInitInvariantOutput* color, GrInitInvariantOutput* coverage, GrBatchToXPOverrides* overrides) const override { color->setKnownFourComponents(fColor); coverage->setUnknownSingleComponent(); } private: void initBatchTracker(const GrXPOverridesForBatch& overrides) override { // Handle any color overrides if (!overrides.readsColor()) { fColor = GrColor_ILLEGAL; } overrides.getOverrideColorIfSet(&fColor); fPipelineInfo = overrides; } void draw(Target* target, const GrGeometryProcessor* gp) const { // construct a cache key from the path's genID and the view matrix static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain(); GrUniqueKey key; int clipBoundsSize32 = fPath.isInverseFillType() ? sizeof(fClipBounds) / sizeof(uint32_t) : 0; int strokeDataSize32 = fStroke.computeUniqueKeyFragmentData32Cnt(); GrUniqueKey::Builder builder(&key, kDomain, 2 + clipBoundsSize32 + strokeDataSize32); builder[0] = fPath.getGenerationID(); builder[1] = fPath.getFillType(); // For inverse fills, the tessellation is dependent on clip bounds. if (fPath.isInverseFillType()) { memcpy(&builder[2], &fClipBounds, sizeof(fClipBounds)); } fStroke.asUniqueKeyFragment(&builder[2 + clipBoundsSize32]); builder.finish(); GrResourceProvider* rp = target->resourceProvider(); SkAutoTUnref<GrVertexBuffer> vertexBuffer(rp->findAndRefTByUniqueKey<GrVertexBuffer>(key)); int actualCount; SkScalar screenSpaceTol = GrPathUtils::kDefaultTolerance; SkScalar tol = GrPathUtils::scaleToleranceToSrc( screenSpaceTol, fViewMatrix, fPath.getBounds()); if (cache_match(vertexBuffer.get(), tol, &actualCount)) { this->drawVertices(target, gp, vertexBuffer.get(), 0, actualCount); return; } SkPath path; GrStrokeInfo stroke(fStroke); if (stroke.isDashed()) { if (!stroke.applyDashToPath(&path, &stroke, fPath)) { return; } } else { path = fPath; } if (!stroke.isFillStyle()) { stroke.setResScale(SkScalarAbs(fViewMatrix.getMaxScale())); if (!stroke.applyToPath(&path, path)) { return; } stroke.setFillStyle(); } bool isLinear; bool canMapVB = GrCaps::kNone_MapFlags != target->caps().mapBufferFlags(); StaticVertexAllocator allocator(vertexBuffer, target->resourceProvider(), canMapVB); int count = GrTessellator::PathToTriangles(path, tol, fClipBounds, &allocator, &isLinear); if (count == 0) { return; } this->drawVertices(target, gp, vertexBuffer.get(), 0, count); if (!fPath.isVolatile()) { TessInfo info; info.fTolerance = isLinear ? 0 : tol; info.fCount = count; SkAutoTUnref<SkData> data(SkData::NewWithCopy(&info, sizeof(info))); key.setCustomData(data.get()); target->resourceProvider()->assignUniqueKeyToResource(key, vertexBuffer.get()); SkPathPriv::AddGenIDChangeListener(fPath, new PathInvalidator(key)); } } void onPrepareDraws(Target* target) const override { SkAutoTUnref<const GrGeometryProcessor> gp; { using namespace GrDefaultGeoProcFactory; Color color(fColor); LocalCoords localCoords(fPipelineInfo.readsLocalCoords() ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type); Coverage::Type coverageType; if (fPipelineInfo.readsCoverage()) { coverageType = Coverage::kSolid_Type; } else { coverageType = Coverage::kNone_Type; } Coverage coverage(coverageType); gp.reset(GrDefaultGeoProcFactory::Create(color, coverage, localCoords, fViewMatrix)); } this->draw(target, gp.get()); } void drawVertices(Target* target, const GrGeometryProcessor* gp, const GrVertexBuffer* vb, int firstVertex, int count) const { target->initDraw(gp, this->pipeline()); SkASSERT(gp->getVertexStride() == sizeof(SkPoint)); GrPrimitiveType primitiveType = TESSELLATOR_WIREFRAME ? kLines_GrPrimitiveType : kTriangles_GrPrimitiveType; GrVertices vertices; vertices.init(primitiveType, vb, firstVertex, count); target->draw(vertices); } bool onCombineIfPossible(GrBatch*, const GrCaps&) override { return false; } TessellatingPathBatch(const GrColor& color, const SkPath& path, const GrStrokeInfo& stroke, const SkMatrix& viewMatrix, const SkRect& clipBounds) : INHERITED(ClassID()) , fColor(color) , fPath(path) , fStroke(stroke) , fViewMatrix(viewMatrix) { const SkRect& pathBounds = path.getBounds(); fClipBounds = clipBounds; // Because the clip bounds are used to add a contour for inverse fills, they must also // include the path bounds. fClipBounds.join(pathBounds); if (path.isInverseFillType()) { fBounds = fClipBounds; } else { fBounds = path.getBounds(); } if (!stroke.isFillStyle()) { SkScalar radius = SkScalarHalf(stroke.getWidth()); if (stroke.getJoin() == SkPaint::kMiter_Join) { SkScalar scale = stroke.getMiter(); if (scale > SK_Scalar1) { radius = SkScalarMul(radius, scale); } } fBounds.outset(radius, radius); } viewMatrix.mapRect(&fBounds); } GrColor fColor; SkPath fPath; GrStrokeInfo fStroke; SkMatrix fViewMatrix; SkRect fClipBounds; // in source space GrXPOverridesForBatch fPipelineInfo; typedef GrVertexBatch INHERITED; }; bool GrTessellatingPathRenderer::onDrawPath(const DrawPathArgs& args) { GR_AUDIT_TRAIL_AUTO_FRAME(args.fTarget->getAuditTrail(), "GrTessellatingPathRenderer::onDrawPath"); SkASSERT(!args.fAntiAlias); const GrRenderTarget* rt = args.fPipelineBuilder->getRenderTarget(); if (nullptr == rt) { return false; } SkIRect clipBoundsI; args.fPipelineBuilder->clip().getConservativeBounds(rt->width(), rt->height(), &clipBoundsI); SkRect clipBounds = SkRect::Make(clipBoundsI); SkMatrix vmi; if (!args.fViewMatrix->invert(&vmi)) { return false; } vmi.mapRect(&clipBounds); SkAutoTUnref<GrDrawBatch> batch(TessellatingPathBatch::Create(args.fColor, *args.fPath, *args.fStroke, *args.fViewMatrix, clipBounds)); args.fTarget->drawBatch(*args.fPipelineBuilder, batch); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef GR_TEST_UTILS DRAW_BATCH_TEST_DEFINE(TesselatingPathBatch) { GrColor color = GrRandomColor(random); SkMatrix viewMatrix = GrTest::TestMatrixInvertible(random); SkPath path = GrTest::TestPath(random); SkRect clipBounds = GrTest::TestRect(random); SkMatrix vmi; bool result = viewMatrix.invert(&vmi); if (!result) { SkFAIL("Cannot invert matrix\n"); } vmi.mapRect(&clipBounds); GrStrokeInfo strokeInfo = GrTest::TestStrokeInfo(random); return TessellatingPathBatch::Create(color, path, strokeInfo, viewMatrix, clipBounds); } #endif <commit_msg>GrTessellator: don't reuse the previous vertex buffer on a cache miss.<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTessellatingPathRenderer.h" #include "GrBatchFlushState.h" #include "GrBatchTest.h" #include "GrDefaultGeoProcFactory.h" #include "GrPathUtils.h" #include "GrVertices.h" #include "GrResourceCache.h" #include "GrResourceProvider.h" #include "GrTessellator.h" #include "SkGeometry.h" #include "batches/GrVertexBatch.h" #include <stdio.h> /* * This path renderer tessellates the path into triangles using GrTessellator, uploads the triangles * to a vertex buffer, and renders them with a single draw call. It does not currently do * antialiasing, so it must be used in conjunction with multisampling. */ namespace { struct TessInfo { SkScalar fTolerance; int fCount; }; // When the SkPathRef genID changes, invalidate a corresponding GrResource described by key. class PathInvalidator : public SkPathRef::GenIDChangeListener { public: explicit PathInvalidator(const GrUniqueKey& key) : fMsg(key) {} private: GrUniqueKeyInvalidatedMessage fMsg; void onChange() override { SkMessageBus<GrUniqueKeyInvalidatedMessage>::Post(fMsg); } }; bool cache_match(GrVertexBuffer* vertexBuffer, SkScalar tol, int* actualCount) { if (!vertexBuffer) { return false; } const SkData* data = vertexBuffer->getUniqueKey().getCustomData(); SkASSERT(data); const TessInfo* info = static_cast<const TessInfo*>(data->data()); if (info->fTolerance == 0 || info->fTolerance < 3.0f * tol) { *actualCount = info->fCount; return true; } return false; } class StaticVertexAllocator : public GrTessellator::VertexAllocator { public: StaticVertexAllocator(GrResourceProvider* resourceProvider, bool canMapVB) : fResourceProvider(resourceProvider) , fCanMapVB(canMapVB) , fVertices(nullptr) { } SkPoint* lock(int vertexCount) override { size_t size = vertexCount * sizeof(SkPoint); fVertexBuffer.reset(fResourceProvider->createVertexBuffer( size, GrResourceProvider::kStatic_BufferUsage, 0)); if (!fVertexBuffer.get()) { return nullptr; } if (fCanMapVB) { fVertices = static_cast<SkPoint*>(fVertexBuffer->map()); } else { fVertices = new SkPoint[vertexCount]; } return fVertices; } void unlock(int actualCount) override { if (fCanMapVB) { fVertexBuffer->unmap(); } else { fVertexBuffer->updateData(fVertices, actualCount * sizeof(SkPoint)); delete[] fVertices; } fVertices = nullptr; } GrVertexBuffer* vertexBuffer() { return fVertexBuffer.get(); } private: SkAutoTUnref<GrVertexBuffer> fVertexBuffer; GrResourceProvider* fResourceProvider; bool fCanMapVB; SkPoint* fVertices; }; } // namespace GrTessellatingPathRenderer::GrTessellatingPathRenderer() { } bool GrTessellatingPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const { // This path renderer can draw all fill styles, all stroke styles except hairlines, but does // not do antialiasing. It can do convex and concave paths, but we'll leave the convex ones to // simpler algorithms. return !IsStrokeHairlineOrEquivalent(*args.fStroke, *args.fViewMatrix, nullptr) && !args.fAntiAlias && !args.fPath->isConvex(); } class TessellatingPathBatch : public GrVertexBatch { public: DEFINE_BATCH_CLASS_ID static GrDrawBatch* Create(const GrColor& color, const SkPath& path, const GrStrokeInfo& stroke, const SkMatrix& viewMatrix, SkRect clipBounds) { return new TessellatingPathBatch(color, path, stroke, viewMatrix, clipBounds); } const char* name() const override { return "TessellatingPathBatch"; } void computePipelineOptimizations(GrInitInvariantOutput* color, GrInitInvariantOutput* coverage, GrBatchToXPOverrides* overrides) const override { color->setKnownFourComponents(fColor); coverage->setUnknownSingleComponent(); } private: void initBatchTracker(const GrXPOverridesForBatch& overrides) override { // Handle any color overrides if (!overrides.readsColor()) { fColor = GrColor_ILLEGAL; } overrides.getOverrideColorIfSet(&fColor); fPipelineInfo = overrides; } void draw(Target* target, const GrGeometryProcessor* gp) const { // construct a cache key from the path's genID and the view matrix static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain(); GrUniqueKey key; int clipBoundsSize32 = fPath.isInverseFillType() ? sizeof(fClipBounds) / sizeof(uint32_t) : 0; int strokeDataSize32 = fStroke.computeUniqueKeyFragmentData32Cnt(); GrUniqueKey::Builder builder(&key, kDomain, 2 + clipBoundsSize32 + strokeDataSize32); builder[0] = fPath.getGenerationID(); builder[1] = fPath.getFillType(); // For inverse fills, the tessellation is dependent on clip bounds. if (fPath.isInverseFillType()) { memcpy(&builder[2], &fClipBounds, sizeof(fClipBounds)); } fStroke.asUniqueKeyFragment(&builder[2 + clipBoundsSize32]); builder.finish(); GrResourceProvider* rp = target->resourceProvider(); SkAutoTUnref<GrVertexBuffer> cachedVertexBuffer( rp->findAndRefTByUniqueKey<GrVertexBuffer>(key)); int actualCount; SkScalar screenSpaceTol = GrPathUtils::kDefaultTolerance; SkScalar tol = GrPathUtils::scaleToleranceToSrc( screenSpaceTol, fViewMatrix, fPath.getBounds()); if (cache_match(cachedVertexBuffer.get(), tol, &actualCount)) { this->drawVertices(target, gp, cachedVertexBuffer.get(), 0, actualCount); return; } SkPath path; GrStrokeInfo stroke(fStroke); if (stroke.isDashed()) { if (!stroke.applyDashToPath(&path, &stroke, fPath)) { return; } } else { path = fPath; } if (!stroke.isFillStyle()) { stroke.setResScale(SkScalarAbs(fViewMatrix.getMaxScale())); if (!stroke.applyToPath(&path, path)) { return; } stroke.setFillStyle(); } bool isLinear; bool canMapVB = GrCaps::kNone_MapFlags != target->caps().mapBufferFlags(); StaticVertexAllocator allocator(rp, canMapVB); int count = GrTessellator::PathToTriangles(path, tol, fClipBounds, &allocator, &isLinear); if (count == 0) { return; } this->drawVertices(target, gp, allocator.vertexBuffer(), 0, count); if (!fPath.isVolatile()) { TessInfo info; info.fTolerance = isLinear ? 0 : tol; info.fCount = count; SkAutoTUnref<SkData> data(SkData::NewWithCopy(&info, sizeof(info))); key.setCustomData(data.get()); rp->assignUniqueKeyToResource(key, allocator.vertexBuffer()); SkPathPriv::AddGenIDChangeListener(fPath, new PathInvalidator(key)); } } void onPrepareDraws(Target* target) const override { SkAutoTUnref<const GrGeometryProcessor> gp; { using namespace GrDefaultGeoProcFactory; Color color(fColor); LocalCoords localCoords(fPipelineInfo.readsLocalCoords() ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type); Coverage::Type coverageType; if (fPipelineInfo.readsCoverage()) { coverageType = Coverage::kSolid_Type; } else { coverageType = Coverage::kNone_Type; } Coverage coverage(coverageType); gp.reset(GrDefaultGeoProcFactory::Create(color, coverage, localCoords, fViewMatrix)); } this->draw(target, gp.get()); } void drawVertices(Target* target, const GrGeometryProcessor* gp, const GrVertexBuffer* vb, int firstVertex, int count) const { target->initDraw(gp, this->pipeline()); SkASSERT(gp->getVertexStride() == sizeof(SkPoint)); GrPrimitiveType primitiveType = TESSELLATOR_WIREFRAME ? kLines_GrPrimitiveType : kTriangles_GrPrimitiveType; GrVertices vertices; vertices.init(primitiveType, vb, firstVertex, count); target->draw(vertices); } bool onCombineIfPossible(GrBatch*, const GrCaps&) override { return false; } TessellatingPathBatch(const GrColor& color, const SkPath& path, const GrStrokeInfo& stroke, const SkMatrix& viewMatrix, const SkRect& clipBounds) : INHERITED(ClassID()) , fColor(color) , fPath(path) , fStroke(stroke) , fViewMatrix(viewMatrix) { const SkRect& pathBounds = path.getBounds(); fClipBounds = clipBounds; // Because the clip bounds are used to add a contour for inverse fills, they must also // include the path bounds. fClipBounds.join(pathBounds); if (path.isInverseFillType()) { fBounds = fClipBounds; } else { fBounds = path.getBounds(); } if (!stroke.isFillStyle()) { SkScalar radius = SkScalarHalf(stroke.getWidth()); if (stroke.getJoin() == SkPaint::kMiter_Join) { SkScalar scale = stroke.getMiter(); if (scale > SK_Scalar1) { radius = SkScalarMul(radius, scale); } } fBounds.outset(radius, radius); } viewMatrix.mapRect(&fBounds); } GrColor fColor; SkPath fPath; GrStrokeInfo fStroke; SkMatrix fViewMatrix; SkRect fClipBounds; // in source space GrXPOverridesForBatch fPipelineInfo; typedef GrVertexBatch INHERITED; }; bool GrTessellatingPathRenderer::onDrawPath(const DrawPathArgs& args) { GR_AUDIT_TRAIL_AUTO_FRAME(args.fTarget->getAuditTrail(), "GrTessellatingPathRenderer::onDrawPath"); SkASSERT(!args.fAntiAlias); const GrRenderTarget* rt = args.fPipelineBuilder->getRenderTarget(); if (nullptr == rt) { return false; } SkIRect clipBoundsI; args.fPipelineBuilder->clip().getConservativeBounds(rt->width(), rt->height(), &clipBoundsI); SkRect clipBounds = SkRect::Make(clipBoundsI); SkMatrix vmi; if (!args.fViewMatrix->invert(&vmi)) { return false; } vmi.mapRect(&clipBounds); SkAutoTUnref<GrDrawBatch> batch(TessellatingPathBatch::Create(args.fColor, *args.fPath, *args.fStroke, *args.fViewMatrix, clipBounds)); args.fTarget->drawBatch(*args.fPipelineBuilder, batch); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// #ifdef GR_TEST_UTILS DRAW_BATCH_TEST_DEFINE(TesselatingPathBatch) { GrColor color = GrRandomColor(random); SkMatrix viewMatrix = GrTest::TestMatrixInvertible(random); SkPath path = GrTest::TestPath(random); SkRect clipBounds = GrTest::TestRect(random); SkMatrix vmi; bool result = viewMatrix.invert(&vmi); if (!result) { SkFAIL("Cannot invert matrix\n"); } vmi.mapRect(&clipBounds); GrStrokeInfo strokeInfo = GrTest::TestStrokeInfo(random); return TessellatingPathBatch::Create(color, path, strokeInfo, viewMatrix, clipBounds); } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgraphicsanchorlayout_p.h" QGraphicsAnchorLayout::QGraphicsAnchorLayout(QGraphicsLayoutItem *parent) : QGraphicsLayout(*new QGraphicsAnchorLayoutPrivate(), parent) { Q_D(QGraphicsAnchorLayout); d->createLayoutEdges(); } QGraphicsAnchorLayout::~QGraphicsAnchorLayout() { Q_D(QGraphicsAnchorLayout); for (int i = count() - 1; i >= 0; --i) { QGraphicsLayoutItem *item = d->items.at(i); removeAt(i); if (item) { if (item->ownedByLayout()) delete item; } } d->deleteLayoutEdges(); // ### make something better here qDeleteAll(d->itemCenterConstraints[0]); d->itemCenterConstraints[0].clear(); qDeleteAll(d->itemCenterConstraints[1]); d->itemCenterConstraints[1].clear(); Q_ASSERT(d->items.isEmpty()); Q_ASSERT(d->m_vertexList.isEmpty()); // ### Remove when integrated into Qt delete d_ptr; } void QGraphicsAnchorLayout::anchor(QGraphicsLayoutItem *firstItem, Edge firstEdge, QGraphicsLayoutItem *secondItem, Edge secondEdge, qreal spacing) { Q_D(QGraphicsAnchorLayout); if ((firstItem == 0) || (secondItem == 0)) { qWarning("QGraphicsAnchorLayout::anchor: " "Cannot anchor NULL items"); return; } if (firstItem == secondItem) { qWarning("QGraphicsAnchorLayout::anchor: " "Cannot anchor the item to itself"); return; } if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) { qWarning("QGraphicsAnchorLayout::anchor: " "Cannot anchor edges of different orientations"); return; } // In QGraphicsAnchorLayout, items are represented in its internal // graph as four anchors that connect: // - Left -> HCenter // - HCenter-> Right // - Top -> VCenter // - VCenter -> Bottom // Ensure that the internal anchors have been created for both items. if (firstItem != this && !d->items.contains(firstItem)) { d->createItemEdges(firstItem); d->addChildItem(firstItem); } if (secondItem != this && !d->items.contains(secondItem)) { d->createItemEdges(secondItem); d->addChildItem(secondItem); } // Use heuristics to find out what the user meant with this anchor. d->correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge); // Create actual anchor between firstItem and secondItem. AnchorData *data; if (spacing >= 0) { data = new AnchorData(spacing); d->addAnchor(firstItem, firstEdge, secondItem, secondEdge, data); } else { data = new AnchorData(-spacing); d->addAnchor(secondItem, secondEdge, firstItem, firstEdge, data); } invalidate(); } void QGraphicsAnchorLayout::removeAnchor(QGraphicsLayoutItem *firstItem, Edge firstEdge, QGraphicsLayoutItem *secondItem, Edge secondEdge) { Q_D(QGraphicsAnchorLayout); if ((firstItem == 0) || (secondItem == 0)) { qWarning("QGraphicsAnchorLayout::removeAnchor: " "Cannot remove anchor between NULL items"); return; } if (firstItem == secondItem) { qWarning("QGraphicsAnchorLayout::removeAnchor: " "Cannot remove anchor from the item to itself"); return; } if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) { qWarning("QGraphicsAnchorLayout::removeAnchor: " "Cannot remove anchor from edges of different orientations"); return; } d->removeAnchor(firstItem, firstEdge, secondItem, secondEdge); invalidate(); } void QGraphicsAnchorLayout::setSpacing(qreal spacing, Qt::Orientations orientations /*= Qt::Horizontal|Qt::Vertical*/) { Q_D(QGraphicsAnchorLayout); if (orientations & Qt::Horizontal) d->spacing[0] = spacing; if (orientations & Qt::Vertical) d->spacing[1] = spacing; } qreal QGraphicsAnchorLayout::spacing(Qt::Orientation orientation) const { Q_D(const QGraphicsAnchorLayout); return d->spacing[orientation & Qt::Vertical]; } void QGraphicsAnchorLayout::setGeometry(const QRectF &geom) { Q_D(QGraphicsAnchorLayout); QGraphicsLayout::setGeometry(geom); d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Horizontal); d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Vertical); d->setItemsGeometries(); } void QGraphicsAnchorLayout::removeAt(int index) { Q_D(QGraphicsAnchorLayout); QGraphicsLayoutItem *item = d->items.value(index); if (item) { d->items.remove(index); d->removeAnchors(item); item->setParentLayoutItem(0); } invalidate(); } int QGraphicsAnchorLayout::count() const { Q_D(const QGraphicsAnchorLayout); return d->items.size(); } QGraphicsLayoutItem *QGraphicsAnchorLayout::itemAt(int index) const { Q_D(const QGraphicsAnchorLayout); return d->items.value(index); } void QGraphicsAnchorLayout::invalidate() { Q_D(QGraphicsAnchorLayout); QGraphicsLayout::invalidate(); d->calculateGraphCacheDirty = 1; } QSizeF QGraphicsAnchorLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { Q_UNUSED(which); Q_UNUSED(constraint); Q_D(const QGraphicsAnchorLayout); // Some setup calculations are delayed until the information is // actually needed, avoiding unnecessary recalculations when // adding multiple anchors. // sizeHint() / effectiveSizeHint() already have a cache // mechanism, using invalidate() to force recalculation. However // sizeHint() is called three times after invalidation (for max, // min and pref), but we just need do our setup once. const_cast<QGraphicsAnchorLayoutPrivate *>(d)->calculateGraphs(); // ### apply constraint! QSizeF engineSizeHint( d->sizeHints[QGraphicsAnchorLayoutPrivate::Horizontal][which], d->sizeHints[QGraphicsAnchorLayoutPrivate::Vertical][which]); qreal left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); return engineSizeHint + QSizeF(left + right, top + bottom); } //////// DEBUG ///////// #include <QFile> void QGraphicsAnchorLayout::dumpGraph() { Q_D(QGraphicsAnchorLayout); QFile file(QString::fromAscii("anchorlayout.dot")); if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) qWarning("Could not write to %s", file.fileName().toLocal8Bit().constData()); QString dotContents = d->graph[0].serializeToDot(); file.write(dotContents.toLocal8Bit()); dotContents = d->graph[1].serializeToDot(); file.write(dotContents.toLocal8Bit()); file.close(); } <commit_msg>QGraphicsAnchorLayout: Bugfix in spacing() method<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgraphicsanchorlayout_p.h" QGraphicsAnchorLayout::QGraphicsAnchorLayout(QGraphicsLayoutItem *parent) : QGraphicsLayout(*new QGraphicsAnchorLayoutPrivate(), parent) { Q_D(QGraphicsAnchorLayout); d->createLayoutEdges(); } QGraphicsAnchorLayout::~QGraphicsAnchorLayout() { Q_D(QGraphicsAnchorLayout); for (int i = count() - 1; i >= 0; --i) { QGraphicsLayoutItem *item = d->items.at(i); removeAt(i); if (item) { if (item->ownedByLayout()) delete item; } } d->deleteLayoutEdges(); // ### make something better here qDeleteAll(d->itemCenterConstraints[0]); d->itemCenterConstraints[0].clear(); qDeleteAll(d->itemCenterConstraints[1]); d->itemCenterConstraints[1].clear(); Q_ASSERT(d->items.isEmpty()); Q_ASSERT(d->m_vertexList.isEmpty()); // ### Remove when integrated into Qt delete d_ptr; } void QGraphicsAnchorLayout::anchor(QGraphicsLayoutItem *firstItem, Edge firstEdge, QGraphicsLayoutItem *secondItem, Edge secondEdge, qreal spacing) { Q_D(QGraphicsAnchorLayout); if ((firstItem == 0) || (secondItem == 0)) { qWarning("QGraphicsAnchorLayout::anchor: " "Cannot anchor NULL items"); return; } if (firstItem == secondItem) { qWarning("QGraphicsAnchorLayout::anchor: " "Cannot anchor the item to itself"); return; } if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) { qWarning("QGraphicsAnchorLayout::anchor: " "Cannot anchor edges of different orientations"); return; } // In QGraphicsAnchorLayout, items are represented in its internal // graph as four anchors that connect: // - Left -> HCenter // - HCenter-> Right // - Top -> VCenter // - VCenter -> Bottom // Ensure that the internal anchors have been created for both items. if (firstItem != this && !d->items.contains(firstItem)) { d->createItemEdges(firstItem); d->addChildItem(firstItem); } if (secondItem != this && !d->items.contains(secondItem)) { d->createItemEdges(secondItem); d->addChildItem(secondItem); } // Use heuristics to find out what the user meant with this anchor. d->correctEdgeDirection(firstItem, firstEdge, secondItem, secondEdge); // Create actual anchor between firstItem and secondItem. AnchorData *data; if (spacing >= 0) { data = new AnchorData(spacing); d->addAnchor(firstItem, firstEdge, secondItem, secondEdge, data); } else { data = new AnchorData(-spacing); d->addAnchor(secondItem, secondEdge, firstItem, firstEdge, data); } invalidate(); } void QGraphicsAnchorLayout::removeAnchor(QGraphicsLayoutItem *firstItem, Edge firstEdge, QGraphicsLayoutItem *secondItem, Edge secondEdge) { Q_D(QGraphicsAnchorLayout); if ((firstItem == 0) || (secondItem == 0)) { qWarning("QGraphicsAnchorLayout::removeAnchor: " "Cannot remove anchor between NULL items"); return; } if (firstItem == secondItem) { qWarning("QGraphicsAnchorLayout::removeAnchor: " "Cannot remove anchor from the item to itself"); return; } if (d->edgeOrientation(secondEdge) != d->edgeOrientation(firstEdge)) { qWarning("QGraphicsAnchorLayout::removeAnchor: " "Cannot remove anchor from edges of different orientations"); return; } d->removeAnchor(firstItem, firstEdge, secondItem, secondEdge); invalidate(); } void QGraphicsAnchorLayout::setSpacing(qreal spacing, Qt::Orientations orientations /*= Qt::Horizontal|Qt::Vertical*/) { Q_D(QGraphicsAnchorLayout); if (orientations & Qt::Horizontal) d->spacing[0] = spacing; if (orientations & Qt::Vertical) d->spacing[1] = spacing; } qreal QGraphicsAnchorLayout::spacing(Qt::Orientation orientation) const { Q_D(const QGraphicsAnchorLayout); // Qt::Horizontal == 0x1, Qt::Vertical = 0x2 return d->spacing[orientation - 1]; } void QGraphicsAnchorLayout::setGeometry(const QRectF &geom) { Q_D(QGraphicsAnchorLayout); QGraphicsLayout::setGeometry(geom); d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Horizontal); d->calculateVertexPositions(QGraphicsAnchorLayoutPrivate::Vertical); d->setItemsGeometries(); } void QGraphicsAnchorLayout::removeAt(int index) { Q_D(QGraphicsAnchorLayout); QGraphicsLayoutItem *item = d->items.value(index); if (item) { d->items.remove(index); d->removeAnchors(item); item->setParentLayoutItem(0); } invalidate(); } int QGraphicsAnchorLayout::count() const { Q_D(const QGraphicsAnchorLayout); return d->items.size(); } QGraphicsLayoutItem *QGraphicsAnchorLayout::itemAt(int index) const { Q_D(const QGraphicsAnchorLayout); return d->items.value(index); } void QGraphicsAnchorLayout::invalidate() { Q_D(QGraphicsAnchorLayout); QGraphicsLayout::invalidate(); d->calculateGraphCacheDirty = 1; } QSizeF QGraphicsAnchorLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { Q_UNUSED(which); Q_UNUSED(constraint); Q_D(const QGraphicsAnchorLayout); // Some setup calculations are delayed until the information is // actually needed, avoiding unnecessary recalculations when // adding multiple anchors. // sizeHint() / effectiveSizeHint() already have a cache // mechanism, using invalidate() to force recalculation. However // sizeHint() is called three times after invalidation (for max, // min and pref), but we just need do our setup once. const_cast<QGraphicsAnchorLayoutPrivate *>(d)->calculateGraphs(); // ### apply constraint! QSizeF engineSizeHint( d->sizeHints[QGraphicsAnchorLayoutPrivate::Horizontal][which], d->sizeHints[QGraphicsAnchorLayoutPrivate::Vertical][which]); qreal left, top, right, bottom; getContentsMargins(&left, &top, &right, &bottom); return engineSizeHint + QSizeF(left + right, top + bottom); } //////// DEBUG ///////// #include <QFile> void QGraphicsAnchorLayout::dumpGraph() { Q_D(QGraphicsAnchorLayout); QFile file(QString::fromAscii("anchorlayout.dot")); if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) qWarning("Could not write to %s", file.fileName().toLocal8Bit().constData()); QString dotContents = d->graph[0].serializeToDot(); file.write(dotContents.toLocal8Bit()); dotContents = d->graph[1].serializeToDot(); file.write(dotContents.toLocal8Bit()); file.close(); } <|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. ===================================================================*/ // MITK #include "mitkGeometryDataReaderService.h" #include "mitkIOMimeTypes.h" // STL #include <iostream> #include <fstream> #include <mitkLocaleSwitch.h> #include <tinyxml.h> mitk::GeometryDataReaderService::GeometryDataReaderService() : AbstractFileReader( IOMimeTypes::GEOMETRY_DATA_MIMETYPE(), "MITK Geometry Data Reader") { RegisterService(); } mitk::GeometryDataReaderService::~GeometryDataReaderService() { } std::vector< itk::SmartPointer<mitk::BaseData> > mitk::GeometryDataReaderService::Read() { // Switch the current locale to "C" LocaleSwitch localeSwitch("C"); std::vector< itk::SmartPointer<BaseData> > result; InputStream stream(this); TiXmlDocument doc; stream >> doc; if (!doc.Error()) { TiXmlHandle docHandle( &doc ); for( TiXmlElement* currentGeometryElement = docHandle.FirstChild("GeometryData").FirstChild("Geometry3D").ToElement(); currentGeometryElement != NULL; currentGeometryElement = currentGeometryElement->NextSiblingElement()) { AffineTransform3D::MatrixType matrix; AffineTransform3D::OffsetType offset; bool isImageGeometry(false); unsigned int frameOfReferenceID(0); BaseGeometry::BoundsArrayType bounds; Point3D origin; Vector3D spacing; if ( TIXML_SUCCESS != currentGeometryElement->QueryUnsignedAttribute("FrameOfReferenceID", &frameOfReferenceID) ) { MITK_WARN << "Missing FrameOfReference for Geometry3D."; } if ( TIXML_SUCCESS != currentGeometryElement->QueryBoolAttribute("ImageGeometry", &isImageGeometry) ) { MITK_WARN << "Missing bool ImageGeometry for Geometry3D."; } // matrix if (TiXmlElement* matrixElem = currentGeometryElement->FirstChildElement("IndexToWorld")->ToElement()) { bool matrixComplete = true; matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_0_0", &matrix[0][0]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_0_1", &matrix[0][1]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_0_2", &matrix[0][2]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_1_0", &matrix[1][0]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_1_1", &matrix[1][1]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_1_2", &matrix[1][2]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_2_0", &matrix[2][0]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_2_1", &matrix[2][1]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_2_2", &matrix[2][2]); if (!matrixComplete) { MITK_ERROR << "Could not parse all Geometry3D matrix coefficients!"; break; } } else { MITK_ERROR << "Parse error: expected Matrix3x3 child below Geometry3D node"; } // offset if (TiXmlElement* offsetElem = currentGeometryElement->FirstChildElement("Offset")->ToElement()) { bool vectorComplete = true; vectorComplete &= TIXML_SUCCESS == offsetElem->QueryDoubleAttribute("x", &offset[0]); vectorComplete &= TIXML_SUCCESS == offsetElem->QueryDoubleAttribute("y", &offset[1]); vectorComplete &= TIXML_SUCCESS == offsetElem->QueryDoubleAttribute("z", &offset[2]); if (!vectorComplete) { MITK_ERROR << "Could not parse complete Geometry3D offset!"; break; } } else { MITK_ERROR << "Parse error: expected Offset3D child below Geometry3D node"; } // bounds if (TiXmlElement* boundsElem = currentGeometryElement->FirstChildElement("Bounds")->ToElement()) { bool vectorsComplete(true); if (TiXmlElement* minElem = boundsElem->FirstChildElement("Min")->ToElement()) { vectorsComplete &= TIXML_SUCCESS == minElem->QueryDoubleAttribute("x", &bounds[0]); vectorsComplete &= TIXML_SUCCESS == minElem->QueryDoubleAttribute("y", &bounds[2]); vectorsComplete &= TIXML_SUCCESS == minElem->QueryDoubleAttribute("z", &bounds[4]); } else { vectorsComplete = false; } if (TiXmlElement* maxElem = boundsElem->FirstChildElement("Max")->ToElement()) { vectorsComplete &= TIXML_SUCCESS == maxElem->QueryDoubleAttribute("x", &bounds[1]); vectorsComplete &= TIXML_SUCCESS == maxElem->QueryDoubleAttribute("y", &bounds[3]); vectorsComplete &= TIXML_SUCCESS == maxElem->QueryDoubleAttribute("z", &bounds[5]); } else { vectorsComplete = false; } if (!vectorsComplete) { MITK_ERROR << "Could not parse complete Geometry3D bounds!"; break; } } // origin + spacing if (TiXmlElement* originElem = currentGeometryElement->FirstChildElement("Origin")->ToElement()) { bool vectorComplete = true; vectorComplete &= TIXML_SUCCESS == originElem->QueryDoubleAttribute("x", &origin[0]); vectorComplete &= TIXML_SUCCESS == originElem->QueryDoubleAttribute("y", &origin[1]); vectorComplete &= TIXML_SUCCESS == originElem->QueryDoubleAttribute("z", &origin[2]); if (!vectorComplete) { MITK_ERROR << "Could not parse complete Geometry3D origin!"; break; } } else { MITK_ERROR << "Parse error: expected Origin child below Geometry3D node"; } if (TiXmlElement* spacingElem = currentGeometryElement->FirstChildElement("Spacing")->ToElement()) { bool vectorComplete = true; vectorComplete &= TIXML_SUCCESS == spacingElem->QueryDoubleAttribute("x", &spacing[0]); vectorComplete &= TIXML_SUCCESS == spacingElem->QueryDoubleAttribute("y", &spacing[1]); vectorComplete &= TIXML_SUCCESS == spacingElem->QueryDoubleAttribute("z", &spacing[2]); if (!vectorComplete) { MITK_ERROR << "Could not parse complete Geometry3D spacing!"; break; } } else { MITK_ERROR << "Parse error: expected Spacing child below Geometry3D node"; } // build GeometryData from matrix/offset AffineTransform3D::Pointer newTransform = AffineTransform3D::New(); newTransform->SetMatrix( matrix ); newTransform->SetOffset( offset ); Geometry3D::Pointer newGeometry = Geometry3D::New(); newGeometry->SetFrameOfReferenceID( frameOfReferenceID ); newGeometry->SetImageGeometry(isImageGeometry); newGeometry->SetIndexToWorldTransform( newTransform ); newGeometry->SetBounds(bounds); newGeometry->SetOrigin(origin); newGeometry->SetSpacing( spacing ); // TODO parameter?! GeometryData::Pointer newGeometryData = GeometryData::New(); newGeometryData->SetGeometry( newGeometry ); result.push_back( newGeometryData.GetPointer() ); } } else { mitkThrow() << "Parsing error at line " << doc.ErrorRow() << ", col " << doc.ErrorCol() << ": " << doc.ErrorDesc(); } return result; } mitk::GeometryDataReaderService::GeometryDataReaderService(const mitk::GeometryDataReaderService& other) : mitk::AbstractFileReader(other) { } mitk::GeometryDataReaderService* mitk::GeometryDataReaderService::Clone() const { return new GeometryDataReaderService(*this); } <commit_msg>Minimize reader and writer, do not store redundant information<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. ===================================================================*/ // MITK #include "mitkGeometryDataReaderService.h" #include "mitkIOMimeTypes.h" // STL #include <iostream> #include <fstream> #include <mitkLocaleSwitch.h> #include <tinyxml.h> mitk::GeometryDataReaderService::GeometryDataReaderService() : AbstractFileReader( IOMimeTypes::GEOMETRY_DATA_MIMETYPE(), "MITK Geometry Data Reader") { RegisterService(); } mitk::GeometryDataReaderService::~GeometryDataReaderService() { } std::vector< itk::SmartPointer<mitk::BaseData> > mitk::GeometryDataReaderService::Read() { // Switch the current locale to "C" LocaleSwitch localeSwitch("C"); std::vector< itk::SmartPointer<BaseData> > result; InputStream stream(this); TiXmlDocument doc; stream >> doc; if (!doc.Error()) { TiXmlHandle docHandle( &doc ); for( TiXmlElement* currentGeometryElement = docHandle.FirstChild("GeometryData").FirstChild("Geometry3D").ToElement(); currentGeometryElement != NULL; currentGeometryElement = currentGeometryElement->NextSiblingElement()) { AffineTransform3D::MatrixType matrix; AffineTransform3D::OffsetType offset; bool isImageGeometry(false); unsigned int frameOfReferenceID(0); BaseGeometry::BoundsArrayType bounds; if ( TIXML_SUCCESS != currentGeometryElement->QueryUnsignedAttribute("FrameOfReferenceID", &frameOfReferenceID) ) { MITK_WARN << "Missing FrameOfReference for Geometry3D."; } if ( TIXML_SUCCESS != currentGeometryElement->QueryBoolAttribute("ImageGeometry", &isImageGeometry) ) { MITK_WARN << "Missing bool ImageGeometry for Geometry3D."; } // matrix if (TiXmlElement* matrixElem = currentGeometryElement->FirstChildElement("IndexToWorld")->ToElement()) { bool matrixComplete = true; matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_0_0", &matrix[0][0]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_0_1", &matrix[0][1]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_0_2", &matrix[0][2]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_1_0", &matrix[1][0]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_1_1", &matrix[1][1]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_1_2", &matrix[1][2]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_2_0", &matrix[2][0]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_2_1", &matrix[2][1]); matrixComplete &= TIXML_SUCCESS == matrixElem->QueryDoubleAttribute("m_2_2", &matrix[2][2]); if (!matrixComplete) { MITK_ERROR << "Could not parse all Geometry3D matrix coefficients!"; break; } } else { MITK_ERROR << "Parse error: expected Matrix3x3 child below Geometry3D node"; } // offset if (TiXmlElement* offsetElem = currentGeometryElement->FirstChildElement("Offset")->ToElement()) { bool vectorComplete = true; vectorComplete &= TIXML_SUCCESS == offsetElem->QueryDoubleAttribute("x", &offset[0]); vectorComplete &= TIXML_SUCCESS == offsetElem->QueryDoubleAttribute("y", &offset[1]); vectorComplete &= TIXML_SUCCESS == offsetElem->QueryDoubleAttribute("z", &offset[2]); if (!vectorComplete) { MITK_ERROR << "Could not parse complete Geometry3D offset!"; break; } } else { MITK_ERROR << "Parse error: expected Offset3D child below Geometry3D node"; } // bounds if (TiXmlElement* boundsElem = currentGeometryElement->FirstChildElement("Bounds")->ToElement()) { bool vectorsComplete(true); if (TiXmlElement* minElem = boundsElem->FirstChildElement("Min")->ToElement()) { vectorsComplete &= TIXML_SUCCESS == minElem->QueryDoubleAttribute("x", &bounds[0]); vectorsComplete &= TIXML_SUCCESS == minElem->QueryDoubleAttribute("y", &bounds[2]); vectorsComplete &= TIXML_SUCCESS == minElem->QueryDoubleAttribute("z", &bounds[4]); } else { vectorsComplete = false; } if (TiXmlElement* maxElem = boundsElem->FirstChildElement("Max")->ToElement()) { vectorsComplete &= TIXML_SUCCESS == maxElem->QueryDoubleAttribute("x", &bounds[1]); vectorsComplete &= TIXML_SUCCESS == maxElem->QueryDoubleAttribute("y", &bounds[3]); vectorsComplete &= TIXML_SUCCESS == maxElem->QueryDoubleAttribute("z", &bounds[5]); } else { vectorsComplete = false; } if (!vectorsComplete) { MITK_ERROR << "Could not parse complete Geometry3D bounds!"; break; } } // build GeometryData from matrix/offset AffineTransform3D::Pointer newTransform = AffineTransform3D::New(); newTransform->SetMatrix( matrix ); newTransform->SetOffset( offset ); Geometry3D::Pointer newGeometry = Geometry3D::New(); newGeometry->SetFrameOfReferenceID( frameOfReferenceID ); newGeometry->SetImageGeometry(isImageGeometry); newGeometry->SetIndexToWorldTransform( newTransform ); newGeometry->SetBounds(bounds); GeometryData::Pointer newGeometryData = GeometryData::New(); newGeometryData->SetGeometry( newGeometry ); result.push_back( newGeometryData.GetPointer() ); } } else { mitkThrow() << "Parsing error at line " << doc.ErrorRow() << ", col " << doc.ErrorCol() << ": " << doc.ErrorDesc(); } return result; } mitk::GeometryDataReaderService::GeometryDataReaderService(const mitk::GeometryDataReaderService& other) : mitk::AbstractFileReader(other) { } mitk::GeometryDataReaderService* mitk::GeometryDataReaderService::Clone() const { return new GeometryDataReaderService(*this); } <|endoftext|>
<commit_before>/*! \file named_mutex.cpp \brief Named mutex synchronization primitive implementation \author Ivan Shynkarenka \date 15.04.2016 \copyright MIT License */ #include "threads/named_mutex.h" #include "errors/exceptions.h" #include "errors/fatal.h" #include "system/shared_type.h" #include <algorithm> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #undef max #undef min #elif defined(unix) || defined(__unix) || defined(__unix__) #include <pthread.h> #endif namespace CppCommon { class NamedMutex::Impl { public: Impl(const std::string& name) #if defined(unix) || defined(__unix) || defined(__unix__) : _shared(name, sizeof(NamedMutexHeader)) #endif { #if defined(_WIN32) || defined(_WIN64) _mutex = CreateMutexA(nullptr, FALSE, name.c_str()); if (_mutex == nullptr) throwex SystemException("Failed to create a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) pthread_mutexattr_t attribute; int result = pthread_mutexattr_init(&attribute); if (result != 0) throwex SystemException("Failed to initialize a named mutex attribute!", result); result = pthread_mutexattr_setpshared(&attribute, PTHREAD_PROCESS_SHARED); if (result != 0) throwex SystemException("Failed to set a named mutex process shared attribute!", result); result = pthread_mutex_init(&_shared->mutex, &attribute); if (result != 0) throwex SystemException("Failed to initialize a named mutex!", result); result = pthread_mutexattr_destroy(&attribute); if (result != 0) throwex SystemException("Failed to destroy a named mutex attribute!", result); #endif } ~Impl() { #if defined(_WIN32) || defined(_WIN64) if (!CloseHandle(_mutex)) fatality("Failed to close a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) if (_shared.owner()) { int result = pthread_mutex_destroy(&_shared->mutex); if (result != 0) fatality("Failed to destroy a named mutex!", result); } #endif } bool TryLock() { #if defined(_WIN32) || defined(_WIN64) DWORD result = WaitForSingleObject(_mutex, 0); if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT)) throwex SystemException("Failed to try lock a named mutex!"); return (result == WAIT_OBJECT_0); #elif defined(unix) || defined(__unix) || defined(__unix__) int result = pthread_mutex_trylock(&_shared->mutex); if ((result != 0) && (result != EBUSY)) throwex SystemException("Failed to try lock a named mutex!", result); return (result == 0); #endif } bool TryLockFor(int64_t nanoseconds) { #if defined(_WIN32) || defined(_WIN64) DWORD result = WaitForSingleObject(_mutex, (DWORD)std::max(1ll, nanoseconds / 1000000000)); if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT)) throwex SystemException("Failed to try lock a named mutex for the given timeout!"); return (result == WAIT_OBJECT_0); #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timeout; timeout.tv_sec = nanoseconds / 1000000000; timeout.tv_nsec = nanoseconds % 1000000000; int result = pthread_mutex_timedlock(&_shared->mutex, &timeout); if ((result != 0) && (result != ETIMEDOUT)) throwex SystemException("Failed to try lock a named mutex for the given timeout!", result); return (result == 0); #endif } void Lock() { #if defined(_WIN32) || defined(_WIN64) DWORD result = WaitForSingleObject(_mutex, INFINITE); if (result != WAIT_OBJECT_0) throwex SystemException("Failed to lock a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) int result = pthread_mutex_lock(&_shared->mutex); if (result != 0) throwex SystemException("Failed to lock a named mutex!", result); #endif } void Unlock() { #if defined(_WIN32) || defined(_WIN64) if (!ReleaseMutex(_mutex)) throwex SystemException("Failed to unlock a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) int result = pthread_mutex_unlock(&_shared->mutex); if (result != 0) throwex SystemException("Failed to unlock a named mutex!", result); #endif } private: #if defined(_WIN32) || defined(_WIN64) HANDLE _mutex; #elif defined(unix) || defined(__unix) || defined(__unix__) // Shared mutex structure struct MutexHeader { pthread_mutex_t mutex; }; // Shared mutex structure wrapper SharedType<MutexHeader> _shared; #endif }; NamedMutex::NamedMutex(const std::string& name) : _pimpl(new Impl(name)), _name(name) { } NamedMutex::~NamedMutex() { } bool NamedMutex::TryLock() { return _pimpl->TryLock(); } bool NamedMutex::TryLockFor(int64_t nanoseconds) { return _pimpl->TryLockFor(nanoseconds); } void NamedMutex::Lock() { _pimpl->Lock(); } void NamedMutex::Unlock() { _pimpl->Unlock(); } } // namespace CppCommon <commit_msg>Update<commit_after>/*! \file named_mutex.cpp \brief Named mutex synchronization primitive implementation \author Ivan Shynkarenka \date 15.04.2016 \copyright MIT License */ #include "threads/named_mutex.h" #include "errors/exceptions.h" #include "errors/fatal.h" #include "system/shared_type.h" #include <algorithm> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> #undef max #undef min #elif defined(unix) || defined(__unix) || defined(__unix__) #include <pthread.h> #endif namespace CppCommon { class NamedMutex::Impl { public: Impl(const std::string& name) #if defined(unix) || defined(__unix) || defined(__unix__) : _shared(name, sizeof(MutexHeader)) #endif { #if defined(_WIN32) || defined(_WIN64) _mutex = CreateMutexA(nullptr, FALSE, name.c_str()); if (_mutex == nullptr) throwex SystemException("Failed to create a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) pthread_mutexattr_t attribute; int result = pthread_mutexattr_init(&attribute); if (result != 0) throwex SystemException("Failed to initialize a named mutex attribute!", result); result = pthread_mutexattr_setpshared(&attribute, PTHREAD_PROCESS_SHARED); if (result != 0) throwex SystemException("Failed to set a named mutex process shared attribute!", result); result = pthread_mutex_init(&_shared->mutex, &attribute); if (result != 0) throwex SystemException("Failed to initialize a named mutex!", result); result = pthread_mutexattr_destroy(&attribute); if (result != 0) throwex SystemException("Failed to destroy a named mutex attribute!", result); #endif } ~Impl() { #if defined(_WIN32) || defined(_WIN64) if (!CloseHandle(_mutex)) fatality("Failed to close a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) if (_shared.owner()) { int result = pthread_mutex_destroy(&_shared->mutex); if (result != 0) fatality("Failed to destroy a named mutex!", result); } #endif } bool TryLock() { #if defined(_WIN32) || defined(_WIN64) DWORD result = WaitForSingleObject(_mutex, 0); if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT)) throwex SystemException("Failed to try lock a named mutex!"); return (result == WAIT_OBJECT_0); #elif defined(unix) || defined(__unix) || defined(__unix__) int result = pthread_mutex_trylock(&_shared->mutex); if ((result != 0) && (result != EBUSY)) throwex SystemException("Failed to try lock a named mutex!", result); return (result == 0); #endif } bool TryLockFor(int64_t nanoseconds) { #if defined(_WIN32) || defined(_WIN64) DWORD result = WaitForSingleObject(_mutex, (DWORD)std::max(1ll, nanoseconds / 1000000000)); if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT)) throwex SystemException("Failed to try lock a named mutex for the given timeout!"); return (result == WAIT_OBJECT_0); #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timeout; timeout.tv_sec = nanoseconds / 1000000000; timeout.tv_nsec = nanoseconds % 1000000000; int result = pthread_mutex_timedlock(&_shared->mutex, &timeout); if ((result != 0) && (result != ETIMEDOUT)) throwex SystemException("Failed to try lock a named mutex for the given timeout!", result); return (result == 0); #endif } void Lock() { #if defined(_WIN32) || defined(_WIN64) DWORD result = WaitForSingleObject(_mutex, INFINITE); if (result != WAIT_OBJECT_0) throwex SystemException("Failed to lock a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) int result = pthread_mutex_lock(&_shared->mutex); if (result != 0) throwex SystemException("Failed to lock a named mutex!", result); #endif } void Unlock() { #if defined(_WIN32) || defined(_WIN64) if (!ReleaseMutex(_mutex)) throwex SystemException("Failed to unlock a named mutex!"); #elif defined(unix) || defined(__unix) || defined(__unix__) int result = pthread_mutex_unlock(&_shared->mutex); if (result != 0) throwex SystemException("Failed to unlock a named mutex!", result); #endif } private: #if defined(_WIN32) || defined(_WIN64) HANDLE _mutex; #elif defined(unix) || defined(__unix) || defined(__unix__) // Shared mutex structure struct MutexHeader { pthread_mutex_t mutex; }; // Shared mutex structure wrapper SharedType<MutexHeader> _shared; #endif }; NamedMutex::NamedMutex(const std::string& name) : _pimpl(new Impl(name)), _name(name) { } NamedMutex::~NamedMutex() { } bool NamedMutex::TryLock() { return _pimpl->TryLock(); } bool NamedMutex::TryLockFor(int64_t nanoseconds) { return _pimpl->TryLockFor(nanoseconds); } void NamedMutex::Lock() { _pimpl->Lock(); } void NamedMutex::Unlock() { _pimpl->Unlock(); } } // namespace CppCommon <|endoftext|>
<commit_before>/************************************************************************************ * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***********************************************************************************/ #include "localhistorycollection.h" //Qt #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QHash> #include <QtCore/QStandardPaths> #include <QtCore/QStandardPaths> #include <QtCore/QUrl> //Ring #include "call.h" #include "media/media.h" #include "media/recording.h" #include "media/avrecording.h" #include "account.h" #include "person.h" #include "certificate.h" #include "contactmethod.h" #include "categorizedhistorymodel.h" #include "globalinstances.h" #include "interfaces/pixmapmanipulatori.h" class LocalHistoryEditor final : public CollectionEditor<Call> { public: LocalHistoryEditor(CollectionMediator<Call>* m, LocalHistoryCollection* parent); virtual bool save ( const Call* item ) override; virtual bool remove ( const Call* item ) override; virtual bool edit ( Call* item ) override; virtual bool addNew ( Call* item ) override; virtual bool addExisting( const Call* item ) override; private: virtual QVector<Call*> items() const override; //Helpers void saveCall(QTextStream& stream, const Call* call); bool regenFile(const Call* toIgnore); //Attributes QVector<Call*> m_lItems; LocalHistoryCollection* m_pCollection; }; LocalHistoryEditor::LocalHistoryEditor(CollectionMediator<Call>* m, LocalHistoryCollection* parent) : CollectionEditor<Call>(m),m_pCollection(parent) { } LocalHistoryCollection::LocalHistoryCollection(CollectionMediator<Call>* mediator) : CollectionInterface(new LocalHistoryEditor(mediator,this)),m_pMediator(mediator) { // setObjectName("LocalHistoryCollection"); } LocalHistoryCollection::~LocalHistoryCollection() { } void LocalHistoryEditor::saveCall(QTextStream& stream, const Call* call) { const QString direction = (call->direction()==Call::Direction::INCOMING)? Call::HistoryStateName::INCOMING : Call::HistoryStateName::OUTGOING; const Account* a = call->account(); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CALLID ).arg(call->historyId() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::TIMESTAMP_START ).arg(call->startTimeStamp() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::TIMESTAMP_STOP ).arg(call->stopTimeStamp() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::ACCOUNT_ID ).arg(a?QString(a->id()):"" ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::DISPLAY_NAME ).arg(call->peerName() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::PEER_NUMBER ).arg(call->peerContactMethod()->uri() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::DIRECTION ).arg(direction ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::MISSED ).arg(call->isMissed() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CONTACT_USED ).arg(false );//TODO //TODO handle more than one recording if (call->hasRecording(Media::Media::Type::AUDIO,Media::Media::Direction::IN)) { stream << QString("%1=%2\n").arg(Call::HistoryMapFields::RECORDING_PATH ).arg(((Media::AVRecording*)call->recordings(Media::Media::Type::AUDIO,Media::Media::Direction::IN)[0])->path().path()); } if (call->peerContactMethod()->contact()) { stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CONTACT_UID ).arg( QString(call->peerContactMethod()->contact()->uid()) ); } if (call->certificate()) stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CERT_PATH).arg(call->certificate()->path()); stream << "\n"; stream.flush(); } bool LocalHistoryEditor::regenFile(const Call* toIgnore) { QDir dir(QString('/')); dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + QString()); QFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') +"history.ini"); if ( file.open(QIODevice::WriteOnly | QIODevice::Text) ) { QTextStream stream(&file); for (const Call* c : CategorizedHistoryModel::instance()->getHistoryCalls()) { if (c != toIgnore) saveCall(stream, c); } file.close(); return true; } return false; } bool LocalHistoryEditor::save(const Call* call) { if (call->collection()->editor<Call>() != this) return addNew(const_cast<Call*>(call)); return regenFile(nullptr); } bool LocalHistoryEditor::remove(const Call* item) { if (regenFile(item)) { mediator()->removeItem(item); return true; } return false; } bool LocalHistoryEditor::edit( Call* item) { Q_UNUSED(item) return false; } bool LocalHistoryEditor::addNew( Call* call) { QDir dir(QString('/')); dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + QString()); if ((call->collection() && call->collection()->editor<Call>() == this) || call->historyId().isEmpty()) return false; //TODO support \r and \n\r end of line QFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/')+"history.ini"); if ( file.open(QIODevice::Append | QIODevice::Text) ) { QTextStream streamFileOut(&file); saveCall(streamFileOut, call); file.close(); const_cast<Call*>(call)->setCollection(m_pCollection); addExisting(call); return true; } else qWarning() << "Unable to save history"; return false; } bool LocalHistoryEditor::addExisting(const Call* item) { m_lItems << const_cast<Call*>(item); mediator()->addItem(item); return true; } QVector<Call*> LocalHistoryEditor::items() const { return m_lItems; } QString LocalHistoryCollection::name () const { return QObject::tr("Local history"); } QString LocalHistoryCollection::category () const { return QObject::tr("History"); } QVariant LocalHistoryCollection::icon() const { return GlobalInstances::pixmapManipulator().collectionIcon(this,Interfaces::PixmapManipulatorI::CollectionIconHint::HISTORY); } bool LocalHistoryCollection::isEnabled() const { return true; } bool LocalHistoryCollection::load() { QFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') +"history.ini"); if ( file.open(QIODevice::ReadOnly | QIODevice::Text) ) { QMap<QString,QString> hc; QStringList lines; while (!file.atEnd()) lines << file.readLine().trimmed(); file.close(); for (const QString& line : lines) { //The item is complete if ((line.isEmpty() || !line.size()) && hc.size()) { Call* pastCall = Call::buildHistoryCall(hc); if (pastCall->peerName().isEmpty()) { pastCall->setPeerName(QObject::tr("Unknown")); } pastCall->setCollection(this); editor<Call>()->addExisting(pastCall); hc.clear(); } // Add to the current set else { const int idx = line.indexOf("="); if (idx >= 0) hc[line.left(idx)] = line.right(line.size()-idx-1); } } return true; } else qWarning() << "History doesn't exist or is not readable"; return false; } bool LocalHistoryCollection::reload() { return false; } FlagPack<CollectionInterface::SupportedFeatures> LocalHistoryCollection::supportedFeatures() const { return CollectionInterface::SupportedFeatures::NONE | CollectionInterface::SupportedFeatures::LOAD | CollectionInterface::SupportedFeatures::CLEAR | CollectionInterface::SupportedFeatures::REMOVE | CollectionInterface::SupportedFeatures::MANAGEABLE | CollectionInterface::SupportedFeatures::ADD ; } bool LocalHistoryCollection::clear() { QFile::remove(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') +"history.ini"); return true; } QByteArray LocalHistoryCollection::id() const { return "mhb"; } <commit_msg>history: prevent Unknown peer name<commit_after>/************************************************************************************ * Copyright (C) 2014-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***********************************************************************************/ #include "localhistorycollection.h" //Qt #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QHash> #include <QtCore/QStandardPaths> #include <QtCore/QStandardPaths> #include <QtCore/QUrl> //Ring #include "call.h" #include "media/media.h" #include "media/recording.h" #include "media/avrecording.h" #include "account.h" #include "person.h" #include "certificate.h" #include "contactmethod.h" #include "categorizedhistorymodel.h" #include "globalinstances.h" #include "interfaces/pixmapmanipulatori.h" class LocalHistoryEditor final : public CollectionEditor<Call> { public: LocalHistoryEditor(CollectionMediator<Call>* m, LocalHistoryCollection* parent); virtual bool save ( const Call* item ) override; virtual bool remove ( const Call* item ) override; virtual bool edit ( Call* item ) override; virtual bool addNew ( Call* item ) override; virtual bool addExisting( const Call* item ) override; private: virtual QVector<Call*> items() const override; //Helpers void saveCall(QTextStream& stream, const Call* call); bool regenFile(const Call* toIgnore); //Attributes QVector<Call*> m_lItems; LocalHistoryCollection* m_pCollection; }; LocalHistoryEditor::LocalHistoryEditor(CollectionMediator<Call>* m, LocalHistoryCollection* parent) : CollectionEditor<Call>(m),m_pCollection(parent) { } LocalHistoryCollection::LocalHistoryCollection(CollectionMediator<Call>* mediator) : CollectionInterface(new LocalHistoryEditor(mediator,this)),m_pMediator(mediator) { // setObjectName("LocalHistoryCollection"); } LocalHistoryCollection::~LocalHistoryCollection() { } void LocalHistoryEditor::saveCall(QTextStream& stream, const Call* call) { const QString direction = (call->direction()==Call::Direction::INCOMING)? Call::HistoryStateName::INCOMING : Call::HistoryStateName::OUTGOING; const Account* a = call->account(); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CALLID ).arg(call->historyId() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::TIMESTAMP_START ).arg(call->startTimeStamp() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::TIMESTAMP_STOP ).arg(call->stopTimeStamp() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::ACCOUNT_ID ).arg(a?QString(a->id()):"" ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::DISPLAY_NAME ).arg(call->peerName() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::PEER_NUMBER ).arg(call->peerContactMethod()->uri() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::DIRECTION ).arg(direction ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::MISSED ).arg(call->isMissed() ); stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CONTACT_USED ).arg(false );//TODO //TODO handle more than one recording if (call->hasRecording(Media::Media::Type::AUDIO,Media::Media::Direction::IN)) { stream << QString("%1=%2\n").arg(Call::HistoryMapFields::RECORDING_PATH ).arg(((Media::AVRecording*)call->recordings(Media::Media::Type::AUDIO,Media::Media::Direction::IN)[0])->path().path()); } if (call->peerContactMethod()->contact()) { stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CONTACT_UID ).arg( QString(call->peerContactMethod()->contact()->uid()) ); } if (call->certificate()) stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CERT_PATH).arg(call->certificate()->path()); stream << "\n"; stream.flush(); } bool LocalHistoryEditor::regenFile(const Call* toIgnore) { QDir dir(QString('/')); dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + QString()); QFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') +"history.ini"); if ( file.open(QIODevice::WriteOnly | QIODevice::Text) ) { QTextStream stream(&file); for (const Call* c : CategorizedHistoryModel::instance()->getHistoryCalls()) { if (c != toIgnore) saveCall(stream, c); } file.close(); return true; } return false; } bool LocalHistoryEditor::save(const Call* call) { if (call->collection()->editor<Call>() != this) return addNew(const_cast<Call*>(call)); return regenFile(nullptr); } bool LocalHistoryEditor::remove(const Call* item) { if (regenFile(item)) { mediator()->removeItem(item); return true; } return false; } bool LocalHistoryEditor::edit( Call* item) { Q_UNUSED(item) return false; } bool LocalHistoryEditor::addNew( Call* call) { QDir dir(QString('/')); dir.mkpath(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') + QString()); if ((call->collection() && call->collection()->editor<Call>() == this) || call->historyId().isEmpty()) return false; //TODO support \r and \n\r end of line QFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/')+"history.ini"); if ( file.open(QIODevice::Append | QIODevice::Text) ) { QTextStream streamFileOut(&file); saveCall(streamFileOut, call); file.close(); const_cast<Call*>(call)->setCollection(m_pCollection); addExisting(call); return true; } else qWarning() << "Unable to save history"; return false; } bool LocalHistoryEditor::addExisting(const Call* item) { m_lItems << const_cast<Call*>(item); mediator()->addItem(item); return true; } QVector<Call*> LocalHistoryEditor::items() const { return m_lItems; } QString LocalHistoryCollection::name () const { return QObject::tr("Local history"); } QString LocalHistoryCollection::category () const { return QObject::tr("History"); } QVariant LocalHistoryCollection::icon() const { return GlobalInstances::pixmapManipulator().collectionIcon(this,Interfaces::PixmapManipulatorI::CollectionIconHint::HISTORY); } bool LocalHistoryCollection::isEnabled() const { return true; } bool LocalHistoryCollection::load() { QFile file(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') +"history.ini"); if ( file.open(QIODevice::ReadOnly | QIODevice::Text) ) { QMap<QString,QString> hc; QStringList lines; while (!file.atEnd()) lines << file.readLine().trimmed(); file.close(); for (const QString& line : lines) { //The item is complete if ((line.isEmpty() || !line.size()) && hc.size()) { Call* pastCall = Call::buildHistoryCall(hc); pastCall->setCollection(this); editor<Call>()->addExisting(pastCall); hc.clear(); } // Add to the current set else { const int idx = line.indexOf("="); if (idx >= 0) hc[line.left(idx)] = line.right(line.size()-idx-1); } } return true; } else qWarning() << "History doesn't exist or is not readable"; return false; } bool LocalHistoryCollection::reload() { return false; } FlagPack<CollectionInterface::SupportedFeatures> LocalHistoryCollection::supportedFeatures() const { return CollectionInterface::SupportedFeatures::NONE | CollectionInterface::SupportedFeatures::LOAD | CollectionInterface::SupportedFeatures::CLEAR | CollectionInterface::SupportedFeatures::REMOVE | CollectionInterface::SupportedFeatures::MANAGEABLE | CollectionInterface::SupportedFeatures::ADD ; } bool LocalHistoryCollection::clear() { QFile::remove(QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/') +"history.ini"); return true; } QByteArray LocalHistoryCollection::id() const { return "mhb"; } <|endoftext|>
<commit_before>/*! $Id: ModbusTCPMaster.cc,v 1.3 2009/02/07 13:27:01 vpashka Exp $ */ // ------------------------------------------------------------------------- #include <string.h> #include <errno.h> #include <iostream> #include <sstream> #include "Exceptions.h" #include "modbus/ModbusTCPMaster.h" #include "modbus/ModbusTCPCore.h" // ------------------------------------------------------------------------- using namespace std; using namespace ModbusRTU; using namespace UniSetTypes; // ------------------------------------------------------------------------- ModbusTCPMaster::ModbusTCPMaster(): tcp(0), iaddr("") { setCRCNoCheckit(true); } // ------------------------------------------------------------------------- ModbusTCPMaster::~ModbusTCPMaster() { if( isConnection() ) disconnect(); } // ------------------------------------------------------------------------- int ModbusTCPMaster::getNextData( unsigned char* buf, int len ) { return ModbusTCPCore::getNextData(buf,len,qrecv,tcp); } // ------------------------------------------------------------------------- void ModbusTCPMaster::setChannelTimeout( timeout_t msec ) { if( tcp ) tcp->setTimeout(msec); } // ------------------------------------------------------------------------- mbErrCode ModbusTCPMaster::sendData( unsigned char* buf, int len ) { return ModbusTCPCore::sendData(buf,len,tcp); } // ------------------------------------------------------------------------- int ModbusTCPMaster::nTransaction = 0; mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg, ModbusMessage& reply, timeout_t timeout ) { // if( !isConnection() ) if( iaddr.empty() ) { dlog[Debug::WARN] << "(query): not connection to server..." << endl; return erHardwareError; } reconnect(); assert(timeout); ptTimeout.setTiming(timeout); ost::Thread::setException(ost::Thread::throwException); try { if( nTransaction >= numeric_limits<int>::max() ) nTransaction = 0; ModbusTCP::MBAPHeader mh; mh.tID = ++nTransaction; mh.pID = 0; mh.len = msg.len + szModbusHeader; // mh.uID = addr; if( crcNoCheckit ) mh.len -= szCRC; mh.swapdata(); // send TCP header if( dlog.debugging(Debug::INFO) ) { dlog[Debug::INFO] << "(ModbusTCPMaster::query): send tcp header(" << sizeof(mh) <<"): "; mbPrintMessage( dlog, (ModbusByte*)(&mh), sizeof(mh)); dlog(Debug::INFO) << endl; } (*tcp) << mh; mh.swapdata(); // send PDU mbErrCode res = send(msg); if( res!=erNoError ) return res; if( !tcp->isPending(ost::Socket::pendingOutput,timeout) ) return erTimeOut; if( timeout != UniSetTimer::WaitUpTime ) { timeout = ptTimeout.getLeft(timeout); if( timeout == 0 ) return erTimeOut; ptTimeout.setTiming(timeout); } // чистим очередь while( !qrecv.empty() ) qrecv.pop(); if( tcp->isPending(ost::Socket::pendingInput,timeout) ) { ModbusTCP::MBAPHeader rmh; int ret = getNextData((unsigned char*)(&rmh),sizeof(rmh)); if( dlog.debugging(Debug::INFO) ) { dlog[Debug::INFO] << "(ModbusTCPMaster::query): recv tcp header(" << ret << "): "; mbPrintMessage( dlog, (ModbusByte*)(&rmh), sizeof(rmh)); dlog(Debug::INFO) << endl; } if( ret < (int)sizeof(rmh) ) return erHardwareError; rmh.swapdata(); if( rmh.tID != mh.tID ) return erBadReplyNodeAddress; if( rmh.pID != 0 ) return erBadReplyNodeAddress; // return recv(addr,msg.func,reply,timeout); // msg.addr = rmh.uID; // return recv_pdu(msg.func,reply,timeout); } return erTimeOut; } catch( ModbusRTU::mbException& ex ) { dlog[Debug::WARN] << "(query): " << ex << endl; } catch(SystemError& err) { dlog[Debug::WARN] << "(query): " << err << endl; } catch(Exception& ex) { dlog[Debug::WARN] << "(query): " << ex << endl; } catch( ost::SockException& e ) { dlog[Debug::WARN] << e.getString() << ": " << e.getSystemErrorString() << endl; } catch(...) { dlog[Debug::WARN] << "(query): cath..." << endl; } return erHardwareError; } // ------------------------------------------------------------------------- void ModbusTCPMaster::reconnect() { if( tcp ) { tcp->disconnect(); delete tcp; } tcp = new ost::TCPStream(iaddr.c_str()); } // ------------------------------------------------------------------------- void ModbusTCPMaster::connect( ost::InetAddress addr, int port ) { if( !tcp ) { ostringstream s; s << addr << ":" << port; if( dlog.debugging(Debug::INFO) ) dlog[Debug::INFO] << "(ModbusTCPMaster): connect to " << s.str() << endl; iaddr = s.str(); tcp = new ost::TCPStream(iaddr.c_str()); } } // ------------------------------------------------------------------------- void ModbusTCPMaster::disconnect() { if( !tcp ) return; // if( dlog.debugging(Debug::INFO) ) // dlog[Debug::INFO] << "(ModbusTCPMaster): disconnect." << endl; tcp->disconnect(); delete tcp; tcp = 0; } // ------------------------------------------------------------------------- bool ModbusTCPMaster::isConnection() { return tcp && tcp->isConnected(); } // ------------------------------------------------------------------------- <commit_msg>minor fixes in ModbusTCPMaster: restore timeout<commit_after>/*! $Id: ModbusTCPMaster.cc,v 1.3 2009/02/07 13:27:01 vpashka Exp $ */ // ------------------------------------------------------------------------- #include <string.h> #include <errno.h> #include <iostream> #include <sstream> #include "Exceptions.h" #include "modbus/ModbusTCPMaster.h" #include "modbus/ModbusTCPCore.h" // ------------------------------------------------------------------------- using namespace std; using namespace ModbusRTU; using namespace UniSetTypes; // ------------------------------------------------------------------------- ModbusTCPMaster::ModbusTCPMaster(): tcp(0), iaddr("") { setCRCNoCheckit(true); } // ------------------------------------------------------------------------- ModbusTCPMaster::~ModbusTCPMaster() { if( isConnection() ) disconnect(); } // ------------------------------------------------------------------------- int ModbusTCPMaster::getNextData( unsigned char* buf, int len ) { return ModbusTCPCore::getNextData(buf,len,qrecv,tcp); } // ------------------------------------------------------------------------- void ModbusTCPMaster::setChannelTimeout( timeout_t msec ) { if( tcp ) tcp->setTimeout(msec); } // ------------------------------------------------------------------------- mbErrCode ModbusTCPMaster::sendData( unsigned char* buf, int len ) { return ModbusTCPCore::sendData(buf,len,tcp); } // ------------------------------------------------------------------------- int ModbusTCPMaster::nTransaction = 0; mbErrCode ModbusTCPMaster::query( ModbusAddr addr, ModbusMessage& msg, ModbusMessage& reply, timeout_t timeout ) { // if( !isConnection() ) if( iaddr.empty() ) { dlog[Debug::WARN] << "(query): not connection to server..." << endl; return erHardwareError; } reconnect(); assert(timeout); ptTimeout.setTiming(timeout); tcp->setTimeout(timeout); ost::Thread::setException(ost::Thread::throwException); try { if( nTransaction >= numeric_limits<int>::max() ) nTransaction = 0; ModbusTCP::MBAPHeader mh; mh.tID = ++nTransaction; mh.pID = 0; mh.len = msg.len + szModbusHeader; // mh.uID = addr; if( crcNoCheckit ) mh.len -= szCRC; mh.swapdata(); // send TCP header if( dlog.debugging(Debug::INFO) ) { dlog[Debug::INFO] << "(ModbusTCPMaster::query): send tcp header(" << sizeof(mh) <<"): "; mbPrintMessage( dlog, (ModbusByte*)(&mh), sizeof(mh)); dlog(Debug::INFO) << endl; } (*tcp) << mh; mh.swapdata(); // send PDU mbErrCode res = send(msg); if( res!=erNoError ) return res; if( !tcp->isPending(ost::Socket::pendingOutput,timeout) ) return erTimeOut; if( timeout != UniSetTimer::WaitUpTime ) { timeout = ptTimeout.getLeft(timeout); if( timeout == 0 ) return erTimeOut; ptTimeout.setTiming(timeout); } // чистим очередь while( !qrecv.empty() ) qrecv.pop(); if( tcp->isPending(ost::Socket::pendingInput,timeout) ) { ModbusTCP::MBAPHeader rmh; int ret = getNextData((unsigned char*)(&rmh),sizeof(rmh)); if( dlog.debugging(Debug::INFO) ) { dlog[Debug::INFO] << "(ModbusTCPMaster::query): recv tcp header(" << ret << "): "; mbPrintMessage( dlog, (ModbusByte*)(&rmh), sizeof(rmh)); dlog(Debug::INFO) << endl; } if( ret < (int)sizeof(rmh) ) return erHardwareError; rmh.swapdata(); if( rmh.tID != mh.tID ) return erBadReplyNodeAddress; if( rmh.pID != 0 ) return erBadReplyNodeAddress; // return recv(addr,msg.func,reply,timeout); // msg.addr = rmh.uID; // return recv_pdu(msg.func,reply,timeout); } return erTimeOut; } catch( ModbusRTU::mbException& ex ) { dlog[Debug::WARN] << "(query): " << ex << endl; } catch(SystemError& err) { dlog[Debug::WARN] << "(query): " << err << endl; } catch(Exception& ex) { dlog[Debug::WARN] << "(query): " << ex << endl; } catch( ost::SockException& e ) { dlog[Debug::WARN] << e.getString() << ": " << e.getSystemErrorString() << endl; } catch(...) { dlog[Debug::WARN] << "(query): cath..." << endl; } return erHardwareError; } // ------------------------------------------------------------------------- void ModbusTCPMaster::reconnect() { if( tcp ) { tcp->disconnect(); delete tcp; } tcp = new ost::TCPStream(iaddr.c_str()); } // ------------------------------------------------------------------------- void ModbusTCPMaster::connect( ost::InetAddress addr, int port ) { if( !tcp ) { ostringstream s; s << addr << ":" << port; if( dlog.debugging(Debug::INFO) ) dlog[Debug::INFO] << "(ModbusTCPMaster): connect to " << s.str() << endl; iaddr = s.str(); tcp = new ost::TCPStream(iaddr.c_str()); } } // ------------------------------------------------------------------------- void ModbusTCPMaster::disconnect() { if( !tcp ) return; // if( dlog.debugging(Debug::INFO) ) // dlog[Debug::INFO] << "(ModbusTCPMaster): disconnect." << endl; tcp->disconnect(); delete tcp; tcp = 0; } // ------------------------------------------------------------------------- bool ModbusTCPMaster::isConnection() { return tcp && tcp->isConnected(); } // ------------------------------------------------------------------------- <|endoftext|>
<commit_before>#pragma once #include "SuperComponent.hpp" #include <string> #include <glm/glm.hpp> #include "../Animation/AnimationController.hpp" namespace Component { /// Animation controller. class AnimationController : public SuperComponent { public: /// Create new animation controller component. AnimationController(); /// Save the component. /** * @return JSON value to be stored on disk. */ Json::Value Save() const override; /// Update the animation controller. /** * @param deltaTime Time between frames. */ ENGINE_API void UpdateAnimation(float deltaTime); /// Set a bool in the state machine. ENGINE_API void SetBool(std::string name, bool value); /// Set a float in the state machine. ENGINE_API void SetFloat(std::string name, float value); /// Vector with the final calculated bones. std::vector<glm::mat4> bones; /// The controller. Animation::AnimationController* controller = nullptr; /// The skeleton. Animation::Skeleton* skeleton = nullptr; private: Animation::AnimationController::AnimationAction* activeAction1 = nullptr; Animation::AnimationController::AnimationAction* activeAction2 = nullptr; Animation::AnimationController::AnimationTransition* activeTransition = nullptr; }; }<commit_msg>Fixed newline.<commit_after>#pragma once #include "SuperComponent.hpp" #include <string> #include <glm/glm.hpp> #include "../Animation/AnimationController.hpp" namespace Component { /// Animation controller. class AnimationController : public SuperComponent { public: /// Create new animation controller component. AnimationController(); /// Save the component. /** * @return JSON value to be stored on disk. */ Json::Value Save() const override; /// Update the animation controller. /** * @param deltaTime Time between frames. */ ENGINE_API void UpdateAnimation(float deltaTime); /// Set a bool in the state machine. ENGINE_API void SetBool(std::string name, bool value); /// Set a float in the state machine. ENGINE_API void SetFloat(std::string name, float value); /// Vector with the final calculated bones. std::vector<glm::mat4> bones; /// The controller. Animation::AnimationController* controller = nullptr; /// The skeleton. Animation::Skeleton* skeleton = nullptr; private: Animation::AnimationController::AnimationAction* activeAction1 = nullptr; Animation::AnimationController::AnimationAction* activeAction2 = nullptr; Animation::AnimationController::AnimationTransition* activeTransition = nullptr; }; } <|endoftext|>
<commit_before>#if defined(_MSC_VER) #include <intrin.h> // SIMD intrinsics for Windows #else #include <x86intrin.h> // SIMD intrinsics for GCC #endif #ifdef linux #include <omp.h> #endif #include "utils.h" #include <cpuid.h> #include <stdio.h> #include <stdlib.h> #define OSXSAVEFlag (1UL<<27) #define AVXFlag ((1UL<<28)|OSXSAVEFlag) #define DEBUG #ifdef DEBUG # define DBG(M, ...) fprintf(stdout, "[DEBUG] (%s %s:%d) " M "\n", __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__) #else # define DBG(M, ...) #endif /* * Class: com_intel_gkl_IntelGKLUtils * Method: getFlushToZeroNative * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_getFlushToZeroNative (JNIEnv *env, jobject obj) { jboolean value = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON ? 1 : 0; return value; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: setFlushToZeroNative * Signature: (Z)V */ JNIEXPORT void JNICALL Java_com_intel_gkl_IntelGKLUtils_setFlushToZeroNative (JNIEnv *env, jobject obj, jboolean value) { if (value) { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); } else { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); } } /* * Class: com_intel_gkl_IntelGKLUtils * Method: isAvxSupportedNative * Signature: (Z)V */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_isAvxSupportedNative (JNIEnv *env, jobject obj) { jint eax, ebx, ecx, edx; __cpuid(0, eax, ebx, ecx, edx); if ((ecx && AVXFlag) == 0 ) return false; return true; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: getAvailableOmpThreadsNative * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_intel_gkl_IntelGKLUtils_getAvailableOmpThreadsNative (JNIEnv *env, jobject obj) { #ifdef _OPENMP int avail_threads = omp_get_max_threads(); #else int avail_threads = 0; #endif return avail_threads; } <commit_msg>Fixed AVX detection code<commit_after>#if defined(_MSC_VER) #include <intrin.h> // SIMD intrinsics for Windows #else #include <x86intrin.h> // SIMD intrinsics for GCC #endif #ifdef linux #include <omp.h> #endif #include "utils.h" #include <stdio.h> #include <stdlib.h> /* * Class: com_intel_gkl_IntelGKLUtils * Method: getFlushToZeroNative * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_getFlushToZeroNative (JNIEnv *env, jobject obj) { jboolean value = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON ? 1 : 0; return value; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: setFlushToZeroNative * Signature: (Z)V */ JNIEXPORT void JNICALL Java_com_intel_gkl_IntelGKLUtils_setFlushToZeroNative (JNIEnv *env, jobject obj, jboolean value) { if (value) { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); } else { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); } } /* * Class: com_intel_gkl_IntelGKLUtils * Method: isAvxSupportedNative * Signature: (Z)V */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_isAvxSupportedNative (JNIEnv *env, jobject obj) { __builtin_cpu_init(); return __builtin_cpu_supports("avx") ? true : false; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: getAvailableOmpThreadsNative * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_intel_gkl_IntelGKLUtils_getAvailableOmpThreadsNative (JNIEnv *env, jobject obj) { #ifdef _OPENMP int avail_threads = omp_get_max_threads(); #else int avail_threads = 0; #endif return avail_threads; } <|endoftext|>
<commit_before>#include "musicsoundtouchwidget.h" #include "ui_musicsoundtouchwidget.h" #include "musicbackgroundmanager.h" #include "musicaudiorecordercore.h" #include "musicmessagebox.h" #include "musicobject.h" #include "musicuiobject.h" #include "musicutils.h" #include <QSound> #include <QProcess> #include <QFileDialog> MusicSoundTouchWidget::MusicSoundTouchWidget(QWidget *parent) : MusicAbstractMoveDialog(parent), ui(new Ui::MusicSoundTouchWidget) { ui->setupUi(this); ui->topTitleCloseButton->setIcon(QIcon(":/share/searchclosed")); ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle03); ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->topTitleCloseButton->setToolTip(tr("Close")); connect(ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close())); ui->playButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->stopButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->openButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->tempoSlider->setStyleSheet(MusicUIObject::MSliderStyle01); ui->pitchSlider->setStyleSheet(MusicUIObject::MSliderStyle01); ui->rateSlider->setStyleSheet(MusicUIObject::MSliderStyle01); ui->tempoSlider->setRange(-95, 5000); ui->pitchSlider->setRange(-60, 60); ui->rateSlider->setRange(-95, 5000); connect(ui->tempoSlider, SIGNAL(valueChanged(int)), SLOT(tempoSliderValueChanged(int))); connect(ui->pitchSlider, SIGNAL(valueChanged(int)), SLOT(pitchSliderValueChanged(int))); connect(ui->rateSlider, SIGNAL(valueChanged(int)), SLOT(rateSliderValueChanged(int))); ui->playWavButton->setStyleSheet(MusicUIObject::MPushButtonStyle05); ui->transformButton->setStyleSheet(MusicUIObject::MPushButtonStyle05); connect(ui->playWavButton, SIGNAL(clicked()), SLOT(onRecordPlay())); connect(ui->transformButton, SIGNAL(clicked()), SLOT(transformButtonClicked())); m_process = new QProcess(this); m_process->setProcessChannelMode(QProcess::MergedChannels); connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(analysisOutput())); connect(m_process, SIGNAL(finished(int)), SLOT(finished(int))); ui->tempoSlider->setValue(2500); ui->pitchSlider->setValue(0); ui->rateSlider->setValue(2500); ui->tempoLabelValue->setText("2500"); ui->pitchLabelValue->setText("0"); ui->rateLabelValue->setText("2500"); setText(MusicObject::getAppDir() + RECORD_FILE); ui->playWavButton->setEnabled(false); ui->transformButton->setEnabled(false); m_recordCore = new MusicAudioRecorderCore(this); connect(ui->playButton, SIGNAL(clicked()), SLOT(onRecordStart())); connect(ui->stopButton, SIGNAL(clicked()), SLOT(onRecordStop())); connect(ui->openButton, SIGNAL(clicked()), SLOT(openWavButtonClicked())); } MusicSoundTouchWidget::~MusicSoundTouchWidget() { delete m_recordCore; delete m_process; delete ui; } QString MusicSoundTouchWidget::getClassName() { return staticMetaObject.className(); } int MusicSoundTouchWidget::exec() { if(!QFile::exists(MAKE_SOUNDTOUCH_FULL)) { MusicMessageBox message; message.setText(tr("Lack of plugin file!")); message.exec(); return -1; } QPixmap pix(M_BACKGROUND_PTR->getMBackground()); ui->background->setPixmap(pix.scaled( size() )); return MusicAbstractMoveDialog::exec(); } void MusicSoundTouchWidget::analysisOutput() { // while(m_process->canReadLine()) // { // QByteArray data = m_process->readLine(); // } } void MusicSoundTouchWidget::onRecordStart() { m_recordCore->onRecordStart(); ui->playButton->setEnabled(false); ui->openButton->setEnabled(false); } void MusicSoundTouchWidget::onRecordStop() { m_recordCore->onRecordStop(); ui->playButton->setEnabled(true); ui->openButton->setEnabled(true); ui->transformButton->setEnabled(true); } void MusicSoundTouchWidget::onRecordPlay() { QSound::play(MusicObject::getAppDir() + RECORD_OUT_FILE); // m_recordCore->onRecordPlay(); } void MusicSoundTouchWidget::tempoSliderValueChanged(int value) { ui->tempoLabelValue->setText(QString::number(value)); } void MusicSoundTouchWidget::pitchSliderValueChanged(int value) { ui->pitchLabelValue->setText(QString::number(value)); } void MusicSoundTouchWidget::rateSliderValueChanged(int value) { ui->rateLabelValue->setText(QString::number(value)); } void MusicSoundTouchWidget::openWavButtonClicked() { QString filename = QFileDialog::getOpenFileName(this, tr("choose a filename to open under"), QDir::currentPath(), "Wav(*.wav)"); if(!filename.isEmpty()) { ui->transformButton->setEnabled(true); m_recordCore->setFileName(filename); setText(filename); } } void MusicSoundTouchWidget::transformButtonClicked() { QString input = m_recordCore->getFileName(); if(input == RECORD_FILE) { m_recordCore->addWavHeader(RECORD_IN_FILE); input = MusicObject::getAppDir() + RECORD_IN_FILE; } QStringList key; key << input << (MusicObject::getAppDir() + RECORD_OUT_FILE) << QString("-tempo=%1").arg(ui->tempoSlider->value()) << QString("-pitch=%1").arg(ui->pitchSlider->value()) << QString("-rate=%1").arg(ui->rateSlider->value()); m_process->start(MAKE_SOUNDTOUCH_FULL, key); } void MusicSoundTouchWidget::finished(int code) { if(code != 0) { MusicMessageBox message; message.setText(tr("Transform wav file error!")); message.exec(); return; } ui->playWavButton->setEnabled(true); } void MusicSoundTouchWidget::setText(const QString &text) { ui->pathLabel->setText(MusicUtils::elidedText(font(), text, Qt::ElideLeft, 390) ); ui->pathLabel->setToolTip(text); } <commit_msg>clean code[963258]<commit_after>#include "musicsoundtouchwidget.h" #include "ui_musicsoundtouchwidget.h" #include "musicbackgroundmanager.h" #include "musicaudiorecordercore.h" #include "musicmessagebox.h" #include "musicobject.h" #include "musicuiobject.h" #include "musicutils.h" #include <QSound> #include <QProcess> #include <QFileDialog> MusicSoundTouchWidget::MusicSoundTouchWidget(QWidget *parent) : MusicAbstractMoveDialog(parent), ui(new Ui::MusicSoundTouchWidget) { ui->setupUi(this); ui->topTitleCloseButton->setIcon(QIcon(":/share/searchclosed")); ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle03); ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor)); ui->topTitleCloseButton->setToolTip(tr("Close")); connect(ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close())); ui->playButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->stopButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->openButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->tempoSlider->setStyleSheet(MusicUIObject::MSliderStyle01); ui->pitchSlider->setStyleSheet(MusicUIObject::MSliderStyle01); ui->rateSlider->setStyleSheet(MusicUIObject::MSliderStyle01); ui->tempoSlider->setRange(-95, 5000); ui->pitchSlider->setRange(-60, 60); ui->rateSlider->setRange(-95, 5000); connect(ui->tempoSlider, SIGNAL(valueChanged(int)), SLOT(tempoSliderValueChanged(int))); connect(ui->pitchSlider, SIGNAL(valueChanged(int)), SLOT(pitchSliderValueChanged(int))); connect(ui->rateSlider, SIGNAL(valueChanged(int)), SLOT(rateSliderValueChanged(int))); ui->playWavButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); ui->transformButton->setStyleSheet(MusicUIObject::MPushButtonStyle08); connect(ui->playWavButton, SIGNAL(clicked()), SLOT(onRecordPlay())); connect(ui->transformButton, SIGNAL(clicked()), SLOT(transformButtonClicked())); m_process = new QProcess(this); m_process->setProcessChannelMode(QProcess::MergedChannels); connect(m_process, SIGNAL(readyReadStandardOutput()), SLOT(analysisOutput())); connect(m_process, SIGNAL(finished(int)), SLOT(finished(int))); ui->tempoSlider->setValue(2500); ui->pitchSlider->setValue(0); ui->rateSlider->setValue(2500); ui->tempoLabelValue->setText("2500"); ui->pitchLabelValue->setText("0"); ui->rateLabelValue->setText("2500"); setText(MusicObject::getAppDir() + RECORD_FILE); ui->playWavButton->setEnabled(false); ui->transformButton->setEnabled(false); m_recordCore = new MusicAudioRecorderCore(this); connect(ui->playButton, SIGNAL(clicked()), SLOT(onRecordStart())); connect(ui->stopButton, SIGNAL(clicked()), SLOT(onRecordStop())); connect(ui->openButton, SIGNAL(clicked()), SLOT(openWavButtonClicked())); } MusicSoundTouchWidget::~MusicSoundTouchWidget() { delete m_recordCore; delete m_process; delete ui; } QString MusicSoundTouchWidget::getClassName() { return staticMetaObject.className(); } int MusicSoundTouchWidget::exec() { if(!QFile::exists(MAKE_SOUNDTOUCH_FULL)) { MusicMessageBox message; message.setText(tr("Lack of plugin file!")); message.exec(); return -1; } QPixmap pix(M_BACKGROUND_PTR->getMBackground()); ui->background->setPixmap(pix.scaled( size() )); return MusicAbstractMoveDialog::exec(); } void MusicSoundTouchWidget::analysisOutput() { // while(m_process->canReadLine()) // { // QByteArray data = m_process->readLine(); // } } void MusicSoundTouchWidget::onRecordStart() { m_recordCore->onRecordStart(); ui->playButton->setEnabled(false); ui->openButton->setEnabled(false); } void MusicSoundTouchWidget::onRecordStop() { m_recordCore->onRecordStop(); ui->playButton->setEnabled(true); ui->openButton->setEnabled(true); ui->transformButton->setEnabled(true); } void MusicSoundTouchWidget::onRecordPlay() { QSound::play(MusicObject::getAppDir() + RECORD_OUT_FILE); // m_recordCore->onRecordPlay(); } void MusicSoundTouchWidget::tempoSliderValueChanged(int value) { ui->tempoLabelValue->setText(QString::number(value)); } void MusicSoundTouchWidget::pitchSliderValueChanged(int value) { ui->pitchLabelValue->setText(QString::number(value)); } void MusicSoundTouchWidget::rateSliderValueChanged(int value) { ui->rateLabelValue->setText(QString::number(value)); } void MusicSoundTouchWidget::openWavButtonClicked() { QString filename = QFileDialog::getOpenFileName(this, tr("choose a filename to open under"), QDir::currentPath(), "Wav(*.wav)"); if(!filename.isEmpty()) { ui->transformButton->setEnabled(true); m_recordCore->setFileName(filename); setText(filename); } } void MusicSoundTouchWidget::transformButtonClicked() { QString input = m_recordCore->getFileName(); if(input == RECORD_FILE) { m_recordCore->addWavHeader(RECORD_IN_FILE); input = MusicObject::getAppDir() + RECORD_IN_FILE; } QStringList key; key << input << (MusicObject::getAppDir() + RECORD_OUT_FILE) << QString("-tempo=%1").arg(ui->tempoSlider->value()) << QString("-pitch=%1").arg(ui->pitchSlider->value()) << QString("-rate=%1").arg(ui->rateSlider->value()); m_process->start(MAKE_SOUNDTOUCH_FULL, key); } void MusicSoundTouchWidget::finished(int code) { if(code != 0) { MusicMessageBox message; message.setText(tr("Transform wav file error!")); message.exec(); return; } ui->playWavButton->setEnabled(true); } void MusicSoundTouchWidget::setText(const QString &text) { ui->pathLabel->setText(MusicUtils::elidedText(font(), text, Qt::ElideLeft, 390) ); ui->pathLabel->setToolTip(text); } <|endoftext|>
<commit_before>#if defined(_MSC_VER) #include <intrin.h> // SIMD intrinsics for Windows #else #include <x86intrin.h> // SIMD intrinsics for GCC #include <stdint.h> #endif #ifdef linux #include <omp.h> #endif #include "utils.h" #include <stdio.h> #include <stdlib.h> /* * Class: com_intel_gkl_IntelGKLUtils * Method: getFlushToZeroNative * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_getFlushToZeroNative (JNIEnv *env, jobject obj) { jboolean value = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON ? 1 : 0; return value; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: setFlushToZeroNative * Signature: (Z)V */ JNIEXPORT void JNICALL Java_com_intel_gkl_IntelGKLUtils_setFlushToZeroNative (JNIEnv *env, jobject obj, jboolean value) { if (value) { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); } else { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); } } // helper function static void run_cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) { #if defined(_MSC_VER) __cpuidex(abcd, eax, ecx); #else uint32_t ebx, edx; # if defined( __i386__ ) && defined ( __PIC__ ) /* in case of PIC under 32-bit EBX cannot be clobbered */ __asm__ ( "movl %%ebx, %%edi \n\t cpuid \n\t xchgl %%ebx, %%edi" : "=D" (ebx), # else __asm__ ( "cpuid" : "+b" (ebx), # endif "+a" (eax), "+c" (ecx), "=d" (edx) ); abcd[0] = eax; abcd[1] = ebx; abcd[2] = ecx; abcd[3] = edx; #endif } // helper function static int check_xcr0_ymm() { uint32_t xcr0; #if defined(_MSC_VER) xcr0 = (uint32_t)_xgetbv(0); #else __asm__ ("xgetbv" : "=a" (xcr0) : "c" (0) : "%edx" ); #endif return ((xcr0 & 6) == 6); } /* * Class: com_intel_gkl_IntelGKLUtils * Method: isAvxSupportedNative * Signature: (Z)V */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_isAvxSupportedNative (JNIEnv *env, jobject obj) { uint32_t abcd[4]; uint32_t avx_mask = (1 << 27) | (1 << 28); run_cpuid(1, 0, abcd); if((abcd[2] & avx_mask) != avx_mask) { return false; } if(!check_xcr0_ymm()) { return false; } return true; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: getAvailableOmpThreadsNative * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_intel_gkl_IntelGKLUtils_getAvailableOmpThreadsNative (JNIEnv *env, jobject obj) { #ifdef _OPENMP int avail_threads = omp_get_max_threads(); #else int avail_threads = 0; #endif return avail_threads; } <commit_msg>Resolved conflict due to additional spaces at the end of lines<commit_after>#if defined(_MSC_VER) #include <intrin.h> // SIMD intrinsics for Windows #else #include <x86intrin.h> // SIMD intrinsics for GCC #include <stdint.h> #endif #ifdef linux #include <omp.h> #endif #include "utils.h" #include <stdio.h> #include <stdlib.h> /* * Class: com_intel_gkl_IntelGKLUtils * Method: getFlushToZeroNative * Signature: ()Z */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_getFlushToZeroNative (JNIEnv *env, jobject obj) { jboolean value = _MM_GET_FLUSH_ZERO_MODE() == _MM_FLUSH_ZERO_ON ? 1 : 0; return value; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: setFlushToZeroNative * Signature: (Z)V */ JNIEXPORT void JNICALL Java_com_intel_gkl_IntelGKLUtils_setFlushToZeroNative (JNIEnv *env, jobject obj, jboolean value) { if (value) { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); } else { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF); } } // helper function static void run_cpuid(uint32_t eax, uint32_t ecx, uint32_t* abcd) { #if defined(_MSC_VER) __cpuidex(abcd, eax, ecx); #else uint32_t ebx, edx; # if defined( __i386__ ) && defined ( __PIC__ ) /* in case of PIC under 32-bit EBX cannot be clobbered */ __asm__ ( "movl %%ebx, %%edi \n\t cpuid \n\t xchgl %%ebx, %%edi" : "=D" (ebx), # else __asm__ ( "cpuid" : "+b" (ebx), # endif "+a" (eax), "+c" (ecx), "=d" (edx) ); abcd[0] = eax; abcd[1] = ebx; abcd[2] = ecx; abcd[3] = edx; #endif } // helper function static int check_xcr0_ymm() { uint32_t xcr0; #if defined(_MSC_VER) xcr0 = (uint32_t)_xgetbv(0); #else __asm__ ("xgetbv" : "=a" (xcr0) : "c" (0) : "%edx" ); #endif return ((xcr0 & 6) == 6); } /* * Class: com_intel_gkl_IntelGKLUtils * Method: isAvxSupportedNative * Signature: (Z)V */ JNIEXPORT jboolean JNICALL Java_com_intel_gkl_IntelGKLUtils_isAvxSupportedNative (JNIEnv *env, jobject obj) { uint32_t abcd[4]; uint32_t avx_mask = (1 << 27) | (1 << 28); run_cpuid(1, 0, abcd); if((abcd[2] & avx_mask) != avx_mask) { return false; } if(!check_xcr0_ymm()) { return false; } return true; } /* * Class: com_intel_gkl_IntelGKLUtils * Method: getAvailableOmpThreadsNative * Signature: ()I */ JNIEXPORT jint JNICALL Java_com_intel_gkl_IntelGKLUtils_getAvailableOmpThreadsNative (JNIEnv *env, jobject obj) { #ifdef _OPENMP int avail_threads = omp_get_max_threads(); #else int avail_threads = 0; #endif return avail_threads; } <|endoftext|>
<commit_before>#include "compiler/build_tables/build_parse_table.h" #include <algorithm> #include <map> #include <set> #include <string> #include <unordered_map> #include <utility> #include "compiler/parse_table.h" #include "compiler/build_tables/parse_conflict_manager.h" #include "compiler/build_tables/parse_item.h" #include "compiler/build_tables/get_completion_status.h" #include "compiler/build_tables/get_metadata.h" #include "compiler/build_tables/item_set_closure.h" #include "compiler/lexical_grammar.h" #include "compiler/syntax_grammar.h" #include "compiler/rules/symbol.h" #include "compiler/rules/built_in_symbols.h" namespace tree_sitter { namespace build_tables { using std::find; using std::pair; using std::vector; using std::set; using std::map; using std::string; using std::to_string; using std::unordered_map; using std::make_shared; using rules::Symbol; class ParseTableBuilder { const SyntaxGrammar grammar; const LexicalGrammar lexical_grammar; ParseConflictManager conflict_manager; unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids; vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process; ParseTable parse_table; std::set<string> conflicts; public: ParseTableBuilder(const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) : grammar(grammar), lexical_grammar(lex_grammar), conflict_manager(grammar) {} pair<ParseTable, const GrammarError *> build() { Symbol start_symbol = Symbol(0, grammar.variables.empty()); Production start_production({ ProductionStep(start_symbol, 0, rules::AssociativityNone, -2), }); add_parse_state(ParseItemSet({ { ParseItem(rules::START(), start_production, 0), LookaheadSet({ rules::END_OF_INPUT() }), }, })); while (!item_sets_to_process.empty()) { auto pair = item_sets_to_process.back(); ParseItemSet item_set = item_set_closure(pair.first, grammar); ParseStateId state_id = pair.second; item_sets_to_process.pop_back(); add_reduce_actions(item_set, state_id); add_shift_actions(item_set, state_id); add_shift_extra_actions(item_set, state_id); if (!conflicts.empty()) return { parse_table, new GrammarError(GrammarErrorTypeParseConflict, "Unresolved conflict.\n\n" + *conflicts.begin()) }; } for (ParseStateId state = 0; state < parse_table.states.size(); state++) add_reduce_extra_actions(state); parse_table.symbols.insert(rules::ERROR()); return { parse_table, nullptr }; } private: ParseStateId add_parse_state(const ParseItemSet &item_set) { auto pair = parse_state_ids.find(item_set); if (pair == parse_state_ids.end()) { ParseStateId state_id = parse_table.add_state(); parse_state_ids[item_set] = state_id; item_sets_to_process.push_back({ item_set, state_id }); return state_id; } else { return pair->second; } } void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) { for (const auto &transition : item_set.transitions()) { const Symbol &symbol = transition.first; const ParseItemSet &next_item_set = transition.second; ParseAction *new_action = add_action( state_id, symbol, ParseAction::Shift(0, precedence_values_for_item_set(next_item_set)), item_set); if (new_action) new_action->state_index = add_parse_state(next_item_set); } } struct CompletionStatus { bool is_done; int precedence; rules::Associativity associativity; }; CompletionStatus get_completion_status(const ParseItem &item) { CompletionStatus result = { false, 0, rules::AssociativityNone }; if (item.step_index == item.production->size()) { result.is_done = true; if (item.step_index > 0) { const ProductionStep &last_step = item.production->at(item.step_index - 1); result.precedence = last_step.precedence; result.associativity = last_step.associativity; } } return result; } void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) { for (const auto &pair : item_set.entries) { const ParseItem &item = pair.first; const auto &lookahead_symbols = pair.second; CompletionStatus completion_status = get_completion_status(item); if (completion_status.is_done) { ParseAction action = (item.lhs() == rules::START()) ? ParseAction::Accept() : ParseAction::Reduce(Symbol(item.variable_index), item.step_index, completion_status.precedence, completion_status.associativity, *item.production); for (const auto &lookahead_sym : *lookahead_symbols.entries) add_action(state_id, lookahead_sym, action, item_set); } } } void add_shift_extra_actions(const ParseItemSet &item_set, ParseStateId state_id) { for (const Symbol &ubiquitous_symbol : grammar.ubiquitous_tokens) add_action(state_id, ubiquitous_symbol, ParseAction::ShiftExtra(), item_set); } void add_reduce_extra_actions(ParseStateId state_id) { const ParseItemSet item_set; const map<Symbol, vector<ParseAction>> &actions = parse_table.states[state_id].actions; for (const Symbol &ubiquitous_symbol : grammar.ubiquitous_tokens) { const auto &entry = actions.find(ubiquitous_symbol); if (entry == actions.end()) continue; for (const auto &action : entry->second) { if (action.type == ParseActionTypeShift) { size_t shift_state_id = action.state_index; for (const auto &pair : actions) { const Symbol &lookahead_sym = pair.first; ParseAction reduce_extra = ParseAction::ReduceExtra(ubiquitous_symbol); add_action(shift_state_id, lookahead_sym, reduce_extra, item_set); } } } } } ParseAction *add_action(ParseStateId state_id, Symbol lookahead, const ParseAction &new_action, const ParseItemSet &item_set) { const auto &current_actions = parse_table.states[state_id].actions; const auto &current_entry = current_actions.find(lookahead); if (current_entry == current_actions.end()) return &parse_table.set_action(state_id, lookahead, new_action); const ParseAction old_action = current_entry->second[0]; auto resolution = conflict_manager.resolve(new_action, old_action, lookahead); switch (resolution.second) { case ConflictTypeNone: if (resolution.first) return &parse_table.set_action(state_id, lookahead, new_action); break; case ConflictTypeResolved: { if (resolution.first) return &parse_table.set_action(state_id, lookahead, new_action); if (old_action.type == ParseActionTypeReduce) parse_table.fragile_productions.insert(old_action.production); if (new_action.type == ParseActionTypeReduce) parse_table.fragile_productions.insert(new_action.production); break; } case ConflictTypeUnresolved: { if (handle_unresolved_conflict(item_set, lookahead)) return &parse_table.add_action(state_id, lookahead, new_action); break; } } return nullptr; } bool handle_unresolved_conflict(const ParseItemSet &item_set, const Symbol &lookahead) { set<Symbol> involved_symbols; set<ParseItem> reduce_items; set<ParseItem> core_shift_items; set<ParseItem> other_shift_items; for (const auto &pair : item_set.entries) { const ParseItem &item = pair.first; const LookaheadSet &lookahead_set = pair.second; if (item.step_index == item.production->size()) { if (lookahead_set.contains(lookahead)) { involved_symbols.insert(item.lhs()); reduce_items.insert(item); } } else { Symbol next_symbol = item.production->at(item.step_index).symbol; if (item.step_index > 0) { set<Symbol> first_set = get_first_set(next_symbol); if (first_set.find(lookahead) != first_set.end()) { involved_symbols.insert(item.lhs()); core_shift_items.insert(item); } } else if (next_symbol == lookahead) { other_shift_items.insert(item); } } } for (const auto &conflict_set : grammar.expected_conflicts) if (involved_symbols == conflict_set) return true; string description = "Lookahead symbol: " + symbol_name(lookahead) + "\n"; if (!reduce_items.empty()) { description += "Reduce items:\n"; for (const ParseItem &item : reduce_items) description += " " + item_string(item) + "\n"; } if (!core_shift_items.empty()) { description += "Core shift items:\n"; for (const ParseItem &item : core_shift_items) description += " " + item_string(item) + "\n"; } if (!other_shift_items.empty()) { description += "Other shift items:\n"; for (const ParseItem &item : other_shift_items) description += " " + item_string(item) + "\n"; } conflicts.insert(description); return false; } string item_string(const ParseItem &item) const { string result = symbol_name(item.lhs()) + " ->"; size_t i = 0; for (const ProductionStep &step : *item.production) { if (i == item.step_index) result += " \u2022"; result += " " + symbol_name(step.symbol); i++; } if (i == item.step_index) result += " \u2022"; result += " (prec " + to_string(item.precedence()); switch (item.associativity()) { case rules::AssociativityNone: result += ")"; break; case rules::AssociativityLeft: result += ", assoc left)"; break; case rules::AssociativityRight: result += ", assoc right)"; break; } return result; } set<Symbol> get_first_set(const Symbol &start_symbol) { set<Symbol> result; vector<Symbol> symbols_to_process({ start_symbol }); while (!symbols_to_process.empty()) { Symbol symbol = symbols_to_process.back(); symbols_to_process.pop_back(); if (result.insert(symbol).second) for (const Production &production : grammar.productions(symbol)) if (!production.empty()) symbols_to_process.push_back(production[0].symbol); } return result; } PrecedenceRange precedence_values_for_item_set(const ParseItemSet &item_set) { PrecedenceRange result; for (const auto &pair : item_set.entries) { const ParseItem &item = pair.first; if (item.step_index > 0) result.add(item.production->at(item.step_index - 1).precedence); } return result; } string symbol_name(const rules::Symbol &symbol) const { if (symbol.is_built_in()) { if (symbol == rules::ERROR()) return "ERROR"; else if (symbol == rules::END_OF_INPUT()) return "END_OF_INPUT"; else return ""; } else if (symbol.is_token) { const Variable &variable = lexical_grammar.variables[symbol.index]; if (variable.type == VariableTypeNamed) return variable.name; else return "'" + variable.name + "'"; } else { return grammar.variables[symbol.index].name; } } }; pair<ParseTable, const GrammarError *> build_parse_table( const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) { return ParseTableBuilder(grammar, lex_grammar).build(); } } // namespace build_tables } // namespace tree_sitter <commit_msg>Add reduce-extra actions for all symbols<commit_after>#include "compiler/build_tables/build_parse_table.h" #include <algorithm> #include <map> #include <set> #include <string> #include <unordered_map> #include <utility> #include "compiler/parse_table.h" #include "compiler/build_tables/parse_conflict_manager.h" #include "compiler/build_tables/parse_item.h" #include "compiler/build_tables/get_completion_status.h" #include "compiler/build_tables/get_metadata.h" #include "compiler/build_tables/item_set_closure.h" #include "compiler/lexical_grammar.h" #include "compiler/syntax_grammar.h" #include "compiler/rules/symbol.h" #include "compiler/rules/built_in_symbols.h" namespace tree_sitter { namespace build_tables { using std::find; using std::pair; using std::vector; using std::set; using std::map; using std::string; using std::to_string; using std::unordered_map; using std::make_shared; using rules::Symbol; class ParseTableBuilder { const SyntaxGrammar grammar; const LexicalGrammar lexical_grammar; ParseConflictManager conflict_manager; unordered_map<ParseItemSet, ParseStateId, ParseItemSet::Hash> parse_state_ids; vector<pair<ParseItemSet, ParseStateId>> item_sets_to_process; ParseTable parse_table; std::set<string> conflicts; public: ParseTableBuilder(const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) : grammar(grammar), lexical_grammar(lex_grammar), conflict_manager(grammar) {} pair<ParseTable, const GrammarError *> build() { Symbol start_symbol = Symbol(0, grammar.variables.empty()); Production start_production({ ProductionStep(start_symbol, 0, rules::AssociativityNone, -2), }); add_parse_state(ParseItemSet({ { ParseItem(rules::START(), start_production, 0), LookaheadSet({ rules::END_OF_INPUT() }), }, })); while (!item_sets_to_process.empty()) { auto pair = item_sets_to_process.back(); ParseItemSet item_set = item_set_closure(pair.first, grammar); ParseStateId state_id = pair.second; item_sets_to_process.pop_back(); add_reduce_actions(item_set, state_id); add_shift_actions(item_set, state_id); add_shift_extra_actions(item_set, state_id); if (!conflicts.empty()) return { parse_table, new GrammarError(GrammarErrorTypeParseConflict, "Unresolved conflict.\n\n" + *conflicts.begin()) }; } for (ParseStateId state = 0; state < parse_table.states.size(); state++) add_reduce_extra_actions(state); parse_table.symbols.insert(rules::ERROR()); return { parse_table, nullptr }; } private: ParseStateId add_parse_state(const ParseItemSet &item_set) { auto pair = parse_state_ids.find(item_set); if (pair == parse_state_ids.end()) { ParseStateId state_id = parse_table.add_state(); parse_state_ids[item_set] = state_id; item_sets_to_process.push_back({ item_set, state_id }); return state_id; } else { return pair->second; } } void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) { for (const auto &transition : item_set.transitions()) { const Symbol &symbol = transition.first; const ParseItemSet &next_item_set = transition.second; ParseAction *new_action = add_action( state_id, symbol, ParseAction::Shift(0, precedence_values_for_item_set(next_item_set)), item_set); if (new_action) new_action->state_index = add_parse_state(next_item_set); } } struct CompletionStatus { bool is_done; int precedence; rules::Associativity associativity; }; CompletionStatus get_completion_status(const ParseItem &item) { CompletionStatus result = { false, 0, rules::AssociativityNone }; if (item.step_index == item.production->size()) { result.is_done = true; if (item.step_index > 0) { const ProductionStep &last_step = item.production->at(item.step_index - 1); result.precedence = last_step.precedence; result.associativity = last_step.associativity; } } return result; } void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) { for (const auto &pair : item_set.entries) { const ParseItem &item = pair.first; const auto &lookahead_symbols = pair.second; CompletionStatus completion_status = get_completion_status(item); if (completion_status.is_done) { ParseAction action = (item.lhs() == rules::START()) ? ParseAction::Accept() : ParseAction::Reduce(Symbol(item.variable_index), item.step_index, completion_status.precedence, completion_status.associativity, *item.production); for (const auto &lookahead_sym : *lookahead_symbols.entries) add_action(state_id, lookahead_sym, action, item_set); } } } void add_shift_extra_actions(const ParseItemSet &item_set, ParseStateId state_id) { for (const Symbol &ubiquitous_symbol : grammar.ubiquitous_tokens) add_action(state_id, ubiquitous_symbol, ParseAction::ShiftExtra(), item_set); } void add_reduce_extra_actions(ParseStateId state_id) { const ParseState &state = parse_table.states[state_id]; const ParseItemSet item_set; for (const Symbol &ubiquitous_symbol : grammar.ubiquitous_tokens) { const auto &actions_for_symbol = state.actions.find(ubiquitous_symbol); if (actions_for_symbol == state.actions.end()) continue; for (const ParseAction &action : actions_for_symbol->second) if (action.type == ParseActionTypeShift) { size_t dest_state_id = action.state_index; ParseAction reduce_extra = ParseAction::ReduceExtra(ubiquitous_symbol); for (const auto &symbol : parse_table.symbols) add_action(dest_state_id, symbol, reduce_extra, item_set); } } } ParseAction *add_action(ParseStateId state_id, Symbol lookahead, const ParseAction &new_action, const ParseItemSet &item_set) { const auto &current_actions = parse_table.states[state_id].actions; const auto &current_entry = current_actions.find(lookahead); if (current_entry == current_actions.end()) return &parse_table.set_action(state_id, lookahead, new_action); const ParseAction old_action = current_entry->second[0]; auto resolution = conflict_manager.resolve(new_action, old_action, lookahead); switch (resolution.second) { case ConflictTypeNone: if (resolution.first) return &parse_table.set_action(state_id, lookahead, new_action); break; case ConflictTypeResolved: { if (resolution.first) return &parse_table.set_action(state_id, lookahead, new_action); if (old_action.type == ParseActionTypeReduce) parse_table.fragile_productions.insert(old_action.production); if (new_action.type == ParseActionTypeReduce) parse_table.fragile_productions.insert(new_action.production); break; } case ConflictTypeUnresolved: { if (handle_unresolved_conflict(item_set, lookahead)) return &parse_table.add_action(state_id, lookahead, new_action); break; } } return nullptr; } bool handle_unresolved_conflict(const ParseItemSet &item_set, const Symbol &lookahead) { set<Symbol> involved_symbols; set<ParseItem> reduce_items; set<ParseItem> core_shift_items; set<ParseItem> other_shift_items; for (const auto &pair : item_set.entries) { const ParseItem &item = pair.first; const LookaheadSet &lookahead_set = pair.second; if (item.step_index == item.production->size()) { if (lookahead_set.contains(lookahead)) { involved_symbols.insert(item.lhs()); reduce_items.insert(item); } } else { Symbol next_symbol = item.production->at(item.step_index).symbol; if (item.step_index > 0) { set<Symbol> first_set = get_first_set(next_symbol); if (first_set.find(lookahead) != first_set.end()) { involved_symbols.insert(item.lhs()); core_shift_items.insert(item); } } else if (next_symbol == lookahead) { other_shift_items.insert(item); } } } for (const auto &conflict_set : grammar.expected_conflicts) if (involved_symbols == conflict_set) return true; string description = "Lookahead symbol: " + symbol_name(lookahead) + "\n"; if (!reduce_items.empty()) { description += "Reduce items:\n"; for (const ParseItem &item : reduce_items) description += " " + item_string(item) + "\n"; } if (!core_shift_items.empty()) { description += "Core shift items:\n"; for (const ParseItem &item : core_shift_items) description += " " + item_string(item) + "\n"; } if (!other_shift_items.empty()) { description += "Other shift items:\n"; for (const ParseItem &item : other_shift_items) description += " " + item_string(item) + "\n"; } conflicts.insert(description); return false; } string item_string(const ParseItem &item) const { string result = symbol_name(item.lhs()) + " ->"; size_t i = 0; for (const ProductionStep &step : *item.production) { if (i == item.step_index) result += " \u2022"; result += " " + symbol_name(step.symbol); i++; } if (i == item.step_index) result += " \u2022"; result += " (prec " + to_string(item.precedence()); switch (item.associativity()) { case rules::AssociativityNone: result += ")"; break; case rules::AssociativityLeft: result += ", assoc left)"; break; case rules::AssociativityRight: result += ", assoc right)"; break; } return result; } set<Symbol> get_first_set(const Symbol &start_symbol) { set<Symbol> result; vector<Symbol> symbols_to_process({ start_symbol }); while (!symbols_to_process.empty()) { Symbol symbol = symbols_to_process.back(); symbols_to_process.pop_back(); if (result.insert(symbol).second) for (const Production &production : grammar.productions(symbol)) if (!production.empty()) symbols_to_process.push_back(production[0].symbol); } return result; } PrecedenceRange precedence_values_for_item_set(const ParseItemSet &item_set) { PrecedenceRange result; for (const auto &pair : item_set.entries) { const ParseItem &item = pair.first; if (item.step_index > 0) result.add(item.production->at(item.step_index - 1).precedence); } return result; } string symbol_name(const rules::Symbol &symbol) const { if (symbol.is_built_in()) { if (symbol == rules::ERROR()) return "ERROR"; else if (symbol == rules::END_OF_INPUT()) return "END_OF_INPUT"; else return ""; } else if (symbol.is_token) { const Variable &variable = lexical_grammar.variables[symbol.index]; if (variable.type == VariableTypeNamed) return variable.name; else return "'" + variable.name + "'"; } else { return grammar.variables[symbol.index].name; } } }; pair<ParseTable, const GrammarError *> build_parse_table( const SyntaxGrammar &grammar, const LexicalGrammar &lex_grammar) { return ParseTableBuilder(grammar, lex_grammar).build(); } } // namespace build_tables } // namespace tree_sitter <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2010 Juergen Riegel <FreeCAD@juergen-riegel.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRep_Builder.hxx> # include <BRepBndLib.hxx> # include <BRepPrimAPI_MakeRevol.hxx> # include <BRepBuilderAPI_Copy.hxx> # include <BRepBuilderAPI_MakeFace.hxx> # include <TopoDS.hxx> # include <TopoDS_Face.hxx> # include <TopoDS_Wire.hxx> # include <TopExp_Explorer.hxx> # include <BRepAlgoAPI_Fuse.hxx> #endif #include <Base/Placement.h> #include <Mod/Part/App/Part2DObject.h> #include "FeatureRevolution.h" using namespace PartDesign; namespace PartDesign { PROPERTY_SOURCE(PartDesign::Revolution, PartDesign::SketchBased) Revolution::Revolution() { ADD_PROPERTY(Base,(Base::Vector3f(0.0f,0.0f,0.0f))); ADD_PROPERTY(Axis,(Base::Vector3f(0.0f,1.0f,0.0f))); ADD_PROPERTY(Angle,(360.0)); } short Revolution::mustExecute() const { if (Sketch.isTouched() || Axis.isTouched() || Base.isTouched() || Angle.isTouched()) return 1; return 0; } App::DocumentObjectExecReturn *Revolution::execute(void) { App::DocumentObject* link = Sketch.getValue(); if (!link) return new App::DocumentObjectExecReturn("No sketch linked"); if (!link->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId())) return new App::DocumentObjectExecReturn("Linked object is not a Sketch or Part2DObject"); TopoDS_Shape shape = static_cast<Part::Part2DObject*>(link)->Shape.getShape()._Shape; if (shape.IsNull()) return new App::DocumentObjectExecReturn("Linked shape object is empty"); // this is a workaround for an obscure OCC bug which leads to empty tessellations // for some faces. Making an explicit copy of the linked shape seems to fix it. // The error only happens when re-computing the shape. if (!this->Shape.getValue().IsNull()) { BRepBuilderAPI_Copy copy(shape); shape = copy.Shape(); if (shape.IsNull()) return new App::DocumentObjectExecReturn("Linked shape object is empty"); } TopExp_Explorer ex; std::vector<TopoDS_Wire> wires; for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next()) { wires.push_back(TopoDS::Wire(ex.Current())); } if (wires.empty()) // there can be several wires return new App::DocumentObjectExecReturn("Linked shape object is not a wire"); #if 0 App::DocumentObject* support = sketch->Support.getValue(); Base::Placement placement = sketch->Placement.getValue(); Base::Vector3d axis(0,1,0); placement.getRotation().multVec(axis, axis); Base::BoundBox3d bbox = sketch->Shape.getBoundingBox(); bbox.Enlarge(0.1); Base::Vector3d base(bbox.MaxX, bbox.MaxY, bbox.MaxZ); #endif // get the Sketch plane Base::Placement SketchPos = static_cast<Part::Part2DObject*>(link)->Placement.getValue(); Base::Rotation SketchOrientation = SketchPos.getRotation(); // get rvolve axis Base::Vector3f v = Axis.getValue(); Base::Vector3d SketchOrientationVector(v.x,v.y,v.z); SketchOrientation.multVec(SketchOrientationVector,SketchOrientationVector); Base::Vector3f b(0,0,0); gp_Pnt pnt(b.x,b.y,b.z); gp_Dir dir(SketchOrientationVector.x,SketchOrientationVector.y,SketchOrientationVector.z); // get the support of the Sketch if any App::DocumentObject* SupportLink = static_cast<Part::Part2DObject*>(link)->Support.getValue(); Part::Feature *SupportObject = 0; if(SupportLink && SupportLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) SupportObject = static_cast<Part::Feature*>(SupportLink); TopoDS_Shape aFace = makeFace(wires); if (aFace.IsNull()) return new App::DocumentObjectExecReturn("Creating a face from sketch failed"); // revolve the face to a solid BRepPrimAPI_MakeRevol RevolMaker(aFace,gp_Ax1(pnt, dir),Angle.getValue()/180.0f*Standard_PI); if (RevolMaker.IsDone()) { TopoDS_Shape result = RevolMaker.Shape(); // if the sketch has a support fuse them to get one result object (PAD!) if (SupportObject) { const TopoDS_Shape& support = SupportObject->Shape.getValue(); if (!support.IsNull() && support.ShapeType() == TopAbs_SOLID) { // Let's call algorithm computing a fuse operation: BRepAlgoAPI_Fuse mkFuse(support, result); // Let's check if the fusion has been successful if (!mkFuse.IsDone()) throw Base::Exception("Fusion with support failed"); result = mkFuse.Shape(); } } this->Shape.setValue(result); } else return new App::DocumentObjectExecReturn("Could not extrude the sketch!"); return App::DocumentObject::StdReturn; } } <commit_msg>+ fix bug in revolve feature<commit_after>/*************************************************************************** * Copyright (c) 2010 Juergen Riegel <FreeCAD@juergen-riegel.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRep_Builder.hxx> # include <BRepBndLib.hxx> # include <BRepPrimAPI_MakeRevol.hxx> # include <BRepBuilderAPI_Copy.hxx> # include <BRepBuilderAPI_MakeFace.hxx> # include <TopoDS.hxx> # include <TopoDS_Face.hxx> # include <TopoDS_Wire.hxx> # include <TopExp_Explorer.hxx> # include <BRepAlgoAPI_Fuse.hxx> #endif #include <Base/Placement.h> #include <Base/Tools.h> #include <Mod/Part/App/Part2DObject.h> #include "FeatureRevolution.h" using namespace PartDesign; namespace PartDesign { PROPERTY_SOURCE(PartDesign::Revolution, PartDesign::SketchBased) Revolution::Revolution() { ADD_PROPERTY(Base,(Base::Vector3f(0.0f,0.0f,0.0f))); ADD_PROPERTY(Axis,(Base::Vector3f(0.0f,1.0f,0.0f))); ADD_PROPERTY(Angle,(360.0)); } short Revolution::mustExecute() const { if (Sketch.isTouched() || Axis.isTouched() || Base.isTouched() || Angle.isTouched()) return 1; return 0; } App::DocumentObjectExecReturn *Revolution::execute(void) { App::DocumentObject* link = Sketch.getValue(); if (!link) return new App::DocumentObjectExecReturn("No sketch linked"); if (!link->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId())) return new App::DocumentObjectExecReturn("Linked object is not a Sketch or Part2DObject"); TopoDS_Shape shape = static_cast<Part::Part2DObject*>(link)->Shape.getShape()._Shape; if (shape.IsNull()) return new App::DocumentObjectExecReturn("Linked shape object is empty"); // this is a workaround for an obscure OCC bug which leads to empty tessellations // for some faces. Making an explicit copy of the linked shape seems to fix it. // The error only happens when re-computing the shape. if (!this->Shape.getValue().IsNull()) { BRepBuilderAPI_Copy copy(shape); shape = copy.Shape(); if (shape.IsNull()) return new App::DocumentObjectExecReturn("Linked shape object is empty"); } TopExp_Explorer ex; std::vector<TopoDS_Wire> wires; for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next()) { wires.push_back(TopoDS::Wire(ex.Current())); } if (wires.empty()) // there can be several wires return new App::DocumentObjectExecReturn("Linked shape object is not a wire"); #if 0 App::DocumentObject* support = sketch->Support.getValue(); Base::Placement placement = sketch->Placement.getValue(); Base::Vector3d axis(0,1,0); placement.getRotation().multVec(axis, axis); Base::BoundBox3d bbox = sketch->Shape.getBoundingBox(); bbox.Enlarge(0.1); Base::Vector3d base(bbox.MaxX, bbox.MaxY, bbox.MaxZ); #endif // get the Sketch plane Base::Placement SketchPos = static_cast<Part::Part2DObject*>(link)->Placement.getValue(); Base::Rotation SketchOrientation = SketchPos.getRotation(); // get rvolve axis Base::Vector3f v = Axis.getValue(); Base::Vector3d SketchOrientationVector(v.x,v.y,v.z); SketchOrientation.multVec(SketchOrientationVector,SketchOrientationVector); Base::Vector3f b = Base.getValue(); gp_Pnt pnt(b.x,b.y,b.z); gp_Dir dir(SketchOrientationVector.x,SketchOrientationVector.y,SketchOrientationVector.z); // get the support of the Sketch if any App::DocumentObject* SupportLink = static_cast<Part::Part2DObject*>(link)->Support.getValue(); Part::Feature *SupportObject = 0; if (SupportLink && SupportLink->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) SupportObject = static_cast<Part::Feature*>(SupportLink); TopoDS_Shape aFace = makeFace(wires); if (aFace.IsNull()) return new App::DocumentObjectExecReturn("Creating a face from sketch failed"); // revolve the face to a solid BRepPrimAPI_MakeRevol RevolMaker(aFace,gp_Ax1(pnt, dir), Base::toRadians<double>(Angle.getValue())); if (RevolMaker.IsDone()) { TopoDS_Shape result = RevolMaker.Shape(); // if the sketch has a support fuse them to get one result object (PAD!) if (SupportObject) { const TopoDS_Shape& support = SupportObject->Shape.getValue(); if (!support.IsNull() && support.ShapeType() == TopAbs_SOLID) { // Let's call algorithm computing a fuse operation: BRepAlgoAPI_Fuse mkFuse(support, result); // Let's check if the fusion has been successful if (!mkFuse.IsDone()) throw Base::Exception("Fusion with support failed"); result = mkFuse.Shape(); } } this->Shape.setValue(result); } else return new App::DocumentObjectExecReturn("Could not revolve the sketch!"); return App::DocumentObject::StdReturn; } } <|endoftext|>
<commit_before>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/DeferredGeometryPass.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Graphics/AbstractViewer.hpp> #include <Nazara/Graphics/DeferredRenderTechnique.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/Scene.hpp> #include <Nazara/Renderer/Renderer.hpp> #include <Nazara/Renderer/RenderTexture.hpp> #include <Nazara/Renderer/ShaderLibrary.hpp> #include <Nazara/Utility/BufferMapper.hpp> #include <Nazara/Utility/StaticMesh.hpp> #include <Nazara/Utility/VertexStruct.hpp> #include <memory> #include <Nazara/Graphics/Debug.hpp> NzDeferredGeometryPass::NzDeferredGeometryPass() { m_clearShader = NzShaderLibrary::Get("DeferredGBufferClear"); m_clearStates.parameters[nzRendererParameter_DepthBuffer] = true; m_clearStates.parameters[nzRendererParameter_FaceCulling] = true; m_clearStates.parameters[nzRendererParameter_StencilTest] = true; m_clearStates.depthFunc = nzRendererComparison_Always; m_clearStates.frontFace.stencilCompare = nzRendererComparison_Always; m_clearStates.frontFace.stencilPass = nzStencilOperation_Zero; } NzDeferredGeometryPass::~NzDeferredGeometryPass() = default; bool NzDeferredGeometryPass::Process(const NzScene* scene, unsigned int firstWorkTexture, unsigned secondWorkTexture) const { NazaraUnused(firstWorkTexture); NazaraUnused(secondWorkTexture); NzAbstractViewer* viewer = scene->GetViewer(); bool instancingEnabled = m_deferredTechnique->IsInstancingEnabled(); m_GBufferRTT->SetColorTargets({0, 1, 2}); // G-Buffer NzRenderer::SetTarget(m_GBufferRTT); NzRenderer::SetViewport(NzRecti(0, 0, m_dimensions.x, m_dimensions.y)); NzRenderer::SetRenderStates(m_clearStates); NzRenderer::SetShader(m_clearShader); NzRenderer::DrawFullscreenQuad(); NzRenderer::SetMatrix(nzMatrixType_Projection, viewer->GetProjectionMatrix()); NzRenderer::SetMatrix(nzMatrixType_View, viewer->GetViewMatrix()); const NzShader* lastShader = nullptr; for (auto& matIt : m_renderQueue->opaqueModels) { bool& used = std::get<0>(matIt.second); if (used) { bool& renderQueueInstancing = std::get<1>(matIt.second); NzDeferredRenderQueue::MeshInstanceContainer& meshInstances = std::get<2>(matIt.second); if (!meshInstances.empty()) { const NzMaterial* material = matIt.first; // Nous utilisons de l'instancing que lorsqu'aucune lumière (autre que directionnelle) n'est active // Ceci car l'instancing n'est pas compatible avec la recherche des lumières les plus proches // (Le deferred shading n'a pas ce problème) bool useInstancing = instancingEnabled && renderQueueInstancing; // On commence par récupérer le programme du matériau nzUInt32 flags = nzShaderFlags_Deferred; if (useInstancing) flags |= nzShaderFlags_Instancing; const NzShader* shader = material->Apply(flags); // Les uniformes sont conservées au sein d'un programme, inutile de les renvoyer tant qu'il ne change pas if (shader != lastShader) { // Couleur ambiante de la scène shader->SendColor(shader->GetUniformLocation(nzShaderUniform_SceneAmbient), scene->GetAmbientColor()); // Position de la caméra shader->SendVector(shader->GetUniformLocation(nzShaderUniform_EyePosition), viewer->GetEyePosition()); lastShader = shader; } // Meshes for (auto& meshIt : meshInstances) { const NzMeshData& meshData = meshIt.first; std::vector<NzMatrix4f>& instances = meshIt.second; if (!instances.empty()) { const NzIndexBuffer* indexBuffer = meshData.indexBuffer; const NzVertexBuffer* vertexBuffer = meshData.vertexBuffer; // Gestion du draw call avant la boucle de rendu std::function<void(nzPrimitiveMode, unsigned int, unsigned int)> DrawFunc; std::function<void(unsigned int, nzPrimitiveMode, unsigned int, unsigned int)> InstancedDrawFunc; unsigned int indexCount; if (indexBuffer) { DrawFunc = NzRenderer::DrawIndexedPrimitives; InstancedDrawFunc = NzRenderer::DrawIndexedPrimitivesInstanced; indexCount = indexBuffer->GetIndexCount(); } else { DrawFunc = NzRenderer::DrawPrimitives; InstancedDrawFunc = NzRenderer::DrawPrimitivesInstanced; indexCount = vertexBuffer->GetVertexCount(); } NzRenderer::SetIndexBuffer(indexBuffer); NzRenderer::SetVertexBuffer(vertexBuffer); if (useInstancing) { // On récupère le buffer d'instancing du Renderer et on le configure pour fonctionner avec des matrices NzVertexBuffer* instanceBuffer = NzRenderer::GetInstanceBuffer(); instanceBuffer->SetVertexDeclaration(NzVertexDeclaration::Get(nzVertexLayout_Matrix4)); const NzMatrix4f* instanceMatrices = &instances[0]; unsigned int instanceCount = instances.size(); unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // Le nombre de matrices que peut contenir le buffer while (instanceCount > 0) { // On calcule le nombre d'instances que l'on pourra afficher cette fois-ci (Selon la taille du buffer d'instancing) unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // On remplit l'instancing buffer avec nos matrices world instanceBuffer->Fill(instanceMatrices, 0, renderedInstanceCount, true); instanceMatrices += renderedInstanceCount; // Et on affiche InstancedDrawFunc(renderedInstanceCount, meshData.primitiveMode, 0, indexCount); } } else { // Sans instancing, on doit effectuer un drawcall pour chaque instance // Cela reste néanmoins plus rapide que l'instancing en dessous d'un certain nombre d'instances // À cause du temps de modification du buffer d'instancing for (const NzMatrix4f& matrix : instances) { NzRenderer::SetMatrix(nzMatrixType_World, matrix); DrawFunc(meshData.primitiveMode, 0, indexCount); } } instances.clear(); } } } // Et on remet à zéro les données renderQueueInstancing = false; used = false; } } return false; // On ne fait que remplir le G-Buffer, les work texture ne sont pas affectées } bool NzDeferredGeometryPass::Resize(const NzVector2ui& dimensions) { NzDeferredRenderPass::Resize(dimensions); /* G-Buffer: Texture0: Diffuse Color + Flags Texture1: Normal map + Depth Texture2: Specular value + Shininess Texture3: N/A */ try { NzErrorFlags errFlags(nzErrorFlag_ThrowException); unsigned int width = dimensions.x; unsigned int height = dimensions.y; m_depthStencilBuffer->Create(nzPixelFormat_Depth24Stencil8, width, height); m_GBuffer[0]->Create(nzImageType_2D, nzPixelFormat_RGBA8, width, height); // Texture 0 : Diffuse Color + Specular m_GBuffer[1]->Create(nzImageType_2D, nzPixelFormat_RG16F, width, height); // Texture 1 : Encoded normal m_GBuffer[2]->Create(nzImageType_2D, nzPixelFormat_RGBA8, width, height); // Texture 2 : Depth (24bits) + Shininess m_GBufferRTT->Create(true); m_GBufferRTT->AttachTexture(nzAttachmentPoint_Color, 0, m_GBuffer[0]); m_GBufferRTT->AttachTexture(nzAttachmentPoint_Color, 1, m_GBuffer[1]); m_GBufferRTT->AttachTexture(nzAttachmentPoint_Color, 2, m_GBuffer[2]); // Texture 3 : Emission map ? m_GBufferRTT->AttachBuffer(nzAttachmentPoint_DepthStencil, 0, m_depthStencilBuffer); m_GBufferRTT->Unlock(); m_workRTT->Create(true); for (unsigned int i = 0; i < 2; ++i) { m_workTextures[i]->Create(nzImageType_2D, nzPixelFormat_RGBA8, width, height); m_workRTT->AttachTexture(nzAttachmentPoint_Color, i, m_workTextures[i]); } m_workRTT->AttachBuffer(nzAttachmentPoint_DepthStencil, 0, m_depthStencilBuffer); m_workRTT->Unlock(); if (!m_workRTT->IsComplete() || !m_GBufferRTT->IsComplete()) { NazaraError("Incomplete RTT"); return false; } return true; } catch (const std::exception& e) { NazaraError("Failed to create G-Buffer RTT: " + NzString(e.what())); return false; } } <commit_msg>Fixed some comments<commit_after>// Copyright (C) 2014 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Graphics/DeferredGeometryPass.hpp> #include <Nazara/Core/ErrorFlags.hpp> #include <Nazara/Graphics/AbstractViewer.hpp> #include <Nazara/Graphics/DeferredRenderTechnique.hpp> #include <Nazara/Graphics/Material.hpp> #include <Nazara/Graphics/Scene.hpp> #include <Nazara/Renderer/Renderer.hpp> #include <Nazara/Renderer/RenderTexture.hpp> #include <Nazara/Renderer/ShaderLibrary.hpp> #include <Nazara/Utility/BufferMapper.hpp> #include <Nazara/Utility/StaticMesh.hpp> #include <Nazara/Utility/VertexStruct.hpp> #include <memory> #include <Nazara/Graphics/Debug.hpp> NzDeferredGeometryPass::NzDeferredGeometryPass() { m_clearShader = NzShaderLibrary::Get("DeferredGBufferClear"); m_clearStates.parameters[nzRendererParameter_DepthBuffer] = true; m_clearStates.parameters[nzRendererParameter_FaceCulling] = true; m_clearStates.parameters[nzRendererParameter_StencilTest] = true; m_clearStates.depthFunc = nzRendererComparison_Always; m_clearStates.frontFace.stencilCompare = nzRendererComparison_Always; m_clearStates.frontFace.stencilPass = nzStencilOperation_Zero; } NzDeferredGeometryPass::~NzDeferredGeometryPass() = default; bool NzDeferredGeometryPass::Process(const NzScene* scene, unsigned int firstWorkTexture, unsigned secondWorkTexture) const { NazaraUnused(firstWorkTexture); NazaraUnused(secondWorkTexture); NzAbstractViewer* viewer = scene->GetViewer(); bool instancingEnabled = m_deferredTechnique->IsInstancingEnabled(); m_GBufferRTT->SetColorTargets({0, 1, 2}); // G-Buffer NzRenderer::SetTarget(m_GBufferRTT); NzRenderer::SetViewport(NzRecti(0, 0, m_dimensions.x, m_dimensions.y)); NzRenderer::SetRenderStates(m_clearStates); NzRenderer::SetShader(m_clearShader); NzRenderer::DrawFullscreenQuad(); NzRenderer::SetMatrix(nzMatrixType_Projection, viewer->GetProjectionMatrix()); NzRenderer::SetMatrix(nzMatrixType_View, viewer->GetViewMatrix()); const NzShader* lastShader = nullptr; for (auto& matIt : m_renderQueue->opaqueModels) { bool& used = std::get<0>(matIt.second); if (used) { bool& renderQueueInstancing = std::get<1>(matIt.second); NzDeferredRenderQueue::MeshInstanceContainer& meshInstances = std::get<2>(matIt.second); if (!meshInstances.empty()) { const NzMaterial* material = matIt.first; bool useInstancing = instancingEnabled && renderQueueInstancing; // On commence par récupérer le programme du matériau nzUInt32 flags = nzShaderFlags_Deferred; if (useInstancing) flags |= nzShaderFlags_Instancing; const NzShader* shader = material->Apply(flags); // Les uniformes sont conservées au sein d'un programme, inutile de les renvoyer tant qu'il ne change pas if (shader != lastShader) { // Couleur ambiante de la scène shader->SendColor(shader->GetUniformLocation(nzShaderUniform_SceneAmbient), scene->GetAmbientColor()); // Position de la caméra shader->SendVector(shader->GetUniformLocation(nzShaderUniform_EyePosition), viewer->GetEyePosition()); lastShader = shader; } // Meshes for (auto& meshIt : meshInstances) { const NzMeshData& meshData = meshIt.first; std::vector<NzMatrix4f>& instances = meshIt.second; if (!instances.empty()) { const NzIndexBuffer* indexBuffer = meshData.indexBuffer; const NzVertexBuffer* vertexBuffer = meshData.vertexBuffer; // Gestion du draw call avant la boucle de rendu std::function<void(nzPrimitiveMode, unsigned int, unsigned int)> DrawFunc; std::function<void(unsigned int, nzPrimitiveMode, unsigned int, unsigned int)> InstancedDrawFunc; unsigned int indexCount; if (indexBuffer) { DrawFunc = NzRenderer::DrawIndexedPrimitives; InstancedDrawFunc = NzRenderer::DrawIndexedPrimitivesInstanced; indexCount = indexBuffer->GetIndexCount(); } else { DrawFunc = NzRenderer::DrawPrimitives; InstancedDrawFunc = NzRenderer::DrawPrimitivesInstanced; indexCount = vertexBuffer->GetVertexCount(); } NzRenderer::SetIndexBuffer(indexBuffer); NzRenderer::SetVertexBuffer(vertexBuffer); if (useInstancing) { // On récupère le buffer d'instancing du Renderer et on le configure pour fonctionner avec des matrices NzVertexBuffer* instanceBuffer = NzRenderer::GetInstanceBuffer(); instanceBuffer->SetVertexDeclaration(NzVertexDeclaration::Get(nzVertexLayout_Matrix4)); const NzMatrix4f* instanceMatrices = &instances[0]; unsigned int instanceCount = instances.size(); unsigned int maxInstanceCount = instanceBuffer->GetVertexCount(); // Le nombre de matrices que peut contenir le buffer while (instanceCount > 0) { // On calcule le nombre d'instances que l'on pourra afficher cette fois-ci (Selon la taille du buffer d'instancing) unsigned int renderedInstanceCount = std::min(instanceCount, maxInstanceCount); instanceCount -= renderedInstanceCount; // On remplit l'instancing buffer avec nos matrices world instanceBuffer->Fill(instanceMatrices, 0, renderedInstanceCount, true); instanceMatrices += renderedInstanceCount; // Et on affiche InstancedDrawFunc(renderedInstanceCount, meshData.primitiveMode, 0, indexCount); } } else { // Sans instancing, on doit effectuer un draw call pour chaque instance // Cela reste néanmoins plus rapide que l'instancing en dessous d'un certain nombre d'instances // À cause du temps de modification du buffer d'instancing for (const NzMatrix4f& matrix : instances) { NzRenderer::SetMatrix(nzMatrixType_World, matrix); DrawFunc(meshData.primitiveMode, 0, indexCount); } } instances.clear(); } } } // Et on remet à zéro les données renderQueueInstancing = false; used = false; } } return false; // On ne fait que remplir le G-Buffer, les work texture ne sont pas affectées } bool NzDeferredGeometryPass::Resize(const NzVector2ui& dimensions) { NzDeferredRenderPass::Resize(dimensions); /* G-Buffer: Texture0: Diffuse Color + Flags Texture1: Normal map + Depth Texture2: Specular value + Shininess Texture3: N/A */ try { NzErrorFlags errFlags(nzErrorFlag_ThrowException); unsigned int width = dimensions.x; unsigned int height = dimensions.y; m_depthStencilBuffer->Create(nzPixelFormat_Depth24Stencil8, width, height); m_GBuffer[0]->Create(nzImageType_2D, nzPixelFormat_RGBA8, width, height); // Texture 0 : Diffuse Color + Specular m_GBuffer[1]->Create(nzImageType_2D, nzPixelFormat_RG16F, width, height); // Texture 1 : Encoded normal m_GBuffer[2]->Create(nzImageType_2D, nzPixelFormat_RGBA8, width, height); // Texture 2 : Depth (24bits) + Shininess m_GBufferRTT->Create(true); m_GBufferRTT->AttachTexture(nzAttachmentPoint_Color, 0, m_GBuffer[0]); m_GBufferRTT->AttachTexture(nzAttachmentPoint_Color, 1, m_GBuffer[1]); m_GBufferRTT->AttachTexture(nzAttachmentPoint_Color, 2, m_GBuffer[2]); // Texture 3 : Emission map ? m_GBufferRTT->AttachBuffer(nzAttachmentPoint_DepthStencil, 0, m_depthStencilBuffer); m_GBufferRTT->Unlock(); m_workRTT->Create(true); for (unsigned int i = 0; i < 2; ++i) { m_workTextures[i]->Create(nzImageType_2D, nzPixelFormat_RGBA8, width, height); m_workRTT->AttachTexture(nzAttachmentPoint_Color, i, m_workTextures[i]); } m_workRTT->AttachBuffer(nzAttachmentPoint_DepthStencil, 0, m_depthStencilBuffer); m_workRTT->Unlock(); if (!m_workRTT->IsComplete() || !m_GBufferRTT->IsComplete()) { NazaraError("Incomplete RTT"); return false; } return true; } catch (const std::exception& e) { NazaraError("Failed to create G-Buffer RTT: " + NzString(e.what())); return false; } } <|endoftext|>
<commit_before>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2009 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ #ifndef OPENMESH_PROPERTYCONTAINER #define OPENMESH_PROPERTYCONTAINER // Use static casts when not debugging #ifdef NDEBUG #define OM_FORCE_STATIC_CAST #endif #include <OpenMesh/Core/Utils/Property.hh> //----------------------------------------------------------------------------- namespace OpenMesh { //== FORWARDDECLARATIONS ====================================================== class BaseKernel; //== CLASS DEFINITION ========================================================= /// A a container for properties. class PropertyContainer { public: //-------------------------------------------------- constructor / destructor PropertyContainer() {} virtual ~PropertyContainer() { std::for_each(properties_.begin(), properties_.end(), Delete()); } //------------------------------------------------------------- info / access typedef std::vector<BaseProperty*> Properties; const Properties& properties() const { return properties_; } size_t size() const { return properties_.size(); } //--------------------------------------------------------- copy / assignment PropertyContainer(const PropertyContainer& _rhs) { operator=(_rhs); } PropertyContainer& operator=(const PropertyContainer& _rhs) { clear(); properties_ = _rhs.properties_; Properties::iterator p_it=properties_.begin(), p_end=properties_.end(); for (; p_it!=p_end; ++p_it) if (*p_it) *p_it = (*p_it)->clone(); return *this; } //--------------------------------------------------------- manage properties template <class T> BasePropHandleT<T> add(const T&, const std::string& _name="<unknown>") { Properties::iterator p_it=properties_.begin(), p_end=properties_.end(); int idx=0; for ( ; p_it!=p_end && *p_it!=NULL; ++p_it, ++idx ) {}; if (p_it==p_end) properties_.push_back(NULL); properties_[idx] = new PropertyT<T>(_name); return BasePropHandleT<T>(idx); } template <class T> BasePropHandleT<T> handle(const T&, const std::string& _name) const { Properties::const_iterator p_it = properties_.begin(); for (int idx=0; p_it != properties_.end(); ++p_it, ++idx) { if (*p_it != NULL && (*p_it)->name() == _name //skip deleted properties // Skip type check #ifndef OM_FORCE_STATIC_CAST && dynamic_cast<PropertyT<T>*>(properties_[idx]) != NULL //check type #endif ) { return BasePropHandleT<T>(idx); } } return BasePropHandleT<T>(); } BaseProperty* property( const std::string& _name ) const { Properties::const_iterator p_it = properties_.begin(); for (int idx=0; p_it != properties_.end(); ++p_it, ++idx) { if (*p_it != NULL && (*p_it)->name() == _name) //skip deleted properties { return *p_it; } } return NULL; } template <class T> PropertyT<T>& property(BasePropHandleT<T> _h) { assert(_h.idx() >= 0 && _h.idx() < (int)properties_.size()); assert(properties_[_h.idx()] != NULL); #ifdef OM_FORCE_STATIC_CAST return *static_cast <PropertyT<T>*> (properties_[_h.idx()]); #else PropertyT<T>* p = dynamic_cast<PropertyT<T>*>(properties_[_h.idx()]); assert(p != NULL); return *p; #endif } template <class T> const PropertyT<T>& property(BasePropHandleT<T> _h) const { assert(_h.idx() >= 0 && _h.idx() < (int)properties_.size()); assert(properties_[_h.idx()] != NULL); #ifdef OM_FORCE_STATIC_CAST return *static_cast<PropertyT<T>*>(properties_[_h.idx()]); #else PropertyT<T>* p = dynamic_cast<PropertyT<T>*>(properties_[_h.idx()]); assert(p != NULL); return *p; #endif } template <class T> void remove(BasePropHandleT<T> _h) { assert(_h.idx() >= 0 && _h.idx() < (int)properties_.size()); delete properties_[_h.idx()]; properties_[_h.idx()] = NULL; } void clear() { // Clear properties vector: // Replaced the old version with new one // which performs a swap to clear values and // deallocate memory. // Old version (changed 22.07.09) { // std::for_each(properties_.begin(), properties_.end(), Delete()); // } std::for_each(properties_.begin(), properties_.end(), ClearAll()); } //---------------------------------------------------- synchronize properties void reserve(size_t _n) const { std::for_each(properties_.begin(), properties_.end(), Reserve(_n)); } void resize(size_t _n) const { std::for_each(properties_.begin(), properties_.end(), Resize(_n)); } void swap(size_t _i0, size_t _i1) const { std::for_each(properties_.begin(), properties_.end(), Swap(_i0, _i1)); } protected: // generic add/get size_t _add( BaseProperty* _bp ) { Properties::iterator p_it=properties_.begin(), p_end=properties_.end(); size_t idx=0; for (; p_it!=p_end && *p_it!=NULL; ++p_it, ++idx) {}; if (p_it==p_end) properties_.push_back(NULL); properties_[idx] = _bp; return idx; } BaseProperty& _property( size_t _idx ) { assert( _idx < properties_.size()); assert( properties_[_idx] != NULL); BaseProperty *p = properties_[_idx]; assert( p != NULL ); return *p; } const BaseProperty& _property( size_t _idx ) const { assert( _idx < properties_.size()); assert( properties_[_idx] != NULL); BaseProperty *p = properties_[_idx]; assert( p != NULL ); return *p; } typedef Properties::iterator iterator; typedef Properties::const_iterator const_iterator; iterator begin() { return properties_.begin(); } iterator end() { return properties_.end(); } const_iterator begin() const { return properties_.begin(); } const_iterator end() const { return properties_.end(); } friend class BaseKernel; private: //-------------------------------------------------- synchronization functors #ifndef DOXY_IGNORE_THIS struct Reserve { Reserve(size_t _n) : n_(_n) {} void operator()(BaseProperty* _p) const { if (_p) _p->reserve(n_); } size_t n_; }; struct Resize { Resize(size_t _n) : n_(_n) {} void operator()(BaseProperty* _p) const { if (_p) _p->resize(n_); } size_t n_; }; struct ClearAll { ClearAll() {} void operator()(BaseProperty* _p) const { if (_p) _p->clear(); } }; struct Swap { Swap(size_t _i0, size_t _i1) : i0_(_i0), i1_(_i1) {} void operator()(BaseProperty* _p) const { if (_p) _p->swap(i0_, i1_); } size_t i0_, i1_; }; struct Delete { Delete() {} void operator()(BaseProperty* _p) const { if (_p) delete _p; _p=NULL; } }; #endif Properties properties_; }; }//namespace OpenMesh #endif//OPENMESH_PROPERTYCONTAINER <commit_msg>Memory leak in Assignment patch (Thanks to <commit_after>/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2009 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh 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 LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ #ifndef OPENMESH_PROPERTYCONTAINER #define OPENMESH_PROPERTYCONTAINER // Use static casts when not debugging #ifdef NDEBUG #define OM_FORCE_STATIC_CAST #endif #include <OpenMesh/Core/Utils/Property.hh> //----------------------------------------------------------------------------- namespace OpenMesh { //== FORWARDDECLARATIONS ====================================================== class BaseKernel; //== CLASS DEFINITION ========================================================= /// A a container for properties. class PropertyContainer { public: //-------------------------------------------------- constructor / destructor PropertyContainer() {} virtual ~PropertyContainer() { std::for_each(properties_.begin(), properties_.end(), Delete()); } //------------------------------------------------------------- info / access typedef std::vector<BaseProperty*> Properties; const Properties& properties() const { return properties_; } size_t size() const { return properties_.size(); } //--------------------------------------------------------- copy / assignment PropertyContainer(const PropertyContainer& _rhs) { operator=(_rhs); } PropertyContainer& operator=(const PropertyContainer& _rhs) { // The assignment below relies on all previous BaseProperty* elements having been deleted std::for_each(properties_.begin(), properties_.end(), Delete()); properties_ = _rhs.properties_; Properties::iterator p_it=properties_.begin(), p_end=properties_.end(); for (; p_it!=p_end; ++p_it) if (*p_it) *p_it = (*p_it)->clone(); return *this; } //--------------------------------------------------------- manage properties template <class T> BasePropHandleT<T> add(const T&, const std::string& _name="<unknown>") { Properties::iterator p_it=properties_.begin(), p_end=properties_.end(); int idx=0; for ( ; p_it!=p_end && *p_it!=NULL; ++p_it, ++idx ) {}; if (p_it==p_end) properties_.push_back(NULL); properties_[idx] = new PropertyT<T>(_name); return BasePropHandleT<T>(idx); } template <class T> BasePropHandleT<T> handle(const T&, const std::string& _name) const { Properties::const_iterator p_it = properties_.begin(); for (int idx=0; p_it != properties_.end(); ++p_it, ++idx) { if (*p_it != NULL && (*p_it)->name() == _name //skip deleted properties // Skip type check #ifndef OM_FORCE_STATIC_CAST && dynamic_cast<PropertyT<T>*>(properties_[idx]) != NULL //check type #endif ) { return BasePropHandleT<T>(idx); } } return BasePropHandleT<T>(); } BaseProperty* property( const std::string& _name ) const { Properties::const_iterator p_it = properties_.begin(); for (int idx=0; p_it != properties_.end(); ++p_it, ++idx) { if (*p_it != NULL && (*p_it)->name() == _name) //skip deleted properties { return *p_it; } } return NULL; } template <class T> PropertyT<T>& property(BasePropHandleT<T> _h) { assert(_h.idx() >= 0 && _h.idx() < (int)properties_.size()); assert(properties_[_h.idx()] != NULL); #ifdef OM_FORCE_STATIC_CAST return *static_cast <PropertyT<T>*> (properties_[_h.idx()]); #else PropertyT<T>* p = dynamic_cast<PropertyT<T>*>(properties_[_h.idx()]); assert(p != NULL); return *p; #endif } template <class T> const PropertyT<T>& property(BasePropHandleT<T> _h) const { assert(_h.idx() >= 0 && _h.idx() < (int)properties_.size()); assert(properties_[_h.idx()] != NULL); #ifdef OM_FORCE_STATIC_CAST return *static_cast<PropertyT<T>*>(properties_[_h.idx()]); #else PropertyT<T>* p = dynamic_cast<PropertyT<T>*>(properties_[_h.idx()]); assert(p != NULL); return *p; #endif } template <class T> void remove(BasePropHandleT<T> _h) { assert(_h.idx() >= 0 && _h.idx() < (int)properties_.size()); delete properties_[_h.idx()]; properties_[_h.idx()] = NULL; } void clear() { // Clear properties vector: // Replaced the old version with new one // which performs a swap to clear values and // deallocate memory. // Old version (changed 22.07.09) { // std::for_each(properties_.begin(), properties_.end(), Delete()); // } std::for_each(properties_.begin(), properties_.end(), ClearAll()); } //---------------------------------------------------- synchronize properties void reserve(size_t _n) const { std::for_each(properties_.begin(), properties_.end(), Reserve(_n)); } void resize(size_t _n) const { std::for_each(properties_.begin(), properties_.end(), Resize(_n)); } void swap(size_t _i0, size_t _i1) const { std::for_each(properties_.begin(), properties_.end(), Swap(_i0, _i1)); } protected: // generic add/get size_t _add( BaseProperty* _bp ) { Properties::iterator p_it=properties_.begin(), p_end=properties_.end(); size_t idx=0; for (; p_it!=p_end && *p_it!=NULL; ++p_it, ++idx) {}; if (p_it==p_end) properties_.push_back(NULL); properties_[idx] = _bp; return idx; } BaseProperty& _property( size_t _idx ) { assert( _idx < properties_.size()); assert( properties_[_idx] != NULL); BaseProperty *p = properties_[_idx]; assert( p != NULL ); return *p; } const BaseProperty& _property( size_t _idx ) const { assert( _idx < properties_.size()); assert( properties_[_idx] != NULL); BaseProperty *p = properties_[_idx]; assert( p != NULL ); return *p; } typedef Properties::iterator iterator; typedef Properties::const_iterator const_iterator; iterator begin() { return properties_.begin(); } iterator end() { return properties_.end(); } const_iterator begin() const { return properties_.begin(); } const_iterator end() const { return properties_.end(); } friend class BaseKernel; private: //-------------------------------------------------- synchronization functors #ifndef DOXY_IGNORE_THIS struct Reserve { Reserve(size_t _n) : n_(_n) {} void operator()(BaseProperty* _p) const { if (_p) _p->reserve(n_); } size_t n_; }; struct Resize { Resize(size_t _n) : n_(_n) {} void operator()(BaseProperty* _p) const { if (_p) _p->resize(n_); } size_t n_; }; struct ClearAll { ClearAll() {} void operator()(BaseProperty* _p) const { if (_p) _p->clear(); } }; struct Swap { Swap(size_t _i0, size_t _i1) : i0_(_i0), i1_(_i1) {} void operator()(BaseProperty* _p) const { if (_p) _p->swap(i0_, i1_); } size_t i0_, i1_; }; struct Delete { Delete() {} void operator()(BaseProperty* _p) const { if (_p) delete _p; _p=NULL; } }; #endif Properties properties_; }; }//namespace OpenMesh #endif//OPENMESH_PROPERTYCONTAINER <|endoftext|>
<commit_before>/** * Copyright (C) 2015-2016 Jessica James. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Written by Jessica James <jessica.aj@outlook.com> */ #include "Jupiter/IRC_Client.h" #include "RenX_Listen.h" #include "RenX_Core.h" #include "RenX_Server.h" using namespace Jupiter::literals; RenX_ListenPlugin::~RenX_ListenPlugin() { RenX_ListenPlugin::socket.close(); } bool RenX_ListenPlugin::initialize() { uint16_t port = this->config.get<uint16_t>("Port"_jrs, 21337); const Jupiter::ReadableString &address = this->config.get("Address"_jrs, "0.0.0.0"_jrs); RenX_ListenPlugin::serverSection = this->config.get("ServerSection"_jrs, this->getName()); return RenX_ListenPlugin::socket.bind(static_cast<std::string>(address).c_str(), port, true) && RenX_ListenPlugin::socket.setBlocking(false); } int RenX_ListenPlugin::think() { Jupiter::Socket *sock = socket.accept(); if (sock != nullptr) { sock->setBlocking(false); RenX::Server *server = new RenX::Server(std::move(*sock), RenX_ListenPlugin::serverSection); printf("Incoming server connected from %.*s:%u" ENDL, server->getSocketHostname().size(), server->getSocketHostname().c_str(), server->getSocketPort()); server->sendLogChan("Incoming server connected from " IRCCOLOR "12%.*s:%u", server->getSocketHostname().size(), server->getSocketHostname().c_str(), server->getSocketPort()); RenX::getCore()->addServer(server); delete sock; } return 0; } int RenX_ListenPlugin::OnRehash() { RenX::Plugin::OnRehash(); uint16_t port = this->config.get<uint16_t>("Port"_jrs, 21337); const Jupiter::ReadableString &address = this->config.get("Address"_jrs, "0.0.0.0"_jrs); RenX_ListenPlugin::serverSection = this->config.get("ServerSection"_jrs, this->getName()); if (port != RenX_ListenPlugin::socket.getRemotePort() || address.equals(RenX_ListenPlugin::socket.getRemoteHostname()) == false) { puts("Notice: The Renegade-X listening socket has been changed!"); RenX_ListenPlugin::socket.close(); return RenX_ListenPlugin::socket.bind(static_cast<std::string>(address).c_str(), port, true) == false || RenX_ListenPlugin::socket.setBlocking(false) == false; } return 0; } // Plugin instantiation and entry point. RenX_ListenPlugin pluginInstance; extern "C" JUPITER_EXPORT Jupiter::Plugin *getPlugin() { return &pluginInstance; } <commit_msg>Fixed `RenX_ListenPlugin::OnRehash`<commit_after>/** * Copyright (C) 2015-2016 Jessica James. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * Written by Jessica James <jessica.aj@outlook.com> */ #include "Jupiter/IRC_Client.h" #include "RenX_Listen.h" #include "RenX_Core.h" #include "RenX_Server.h" using namespace Jupiter::literals; RenX_ListenPlugin::~RenX_ListenPlugin() { RenX_ListenPlugin::socket.close(); } bool RenX_ListenPlugin::initialize() { uint16_t port = this->config.get<uint16_t>("Port"_jrs, 21337); const Jupiter::ReadableString &address = this->config.get("Address"_jrs, "0.0.0.0"_jrs); RenX_ListenPlugin::serverSection = this->config.get("ServerSection"_jrs, this->getName()); return RenX_ListenPlugin::socket.bind(static_cast<std::string>(address).c_str(), port, true) && RenX_ListenPlugin::socket.setBlocking(false); } int RenX_ListenPlugin::think() { Jupiter::Socket *sock = socket.accept(); if (sock != nullptr) { sock->setBlocking(false); RenX::Server *server = new RenX::Server(std::move(*sock), RenX_ListenPlugin::serverSection); printf("Incoming server connected from %.*s:%u" ENDL, server->getSocketHostname().size(), server->getSocketHostname().c_str(), server->getSocketPort()); server->sendLogChan("Incoming server connected from " IRCCOLOR "12%.*s:%u", server->getSocketHostname().size(), server->getSocketHostname().c_str(), server->getSocketPort()); RenX::getCore()->addServer(server); delete sock; } return 0; } int RenX_ListenPlugin::OnRehash() { RenX::Plugin::OnRehash(); uint16_t port = this->config.get<uint16_t>("Port"_jrs, 21337); const Jupiter::ReadableString &address = this->config.get("Address"_jrs, "0.0.0.0"_jrs); RenX_ListenPlugin::serverSection = this->config.get("ServerSection"_jrs, this->getName()); if (port != RenX_ListenPlugin::socket.getBoundPort() || address.equals(RenX_ListenPlugin::socket.getBoundHostname()) == false) { puts("Notice: The Renegade-X listening socket has been changed!"); RenX_ListenPlugin::socket.close(); return RenX_ListenPlugin::socket.bind(static_cast<std::string>(address).c_str(), port, true) == false || RenX_ListenPlugin::socket.setBlocking(false) == false; } return 0; } // Plugin instantiation and entry point. RenX_ListenPlugin pluginInstance; extern "C" JUPITER_EXPORT Jupiter::Plugin *getPlugin() { return &pluginInstance; } <|endoftext|>
<commit_before>#include "storagepaths.h" #include "../log/logger.h" #include <QAndroidJniObject> LOGGER(StoragePaths); class StoragePaths::Private { public: static bool initialized; static QDir scheduler; static QDir report; static QDir cache; static QDir log; static QDir crashDumps; }; bool StoragePaths::Private::initialized = false; QDir StoragePaths::Private::scheduler; QDir StoragePaths::Private::report; QDir StoragePaths::Private::cache; QDir StoragePaths::Private::log; QDir StoragePaths::Private::crashDumps; StoragePaths::StoragePaths() : d(NULL) { if (StoragePaths::Private::initialized) { return; } QAndroidJniObject storageHelper("de/hsaugsburg/informatik/mplane/StorageHelper"); StoragePaths::Private::scheduler = storageHelper.callObjectMethod<jstring>("getSchedulerDirectory").toString(); StoragePaths::Private::report = storageHelper.callObjectMethod<jstring>("getReportDirectory").toString(); StoragePaths::Private::cache = storageHelper.callObjectMethod<jstring>("getCacheDirectory").toString(); StoragePaths::Private::log = storageHelper.callObjectMethod<jstring>("getLogDirectory").toString(); StoragePaths::Private::crashDumps = storageHelper.callObjectMethod<jstring>("getCrashDumpDirectory").toString(); StoragePaths::Private::initialized = true; } StoragePaths::~StoragePaths() { } QDir StoragePaths::schedulerDirectory() const { return StoragePaths::Private::scheduler; } QDir StoragePaths::reportDirectory() const { return StoragePaths::Private::report; } QDir StoragePaths::cacheDirectory() const { return StoragePaths::Private::cache; } QDir StoragePaths::logDirectory() const { return StoragePaths::Private::log; } QDir StoragePaths::crashDumpDirectory() const { return StoragePaths::Private::crashDumps; } <commit_msg>fix Android storage paths<commit_after>#include "storagepaths.h" #include "../log/logger.h" #include <QAndroidJniObject> LOGGER(StoragePaths); class StoragePaths::Private { public: static bool initialized; static QDir scheduler; static QDir report; static QDir cache; static QDir log; static QDir crashDumps; static QDir localCopy; }; bool StoragePaths::Private::initialized = false; QDir StoragePaths::Private::scheduler; QDir StoragePaths::Private::report; QDir StoragePaths::Private::cache; QDir StoragePaths::Private::log; QDir StoragePaths::Private::crashDumps; QDir StoragePaths::Private::localCopy; StoragePaths::StoragePaths() : d(NULL) { if (StoragePaths::Private::initialized) { return; } QAndroidJniObject storageHelper("de/hsaugsburg/informatik/mplane/StorageHelper"); StoragePaths::Private::scheduler = storageHelper.callObjectMethod<jstring>("getSchedulerDirectory").toString(); StoragePaths::Private::report = storageHelper.callObjectMethod<jstring>("getReportDirectory").toString(); StoragePaths::Private::cache = storageHelper.callObjectMethod<jstring>("getCacheDirectory").toString(); StoragePaths::Private::log = storageHelper.callObjectMethod<jstring>("getLogDirectory").toString(); StoragePaths::Private::crashDumps = storageHelper.callObjectMethod<jstring>("getCrashDumpDirectory").toString(); StoragePaths::Private::localCopy = storageHelper.callObjectMethod<jstring>("getLocalCopyDirectory").toString(); StoragePaths::Private::initialized = true; } StoragePaths::~StoragePaths() { } QDir StoragePaths::schedulerDirectory() const { return StoragePaths::Private::scheduler; } QDir StoragePaths::reportDirectory() const { return StoragePaths::Private::report; } QDir StoragePaths::cacheDirectory() const { return StoragePaths::Private::cache; } QDir StoragePaths::logDirectory() const { return StoragePaths::Private::log; } QDir StoragePaths::crashDumpDirectory() const { return StoragePaths::Private::crashDumps; } QDir StoragePaths::localCopyDirectory() const { return StoragePaths::Private::localCopy; } <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <map> #include <occa/base.hpp> #include <occa/memory.hpp> #include <occa/device.hpp> #include <occa/modes/serial/memory.hpp> #include <occa/uva.hpp> #include <occa/tools/sys.hpp> namespace occa { //---[ memory_v ]--------------------- memory_v::memory_v(const occa::properties &properties_) { memInfo = uvaFlag::none; properties = properties_; ptr = NULL; uvaPtr = NULL; dHandle = NULL; size = 0; } memory_v::~memory_v() {} bool memory_v::isManaged() const { return (memInfo & uvaFlag::isManaged); } bool memory_v::inDevice() const { return (memInfo & uvaFlag::inDevice); } bool memory_v::isStale() const { return (memInfo & uvaFlag::isStale); } //---[ memory ]----------------------- memory::memory() : mHandle(NULL) {} memory::memory(void *uvaPtr) : mHandle(NULL) { ptrRangeMap::iterator it = uvaMap.find(uvaPtr); if (it != uvaMap.end()) { setMHandle(it->second); } else { setMHandle((memory_v*) uvaPtr); } } memory::memory(memory_v *mHandle_) : mHandle(NULL) { setMHandle(mHandle_); } memory::memory(const memory &m) : mHandle(NULL) { setMHandle(m.mHandle); } memory& memory::operator = (const memory &m) { setMHandle(m.mHandle); return *this; } memory::~memory() { removeMHandleRef(); } void memory::setMHandle(memory_v *mHandle_) { if (mHandle != mHandle_) { removeMHandleRef(); mHandle = mHandle_; mHandle->addRef(); } } void memory::setDHandle(device_v *dHandle) { mHandle->dHandle = dHandle; // If this is the very first reference, update the device references if (mHandle->getRefs() == 1) { mHandle->dHandle->addRef(); } } void memory::removeMHandleRef() { if (mHandle && !mHandle->removeRef()) { device_v *dHandle = mHandle->dHandle; free(); device::removeDHandleRefFrom(dHandle); delete mHandle; mHandle = NULL; } } void memory::dontUseRefs() { if (mHandle) { mHandle->dontUseRefs(); } } bool memory::isInitialized() const { return (mHandle != NULL); } memory& memory::swap(memory &m) { memory_v *mHandle_ = mHandle; mHandle = m.mHandle; m.mHandle = mHandle_; return *this; } void* memory::ptr() { return (mHandle ? mHandle->ptr : NULL); } const void* memory::ptr() const { return (mHandle ? mHandle->ptr : NULL); } memory_v* memory::getMHandle() const { return mHandle; } device_v* memory::getDHandle() const { return mHandle->dHandle; } occa::device memory::getDevice() const { return occa::device(mHandle->dHandle); } memory::operator kernelArg() const { if (!mHandle) { return kernelArg((void*) NULL); } return mHandle->makeKernelArg(); } const std::string& memory::mode() const { return mHandle->dHandle->mode; } const occa::properties& memory::properties() const { return mHandle->properties; } udim_t memory::size() const { if (mHandle == NULL) { return 0; } return mHandle->size; } bool memory::isManaged() const { return mHandle->isManaged(); } bool memory::inDevice() const { return mHandle->inDevice(); } bool memory::isStale() const { return mHandle->isStale(); } void memory::setupUva() { if ( !(mHandle->dHandle->hasSeparateMemorySpace()) ) { mHandle->uvaPtr = mHandle->ptr; } else { mHandle->uvaPtr = (char*) sys::malloc(mHandle->size); } ptrRange range; range.start = mHandle->uvaPtr; range.end = (range.start + mHandle->size); uvaMap[range] = mHandle; mHandle->dHandle->uvaMap[range] = mHandle; // Needed for kernelArg.void_ -> mHandle checks if (mHandle->uvaPtr != mHandle->ptr) { uvaMap[mHandle->ptr] = mHandle; } } void memory::startManaging() { mHandle->memInfo |= uvaFlag::isManaged; } void memory::stopManaging() { mHandle->memInfo &= ~uvaFlag::isManaged; } void memory::syncToDevice(const dim_t bytes, const dim_t offset) { udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to copy negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); if (bytes_ == 0) { return; } OCCA_ERROR("Memory has size [" << mHandle->size << "]," << " trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); if (!mHandle->dHandle->hasSeparateMemorySpace()) { return; } copyFrom(mHandle->uvaPtr, bytes_, offset); mHandle->memInfo |= uvaFlag::inDevice; mHandle->memInfo &= ~uvaFlag::isStale; removeFromStaleMap(mHandle); } void memory::syncToHost(const dim_t bytes, const dim_t offset) { udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to copy negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); if (bytes_ == 0) { return; } OCCA_ERROR("Memory has size [" << mHandle->size << "]," << " trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); if (!mHandle->dHandle->hasSeparateMemorySpace()) { return; } copyTo(mHandle->uvaPtr, bytes_, offset); mHandle->memInfo &= ~uvaFlag::inDevice; mHandle->memInfo &= ~uvaFlag::isStale; removeFromStaleMap(mHandle); } bool memory::uvaIsStale() const { return (mHandle && mHandle->isStale()); } void memory::uvaMarkStale() { if (mHandle != NULL) { mHandle->memInfo |= uvaFlag::isStale; } } void memory::uvaMarkFresh() { if (mHandle != NULL) { mHandle->memInfo &= ~uvaFlag::isStale; } } bool memory::operator == (const occa::memory &m) { return (mHandle == m.mHandle); } bool memory::operator != (const occa::memory &m) { return (mHandle != m.mHandle); } occa::memory memory::operator + (const dim_t offset) const { return slice(offset); } occa::memory& memory::operator += (const dim_t offset) { *this = slice(offset); return *this; } occa::memory memory::slice(const dim_t offset, const dim_t bytes) const { udim_t bytes_ = ((bytes == -1) ? (mHandle->size - offset) : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); OCCA_ERROR("Cannot have offset and bytes greater than the memory size (" << offset << " + " << bytes_ << " > " << size() << ")", (offset + (dim_t) bytes_) <= (dim_t) size()); bool needsFree; occa::memory m(mHandle->addOffset(offset, needsFree)); memory_v &mv = *(m.mHandle); mv.dHandle = mHandle->dHandle; mv.size = bytes_; if (mHandle->uvaPtr) { mv.uvaPtr = (mHandle->uvaPtr + offset); } if (!needsFree) { m.dontUseRefs(); } return m; } void memory::copyFrom(const void *src, const dim_t bytes, const dim_t offset, const occa::properties &props) { udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); OCCA_ERROR("Destination memory has size [" << mHandle->size << "]," << "trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); mHandle->copyFrom(src, bytes_, offset, props); } void memory::copyFrom(const memory src, const dim_t bytes, const dim_t destOffset, const dim_t srcOffset, const occa::properties &props) { udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << destOffset << ")", destOffset >= 0); OCCA_ERROR("Cannot have a negative offset (" << srcOffset << ")", srcOffset >= 0); OCCA_ERROR("Source memory has size [" << src.mHandle->size << "]," << "trying to access [ " << srcOffset << " , " << (srcOffset + bytes_) << " ]", (bytes_ + srcOffset) <= src.mHandle->size); OCCA_ERROR("Destination memory has size [" << mHandle->size << "]," << "trying to access [ " << destOffset << " , " << (destOffset + bytes_) << " ]", (bytes_ + destOffset) <= mHandle->size); mHandle->copyFrom(src.mHandle, bytes_, destOffset, srcOffset, props); } void memory::copyTo(void *dest, const dim_t bytes, const dim_t offset, const occa::properties &props) const { udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); OCCA_ERROR("Source memory has size [" << mHandle->size << "]," << "trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); mHandle->copyTo(dest, bytes_, offset, props); } void memory::copyTo(memory dest, const dim_t bytes, const dim_t destOffset, const dim_t srcOffset, const occa::properties &props) const { udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << destOffset << ")", destOffset >= 0); OCCA_ERROR("Cannot have a negative offset (" << srcOffset << ")", srcOffset >= 0); OCCA_ERROR("Source memory has size [" << mHandle->size << "]," << "trying to access [ " << srcOffset << " , " << (srcOffset + bytes_) << " ]", (bytes_ + srcOffset) <= mHandle->size); OCCA_ERROR("Destination memory has size [" << dest.mHandle->size << "]," << "trying to access [ " << destOffset << " , " << (destOffset + bytes_) << " ]", (bytes_ + destOffset) <= dest.mHandle->size); dest.mHandle->copyFrom(mHandle, bytes_, destOffset, srcOffset, props); } void memory::copyFrom(const void *src, const occa::properties &props) { copyFrom(src, -1, 0, props); } void memory::copyFrom(const memory src, const occa::properties &props) { copyFrom(src, -1, 0, 0, props); } void memory::copyTo(void *dest, const occa::properties &props) const { copyTo(dest, -1, 0, props); } void memory::copyTo(const memory dest, const occa::properties &props) const { copyTo(dest, -1, 0, 0, props); } occa::memory memory::clone() const { return occa::device(mHandle->dHandle).malloc(size(), *this, properties()); } void memory::free() { deleteRefs(true); } void memory::detach() { deleteRefs(false); } void memory::deleteRefs(const bool freeMemory) { if (mHandle == NULL) { return; } mHandle->dHandle->bytesAllocated -= (mHandle->size); if (mHandle->uvaPtr) { uvaMap.erase(mHandle->uvaPtr); mHandle->dHandle->uvaMap.erase(mHandle->uvaPtr); // CPU case where memory is shared if (mHandle->uvaPtr != mHandle->ptr) { uvaMap.erase(mHandle->ptr); mHandle->dHandle->uvaMap.erase(mHandle->uvaPtr); ::free(mHandle->uvaPtr); mHandle->uvaPtr = NULL; } } if (freeMemory) { mHandle->free(); } else { mHandle->detach(); } } namespace cpu { occa::memory wrapMemory(void *ptr, const udim_t bytes) { serial::memory &mem = *(new serial::memory); mem.dontUseRefs(); mem.dHandle = host().getDHandle(); mem.size = bytes; mem.ptr = (char*) ptr; return occa::memory(&mem); } } } <commit_msg>[Memory] Added initialization checks before calls<commit_after>/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <map> #include <occa/base.hpp> #include <occa/memory.hpp> #include <occa/device.hpp> #include <occa/modes/serial/memory.hpp> #include <occa/uva.hpp> #include <occa/tools/sys.hpp> namespace occa { //---[ memory_v ]--------------------- memory_v::memory_v(const occa::properties &properties_) { memInfo = uvaFlag::none; properties = properties_; ptr = NULL; uvaPtr = NULL; dHandle = NULL; size = 0; } memory_v::~memory_v() {} bool memory_v::isManaged() const { return (memInfo & uvaFlag::isManaged); } bool memory_v::inDevice() const { return (memInfo & uvaFlag::inDevice); } bool memory_v::isStale() const { return (memInfo & uvaFlag::isStale); } //---[ memory ]----------------------- memory::memory() : mHandle(NULL) {} memory::memory(void *uvaPtr) : mHandle(NULL) { ptrRangeMap::iterator it = uvaMap.find(uvaPtr); if (it != uvaMap.end()) { setMHandle(it->second); } else { setMHandle((memory_v*) uvaPtr); } } memory::memory(memory_v *mHandle_) : mHandle(NULL) { setMHandle(mHandle_); } memory::memory(const memory &m) : mHandle(NULL) { setMHandle(m.mHandle); } memory& memory::operator = (const memory &m) { setMHandle(m.mHandle); return *this; } memory::~memory() { removeMHandleRef(); } void memory::setMHandle(memory_v *mHandle_) { if (mHandle != mHandle_) { removeMHandleRef(); mHandle = mHandle_; mHandle->addRef(); } } void memory::setDHandle(device_v *dHandle) { mHandle->dHandle = dHandle; // If this is the very first reference, update the device references if (mHandle->getRefs() == 1) { mHandle->dHandle->addRef(); } } void memory::removeMHandleRef() { if (mHandle && !mHandle->removeRef()) { device_v *dHandle = mHandle->dHandle; free(); device::removeDHandleRefFrom(dHandle); delete mHandle; mHandle = NULL; } } void memory::dontUseRefs() { if (mHandle) { mHandle->dontUseRefs(); } } bool memory::isInitialized() const { return (mHandle != NULL); } memory& memory::swap(memory &m) { memory_v *mHandle_ = mHandle; mHandle = m.mHandle; m.mHandle = mHandle_; return *this; } void* memory::ptr() { return (mHandle ? mHandle->ptr : NULL); } const void* memory::ptr() const { return (mHandle ? mHandle->ptr : NULL); } memory_v* memory::getMHandle() const { return mHandle; } device_v* memory::getDHandle() const { return mHandle->dHandle; } occa::device memory::getDevice() const { return occa::device(mHandle ? mHandle->dHandle : NULL); } memory::operator kernelArg() const { if (!mHandle) { return kernelArg((void*) NULL); } return mHandle->makeKernelArg(); } const std::string& memory::mode() const { OCCA_ERROR("Memory not initialized", mHandle != NULL); return mHandle->dHandle->mode; } const occa::properties& memory::properties() const { OCCA_ERROR("Memory not initialized", mHandle != NULL); return mHandle->properties; } udim_t memory::size() const { if (mHandle == NULL) { return 0; } return mHandle->size; } bool memory::isManaged() const { return (mHandle && mHandle->isManaged()); } bool memory::inDevice() const { return (mHandle && mHandle->inDevice()); } bool memory::isStale() const { return (mHandle && mHandle->isStale()); } void memory::setupUva() { if (!mHandle) { return; } if ( !(mHandle->dHandle->hasSeparateMemorySpace()) ) { mHandle->uvaPtr = mHandle->ptr; } else { mHandle->uvaPtr = (char*) sys::malloc(mHandle->size); } ptrRange range; range.start = mHandle->uvaPtr; range.end = (range.start + mHandle->size); uvaMap[range] = mHandle; mHandle->dHandle->uvaMap[range] = mHandle; // Needed for kernelArg.void_ -> mHandle checks if (mHandle->uvaPtr != mHandle->ptr) { uvaMap[mHandle->ptr] = mHandle; } } void memory::startManaging() { if (!mHandle) { return; } mHandle->memInfo |= uvaFlag::isManaged; } void memory::stopManaging() { if (mHandle) { mHandle->memInfo &= ~uvaFlag::isManaged; } } void memory::syncToDevice(const dim_t bytes, const dim_t offset) { OCCA_ERROR("Memory not initialized", mHandle != NULL); udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to copy negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); if (bytes_ == 0) { return; } OCCA_ERROR("Memory has size [" << mHandle->size << "]," << " trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); if (!mHandle->dHandle->hasSeparateMemorySpace()) { return; } copyFrom(mHandle->uvaPtr, bytes_, offset); mHandle->memInfo |= uvaFlag::inDevice; mHandle->memInfo &= ~uvaFlag::isStale; removeFromStaleMap(mHandle); } void memory::syncToHost(const dim_t bytes, const dim_t offset) { OCCA_ERROR("Memory not initialized", mHandle != NULL); udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to copy negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); if (bytes_ == 0) { return; } OCCA_ERROR("Memory has size [" << mHandle->size << "]," << " trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); if (!mHandle->dHandle->hasSeparateMemorySpace()) { return; } copyTo(mHandle->uvaPtr, bytes_, offset); mHandle->memInfo &= ~uvaFlag::inDevice; mHandle->memInfo &= ~uvaFlag::isStale; removeFromStaleMap(mHandle); } bool memory::uvaIsStale() const { return (mHandle && mHandle->isStale()); } void memory::uvaMarkStale() { if (mHandle != NULL) { mHandle->memInfo |= uvaFlag::isStale; } } void memory::uvaMarkFresh() { if (mHandle != NULL) { mHandle->memInfo &= ~uvaFlag::isStale; } } bool memory::operator == (const occa::memory &m) { return (mHandle == m.mHandle); } bool memory::operator != (const occa::memory &m) { return (mHandle != m.mHandle); } occa::memory memory::operator + (const dim_t offset) const { return slice(offset); } occa::memory& memory::operator += (const dim_t offset) { *this = slice(offset); return *this; } occa::memory memory::slice(const dim_t offset, const dim_t bytes) const { OCCA_ERROR("Memory not initialized", mHandle != NULL); udim_t bytes_ = ((bytes == -1) ? (mHandle->size - offset) : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); OCCA_ERROR("Cannot have offset and bytes greater than the memory size (" << offset << " + " << bytes_ << " > " << size() << ")", (offset + (dim_t) bytes_) <= (dim_t) size()); bool needsFree; occa::memory m(mHandle->addOffset(offset, needsFree)); memory_v &mv = *(m.mHandle); mv.dHandle = mHandle->dHandle; mv.size = bytes_; if (mHandle->uvaPtr) { mv.uvaPtr = (mHandle->uvaPtr + offset); } if (!needsFree) { m.dontUseRefs(); } return m; } void memory::copyFrom(const void *src, const dim_t bytes, const dim_t offset, const occa::properties &props) { OCCA_ERROR("Memory not initialized", mHandle != NULL); udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); OCCA_ERROR("Destination memory has size [" << mHandle->size << "]," << "trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); mHandle->copyFrom(src, bytes_, offset, props); } void memory::copyFrom(const memory src, const dim_t bytes, const dim_t destOffset, const dim_t srcOffset, const occa::properties &props) { OCCA_ERROR("Memory not initialized", mHandle && src.mHandle); udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << destOffset << ")", destOffset >= 0); OCCA_ERROR("Cannot have a negative offset (" << srcOffset << ")", srcOffset >= 0); OCCA_ERROR("Source memory has size [" << src.mHandle->size << "]," << "trying to access [ " << srcOffset << " , " << (srcOffset + bytes_) << " ]", (bytes_ + srcOffset) <= src.mHandle->size); OCCA_ERROR("Destination memory has size [" << mHandle->size << "]," << "trying to access [ " << destOffset << " , " << (destOffset + bytes_) << " ]", (bytes_ + destOffset) <= mHandle->size); mHandle->copyFrom(src.mHandle, bytes_, destOffset, srcOffset, props); } void memory::copyTo(void *dest, const dim_t bytes, const dim_t offset, const occa::properties &props) const { OCCA_ERROR("Memory not initialized", mHandle != NULL); udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << offset << ")", offset >= 0); OCCA_ERROR("Source memory has size [" << mHandle->size << "]," << "trying to access [ " << offset << " , " << (offset + bytes_) << " ]", (bytes_ + offset) <= mHandle->size); mHandle->copyTo(dest, bytes_, offset, props); } void memory::copyTo(memory dest, const dim_t bytes, const dim_t destOffset, const dim_t srcOffset, const occa::properties &props) const { OCCA_ERROR("Memory not initialized", mHandle && dest.mHandle); udim_t bytes_ = ((bytes == -1) ? mHandle->size : bytes); OCCA_ERROR("Trying to allocate negative bytes (" << bytes << ")", bytes >= -1); OCCA_ERROR("Cannot have a negative offset (" << destOffset << ")", destOffset >= 0); OCCA_ERROR("Cannot have a negative offset (" << srcOffset << ")", srcOffset >= 0); OCCA_ERROR("Source memory has size [" << mHandle->size << "]," << "trying to access [ " << srcOffset << " , " << (srcOffset + bytes_) << " ]", (bytes_ + srcOffset) <= mHandle->size); OCCA_ERROR("Destination memory has size [" << dest.mHandle->size << "]," << "trying to access [ " << destOffset << " , " << (destOffset + bytes_) << " ]", (bytes_ + destOffset) <= dest.mHandle->size); dest.mHandle->copyFrom(mHandle, bytes_, destOffset, srcOffset, props); } void memory::copyFrom(const void *src, const occa::properties &props) { copyFrom(src, -1, 0, props); } void memory::copyFrom(const memory src, const occa::properties &props) { copyFrom(src, -1, 0, 0, props); } void memory::copyTo(void *dest, const occa::properties &props) const { copyTo(dest, -1, 0, props); } void memory::copyTo(const memory dest, const occa::properties &props) const { copyTo(dest, -1, 0, 0, props); } occa::memory memory::clone() const { if (mHandle) { return occa::device(mHandle->dHandle).malloc(size(), *this, properties()); } return occa::memory(); } void memory::free() { deleteRefs(true); } void memory::detach() { deleteRefs(false); } void memory::deleteRefs(const bool freeMemory) { if (!mHandle) { return; } mHandle->dHandle->bytesAllocated -= (mHandle->size); if (mHandle->uvaPtr) { uvaMap.erase(mHandle->uvaPtr); mHandle->dHandle->uvaMap.erase(mHandle->uvaPtr); // CPU case where memory is shared if (mHandle->uvaPtr != mHandle->ptr) { uvaMap.erase(mHandle->ptr); mHandle->dHandle->uvaMap.erase(mHandle->uvaPtr); ::free(mHandle->uvaPtr); mHandle->uvaPtr = NULL; } } if (freeMemory) { mHandle->free(); } else { mHandle->detach(); } } namespace cpu { occa::memory wrapMemory(void *ptr, const udim_t bytes) { serial::memory &mem = *(new serial::memory); mem.dontUseRefs(); mem.dHandle = host().getDHandle(); mem.size = bytes; mem.ptr = (char*) ptr; return occa::memory(&mem); } } } <|endoftext|>
<commit_before>/* * The MIT License * * Copyright (c) 2010 Sam Day * Copyright (c) 2012 Xavier Mendez * * 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 "message.h" #include "git2.h" namespace gitteh { // prepare input for processing inline void prepare(const char* in, char* out, int& len) { int o = 0; for (int i=0; i<len; i++) if (in[i] != 0) out[o++] = in[i]; // skip any \0 out[o] = 0; // set last trailing \0 } // another approach would be to call prettify() with no buffer, // allocate the size and call again, but this is faster V8_CB(Prettify) { // Allocate v8::String::Utf8Value msg (args[0]); int len = msg.length(); int out_len = len; char* in = new (std::nothrow) char [++out_len]; // one more for the trailing \0 if (in == NULL) V8_THROW(v8u::Err("Couldn't allocate memory.")); char* out = new (std::nothrow) char [++out_len]; // another for the trailing \n if (out == NULL) { delete[] in; V8_THROW(v8u::Err("Couldn't allocate memory.")); } // Prepare input prepare(*msg, in, len); // Call & return int final_len = git_message_prettify(out, out_len, in, v8u::Bool(args[1])); delete[] in; v8::Local<v8::String> ret = v8u::Str(out, final_len-1); delete[] out; V8_RET(ret); } V8_CB_END() }; <commit_msg>AHUWOEIUHWQEFHN FUCK YOU IF NOT ENOUGH MEMORY!!<commit_after>/* * The MIT License * * Copyright (c) 2010 Sam Day * Copyright (c) 2012 Xavier Mendez * * 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 "message.h" #include "git2.h" namespace gitteh { // prepare input for processing inline void prepare(const char* in, char* out, int& len) { int o = 0; for (int i=0; i<len; i++) if (in[i] != 0) out[o++] = in[i]; // skip any \0 out[o] = 0; // set last trailing \0 } // another approach would be to call prettify() with no buffer, // allocate the size and call again, but this is faster V8_SCB(Prettify) { // Allocate v8::String::Utf8Value msg (args[0]); int len = msg.length(); int out_len = len; char* in = new char [++out_len]; // one more for the trailing \0 char* out = new char [++out_len]; // another for the trailing \n // Prepare input prepare(*msg, in, len); // Call & return int final_len = git_message_prettify(out, out_len, in, v8u::Bool(args[1])); delete[] in; v8::Local<v8::String> ret = v8u::Str(out, final_len-1); delete[] out; return ret; } }; <|endoftext|>
<commit_before>#ifndef __MINEAR_HPP__ #define __MINEAR_HPP__ #include <memory> #include <iostream> namespace minear { template <class T> class Matrix { public: unsigned int n_rows; unsigned int n_cols; /* constructors and destructors */ Matrix<T>() : n_rows(10), n_cols(10), data(new T[100]), insertion_index(0) {} Matrix<T>(const unsigned int n, const unsigned int m) : n_rows(n), n_cols(m), data(new T[n*m]), insertion_index(0) {}; Matrix<T>(const unsigned int n, const unsigned int m, const T value); Matrix<T>(const Matrix<T>&); Matrix<T>& operator=(const Matrix<T>&); Matrix<T>(Matrix<T>&&); Matrix<T>& operator=(Matrix<T>&&); ~Matrix<T>() { delete[] data; } /* data insertion */ Matrix<T>& operator<<(const T value); void reset_index() { insertion_index = 0; } /* data accessors */ T& operator()(const unsigned int i, const unsigned int j) { return data[i*n_rows + j]; } const T& operator() (const unsigned int i, const unsigned int j) const { return data[i*n_rows + j]; } /* printing */ friend std::ostream& operator<< (std::ostream& stream, const Matrix& a) { for (unsigned int i = 0; i < a.n_rows; i++) { for (unsigned int j = 0; j < a.n_cols; j++) stream << " " << a(i,j); stream << std::endl; } return stream; } /* memory management */ void resize(const unsigned int, const unsigned int); private: T* data; unsigned int insertion_index; }; template <class T> Matrix<T>::Matrix(const unsigned int n, const unsigned int m, const T value) : Matrix<T>(n,m) { for (unsigned int i = 0; i < n*m; i++) data[i] = value; } template <class T> Matrix<T>::Matrix(const Matrix<T>& a) : n_rows(a.n_rows), n_cols(a.n_cols) { data = new T[n_rows*n_cols]; for (unsigned int i = 0; i < n_rows; i++) for (unsigned int j = 0; j < n_cols; j++) data[i*n_rows + j] = a(i,j); } template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& a) { insertion_index = 0; T* p = new T[a.n_rows*a.n_cols]; for (unsigned int i = 0; i < n_rows; i++) for (unsigned int j = 0; j < n_cols; j++) data[i*n_rows + j] = a(i,j); delete[] data; data = p; n_rows = a.n_rows; n_cols = a.n_cols; return *this; } template <class T> Matrix<T>::Matrix(Matrix<T>&& a) : n_rows(a.n_rows), n_cols(a.n_cols), data(a.data), insertion_index(0) { a.data = nullptr; a.n_rows = 0; a.n_cols = 0; a.insertion_index = 0; } template <class T> Matrix<T>& Matrix<T>::operator=(Matrix<T>&& a) { insertion_index = 0; data = a.data; n_rows = a.n_rows; n_cols = a.n_cols; a.data = nullptr; a.n_rows = 0; a.n_cols = 0; a.insertion_index = 0; return *this; } template <class T> Matrix<T>& Matrix<T>::operator<<(const T value) { data[insertion_index] = value; insertion_index++; if (insertion_index == n_rows*n_cols) insertion_index = 0; return *this; } template <class T> Matrix<T> operator+(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = a(i,j) + b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = a(i,j) - b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = -a(i,j); return result; } template <class T> Matrix<T> operator*(const Matrix<T>& a, const Matrix<T>& b) { Matrix<T> result(a.n_rows,b.n_cols,0); for (unsigned int i = 0; i < a.n_rows; i++) { for (unsigned int j = 0; j < b.n_cols; j++) for (unsigned int k = 0; k < b.n_rows; k++) result(i,j) += a(i,k)*b(k,j); } return result; } template <class T> void Matrix<T>::resize(const unsigned int n, const unsigned int m) { if (sizeof(data)/sizeof(T) < n*m) { double* p = data; data = new double[n*m]; delete[] p; insertion_index = 0; } n_rows = n; n_cols = m; } } #endif /* __MINEAR_HPP__ */ <commit_msg>fixed problem with type<commit_after>#ifndef __MINEAR_HPP__ #define __MINEAR_HPP__ #include <memory> #include <iostream> namespace minear { template <class T> class Matrix { public: unsigned int n_rows; unsigned int n_cols; /* constructors and destructors */ Matrix<T>() : n_rows(10), n_cols(10), data(new T[100]), insertion_index(0) {} Matrix<T>(const unsigned int n, const unsigned int m) : n_rows(n), n_cols(m), data(new T[n*m]), insertion_index(0) {}; Matrix<T>(const unsigned int n, const unsigned int m, const T value); Matrix<T>(const Matrix<T>&); Matrix<T>& operator=(const Matrix<T>&); Matrix<T>(Matrix<T>&&); Matrix<T>& operator=(Matrix<T>&&); ~Matrix<T>() { delete[] data; } /* data insertion */ Matrix<T>& operator<<(const T value); void reset_index() { insertion_index = 0; } /* data accessors */ T& operator()(const unsigned int i, const unsigned int j) { return data[i*n_rows + j]; } const T& operator() (const unsigned int i, const unsigned int j) const { return data[i*n_rows + j]; } /* printing */ friend std::ostream& operator<< (std::ostream& stream, const Matrix& a) { for (unsigned int i = 0; i < a.n_rows; i++) { for (unsigned int j = 0; j < a.n_cols; j++) stream << " " << a(i,j); stream << std::endl; } return stream; } /* memory management */ void resize(const unsigned int, const unsigned int); private: T* data; unsigned int insertion_index; }; template <class T> Matrix<T>::Matrix(const unsigned int n, const unsigned int m, const T value) : Matrix<T>(n,m) { for (unsigned int i = 0; i < n*m; i++) data[i] = value; } template <class T> Matrix<T>::Matrix(const Matrix<T>& a) : n_rows(a.n_rows), n_cols(a.n_cols) { data = new T[n_rows*n_cols]; for (unsigned int i = 0; i < n_rows; i++) for (unsigned int j = 0; j < n_cols; j++) data[i*n_rows + j] = a(i,j); } template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& a) { insertion_index = 0; T* p = new T[a.n_rows*a.n_cols]; for (unsigned int i = 0; i < n_rows; i++) for (unsigned int j = 0; j < n_cols; j++) p[i*n_rows + j] = a(i,j); delete[] data; data = p; n_rows = a.n_rows; n_cols = a.n_cols; return *this; } template <class T> Matrix<T>::Matrix(Matrix<T>&& a) : n_rows(a.n_rows), n_cols(a.n_cols), data(a.data), insertion_index(0) { a.data = nullptr; a.n_rows = 0; a.n_cols = 0; a.insertion_index = 0; } template <class T> Matrix<T>& Matrix<T>::operator=(Matrix<T>&& a) { insertion_index = 0; data = a.data; n_rows = a.n_rows; n_cols = a.n_cols; a.data = nullptr; a.n_rows = 0; a.n_cols = 0; a.insertion_index = 0; return *this; } template <class T> Matrix<T>& Matrix<T>::operator<<(const T value) { data[insertion_index] = value; insertion_index++; if (insertion_index == n_rows*n_cols) insertion_index = 0; return *this; } template <class T> Matrix<T> operator+(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = a(i,j) + b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = a(i,j) - b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = -a(i,j); return result; } template <class T> Matrix<T> operator*(const Matrix<T>& a, const Matrix<T>& b) { Matrix<T> result(a.n_rows,b.n_cols,0); for (unsigned int i = 0; i < a.n_rows; i++) { for (unsigned int j = 0; j < b.n_cols; j++) for (unsigned int k = 0; k < b.n_rows; k++) result(i,j) += a(i,k)*b(k,j); } return result; } template <class T> void Matrix<T>::resize(const unsigned int n, const unsigned int m) { if (sizeof(data)/sizeof(T) < n*m) { double* p = data; data = new double[n*m]; delete[] p; insertion_index = 0; } n_rows = n; n_cols = m; } } #endif /* __MINEAR_HPP__ */ <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, PAL Robotics, S.L. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* * Author: Bence Magyar */ #include <controller_interface/controller.h> #include <hardware_interface/joint_command_interface.h> #include <pluginlib/class_list_macros.h> #include <nav_msgs/Odometry.h> #include <tf/tfMessage.h> #include <tf/transform_datatypes.h> #include <urdf_parser/urdf_parser.h> #include <realtime_tools/realtime_buffer.h> #include <realtime_tools/realtime_publisher.h> #include <boost/assign.hpp> #include <diff_drive_controller/odometry.h> namespace diff_drive_controller{ class DiffDriveController : public controller_interface::Controller<hardware_interface::VelocityJointInterface> { public: bool init(hardware_interface::VelocityJointInterface* hw, ros::NodeHandle& root_nh, ros::NodeHandle &controller_nh) { name_ = getLeafNamespace(controller_nh); // get joint names from the parameter server std::string left_wheel_name, right_wheel_name; bool res = controller_nh.hasParam("left_wheel"); if(!res || !controller_nh.getParam("left_wheel", left_wheel_name)) { ROS_ERROR("Couldn't retrieve left wheel name from param server."); return false; } res = controller_nh.hasParam("right_wheel"); if(!res || !controller_nh.getParam("right_wheel", right_wheel_name)) { ROS_ERROR("Couldn't retrieve right wheel name from param server."); return false; } // parse robot description const std::string model_param_name = "/robot_description"; res = root_nh.hasParam(model_param_name); std::string robot_model_str=""; if(!res || !root_nh.getParam(model_param_name,robot_model_str)) { ROS_ERROR("Robot descripion couldn't be retrieved from param server."); return false; } boost::shared_ptr<urdf::ModelInterface> model_ptr(urdf::parseURDF(robot_model_str)); boost::shared_ptr<const urdf::Joint> wheelJointPtr(model_ptr->getJoint(left_wheel_name)); if(!wheelJointPtr.get()) { ROS_ERROR_STREAM(left_wheel_name << " couldn't be retrieved from model description"); return false; } wheel_radius_ = fabs(wheelJointPtr->parent_to_joint_origin_transform.position.z); wheel_separation_ = 2.0 * fabs(wheelJointPtr->parent_to_joint_origin_transform.position.y); ROS_DEBUG_STREAM("Odometry params : wheel separation " << wheel_separation_ << ", wheel radius " << wheel_radius_); // get the joint object to use in the realtime loop ROS_DEBUG_STREAM("Adding left wheel with joint name: " << left_wheel_name << " and right wheel with joint name: " << right_wheel_name); left_wheel_joint_ = hw->getHandle(left_wheel_name); // throws on failure right_wheel_joint_ = hw->getHandle(right_wheel_name); // throws on failure // setup odometry realtime publisher + odom message constant fields odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100)); odom_pub_->msg_.header.frame_id = "odom"; odom_pub_->msg_.pose.pose.position.z = 0; odom_pub_->msg_.pose.covariance = boost::assign::list_of (1e-3) (0) (0) (0) (0) (0) (0) (1e-3) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e3); odom_pub_->msg_.twist.twist.linear.y = 0; odom_pub_->msg_.twist.twist.linear.z = 0; odom_pub_->msg_.twist.twist.angular.x = 0; odom_pub_->msg_.twist.twist.angular.y = 0; odom_pub_->msg_.twist.covariance = boost::assign::list_of (1e-3) (0) (0) (0) (0) (0) (0) (1e-3) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e3); tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(controller_nh, "/tf", 100)); odom_frame.transform.translation.z = 0.0; odom_frame.child_frame_id = "base_footprint"; odom_frame.header.frame_id = "odom"; sub_command_ = controller_nh.subscribe("cmd_vel", 1, &DiffDriveController::cmdVelCallback, this); return true; } void update(const ros::Time& time, const ros::Duration& period) { // MOVE ROBOT // command the wheels according to the messages from the cmd_vel topic const Commands curr_cmd = *(command_.readFromRT()); const double vel_right = (curr_cmd.lin + curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_; const double vel_left = (curr_cmd.lin - curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_; left_wheel_joint_.setCommand(vel_left); right_wheel_joint_.setCommand(vel_right); // estimate linear and angular velocity using joint information //---------------------------- // get current wheel joint positions left_wheel_cur_pos_ = left_wheel_joint_.getPosition()*wheel_radius_; right_wheel_cur_pos_ = right_wheel_joint_.getPosition()*wheel_radius_; // estimate velocity of wheels using old and current position left_wheel_est_vel_ = left_wheel_cur_pos_ - left_wheel_old_pos_; right_wheel_est_vel_ = right_wheel_cur_pos_ - right_wheel_old_pos_; // update old position with current left_wheel_old_pos_ = left_wheel_cur_pos_; right_wheel_old_pos_ = right_wheel_cur_pos_; // compute linear and angular velocity const double linear = (left_wheel_est_vel_ + right_wheel_est_vel_) * 0.5 ; const double angular = (right_wheel_est_vel_ - left_wheel_est_vel_) / wheel_separation_; if((fabs(angular) < 1e-15) && (fabs(linear) < 1e-15)) // when both velocities are ~0 { ROS_WARN("Dropped odom: velocities are 0."); return; } if(!odometryReading_.integrate(linear, angular, time)) { ROS_WARN("Dropped odom: interval too small to integrate."); return; } // estimate speeds speedEstimation(odometryReading_.getLinear(), odometryReading_.getAngular()); //---------------------------- // compute and store orientation info const geometry_msgs::Quaternion orientation( tf::createQuaternionMsgFromYaw(odometryReading_.getHeading())); // COMPUTE AND PUBLISH ODOMETRY if(odom_pub_->trylock()) { // populate odom message and publish odom_pub_->msg_.header.stamp = time; odom_pub_->msg_.pose.pose.position.x = odometryReading_.getPos().x; odom_pub_->msg_.pose.pose.position.y = odometryReading_.getPos().y; odom_pub_->msg_.pose.pose.orientation = orientation; odom_pub_->msg_.twist.twist.linear.x = linear_est_speed_; odom_pub_->msg_.twist.twist.angular.z = angular_est_speed_; odom_pub_->unlockAndPublish(); } // publish tf /odom frame if(tf_odom_pub_->trylock()) { //publish odom tf odom_frame.header.stamp = time; odom_frame.transform.translation.x = odometryReading_.getPos().x; odom_frame.transform.translation.y = odometryReading_.getPos().y; odom_frame.transform.rotation = orientation; tf_odom_pub_->msg_.transforms.clear(); tf_odom_pub_->msg_.transforms.push_back(odom_frame); tf_odom_pub_->unlockAndPublish(); } } void starting(const ros::Time& time) { // set velocity to 0 const double vel = 0.0; left_wheel_joint_.setCommand(vel); right_wheel_joint_.setCommand(vel); } void stopping(const ros::Time& time) { // set velocity to 0 const double vel = 0.0; left_wheel_joint_.setCommand(vel); right_wheel_joint_.setCommand(vel); } private: std::string name_; struct Commands { double lin; double ang; }; realtime_tools::RealtimeBuffer<Commands> command_; Commands command_struct_; ros::Subscriber sub_command_; hardware_interface::JointHandle left_wheel_joint_; hardware_interface::JointHandle right_wheel_joint_; boost::shared_ptr<realtime_tools::RealtimePublisher<nav_msgs::Odometry> > odom_pub_; boost::shared_ptr<realtime_tools::RealtimePublisher<tf::tfMessage> > tf_odom_pub_; Odometry odometryReading_; double wheel_separation_; double wheel_radius_; double left_wheel_old_pos_, right_wheel_old_pos_; double left_wheel_cur_pos_, right_wheel_cur_pos_; double left_wheel_est_vel_, right_wheel_est_vel_; double linear_est_speed_, angular_est_speed_; geometry_msgs::TransformStamped odom_frame; std::list<geometry_msgs::Point> lastSpeeds; typedef std::list<geometry_msgs::Point>::const_iterator speeds_it; private: void cmdVelCallback(const geometry_msgs::Twist& command) { if(isRunning()) { command_struct_.ang = command.angular.z; command_struct_.lin = command.linear.x; command_.writeFromNonRT (command_struct_); ROS_DEBUG_STREAM("Added values to command. Ang: " << command_struct_.ang << ", Lin: " << command_struct_.lin); } else { ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running."); } } std::string getLeafNamespace(const ros::NodeHandle& nh) { const std::string complete_ns = nh.getNamespace(); std::size_t id = complete_ns.find_last_of("/"); return complete_ns.substr(id + 1); } void speedEstimation(const double &linear, double const &angular) { if(lastSpeeds.size()> 10) lastSpeeds.pop_front(); geometry_msgs::Point speed; speed.x = linear; speed.y = angular; lastSpeeds.push_back(speed); double averageLinearSpeed = 0.0, averageAngularSpeed = 0.0; for(speeds_it it=lastSpeeds.begin();it!= lastSpeeds.end(); ++it) { averageLinearSpeed += it->x; averageAngularSpeed += it->y; } linear_est_speed_ = averageLinearSpeed/lastSpeeds.size(); angular_est_speed_ = averageAngularSpeed/lastSpeeds.size(); } }; PLUGINLIB_DECLARE_CLASS(diff_drive_controller, DiffDriveController, diff_drive_controller::DiffDriveController, controller_interface::ControllerBase); }//namespace <commit_msg>Added publish rate param + handling.<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2013, PAL Robotics, S.L. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* * Author: Bence Magyar */ #include <controller_interface/controller.h> #include <hardware_interface/joint_command_interface.h> #include <pluginlib/class_list_macros.h> #include <nav_msgs/Odometry.h> #include <tf/tfMessage.h> #include <tf/transform_datatypes.h> #include <urdf_parser/urdf_parser.h> #include <realtime_tools/realtime_buffer.h> #include <realtime_tools/realtime_publisher.h> #include <boost/assign.hpp> #include <diff_drive_controller/odometry.h> namespace diff_drive_controller{ class DiffDriveController : public controller_interface::Controller<hardware_interface::VelocityJointInterface> { public: bool init(hardware_interface::VelocityJointInterface* hw, ros::NodeHandle& root_nh, ros::NodeHandle &controller_nh) { name_ = getLeafNamespace(controller_nh); // get joint names from the parameter server std::string left_wheel_name, right_wheel_name; bool res = controller_nh.hasParam("left_wheel"); if(!res || !controller_nh.getParam("left_wheel", left_wheel_name)) { ROS_ERROR_NAMED(name_, "Couldn't retrieve left wheel name from param server."); return false; } res = controller_nh.hasParam("right_wheel"); if(!res || !controller_nh.getParam("right_wheel", right_wheel_name)) { ROS_ERROR_NAMED(name_, "Couldn't retrieve right wheel name from param server."); return false; } double publish_rate; controller_nh.param("publish_rate", publish_rate, 50.0); ROS_INFO_STREAM_NAMED(name_, "Controller state will be published at " << publish_rate << "Hz."); publish_period_ = ros::Duration(1.0 / publish_rate); // parse robot description const std::string model_param_name = "/robot_description"; res = root_nh.hasParam(model_param_name); std::string robot_model_str=""; if(!res || !root_nh.getParam(model_param_name,robot_model_str)) { ROS_ERROR_NAMED(name_, "Robot descripion couldn't be retrieved from param server."); return false; } boost::shared_ptr<urdf::ModelInterface> model_ptr(urdf::parseURDF(robot_model_str)); boost::shared_ptr<const urdf::Joint> wheelJointPtr(model_ptr->getJoint(left_wheel_name)); if(!wheelJointPtr.get()) { ROS_ERROR_STREAM(left_wheel_name << " couldn't be retrieved from model description"); return false; } wheel_radius_ = fabs(wheelJointPtr->parent_to_joint_origin_transform.position.z); wheel_separation_ = 2.0 * fabs(wheelJointPtr->parent_to_joint_origin_transform.position.y); ROS_DEBUG_STREAM_NAMED(name_, "Odometry params : wheel separation " << wheel_separation_ << ", wheel radius " << wheel_radius_); // get the joint object to use in the realtime loop ROS_DEBUG_STREAM_NAMED(name_, "Adding left wheel with joint name: " << left_wheel_name << " and right wheel with joint name: " << right_wheel_name); left_wheel_joint_ = hw->getHandle(left_wheel_name); // throws on failure right_wheel_joint_ = hw->getHandle(right_wheel_name); // throws on failure // setup odometry realtime publisher + odom message constant fields odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100)); odom_pub_->msg_.header.frame_id = "odom"; odom_pub_->msg_.pose.pose.position.z = 0; odom_pub_->msg_.pose.covariance = boost::assign::list_of (1e-3) (0) (0) (0) (0) (0) (0) (1e-3) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e3); odom_pub_->msg_.twist.twist.linear.y = 0; odom_pub_->msg_.twist.twist.linear.z = 0; odom_pub_->msg_.twist.twist.angular.x = 0; odom_pub_->msg_.twist.twist.angular.y = 0; odom_pub_->msg_.twist.covariance = boost::assign::list_of (1e-3) (0) (0) (0) (0) (0) (0) (1e-3) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e6) (0) (0) (0) (0) (0) (0) (1e3); tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(controller_nh, "/tf", 100)); odom_frame.transform.translation.z = 0.0; odom_frame.child_frame_id = "base_footprint"; odom_frame.header.frame_id = "odom"; sub_command_ = controller_nh.subscribe("cmd_vel", 1, &DiffDriveController::cmdVelCallback, this); return true; } void update(const ros::Time& time, const ros::Duration& period) { // MOVE ROBOT // command the wheels according to the messages from the cmd_vel topic const Commands curr_cmd = *(command_.readFromRT()); const double vel_right = (curr_cmd.lin + curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_; const double vel_left = (curr_cmd.lin - curr_cmd.ang * wheel_separation_ / 2.0)/wheel_radius_; left_wheel_joint_.setCommand(vel_left); right_wheel_joint_.setCommand(vel_right); // estimate linear and angular velocity using joint information //---------------------------- // get current wheel joint positions left_wheel_cur_pos_ = left_wheel_joint_.getPosition()*wheel_radius_; right_wheel_cur_pos_ = right_wheel_joint_.getPosition()*wheel_radius_; // estimate velocity of wheels using old and current position left_wheel_est_vel_ = left_wheel_cur_pos_ - left_wheel_old_pos_; right_wheel_est_vel_ = right_wheel_cur_pos_ - right_wheel_old_pos_; // update old position with current left_wheel_old_pos_ = left_wheel_cur_pos_; right_wheel_old_pos_ = right_wheel_cur_pos_; // compute linear and angular velocity const double linear = (left_wheel_est_vel_ + right_wheel_est_vel_) * 0.5 ; const double angular = (right_wheel_est_vel_ - left_wheel_est_vel_) / wheel_separation_; if((fabs(angular) < 1e-15) && (fabs(linear) < 1e-15)) // when both velocities are ~0 { ROS_WARN("Dropped odom: velocities are 0."); return; } if(!odometryReading_.integrate(linear, angular, time)) { ROS_WARN("Dropped odom: interval too small to integrate."); return; } // estimate speeds speedEstimation(odometryReading_.getLinear(), odometryReading_.getAngular()); //---------------------------- if(last_state_publish_time_ + publish_period_ < time) { last_state_publish_time_ += publish_period_; // compute and store orientation info const geometry_msgs::Quaternion orientation( tf::createQuaternionMsgFromYaw(odometryReading_.getHeading())); // COMPUTE AND PUBLISH ODOMETRY if(odom_pub_->trylock()) { // populate odom message and publish odom_pub_->msg_.header.stamp = time; odom_pub_->msg_.pose.pose.position.x = odometryReading_.getPos().x; odom_pub_->msg_.pose.pose.position.y = odometryReading_.getPos().y; odom_pub_->msg_.pose.pose.orientation = orientation; odom_pub_->msg_.twist.twist.linear.x = linear_est_speed_; odom_pub_->msg_.twist.twist.angular.z = angular_est_speed_; odom_pub_->unlockAndPublish(); } // publish tf /odom frame if(tf_odom_pub_->trylock()) { //publish odom tf odom_frame.header.stamp = time; odom_frame.transform.translation.x = odometryReading_.getPos().x; odom_frame.transform.translation.y = odometryReading_.getPos().y; odom_frame.transform.rotation = orientation; tf_odom_pub_->msg_.transforms.clear(); tf_odom_pub_->msg_.transforms.push_back(odom_frame); tf_odom_pub_->unlockAndPublish(); } } } void starting(const ros::Time& time) { // set velocity to 0 const double vel = 0.0; left_wheel_joint_.setCommand(vel); right_wheel_joint_.setCommand(vel); last_state_publish_time_ = time; } void stopping(const ros::Time& time) { // set velocity to 0 const double vel = 0.0; left_wheel_joint_.setCommand(vel); right_wheel_joint_.setCommand(vel); } private: std::string name_; // publish rate related ros::Duration publish_period_; ros::Time last_state_publish_time_; // hardware handles hardware_interface::JointHandle left_wheel_joint_; hardware_interface::JointHandle right_wheel_joint_; // cmd_vel related struct Commands { double lin; double ang; }; realtime_tools::RealtimeBuffer<Commands> command_; Commands command_struct_; ros::Subscriber sub_command_; // odometry related boost::shared_ptr<realtime_tools::RealtimePublisher<nav_msgs::Odometry> > odom_pub_; boost::shared_ptr<realtime_tools::RealtimePublisher<tf::tfMessage> > tf_odom_pub_; Odometry odometryReading_; double wheel_separation_; double wheel_radius_; double left_wheel_old_pos_, right_wheel_old_pos_; double left_wheel_cur_pos_, right_wheel_cur_pos_; double left_wheel_est_vel_, right_wheel_est_vel_; double linear_est_speed_, angular_est_speed_; geometry_msgs::TransformStamped odom_frame; std::list<geometry_msgs::Point> lastSpeeds; typedef std::list<geometry_msgs::Point>::const_iterator speeds_it; private: void cmdVelCallback(const geometry_msgs::Twist& command) { if(isRunning()) { command_struct_.ang = command.angular.z; command_struct_.lin = command.linear.x; command_.writeFromNonRT (command_struct_); ROS_DEBUG_STREAM("Added values to command. Ang: " << command_struct_.ang << ", Lin: " << command_struct_.lin); } else { ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running."); } } std::string getLeafNamespace(const ros::NodeHandle& nh) { const std::string complete_ns = nh.getNamespace(); std::size_t id = complete_ns.find_last_of("/"); return complete_ns.substr(id + 1); } void speedEstimation(const double &linear, double const &angular) { if(lastSpeeds.size()> 10) lastSpeeds.pop_front(); geometry_msgs::Point speed; speed.x = linear; speed.y = angular; lastSpeeds.push_back(speed); double averageLinearSpeed = 0.0, averageAngularSpeed = 0.0; for(speeds_it it=lastSpeeds.begin();it!= lastSpeeds.end(); ++it) { averageLinearSpeed += it->x; averageAngularSpeed += it->y; } linear_est_speed_ = averageLinearSpeed/lastSpeeds.size(); angular_est_speed_ = averageAngularSpeed/lastSpeeds.size(); } }; PLUGINLIB_DECLARE_CLASS(diff_drive_controller, DiffDriveController, diff_drive_controller::DiffDriveController, controller_interface::ControllerBase); }//namespace <|endoftext|>
<commit_before>#include "logging.h" #include "postProcessManager.h" bool PostProcessor::global_post_processor_enabled = true; static int powerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } PostProcessor::PostProcessor(string name, RenderChain* chain) : chain(chain) { if (sf::Shader::isAvailable()) { if (shader.loadFromFile("resources/" + name + ".frag", sf::Shader::Fragment)) { LOG(INFO) << "Loaded shader: " << name; enabled = true; }else{ LOG(WARNING) << "Failed to load shader:" << name; enabled = false; } }else{ LOG(WARNING) << "Did not load load shader: " << name; LOG(WARNING) << "Because of no shader support in video card driver."; enabled = false; } } void PostProcessor::render(sf::RenderTarget& window) { if (!enabled || !sf::Shader::isAvailable() || !global_post_processor_enabled) { chain->render(window); return; } sf::View view(window.getView()); // If the window or texture size is 0/impossible, or if the window size has // changed, resize the viewport, render texture, and input/textureSizes. if (size.x < 1 || renderTexture.getSize().x < 1 || size != window.getSize()) { size = window.getSize(); //Setup a backBuffer to render the game on. Then we can render the backbuffer back to the main screen with full-screen shader effects int w = view.getViewport().width * size.x; int h = view.getViewport().height * size.y; int tw = powerOfTwo(w); int th = powerOfTwo(h); view.setViewport(sf::FloatRect(0, 1.0 - float(h) / float(th), float(w) / float(tw), float(h) / float(th))); renderTexture.create(tw, th, true); renderTexture.setRepeated(true); renderTexture.setSmooth(true); renderTexture.setView(view); shader.setUniform("inputSize", sf::Vector2f(size.x, size.y)); shader.setUniform("textureSize", sf::Vector2f(renderTexture.getSize().x, renderTexture.getSize().y)); } renderTexture.clear(sf::Color(20, 20, 20)); chain->render(renderTexture); renderTexture.display(); sf::Sprite backBufferSprite(renderTexture.getTexture(), sf::IntRect(0, renderTexture.getSize().y - view.getViewport().height * size.y, view.getViewport().width * size.x, view.getViewport().height * size.y)); backBufferSprite.setScale(view.getSize().x / float(renderTexture.getSize().x) / renderTexture.getView().getViewport().width, view.getSize().y / float(renderTexture.getSize().y) / renderTexture.getView().getViewport().height); window.draw(backBufferSprite, &shader); } void PostProcessor::setUniform(string name, float value) { if (sf::Shader::isAvailable() && global_post_processor_enabled) shader.setUniform(name, value); } <commit_msg>Postprocess RT sizing fix (#77)<commit_after>#include "logging.h" #include "postProcessManager.h" bool PostProcessor::global_post_processor_enabled = true; PostProcessor::PostProcessor(string name, RenderChain* chain) : chain(chain) { if (sf::Shader::isAvailable()) { if (shader.loadFromFile("resources/" + name + ".frag", sf::Shader::Fragment)) { LOG(INFO) << "Loaded shader: " << name; enabled = true; }else{ LOG(WARNING) << "Failed to load shader:" << name; enabled = false; } }else{ LOG(WARNING) << "Did not load load shader: " << name; LOG(WARNING) << "Because of no shader support in video card driver."; enabled = false; } } void PostProcessor::render(sf::RenderTarget& window) { if (!enabled || !sf::Shader::isAvailable() || !global_post_processor_enabled) { chain->render(window); return; } //Hack the rectangle for this element so it sits perfectly on pixel boundaries. sf::Vector2u pixel_size{ window.getSize() }; // If the window or texture size is 0/impossible, or if the window size has // changed, resize the viewport, render texture, and input/textureSizes. if (size.x < 1 || renderTexture.getSize().x < 1 || size != pixel_size) { size = pixel_size; //Setup a backBuffer to render the game on. Then we can render the backbuffer back to the main screen with full-screen shader effects renderTexture.create(size.x, size.y, true); renderTexture.setRepeated(true); renderTexture.setSmooth(true); shader.setUniform("inputSize", sf::Vector2f{ size }); shader.setUniform("textureSize", sf::Vector2f{ renderTexture.getSize() }); } // The view can evolve independently from the window size - update every frame. renderTexture.setView(window.getView()); renderTexture.clear(sf::Color(20, 20, 20)); chain->render(renderTexture); renderTexture.display(); // The RT is a fullscreen texture. // Setup the view to cover the entire RT. window.setView(sf::View({ 0.f, 0.f, static_cast<float>(renderTexture.getSize().x), static_cast<float>(renderTexture.getSize().y) })); sf::Sprite backBufferSprite(renderTexture.getTexture()); window.draw(backBufferSprite, &shader); // Restore view window.setView(renderTexture.getView()); } void PostProcessor::setUniform(string name, float value) { if (sf::Shader::isAvailable() && global_post_processor_enabled) shader.setUniform(name, value); } <|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2014 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "monitor.hh" #include "configmanager.hh" #include "authdb.hh" #include <sofia-sip/su_md5.h> #include <ortp/rtpsession.h> using namespace std; Monitor::Init Monitor::sInit; const string Monitor::PYTHON_INTERPRETOR = "/usr/bin/python2"; const string Monitor::SCRIPT_PATH = "/home/francois/projects/flexisip/flexisip_monitor/flexisip_monitor.py"; const string Monitor::CALLER_PREFIX = "monitor-caller"; const string Monitor::CALLEE_PREFIX = "monitor-callee"; Monitor::Init::Init() { ConfigItemDescriptor items[] = { { Boolean , "enabled" , "Enable or disable the Flexisip monitor daemon", "false" }, { Integer , "test-interval" , "Time between two consecutive tests", "30"}, { String , "logfile" , "Path to the log file", "/etc/flexisip/flexisip_monitor.log"}, { Integer , "switch-port" , "Port to open/close folowing the test succeed or not", "12345"}, { String , "password-salt" , "Salt used to generate the passwords of each test account", "" }, config_item_end }; GenericStruct *s = new GenericStruct("monitor", "Flexisip monitor parameters", 0); GenericManager::get()->getRoot()->addChild(s); s->addChildrenValues(items); } void Monitor::exec(int socket) { // Create a temporary agent to load all modules su_root_t *root = NULL; shared_ptr<Agent> a = make_shared<Agent>(root); GenericManager::get()->loadStrict(); GenericStruct *monitorParams = GenericManager::get()->getRoot()->get<GenericStruct>("monitor"); GenericStruct *cluster = GenericManager::get()->getRoot()->get<GenericStruct>("cluster"); string interval = monitorParams->get<ConfigValue>("test-interval")->get(); string logfile = monitorParams->get<ConfigString>("logfile")->read(); string port = monitorParams->get<ConfigValue>("switch-port")->get(); string salt = monitorParams->get<ConfigString>("password-salt")->read(); list<string> nodes = cluster->get<ConfigStringList>("nodes")->read(); string domain; try { domain = findDomain(); } catch(const FlexisipException &e) { LOGF("Monitor: cannot find domain. %s", e.str().c_str()); exit(-1); } if(salt.empty()) { LOGF("Monitor: no salt set"); exit(-1); } if(nodes.empty()) { LOGF("Monitor: no nodes declared in the cluster section"); exit(-1); } char **args = new char *[10 + nodes.size() + 1]; args[0] = strdup(PYTHON_INTERPRETOR.c_str()); args[1] = strdup(SCRIPT_PATH.c_str()); args[2] = strdup("--interval"); args[3] = strdup(interval.c_str()); args[4] = strdup("--log"); args[5] = strdup(logfile.c_str()); args[6] = strdup("--port"); args[7] = strdup(port.c_str()); args[8] = strdup(domain.c_str()); args[9] = strdup(salt.c_str()); int i = 10; for(string node : nodes) { args[i] = strdup(node.c_str()); i++; } args[i] = NULL; if(write(socket, "ok", 3) == -1) { exit(-1); } close(socket); execvp(args[0], args); } string Monitor::findLocalAddress(const list<string> &nodes) { RtpSession *session = rtp_session_new(RTP_SESSION_RECVONLY); for(const string & node : nodes) { if(rtp_session_set_local_addr(session, node.c_str(), 0, 0) != -1) { rtp_session_destroy(session); return node; } } return ""; } void Monitor::createAccounts() { url_t url = {0}; AuthDb *authDb = AuthDb::get(); GenericStruct *cluster = GenericManager::get()->getRoot()->get<GenericStruct>("cluster"); GenericStruct *monitorConf = GenericManager::get()->getRoot()->get<GenericStruct>("monitor"); string salt = monitorConf->get<ConfigString>("password-salt")->read(); list<string> nodes = cluster->get<ConfigStringList>("nodes")->read(); string domaine = findDomain(); url.url_host = domaine.c_str(); string localIP = findLocalAddress(nodes); if(localIP == "") { SLOGA << "Could not find local IP address"; exit(-1); } string password = generatePassword(localIP, salt).c_str(); string username = generateUsername(CALLER_PREFIX, localIP); url.url_user = username.c_str(); authDb->createAccount(&url, url.url_user, password.c_str(), INT_MAX/2); username = generateUsername(CALLEE_PREFIX, localIP).c_str(); url.url_user = username.c_str(); authDb->createAccount(&url, url.url_user, password.c_str(), INT_MAX/2); } bool Monitor::isLocalhost(const string &host) { return host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "localhost.localdomain"; } bool Monitor::notLocalhost(const string &host) { return !isLocalhost(host); } string Monitor::md5sum(const string &s) { char digest[2 * SU_MD5_DIGEST_SIZE + 1]; su_md5_t ctx; su_md5_init(&ctx); su_md5_strupdate(&ctx, s.c_str()); su_md5_hexdigest(&ctx, digest); return digest; } string Monitor::generateUsername(const string &prefix, const string &host) { return prefix + "-" + md5sum(host); } string Monitor::generatePassword(const string &host, const string &salt) { return md5sum(host + salt); } string Monitor::findDomain() { GenericStruct *registrarConf = GenericManager::get()->getRoot()->get<GenericStruct>("module::Registrar"); list<string> domains = registrarConf->get<ConfigStringList>("reg-domains")->read(); if(domains.size() == 0) { throw FlexisipException("No domain declared in the registar module parameters"); } list<string>::const_iterator it = find_if(domains.cbegin(), domains.cend(), notLocalhost); if(it == domains.cend()) { throw FlexisipException("Only localhost is declared as registrar domain"); } return *it; } <commit_msg>Fix compilation issue with clang<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2014 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "monitor.hh" #include "configmanager.hh" #include "authdb.hh" #include <sofia-sip/su_md5.h> #include <ortp/rtpsession.h> using namespace std; Monitor::Init Monitor::sInit; const string Monitor::PYTHON_INTERPRETOR = "/usr/bin/python2"; const string Monitor::SCRIPT_PATH = "/home/francois/projects/flexisip/flexisip_monitor/flexisip_monitor.py"; const string Monitor::CALLER_PREFIX = "monitor-caller"; const string Monitor::CALLEE_PREFIX = "monitor-callee"; Monitor::Init::Init() { ConfigItemDescriptor items[] = { { Boolean , "enabled" , "Enable or disable the Flexisip monitor daemon", "false" }, { Integer , "test-interval" , "Time between two consecutive tests", "30"}, { String , "logfile" , "Path to the log file", "/etc/flexisip/flexisip_monitor.log"}, { Integer , "switch-port" , "Port to open/close folowing the test succeed or not", "12345"}, { String , "password-salt" , "Salt used to generate the passwords of each test account", "" }, config_item_end }; GenericStruct *s = new GenericStruct("monitor", "Flexisip monitor parameters", 0); GenericManager::get()->getRoot()->addChild(s); s->addChildrenValues(items); } void Monitor::exec(int socket) { // Create a temporary agent to load all modules su_root_t *root = NULL; shared_ptr<Agent> a = make_shared<Agent>(root); GenericManager::get()->loadStrict(); GenericStruct *monitorParams = GenericManager::get()->getRoot()->get<GenericStruct>("monitor"); GenericStruct *cluster = GenericManager::get()->getRoot()->get<GenericStruct>("cluster"); string interval = monitorParams->get<ConfigValue>("test-interval")->get(); string logfile = monitorParams->get<ConfigString>("logfile")->read(); string port = monitorParams->get<ConfigValue>("switch-port")->get(); string salt = monitorParams->get<ConfigString>("password-salt")->read(); list<string> nodes = cluster->get<ConfigStringList>("nodes")->read(); string domain; try { domain = findDomain(); } catch(const FlexisipException &e) { LOGF("Monitor: cannot find domain. %s", e.str().c_str()); exit(-1); } if(salt.empty()) { LOGF("Monitor: no salt set"); exit(-1); } if(nodes.empty()) { LOGF("Monitor: no nodes declared in the cluster section"); exit(-1); } char **args = new char *[10 + nodes.size() + 1]; args[0] = strdup(PYTHON_INTERPRETOR.c_str()); args[1] = strdup(SCRIPT_PATH.c_str()); args[2] = strdup("--interval"); args[3] = strdup(interval.c_str()); args[4] = strdup("--log"); args[5] = strdup(logfile.c_str()); args[6] = strdup("--port"); args[7] = strdup(port.c_str()); args[8] = strdup(domain.c_str()); args[9] = strdup(salt.c_str()); int i = 10; for(string node : nodes) { args[i] = strdup(node.c_str()); i++; } args[i] = NULL; if(write(socket, "ok", 3) == -1) { exit(-1); } close(socket); execvp(args[0], args); } string Monitor::findLocalAddress(const list<string> &nodes) { RtpSession *session = rtp_session_new(RTP_SESSION_RECVONLY); for(const string & node : nodes) { if(rtp_session_set_local_addr(session, node.c_str(), 0, 0) != -1) { rtp_session_destroy(session); return node; } } return ""; } void Monitor::createAccounts() { url_t url; memset(&url, 0, sizeof(url_t)); AuthDb *authDb = AuthDb::get(); GenericStruct *cluster = GenericManager::get()->getRoot()->get<GenericStruct>("cluster"); GenericStruct *monitorConf = GenericManager::get()->getRoot()->get<GenericStruct>("monitor"); string salt = monitorConf->get<ConfigString>("password-salt")->read(); list<string> nodes = cluster->get<ConfigStringList>("nodes")->read(); string domaine = findDomain(); url.url_host = domaine.c_str(); string localIP = findLocalAddress(nodes); if(localIP == "") { SLOGA << "Could not find local IP address"; exit(-1); } string password = generatePassword(localIP, salt).c_str(); string username = generateUsername(CALLER_PREFIX, localIP); url.url_user = username.c_str(); authDb->createAccount(&url, url.url_user, password.c_str(), INT_MAX/2); username = generateUsername(CALLEE_PREFIX, localIP).c_str(); url.url_user = username.c_str(); authDb->createAccount(&url, url.url_user, password.c_str(), INT_MAX/2); } bool Monitor::isLocalhost(const string &host) { return host == "localhost" || host == "127.0.0.1" || host == "::1" || host == "localhost.localdomain"; } bool Monitor::notLocalhost(const string &host) { return !isLocalhost(host); } string Monitor::md5sum(const string &s) { char digest[2 * SU_MD5_DIGEST_SIZE + 1]; su_md5_t ctx; su_md5_init(&ctx); su_md5_strupdate(&ctx, s.c_str()); su_md5_hexdigest(&ctx, digest); return digest; } string Monitor::generateUsername(const string &prefix, const string &host) { return prefix + "-" + md5sum(host); } string Monitor::generatePassword(const string &host, const string &salt) { return md5sum(host + salt); } string Monitor::findDomain() { GenericStruct *registrarConf = GenericManager::get()->getRoot()->get<GenericStruct>("module::Registrar"); list<string> domains = registrarConf->get<ConfigStringList>("reg-domains")->read(); if(domains.size() == 0) { throw FlexisipException("No domain declared in the registar module parameters"); } list<string>::const_iterator it = find_if(domains.cbegin(), domains.cend(), notLocalhost); if(it == domains.cend()) { throw FlexisipException("Only localhost is declared as registrar domain"); } return *it; } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_ERROR_HPP_ #define RDB_PROTOCOL_ERROR_HPP_ #include <list> #include <string> #include "utils.hpp" #include "containers/archive/stl_types.hpp" #include "rdb_protocol/counted_term.hpp" #include "rdb_protocol/ql2.pb.h" #include "rdb_protocol/ql2_extensions.pb.h" #include "rpc/serialize_macros.hpp" namespace ql { // Catch this if you want to handle either `exc_t` or `datum_exc_t`. class base_exc_t : public std::exception { public: enum type_t { GENERIC, // All errors except those below. // The only thing that cares about these is `default`. EMPTY_USER, // An error caused by `r.error` with no arguments. NON_EXISTENCE // An error related to the absence of an expected value. }; explicit base_exc_t(type_t type) : type_(type) { } virtual ~base_exc_t() throw () { } type_t get_type() const { return type_; } protected: type_t type_; }; ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE( base_exc_t::type_t, int8_t, base_exc_t::GENERIC, base_exc_t::NON_EXISTENCE); // NOTE: you usually want to inherit from `rcheckable_t` instead of calling this // directly. void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg, const Backtrace *bt_src) NORETURN; void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg) NORETURN; void runtime_sanity_check_failed() NORETURN; // Inherit from this in classes that wish to use `rcheck`. If a class is // rcheckable, it means that you can call `rcheck` from within it or use it as a // target for `rcheck_target`. class rcheckable_t { public: virtual ~rcheckable_t() { } virtual void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg) const = 0; }; protob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t); // This is a particular type of rcheckable. A `pb_rcheckable_t` corresponds to // a part of the protobuf source tree, and can be used to produce a useful // backtrace. (By contrast, a normal rcheckable might produce an error with no // backtrace, e.g. if we some constraint that doesn't involve the user's code // is violated.) class pb_rcheckable_t : public rcheckable_t { public: virtual void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg) const { ql::runtime_fail(type, test, file, line, msg, bt_src.get()); } // Propagate the associated backtrace through the rewrite term. void propagate(Term *t) const; protob_t<const Backtrace> backtrace() const { return bt_src; } protected: explicit pb_rcheckable_t(const protob_t<const Backtrace> &_bt_src) : bt_src(_bt_src) { } private: protob_t<const Backtrace> bt_src; }; // Use these macros to return errors to users. #define rcheck_target(target, type, pred, msg) do { \ (pred) \ ? (void)0 \ : (target)->runtime_fail(type, stringify(pred), \ __FILE__, __LINE__, (msg)); \ } while (0) #define rcheck_typed_target(target, pred, msg) do { \ (pred) \ ? (void)0 \ : (target)->runtime_fail(exc_type(target), stringify(pred), \ __FILE__, __LINE__, (msg)); \ } while (0) #define rcheck_src(src, type, pred, msg) do { \ (pred) \ ? (void)0 \ : ql::runtime_fail(type, stringify(pred), \ __FILE__, __LINE__, (msg), (src)); \ } while (0) #define rcheck_datum(pred, type, msg) do { \ (pred) \ ? (void)0 \ : ql::runtime_fail(type, stringify(pred), \ __FILE__, __LINE__, (msg)); \ } while (0) #define rcheck(pred, type, msg) rcheck_target(this, type, pred, msg) #define rcheck_typed(pred, typed_arg, msg) \ rcheck_target(this, exc_type(typed_arg), typed_arg, pred, msg) #define rcheck_toplevel(pred, type, msg) \ rcheck_src(NULL, type, pred, msg) #define rfail_datum(type, args...) do { \ rcheck_datum(false, type, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_target(target, type, args...) do { \ rcheck_target(target, type, false, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_typed_target(target, args...) do { \ rcheck_typed_target(target, false, strprintf(args)); \ unreachable(); \ } while (0) #define rfail(type, args...) do { \ rcheck(false, type, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_toplevel(type, args...) do { \ rcheck_toplevel(false, type, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_typed(typed_arg, args...) do { \ rcheck_typed(false, typed_arg, strprintf(args)); \ unreachable(); \ } while (0) class datum_t; class val_t; base_exc_t::type_t exc_type(const datum_t *d); base_exc_t::type_t exc_type(const counted_t<const datum_t> &d); base_exc_t::type_t exc_type(const val_t *d); base_exc_t::type_t exc_type(const counted_t<val_t> &v); // r_sanity_check should be used in place of guarantee if you think the // guarantee will almost always fail due to an error in the query logic rather // than memory corruption. #ifndef NDEBUG #define r_sanity_check(test) guarantee(test) #else #define r_sanity_check(test) do { \ if (!(test)) { \ ::ql::runtime_sanity_check_failed(); \ } while (0) #endif // NDEBUG // A backtrace we return to the user. Pretty self-explanatory. class backtrace_t { public: explicit backtrace_t(const Backtrace *bt) { if (!bt) return; for (int i = 0; i < bt->frames_size(); ++i) { frame_t f(bt->frames(i)); r_sanity_check(f.is_valid()); frames.push_back(f); } } backtrace_t() { } class frame_t { public: explicit frame_t() : type(OPT), opt("UNITIALIZED") { } explicit frame_t(int32_t _pos) : type(POS), pos(_pos) { } explicit frame_t(const std::string &_opt) : type(OPT), opt(_opt) { } explicit frame_t(const char *_opt) : type(OPT), opt(_opt) { } explicit frame_t(const Frame &f); Frame toproto() const; static frame_t invalid() { return frame_t(INVALID); } bool is_invalid() const { return type == POS && pos == INVALID; } static frame_t head() { return frame_t(HEAD); } bool is_head() const { return type == POS && pos == HEAD; } static frame_t skip() { return frame_t(SKIP); } bool is_skip() const { return type == POS && pos == SKIP; } bool is_valid() { // -1 is the classic "invalid" frame return is_head() || is_skip() || (type == POS && pos >= 0) || (type == OPT && opt != "UNINITIALIZED"); } bool is_stream_funcall_frame() { return type == POS && pos != 0; } private: enum special_frames { INVALID = -1, HEAD = -2, SKIP = -3 }; enum type_t { POS = 0, OPT = 1 }; int32_t type; // serialize macros didn't like `type_t` for some reason int32_t pos; std::string opt; public: RDB_MAKE_ME_SERIALIZABLE_3(type, pos, opt); }; void fill_bt(Backtrace *bt) const; // Write out the backtrace to return it to the user. void fill_error(Response *res, Response_ResponseType type, std::string msg) const; RDB_MAKE_ME_SERIALIZABLE_1(frames); bool is_empty() { return frames.size() == 0; } void delete_frames(int num_frames) { for (int i = 0; i < num_frames; ++i) { if (frames.size() == 0) { rassert(false); } else { frames.pop_back(); } } } private: std::list<frame_t> frames; }; const backtrace_t::frame_t head_frame = backtrace_t::frame_t::head(); // A RQL exception. class exc_t : public base_exc_t { public: // We have a default constructor because these are serialized. exc_t() : base_exc_t(base_exc_t::GENERIC), exc_msg_("UNINITIALIZED") { } exc_t(base_exc_t::type_t type, const std::string &exc_msg, const Backtrace *bt_src) : base_exc_t(type), exc_msg_(exc_msg) { if (bt_src != NULL) { backtrace_ = backtrace_t(bt_src); } } exc_t(const base_exc_t &e, const Backtrace *bt_src, int dummy_frames = 0) : base_exc_t(e.get_type()), exc_msg_(e.what()) { if (bt_src != NULL) { backtrace_ = backtrace_t(bt_src); } backtrace_.delete_frames(dummy_frames); } exc_t(base_exc_t::type_t type, const std::string &exc_msg, const backtrace_t &backtrace) : base_exc_t(type), backtrace_(backtrace), exc_msg_(exc_msg) { } virtual ~exc_t() throw () { } const char *what() const throw () { return exc_msg_.c_str(); } const backtrace_t &backtrace() const { return backtrace_; } RDB_MAKE_ME_SERIALIZABLE_3(type_, backtrace_, exc_msg_); private: backtrace_t backtrace_; std::string exc_msg_; }; // A datum exception is like a normal RQL exception, except it doesn't // correspond to part of the source tree. It's usually thrown from inside // datum.{hpp,cc} and must be caught by the enclosing term/stream/whatever and // turned into a normal `exc_t`. class datum_exc_t : public base_exc_t { public: datum_exc_t() : base_exc_t(base_exc_t::GENERIC), exc_msg("UNINITIALIZED") { } explicit datum_exc_t(base_exc_t::type_t type, const std::string &_exc_msg) : base_exc_t(type), exc_msg(_exc_msg) { } virtual ~datum_exc_t() throw () { } const char *what() const throw () { return exc_msg.c_str(); } private: std::string exc_msg; public: RDB_MAKE_ME_SERIALIZABLE_2(type_, exc_msg); }; void fill_error(Response *res, Response_ResponseType type, std::string msg, const backtrace_t &bt = backtrace_t()); } // namespace ql #endif // RDB_PROTOCOL_ERROR_HPP_ <commit_msg>Made r_sanity_check macro have balanced braces.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_ERROR_HPP_ #define RDB_PROTOCOL_ERROR_HPP_ #include <list> #include <string> #include "utils.hpp" #include "containers/archive/stl_types.hpp" #include "rdb_protocol/counted_term.hpp" #include "rdb_protocol/ql2.pb.h" #include "rdb_protocol/ql2_extensions.pb.h" #include "rpc/serialize_macros.hpp" namespace ql { // Catch this if you want to handle either `exc_t` or `datum_exc_t`. class base_exc_t : public std::exception { public: enum type_t { GENERIC, // All errors except those below. // The only thing that cares about these is `default`. EMPTY_USER, // An error caused by `r.error` with no arguments. NON_EXISTENCE // An error related to the absence of an expected value. }; explicit base_exc_t(type_t type) : type_(type) { } virtual ~base_exc_t() throw () { } type_t get_type() const { return type_; } protected: type_t type_; }; ARCHIVE_PRIM_MAKE_RANGED_SERIALIZABLE( base_exc_t::type_t, int8_t, base_exc_t::GENERIC, base_exc_t::NON_EXISTENCE); // NOTE: you usually want to inherit from `rcheckable_t` instead of calling this // directly. void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg, const Backtrace *bt_src) NORETURN; void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg) NORETURN; void runtime_sanity_check_failed() NORETURN; // Inherit from this in classes that wish to use `rcheck`. If a class is // rcheckable, it means that you can call `rcheck` from within it or use it as a // target for `rcheck_target`. class rcheckable_t { public: virtual ~rcheckable_t() { } virtual void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg) const = 0; }; protob_t<const Backtrace> get_backtrace(const protob_t<const Term> &t); // This is a particular type of rcheckable. A `pb_rcheckable_t` corresponds to // a part of the protobuf source tree, and can be used to produce a useful // backtrace. (By contrast, a normal rcheckable might produce an error with no // backtrace, e.g. if we some constraint that doesn't involve the user's code // is violated.) class pb_rcheckable_t : public rcheckable_t { public: virtual void runtime_fail(base_exc_t::type_t type, const char *test, const char *file, int line, std::string msg) const { ql::runtime_fail(type, test, file, line, msg, bt_src.get()); } // Propagate the associated backtrace through the rewrite term. void propagate(Term *t) const; protob_t<const Backtrace> backtrace() const { return bt_src; } protected: explicit pb_rcheckable_t(const protob_t<const Backtrace> &_bt_src) : bt_src(_bt_src) { } private: protob_t<const Backtrace> bt_src; }; // Use these macros to return errors to users. #define rcheck_target(target, type, pred, msg) do { \ (pred) \ ? (void)0 \ : (target)->runtime_fail(type, stringify(pred), \ __FILE__, __LINE__, (msg)); \ } while (0) #define rcheck_typed_target(target, pred, msg) do { \ (pred) \ ? (void)0 \ : (target)->runtime_fail(exc_type(target), stringify(pred), \ __FILE__, __LINE__, (msg)); \ } while (0) #define rcheck_src(src, type, pred, msg) do { \ (pred) \ ? (void)0 \ : ql::runtime_fail(type, stringify(pred), \ __FILE__, __LINE__, (msg), (src)); \ } while (0) #define rcheck_datum(pred, type, msg) do { \ (pred) \ ? (void)0 \ : ql::runtime_fail(type, stringify(pred), \ __FILE__, __LINE__, (msg)); \ } while (0) #define rcheck(pred, type, msg) rcheck_target(this, type, pred, msg) #define rcheck_typed(pred, typed_arg, msg) \ rcheck_target(this, exc_type(typed_arg), typed_arg, pred, msg) #define rcheck_toplevel(pred, type, msg) \ rcheck_src(NULL, type, pred, msg) #define rfail_datum(type, args...) do { \ rcheck_datum(false, type, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_target(target, type, args...) do { \ rcheck_target(target, type, false, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_typed_target(target, args...) do { \ rcheck_typed_target(target, false, strprintf(args)); \ unreachable(); \ } while (0) #define rfail(type, args...) do { \ rcheck(false, type, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_toplevel(type, args...) do { \ rcheck_toplevel(false, type, strprintf(args)); \ unreachable(); \ } while (0) #define rfail_typed(typed_arg, args...) do { \ rcheck_typed(false, typed_arg, strprintf(args)); \ unreachable(); \ } while (0) class datum_t; class val_t; base_exc_t::type_t exc_type(const datum_t *d); base_exc_t::type_t exc_type(const counted_t<const datum_t> &d); base_exc_t::type_t exc_type(const val_t *d); base_exc_t::type_t exc_type(const counted_t<val_t> &v); // r_sanity_check should be used in place of guarantee if you think the // guarantee will almost always fail due to an error in the query logic rather // than memory corruption. #ifndef NDEBUG #define r_sanity_check(test) guarantee(test) #else #define r_sanity_check(test) do { \ if (!(test)) { \ ::ql::runtime_sanity_check_failed(); \ } \ } while (0) #endif // NDEBUG // A backtrace we return to the user. Pretty self-explanatory. class backtrace_t { public: explicit backtrace_t(const Backtrace *bt) { if (!bt) return; for (int i = 0; i < bt->frames_size(); ++i) { frame_t f(bt->frames(i)); r_sanity_check(f.is_valid()); frames.push_back(f); } } backtrace_t() { } class frame_t { public: explicit frame_t() : type(OPT), opt("UNITIALIZED") { } explicit frame_t(int32_t _pos) : type(POS), pos(_pos) { } explicit frame_t(const std::string &_opt) : type(OPT), opt(_opt) { } explicit frame_t(const char *_opt) : type(OPT), opt(_opt) { } explicit frame_t(const Frame &f); Frame toproto() const; static frame_t invalid() { return frame_t(INVALID); } bool is_invalid() const { return type == POS && pos == INVALID; } static frame_t head() { return frame_t(HEAD); } bool is_head() const { return type == POS && pos == HEAD; } static frame_t skip() { return frame_t(SKIP); } bool is_skip() const { return type == POS && pos == SKIP; } bool is_valid() { // -1 is the classic "invalid" frame return is_head() || is_skip() || (type == POS && pos >= 0) || (type == OPT && opt != "UNINITIALIZED"); } bool is_stream_funcall_frame() { return type == POS && pos != 0; } private: enum special_frames { INVALID = -1, HEAD = -2, SKIP = -3 }; enum type_t { POS = 0, OPT = 1 }; int32_t type; // serialize macros didn't like `type_t` for some reason int32_t pos; std::string opt; public: RDB_MAKE_ME_SERIALIZABLE_3(type, pos, opt); }; void fill_bt(Backtrace *bt) const; // Write out the backtrace to return it to the user. void fill_error(Response *res, Response_ResponseType type, std::string msg) const; RDB_MAKE_ME_SERIALIZABLE_1(frames); bool is_empty() { return frames.size() == 0; } void delete_frames(int num_frames) { for (int i = 0; i < num_frames; ++i) { if (frames.size() == 0) { rassert(false); } else { frames.pop_back(); } } } private: std::list<frame_t> frames; }; const backtrace_t::frame_t head_frame = backtrace_t::frame_t::head(); // A RQL exception. class exc_t : public base_exc_t { public: // We have a default constructor because these are serialized. exc_t() : base_exc_t(base_exc_t::GENERIC), exc_msg_("UNINITIALIZED") { } exc_t(base_exc_t::type_t type, const std::string &exc_msg, const Backtrace *bt_src) : base_exc_t(type), exc_msg_(exc_msg) { if (bt_src != NULL) { backtrace_ = backtrace_t(bt_src); } } exc_t(const base_exc_t &e, const Backtrace *bt_src, int dummy_frames = 0) : base_exc_t(e.get_type()), exc_msg_(e.what()) { if (bt_src != NULL) { backtrace_ = backtrace_t(bt_src); } backtrace_.delete_frames(dummy_frames); } exc_t(base_exc_t::type_t type, const std::string &exc_msg, const backtrace_t &backtrace) : base_exc_t(type), backtrace_(backtrace), exc_msg_(exc_msg) { } virtual ~exc_t() throw () { } const char *what() const throw () { return exc_msg_.c_str(); } const backtrace_t &backtrace() const { return backtrace_; } RDB_MAKE_ME_SERIALIZABLE_3(type_, backtrace_, exc_msg_); private: backtrace_t backtrace_; std::string exc_msg_; }; // A datum exception is like a normal RQL exception, except it doesn't // correspond to part of the source tree. It's usually thrown from inside // datum.{hpp,cc} and must be caught by the enclosing term/stream/whatever and // turned into a normal `exc_t`. class datum_exc_t : public base_exc_t { public: datum_exc_t() : base_exc_t(base_exc_t::GENERIC), exc_msg("UNINITIALIZED") { } explicit datum_exc_t(base_exc_t::type_t type, const std::string &_exc_msg) : base_exc_t(type), exc_msg(_exc_msg) { } virtual ~datum_exc_t() throw () { } const char *what() const throw () { return exc_msg.c_str(); } private: std::string exc_msg; public: RDB_MAKE_ME_SERIALIZABLE_2(type_, exc_msg); }; void fill_error(Response *res, Response_ResponseType type, std::string msg, const backtrace_t &bt = backtrace_t()); } // namespace ql #endif // RDB_PROTOCOL_ERROR_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_CLUSTER_TREE_HPP #define REALM_CLUSTER_TREE_HPP #include <realm/obj.hpp> namespace realm { class ClusterTree { public: class ConstIterator; class Iterator; using TraverseFunction = std::function<bool(const Cluster*)>; using UpdateFunction = std::function<void(Cluster*)>; ClusterTree(Table* owner, Allocator& alloc); static MemRef create_empty_cluster(Allocator& alloc); ClusterTree(ClusterTree&&) = default; ClusterTree& operator=(ClusterTree&&) = default; // Disable copying, this is not allowed. ClusterTree& operator=(const ClusterTree&) = delete; ClusterTree(const ClusterTree&) = delete; void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept { m_root->set_parent(parent, ndx_in_parent); } bool is_attached() const { return m_root->is_attached(); } Allocator& get_alloc() const { return m_alloc; } const Table* get_owner() const { return m_owner; } const Spec& get_spec() const; void init_from_ref(ref_type ref); void init_from_parent(); bool update_from_parent(size_t old_baseline) noexcept; size_t size() const noexcept { return m_size; } void clear(); bool is_empty() const noexcept { return size() == 0; } int64_t get_last_key_value() const { return m_root->get_last_key_value(); } MemRef ensure_writeable(ObjKey k) { return m_root->ensure_writeable(k); } Array& get_fields_accessor(Array& fallback, MemRef mem) const { if (m_root->is_leaf()) { return *m_root; } fallback.init_from_mem(mem); return fallback; } uint64_t bump_content_version() { m_alloc.bump_content_version(); return m_alloc.get_content_version(); } void bump_storage_version() { m_alloc.bump_storage_version(); } uint64_t get_content_version() const { return m_alloc.get_content_version(); } uint64_t get_instance_version() const { return m_alloc.get_instance_version(); } uint64_t get_storage_version(uint64_t inst_ver) const { return m_alloc.get_storage_version(inst_ver); } void insert_column(ColKey col) { m_root->insert_column(col); } void remove_column(ColKey col) { m_root->remove_column(col); } // Insert entry for object, but do not create and return the object accessor void insert_fast(ObjKey k, const FieldValues& init_values, ClusterNode::State& state); // Create and return object Obj insert(ObjKey k, const FieldValues&); // Delete object with given key void erase(ObjKey k, CascadeState& state); // Check if an object with given key exists bool is_valid(ObjKey k) const; // Lookup and return read-only object ConstObj get(ObjKey k) const; // Lookup and return object Obj get(ObjKey k); // Lookup ContsObj by index ConstObj get(size_t ndx) const; // Lookup Obj by index Obj get(size_t ndx); // Get logical index of object identified by k size_t get_ndx(ObjKey k) const; // Find the leaf containing the requested object bool get_leaf(ObjKey key, ClusterNode::IteratorState& state) const noexcept; // Visit all leaves and call the supplied function. Stop when function returns true. // Not allowed to modify the tree bool traverse(TraverseFunction& func) const; // Visit all leaves and call the supplied function. The function can modify the leaf. void update(UpdateFunction& func); void enumerate_string_column(ColKey col_key); void dump_objects() { m_root->dump_objects(0, ""); } void verify() const { // TODO: implement } private: friend class ConstObj; friend class Obj; friend class Cluster; friend class ClusterNodeInner; Table* m_owner; Allocator& m_alloc; std::unique_ptr<ClusterNode> m_root; size_t m_size = 0; void replace_root(std::unique_ptr<ClusterNode> leaf); std::unique_ptr<ClusterNode> create_root_from_mem(Allocator& alloc, MemRef mem); std::unique_ptr<ClusterNode> create_root_from_ref(Allocator& alloc, ref_type ref) { return create_root_from_mem(alloc, MemRef{alloc.translate(ref), ref, alloc}); } std::unique_ptr<ClusterNode> get_node(ref_type ref) const; size_t get_column_index(StringData col_name) const; void remove_links(); }; class ClusterTree::ConstIterator { public: typedef std::output_iterator_tag iterator_category; typedef const Obj value_type; typedef ptrdiff_t difference_type; typedef const Obj* pointer; typedef const Obj& reference; ConstIterator(const ClusterTree& t, size_t ndx); ConstIterator(const ClusterTree& t, ObjKey key); ConstIterator(Iterator&&); ConstIterator(const ConstIterator& other) : ConstIterator(other.m_tree, other.m_key) { } ConstIterator& operator=(ConstIterator&& other) { REALM_ASSERT(&m_tree == &other.m_tree); m_key = other.m_key; return *this; } reference operator*() const { return *operator->(); } pointer operator->() const; ConstIterator& operator++(); ConstIterator& operator+=(ptrdiff_t adj); ConstIterator operator+(ptrdiff_t adj) { ConstIterator tmp(*this); tmp += adj; return tmp; } bool operator!=(const ConstIterator& rhs) const { return m_key != rhs.m_key; } protected: const ClusterTree& m_tree; mutable uint64_t m_storage_version = uint64_t(-1); mutable Cluster m_leaf; mutable ClusterNode::IteratorState m_state; mutable uint64_t m_instance_version = uint64_t(-1); mutable ObjKey m_key; mutable std::aligned_storage<sizeof(Obj), alignof(Obj)>::type m_obj_cache_storage; ObjKey load_leaf(ObjKey key) const; }; class ClusterTree::Iterator : public ClusterTree::ConstIterator { public: typedef std::forward_iterator_tag iterator_category; typedef Obj value_type; typedef Obj* pointer; typedef Obj& reference; Iterator(const ClusterTree& t, size_t ndx) : ConstIterator(t, ndx) { } Iterator(const ClusterTree& t, ObjKey key) : ConstIterator(t, key) { } reference operator*() const { return *operator->(); } pointer operator->() const { return const_cast<pointer>(ConstIterator::operator->()); } Iterator& operator++() { return static_cast<Iterator&>(ConstIterator::operator++()); } Iterator& operator+=(ptrdiff_t adj) { return static_cast<Iterator&>(ConstIterator::operator+=(adj)); } Iterator operator+(ptrdiff_t adj) { Iterator tmp(*this); tmp.ConstIterator::operator+=(adj); return tmp; } }; } #endif /* REALM_CLUSTER_TREE_HPP */ <commit_msg>Fix warning "explicitly defaulted move assignment operator is implicitly deleted "<commit_after>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_CLUSTER_TREE_HPP #define REALM_CLUSTER_TREE_HPP #include <realm/obj.hpp> namespace realm { class ClusterTree { public: class ConstIterator; class Iterator; using TraverseFunction = std::function<bool(const Cluster*)>; using UpdateFunction = std::function<void(Cluster*)>; ClusterTree(Table* owner, Allocator& alloc); static MemRef create_empty_cluster(Allocator& alloc); ClusterTree(ClusterTree&&) = default; // Disable copying, this is not allowed. ClusterTree& operator=(const ClusterTree&) = delete; ClusterTree(const ClusterTree&) = delete; void set_parent(ArrayParent* parent, size_t ndx_in_parent) noexcept { m_root->set_parent(parent, ndx_in_parent); } bool is_attached() const { return m_root->is_attached(); } Allocator& get_alloc() const { return m_alloc; } const Table* get_owner() const { return m_owner; } const Spec& get_spec() const; void init_from_ref(ref_type ref); void init_from_parent(); bool update_from_parent(size_t old_baseline) noexcept; size_t size() const noexcept { return m_size; } void clear(); bool is_empty() const noexcept { return size() == 0; } int64_t get_last_key_value() const { return m_root->get_last_key_value(); } MemRef ensure_writeable(ObjKey k) { return m_root->ensure_writeable(k); } Array& get_fields_accessor(Array& fallback, MemRef mem) const { if (m_root->is_leaf()) { return *m_root; } fallback.init_from_mem(mem); return fallback; } uint64_t bump_content_version() { m_alloc.bump_content_version(); return m_alloc.get_content_version(); } void bump_storage_version() { m_alloc.bump_storage_version(); } uint64_t get_content_version() const { return m_alloc.get_content_version(); } uint64_t get_instance_version() const { return m_alloc.get_instance_version(); } uint64_t get_storage_version(uint64_t inst_ver) const { return m_alloc.get_storage_version(inst_ver); } void insert_column(ColKey col) { m_root->insert_column(col); } void remove_column(ColKey col) { m_root->remove_column(col); } // Insert entry for object, but do not create and return the object accessor void insert_fast(ObjKey k, const FieldValues& init_values, ClusterNode::State& state); // Create and return object Obj insert(ObjKey k, const FieldValues&); // Delete object with given key void erase(ObjKey k, CascadeState& state); // Check if an object with given key exists bool is_valid(ObjKey k) const; // Lookup and return read-only object ConstObj get(ObjKey k) const; // Lookup and return object Obj get(ObjKey k); // Lookup ContsObj by index ConstObj get(size_t ndx) const; // Lookup Obj by index Obj get(size_t ndx); // Get logical index of object identified by k size_t get_ndx(ObjKey k) const; // Find the leaf containing the requested object bool get_leaf(ObjKey key, ClusterNode::IteratorState& state) const noexcept; // Visit all leaves and call the supplied function. Stop when function returns true. // Not allowed to modify the tree bool traverse(TraverseFunction& func) const; // Visit all leaves and call the supplied function. The function can modify the leaf. void update(UpdateFunction& func); void enumerate_string_column(ColKey col_key); void dump_objects() { m_root->dump_objects(0, ""); } void verify() const { // TODO: implement } private: friend class ConstObj; friend class Obj; friend class Cluster; friend class ClusterNodeInner; Table* m_owner; Allocator& m_alloc; std::unique_ptr<ClusterNode> m_root; size_t m_size = 0; void replace_root(std::unique_ptr<ClusterNode> leaf); std::unique_ptr<ClusterNode> create_root_from_mem(Allocator& alloc, MemRef mem); std::unique_ptr<ClusterNode> create_root_from_ref(Allocator& alloc, ref_type ref) { return create_root_from_mem(alloc, MemRef{alloc.translate(ref), ref, alloc}); } std::unique_ptr<ClusterNode> get_node(ref_type ref) const; size_t get_column_index(StringData col_name) const; void remove_links(); }; class ClusterTree::ConstIterator { public: typedef std::output_iterator_tag iterator_category; typedef const Obj value_type; typedef ptrdiff_t difference_type; typedef const Obj* pointer; typedef const Obj& reference; ConstIterator(const ClusterTree& t, size_t ndx); ConstIterator(const ClusterTree& t, ObjKey key); ConstIterator(Iterator&&); ConstIterator(const ConstIterator& other) : ConstIterator(other.m_tree, other.m_key) { } ConstIterator& operator=(ConstIterator&& other) { REALM_ASSERT(&m_tree == &other.m_tree); m_key = other.m_key; return *this; } reference operator*() const { return *operator->(); } pointer operator->() const; ConstIterator& operator++(); ConstIterator& operator+=(ptrdiff_t adj); ConstIterator operator+(ptrdiff_t adj) { ConstIterator tmp(*this); tmp += adj; return tmp; } bool operator!=(const ConstIterator& rhs) const { return m_key != rhs.m_key; } protected: const ClusterTree& m_tree; mutable uint64_t m_storage_version = uint64_t(-1); mutable Cluster m_leaf; mutable ClusterNode::IteratorState m_state; mutable uint64_t m_instance_version = uint64_t(-1); mutable ObjKey m_key; mutable std::aligned_storage<sizeof(Obj), alignof(Obj)>::type m_obj_cache_storage; ObjKey load_leaf(ObjKey key) const; }; class ClusterTree::Iterator : public ClusterTree::ConstIterator { public: typedef std::forward_iterator_tag iterator_category; typedef Obj value_type; typedef Obj* pointer; typedef Obj& reference; Iterator(const ClusterTree& t, size_t ndx) : ConstIterator(t, ndx) { } Iterator(const ClusterTree& t, ObjKey key) : ConstIterator(t, key) { } reference operator*() const { return *operator->(); } pointer operator->() const { return const_cast<pointer>(ConstIterator::operator->()); } Iterator& operator++() { return static_cast<Iterator&>(ConstIterator::operator++()); } Iterator& operator+=(ptrdiff_t adj) { return static_cast<Iterator&>(ConstIterator::operator+=(adj)); } Iterator operator+(ptrdiff_t adj) { Iterator tmp(*this); tmp.ConstIterator::operator+=(adj); return tmp; } }; } #endif /* REALM_CLUSTER_TREE_HPP */ <|endoftext|>
<commit_before>// symbiosis: A hacky and lightweight compiler framework // #include "symbiosis.hpp" #include <sys/stat.h> #include <iostream> #include <vector> #include "cpu_defines.hpp" using namespace std; namespace symbiosis { void dump(uchar* start, size_t s) { for (size_t i = 0; i < s; i++) { printf("%02x ", start[i]); } } bool intel = false; bool arm = false; bool pic_mode = false; bool identify_cpu_and_pic_mode() { uchar *start = (uchar *)identify_cpu_and_pic_mode; uchar *p = start; uchar c0,c1,c2; int i = 0; p = start; do { c0 = *p; c1 = *(p+1); c2 = *(p+2); // 4c 8b 3d aa 38 20 00 mov r15,QWORD PTR [rip+0x2038aa] if ((c0 >= I_REX_W_48 && c0 <= I_REX_WRXB_4f) && (c1 == I_LEA_8d || c1 == I_MOV_r64_r64_8b) && ((c2 & I_RM_BITS_07) == I_BP_RM_RIP_DISP32_05)) { intel = true; pic_mode = true; return true; } p++; } while (++i < 20); i = 0; p = start; do { c0 = *p; c1 = *(p+1); c2 = *(p+2); // 8a 88 9f 1a 40 00 mov cl,BYTE PTR [rax+0x401a9f] // 8a 05 f9 ff ff ff mov al,BYTE PTR [rip-5] if (c0 == I_MOV_r8_rm8_8a && (c1 >= I_MOD_SDWORD_RAX_SDWORD_AL_80 && c1 <= I_MOD_SDWORD_RDI_SDWORD_BH_bf)) { intel = true; pic_mode = false; return true; } p++; } while (++i < 20); uchar c3; int ldr_count = 0; i = 0; p = start; do { c0 = *p; c1 = *(p+1); c2 = *(p+2); c3 = *(p + 3); // e59f0028 ldr r0, [pc, #40] if (c3 == A_LDR_e5) { ldr_count++; } p += 4; i += 4; } while (i < 50); if (ldr_count == 4) { arm = true; pic_mode = true; return true; } if (ldr_count > 1) { arm = true; return true; } cout << "Unknown CPU id: "; dump(start, 20); return false; } class exception : public std::exception { const char *what_; public: exception(const char *w) : what_(w) { } virtual ~exception() throw() { } virtual const char* what() const throw() { return what_; } }; char *command_file = 0;; #define M10(v, b) #v #b #define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v) #define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v) #define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v) #define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v) uchar *virtual_code_start = 0; uchar *virtual_code_end = 0; uchar *out_code_start = 0; uchar *out_code_end = 0; uchar *out_c = 0; uchar *out_c0 = 0; uchar *virtual_strings_start = 0; uchar *virtual_strings_end = 0; uchar *out_strings_start = 0; uchar *out_strings_end = 0; uchar *out_s = 0; #define STRINGS_START "STRINGS_START" #define STRINGS_END "STRINGS_END" unsigned int _i32 = 0; const char* id::i32() { if (virtual_adr) { _i32 = (size_t)virtual_adr; //printf("virtual_adr: %x\n", _i32); return (const char*)&_i32; } if (type == T_UINT) return (const char*)&d.ui; return (const char*)&d.i; } const char* id::i64() { if (type == T_ULONG) return (const char*)&d.ul; return (const char*)&d.l; } vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong", "charp", "float", "double"}; void id::describe() { if (type > type_str.size() - 1) { cout << "<id:" << type << ">"; } else { cout << type_str[type]; } cout << endl; } id id::operator()(id i) { add_parameter(i); return i; } id_new::id_new(const char *p) : id(p) { virtual_adr = virtual_strings_start + (out_s - out_strings_start); virtual_size = strlen(p); if (out_s + virtual_size + 1 > out_strings_end) throw exception("Strings: Out of memory"); memcpy(out_s, p, virtual_size + 1); out_s += virtual_size + 1; }; const char *reserved_strings[] = { STRINGS_START, M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc) STRINGS_END }; #define FIND(v) { \ pos = 0; \ bool found = false; \ for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \ for (int j = 0; j < v##_s; j++) { \ if (buf[i + j] != v[j]) break; \ if (j == v##_s - 1) { \ pos = i; \ found = true; \ } \ } \ } } uchar buf[200 * 1024]; FILE* input = 0; size_t input_size = 0; void find_space(uchar* start, size_t start_s, uchar* end, size_t end_s, uchar **out_start, uchar **out_end) { if (!input) { input = fopen(command_file, "r"); if (!input) { fprintf(stderr, "Failed\n"); } input_size = fread(buf, 1, sizeof(buf), input); } size_t pos = 0, s = 0, e = 0; FIND(start); s = pos; FIND(end); e = pos; *out_start = &buf[s]; *out_end = &buf[e]; //printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s); } void write() { FILE *out = fopen("a.out", "w"); fwrite(buf, 1, input_size, out); fclose(out); printf("Writing a.out\n"); chmod("a.out", 0777); } int __offset = 0; const char* call_offset(uchar *out_current_code_pos, void *__virt_f) { auto virt_f = (uchar*)__virt_f; ssize_t out_start_distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = virt_f - virtual_code_start; __offset = virt_dist_from_code_start - out_start_distance - 5; cout << "__virt_f: " << __virt_f << endl; //cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl; return (const char*)&__offset; } const char* rip_relative_offset(uchar *out_current_code_pos, uchar *virt_adr) { ssize_t distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = (size_t)virt_adr - (size_t)virtual_code_start - distance; __offset = virt_dist_from_code_start - 7; printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n", (size_t)virt_adr, __offset, (size_t)(out_s - out_strings_start)); return (const char*)&__offset; } int parameter_count = 0; const char *register_parameters_intel_32[] = { "\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ }; const char *register_rip_relative_parameters_intel_64[] = { "\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */ "\x48\x8d\x15" /* rdx */ }; const char *register_parameters_arm_32[] = { "\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ }; const char *register_parameters_intel_64[] = { "\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ }; constexpr int parameters_max = 3; void emit(const char* _s, size_t _l = 0) { size_t l = _l > 0 ? _l : strlen(_s); uchar *s = (uchar *)_s; uchar *e = s + l; if (out_c + l > out_code_end) throw exception("Code: Out of memory"); for (uchar * b = s; b < e; b++, out_c++) { *out_c = *b; } dump(s, l); } void emit(uchar uc) { emit((const char *)&uc, sizeof(uc)); } id add_parameter(id p) { if (parameter_count >= parameters_max) { fprintf(stderr, "Too many parameters!\n"); return p; } //cout << "parameter_count: " << parameter_count << " "; p.describe(); if (p.is_charp()) { if (!pic_mode) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else { uchar *out_current_code_pos = out_c; emit(register_rip_relative_parameters_intel_64[parameter_count]); emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4); } } else if (p.is_integer()) { //cout << "is_integer" << endl; if (intel) { //cout << "intel" << endl; if (p.is_32()) { //cout << "is_32" << endl; emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else if (p.is_64()) { //cout << "is_64" << endl; emit(register_parameters_intel_64[parameter_count]); emit(p.i64(), 8); } } else if (arm) { emit(register_parameters_intel_32[parameter_count]); } } ++parameter_count; return p; } void jmp(void *f) { uchar *out_current_code_pos = out_c; emit(I_JMP_e9); emit(call_offset(out_current_code_pos, f), 4); } void __call(void *f) { uchar *out_current_code_pos = out_c; emit(I_CALL_e8); emit(call_offset(out_current_code_pos, f), 4); parameter_count = 0; } void __vararg_call(void *f) { emit(I_XOR_30); emit(0xc0); // xor al,al call(f); } size_t __p = 0; void f(const char *s, int i) { __p += (size_t)s + i; } void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) { if (!identify_cpu_and_pic_mode()) exit(1); cout << "intel: " << intel << ", arm: " << arm << ", pic_mode: " << pic_mode << endl; command_file = c; virtual_code_start = start; virtual_code_end = end; find_space(start, ss, end, es, &out_code_start, &out_code_end); //printf("code: %zu\n", out_code_end - out_code_start); virtual_strings_start = (uchar *)STRINGS_START; virtual_strings_end = (uchar *)STRINGS_END; out_c = out_code_start; find_space(virtual_strings_start, strlen(STRINGS_START), virtual_strings_end, strlen(STRINGS_END), &out_strings_start, &out_strings_end); //printf("strings: %zu\n", out_strings_end - out_strings_start); out_s = out_strings_start; } void finish() { jmp(virtual_code_end); write(); } } <commit_msg>Arm pic/nopic detection.<commit_after>// symbiosis: A hacky and lightweight compiler framework // #include "symbiosis.hpp" #include <sys/stat.h> #include <iostream> #include <vector> #include "cpu_defines.hpp" using namespace std; namespace symbiosis { void dump(uchar* start, size_t s) { for (size_t i = 0; i < s; i++) { printf("%02x ", start[i]); } } bool intel = false; bool arm = false; bool pic_mode = false; bool identify_cpu_and_pic_mode() { uchar *start = (uchar *)identify_cpu_and_pic_mode; uchar *p = start; uchar c0,c1,c2; int i = 0; p = start; do { c0 = *p; c1 = *(p+1); c2 = *(p+2); // 4c 8b 3d aa 38 20 00 mov r15,QWORD PTR [rip+0x2038aa] if ((c0 >= I_REX_W_48 && c0 <= I_REX_WRXB_4f) && (c1 == I_LEA_8d || c1 == I_MOV_r64_r64_8b) && ((c2 & I_RM_BITS_07) == I_BP_RM_RIP_DISP32_05)) { intel = true; pic_mode = true; return true; } p++; } while (++i < 20); i = 0; p = start; do { c0 = *p; c1 = *(p+1); c2 = *(p+2); // 8a 88 9f 1a 40 00 mov cl,BYTE PTR [rax+0x401a9f] // 8a 05 f9 ff ff ff mov al,BYTE PTR [rip-5] if (c0 == I_MOV_r8_rm8_8a && (c1 >= I_MOD_SDWORD_RAX_SDWORD_AL_80 && c1 <= I_MOD_SDWORD_RDI_SDWORD_BH_bf)) { intel = true; pic_mode = false; return true; } p++; } while (++i < 20); uchar c3; int ldr_count = 0; i = 0; p = start; do { c0 = *p; c1 = *(p+1); c2 = *(p+2); c3 = *(p + 3); // e59f0028 ldr r0, [pc, #40] if (c3 == A_LDR_e5) { ldr_count++; } p += 4; i += 4; } while (i < 100); if (ldr_count >= 4) { arm = true; pic_mode = true; return true; } if (ldr_count > 1) { arm = true; return true; } cout << "Unknown CPU id: "; dump(start, 20); return false; } class exception : public std::exception { const char *what_; public: exception(const char *w) : what_(w) { } virtual ~exception() throw() { } virtual const char* what() const throw() { return what_; } }; char *command_file = 0;; #define M10(v, b) #v #b #define M3(a,b) M10(a+1000, v),M10(a+2000, v), M10(a+3000, v),M10(a+4000, v) #define M2(a,b) M3(a+100, v) , M3(a+200, v) , M3(a+300, v) , M3(a+400, v) #define M1(a,b) M2(a+10, v) , M2(a+20, v) , M2(a+30, v) , M2(a+40, v) #define M(v) M1(1, v), M1(2, v), M1(3, v), M1(4, v), M1(5, v) uchar *virtual_code_start = 0; uchar *virtual_code_end = 0; uchar *out_code_start = 0; uchar *out_code_end = 0; uchar *out_c = 0; uchar *out_c0 = 0; uchar *virtual_strings_start = 0; uchar *virtual_strings_end = 0; uchar *out_strings_start = 0; uchar *out_strings_end = 0; uchar *out_s = 0; #define STRINGS_START "STRINGS_START" #define STRINGS_END "STRINGS_END" unsigned int _i32 = 0; const char* id::i32() { if (virtual_adr) { _i32 = (size_t)virtual_adr; //printf("virtual_adr: %x\n", _i32); return (const char*)&_i32; } if (type == T_UINT) return (const char*)&d.ui; return (const char*)&d.i; } const char* id::i64() { if (type == T_ULONG) return (const char*)&d.ul; return (const char*)&d.l; } vector<const char*> type_str = { "0:???", "int", "uint", "long", "ulong", "charp", "float", "double"}; void id::describe() { if (type > type_str.size() - 1) { cout << "<id:" << type << ">"; } else { cout << type_str[type]; } cout << endl; } id id::operator()(id i) { add_parameter(i); return i; } id_new::id_new(const char *p) : id(p) { virtual_adr = virtual_strings_start + (out_s - out_strings_start); virtual_size = strlen(p); if (out_s + virtual_size + 1 > out_strings_end) throw exception("Strings: Out of memory"); memcpy(out_s, p, virtual_size + 1); out_s += virtual_size + 1; }; const char *reserved_strings[] = { STRINGS_START, M(ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc) STRINGS_END }; #define FIND(v) { \ pos = 0; \ bool found = false; \ for (size_t i = 0; !found && i < (input_size - v##_s); i++) { \ for (int j = 0; j < v##_s; j++) { \ if (buf[i + j] != v[j]) break; \ if (j == v##_s - 1) { \ pos = i; \ found = true; \ } \ } \ } } uchar buf[200 * 1024]; FILE* input = 0; size_t input_size = 0; void find_space(uchar* start, size_t start_s, uchar* end, size_t end_s, uchar **out_start, uchar **out_end) { if (!input) { input = fopen(command_file, "r"); if (!input) { fprintf(stderr, "Failed\n"); } input_size = fread(buf, 1, sizeof(buf), input); } size_t pos = 0, s = 0, e = 0; FIND(start); s = pos; FIND(end); e = pos; *out_start = &buf[s]; *out_end = &buf[e]; //printf("s: %zd, e:%zd, l:%zd\n", s, e, e - s); } void write() { FILE *out = fopen("a.out", "w"); fwrite(buf, 1, input_size, out); fclose(out); printf("Writing a.out\n"); chmod("a.out", 0777); } int __offset = 0; const char* call_offset(uchar *out_current_code_pos, void *__virt_f) { auto virt_f = (uchar*)__virt_f; ssize_t out_start_distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = virt_f - virtual_code_start; __offset = virt_dist_from_code_start - out_start_distance - 5; cout << "__virt_f: " << __virt_f << endl; //cout << "call_offset: " << __offset << " virt: " << virt_dist_from_code_start << " out: " << out_start_distance << endl; return (const char*)&__offset; } const char* rip_relative_offset(uchar *out_current_code_pos, uchar *virt_adr) { ssize_t distance = out_current_code_pos - out_code_start; ssize_t virt_dist_from_code_start = (size_t)virt_adr - (size_t)virtual_code_start - distance; __offset = virt_dist_from_code_start - 7; printf("virt_dist_from_code_start: %zx %x, string ofs: %zd\n", (size_t)virt_adr, __offset, (size_t)(out_s - out_strings_start)); return (const char*)&__offset; } int parameter_count = 0; const char *register_parameters_intel_32[] = { "\xbf", /*edi*/ "\xbe", /*esi*/ "\xba" /*edx*/ }; const char *register_rip_relative_parameters_intel_64[] = { "\x48\x8d\x3d", /* rdi */ "\x48\x8d\x35", /* rsi */ "\x48\x8d\x15" /* rdx */ }; const char *register_parameters_arm_32[] = { "\xe5\x9f\x00", /*r0*/ "\xe5\x9f\x10", /*r1*/ "\xe5\x9f\x20" /*r2*/ }; const char *register_parameters_intel_64[] = { "\x48\xbf" /*rdi*/, "\x48\xbe" ,/*rsi*/ "\x48\xba" /*rdx*/ }; constexpr int parameters_max = 3; void emit(const char* _s, size_t _l = 0) { size_t l = _l > 0 ? _l : strlen(_s); uchar *s = (uchar *)_s; uchar *e = s + l; if (out_c + l > out_code_end) throw exception("Code: Out of memory"); for (uchar * b = s; b < e; b++, out_c++) { *out_c = *b; } dump(s, l); } void emit(uchar uc) { emit((const char *)&uc, sizeof(uc)); } id add_parameter(id p) { if (parameter_count >= parameters_max) { fprintf(stderr, "Too many parameters!\n"); return p; } if (p.is_charp()) { if (!pic_mode) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else { uchar *out_current_code_pos = out_c; emit(register_rip_relative_parameters_intel_64[parameter_count]); emit(rip_relative_offset(out_current_code_pos, p.virtual_adr), 4); } } else if (p.is_integer()) { if (intel) { if (p.is_32()) { emit(register_parameters_intel_32[parameter_count]); emit(p.i32(), 4); } else if (p.is_64()) { emit(register_parameters_intel_64[parameter_count]); emit(p.i64(), 8); } } else if (arm) { emit(register_parameters_intel_32[parameter_count]); } } ++parameter_count; return p; } void jmp(void *f) { uchar *out_current_code_pos = out_c; emit(I_JMP_e9); emit(call_offset(out_current_code_pos, f), 4); } void __call(void *f) { uchar *out_current_code_pos = out_c; emit(I_CALL_e8); emit(call_offset(out_current_code_pos, f), 4); parameter_count = 0; } void __vararg_call(void *f) { emit(I_XOR_30); emit(0xc0); // xor al,al call(f); } void init(char *c, uchar *start, size_t ss, uchar *end, size_t es) { if (!identify_cpu_and_pic_mode()) exit(1); cout << "intel: " << intel << ", arm: " << arm << ", pic_mode: " << pic_mode << endl; command_file = c; virtual_code_start = start; virtual_code_end = end; find_space(start, ss, end, es, &out_code_start, &out_code_end); //printf("code: %zu\n", out_code_end - out_code_start); virtual_strings_start = (uchar *)STRINGS_START; virtual_strings_end = (uchar *)STRINGS_END; out_c = out_code_start; find_space(virtual_strings_start, strlen(STRINGS_START), virtual_strings_end, strlen(STRINGS_END), &out_strings_start, &out_strings_end); //printf("strings: %zu\n", out_strings_end - out_strings_start); out_s = out_strings_start; } void finish() { jmp(virtual_code_end); write(); } } <|endoftext|>
<commit_before>/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "link_uniform_block_active_visitor.h" #include "program.h" link_uniform_block_active * process_block(void *mem_ctx, struct hash_table *ht, ir_variable *var) { const uint32_t h = _mesa_hash_string(var->get_interface_type()->name); const hash_entry *const existing_block = _mesa_hash_table_search(ht, h, var->get_interface_type()->name); const glsl_type *const block_type = var->is_interface_instance() ? var->type : var->get_interface_type(); /* If a block with this block-name has not previously been seen, add it. * If a block with this block-name has been seen, it must be identical to * the block currently being examined. */ if (existing_block == NULL) { link_uniform_block_active *const b = rzalloc(mem_ctx, struct link_uniform_block_active); b->type = block_type; b->has_instance_name = var->is_interface_instance(); if (var->data.explicit_binding) { b->has_binding = true; b->binding = var->data.binding; } else { b->has_binding = false; b->binding = 0; } _mesa_hash_table_insert(ht, h, var->get_interface_type()->name, (void *) b); return b; } else { link_uniform_block_active *const b = (link_uniform_block_active *) existing_block->data; if (b->type != block_type || b->has_instance_name != var->is_interface_instance()) return NULL; else return b; } assert(!"Should not get here."); return NULL; } ir_visitor_status link_uniform_block_active_visitor::visit_enter(ir_dereference_array *ir) { ir_dereference_variable *const d = ir->array->as_dereference_variable(); ir_variable *const var = (d == NULL) ? NULL : d->var; /* If the r-value being dereferenced is not a variable (e.g., a field of a * structure) or is not a uniform block instance, continue. * * WARNING: It is not enough for the variable to be part of uniform block. * It must represent the entire block. Arrays (or matrices) inside blocks * that lack an instance name are handled by the ir_dereference_variable * function. */ if (var == NULL || !var->is_in_uniform_block() || !var->is_interface_instance()) return visit_continue; /* Process the block. Bail if there was an error. */ link_uniform_block_active *const b = process_block(this->mem_ctx, this->ht, var); if (b == NULL) { linker_error(prog, "uniform block `%s' has mismatching definitions", var->get_interface_type()->name); this->success = false; return visit_stop; } /* Block arrays must be declared with an instance name. */ assert(b->has_instance_name); assert((b->num_array_elements == 0) == (b->array_elements == NULL)); assert(b->type != NULL); /* Determine whether or not this array index has already been added to the * list of active array indices. At this point all constant folding must * have occured, and the array index must be a constant. */ ir_constant *c = ir->array_index->as_constant(); assert(c != NULL); const unsigned idx = c->get_uint_component(0); unsigned i; for (i = 0; i < b->num_array_elements; i++) { if (b->array_elements[i] == idx) break; } assert(i <= b->num_array_elements); if (i == b->num_array_elements) { b->array_elements = reralloc(this->mem_ctx, b->array_elements, unsigned, b->num_array_elements + 1); b->array_elements[b->num_array_elements] = idx; b->num_array_elements++; } return visit_continue_with_parent; } ir_visitor_status link_uniform_block_active_visitor::visit(ir_dereference_variable *ir) { ir_variable *var = ir->var; if (!var->is_in_uniform_block()) return visit_continue; assert(!var->is_interface_instance() || !var->type->is_array()); /* Process the block. Bail if there was an error. */ link_uniform_block_active *const b = process_block(this->mem_ctx, this->ht, var); if (b == NULL) { linker_error(this->prog, "uniform block `%s' has mismatching definitions", var->get_interface_type()->name); this->success = false; return visit_stop; } assert(b->num_array_elements == 0); assert(b->array_elements == NULL); assert(b->type != NULL); return visit_continue; } <commit_msg>glsl: Mark entire UBO array active if indexed with non-constant.<commit_after>/* * Copyright © 2013 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "link_uniform_block_active_visitor.h" #include "program.h" link_uniform_block_active * process_block(void *mem_ctx, struct hash_table *ht, ir_variable *var) { const uint32_t h = _mesa_hash_string(var->get_interface_type()->name); const hash_entry *const existing_block = _mesa_hash_table_search(ht, h, var->get_interface_type()->name); const glsl_type *const block_type = var->is_interface_instance() ? var->type : var->get_interface_type(); /* If a block with this block-name has not previously been seen, add it. * If a block with this block-name has been seen, it must be identical to * the block currently being examined. */ if (existing_block == NULL) { link_uniform_block_active *const b = rzalloc(mem_ctx, struct link_uniform_block_active); b->type = block_type; b->has_instance_name = var->is_interface_instance(); if (var->data.explicit_binding) { b->has_binding = true; b->binding = var->data.binding; } else { b->has_binding = false; b->binding = 0; } _mesa_hash_table_insert(ht, h, var->get_interface_type()->name, (void *) b); return b; } else { link_uniform_block_active *const b = (link_uniform_block_active *) existing_block->data; if (b->type != block_type || b->has_instance_name != var->is_interface_instance()) return NULL; else return b; } assert(!"Should not get here."); return NULL; } ir_visitor_status link_uniform_block_active_visitor::visit_enter(ir_dereference_array *ir) { ir_dereference_variable *const d = ir->array->as_dereference_variable(); ir_variable *const var = (d == NULL) ? NULL : d->var; /* If the r-value being dereferenced is not a variable (e.g., a field of a * structure) or is not a uniform block instance, continue. * * WARNING: It is not enough for the variable to be part of uniform block. * It must represent the entire block. Arrays (or matrices) inside blocks * that lack an instance name are handled by the ir_dereference_variable * function. */ if (var == NULL || !var->is_in_uniform_block() || !var->is_interface_instance()) return visit_continue; /* Process the block. Bail if there was an error. */ link_uniform_block_active *const b = process_block(this->mem_ctx, this->ht, var); if (b == NULL) { linker_error(prog, "uniform block `%s' has mismatching definitions", var->get_interface_type()->name); this->success = false; return visit_stop; } /* Block arrays must be declared with an instance name. */ assert(b->has_instance_name); assert((b->num_array_elements == 0) == (b->array_elements == NULL)); assert(b->type != NULL); ir_constant *c = ir->array_index->as_constant(); if (c) { /* Index is a constant, so mark just that element used, if not already */ const unsigned idx = c->get_uint_component(0); unsigned i; for (i = 0; i < b->num_array_elements; i++) { if (b->array_elements[i] == idx) break; } assert(i <= b->num_array_elements); if (i == b->num_array_elements) { b->array_elements = reralloc(this->mem_ctx, b->array_elements, unsigned, b->num_array_elements + 1); b->array_elements[b->num_array_elements] = idx; b->num_array_elements++; } } else { /* The array index is not a constant, so mark the entire array used. */ assert(b->type->is_array()); if (b->num_array_elements < b->type->length) { b->num_array_elements = b->type->length; b->array_elements = reralloc(this->mem_ctx, b->array_elements, unsigned, b->num_array_elements); for (unsigned i = 0; i < b->num_array_elements; i++) { b->array_elements[i] = i; } } } return visit_continue_with_parent; } ir_visitor_status link_uniform_block_active_visitor::visit(ir_dereference_variable *ir) { ir_variable *var = ir->var; if (!var->is_in_uniform_block()) return visit_continue; assert(!var->is_interface_instance() || !var->type->is_array()); /* Process the block. Bail if there was an error. */ link_uniform_block_active *const b = process_block(this->mem_ctx, this->ht, var); if (b == NULL) { linker_error(this->prog, "uniform block `%s' has mismatching definitions", var->get_interface_type()->name); this->success = false; return visit_stop; } assert(b->num_array_elements == 0); assert(b->array_elements == NULL); assert(b->type != NULL); return visit_continue; } <|endoftext|>
<commit_before>/* * HemisphereA100GPS.cpp * * Created on: Nov 5, 2012 * Author: Matthew Barulic */ #include "nmeacompatiblegps.h" #include "nmea.hpp" #include <string> #include <common/logger/logger.h> NMEACompatibleGPS::NMEACompatibleGPS(string devicePath, uint baudRate) :serialPort(devicePath, baudRate), //serialPort("/dev/ttyGPS", 19200/*For HemisphereA100 4800*/), LonNewSerialLine(this), stateQueue() { serialPort.onNewLine += &LonNewSerialLine; maxBufferLength = 10; serialPort.startEvents(); Logger::Log(LogLevel::Info, "GPS Initialized"); } void NMEACompatibleGPS::onNewSerialLine(string line) { GPSData state; if(parseLine(line, state)) { // TODO set time // gettimeofday(&state.laptoptime, NULL); boost::mutex::scoped_lock lock(queueLocker); stateQueue.push_back(state); if(stateQueue.size() > maxBufferLength) { stateQueue.pop_front(); } onNewData(state); } } bool NMEACompatibleGPS::parseLine(std::string line, GPSData &state) { return nmea::decodeGPGGA(line, state) || nmea::decodeGPRMC(line, state); } GPSData NMEACompatibleGPS::GetState() { boost::mutex::scoped_lock lock(queueLocker); GPSData state = stateQueue.back(); stateQueue.remove(state); return state; } GPSData NMEACompatibleGPS::GetStateAtTime(timeval time) { boost::mutex::scoped_lock lock(queueLocker); std::list<GPSData>::iterator iter = stateQueue.begin(); //double acceptableError = 0.1; while(iter != stateQueue.end()) { GPSData s = (*iter); /*time_t secDelta = difftime(time.tv_sec, s.laptoptime.tv_sec); suseconds_t usecDelta = time.tv_usec - s.laptoptime.tv_usec; double delta = double(secDelta) + 1e-6*double(usecDelta); if(delta <= acceptableError) { // iter = stateQueue.erase(iter); return s; } else { iter++; }*/ } GPSData empty; return empty; } bool NMEACompatibleGPS::StateIsAvailable() { return !stateQueue.empty(); } bool NMEACompatibleGPS::isOpen() { return serialPort.isConnected(); } NMEACompatibleGPS::~NMEACompatibleGPS() { serialPort.stopEvents(); serialPort.close(); } <commit_msg>Fixes GPS init printout logic.<commit_after>/* * HemisphereA100GPS.cpp * * Created on: Nov 5, 2012 * Author: Matthew Barulic */ #include "nmeacompatiblegps.h" #include "nmea.hpp" #include <string> #include <common/logger/logger.h> NMEACompatibleGPS::NMEACompatibleGPS(string devicePath, uint baudRate) :serialPort(devicePath, baudRate), //serialPort("/dev/ttyGPS", 19200/*For HemisphereA100 4800*/), LonNewSerialLine(this), stateQueue() { serialPort.onNewLine += &LonNewSerialLine; maxBufferLength = 10; serialPort.startEvents(); if(serialPort.isConnected()) Logger::Log(LogLevel::Info, "GPS Initialized"); else Logger::Log(LogLevel::Error, "GPS failed to initialize"); } void NMEACompatibleGPS::onNewSerialLine(string line) { GPSData state; if(parseLine(line, state)) { // TODO set time // gettimeofday(&state.laptoptime, NULL); boost::mutex::scoped_lock lock(queueLocker); stateQueue.push_back(state); if(stateQueue.size() > maxBufferLength) { stateQueue.pop_front(); } onNewData(state); } } bool NMEACompatibleGPS::parseLine(std::string line, GPSData &state) { return nmea::decodeGPGGA(line, state) || nmea::decodeGPRMC(line, state); } GPSData NMEACompatibleGPS::GetState() { boost::mutex::scoped_lock lock(queueLocker); GPSData state = stateQueue.back(); stateQueue.remove(state); return state; } GPSData NMEACompatibleGPS::GetStateAtTime(timeval time) { boost::mutex::scoped_lock lock(queueLocker); std::list<GPSData>::iterator iter = stateQueue.begin(); //double acceptableError = 0.1; while(iter != stateQueue.end()) { GPSData s = (*iter); /*time_t secDelta = difftime(time.tv_sec, s.laptoptime.tv_sec); suseconds_t usecDelta = time.tv_usec - s.laptoptime.tv_usec; double delta = double(secDelta) + 1e-6*double(usecDelta); if(delta <= acceptableError) { // iter = stateQueue.erase(iter); return s; } else { iter++; }*/ } GPSData empty; return empty; } bool NMEACompatibleGPS::StateIsAvailable() { return !stateQueue.empty(); } bool NMEACompatibleGPS::isOpen() { return serialPort.isConnected(); } NMEACompatibleGPS::~NMEACompatibleGPS() { serialPort.stopEvents(); serialPort.close(); } <|endoftext|>
<commit_before>/* notify.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 30 Nov 2013 FreeBSD-style copyright and disclaimer apply Notify implementation */ #include "notify.h" #include "utils.h" #include <unistd.h> #include <sys/eventfd.h> namespace slick { /******************************************************************************/ /* NOTIFY */ /******************************************************************************/ Notify:: Notify() { fd_ = eventfd(0, EFD_NONBLOCK); SLICK_CHECK_ERRNO(fd_ >= 0, "Notify.eventfd"); } Notify:: ~Notify() { close(fd_); } bool Notify:: poll() { eventfd_t val; int ret = read(fd_, &val, sizeof val); if (ret < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) return false; SLICK_CHECK_ERRNO(!ret, "Notify.read"); return true; } void Notify:: signal() { eventfd_t val = 1; int ret = eventfd_write(fd_, val); SLICK_CHECK_ERRNO(!ret, "Notify.write"); } } // slick <commit_msg>Notify now properly handles its error codes.<commit_after>/* notify.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 30 Nov 2013 FreeBSD-style copyright and disclaimer apply Notify implementation */ #include "notify.h" #include "utils.h" #include <cassert> #include <unistd.h> #include <sys/eventfd.h> namespace slick { /******************************************************************************/ /* NOTIFY */ /******************************************************************************/ Notify:: Notify() { fd_ = eventfd(0, EFD_NONBLOCK); SLICK_CHECK_ERRNO(fd_ >= 0, "Notify.eventfd"); } Notify:: ~Notify() { close(fd_); } bool Notify:: poll() { eventfd_t val; while (true) { ssize_t ret = read(fd_, &val, sizeof val); if (ret >= 0) return true; if (errno == EINTR) continue; if (errno == EAGAIN || errno == EWOULDBLOCK) return false; SLICK_CHECK_ERRNO(!ret, "Notify.read"); } assert(false); return false; } void Notify:: signal() { eventfd_t val = 1; int ret = eventfd_write(fd_, val); SLICK_CHECK_ERRNO(!ret, "Notify.write"); } } // slick <|endoftext|>
<commit_before>#pragma once #include <roerei/dataset.hpp> #include <roerei/math.hpp> #include <algorithm> #include <list> #include <map> #include <set> #include <iostream> namespace roerei { class performance { private: performance() = delete; public: struct metrics_t { float oocover, ooprecision, recall, rank, auc; size_t n; metrics_t() : oocover(1.0f) , ooprecision(1.0f) , recall(std::numeric_limits<float>::max()) , rank(std::numeric_limits<float>::max()) , auc(0.0f) , n(0) {} metrics_t(float _oocover, float _ooprecision, float _recall, float _rank, float _auc) : oocover(_oocover) , ooprecision(_ooprecision) , recall(_recall) , rank(_rank) , auc(_auc) , n(1) {} metrics_t(float _oocover, float _ooprecision, float _recall, float _rank, float _auc, size_t _n) : oocover(_oocover) , ooprecision(_ooprecision) , recall(_recall) , rank(_rank) , auc(_auc) , n(_n) {} metrics_t operator+(metrics_t const& rhs) const { if(n == 0) return rhs; else if(rhs.n == 0) return *this; float total = n + rhs.n; float nr_f = (float)n / total; float rhs_nr_f = (float)rhs.n / total; return { oocover * nr_f + rhs.oocover * rhs_nr_f, ooprecision * nr_f + rhs.ooprecision * rhs_nr_f, recall * nr_f + rhs.recall * rhs_nr_f, rank * nr_f + rhs.rank * rhs_nr_f, auc * nr_f + rhs.auc * rhs_nr_f, total }; } metrics_t& operator+=(metrics_t const& rhs) { *this = operator+(rhs); return *this; } }; struct result_t { metrics_t metrics; std::vector<std::pair<size_t, float>> predictions; std::vector<std::pair<size_t, float>> suggestions_sorted; std::set<size_t> required_deps, oosuggested_deps, oofound_deps, missing_deps; }; template<typename ML, typename ROW> static result_t measure(dataset_t const& d, ML const& ml, ROW const& test_row) { std::map<size_t, float> suggestions; // <id, weighted freq> auto predictions(ml.predict(test_row)); std::reverse(predictions.begin(), predictions.end()); for(auto const& kvp : predictions) { float weight = 1.0f / (kvp.second + 1.0f); // "Similarity", higher is more similar for(auto dep_kvp : d.dependency_matrix[kvp.first]) suggestions[dep_kvp.first] += ((float)dep_kvp.second) * weight; } std::vector<std::pair<size_t, float>> suggestions_sorted; for(auto const& kvp : suggestions) suggestions_sorted.emplace_back(kvp); std::sort(suggestions_sorted.begin(), suggestions_sorted.end(), [&](std::pair<size_t, float> const& x, std::pair<size_t, float> const& y) { return x.second > y.second; }); std::map<size_t, size_t> suggestions_ranks; for(size_t j = 0; j < suggestions_sorted.size() && j < 100; ++j) suggestions_ranks[suggestions_sorted[j].first] = j; std::set<size_t> required_deps, suggested_deps, oosuggested_deps, found_deps, oofound_deps, missing_deps, irrelevant_deps; for(auto const& kvp : d.dependency_matrix[test_row.row_i]) required_deps.insert(kvp.first); for(size_t j = 0; j < suggestions_sorted.size() && j < 100; ++j) oosuggested_deps.insert(suggestions_sorted[j].first); for(size_t j = 0; j < suggestions_sorted.size(); ++j) suggested_deps.insert(suggestions_sorted[j].first); std::set_intersection( required_deps.begin(), required_deps.end(), oosuggested_deps.begin(), oosuggested_deps.end(), std::inserter(oofound_deps, oofound_deps.begin()) ); std::set_intersection( required_deps.begin(), required_deps.end(), suggested_deps.begin(), suggested_deps.end(), std::inserter(found_deps, found_deps.begin()) ); std::set_difference( required_deps.begin(), required_deps.end(), found_deps.begin(), found_deps.end(), std::inserter(missing_deps, missing_deps.begin()) ); std::set_difference( suggested_deps.begin(), suggested_deps.end(), found_deps.begin(), found_deps.end(), std::inserter(irrelevant_deps, irrelevant_deps.begin()) ); float c_required = required_deps.size(); float c_found = found_deps.size(); float c_suggested = suggested_deps.size(); float c_irrelevant = irrelevant_deps.size(); float c_oosuggested = oosuggested_deps.size(); float c_oofound = oofound_deps.size(); float oocover = c_oofound/c_required; float ooprecision = c_oofound/c_oosuggested; float recall = c_suggested + 1.0f; float rank = 0.0f; float auc = 0.0f; if(c_oofound == 0.0f) ooprecision = 0.0f; if(c_required == 0.0f) { oocover = 1.0f; ooprecision = 1.0f; } if(missing_deps.empty()) { std::set<size_t> todo_deps(required_deps); // Copy size_t j = 0; for(; j < suggestions_sorted.size() && !todo_deps.empty(); ++j) if(todo_deps.erase(suggestions_sorted[j].first) > 0) rank += j; recall = j; rank /= c_found; } if(c_found == 0) rank = c_suggested + 1.0f; for(size_t found_dep : found_deps) for(size_t irrelevant_dep : irrelevant_deps) if(suggestions_ranks[found_dep] > suggestions_ranks[irrelevant_dep]) auc += 1.0f; if(c_found * c_irrelevant != 0) auc /= c_found * c_irrelevant; else if(c_irrelevant == 0) auc = 1.0f; else auc = 0.0f; return { { oocover, ooprecision, recall, rank, auc }, std::move(predictions), std::move(suggestions_sorted), std::move(required_deps), std::move(oosuggested_deps), std::move(oofound_deps), std::move(missing_deps) }; } }; } namespace std { std::ostream& operator<<(std::ostream& os, roerei::performance::metrics_t const& rhs) { os << "100Cover " << roerei::fill(roerei::round(rhs.oocover, 3), 5) << " + " << "100Precision " << roerei::fill(roerei::round(rhs.ooprecision, 3), 5) << " + " << "FullRecall " << roerei::fill(roerei::round(rhs.recall, 1), 4) << " + " << "Rank " << roerei::fill(roerei::round(rhs.rank, 1), 4) << " + " << "AUC " << roerei::fill(roerei::round(rhs.auc, 3), 5); return os; } } <commit_msg>Moved recall, rank, AUC to separate functions in performance<commit_after>#pragma once #include <roerei/dataset.hpp> #include <roerei/math.hpp> #include <algorithm> #include <list> #include <map> #include <set> #include <iostream> namespace roerei { class performance { private: performance() = delete; public: struct metrics_t { float oocover, ooprecision, recall, rank, auc; size_t n; metrics_t() : oocover(1.0f) , ooprecision(1.0f) , recall(std::numeric_limits<float>::max()) , rank(std::numeric_limits<float>::max()) , auc(0.0f) , n(0) {} metrics_t(float _oocover, float _ooprecision, float _recall, float _rank, float _auc) : oocover(_oocover) , ooprecision(_ooprecision) , recall(_recall) , rank(_rank) , auc(_auc) , n(1) {} metrics_t(float _oocover, float _ooprecision, float _recall, float _rank, float _auc, size_t _n) : oocover(_oocover) , ooprecision(_ooprecision) , recall(_recall) , rank(_rank) , auc(_auc) , n(_n) {} metrics_t operator+(metrics_t const& rhs) const { if(n == 0) return rhs; else if(rhs.n == 0) return *this; float total = n + rhs.n; float nr_f = (float)n / total; float rhs_nr_f = (float)rhs.n / total; return { oocover * nr_f + rhs.oocover * rhs_nr_f, ooprecision * nr_f + rhs.ooprecision * rhs_nr_f, recall * nr_f + rhs.recall * rhs_nr_f, rank * nr_f + rhs.rank * rhs_nr_f, auc * nr_f + rhs.auc * rhs_nr_f, total }; } metrics_t& operator+=(metrics_t const& rhs) { *this = operator+(rhs); return *this; } }; struct result_t { metrics_t metrics; std::vector<std::pair<size_t, float>> predictions; std::vector<std::pair<size_t, float>> suggestions_sorted; std::set<size_t> required_deps, oosuggested_deps, oofound_deps, missing_deps; }; static std::pair<float, float> compute_recall_rank(float const c_found, float const c_suggested, std::set<size_t> const& required_deps, std::vector<std::pair<size_t, float>> const& suggestions_sorted) { float recall = suggestions_sorted.size() + 1.0f; float rank = 0.0f; if(required_deps.size() == c_found) { std::set<size_t> todo_deps(required_deps); // Copy size_t j = 0; for(; j < suggestions_sorted.size() && !todo_deps.empty(); ++j) if(todo_deps.erase(suggestions_sorted.at(j).first) > 0) rank += j; recall = j; rank /= c_found; } if(c_found == 0) rank = c_suggested + 1.0f; return std::make_pair(recall, rank); } static float compute_auc(std::set<size_t> const& found_deps, std::set<size_t> const& irrelevant_deps, std::map<size_t, size_t> const& suggestions_ranks) { auto sr_f([&](size_t i) { return suggestions_ranks.find(i)->second; }); // Cannot be std::map::end if(irrelevant_deps.empty()) return 1.0f; if(found_deps.empty()) return 0.0f; std::vector<size_t> found_ranks, irrelevant_ranks; found_ranks.reserve(found_deps.size()); for(size_t i : found_deps) found_ranks.emplace_back(sr_f(i)); irrelevant_ranks.reserve(irrelevant_deps.size()); for(size_t j : irrelevant_deps) irrelevant_ranks.emplace_back(sr_f(j)); float auc_sum = 0.0f; for(size_t x : found_ranks) for(size_t y : irrelevant_ranks) if(x < y) // Lower rank is 'better' auc_sum += 1.0f; return auc_sum / (float)(found_deps.size() * irrelevant_deps.size()); } template<typename ML, typename ROW> static result_t measure(dataset_t const& d, ML const& ml, ROW const& test_row) { std::map<size_t, float> suggestions; // <id, weighted freq> auto predictions(ml.predict(test_row)); std::reverse(predictions.begin(), predictions.end()); for(auto const& kvp : predictions) { float weight = 1.0f / (kvp.second + 1.0f); // "Similarity", higher is more similar for(auto dep_kvp : d.dependency_matrix[kvp.first]) suggestions[dep_kvp.first] += ((float)dep_kvp.second) * weight; } std::vector<std::pair<size_t, float>> suggestions_sorted; for(auto const& kvp : suggestions) suggestions_sorted.emplace_back(kvp); std::sort(suggestions_sorted.begin(), suggestions_sorted.end(), [&](std::pair<size_t, float> const& x, std::pair<size_t, float> const& y) { return x.second > y.second; }); std::map<size_t, size_t> suggestions_ranks; for(size_t j = 0; j < suggestions_sorted.size() && j < 100; ++j) suggestions_ranks[suggestions_sorted[j].first] = j; std::set<size_t> required_deps, suggested_deps, oosuggested_deps, found_deps, oofound_deps, missing_deps, irrelevant_deps; for(auto const& kvp : d.dependency_matrix[test_row.row_i]) required_deps.insert(kvp.first); for(size_t j = 0; j < suggestions_sorted.size() && j < 100; ++j) oosuggested_deps.insert(suggestions_sorted[j].first); for(size_t j = 0; j < suggestions_sorted.size(); ++j) suggested_deps.insert(suggestions_sorted[j].first); std::set_intersection( required_deps.begin(), required_deps.end(), oosuggested_deps.begin(), oosuggested_deps.end(), std::inserter(oofound_deps, oofound_deps.begin()) ); std::set_intersection( required_deps.begin(), required_deps.end(), suggested_deps.begin(), suggested_deps.end(), std::inserter(found_deps, found_deps.begin()) ); std::set_difference( required_deps.begin(), required_deps.end(), found_deps.begin(), found_deps.end(), std::inserter(missing_deps, missing_deps.begin()) ); std::set_difference( suggested_deps.begin(), suggested_deps.end(), found_deps.begin(), found_deps.end(), std::inserter(irrelevant_deps, irrelevant_deps.begin()) ); float c_required = required_deps.size(); float c_found = found_deps.size(); float c_suggested = suggested_deps.size(); float c_oosuggested = oosuggested_deps.size(); float c_oofound = oofound_deps.size(); float oocover = c_oofound/c_required; float ooprecision = c_oofound/c_oosuggested; if(c_oofound == 0.0f) ooprecision = 0.0f; if(c_required == 0.0f) { oocover = 1.0f; ooprecision = 1.0f; } auto recall_rank_kvp(compute_recall_rank(c_found, c_suggested, required_deps, suggestions_sorted)); return { { oocover, ooprecision, recall_rank_kvp.first, recall_rank_kvp.second, compute_auc(found_deps, irrelevant_deps, suggestions_ranks) }, std::move(predictions), std::move(suggestions_sorted), std::move(required_deps), std::move(oosuggested_deps), std::move(oofound_deps), std::move(missing_deps) }; } }; } namespace std { std::ostream& operator<<(std::ostream& os, roerei::performance::metrics_t const& rhs) { os << "100Cover " << roerei::fill(roerei::round(rhs.oocover, 3), 5) << " + " << "100Precision " << roerei::fill(roerei::round(rhs.ooprecision, 3), 5) << " + " << "FullRecall " << roerei::fill(roerei::round(rhs.recall, 1), 4) << " + " << "Rank " << roerei::fill(roerei::round(rhs.rank, 1), 4) << " + " << "AUC " << roerei::fill(roerei::round(rhs.auc, 3), 5); return os; } } <|endoftext|>
<commit_before>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <qitype/genericobject.hpp> #include "object_p.hpp" namespace qi { GenericObject::GenericObject(ObjectType *type, void *value) : type(type) , value(value) { } GenericObject::~GenericObject() { } Manageable::Manageable() { _p = new ManageablePrivate(); _p->eventLoop = getDefaultObjectEventLoop(); _p->dying = false; } Manageable::Manageable(const Manageable& b) { _p = new ManageablePrivate(); _p->eventLoop = b._p->eventLoop; _p->dying = false; } void Manageable::operator = (const Manageable& b) { this->~Manageable(); _p = new ManageablePrivate(); _p->eventLoop = b._p->eventLoop; _p->dying = false; } Manageable::~Manageable() { _p->dying = true; std::vector<SignalSubscriber> copy; { boost::mutex::scoped_lock sl(_p->registrationsMutex); copy = _p->registrations; } for (unsigned i = 0; i < copy.size(); ++i) { copy[i].source->disconnect(copy[i].linkId); } delete _p; } void Manageable::moveToEventLoop(EventLoop* el) { _p->eventLoop = el; } EventLoop* Manageable::eventLoop() const { return _p->eventLoop; } const MetaObject &GenericObject::metaObject() { if (!type || !value) { static qi::MetaObject fail; qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return fail; } return type->metaObject(value); } qi::Future<GenericValuePtr> GenericObject::metaCall(unsigned int method, const GenericFunctionParameters& params, MetaCallType callType) { qi::Promise<GenericValuePtr> out; if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; out.setError("Invalid object"); return out.future(); } try { return type->metaCall(value, method, params, callType); } catch (std::runtime_error &e) { out.setError(e.what()); return out.future(); } } void GenericObject::metaPost(unsigned int event, const GenericFunctionParameters& args) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return; } type->metaPost(value, event, args); } static qi::Future<GenericValuePtr> generateError(qi::Promise<GenericValuePtr> *out, const std::string &type, const std::string &signature, const std::vector<qi::MetaMethod> &candidates) { std::stringstream ss; std::vector<qi::MetaMethod>::const_iterator it; ss << "Can't find " << type << ": " << signature << std::endl << " Candidate(s):" << std::endl; for (it = candidates.begin(); it != candidates.end(); ++it) { const qi::MetaMethod &mm = *it; ss << " " << mm.signature() << std::endl; } qiLogError("object") << ss.str(); out->setError(ss.str()); return out->future(); } qi::Future<GenericValuePtr> GenericObject::metaCall(const std::string &signature, const GenericFunctionParameters& args, MetaCallType callType) { qi::Promise<GenericValuePtr> out; if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; out.setError("Invalid object"); return out.future(); } const GenericFunctionParameters* newArgs = 0; int methodId = metaObject().methodId(signature); #ifndef QI_REQUIRE_SIGNATURE_EXACT_MATCH if (methodId < 0) { // Try to find an other method with compatible signature // For this, first get a signature that resolves dynamic std::string resolvedSig = "("; for (unsigned i=0; i<args.size(); ++i) resolvedSig += args[i].signature(true); resolvedSig = resolvedSig + ')'; std::string fullSig = qi::signatureSplit(signature)[1] + "::" + resolvedSig; qiLogDebug("qi.object") << "Finding method for resolved signature " << fullSig; std::vector<qi::MetaMethod> mml = metaObject().findCompatibleMethod(fullSig); if (mml.size() > 1) { return generateError(&out, "overload", signature, mml); } if (mml.size() == 1) { qiLogVerbose("qi.object") << "Signature mismatch, but found compatible type " << mml[0].signature() <<" for " << signature; methodId = mml[0].uid(); qi::Signature s(qi::signatureSplit(mml[0].signature())[2]); // Signature is wrapped in a tuple, unwrap newArgs = new GenericFunctionParameters(args.convert(s.begin().children())); } } #endif if (methodId < 0) { return generateError(&out, "method", signature, metaObject().findMethod(qi::signatureSplit(signature)[1])); } //TODO: check for metacall to return false when not able to send the answer if (newArgs) { qi::Future<GenericValuePtr> res = metaCall(methodId, *newArgs, callType); delete newArgs; return res; } else return metaCall(methodId, args, callType); } /// Resolve signature and bounce bool GenericObject::xMetaPost(const std::string &signature, const GenericFunctionParameters &in) { if (!value || !type) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return false; } int eventId = metaObject().signalId(signature); if (eventId < 0) eventId = metaObject().methodId(signature); if (eventId < 0) { std::stringstream ss; ss << "Can't find event: " << signature << std::endl << " Candidate(s):" << std::endl; std::vector<MetaSignal> mml = metaObject().findSignal(qi::signatureSplit(signature)[1]); std::vector<MetaSignal>::const_iterator it; for (it = mml.begin(); it != mml.end(); ++it) { ss << " " << it->signature() << std::endl; } qiLogError("object") << ss.str(); return false; } metaPost(eventId, in); return true; } /// Resolve signature and bounce qi::FutureSync<unsigned int> GenericObject::xConnect(const std::string &signature, const SignalSubscriber& functor) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return qi::makeFutureError<unsigned int>("Operating on invalid GenericObject.."); } int eventId = metaObject().signalId(signature); #ifndef QI_REQUIRE_SIGNATURE_EXACT_MATCH if (eventId < 0) { // Try to find an other event with compatible signature std::vector<qi::MetaSignal> mml = metaObject().findSignal(qi::signatureSplit(signature)[1]); Signature sargs(signatureSplit(signature)[2]); for (unsigned i = 0; i < mml.size(); ++i) { Signature s(signatureSplit(mml[i].signature())[2]); qiLogDebug("qi.object") << "Checking compatibility " << s.toString() << ' ' << sargs.toString(); // Order is reversed from method call check. if (s.isConvertibleTo(sargs)) { qiLogVerbose("qi.object") << "Signature mismatch, but found compatible type " << mml[i].signature() <<" for " << signature; eventId = mml[i].uid(); break; } } } #endif if (eventId < 0) { std::stringstream ss; ss << "Can't find event: " << signature << std::endl << " Candidate(s):" << std::endl; std::vector<MetaSignal> mml = metaObject().findSignal(qi::signatureSplit(signature)[1]); std::vector<MetaSignal>::const_iterator it; for (it = mml.begin(); it != mml.end(); ++it) { ss << " " << it->signature() << std::endl; } qiLogError("object") << ss.str(); return qi::makeFutureError<unsigned int>(ss.str()); } return connect(eventId, functor); } qi::FutureSync<unsigned int> GenericObject::connect(unsigned int event, const SignalSubscriber& sub) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return qi::makeFutureError<unsigned int>("Operating on invalid GenericObject.."); } return type->connect(value, event, sub); } qi::FutureSync<void> GenericObject::disconnect(unsigned int linkId) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return qi::makeFutureError<void>("Operating on invalid GenericObject"); } return type->disconnect(value, linkId); } qi::FutureSync<unsigned int> GenericObject::connect(unsigned int signal, ObjectPtr target, unsigned int slot) { return connect(signal, SignalSubscriber(target, slot)); } /* std::vector<SignalSubscriber> GenericObject::subscribers(int eventId) const { std::vector<SignalSubscriber> res; if (!_p) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return res; } return _p->subscribers(eventId); }*/ void GenericObject::emitEvent(const std::string& eventName, qi::AutoGenericValuePtr p1, qi::AutoGenericValuePtr p2, qi::AutoGenericValuePtr p3, qi::AutoGenericValuePtr p4, qi::AutoGenericValuePtr p5, qi::AutoGenericValuePtr p6, qi::AutoGenericValuePtr p7, qi::AutoGenericValuePtr p8) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return; } qi::AutoGenericValuePtr* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::GenericValuePtr> params; for (unsigned i=0; i<8; ++i) if (vals[i]->value) params.push_back(*vals[i]); // Signature construction std::string signature = eventName + "::("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; xMetaPost(signature, GenericFunctionParameters(params)); } int ObjectType::inherits(Type* other) { /* A registered class C can have to Type* around: * - TypeImpl<C*> * - The staticObjectType that was created by the builder. * So assume that any of them can be in the parentTypes list. */ if (this == other) return 0; const std::vector<std::pair<Type*, int> >& parents = parentTypes(); qiLogDebug("qi.meta") << infoString() <<" has " << parents.size() <<" parents"; for (unsigned i=0; i<parents.size(); ++i) { if (parents[i].first->info() == other->info()) return parents[i].second; ObjectType* op = dynamic_cast<ObjectType*>(parents[i].first); if (op) { int offset = op->inherits(other); if (offset != -1) { qiLogDebug("qi.meta") << "Inheritance offsets " << parents[i].second << " " << offset; return parents[i].second + offset; } } qiLogDebug("qi.meta") << parents[i].first->infoString() << " does not match " << other->infoString() <<" " << ((bool)op == (bool)dynamic_cast<ObjectType*>(other)); } return -1; } } <commit_msg>emitEvent: Fix bug when last argument is int 0.<commit_after>/* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #include <iostream> #include <qitype/genericobject.hpp> #include "object_p.hpp" namespace qi { GenericObject::GenericObject(ObjectType *type, void *value) : type(type) , value(value) { } GenericObject::~GenericObject() { } Manageable::Manageable() { _p = new ManageablePrivate(); _p->eventLoop = getDefaultObjectEventLoop(); _p->dying = false; } Manageable::Manageable(const Manageable& b) { _p = new ManageablePrivate(); _p->eventLoop = b._p->eventLoop; _p->dying = false; } void Manageable::operator = (const Manageable& b) { this->~Manageable(); _p = new ManageablePrivate(); _p->eventLoop = b._p->eventLoop; _p->dying = false; } Manageable::~Manageable() { _p->dying = true; std::vector<SignalSubscriber> copy; { boost::mutex::scoped_lock sl(_p->registrationsMutex); copy = _p->registrations; } for (unsigned i = 0; i < copy.size(); ++i) { copy[i].source->disconnect(copy[i].linkId); } delete _p; } void Manageable::moveToEventLoop(EventLoop* el) { _p->eventLoop = el; } EventLoop* Manageable::eventLoop() const { return _p->eventLoop; } const MetaObject &GenericObject::metaObject() { if (!type || !value) { static qi::MetaObject fail; qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return fail; } return type->metaObject(value); } qi::Future<GenericValuePtr> GenericObject::metaCall(unsigned int method, const GenericFunctionParameters& params, MetaCallType callType) { qi::Promise<GenericValuePtr> out; if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; out.setError("Invalid object"); return out.future(); } try { return type->metaCall(value, method, params, callType); } catch (std::runtime_error &e) { out.setError(e.what()); return out.future(); } } void GenericObject::metaPost(unsigned int event, const GenericFunctionParameters& args) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return; } type->metaPost(value, event, args); } static qi::Future<GenericValuePtr> generateError(qi::Promise<GenericValuePtr> *out, const std::string &type, const std::string &signature, const std::vector<qi::MetaMethod> &candidates) { std::stringstream ss; std::vector<qi::MetaMethod>::const_iterator it; ss << "Can't find " << type << ": " << signature << std::endl << " Candidate(s):" << std::endl; for (it = candidates.begin(); it != candidates.end(); ++it) { const qi::MetaMethod &mm = *it; ss << " " << mm.signature() << std::endl; } qiLogError("object") << ss.str(); out->setError(ss.str()); return out->future(); } qi::Future<GenericValuePtr> GenericObject::metaCall(const std::string &signature, const GenericFunctionParameters& args, MetaCallType callType) { qi::Promise<GenericValuePtr> out; if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; out.setError("Invalid object"); return out.future(); } const GenericFunctionParameters* newArgs = 0; int methodId = metaObject().methodId(signature); #ifndef QI_REQUIRE_SIGNATURE_EXACT_MATCH if (methodId < 0) { // Try to find an other method with compatible signature // For this, first get a signature that resolves dynamic std::string resolvedSig = "("; for (unsigned i=0; i<args.size(); ++i) resolvedSig += args[i].signature(true); resolvedSig = resolvedSig + ')'; std::string fullSig = qi::signatureSplit(signature)[1] + "::" + resolvedSig; qiLogDebug("qi.object") << "Finding method for resolved signature " << fullSig; std::vector<qi::MetaMethod> mml = metaObject().findCompatibleMethod(fullSig); if (mml.size() > 1) { return generateError(&out, "overload", signature, mml); } if (mml.size() == 1) { qiLogVerbose("qi.object") << "Signature mismatch, but found compatible type " << mml[0].signature() <<" for " << signature; methodId = mml[0].uid(); qi::Signature s(qi::signatureSplit(mml[0].signature())[2]); // Signature is wrapped in a tuple, unwrap newArgs = new GenericFunctionParameters(args.convert(s.begin().children())); } } #endif if (methodId < 0) { return generateError(&out, "method", signature, metaObject().findMethod(qi::signatureSplit(signature)[1])); } //TODO: check for metacall to return false when not able to send the answer if (newArgs) { qi::Future<GenericValuePtr> res = metaCall(methodId, *newArgs, callType); delete newArgs; return res; } else return metaCall(methodId, args, callType); } /// Resolve signature and bounce bool GenericObject::xMetaPost(const std::string &signature, const GenericFunctionParameters &in) { if (!value || !type) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return false; } int eventId = metaObject().signalId(signature); if (eventId < 0) eventId = metaObject().methodId(signature); if (eventId < 0) { std::stringstream ss; ss << "Can't find event: " << signature << std::endl << " Candidate(s):" << std::endl; std::vector<MetaSignal> mml = metaObject().findSignal(qi::signatureSplit(signature)[1]); std::vector<MetaSignal>::const_iterator it; for (it = mml.begin(); it != mml.end(); ++it) { ss << " " << it->signature() << std::endl; } qiLogError("object") << ss.str(); return false; } metaPost(eventId, in); return true; } /// Resolve signature and bounce qi::FutureSync<unsigned int> GenericObject::xConnect(const std::string &signature, const SignalSubscriber& functor) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return qi::makeFutureError<unsigned int>("Operating on invalid GenericObject.."); } int eventId = metaObject().signalId(signature); #ifndef QI_REQUIRE_SIGNATURE_EXACT_MATCH if (eventId < 0) { // Try to find an other event with compatible signature std::vector<qi::MetaSignal> mml = metaObject().findSignal(qi::signatureSplit(signature)[1]); Signature sargs(signatureSplit(signature)[2]); for (unsigned i = 0; i < mml.size(); ++i) { Signature s(signatureSplit(mml[i].signature())[2]); qiLogDebug("qi.object") << "Checking compatibility " << s.toString() << ' ' << sargs.toString(); // Order is reversed from method call check. if (s.isConvertibleTo(sargs)) { qiLogVerbose("qi.object") << "Signature mismatch, but found compatible type " << mml[i].signature() <<" for " << signature; eventId = mml[i].uid(); break; } } } #endif if (eventId < 0) { std::stringstream ss; ss << "Can't find event: " << signature << std::endl << " Candidate(s):" << std::endl; std::vector<MetaSignal> mml = metaObject().findSignal(qi::signatureSplit(signature)[1]); std::vector<MetaSignal>::const_iterator it; for (it = mml.begin(); it != mml.end(); ++it) { ss << " " << it->signature() << std::endl; } qiLogError("object") << ss.str(); return qi::makeFutureError<unsigned int>(ss.str()); } return connect(eventId, functor); } qi::FutureSync<unsigned int> GenericObject::connect(unsigned int event, const SignalSubscriber& sub) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return qi::makeFutureError<unsigned int>("Operating on invalid GenericObject.."); } return type->connect(value, event, sub); } qi::FutureSync<void> GenericObject::disconnect(unsigned int linkId) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return qi::makeFutureError<void>("Operating on invalid GenericObject"); } return type->disconnect(value, linkId); } qi::FutureSync<unsigned int> GenericObject::connect(unsigned int signal, ObjectPtr target, unsigned int slot) { return connect(signal, SignalSubscriber(target, slot)); } /* std::vector<SignalSubscriber> GenericObject::subscribers(int eventId) const { std::vector<SignalSubscriber> res; if (!_p) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return res; } return _p->subscribers(eventId); }*/ void GenericObject::emitEvent(const std::string& eventName, qi::AutoGenericValuePtr p1, qi::AutoGenericValuePtr p2, qi::AutoGenericValuePtr p3, qi::AutoGenericValuePtr p4, qi::AutoGenericValuePtr p5, qi::AutoGenericValuePtr p6, qi::AutoGenericValuePtr p7, qi::AutoGenericValuePtr p8) { if (!type || !value) { qiLogWarning("qi.object") << "Operating on invalid GenericObject.."; return; } qi::AutoGenericValuePtr* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::GenericValuePtr> params; for (unsigned i=0; i<8; ++i) if (vals[i]->type) params.push_back(*vals[i]); // Signature construction std::string signature = eventName + "::("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; xMetaPost(signature, GenericFunctionParameters(params)); } int ObjectType::inherits(Type* other) { /* A registered class C can have to Type* around: * - TypeImpl<C*> * - The staticObjectType that was created by the builder. * So assume that any of them can be in the parentTypes list. */ if (this == other) return 0; const std::vector<std::pair<Type*, int> >& parents = parentTypes(); qiLogDebug("qi.meta") << infoString() <<" has " << parents.size() <<" parents"; for (unsigned i=0; i<parents.size(); ++i) { if (parents[i].first->info() == other->info()) return parents[i].second; ObjectType* op = dynamic_cast<ObjectType*>(parents[i].first); if (op) { int offset = op->inherits(other); if (offset != -1) { qiLogDebug("qi.meta") << "Inheritance offsets " << parents[i].second << " " << offset; return parents[i].second + offset; } } qiLogDebug("qi.meta") << parents[i].first->infoString() << " does not match " << other->infoString() <<" " << ((bool)op == (bool)dynamic_cast<ObjectType*>(other)); } return -1; } } <|endoftext|>
<commit_before>/** * ofxCsv.cpp * Inspired and based on Ben Fry's [table class](http://benfry.com/writing/map/Table.pde) * * The MIT License * * Copyright (c) 2011-2014 Paul Vollmer, http://www.wng.cc * * 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. * * * @modified 2015.04.21 * @version 0.2.0 */ #include "ofxCsv.h" #include "ofLog.h" #include "ofUtils.h" #include "ofFileUtils.h" //-------------------------------------------------- ofxCsv::ofxCsv() { fieldSeparator = ","; commentPrefix = "#"; quoteFields = false; } //-------------------------------------------------- bool ofxCsv::load(string path, string separator, string comment) { clear(); if(path == "") { path = filePath; } else { filePath = path; } fieldSeparator = separator; commentPrefix = comment; // verbose log print ofLogVerbose("ofxCsv") << "Loading " << filePath; ofLogVerbose("ofxCsv") << " fieldSeparator: " << fieldSeparator; ofLogVerbose("ofxCsv") << " commentPrefix: " << commentPrefix; // open file & read each line int lineCount = 0; int maxCols = 0; ofBuffer buffer = ofBufferFromFile(ofToDataPath(path)); for(auto line : buffer.getLines()) { // skip empty lines if(line.empty()) { ofLogVerbose("ofxCsv") << "Skipping empty line: " << lineCount; lineCount++; continue; } // skip comment lines // TODO: only checks substring at line beginning, does not ignore whitespace if(line.substr(0, commentPrefix.length()) == commentPrefix) { ofLogVerbose("ofxCsv") << "Skipping comment line: " << lineCount; lineCount++; continue; } // split line into separate files vector<string> cols = fromRowString(line, separator); data.push_back(cols); // calc maxium table cols if(cols.size() > maxCols) { maxCols = cols.size(); } lineCount++; } buffer.clear(); // expand to fill in any missing cols, just in case expand(data.size(), maxCols); ofLogVerbose("ofxCsv") << "Read " << lineCount << " lines"; ofLogVerbose("ofxCsv") << "Loaded a " << data.size() << "x" << maxCols << " table"; return true; } //-------------------------------------------------- bool ofxCsv::load(string path, string separator) { return load(path, separator, commentPrefix); } //-------------------------------------------------- bool ofxCsv::load(string path) { return load(path, fieldSeparator); } //-------------------------------------------------- bool ofxCsv::save(string path, bool quote, string separator) { if(path == "") { path = filePath; } else { filePath = path; } fieldSeparator = separator; quoteFields = quote; // verbose log print ofLogVerbose("ofxCsv") << "Saving " << path; ofLogVerbose("ofxCsv") << " fieldSeparator: " << fieldSeparator; ofLogVerbose("ofxCsv") << " quoteFields: " << quoteFields; if(data.empty()) { ofLogWarning("ofxCsv") << "Aborting save to " << path << ": data is empty"; return false; } // create file if needed if(!ofFile::doesFileExist(ofToDataPath(path))) { if(!createFile(path)) { ofLogError("ofxCsv") << "Could not save to " << path << ": couldn't create"; return false; } } // fill buffer & write to file ofBuffer buffer; int lineCount = 0; for(auto row : data) { buffer.append(toRowString(row, fieldSeparator, quote)+"\n"); lineCount++; } if(!ofBufferToFile(path, buffer)) { ofLogError("ofxCsv") << "Could not save to " << path << ": couldn't save buffer"; return false; } buffer.clear(); ofLogVerbose("ofxCsv") << "Wrote " << lineCount << " lines to " << path; return true; } //-------------------------------------------------- bool ofxCsv::save(string path, bool quote) { return save(path, quote, fieldSeparator); } //-------------------------------------------------- bool ofxCsv::save(string path) { return save(path, false, fieldSeparator); } //-------------------------------------------------- bool ofxCsv::createFile(string path) { ofLogVerbose("ofxCsv") << "Creating " << path; ofFile file(ofToDataPath(path), ofFile::WriteOnly, false); return file.create(); } /// DATA IO //-------------------------------------------------- void ofxCsv::load(vector<ofxCsvRow> &rows) { clear(); data = rows; } //-------------------------------------------------- void ofxCsv::load(vector<vector<string>> &rows) { clear(); for(auto row : rows) { data.push_back(ofxCsvRow(row)); } } //-------------------------------------------------- void ofxCsv::add(ofxCsvRow &row) { data.push_back(row); } //-------------------------------------------------- void ofxCsv::insert(ofxCsvRow &row, int index) { int cols = getNumCols(); if(index > data.size()) { expand(index-1, cols); } data.insert(data.begin()+index, row); data[index].expand(cols); } //-------------------------------------------------- void ofxCsv::remove(int index) { data.erase(data.begin()+index); } //-------------------------------------------------- void ofxCsv::expand(int rows, int cols) { while(data.size() < rows) { data.push_back(ofxCsvRow()); } for(auto &row : data) { row.expand(cols-1); } } //-------------------------------------------------- void ofxCsv::clear() { for(auto &row : data) { row.clear(); } data.clear(); } /// DATA ACCESS //-------------------------------------------------- unsigned int ofxCsv::getNumRows() { return data.size(); } //-------------------------------------------------- unsigned int ofxCsv::getNumCols(int row) { if(row > -1 && row < data.size()) { return data[row].size(); } ofLogWarning("ofxCsv") << "Cannot get num cols for row " << row << ": total num rows is " << data.size(); return 0; } //-------------------------------------------------- int ofxCsv::getInt(int row, int col) { expandRow(row, col); return data[row].getInt(col); } //-------------------------------------------------- float ofxCsv::getFloat(int row, int col) { expandRow(row, col); return data[row].getFloat(col); } //-------------------------------------------------- string ofxCsv::getString(int row, int col) { expandRow(row, col); return data[row].getString(col); } //-------------------------------------------------- bool ofxCsv::getBool(int row, int col) { expandRow(row, col); return data[row].getBool(col); } //-------------------------------------------------- void ofxCsv::setInt(int row, int col, int what) { expandRow(row, col); data[row].setInt(col, what); } void ofxCsv::setFloat(int row, int col, float what) { expandRow(row, col); data[row].setFloat(col, what); } //-------------------------------------------------- void ofxCsv::setString(int row, int col, string what) { expandRow(row, col); data[row].setString(col, what); } //-------------------------------------------------- void ofxCsv::setBool(int row, int col, bool what) { expandRow(row, col); data[row].setBool(col, what); } //-------------------------------------------------- void ofxCsv::print() { for(auto &row : data) { ofLogNotice("ofxCsv") << row; } } // RAW DATA ACCESS //-------------------------------------------------- vector<ofxCsvRow>::iterator ofxCsv::begin() { return data.begin(); } //-------------------------------------------------- vector<ofxCsvRow>::iterator ofxCsv::end() { return data.end(); } //-------------------------------------------------- vector<ofxCsvRow>::const_iterator ofxCsv::begin() const{ return data.begin(); } //-------------------------------------------------- vector<ofxCsvRow>::const_iterator ofxCsv::end() const{ return data.end(); } //-------------------------------------------------- vector<ofxCsvRow>::reverse_iterator ofxCsv::rbegin() { return data.rbegin(); } //-------------------------------------------------- vector<ofxCsvRow>::reverse_iterator ofxCsv::rend() { return data.rend(); } //-------------------------------------------------- vector<ofxCsvRow>::const_reverse_iterator ofxCsv::rbegin() const{ return data.rbegin(); } //-------------------------------------------------- vector<ofxCsvRow>::const_reverse_iterator ofxCsv::rend() const{ return data.rend(); } //-------------------------------------------------- ofxCsv::operator vector<ofxCsvRow>() const { return data; } //-------------------------------------------------- ofxCsvRow ofxCsv::operator[](size_t index) { return data[index]; } //-------------------------------------------------- ofxCsvRow ofxCsv::at(size_t index) { return data.at(index); } //-------------------------------------------------- ofxCsvRow ofxCsv::front() { if(data.empty()) { return ofxCsvRow(); } return data.front(); } //-------------------------------------------------- ofxCsvRow ofxCsv::back() { if(data.empty()) { return ofxCsvRow(); } return data.back(); } //-------------------------------------------------- size_t ofxCsv::size() { return data.size(); } // UTIL //-------------------------------------------------- void ofxCsv::trim() { for(int row = 0; row < data.size(); row++) { data[row].trim(); } } //-------------------------------------------------- vector<string> ofxCsv::fromRowString(string row, string separator) { return ofxCsvRow::fromString(row, separator); } //-------------------------------------------------- vector<string> ofxCsv::fromRowString(string row) { return ofxCsvRow::fromString(row, fieldSeparator); } //-------------------------------------------------- string ofxCsv::toRowString(vector<string> row, string separator, bool quote) { return ofxCsvRow::toString(row, separator, quote); } //-------------------------------------------------- string ofxCsv::toRowString(vector<string> row, string separator) { return ofxCsvRow::toString(row, separator, false); } //-------------------------------------------------- string ofxCsv::toRowString(vector<string> row) { return ofxCsvRow::toString(row, fieldSeparator, false); } //-------------------------------------------------- string ofxCsv::getPath() { return filePath; } //-------------------------------------------------- string ofxCsv::getFieldSeparator() { return fieldSeparator; } //-------------------------------------------------- string ofxCsv::getCommentPrefix() { return commentPrefix; } // PROTECTED //-------------------------------------------------- void ofxCsv::expandRow(int row, int cols) { while(data.size() <= row) { data.push_back(ofxCsvRow()); } data[row].expand(cols); } <commit_msg>added getQuoteFields()<commit_after>/** * ofxCsv.cpp * Inspired and based on Ben Fry's [table class](http://benfry.com/writing/map/Table.pde) * * The MIT License * * Copyright (c) 2011-2014 Paul Vollmer, http://www.wng.cc * * 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. * * * @modified 2015.04.21 * @version 0.2.0 */ #include "ofxCsv.h" #include "ofLog.h" #include "ofUtils.h" #include "ofFileUtils.h" //-------------------------------------------------- ofxCsv::ofxCsv() { fieldSeparator = ","; commentPrefix = "#"; quoteFields = false; } //-------------------------------------------------- bool ofxCsv::load(string path, string separator, string comment) { clear(); if(path == "") { path = filePath; } else { filePath = path; } fieldSeparator = separator; commentPrefix = comment; // verbose log print ofLogVerbose("ofxCsv") << "Loading " << filePath; ofLogVerbose("ofxCsv") << " fieldSeparator: " << fieldSeparator; ofLogVerbose("ofxCsv") << " commentPrefix: " << commentPrefix; // open file & read each line int lineCount = 0; int maxCols = 0; ofBuffer buffer = ofBufferFromFile(ofToDataPath(path)); for(auto line : buffer.getLines()) { // skip empty lines if(line.empty()) { ofLogVerbose("ofxCsv") << "Skipping empty line: " << lineCount; lineCount++; continue; } // skip comment lines // TODO: only checks substring at line beginning, does not ignore whitespace if(line.substr(0, commentPrefix.length()) == commentPrefix) { ofLogVerbose("ofxCsv") << "Skipping comment line: " << lineCount; lineCount++; continue; } // split line into separate files vector<string> cols = fromRowString(line, separator); data.push_back(cols); // calc maxium table cols if(cols.size() > maxCols) { maxCols = cols.size(); } lineCount++; } buffer.clear(); // expand to fill in any missing cols, just in case expand(data.size(), maxCols); ofLogVerbose("ofxCsv") << "Read " << lineCount << " lines"; ofLogVerbose("ofxCsv") << "Loaded a " << data.size() << "x" << maxCols << " table"; return true; } //-------------------------------------------------- bool ofxCsv::load(string path, string separator) { return load(path, separator, commentPrefix); } //-------------------------------------------------- bool ofxCsv::load(string path) { return load(path, fieldSeparator); } //-------------------------------------------------- bool ofxCsv::save(string path, bool quote, string separator) { if(path == "") { path = filePath; } else { filePath = path; } fieldSeparator = separator; quoteFields = quote; // verbose log print ofLogVerbose("ofxCsv") << "Saving " << path; ofLogVerbose("ofxCsv") << " fieldSeparator: " << fieldSeparator; ofLogVerbose("ofxCsv") << " quoteFields: " << quoteFields; if(data.empty()) { ofLogWarning("ofxCsv") << "Aborting save to " << path << ": data is empty"; return false; } // create file if needed if(!ofFile::doesFileExist(ofToDataPath(path))) { if(!createFile(path)) { ofLogError("ofxCsv") << "Could not save to " << path << ": couldn't create"; return false; } } // fill buffer & write to file ofBuffer buffer; int lineCount = 0; for(auto row : data) { buffer.append(toRowString(row, fieldSeparator, quote)+"\n"); lineCount++; } if(!ofBufferToFile(path, buffer)) { ofLogError("ofxCsv") << "Could not save to " << path << ": couldn't save buffer"; return false; } buffer.clear(); ofLogVerbose("ofxCsv") << "Wrote " << lineCount << " lines to " << path; return true; } //-------------------------------------------------- bool ofxCsv::save(string path, bool quote) { return save(path, quote, fieldSeparator); } //-------------------------------------------------- bool ofxCsv::save(string path) { return save(path, false, fieldSeparator); } //-------------------------------------------------- bool ofxCsv::createFile(string path) { ofLogVerbose("ofxCsv") << "Creating " << path; ofFile file(ofToDataPath(path), ofFile::WriteOnly, false); return file.create(); } /// DATA IO //-------------------------------------------------- void ofxCsv::load(vector<ofxCsvRow> &rows) { clear(); data = rows; } //-------------------------------------------------- void ofxCsv::load(vector<vector<string>> &rows) { clear(); for(auto row : rows) { data.push_back(ofxCsvRow(row)); } } //-------------------------------------------------- void ofxCsv::add(ofxCsvRow &row) { data.push_back(row); } //-------------------------------------------------- void ofxCsv::insert(ofxCsvRow &row, int index) { int cols = getNumCols(); if(index > data.size()) { expand(index-1, cols); } data.insert(data.begin()+index, row); data[index].expand(cols); } //-------------------------------------------------- void ofxCsv::remove(int index) { data.erase(data.begin()+index); } //-------------------------------------------------- void ofxCsv::expand(int rows, int cols) { while(data.size() < rows) { data.push_back(ofxCsvRow()); } for(auto &row : data) { row.expand(cols-1); } } //-------------------------------------------------- void ofxCsv::clear() { for(auto &row : data) { row.clear(); } data.clear(); } /// DATA ACCESS //-------------------------------------------------- unsigned int ofxCsv::getNumRows() { return data.size(); } //-------------------------------------------------- unsigned int ofxCsv::getNumCols(int row) { if(row > -1 && row < data.size()) { return data[row].size(); } ofLogWarning("ofxCsv") << "Cannot get num cols for row " << row << ": total num rows is " << data.size(); return 0; } //-------------------------------------------------- int ofxCsv::getInt(int row, int col) { expandRow(row, col); return data[row].getInt(col); } //-------------------------------------------------- float ofxCsv::getFloat(int row, int col) { expandRow(row, col); return data[row].getFloat(col); } //-------------------------------------------------- string ofxCsv::getString(int row, int col) { expandRow(row, col); return data[row].getString(col); } //-------------------------------------------------- bool ofxCsv::getBool(int row, int col) { expandRow(row, col); return data[row].getBool(col); } //-------------------------------------------------- void ofxCsv::setInt(int row, int col, int what) { expandRow(row, col); data[row].setInt(col, what); } void ofxCsv::setFloat(int row, int col, float what) { expandRow(row, col); data[row].setFloat(col, what); } //-------------------------------------------------- void ofxCsv::setString(int row, int col, string what) { expandRow(row, col); data[row].setString(col, what); } //-------------------------------------------------- void ofxCsv::setBool(int row, int col, bool what) { expandRow(row, col); data[row].setBool(col, what); } //-------------------------------------------------- void ofxCsv::print() { for(auto &row : data) { ofLogNotice("ofxCsv") << row; } } // RAW DATA ACCESS //-------------------------------------------------- vector<ofxCsvRow>::iterator ofxCsv::begin() { return data.begin(); } //-------------------------------------------------- vector<ofxCsvRow>::iterator ofxCsv::end() { return data.end(); } //-------------------------------------------------- vector<ofxCsvRow>::const_iterator ofxCsv::begin() const{ return data.begin(); } //-------------------------------------------------- vector<ofxCsvRow>::const_iterator ofxCsv::end() const{ return data.end(); } //-------------------------------------------------- vector<ofxCsvRow>::reverse_iterator ofxCsv::rbegin() { return data.rbegin(); } //-------------------------------------------------- vector<ofxCsvRow>::reverse_iterator ofxCsv::rend() { return data.rend(); } //-------------------------------------------------- vector<ofxCsvRow>::const_reverse_iterator ofxCsv::rbegin() const{ return data.rbegin(); } //-------------------------------------------------- vector<ofxCsvRow>::const_reverse_iterator ofxCsv::rend() const{ return data.rend(); } //-------------------------------------------------- ofxCsv::operator vector<ofxCsvRow>() const { return data; } //-------------------------------------------------- ofxCsvRow ofxCsv::operator[](size_t index) { return data[index]; } //-------------------------------------------------- ofxCsvRow ofxCsv::at(size_t index) { return data.at(index); } //-------------------------------------------------- ofxCsvRow ofxCsv::front() { if(data.empty()) { return ofxCsvRow(); } return data.front(); } //-------------------------------------------------- ofxCsvRow ofxCsv::back() { if(data.empty()) { return ofxCsvRow(); } return data.back(); } //-------------------------------------------------- size_t ofxCsv::size() { return data.size(); } // UTIL //-------------------------------------------------- void ofxCsv::trim() { for(int row = 0; row < data.size(); row++) { data[row].trim(); } } //-------------------------------------------------- vector<string> ofxCsv::fromRowString(string row, string separator) { return ofxCsvRow::fromString(row, separator); } //-------------------------------------------------- vector<string> ofxCsv::fromRowString(string row) { return ofxCsvRow::fromString(row, fieldSeparator); } //-------------------------------------------------- string ofxCsv::toRowString(vector<string> row, string separator, bool quote) { return ofxCsvRow::toString(row, separator, quote); } //-------------------------------------------------- string ofxCsv::toRowString(vector<string> row, string separator) { return ofxCsvRow::toString(row, separator, false); } //-------------------------------------------------- string ofxCsv::toRowString(vector<string> row) { return ofxCsvRow::toString(row, fieldSeparator, false); } //-------------------------------------------------- string ofxCsv::getPath() { return filePath; } //-------------------------------------------------- string ofxCsv::getFieldSeparator() { return fieldSeparator; } //-------------------------------------------------- string ofxCsv::getCommentPrefix() { return commentPrefix; } //-------------------------------------------------- bool ofxCsv::getQuoteFields() { return quoteFields; } // PROTECTED //-------------------------------------------------- void ofxCsv::expandRow(int row, int cols) { while(data.size() <= row) { data.push_back(ofxCsvRow()); } data[row].expand(cols); } <|endoftext|>
<commit_before>/* * Copyright 2009 Bjorn Fahller <bjorn@fahller.se> * All rights reserved * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <crpcut.hpp> #include "output.hpp" #include "posix_encapsulation.hpp" #define STR(s) { "\"" #s "\"", sizeof(#s) + 1 } namespace { struct phase_tag { const char *str; size_t len; }; phase_tag phase_str[] = { STR(creating), STR(running), STR(destroying), STR(post_mortem) }; } namespace crpcut { namespace output { using implementation::test_case_registrator; size_t formatter::write(const char *str, size_t len, type t) const { if (t == verbatim) { return do_write(str, len); } const char *prev = str; for (size_t n = 0; n < len; ++n) { const char *esc; size_t esc_len; switch (str[n]) { case '<' : esc = "&lt;"; esc_len = 4; break; case '>' : esc = "&gt;"; esc_len = 4; break; case '&' : esc = "&amp;"; esc_len = 5; break; case '"' : esc = "&quot;"; esc_len = 6; break; case '\'': esc = "&apos;"; esc_len = 6; break; case '\0': esc = 0; esc_len = 0; break; default: continue; } do_write(prev, &str[n] - prev); do_write(esc, esc_len); prev = &str[n] + 1; } do_write(prev, str + len - prev); return len; } size_t formatter::do_write(const char *p, size_t len) const { size_t bytes_written = 0; while (bytes_written < len) { ssize_t rv = wrapped::write(fd_, p, len); assert(rv >= 0); bytes_written += rv; } return bytes_written; } xml_formatter::xml_formatter(int fd, int argc_, const char *argv_[]) : formatter(fd), last_closed(false), blocked_tests(false), statistics_printed(false), argc(argc_), argv(argv_) { write("<?xml version=\"1.0\"?>\n\n" "<crpcut xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" " xsi:noNamespaceSchemaLocation=\"crpcut.xsd\"" " starttime=\""); char time_string[sizeof("2009-01-09T23:59:59Z")]; time_t now = wrapped::time(0); struct tm *tmdata = wrapped::gmtime(&now); int len = wrapped::snprintf(time_string, sizeof(time_string), "%4.4d-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ", tmdata->tm_year + 1900, tmdata->tm_mon + 1, tmdata->tm_mday, tmdata->tm_hour, tmdata->tm_min, tmdata->tm_sec); assert(len < int(sizeof(time_string))); assert(time_string[len] == 0); write(time_string); char machine_string[PATH_MAX]; if (wrapped::gethostname(machine_string, sizeof(machine_string))) { machine_string[0] = 0; } write("\" host=\""); write(machine_string, wrapped::strlen(machine_string), escaped); write("\" command=\""); for (int i = 0; i < argc; ++i) { if (i > 0) write(" ", 1); write(argv[i], escaped); } write("\">\n"); } xml_formatter::~xml_formatter() { if (statistics_printed) { write("</crpcut>\n"); } } void xml_formatter::begin_case(const char *name, size_t name_len, bool result) { write(" <test name=\""); write(name, name_len, escaped); write("\" result="); static const char *rstring[] = { "\"FAILED\"", "\"PASSED\"" }; write(rstring[result]); last_closed=false; } void xml_formatter::end_case() { if (last_closed) { write(" </log>\n </test>\n"); } else { write("/>\n"); } } void xml_formatter::terminate(test_phase phase, const char *msg, size_t msg_len, const char *dirname, size_t dn_len) { make_closed(); write(" <violation phase="); write(phase_str[phase].str, phase_str[phase].len); if (dirname) { write(" nonempty_dir=\""); write(dirname, dn_len, escaped); write("\""); } if (msg_len == 0) { write("/>\n"); return; } write(">"); write(msg, msg_len, escaped); write("</violation>\n"); } void xml_formatter::print(const char *tag, size_t tlen, const char *data, size_t dlen) { make_closed(); write(" <"); write(tag, tlen); if (dlen == 0) { write("/>\n"); return; } write(">"); write(data, dlen, escaped); write("</"); write(tag); write(">\n"); } void xml_formatter::statistics(unsigned num_registered, unsigned /* num_selected */, unsigned num_run, unsigned num_failed) { if (blocked_tests) { write(" </blocked_tests>\n"); } write(" <statistics>\n" " <registered_test_cases>"); write(num_registered); write("</registered_test_cases>\n" " <run_test_cases>"); write(num_run); write("</run_test_cases>\n" " <failed_test_cases>"); write(num_failed); write("</failed_test_cases>\n" " </statistics>\n"); statistics_printed = true; } void xml_formatter::nonempty_dir(const char *s) { write(" <remaining_files nonempty_dir=\""); write(s); write("\"/>\n"); } void xml_formatter::blocked_test(const test_case_registrator *i) { if (!blocked_tests) { write(" <blocked_tests>\n"); blocked_tests = true; } const size_t len = i->full_name_len() + 1; char *name = static_cast<char*>(alloca(len)); stream::oastream os(name, name + len); write(" <test name=\""); os << *i; write(os, escaped); write("\"/>\n"); } void xml_formatter::make_closed() { if (!last_closed) { write(">\n <log>\n"); last_closed = true; } } } } namespace { static const char barrier[] = "===============================================================================\n"; static const char rlabel[2][9] = { "FAILED: ", "PASSED: " }; static const char delim[]= "-------------------------------------------------------------------------------\n"; } namespace crpcut { namespace output { void text_formatter::begin_case(const char *name, size_t name_len, bool result) { did_output = false; write(rlabel[result], 8); write(name, name_len); write("\n"); } void text_formatter::end_case() { write(barrier); } void text_formatter::terminate(test_phase phase, const char *msg, size_t msg_len, const char *dirname, size_t dn_len) { did_output = true; if (dirname) { write(dirname, dn_len); write(" is not empty!!\n"); } if (msg_len) { write("phase="); write(phase_str[phase].str, phase_str[phase].len); write(" "); write(delim + 8 + phase_str[phase].len, sizeof(delim) - 8 - phase_str[phase].len - 1); write(msg, msg_len); write("\n"); write(delim); } } void text_formatter::print(const char *tag, size_t tlen, const char *data, size_t dlen) { did_output = true; const size_t len = write(tag, tlen); if (len < sizeof(delim)) { write(delim + len, sizeof(delim) - len - 1); } write(data, dlen); write("\n"); } void text_formatter::statistics(unsigned /* num_registered */, unsigned num_selected, unsigned num_run, unsigned num_failed) { write("Total "); write(num_selected); write(" test cases selected"); write("\nUNTESTED : "); write(num_selected - num_run); write("\nPASSED : "); write(num_run - num_failed); write("\nFAILED : "); write(num_failed); write("\n"); } void text_formatter::nonempty_dir(const char *s) { write("Files remain under "); write(s); write("\n"); } void text_formatter::blocked_test(const test_case_registrator *i) { if (!blocked_tests) { write("The following tests were blocked from running:\n"); blocked_tests = true; } const size_t len = i->full_name_len()+1; char * name = static_cast<char*>(alloca(len)); stream::oastream os(name, name+len+2); os << " " << *i << '\n'; write(os); } } } <commit_msg>Fixed separation of log-items in text report<commit_after>/* * Copyright 2009 Bjorn Fahller <bjorn@fahller.se> * All rights reserved * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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 <crpcut.hpp> #include "output.hpp" #include "posix_encapsulation.hpp" #define STR(s) { "\"" #s "\"", sizeof(#s) + 1 } namespace { struct phase_tag { const char *str; size_t len; }; phase_tag phase_str[] = { STR(creating), STR(running), STR(destroying), STR(post_mortem) }; } namespace crpcut { namespace output { using implementation::test_case_registrator; size_t formatter::write(const char *str, size_t len, type t) const { if (t == verbatim) { return do_write(str, len); } const char *prev = str; for (size_t n = 0; n < len; ++n) { const char *esc; size_t esc_len; switch (str[n]) { case '<' : esc = "&lt;"; esc_len = 4; break; case '>' : esc = "&gt;"; esc_len = 4; break; case '&' : esc = "&amp;"; esc_len = 5; break; case '"' : esc = "&quot;"; esc_len = 6; break; case '\'': esc = "&apos;"; esc_len = 6; break; case '\0': esc = 0; esc_len = 0; break; default: continue; } do_write(prev, &str[n] - prev); do_write(esc, esc_len); prev = &str[n] + 1; } do_write(prev, str + len - prev); return len; } size_t formatter::do_write(const char *p, size_t len) const { size_t bytes_written = 0; while (bytes_written < len) { ssize_t rv = wrapped::write(fd_, p, len); assert(rv >= 0); bytes_written += rv; } return bytes_written; } xml_formatter::xml_formatter(int fd, int argc_, const char *argv_[]) : formatter(fd), last_closed(false), blocked_tests(false), statistics_printed(false), argc(argc_), argv(argv_) { write("<?xml version=\"1.0\"?>\n\n" "<crpcut xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" " xsi:noNamespaceSchemaLocation=\"crpcut.xsd\"" " starttime=\""); char time_string[sizeof("2009-01-09T23:59:59Z")]; time_t now = wrapped::time(0); struct tm *tmdata = wrapped::gmtime(&now); int len = wrapped::snprintf(time_string, sizeof(time_string), "%4.4d-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ", tmdata->tm_year + 1900, tmdata->tm_mon + 1, tmdata->tm_mday, tmdata->tm_hour, tmdata->tm_min, tmdata->tm_sec); assert(len < int(sizeof(time_string))); assert(time_string[len] == 0); write(time_string); char machine_string[PATH_MAX]; if (wrapped::gethostname(machine_string, sizeof(machine_string))) { machine_string[0] = 0; } write("\" host=\""); write(machine_string, wrapped::strlen(machine_string), escaped); write("\" command=\""); for (int i = 0; i < argc; ++i) { if (i > 0) write(" ", 1); write(argv[i], escaped); } write("\">\n"); } xml_formatter::~xml_formatter() { if (statistics_printed) { write("</crpcut>\n"); } } void xml_formatter::begin_case(const char *name, size_t name_len, bool result) { write(" <test name=\""); write(name, name_len, escaped); write("\" result="); static const char *rstring[] = { "\"FAILED\"", "\"PASSED\"" }; write(rstring[result]); last_closed=false; } void xml_formatter::end_case() { if (last_closed) { write(" </log>\n </test>\n"); } else { write("/>\n"); } } void xml_formatter::terminate(test_phase phase, const char *msg, size_t msg_len, const char *dirname, size_t dn_len) { make_closed(); write(" <violation phase="); write(phase_str[phase].str, phase_str[phase].len); if (dirname) { write(" nonempty_dir=\""); write(dirname, dn_len, escaped); write("\""); } if (msg_len == 0) { write("/>\n"); return; } write(">"); write(msg, msg_len, escaped); write("</violation>\n"); } void xml_formatter::print(const char *tag, size_t tlen, const char *data, size_t dlen) { make_closed(); write(" <"); write(tag, tlen); if (dlen == 0) { write("/>\n"); return; } write(">"); write(data, dlen, escaped); write("</"); write(tag); write(">\n"); } void xml_formatter::statistics(unsigned num_registered, unsigned /* num_selected */, unsigned num_run, unsigned num_failed) { if (blocked_tests) { write(" </blocked_tests>\n"); } write(" <statistics>\n" " <registered_test_cases>"); write(num_registered); write("</registered_test_cases>\n" " <run_test_cases>"); write(num_run); write("</run_test_cases>\n" " <failed_test_cases>"); write(num_failed); write("</failed_test_cases>\n" " </statistics>\n"); statistics_printed = true; } void xml_formatter::nonempty_dir(const char *s) { write(" <remaining_files nonempty_dir=\""); write(s); write("\"/>\n"); } void xml_formatter::blocked_test(const test_case_registrator *i) { if (!blocked_tests) { write(" <blocked_tests>\n"); blocked_tests = true; } const size_t len = i->full_name_len() + 1; char *name = static_cast<char*>(alloca(len)); stream::oastream os(name, name + len); write(" <test name=\""); os << *i; write(os, escaped); write("\"/>\n"); } void xml_formatter::make_closed() { if (!last_closed) { write(">\n <log>\n"); last_closed = true; } } } } namespace { static const char barrier[] = "===============================================================================\n"; static const char rlabel[2][9] = { "FAILED: ", "PASSED: " }; static const char delim[]= "-------------------------------------------------------------------------------\n"; } namespace crpcut { namespace output { void text_formatter::begin_case(const char *name, size_t name_len, bool result) { did_output = false; write(rlabel[result], 8); write(name, name_len); write("\n"); } void text_formatter::end_case() { write(barrier); } void text_formatter::terminate(test_phase phase, const char *msg, size_t msg_len, const char *dirname, size_t dn_len) { if (did_output) { write(delim); } did_output = true; if (dirname) { write(dirname, dn_len); write(" is not empty!!\n"); } if (msg_len) { write("phase="); write(phase_str[phase].str, phase_str[phase].len); write(" "); write(delim + 8 + phase_str[phase].len, sizeof(delim) - 8 - phase_str[phase].len - 1); write(msg, msg_len); write("\n"); write(delim); } } void text_formatter::print(const char *tag, size_t tlen, const char *data, size_t dlen) { if (did_output) { write(delim); } did_output = true; const size_t len = write(tag, tlen); if (len < sizeof(delim)) { write(delim + len, sizeof(delim) - len - 1); } write(data, dlen); write("\n"); } void text_formatter::statistics(unsigned /* num_registered */, unsigned num_selected, unsigned num_run, unsigned num_failed) { write("Total "); write(num_selected); write(" test cases selected"); write("\nUNTESTED : "); write(num_selected - num_run); write("\nPASSED : "); write(num_run - num_failed); write("\nFAILED : "); write(num_failed); write("\n"); } void text_formatter::nonempty_dir(const char *s) { write("Files remain under "); write(s); write("\n"); } void text_formatter::blocked_test(const test_case_registrator *i) { if (!blocked_tests) { write("The following tests were blocked from running:\n"); blocked_tests = true; } const size_t len = i->full_name_len()+1; char * name = static_cast<char*>(alloca(len)); stream::oastream os(name, name+len+2); os << " " << *i << '\n'; write(os); } } } <|endoftext|>
<commit_before>Parcer::Parcer(std::string filename){ Tokens = LexicalAnaltysis(filename); }; /* 構文解析実行 @return 成功:true 失敗:false */ bool Parser::doParse(){ if(!Tokens){ fprintf(stderr, "error at lexer\n"); return false; } else{ return VisitTranslationUnit(); } }; TranslationUnitAST &Parser::getAST(){ if(TU){ return *TU; } else{ return *(new TranslationUnitAST()); } }; // TranslationUnit用構文解析メソッド bool Parser::visitTranslationUnit(){ TU = new TranslatonUnitAST(); // ExternalDecl while(true){ if(!visitExternalDeclaration(TU)){ SAFE_DELETE(TU); return false; } if(Tokens->getCurType == TOK_EOF){ break; } } return true; } // ExternalDeclaration用構文解析メソッド bool Parser::visitExternalDeclaration(TranslationUnitAST *tunit){ PrototypeAST *proto = visitFunctionDeclaration(); if(proto){ tunit->addPrototype(proto); return true; } FunctionAST *func_def = visitFunctionDefinition(); if(func_def){ tunit->addFunction(func_def); return true; } return false; } <commit_msg>関数宣言と関数定義の解析<commit_after>Parcer::Parcer(std::string filename){ Tokens = LexicalAnaltysis(filename); }; /* 構文解析実行 @return 成功:true 失敗:false */ bool Parser::doParse(){ if(!Tokens){ fprintf(stderr, "error at lexer\n"); return false; } else{ return VisitTranslationUnit(); } }; TranslationUnitAST &Parser::getAST(){ if(TU){ return *TU; } else{ return *(new TranslationUnitAST()); } }; // TranslationUnit用構文解析メソッド bool Parser::visitTranslationUnit(){ TU = new TranslatonUnitAST(); // ExternalDecl while(true){ if(!visitExternalDeclaration(TU)){ SAFE_DELETE(TU); return false; } if(Tokens->getCurType == TOK_EOF){ break; } } return true; } // ExternalDeclaration用構文解析メソッド bool Parser::visitExternalDeclaration(TranslationUnitAST *tunit){ PrototypeAST *proto = visitFunctionDeclaration(); if(proto){ tunit->addPrototype(proto); return true; } FunctionAST *func_def = visitFunctionDefinition(); if(func_def){ tunit->addFunction(func_def); return true; } return false; } PrototypeAST *Parser::zisitFunctionDeclaration(){ int backup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } if(Tokens->getCurString() == ';'){ // 本来であればここで再定義されていないか確認 Tokens->getNextToken(); return proto; } else{ SAFE_DELETE(proto); Tokens->applyTokenIndex(backup); return NULL; } } FunctionAST *Parser::visitFunctionDefinition(){ int backup = Tokens->getCurIndex(); PrototypeAST *proto = visitPrototype(); if(!proto){ return NULL; } // 本来であればここで再定義されていないか確認 FunctionStmtAST *func_stmt = visitFunctionStatement(proto); } <|endoftext|>
<commit_before>#include "parser.hpp" #include "ast_data.hpp" namespace klang { Parser::Parser(TokenVector tokens) : tokens_(std::move(tokens)), current_(std::begin(tokens_)) {} bool Parser::parse_symbol(const char* str) { if (current_type() == TokenType::SYMBOL && current_string() == std::string{str}) { advance(1); return true; } else { return false; } } ast::IdentifierPtr Parser::parse_identifier() { if (current_type() == TokenType::IDENTIFIER) { advance(1); return make_unique<ast::IdentifierData>(current_string()); } else { return nullptr; } } ast::TypePtr Parser::parse_type() { if (current_type() == TokenType::SYMBOL) { advance(1); return make_unique<ast::TypeData>(current_string()); } else { return nullptr; } } ast::IntegerLiteralPtr Parser::parse_integer_literal() { if (current_type() == TokenType::NUMBER) { advance(1); return make_unique<ast::IntegerLiteralData>(current_string()); } else { return nullptr; } } ast::CharacterLiteralPtr Parser::parse_character_literal() { if (current_type() == TokenType::CHARACTER) { advance(1); return make_unique<ast::CharacterLiteralData>(current_string()); } else { return nullptr; } } ast::StringLiteralPtr Parser::parse_string_literal() { if (current_type() == TokenType::STRING) { advance(1); return make_unique<ast::StringLiteralData>(current_string()); } else { return nullptr; } } ast::TranslationUnitPtr Parser::parse_translation_unit() { std::vector<ast::FunctionDefinitionPtr> functions; while (auto function = parse_function_definition()) { functions.push_back(std::move(function)); } return make_unique<ast::TranslationUnitData>(std::move(functions)); } ast::FunctionDefinitionPtr Parser::parse_function_definition() { const auto s = snapshot(); if (parse_symbol("def")) { if (auto function_name = parse_identifier()) { if (parse_symbol("(")) { if (auto arguments = parse_argument_list()) { if (parse_symbol(")") && parse_symbol("->") && parse_symbol("(")) { if (auto return_type = parse_type()) { if (parse_symbol(")")) { if (auto function_body = parse_compound_statement()) { return make_unique<ast::FunctionDefinitionData>( std::move(function_name), std::move(arguments), std::move(return_type), std::move(function_body)); } } } } } } } } rewind(s); return nullptr; } ast::ArgumentListPtr Parser::parse_argument_list() { std::vector<ast::ArgumentPtr> arguments; if (auto first_argument = parse_argument()) { arguments.push_back(std::move(first_argument)); while (true) { const auto s = snapshot(); if (parse_symbol(",")) { if (auto argument = parse_argument()) { arguments.push_back(std::move(argument)); continue; } } rewind(s); break; } } return make_unique<ast::ArgumentListData>(std::move(arguments)); } ast::ArgumentPtr Parser::parse_argument() { const auto s = snapshot(); if (auto argument_type = parse_type()) { if (auto argument_name = parse_identifier()) { return make_unique<ast::ArgumentData>(std::move(argument_type), std::move(argument_name)); } } rewind(s); return nullptr; } ast::StatementPtr Parser::parse_statement() { if (auto statement = parse_compound_statement()) { return std::move(statement); } else if (auto statement = parse_if_statement()){ return std::move(statement); } else if (auto statement = parse_while_statement()){ return std::move(statement); } else if (auto statement = parse_for_statement()){ return std::move(statement); } else if (auto statement = parse_return_statement()){ return std::move(statement); } else if (auto statement = parse_break_statement()){ return std::move(statement); } else if (auto statement = parse_continue_statement()){ return std::move(statement); } else if (auto statement = parse_variable_definition_statement()){ return std::move(statement); } else if (auto statement = parse_expression_statement()){ return std::move(statement); } return nullptr; } ast::CompoundStatementPtr Parser::parse_compound_statement() { std::vector<ast::StatementPtr> statements; const auto s = snapshot(); if (parse_symbol("{")) { while (auto statement = parse_statement()) { statements.push_back(std::move(statement)); } if (parse_symbol("}")) { return make_unique<ast::CompoundStatementData>(std::move(statements)); } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_if_statement() { const auto s = snapshot(); if (parse_symbol("if") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::IfStatementData>( std::move(condition), std::move(compound_statement), parse_else_statement()); } } } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_else_statement() { const auto s = snapshot(); if (parse_symbol("else")) { if (auto else_if_statement = parse_if_statement()) { return std::move(else_if_statement); } else if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::ElseStatementData>(std::move(compound_statement)); } } rewind(s); return nullptr; } ast::WhileStatementPtr Parser::parse_while_statement() { const auto s = snapshot(); if (parse_symbol("while") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::WhileStatementData>( std::move(condition), std::move(compound_statement)); } } } } rewind(s); return nullptr; } ast::ForStatementPtr Parser::parse_for_statement() { const auto s = snapshot(); if (parse_symbol("for") && parse_symbol("(")) { auto init_expression = parse_expression(); if (parse_symbol(";")) { auto cond_expression = parse_expression(); if (parse_symbol(";")) { auto reinit_expression = parse_expression(); if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::ForStatementData>( std::move(init_expression), std::move(cond_expression), std::move(reinit_expression), std::move(compound_statement)); } } } } } rewind(s); return nullptr; } ast::ReturnStatementPtr Parser::parse_return_statement() { const auto s = snapshot(); if (parse_symbol("return")) { if (auto return_value = parse_expression()) { if (parse_symbol(";")) { return make_unique<ast::ReturnStatementData>(std::move(return_value)); } } } rewind(s); return nullptr; } ast::BreakStatementPtr Parser::parse_break_statement() { const auto s = snapshot(); if (parse_symbol("break") && parse_symbol(";")) { return make_unique<ast::BreakStatementData>(); } rewind(s); return nullptr; } ast::ContinueStatementPtr Parser::parse_continue_statement() { const auto s = snapshot(); if (parse_symbol("continue") && parse_symbol(";")) { return make_unique<ast::ContinueStatementData>(); } rewind(s); return nullptr; } ast::VariableDefinitionStatementPtr Parser::parse_variable_definition_statement() { const auto s = snapshot(); if (auto variable_definition = parse_variable_definition()) { if (parse_symbol(";")) { return make_unique<ast::VariableDefinitionStatementData>( std::move(variable_definition)); } } rewind(s); return nullptr; } TokenType Parser::current_type() const { return is_eof() ? TokenType::IGNORE : current_->type(); } std::string Parser::current_string() const { static const std::string empty_string{""}; return is_eof() ? empty_string : current_->str(); } bool Parser::is_eof() const { using std::end; return current_ == end(tokens_); } bool Parser::advance(int count) { using std::begin; using std::end; const auto b = begin(tokens_); const auto e = end(tokens_); while (count < 0) { if (current_ != b) { ++count; --current_; } else { return false; } } while (0 < count) { if (current_ != e) { --count; ++current_; } else { return false; } } return true; } auto Parser::snapshot() const -> Pointer { return current_; } void Parser::rewind(Pointer p) { current_ = p; } } // namespace klang <commit_msg>Add parse_variable_definition() member<commit_after>#include "parser.hpp" #include "ast_data.hpp" namespace klang { Parser::Parser(TokenVector tokens) : tokens_(std::move(tokens)), current_(std::begin(tokens_)) {} bool Parser::parse_symbol(const char* str) { if (current_type() == TokenType::SYMBOL && current_string() == std::string{str}) { advance(1); return true; } else { return false; } } ast::IdentifierPtr Parser::parse_identifier() { if (current_type() == TokenType::IDENTIFIER) { advance(1); return make_unique<ast::IdentifierData>(current_string()); } else { return nullptr; } } ast::TypePtr Parser::parse_type() { if (current_type() == TokenType::SYMBOL) { advance(1); return make_unique<ast::TypeData>(current_string()); } else { return nullptr; } } ast::IntegerLiteralPtr Parser::parse_integer_literal() { if (current_type() == TokenType::NUMBER) { advance(1); return make_unique<ast::IntegerLiteralData>(current_string()); } else { return nullptr; } } ast::CharacterLiteralPtr Parser::parse_character_literal() { if (current_type() == TokenType::CHARACTER) { advance(1); return make_unique<ast::CharacterLiteralData>(current_string()); } else { return nullptr; } } ast::StringLiteralPtr Parser::parse_string_literal() { if (current_type() == TokenType::STRING) { advance(1); return make_unique<ast::StringLiteralData>(current_string()); } else { return nullptr; } } ast::TranslationUnitPtr Parser::parse_translation_unit() { std::vector<ast::FunctionDefinitionPtr> functions; while (auto function = parse_function_definition()) { functions.push_back(std::move(function)); } return make_unique<ast::TranslationUnitData>(std::move(functions)); } ast::FunctionDefinitionPtr Parser::parse_function_definition() { const auto s = snapshot(); if (parse_symbol("def")) { if (auto function_name = parse_identifier()) { if (parse_symbol("(")) { if (auto arguments = parse_argument_list()) { if (parse_symbol(")") && parse_symbol("->") && parse_symbol("(")) { if (auto return_type = parse_type()) { if (parse_symbol(")")) { if (auto function_body = parse_compound_statement()) { return make_unique<ast::FunctionDefinitionData>( std::move(function_name), std::move(arguments), std::move(return_type), std::move(function_body)); } } } } } } } } rewind(s); return nullptr; } ast::ArgumentListPtr Parser::parse_argument_list() { std::vector<ast::ArgumentPtr> arguments; if (auto first_argument = parse_argument()) { arguments.push_back(std::move(first_argument)); while (true) { const auto s = snapshot(); if (parse_symbol(",")) { if (auto argument = parse_argument()) { arguments.push_back(std::move(argument)); continue; } } rewind(s); break; } } return make_unique<ast::ArgumentListData>(std::move(arguments)); } ast::ArgumentPtr Parser::parse_argument() { const auto s = snapshot(); if (auto argument_type = parse_type()) { if (auto argument_name = parse_identifier()) { return make_unique<ast::ArgumentData>(std::move(argument_type), std::move(argument_name)); } } rewind(s); return nullptr; } ast::StatementPtr Parser::parse_statement() { if (auto statement = parse_compound_statement()) { return std::move(statement); } else if (auto statement = parse_if_statement()){ return std::move(statement); } else if (auto statement = parse_while_statement()){ return std::move(statement); } else if (auto statement = parse_for_statement()){ return std::move(statement); } else if (auto statement = parse_return_statement()){ return std::move(statement); } else if (auto statement = parse_break_statement()){ return std::move(statement); } else if (auto statement = parse_continue_statement()){ return std::move(statement); } else if (auto statement = parse_variable_definition_statement()){ return std::move(statement); } else if (auto statement = parse_expression_statement()){ return std::move(statement); } return nullptr; } ast::CompoundStatementPtr Parser::parse_compound_statement() { std::vector<ast::StatementPtr> statements; const auto s = snapshot(); if (parse_symbol("{")) { while (auto statement = parse_statement()) { statements.push_back(std::move(statement)); } if (parse_symbol("}")) { return make_unique<ast::CompoundStatementData>(std::move(statements)); } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_if_statement() { const auto s = snapshot(); if (parse_symbol("if") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::IfStatementData>( std::move(condition), std::move(compound_statement), parse_else_statement()); } } } } rewind(s); return nullptr; } ast::IfStatementPtr Parser::parse_else_statement() { const auto s = snapshot(); if (parse_symbol("else")) { if (auto else_if_statement = parse_if_statement()) { return std::move(else_if_statement); } else if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::ElseStatementData>(std::move(compound_statement)); } } rewind(s); return nullptr; } ast::WhileStatementPtr Parser::parse_while_statement() { const auto s = snapshot(); if (parse_symbol("while") && parse_symbol("(")) { if (auto condition = parse_expression()) { if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::WhileStatementData>( std::move(condition), std::move(compound_statement)); } } } } rewind(s); return nullptr; } ast::ForStatementPtr Parser::parse_for_statement() { const auto s = snapshot(); if (parse_symbol("for") && parse_symbol("(")) { auto init_expression = parse_expression(); if (parse_symbol(";")) { auto cond_expression = parse_expression(); if (parse_symbol(";")) { auto reinit_expression = parse_expression(); if (parse_symbol(")")) { if (auto compound_statement = parse_compound_statement()) { return make_unique<ast::ForStatementData>( std::move(init_expression), std::move(cond_expression), std::move(reinit_expression), std::move(compound_statement)); } } } } } rewind(s); return nullptr; } ast::ReturnStatementPtr Parser::parse_return_statement() { const auto s = snapshot(); if (parse_symbol("return")) { if (auto return_value = parse_expression()) { if (parse_symbol(";")) { return make_unique<ast::ReturnStatementData>(std::move(return_value)); } } } rewind(s); return nullptr; } ast::BreakStatementPtr Parser::parse_break_statement() { const auto s = snapshot(); if (parse_symbol("break") && parse_symbol(";")) { return make_unique<ast::BreakStatementData>(); } rewind(s); return nullptr; } ast::ContinueStatementPtr Parser::parse_continue_statement() { const auto s = snapshot(); if (parse_symbol("continue") && parse_symbol(";")) { return make_unique<ast::ContinueStatementData>(); } rewind(s); return nullptr; } ast::VariableDefinitionStatementPtr Parser::parse_variable_definition_statement() { const auto s = snapshot(); if (auto variable_definition = parse_variable_definition()) { if (parse_symbol(";")) { return make_unique<ast::VariableDefinitionStatementData>( std::move(variable_definition)); } } rewind(s); return nullptr; } ast::VariableDefinitionPtr Parser::parse_variable_definition() { const auto s = snapshot(); if (parse_symbol("def")) { if (auto type_name = parse_type()) { const bool is_mutable = parse_symbol("var"); if (auto variable_name = parse_identifier()) { if (parse_symbol(":=")) { if (auto expression = parse_expression()) { return make_unique<ast::VariableDefinitionData>( std::move(type_name), is_mutable, std::move(variable_name), std::move(expression)); } } } } } rewind(s); return nullptr; } TokenType Parser::current_type() const { return is_eof() ? TokenType::IGNORE : current_->type(); } std::string Parser::current_string() const { static const std::string empty_string{""}; return is_eof() ? empty_string : current_->str(); } bool Parser::is_eof() const { using std::end; return current_ == end(tokens_); } bool Parser::advance(int count) { using std::begin; using std::end; const auto b = begin(tokens_); const auto e = end(tokens_); while (count < 0) { if (current_ != b) { ++count; --current_; } else { return false; } } while (0 < count) { if (current_ != e) { --count; ++current_; } else { return false; } } return true; } auto Parser::snapshot() const -> Pointer { return current_; } void Parser::rewind(Pointer p) { current_ = p; } } // namespace klang <|endoftext|>
<commit_before>#ifndef MODBUS_CLIENT_HPP #define MODBUS_CLIENT_HPP #include <boost/asio.hpp> #include <stdexcept> class ModbusClient { public: inline ModbusClient(const modbus::tcp::UnitId& unitId, std::unique_ptr<OutputFormatter> out); inline void setTransactionId(const modbus::tcp::TransactionId& transactionId); inline void connect(const boost::asio::ip::tcp::endpoint& ep); inline void readCoils(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numCoils); inline void readDiscreteInputs(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numInputs); inline void readInputRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs); inline void readHoldingRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs); inline void setFormatter(std::unique_ptr<OutputFormatter> out); private: std::unique_ptr<OutputFormatter> m_outFormatter; boost::asio::io_service m_io; boost::asio::ip::tcp::socket m_socket; modbus::tcp::UnitId m_unitId; modbus::tcp::TransactionId m_transactionId; std::vector<uint8_t> m_tx_buffer; std::vector<uint8_t> m_rx_buffer; void recvResponse(); }; ModbusClient::ModbusClient(const modbus::tcp::UnitId& unitId, std::unique_ptr<OutputFormatter> out) : m_outFormatter(std::move(out)), m_io(), m_socket(m_io), m_unitId(unitId), m_transactionId(1), m_tx_buffer(), m_rx_buffer() {} void ModbusClient::setTransactionId(const modbus::tcp::TransactionId& transactionId) { m_transactionId = transactionId; } void ModbusClient::setFormatter(std::unique_ptr<OutputFormatter> out) { m_outFormatter = std::move(out); } void ModbusClient::connect(const boost::asio::ip::tcp::endpoint& ep) { m_socket.connect(ep); } void ModbusClient::readCoils(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numCoils) { modbus::tcp::Encoder encoder(m_unitId, m_transactionId); encoder.encodeReadCoilsReq(startAddress, numCoils, m_tx_buffer); m_outFormatter->displayOutgoing(m_tx_buffer); boost::asio::write(m_socket, boost::asio::buffer(m_tx_buffer)); recvResponse(); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); if (rsp_header_view.isError()) m_outFormatter->displayErrorResponse(m_tx_buffer, m_rx_buffer); else m_outFormatter->displayReadCoils(m_tx_buffer, m_rx_buffer); } void ModbusClient::readDiscreteInputs(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numInputs) { modbus::tcp::Encoder encoder(m_unitId, m_transactionId); encoder.encodeReadDiscreteInputsReq(startAddress, numInputs, m_tx_buffer); m_outFormatter->displayOutgoing(m_tx_buffer); boost::asio::write(m_socket, boost::asio::buffer(m_tx_buffer)); recvResponse(); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); if (rsp_header_view.isError()) m_outFormatter->displayErrorResponse(m_tx_buffer, m_rx_buffer); else m_outFormatter->displayReadDiscreteInputs(m_tx_buffer, m_rx_buffer); } void ModbusClient::readInputRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs) { modbus::tcp::Encoder encoder(m_unitId, m_transactionId); encoder.encodeReadInputRegistersReq(startAddress, numRegs, m_tx_buffer); m_outFormatter->displayOutgoing(m_tx_buffer); boost::asio::write(m_socket, boost::asio::buffer(m_tx_buffer)); recvResponse(); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); if (rsp_header_view.isError()) m_outFormatter->displayErrorResponse(m_tx_buffer, m_rx_buffer); else m_outFormatter->displayReadInputRegisters(m_tx_buffer, m_rx_buffer); } void ModbusClient::readHoldingRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs) { modbus::tcp::Encoder encoder(m_unitId, m_transactionId); encoder.encodeReadHoldingRegistersReq(startAddress, numRegs, m_tx_buffer); m_outFormatter->displayOutgoing(m_tx_buffer); boost::asio::write(m_socket, boost::asio::buffer(m_tx_buffer)); recvResponse(); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); if (rsp_header_view.isError()) m_outFormatter->displayErrorResponse(m_tx_buffer, m_rx_buffer); else m_outFormatter->displayReadHoldingRegisters(m_tx_buffer, m_rx_buffer); } void ModbusClient::recvResponse() { m_rx_buffer.resize(sizeof(modbus::tcp::Header)); boost::asio::read(m_socket, boost::asio::buffer(m_rx_buffer)); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); uint16_t payload_size = rsp_header_view.getLength() - 2; m_rx_buffer.resize(sizeof(modbus::tcp::Header) + payload_size); uint8_t *payload = m_rx_buffer.data() + sizeof(modbus::tcp::Header); boost::asio::read(m_socket, boost::asio::buffer(payload, payload_size)); } #endif <commit_msg>Remove duplicate code<commit_after>#ifndef MODBUS_CLIENT_HPP #define MODBUS_CLIENT_HPP #include <boost/asio.hpp> #include <stdexcept> class ModbusClient { public: inline ModbusClient(const modbus::tcp::UnitId& unitId, std::unique_ptr<OutputFormatter> out); inline void setTransactionId(const modbus::tcp::TransactionId& transactionId); inline void connect(const boost::asio::ip::tcp::endpoint& ep); inline void readCoils(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numCoils); inline void readDiscreteInputs(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numInputs); inline void readInputRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs); inline void readHoldingRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs); inline void setFormatter(std::unique_ptr<OutputFormatter> out); private: std::unique_ptr<OutputFormatter> m_outFormatter; boost::asio::io_service m_io; boost::asio::ip::tcp::socket m_socket; modbus::tcp::UnitId m_unitId; modbus::tcp::TransactionId m_transactionId; std::vector<uint8_t> m_tx_buffer; std::vector<uint8_t> m_rx_buffer; void readValues(std::function<void(modbus::tcp::Encoder&)> encodeFn, std::function<void(void)> displayFn); void recvResponse(); }; ModbusClient::ModbusClient(const modbus::tcp::UnitId& unitId, std::unique_ptr<OutputFormatter> out) : m_outFormatter(std::move(out)), m_io(), m_socket(m_io), m_unitId(unitId), m_transactionId(1), m_tx_buffer(), m_rx_buffer() {} void ModbusClient::setTransactionId(const modbus::tcp::TransactionId& transactionId) { m_transactionId = transactionId; } void ModbusClient::setFormatter(std::unique_ptr<OutputFormatter> out) { m_outFormatter = std::move(out); } void ModbusClient::connect(const boost::asio::ip::tcp::endpoint& ep) { m_socket.connect(ep); } void ModbusClient::readCoils(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numCoils) { readValues([this, &startAddress, numCoils](modbus::tcp::Encoder& encoder) { encoder.encodeReadCoilsReq(startAddress, numCoils, m_tx_buffer); }, [this]() { m_outFormatter->displayReadCoils(m_tx_buffer, m_rx_buffer); }); } void ModbusClient::readDiscreteInputs(const modbus::tcp::Address& startAddress, const modbus::tcp::NumBits& numInputs) { readValues([this, &startAddress, numInputs](modbus::tcp::Encoder& encoder) { encoder.encodeReadDiscreteInputsReq(startAddress, numInputs, m_tx_buffer); }, [this]() { m_outFormatter->displayReadDiscreteInputs(m_tx_buffer, m_rx_buffer); }); } void ModbusClient::readInputRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs) { readValues([this, &startAddress, numRegs](modbus::tcp::Encoder& encoder) { encoder.encodeReadInputRegistersReq(startAddress, numRegs, m_tx_buffer); }, [this]() { m_outFormatter->displayReadInputRegisters(m_tx_buffer, m_rx_buffer); }); } void ModbusClient::readHoldingRegisters(const modbus::tcp::Address& startAddress, const modbus::tcp::NumRegs& numRegs) { readValues([this, &startAddress, &numRegs](modbus::tcp::Encoder& encoder) { encoder.encodeReadHoldingRegistersReq(startAddress, numRegs, m_tx_buffer); }, [this]() { m_outFormatter->displayReadHoldingRegisters(m_tx_buffer, m_rx_buffer); }); } void ModbusClient::readValues(std::function<void(modbus::tcp::Encoder&)> encodeFn, std::function<void(void)> displayFn) { modbus::tcp::Encoder encoder(m_unitId, m_transactionId); encodeFn(encoder); m_outFormatter->displayOutgoing(m_tx_buffer); boost::asio::write(m_socket, boost::asio::buffer(m_tx_buffer)); recvResponse(); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); if (rsp_header_view.isError()) m_outFormatter->displayErrorResponse(m_tx_buffer, m_rx_buffer); else displayFn(); } void ModbusClient::recvResponse() { m_rx_buffer.resize(sizeof(modbus::tcp::Header)); boost::asio::read(m_socket, boost::asio::buffer(m_rx_buffer)); modbus::tcp::decoder_views::Header rsp_header_view(m_rx_buffer); uint16_t payload_size = rsp_header_view.getLength() - 2; m_rx_buffer.resize(sizeof(modbus::tcp::Header) + payload_size); uint8_t *payload = m_rx_buffer.data() + sizeof(modbus::tcp::Header); boost::asio::read(m_socket, boost::asio::buffer(payload, payload_size)); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2010 SURFnet bv * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /***************************************************************************** ObjectStoreTests.cpp Contains test cases to test the object store implementation *****************************************************************************/ #include <stdlib.h> #include <string.h> #include <cppunit/extensions/HelperMacros.h> #include "ObjectStoreTests.h" #include "ObjectStore.h" #include "ObjectFile.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(ObjectStoreTests); // FIXME: all pathnames in this file are *NIX/BSD specific void ObjectStoreTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void ObjectStoreTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void ObjectStoreTests::testEmptyStore() { // Create the store for an empty dir #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); } void ObjectStoreTests::testNewTokens() { ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; { // Create an empty store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); // Create a new token ObjectStoreToken* token1 = store.newToken(label1); CPPUNIT_ASSERT(token1 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 1); // Create another new token ObjectStoreToken* token2 = store.newToken(label2); CPPUNIT_ASSERT(token2 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); } // Now reopen that same store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store.getToken(0); ObjectStoreToken* token2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2; CPPUNIT_ASSERT(token1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(token2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel2 == label1)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); ByteString retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(token1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(token2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testExistingTokens() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testDeleteToken() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); // Now, delete token #1 CPPUNIT_ASSERT(store.destroyToken(retrieveToken1)); CPPUNIT_ASSERT(store.getTokenCount() == 1); ObjectStoreToken* retrieveToken_ = store.getToken(0); ByteString retrieveLabel_,retrieveSerial_; CPPUNIT_ASSERT(retrieveToken_->getTokenLabel(retrieveLabel_)); CPPUNIT_ASSERT(retrieveToken_->getTokenSerial(retrieveSerial_)); CPPUNIT_ASSERT(((retrieveLabel_ == label1) && (retrieveSerial_ == serial1)) || ((retrieveLabel_ == label2) && (retrieveSerial_ == serial2))); // Now add a new token ByteString label3 = "DEADC0FFEEBEEF"; // Create a new token ObjectStoreToken* tokenNew = store.newToken(label3); CPPUNIT_ASSERT(tokenNew != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1_ = store.getToken(0); ObjectStoreToken* retrieveToken2_ = store.getToken(1); CPPUNIT_ASSERT(retrieveToken1_ != NULL); CPPUNIT_ASSERT(retrieveToken2_ != NULL); CPPUNIT_ASSERT(retrieveToken1_->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1_->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label3) || (retrieveLabel2 == label3)); CPPUNIT_ASSERT(((retrieveLabel1 == label1) && (retrieveLabel2 != label2)) || ((retrieveLabel1 == label2) && (retrieveLabel2 != label1))); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); } <commit_msg>Remove superfluous #include.<commit_after>/* * Copyright (c) 2010 SURFnet bv * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /***************************************************************************** ObjectStoreTests.cpp Contains test cases to test the object store implementation *****************************************************************************/ #include <stdlib.h> #include <string.h> #include <cppunit/extensions/HelperMacros.h> #include "ObjectStoreTests.h" #include "ObjectStore.h" #include "File.h" #include "Directory.h" #include "OSAttribute.h" #include "OSAttributes.h" #include "cryptoki.h" CPPUNIT_TEST_SUITE_REGISTRATION(ObjectStoreTests); // FIXME: all pathnames in this file are *NIX/BSD specific void ObjectStoreTests::setUp() { CPPUNIT_ASSERT(!system("mkdir testdir")); } void ObjectStoreTests::tearDown() { #ifndef _WIN32 CPPUNIT_ASSERT(!system("rm -rf testdir")); #else CPPUNIT_ASSERT(!system("rmdir /s /q testdir 2> nul")); #endif } void ObjectStoreTests::testEmptyStore() { // Create the store for an empty dir #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); } void ObjectStoreTests::testNewTokens() { ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; { // Create an empty store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 0); // Create a new token ObjectStoreToken* token1 = store.newToken(label1); CPPUNIT_ASSERT(token1 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 1); // Create another new token ObjectStoreToken* token2 = store.newToken(label2); CPPUNIT_ASSERT(token2 != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); } // Now reopen that same store #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* token1 = store.getToken(0); ObjectStoreToken* token2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2; CPPUNIT_ASSERT(token1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(token2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel2 == label1)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); ByteString retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(token1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(token2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testExistingTokens() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); } void ObjectStoreTests::testDeleteToken() { // Create some tokens ByteString label1 = "DEADC0FFEE"; ByteString label2 = "DEADBEEF"; ByteString serial1 = "0011001100110011"; ByteString serial2 = "2233223322332233"; #ifndef _WIN32 ObjectStoreToken* token1 = ObjectStoreToken::createToken("./testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken("./testdir", "token2", label2, serial2); #else ObjectStoreToken* token1 = ObjectStoreToken::createToken(".\\testdir", "token1", label1, serial1); ObjectStoreToken* token2 = ObjectStoreToken::createToken(".\\testdir", "token2", label2, serial2); #endif CPPUNIT_ASSERT((token1 != NULL) && (token2 != NULL)); delete token1; delete token2; // Now associate a store with the test directory #ifndef _WIN32 ObjectStore store("./testdir"); #else ObjectStore store(".\\testdir"); #endif CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1 = store.getToken(0); ObjectStoreToken* retrieveToken2 = store.getToken(1); ByteString retrieveLabel1, retrieveLabel2, retrieveSerial1, retrieveSerial2; CPPUNIT_ASSERT(retrieveToken1 != NULL); CPPUNIT_ASSERT(retrieveToken2 != NULL); CPPUNIT_ASSERT(retrieveToken1->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label1) || (retrieveLabel1 == label2)); CPPUNIT_ASSERT((retrieveLabel2 == label1) || (retrieveLabel2 == label2)); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); CPPUNIT_ASSERT((retrieveSerial1 == serial1) || (retrieveSerial1 == serial2)); CPPUNIT_ASSERT((retrieveSerial2 == serial1) || (retrieveSerial2 == serial2)); CPPUNIT_ASSERT(retrieveSerial1 != retrieveSerial2); // Now, delete token #1 CPPUNIT_ASSERT(store.destroyToken(retrieveToken1)); CPPUNIT_ASSERT(store.getTokenCount() == 1); ObjectStoreToken* retrieveToken_ = store.getToken(0); ByteString retrieveLabel_,retrieveSerial_; CPPUNIT_ASSERT(retrieveToken_->getTokenLabel(retrieveLabel_)); CPPUNIT_ASSERT(retrieveToken_->getTokenSerial(retrieveSerial_)); CPPUNIT_ASSERT(((retrieveLabel_ == label1) && (retrieveSerial_ == serial1)) || ((retrieveLabel_ == label2) && (retrieveSerial_ == serial2))); // Now add a new token ByteString label3 = "DEADC0FFEEBEEF"; // Create a new token ObjectStoreToken* tokenNew = store.newToken(label3); CPPUNIT_ASSERT(tokenNew != NULL); CPPUNIT_ASSERT(store.getTokenCount() == 2); // Retrieve both tokens and check that both are present ObjectStoreToken* retrieveToken1_ = store.getToken(0); ObjectStoreToken* retrieveToken2_ = store.getToken(1); CPPUNIT_ASSERT(retrieveToken1_ != NULL); CPPUNIT_ASSERT(retrieveToken2_ != NULL); CPPUNIT_ASSERT(retrieveToken1_->getTokenLabel(retrieveLabel1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenLabel(retrieveLabel2)); CPPUNIT_ASSERT(retrieveToken1_->getTokenSerial(retrieveSerial1)); CPPUNIT_ASSERT(retrieveToken2_->getTokenSerial(retrieveSerial2)); CPPUNIT_ASSERT((retrieveLabel1 == label3) || (retrieveLabel2 == label3)); CPPUNIT_ASSERT(((retrieveLabel1 == label1) && (retrieveLabel2 != label2)) || ((retrieveLabel1 == label2) && (retrieveLabel2 != label1))); CPPUNIT_ASSERT(retrieveLabel1 != retrieveLabel2); } <|endoftext|>
<commit_before>#include "model/PhysicsRemoteCar.h" #include "model/PhysicsWorld.h" #include <btBulletDynamicsCommon.h> #include <sstream> #include <iostream> namespace Rally { namespace Model { namespace { const btVector3 CAR_DIMENSIONS(2.0f, 1.0f, 4.0f); const float MAX_CORRECTION_DISTANCE = 10.0f; } PhysicsRemoteCar::PhysicsRemoteCar() : physicsWorld(NULL), dynamicsWorld(NULL), bodyShape(NULL), bodyConstructionInfo(NULL), bodyRigidBody(NULL) { } PhysicsRemoteCar::~PhysicsRemoteCar() { if(physicsWorld != NULL) { physicsWorld->unregisterStepCallback(this); } if(dynamicsWorld != NULL && bodyRigidBody != NULL) { dynamicsWorld->removeRigidBody(bodyRigidBody); delete bodyRigidBody; } // TODO: These could be shared among all remote cars... delete bodyConstructionInfo; delete bodyShape; } void PhysicsRemoteCar::initializeConstructionInfo() { if(bodyConstructionInfo != NULL) { return; } bodyShape = new btBoxShape(CAR_DIMENSIONS / 2); // Takes half-extents bodyConstructionInfo = new btRigidBody::btRigidBodyConstructionInfo(0, &bodyMotionState, bodyShape, btVector3(0, 0, 0)); } void PhysicsRemoteCar::attachTo(PhysicsWorld& physicsWorld) { this->physicsWorld = &physicsWorld; this->dynamicsWorld = physicsWorld.getDynamicsWorld(); // Create car body this->initializeConstructionInfo(); bodyRigidBody = new btRigidBody(*bodyConstructionInfo); bodyRigidBody->setCollisionFlags(bodyRigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); bodyRigidBody->setActivationState(DISABLE_DEACTIVATION); // So that our motion stte is queried every simulation stop dynamicsWorld->addRigidBody(bodyRigidBody); // Register for physics world updates physicsWorld.registerStepCallback(this); } void PhysicsRemoteCar::setTargetTransform(const Rally::Vector3& targetPosition, const Rally::Vector3& incomingVelocity, const Rally::Quaternion& targetOrientation) { bodyMotionState.setTargetTransform(targetPosition, incomingVelocity, targetOrientation); } Rally::Vector3 PhysicsRemoteCar::getPosition() const { // Note that we cannot ask the rigidbody for its position, // as we won't get interpolated values then. That's motion-state exclusive info. const btVector3& position = bodyMotionState.currentTransform.getOrigin(); return Rally::Vector3(position.x(), position.y(), position.z()); } Rally::Quaternion PhysicsRemoteCar::getOrientation() const { const btQuaternion orientation = bodyMotionState.currentTransform.getRotation(); return Rally::Quaternion(orientation.x(), orientation.y(), orientation.z(), orientation.w()); } void PhysicsRemoteCar_BodyMotionState::setTargetTransform(const Rally::Vector3& targetPosition, const Rally::Vector3& incomingVelocity, const Rally::Quaternion& targetOrientation) { btVector3 currentPosition = currentTransform.getOrigin(); Rally::Vector3 correctionDistance = targetPosition - Rally::Vector3(currentPosition.x(), currentPosition.y(), currentPosition.z()); if(correctionDistance.length() <= MAX_CORRECTION_DISTANCE) { // Correction velocity is the velocity we need to go to where the physics car will be in one second, // in one second. It is then scaled by the length of the incoming velocity to not create jitter. // It effectively means that the velocity vector is steered to the correct position, interpolating it. Rally::Vector3 correctionVelocity = incomingVelocity + correctionDistance; float correctionVelocityLength = correctionVelocity.length(); if(correctionVelocityLength > 0.001f) { correctionVelocity = (correctionVelocity / correctionVelocityLength) * incomingVelocity.length(); } interpolationVelocity = btVector3(correctionVelocity.x, correctionVelocity.y, correctionVelocity.z); } else { // If the correction distance is to high, we just teleport instead. Probably happens: // * When the simulation has just started and there is no valid position set already. // * When there is a lot of network drop/lag. interpolationVelocity = btVector3(incomingVelocity.x, incomingVelocity.y, incomingVelocity.z); currentTransform.setOrigin(btVector3(targetPosition.x, targetPosition.y, targetPosition.z)); } // Todo: Interpolate here currentTransform.setRotation(btQuaternion(targetOrientation.x, targetOrientation.y, targetOrientation.z, targetOrientation.w)); } void PhysicsRemoteCar::willStep(float deltaTime) { // setLinearVelocity() is used by the solver for other colliding objects. bodyRigidBody->setLinearVelocity(bodyMotionState.interpolationVelocity); // Interpolate the position by integrating the velocity. btVector3 currentPosition = bodyMotionState.currentTransform.getOrigin(); bodyMotionState.currentTransform.setOrigin(currentPosition + bodyMotionState.interpolationVelocity*deltaTime); } void PhysicsRemoteCar_BodyMotionState::getWorldTransform(btTransform& worldTransform) const { worldTransform = currentTransform; } void PhysicsRemoteCar_BodyMotionState::setWorldTransform(const btTransform& worldTransform) { std::cout << "SetWorldTransform called for remote car. Notify Joel if you see this!" << std::endl; } } } <commit_msg>Fixed remote car quaternion bug.<commit_after>#include "model/PhysicsRemoteCar.h" #include "model/PhysicsWorld.h" #include <btBulletDynamicsCommon.h> #include <sstream> #include <iostream> namespace Rally { namespace Model { namespace { const btVector3 CAR_DIMENSIONS(2.0f, 1.0f, 4.0f); const float MAX_CORRECTION_DISTANCE = 10.0f; } PhysicsRemoteCar::PhysicsRemoteCar() : physicsWorld(NULL), dynamicsWorld(NULL), bodyShape(NULL), bodyConstructionInfo(NULL), bodyRigidBody(NULL) { } PhysicsRemoteCar::~PhysicsRemoteCar() { if(physicsWorld != NULL) { physicsWorld->unregisterStepCallback(this); } if(dynamicsWorld != NULL && bodyRigidBody != NULL) { dynamicsWorld->removeRigidBody(bodyRigidBody); delete bodyRigidBody; } // TODO: These could be shared among all remote cars... delete bodyConstructionInfo; delete bodyShape; } void PhysicsRemoteCar::initializeConstructionInfo() { if(bodyConstructionInfo != NULL) { return; } bodyShape = new btBoxShape(CAR_DIMENSIONS / 2); // Takes half-extents bodyConstructionInfo = new btRigidBody::btRigidBodyConstructionInfo(0, &bodyMotionState, bodyShape, btVector3(0, 0, 0)); } void PhysicsRemoteCar::attachTo(PhysicsWorld& physicsWorld) { this->physicsWorld = &physicsWorld; this->dynamicsWorld = physicsWorld.getDynamicsWorld(); // Create car body this->initializeConstructionInfo(); bodyRigidBody = new btRigidBody(*bodyConstructionInfo); bodyRigidBody->setCollisionFlags(bodyRigidBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT); bodyRigidBody->setActivationState(DISABLE_DEACTIVATION); // So that our motion stte is queried every simulation stop dynamicsWorld->addRigidBody(bodyRigidBody); // Register for physics world updates physicsWorld.registerStepCallback(this); } void PhysicsRemoteCar::setTargetTransform(const Rally::Vector3& targetPosition, const Rally::Vector3& incomingVelocity, const Rally::Quaternion& targetOrientation) { bodyMotionState.setTargetTransform(targetPosition, incomingVelocity, targetOrientation); } Rally::Vector3 PhysicsRemoteCar::getPosition() const { // Note that we cannot ask the rigidbody for its position, // as we won't get interpolated values then. That's motion-state exclusive info. const btVector3& position = bodyMotionState.currentTransform.getOrigin(); return Rally::Vector3(position.x(), position.y(), position.z()); } Rally::Quaternion PhysicsRemoteCar::getOrientation() const { const btQuaternion orientation = bodyMotionState.currentTransform.getRotation(); return Rally::Quaternion(orientation.w(), orientation.x(), orientation.y(), orientation.z()); } void PhysicsRemoteCar_BodyMotionState::setTargetTransform(const Rally::Vector3& targetPosition, const Rally::Vector3& incomingVelocity, const Rally::Quaternion& targetOrientation) { btVector3 currentPosition = currentTransform.getOrigin(); Rally::Vector3 correctionDistance = targetPosition - Rally::Vector3(currentPosition.x(), currentPosition.y(), currentPosition.z()); if(correctionDistance.length() <= MAX_CORRECTION_DISTANCE) { // Correction velocity is the velocity we need to go to where the physics car will be in one second, // in one second. It is then scaled by the length of the incoming velocity to not create jitter. // It effectively means that the velocity vector is steered to the correct position, interpolating it. Rally::Vector3 correctionVelocity = incomingVelocity + correctionDistance; float correctionVelocityLength = correctionVelocity.length(); if(correctionVelocityLength > 0.001f) { correctionVelocity = (correctionVelocity / correctionVelocityLength) * incomingVelocity.length(); } interpolationVelocity = btVector3(correctionVelocity.x, correctionVelocity.y, correctionVelocity.z); } else { // If the correction distance is to high, we just teleport instead. Probably happens: // * When the simulation has just started and there is no valid position set already. // * When there is a lot of network drop/lag. interpolationVelocity = btVector3(incomingVelocity.x, incomingVelocity.y, incomingVelocity.z); currentTransform.setOrigin(btVector3(targetPosition.x, targetPosition.y, targetPosition.z)); } // Todo: Interpolate here currentTransform.setRotation(btQuaternion(targetOrientation.x, targetOrientation.y, targetOrientation.z, targetOrientation.w)); } void PhysicsRemoteCar::willStep(float deltaTime) { // setLinearVelocity() is used by the solver for other colliding objects. bodyRigidBody->setLinearVelocity(bodyMotionState.interpolationVelocity); // Interpolate the position by integrating the velocity. btVector3 currentPosition = bodyMotionState.currentTransform.getOrigin(); bodyMotionState.currentTransform.setOrigin(currentPosition + bodyMotionState.interpolationVelocity*deltaTime); } void PhysicsRemoteCar_BodyMotionState::getWorldTransform(btTransform& worldTransform) const { worldTransform = currentTransform; } void PhysicsRemoteCar_BodyMotionState::setWorldTransform(const btTransform& worldTransform) { std::cout << "SetWorldTransform called for remote car. Notify Joel if you see this!" << std::endl; } } } <|endoftext|>
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Source: FGExternalForce.cpp Author: Jon Berndt, Dave Culp Date started: 9/21/07 ------------- Copyright (C) 2007 Jon S. Berndt (jon@jsbsim.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 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. HISTORY -------------------------------------------------------------------------------- 9/21/07 JB Created <external_reactions> <!-- Interface properties, a.k.a. property declarations --> <property> ... </property> <force name="name" frame="BODY|LOCAL|WIND"> <function> ... </function> <location unit="units"> <!-- location --> <x> value </x> <y> value </y> <z> value </z> </location> <direction> <!-- optional for initial direction vector --> <x> value </x> <y> value </y> <z> value </z> </direction> </force> </external_reactions> */ #include "FGExternalForce.h" #include "input_output/FGXMLElement.h" #include <iostream> using namespace std; namespace JSBSim { IDENT(IdSrc,"$Id: FGExternalForce.cpp,v 1.15 2014/11/25 01:44:17 dpculp Exp $"); IDENT(IdHdr,ID_EXTERNALFORCE); //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGExternalForce::FGExternalForce(FGFDMExec *FDMExec, Element *el, int index) : FGForce(FDMExec) { Element* location_element=0; Element* direction_element=0; Element* function_element=0; string sFrame; string BasePropertyName; FGColumnVector3 location; Magnitude_Function = 0; magnitude = 0.0; azimuth = 0.0; FGPropertyManager* PropertyManager = fdmex->GetPropertyManager(); Name = el->GetAttributeValue("name"); BasePropertyName = "external_reactions/" + Name; // The value sent to the sim through the external_forces/{force name}/magnitude // property will be multiplied against the unit vector, which can come in // initially in the direction vector. The frame in which the vector is defined // is specified with the frame attribute. The vector is normalized to magnitude 1. function_element = el->FindElement("function"); if (function_element) { Magnitude_Function = new FGFunction(PropertyManager, function_element); } else { PropertyManager->Tie( BasePropertyName + "/magnitude",(FGExternalForce*)this, &FGExternalForce::GetMagnitude, &FGExternalForce::SetMagnitude); } // Set frame (from FGForce). sFrame = el->GetAttributeValue("frame"); if (sFrame.empty()) { cerr << "No frame specified for external force, \"" << Name << "\"." << endl; cerr << "Frame set to Body" << endl; ttype = tNone; } else if (sFrame == "BODY") { ttype = tNone; } else if (sFrame == "LOCAL") { ttype = tLocalBody; PropertyManager->Tie( BasePropertyName + "/azimuth", (FGExternalForce*)this, &FGExternalForce::GetAzimuth, &FGExternalForce::SetAzimuth); } else if (sFrame == "WIND") { ttype = tWindBody; } else { cerr << "Invalid frame specified for external force, \"" << Name << "\"." << endl; cerr << "Frame set to Body" << endl; ttype = tNone; } PropertyManager->Tie( BasePropertyName + "/x", (FGExternalForce*)this, &FGExternalForce::GetX, &FGExternalForce::SetX); PropertyManager->Tie( BasePropertyName + "/y", (FGExternalForce*)this, &FGExternalForce::GetY, &FGExternalForce::SetY); PropertyManager->Tie( BasePropertyName + "/z", (FGExternalForce*)this, &FGExternalForce::GetZ, &FGExternalForce::SetZ); location_element = el->FindElement("location"); if (!location_element) { cerr << "No location element specified in force object." << endl; } else { location = location_element->FindElementTripletConvertTo("IN"); SetLocation(location); } PropertyManager->Tie( BasePropertyName + "/locx", (FGExternalForce*)this, &FGExternalForce::GetLocX, &FGExternalForce::SetLocX); PropertyManager->Tie( BasePropertyName + "/locy", (FGExternalForce*)this, &FGExternalForce::GetLocY, &FGExternalForce::SetLocY); PropertyManager->Tie( BasePropertyName + "/locz", (FGExternalForce*)this, &FGExternalForce::GetLocZ, &FGExternalForce::SetLocZ); direction_element = el->FindElement("direction"); if (!direction_element) { cerr << "No direction element specified in force object. Default is (0,0,0)." << endl; } else { vDirection = direction_element->FindElementTripletConvertTo("IN"); vDirection.Normalize(); } Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Copy constructor FGExternalForce::FGExternalForce(const FGExternalForce& extForce) : FGForce(extForce) { magnitude = extForce.magnitude; Frame = extForce.Frame; vDirection = extForce.vDirection; Name = extForce.Name; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGExternalForce::~FGExternalForce() { delete Magnitude_Function; Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGExternalForce::SetMagnitude(double mag) { magnitude = mag; vFn = vDirection*mag; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% const FGColumnVector3& FGExternalForce::GetBodyForces(void) { if (Magnitude_Function) { double mag = Magnitude_Function->GetValue(); SetMagnitude(mag); } return FGForce::GetBodyForces(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGExternalForce::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor cout << " " << Name << endl; cout << " Frame: " << Frame << endl; cout << " Location: (" << vXYZn(eX) << ", " << vXYZn(eY) << ", " << vXYZn(eZ) << ")" << endl; } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGExternalForce" << endl; if (from == 1) cout << "Destroyed: FGExternalForce" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } } <commit_msg>cvsimport<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Source: FGExternalForce.cpp Author: Jon Berndt, Dave Culp Date started: 9/21/07 ------------- Copyright (C) 2007 Jon S. Berndt (jon@jsbsim.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 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU Lesser General Public License can also be found on the world wide web at http://www.gnu.org. HISTORY -------------------------------------------------------------------------------- 9/21/07 JB Created <external_reactions> <!-- Interface properties, a.k.a. property declarations --> <property> ... </property> <force name="name" frame="BODY|LOCAL|WIND"> <function> ... </function> <location unit="units"> <!-- location --> <x> value </x> <y> value </y> <z> value </z> </location> <direction> <!-- optional for initial direction vector --> <x> value </x> <y> value </y> <z> value </z> </direction> </force> </external_reactions> */ #include "FGExternalForce.h" #include "input_output/FGXMLElement.h" #include <iostream> using namespace std; namespace JSBSim { IDENT(IdSrc,"$Id: FGExternalForce.cpp,v 1.16 2014/12/18 09:56:05 andgi Exp $"); IDENT(IdHdr,ID_EXTERNALFORCE); //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGExternalForce::FGExternalForce(FGFDMExec *FDMExec, Element *el, int index) : FGForce(FDMExec) { Element* location_element=0; Element* direction_element=0; Element* function_element=0; string sFrame; string BasePropertyName; FGColumnVector3 location; Magnitude_Function = 0; magnitude = 0.0; azimuth = 0.0; FGPropertyManager* PropertyManager = fdmex->GetPropertyManager(); Name = el->GetAttributeValue("name"); BasePropertyName = "external_reactions/" + Name; // The value sent to the sim through the external_forces/{force name}/magnitude // property will be multiplied against the unit vector, which can come in // initially in the direction vector. The frame in which the vector is defined // is specified with the frame attribute. The vector is normalized to magnitude 1. function_element = el->FindElement("function"); if (function_element) { Magnitude_Function = new FGFunction(PropertyManager, function_element); } else { PropertyManager->Tie( BasePropertyName + "/magnitude",(FGExternalForce*)this, &FGExternalForce::GetMagnitude, &FGExternalForce::SetMagnitude); } // Set frame (from FGForce). sFrame = el->GetAttributeValue("frame"); if (sFrame.empty()) { cerr << "No frame specified for external force, \"" << Name << "\"." << endl; cerr << "Frame set to Body" << endl; ttype = tNone; } else if (sFrame == "BODY") { ttype = tNone; } else if (sFrame == "LOCAL") { ttype = tLocalBody; PropertyManager->Tie( BasePropertyName + "/azimuth", (FGExternalForce*)this, &FGExternalForce::GetAzimuth, &FGExternalForce::SetAzimuth); } else if (sFrame == "WIND") { ttype = tWindBody; } else { cerr << "Invalid frame specified for external force, \"" << Name << "\"." << endl; cerr << "Frame set to Body" << endl; ttype = tNone; } PropertyManager->Tie( BasePropertyName + "/x", (FGExternalForce*)this, &FGExternalForce::GetX, &FGExternalForce::SetX); PropertyManager->Tie( BasePropertyName + "/y", (FGExternalForce*)this, &FGExternalForce::GetY, &FGExternalForce::SetY); PropertyManager->Tie( BasePropertyName + "/z", (FGExternalForce*)this, &FGExternalForce::GetZ, &FGExternalForce::SetZ); location_element = el->FindElement("location"); if (!location_element) { cerr << "No location element specified in force object." << endl; } else { location = location_element->FindElementTripletConvertTo("IN"); SetLocation(location); } PropertyManager->Tie( BasePropertyName + "/location-x-in", (FGExternalForce*)this, &FGExternalForce::GetLocX, &FGExternalForce::SetLocX); PropertyManager->Tie( BasePropertyName + "/location-y-in", (FGExternalForce*)this, &FGExternalForce::GetLocY, &FGExternalForce::SetLocY); PropertyManager->Tie( BasePropertyName + "/location-z-in", (FGExternalForce*)this, &FGExternalForce::GetLocZ, &FGExternalForce::SetLocZ); direction_element = el->FindElement("direction"); if (!direction_element) { cerr << "No direction element specified in force object. Default is (0,0,0)." << endl; } else { vDirection = direction_element->FindElementTripletConvertTo("IN"); vDirection.Normalize(); } Debug(0); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Copy constructor FGExternalForce::FGExternalForce(const FGExternalForce& extForce) : FGForce(extForce) { magnitude = extForce.magnitude; Frame = extForce.Frame; vDirection = extForce.vDirection; Name = extForce.Name; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FGExternalForce::~FGExternalForce() { delete Magnitude_Function; Debug(1); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% void FGExternalForce::SetMagnitude(double mag) { magnitude = mag; vFn = vDirection*mag; } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% const FGColumnVector3& FGExternalForce::GetBodyForces(void) { if (Magnitude_Function) { double mag = Magnitude_Function->GetValue(); SetMagnitude(mag); } return FGForce::GetBodyForces(); } //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // The bitmasked value choices are as follows: // unset: In this case (the default) JSBSim would only print // out the normally expected messages, essentially echoing // the config files as they are read. If the environment // variable is not set, debug_lvl is set to 1 internally // 0: This requests JSBSim not to output any messages // whatsoever. // 1: This value explicity requests the normal JSBSim // startup messages // 2: This value asks for a message to be printed out when // a class is instantiated // 4: When this value is set, a message is displayed when a // FGModel object executes its Run() method // 8: When this value is set, various runtime state variables // are printed out periodically // 16: When set various parameters are sanity checked and // a message is printed out when they go out of bounds void FGExternalForce::Debug(int from) { if (debug_lvl <= 0) return; if (debug_lvl & 1) { // Standard console startup message output if (from == 0) { // Constructor cout << " " << Name << endl; cout << " Frame: " << Frame << endl; cout << " Location: (" << vXYZn(eX) << ", " << vXYZn(eY) << ", " << vXYZn(eZ) << ")" << endl; } } if (debug_lvl & 2 ) { // Instantiation/Destruction notification if (from == 0) cout << "Instantiated: FGExternalForce" << endl; if (from == 1) cout << "Destroyed: FGExternalForce" << endl; } if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects } if (debug_lvl & 8 ) { // Runtime state variables } if (debug_lvl & 16) { // Sanity checking } if (debug_lvl & 64) { if (from == 0) { // Constructor cout << IdSrc << endl; cout << IdHdr << endl; } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "plugindetailsview.h" #include "ui_plugindetailsview.h" #include "pluginspec.h" #include <QDir> #include <QRegExp> /*! \class ExtensionSystem::PluginDetailsView \brief The PluginDetailsView class implements a widget that displays the contents of a PluginSpec. Can be used for integration in the application that uses the plugin manager. \sa ExtensionSystem::PluginView */ using namespace ExtensionSystem; /*! Constructs a new view with given \a parent widget. */ PluginDetailsView::PluginDetailsView(QWidget *parent) : QWidget(parent), m_ui(new Internal::Ui::PluginDetailsView()) { m_ui->setupUi(this); } /*! \internal */ PluginDetailsView::~PluginDetailsView() { delete m_ui; } /*! Reads the given \a spec and displays its values in this PluginDetailsView. */ void PluginDetailsView::update(PluginSpec *spec) { m_ui->name->setText(spec->name()); m_ui->version->setText(spec->version()); m_ui->compatVersion->setText(spec->compatVersion()); m_ui->vendor->setText(spec->vendor()); const QString link = QString::fromLatin1("<a href=\"%1\">%1</a>").arg(spec->url()); m_ui->url->setText(link); QString component = tr("None"); if (!spec->category().isEmpty()) component = spec->category(); m_ui->component->setText(component); m_ui->location->setText(QDir::toNativeSeparators(spec->filePath())); m_ui->description->setText(spec->description()); m_ui->copyright->setText(spec->copyright()); m_ui->license->setText(spec->license()); const QRegExp platforms = spec->platformSpecification(); m_ui->platforms->setText(platforms.isEmpty() ? tr("All") : platforms.pattern()); QStringList depStrings; foreach (const PluginDependency &dep, spec->dependencies()) { QString depString = dep.name; depString += QLatin1String(" ("); depString += dep.version; if (dep.type == PluginDependency::Optional) depString += QLatin1String(", optional"); depString += QLatin1Char(')'); depStrings.append(depString); } m_ui->dependencies->addItems(depStrings); } <commit_msg>Plugin manager: Show current platform string in plugin details<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "plugindetailsview.h" #include "ui_plugindetailsview.h" #include "pluginmanager.h" #include "pluginspec.h" #include <QDir> #include <QRegExp> /*! \class ExtensionSystem::PluginDetailsView \brief The PluginDetailsView class implements a widget that displays the contents of a PluginSpec. Can be used for integration in the application that uses the plugin manager. \sa ExtensionSystem::PluginView */ using namespace ExtensionSystem; /*! Constructs a new view with given \a parent widget. */ PluginDetailsView::PluginDetailsView(QWidget *parent) : QWidget(parent), m_ui(new Internal::Ui::PluginDetailsView()) { m_ui->setupUi(this); } /*! \internal */ PluginDetailsView::~PluginDetailsView() { delete m_ui; } /*! Reads the given \a spec and displays its values in this PluginDetailsView. */ void PluginDetailsView::update(PluginSpec *spec) { m_ui->name->setText(spec->name()); m_ui->version->setText(spec->version()); m_ui->compatVersion->setText(spec->compatVersion()); m_ui->vendor->setText(spec->vendor()); const QString link = QString::fromLatin1("<a href=\"%1\">%1</a>").arg(spec->url()); m_ui->url->setText(link); QString component = tr("None"); if (!spec->category().isEmpty()) component = spec->category(); m_ui->component->setText(component); m_ui->location->setText(QDir::toNativeSeparators(spec->filePath())); m_ui->description->setText(spec->description()); m_ui->copyright->setText(spec->copyright()); m_ui->license->setText(spec->license()); const QRegExp platforms = spec->platformSpecification(); const QString pluginPlatformString = platforms.isEmpty() ? tr("All") : platforms.pattern(); const QString platformString = tr("%1 (current: \"%2\")").arg(pluginPlatformString, PluginManager::platformName()); m_ui->platforms->setText(platformString); QStringList depStrings; foreach (const PluginDependency &dep, spec->dependencies()) { QString depString = dep.name; depString += QLatin1String(" ("); depString += dep.version; if (dep.type == PluginDependency::Optional) depString += QLatin1String(", optional"); depString += QLatin1Char(')'); depStrings.append(depString); } m_ui->dependencies->addItems(depStrings); } <|endoftext|>
<commit_before>//! \file /* ** Copyright (C) - Triton ** ** This program is under the terms of the LGPLv3 License. */ #ifndef TRITON_ASTGARBAGECOLLECTOR_H #define TRITON_ASTGARBAGECOLLECTOR_H #include <set> #include <string> #include "ast.hpp" #include "symbolicEnums.hpp" #include "tritonTypes.hpp" //! \module The Triton namespace namespace triton { /*! * \addtogroup triton * @{ */ //! \module The AST namespace namespace ast { /*! * \ingroup triton * \addtogroup ast * @{ */ //! \class AstGarbageCollector /*! \brief The AST garbage collector class */ class AstGarbageCollector { protected: /* This container contains all allocated nodes. */ std::set<triton::ast::AbstractNode*> allocatedNodes; /* This map maintains a link between symbolic variables and their nodes. */ std::map<std::string, triton::ast::AbstractNode*> variableNodes; public: //! Constructor. AstGarbageCollector(); //! Destructor. ~AstGarbageCollector(); //! Go through every allocated nodes and free them. void freeAllAstNodes(void); //! Frees a set of nodes and removes them from the global container. void freeAstNodes(std::set<triton::ast::AbstractNode*>& nodes); //! Extracts all unique nodes from a partial AST into the uniqueNodes set. void extractUniqueAstNodes(std::set<triton::ast::AbstractNode*>& uniqueNodes, triton::ast::AbstractNode* root); //! Records the allocated node or returns the same node if it already exists inside the dictionaries. triton::ast::AbstractNode* recordAstNode(triton::ast::AbstractNode* node); //! Records a variable AST node. void recordVariableAstNode(std::string& name, triton::ast::AbstractNode* node); //! Returns all allocated nodes. std::set<triton::ast::AbstractNode*> getAllocatedAstNodes(void); //! Returns all variable nodes recorded. std::map<std::string, triton::ast::AbstractNode*> getAstVariableNodes(void); //! Returns the node of a recorded variable. triton::ast::AbstractNode* getAstVariableNode(std::string& name); //! Sets all allocated nodes. void setAllocatedAstNodes(std::set<triton::ast::AbstractNode*> nodes); //! Sets all variable nodes recorded. void setAstVariableNodes(std::map<std::string, triton::ast::AbstractNode*> nodes); }; /*! @} End of ast namespace */ }; /*! @} End of triton namespace */ }; #endif /* TRITON_ASTGARBAGECOLLECTOR_H */ <commit_msg>Update doxygen comment<commit_after>//! \file /* ** Copyright (C) - Triton ** ** This program is under the terms of the LGPLv3 License. */ #ifndef TRITON_ASTGARBAGECOLLECTOR_H #define TRITON_ASTGARBAGECOLLECTOR_H #include <set> #include <string> #include "ast.hpp" #include "symbolicEnums.hpp" #include "tritonTypes.hpp" //! \module The Triton namespace namespace triton { /*! * \addtogroup triton * @{ */ //! \module The AST namespace namespace ast { /*! * \ingroup triton * \addtogroup ast * @{ */ //! \class AstGarbageCollector /*! \brief The AST garbage collector class */ class AstGarbageCollector { protected: //! This container contains all allocated nodes. std::set<triton::ast::AbstractNode*> allocatedNodes; //! This map maintains a link between symbolic variables and their nodes. std::map<std::string, triton::ast::AbstractNode*> variableNodes; public: //! Constructor. AstGarbageCollector(); //! Destructor. ~AstGarbageCollector(); //! Go through every allocated nodes and free them. void freeAllAstNodes(void); //! Frees a set of nodes and removes them from the global container. void freeAstNodes(std::set<triton::ast::AbstractNode*>& nodes); //! Extracts all unique nodes from a partial AST into the uniqueNodes set. void extractUniqueAstNodes(std::set<triton::ast::AbstractNode*>& uniqueNodes, triton::ast::AbstractNode* root); //! Records the allocated node or returns the same node if it already exists inside the dictionaries. triton::ast::AbstractNode* recordAstNode(triton::ast::AbstractNode* node); //! Records a variable AST node. void recordVariableAstNode(std::string& name, triton::ast::AbstractNode* node); //! Returns all allocated nodes. std::set<triton::ast::AbstractNode*> getAllocatedAstNodes(void); //! Returns all variable nodes recorded. std::map<std::string, triton::ast::AbstractNode*> getAstVariableNodes(void); //! Returns the node of a recorded variable. triton::ast::AbstractNode* getAstVariableNode(std::string& name); //! Sets all allocated nodes. void setAllocatedAstNodes(std::set<triton::ast::AbstractNode*> nodes); //! Sets all variable nodes recorded. void setAstVariableNodes(std::map<std::string, triton::ast::AbstractNode*> nodes); }; /*! @} End of ast namespace */ }; /*! @} End of triton namespace */ }; #endif /* TRITON_ASTGARBAGECOLLECTOR_H */ <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "PythonMacros.h" #include "PythonEnvironment.h" #include "PythonScriptController.h" #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/FileSystem.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/simulation/Node.h> #include <sofa/helper/Utils.h> #if defined(__linux__) # include <dlfcn.h> // for dlopen(), see workaround in Init() #endif using namespace sofa::component::controller; using sofa::helper::system::FileSystem; using sofa::helper::Utils; namespace sofa { namespace simulation { PyMODINIT_FUNC initModulesHelper(const std::string& name, PyMethodDef* methodDef) { Py_InitModule(name.c_str(), methodDef); } void PythonEnvironment::addModule(const std::string& name, PyMethodDef* methodDef) { initModulesHelper(name, methodDef); } void PythonEnvironment::Init() { std::string pythonVersion = Py_GetVersion(); #ifndef NDEBUG SP_MESSAGE_INFO("Python version: " + pythonVersion) #endif #if defined(__linux__) // WARNING: workaround to be able to import python libraries on linux (like // numpy), at least on Ubuntu (see http://bugs.python.org/issue4434). It is // not fixing the real problem, but at least it is working for now. std::string pythonLibraryName = "libpython" + std::string(pythonVersion,0,3) + ".so"; dlopen( pythonLibraryName.c_str(), RTLD_LAZY|RTLD_GLOBAL ); #endif // Prevent the python terminal from being buffered, not to miss or mix up traces. if( putenv( (char*)"PYTHONUNBUFFERED=1" ) ) SP_MESSAGE_WARNING("failed to set environment variable PYTHONUNBUFFERED") if ( !Py_IsInitialized() ) { Py_Initialize(); } // Append sofa modules to the embedded python environment. bindSofaPythonModule(); // Required for sys.path, used in addPythonModulePath(). PyRun_SimpleString("import sys"); // Force C locale. PyRun_SimpleString("import locale"); PyRun_SimpleString("locale.setlocale(locale.LC_ALL, 'C')"); // Workaround: try to import numpy and to launch numpy.finfo to cache data; // this prevents a deadlock when calling numpy.finfo from a worker thread. // ocarre: may crash on some configurations, we have to find a fix PyRun_SimpleString("\ try:\n\ import numpy\n\ numpy.finfo(float)\n\ except:\n\ pass"); // If the script directory is not available (e.g. if the interpreter is invoked interactively // or if the script is read from standard input), path[0] is the empty string, // which directs Python to search modules in the current directory first. PyRun_SimpleString(std::string("sys.path.insert(0,\"\")").c_str()); // Add the paths to the plugins' python modules to sys.path. Those paths // are read from all the files in 'etc/sofa/python.d' std::string confDir = Utils::getSofaPathPrefix() + "/etc/sofa/python.d"; if (FileSystem::exists(confDir)) { std::vector<std::string> files; FileSystem::listDirectory(confDir, files); for (size_t i=0; i<files.size(); i++) { addPythonModulePathsFromConfigFile(confDir + "/" + files[i]); } } // Add the directories listed in the SOFAPYTHON_PLUGINS_PATH environnement // variable (colon-separated) to sys.path char * pathVar = getenv("SOFAPYTHON_PLUGINS_PATH"); if (pathVar != NULL) { std::istringstream ss(pathVar); std::string path; while(std::getline(ss, path, ':')) { if (FileSystem::exists(path)) addPythonModulePathsForPlugins(path); else SP_MESSAGE_WARNING("no such directory: '" + path + "'"); } } // python livecoding related PyRun_SimpleString("from SofaPython.livecoding import onReimpAFile"); // general sofa-python stuff PyRun_SimpleString("import SofaPython"); // python modules are automatically reloaded at each scene loading setAutomaticModuleReload( true ); } void PythonEnvironment::Release() { // Finish the Python Interpreter Py_Finalize(); } void PythonEnvironment::addPythonModulePath(const std::string& path) { static std::set<std::string> addedPath; if (addedPath.find(path)==addedPath.end()) { // note not to insert at first 0 place // an empty string must be at first so modules can be found in the current directory first. PyRun_SimpleString(std::string("sys.path.insert(1,\""+path+"\")").c_str()); SP_MESSAGE_INFO("Added '" + path + "' to sys.path"); addedPath.insert(path); } } void PythonEnvironment::addPythonModulePathsFromConfigFile(const std::string& path) { std::ifstream configFile(path.c_str()); std::string line; while(std::getline(configFile, line)) { if (!FileSystem::isAbsolute(line)) { line = Utils::getSofaPathPrefix() + "/" + line; } addPythonModulePath(line); } } void PythonEnvironment::addPythonModulePathsForPlugins(const std::string& pluginsDirectory) { std::vector<std::string> files; FileSystem::listDirectory(pluginsDirectory, files); for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); ++i) { const std::string pluginPath = pluginsDirectory + "/" + *i; if (FileSystem::exists(pluginPath) && FileSystem::isDirectory(pluginPath)) { const std::string pythonDir = pluginPath + "/python"; if (FileSystem::exists(pythonDir) && FileSystem::isDirectory(pythonDir)) { addPythonModulePath(pythonDir); } } } } /* // helper functions sofa::simulation::tree::GNode::SPtr PythonEnvironment::initGraphFromScript( const char *filename ) { PyObject *script = importScript(filename); if (!script) return 0; // the root node GNode::SPtr groot = sofa::core::objectmodel::New<GNode>(); // TODO: passer par une factory groot->setName( "root" ); // groot->setGravity( Coord3(0,-10,0) ); if (!initGraph(script,groot)) groot = 0; else printf("Root node name after pyhton: %s\n",groot->getName().c_str()); Py_DECREF(script); return groot; } */ // some basic RAII stuff to handle init/termination cleanly namespace { struct raii { raii() { // initialization is done when loading the plugin // otherwise it can be executed too soon // when an application is directly linking with the SofaPython library // PythonEnvironment::Init(); } ~raii() { PythonEnvironment::Release(); } }; static raii singleton; } // basic script functions std::string PythonEnvironment::getError() { std::string error; PyObject *ptype, *pvalue /* error msg */, *ptraceback /*stack snapshot and many other informations (see python traceback structure)*/; PyErr_Fetch(&ptype, &pvalue, &ptraceback); if(pvalue) error = PyString_AsString(pvalue); return error; } bool PythonEnvironment::runString(const std::string& script) { PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__")); PyObject* result = PyRun_String(script.data(), Py_file_input, pDict, pDict); if(0 == result) { SP_MESSAGE_ERROR("Script (string) import error") PyErr_Print(); return false; } Py_DECREF(result); return true; } bool PythonEnvironment::runFile( const char *filename, const std::vector<std::string>& arguments) { // SP_MESSAGE_INFO( "Loading python script \""<<filename<<"\"" ) std::string dir = sofa::helper::system::SetDirectory::GetParentDir(filename); std::string bareFilename = sofa::helper::system::SetDirectory::GetFileNameWithoutExtension(filename); // SP_MESSAGE_INFO( "script directory \""<<dir<<"\"" ) // SP_MESSAGE_INFO( commandString.c_str() ) if(!arguments.empty()) { char**argv = new char*[arguments.size()+1]; argv[0] = new char[bareFilename.size()+1]; strcpy( argv[0], bareFilename.c_str() ); for( size_t i=0 ; i<arguments.size() ; ++i ) { argv[i+1] = new char[arguments[i].size()+1]; strcpy( argv[i+1], arguments[i].c_str() ); } Py_SetProgramName(argv[0]); // TODO check what it is doing exactly PySys_SetArgv(arguments.size()+1, argv); for( size_t i=0 ; i<arguments.size()+1 ; ++i ) { delete [] argv[i]; } delete [] argv; } // Py_BEGIN_ALLOW_THREADS // Load the scene script char* pythonFilename = strdup(filename); PyObject* scriptPyFile = PyFile_FromString(pythonFilename, (char*)("r")); free(pythonFilename); if( !scriptPyFile ) { SP_MESSAGE_ERROR("cannot open file:" << filename) PyErr_Print(); return false; } PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__")); std::string backupFileName; PyObject* backupFileObject = PyDict_GetItemString(pDict, "__file__"); if(backupFileObject) backupFileName = PyString_AsString(backupFileObject); PyObject* newFileObject = PyString_FromString(filename); PyDict_SetItemString(pDict, "__file__", newFileObject); int error = PyRun_SimpleFileEx(PyFile_AsFile(scriptPyFile), filename, 1); backupFileObject = PyString_FromString(backupFileName.c_str()); PyDict_SetItemString(pDict, "__file__", backupFileObject); // Py_END_ALLOW_THREADS if(0 != error) { SP_MESSAGE_ERROR("Script (file:" << bareFilename << ") import error") PyErr_Print(); return false; } return true; } /* bool PythonEnvironment::initGraph(PyObject *script, sofa::simulation::tree::GNode::SPtr graphRoot) // calls the method "initGraph(root)" of the script { // pDict is a borrowed reference PyObject *pDict = PyModule_GetDict(script); // pFunc is also a borrowed reference PyObject *pFunc = PyDict_GetItemString(pDict, "initGraph"); if (PyCallable_Check(pFunc)) { // PyObject *args = PyTuple_New(1); // PyTuple_SetItem(args,0,object(graphRoot.get()).ptr()); try { //PyObject_CallObject(pFunc, NULL);//args); boost::python::call<int>(pFunc,boost::ref(*graphRoot.get())); } catch (const error_already_set e) { SP_MESSAGE_EXCEPTION("") PyErr_Print(); } // Py_DECREF(args); return true; } else { PyErr_Print(); return false; } } */ void PythonEnvironment::SceneLoaderListerner::rightBeforeLoadingScene() { // unload python modules to force importing their eventual modifications PyRun_SimpleString("SofaPython.unloadModules()"); } void PythonEnvironment::setAutomaticModuleReload( bool b ) { if( b ) SceneLoader::addListener( SceneLoaderListerner::getInstance() ); else SceneLoader::removeListener( SceneLoaderListerner::getInstance() ); } void PythonEnvironment::excludeModuleFromReload( const std::string& moduleName ) { PyRun_SimpleString( std::string( "try: SofaPython.__SofaPythonEnvironment_modulesExcludedFromReload.append('" + moduleName + "')\nexcept:pass" ).c_str() ); } } // namespace simulation } // namespace sofa <commit_msg>[SofaPython] pre-importing scipy from the main thread. (to avoid locking when importing scipy in another thread, like when loading a scene asynchronously)<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "PythonMacros.h" #include "PythonEnvironment.h" #include "PythonScriptController.h" #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/FileSystem.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/simulation/Node.h> #include <sofa/helper/Utils.h> #if defined(__linux__) # include <dlfcn.h> // for dlopen(), see workaround in Init() #endif using namespace sofa::component::controller; using sofa::helper::system::FileSystem; using sofa::helper::Utils; namespace sofa { namespace simulation { PyMODINIT_FUNC initModulesHelper(const std::string& name, PyMethodDef* methodDef) { Py_InitModule(name.c_str(), methodDef); } void PythonEnvironment::addModule(const std::string& name, PyMethodDef* methodDef) { initModulesHelper(name, methodDef); } void PythonEnvironment::Init() { std::string pythonVersion = Py_GetVersion(); #ifndef NDEBUG SP_MESSAGE_INFO("Python version: " + pythonVersion) #endif #if defined(__linux__) // WARNING: workaround to be able to import python libraries on linux (like // numpy), at least on Ubuntu (see http://bugs.python.org/issue4434). It is // not fixing the real problem, but at least it is working for now. std::string pythonLibraryName = "libpython" + std::string(pythonVersion,0,3) + ".so"; dlopen( pythonLibraryName.c_str(), RTLD_LAZY|RTLD_GLOBAL ); #endif // Prevent the python terminal from being buffered, not to miss or mix up traces. if( putenv( (char*)"PYTHONUNBUFFERED=1" ) ) SP_MESSAGE_WARNING("failed to set environment variable PYTHONUNBUFFERED") if ( !Py_IsInitialized() ) { Py_Initialize(); } // Append sofa modules to the embedded python environment. bindSofaPythonModule(); // Required for sys.path, used in addPythonModulePath(). PyRun_SimpleString("import sys"); // Force C locale. PyRun_SimpleString("import locale"); PyRun_SimpleString("locale.setlocale(locale.LC_ALL, 'C')"); // Workaround: try to import numpy and to launch numpy.finfo to cache data; // this prevents a deadlock when calling numpy.finfo from a worker thread. // ocarre: may crash on some configurations, we have to find a fix PyRun_SimpleString("try:\n\timport numpy;numpy.finfo(float)\nexcept:\n\tpass"); // Workaround: try to import scipy from the main thread this prevents a deadlock when importing scipy from a worker thread when we use the SofaScene asynchronous loading PyRun_SimpleString("try:\n\tfrom scipy import misc, optimize\nexcept:\n\tpass\n"); // If the script directory is not available (e.g. if the interpreter is invoked interactively // or if the script is read from standard input), path[0] is the empty string, // which directs Python to search modules in the current directory first. PyRun_SimpleString(std::string("sys.path.insert(0,\"\")").c_str()); // Add the paths to the plugins' python modules to sys.path. Those paths // are read from all the files in 'etc/sofa/python.d' std::string confDir = Utils::getSofaPathPrefix() + "/etc/sofa/python.d"; if (FileSystem::exists(confDir)) { std::vector<std::string> files; FileSystem::listDirectory(confDir, files); for (size_t i=0; i<files.size(); i++) { addPythonModulePathsFromConfigFile(confDir + "/" + files[i]); } } // Add the directories listed in the SOFAPYTHON_PLUGINS_PATH environnement // variable (colon-separated) to sys.path char * pathVar = getenv("SOFAPYTHON_PLUGINS_PATH"); if (pathVar != NULL) { std::istringstream ss(pathVar); std::string path; while(std::getline(ss, path, ':')) { if (FileSystem::exists(path)) addPythonModulePathsForPlugins(path); else SP_MESSAGE_WARNING("no such directory: '" + path + "'"); } } // python livecoding related PyRun_SimpleString("from SofaPython.livecoding import onReimpAFile"); // general sofa-python stuff PyRun_SimpleString("import SofaPython"); // python modules are automatically reloaded at each scene loading setAutomaticModuleReload( true ); } void PythonEnvironment::Release() { // Finish the Python Interpreter Py_Finalize(); } void PythonEnvironment::addPythonModulePath(const std::string& path) { static std::set<std::string> addedPath; if (addedPath.find(path)==addedPath.end()) { // note not to insert at first 0 place // an empty string must be at first so modules can be found in the current directory first. PyRun_SimpleString(std::string("sys.path.insert(1,\""+path+"\")").c_str()); SP_MESSAGE_INFO("Added '" + path + "' to sys.path"); addedPath.insert(path); } } void PythonEnvironment::addPythonModulePathsFromConfigFile(const std::string& path) { std::ifstream configFile(path.c_str()); std::string line; while(std::getline(configFile, line)) { if (!FileSystem::isAbsolute(line)) { line = Utils::getSofaPathPrefix() + "/" + line; } addPythonModulePath(line); } } void PythonEnvironment::addPythonModulePathsForPlugins(const std::string& pluginsDirectory) { std::vector<std::string> files; FileSystem::listDirectory(pluginsDirectory, files); for (std::vector<std::string>::iterator i = files.begin(); i != files.end(); ++i) { const std::string pluginPath = pluginsDirectory + "/" + *i; if (FileSystem::exists(pluginPath) && FileSystem::isDirectory(pluginPath)) { const std::string pythonDir = pluginPath + "/python"; if (FileSystem::exists(pythonDir) && FileSystem::isDirectory(pythonDir)) { addPythonModulePath(pythonDir); } } } } /* // helper functions sofa::simulation::tree::GNode::SPtr PythonEnvironment::initGraphFromScript( const char *filename ) { PyObject *script = importScript(filename); if (!script) return 0; // the root node GNode::SPtr groot = sofa::core::objectmodel::New<GNode>(); // TODO: passer par une factory groot->setName( "root" ); // groot->setGravity( Coord3(0,-10,0) ); if (!initGraph(script,groot)) groot = 0; else printf("Root node name after pyhton: %s\n",groot->getName().c_str()); Py_DECREF(script); return groot; } */ // some basic RAII stuff to handle init/termination cleanly namespace { struct raii { raii() { // initialization is done when loading the plugin // otherwise it can be executed too soon // when an application is directly linking with the SofaPython library // PythonEnvironment::Init(); } ~raii() { PythonEnvironment::Release(); } }; static raii singleton; } // basic script functions std::string PythonEnvironment::getError() { std::string error; PyObject *ptype, *pvalue /* error msg */, *ptraceback /*stack snapshot and many other informations (see python traceback structure)*/; PyErr_Fetch(&ptype, &pvalue, &ptraceback); if(pvalue) error = PyString_AsString(pvalue); return error; } bool PythonEnvironment::runString(const std::string& script) { PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__")); PyObject* result = PyRun_String(script.data(), Py_file_input, pDict, pDict); if(0 == result) { SP_MESSAGE_ERROR("Script (string) import error") PyErr_Print(); return false; } Py_DECREF(result); return true; } bool PythonEnvironment::runFile( const char *filename, const std::vector<std::string>& arguments) { // SP_MESSAGE_INFO( "Loading python script \""<<filename<<"\"" ) std::string dir = sofa::helper::system::SetDirectory::GetParentDir(filename); std::string bareFilename = sofa::helper::system::SetDirectory::GetFileNameWithoutExtension(filename); // SP_MESSAGE_INFO( "script directory \""<<dir<<"\"" ) // SP_MESSAGE_INFO( commandString.c_str() ) if(!arguments.empty()) { char**argv = new char*[arguments.size()+1]; argv[0] = new char[bareFilename.size()+1]; strcpy( argv[0], bareFilename.c_str() ); for( size_t i=0 ; i<arguments.size() ; ++i ) { argv[i+1] = new char[arguments[i].size()+1]; strcpy( argv[i+1], arguments[i].c_str() ); } Py_SetProgramName(argv[0]); // TODO check what it is doing exactly PySys_SetArgv(arguments.size()+1, argv); for( size_t i=0 ; i<arguments.size()+1 ; ++i ) { delete [] argv[i]; } delete [] argv; } // Py_BEGIN_ALLOW_THREADS // Load the scene script char* pythonFilename = strdup(filename); PyObject* scriptPyFile = PyFile_FromString(pythonFilename, (char*)("r")); free(pythonFilename); if( !scriptPyFile ) { SP_MESSAGE_ERROR("cannot open file:" << filename) PyErr_Print(); return false; } PyObject* pDict = PyModule_GetDict(PyImport_AddModule("__main__")); std::string backupFileName; PyObject* backupFileObject = PyDict_GetItemString(pDict, "__file__"); if(backupFileObject) backupFileName = PyString_AsString(backupFileObject); PyObject* newFileObject = PyString_FromString(filename); PyDict_SetItemString(pDict, "__file__", newFileObject); int error = PyRun_SimpleFileEx(PyFile_AsFile(scriptPyFile), filename, 1); backupFileObject = PyString_FromString(backupFileName.c_str()); PyDict_SetItemString(pDict, "__file__", backupFileObject); // Py_END_ALLOW_THREADS if(0 != error) { SP_MESSAGE_ERROR("Script (file:" << bareFilename << ") import error") PyErr_Print(); return false; } return true; } /* bool PythonEnvironment::initGraph(PyObject *script, sofa::simulation::tree::GNode::SPtr graphRoot) // calls the method "initGraph(root)" of the script { // pDict is a borrowed reference PyObject *pDict = PyModule_GetDict(script); // pFunc is also a borrowed reference PyObject *pFunc = PyDict_GetItemString(pDict, "initGraph"); if (PyCallable_Check(pFunc)) { // PyObject *args = PyTuple_New(1); // PyTuple_SetItem(args,0,object(graphRoot.get()).ptr()); try { //PyObject_CallObject(pFunc, NULL);//args); boost::python::call<int>(pFunc,boost::ref(*graphRoot.get())); } catch (const error_already_set e) { SP_MESSAGE_EXCEPTION("") PyErr_Print(); } // Py_DECREF(args); return true; } else { PyErr_Print(); return false; } } */ void PythonEnvironment::SceneLoaderListerner::rightBeforeLoadingScene() { // unload python modules to force importing their eventual modifications PyRun_SimpleString("SofaPython.unloadModules()"); } void PythonEnvironment::setAutomaticModuleReload( bool b ) { if( b ) SceneLoader::addListener( SceneLoaderListerner::getInstance() ); else SceneLoader::removeListener( SceneLoaderListerner::getInstance() ); } void PythonEnvironment::excludeModuleFromReload( const std::string& moduleName ) { PyRun_SimpleString( std::string( "try: SofaPython.__SofaPythonEnvironment_modulesExcludedFromReload.append('" + moduleName + "')\nexcept:pass" ).c_str() ); } } // namespace simulation } // namespace sofa <|endoftext|>
<commit_before>#include <QString> #include <QSharedPointer> #include <QVector> #include <QUrl> #include <QFileInfo> #include "kernel.h" #include "ilwisdata.h" #include "abstractfactory.h" #include "connectorinterface.h" #include "connectorfactory.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogconnector.h" #include "catalogexplorer.h" #include "domain.h" #include "indexdefinition.h" #include "columndefinition.h" #include "table.h" #include "catalog.h" #include "dataset.h" using namespace Ilwis; CatalogConnector::CatalogConnector(const Resource &resource, bool load ) : IlwisObjectConnector(resource, load) { } bool CatalogConnector::isValid() const { return source().isValid(); } bool CatalogConnector::canUse(const Resource &resource) const { if (_dataProviders.size() == 0) const_cast<CatalogConnector *>(this)->loadExplorers(); for(const auto& explorer : _dataProviders){ if (explorer->canUse(resource)) return true; } return false; } QFileInfo CatalogConnector::toLocalFile(const QUrl &url) const { QString local = url.toLocalFile(); QFileInfo localFile(local); if ( localFile.exists()) return local; int index = local.lastIndexOf("/"); if ( index == -1){ return QFileInfo(); } QString parent = local.left(index); QString ownSection = local.right(local.size() - index - 1); if (Ilwis::Resource::isRoot(parent)){ // we are at the root; '/'has been removed and has to be added again; recursion ends here return local; // we return local here as we don't need to reconstruct our path. local is directly attached to the root and thus has sufficient info } QUrl parentUrl(QUrl::fromLocalFile(parent)); quint64 id = mastercatalog()->url2id(parentUrl, itCATALOG); if ( id == i64UNDEF) return localFile; //return QFileInfo(parent); Resource parentResource = mastercatalog()->id2Resource(id); QFileInfo parentPath = parentResource.toLocalFile(); if ( parentPath.fileName() == sUNDEF) parentPath = parent; QFileInfo currentPath(parentPath.absoluteFilePath() + "/"+ ownSection); return currentPath; } QFileInfo CatalogConnector::toLocalFile(const Resource &resource) const { QFileInfo currentPath = toLocalFile(resource.url()); if ( !currentPath.exists()){ for(const auto& explorer: _dataProviders) { if ( explorer->canUse(resource)){ return explorer->resolve2Local(); } } } return currentPath; } QString CatalogConnector::provider() const { return "ilwis"; } ConnectorInterface *CatalogConnector::create(const Ilwis::Resource &resource, bool load,const IOOptions& options) { return new CatalogConnector(resource, load); } bool CatalogConnector::loadMetaData(IlwisObject *data,const IOOptions &) { return loadExplorers(); } bool CatalogConnector::loadData(IlwisObject *obj, const IOOptions& ){ Catalog *cat = static_cast<Catalog *>(obj); for(const auto& explorer : _dataProviders){ std::vector<Resource> items = explorer->loadItems(); cat->addItemsPrivate(items); } return true; } Ilwis::IlwisObject *CatalogConnector::create() const { if ( source().hasProperty("domain")) return new DataSet(source()); return new Catalog(source()); } bool CatalogConnector::loadExplorers() { if ( _dataProviders.size() > 0) // already done return true; const Ilwis::ConnectorFactory *factory = kernel()->factory<Ilwis::ConnectorFactory>("ilwis::ConnectorFactory"); std::vector<CatalogExplorer*> explorers = factory->explorersForResource(source()); if ( explorers.size() == 0) { return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Catalog connector", source().toLocalFile()); } _dataProviders.resize(explorers.size()); int i =0; for(CatalogExplorer *explorer : explorers) { _dataProviders[i++].reset(explorer); } return true; } <commit_msg>reorder includes<commit_after>#include <QString> #include <QSharedPointer> #include <QVector> #include <QUrl> #include <QFileInfo> #include "kernel.h" #include "ilwisdata.h" #include "abstractfactory.h" #include "connectorinterface.h" #include "connectorfactory.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogconnector.h" #include "catalogexplorer.h" #include "domain.h" #include "datadefinition.h" #include "columndefinition.h" #include "table.h" #include "catalog.h" #include "dataset.h" using namespace Ilwis; CatalogConnector::CatalogConnector(const Resource &resource, bool load ) : IlwisObjectConnector(resource, load) { } bool CatalogConnector::isValid() const { return source().isValid(); } bool CatalogConnector::canUse(const Resource &resource) const { if (_dataProviders.size() == 0) const_cast<CatalogConnector *>(this)->loadExplorers(); for(const auto& explorer : _dataProviders){ if (explorer->canUse(resource)) return true; } return false; } QFileInfo CatalogConnector::toLocalFile(const QUrl &url) const { QString local = url.toLocalFile(); QFileInfo localFile(local); if ( localFile.exists()) return local; int index = local.lastIndexOf("/"); if ( index == -1){ return QFileInfo(); } QString parent = local.left(index); QString ownSection = local.right(local.size() - index - 1); if (Ilwis::Resource::isRoot(parent)){ // we are at the root; '/'has been removed and has to be added again; recursion ends here return local; // we return local here as we don't need to reconstruct our path. local is directly attached to the root and thus has sufficient info } QUrl parentUrl(QUrl::fromLocalFile(parent)); quint64 id = mastercatalog()->url2id(parentUrl, itCATALOG); if ( id == i64UNDEF) return localFile; //return QFileInfo(parent); Resource parentResource = mastercatalog()->id2Resource(id); QFileInfo parentPath = parentResource.toLocalFile(); if ( parentPath.fileName() == sUNDEF) parentPath = parent; QFileInfo currentPath(parentPath.absoluteFilePath() + "/"+ ownSection); return currentPath; } QFileInfo CatalogConnector::toLocalFile(const Resource &resource) const { QFileInfo currentPath = toLocalFile(resource.url()); if ( !currentPath.exists()){ for(const auto& explorer: _dataProviders) { if ( explorer->canUse(resource)){ return explorer->resolve2Local(); } } } return currentPath; } QString CatalogConnector::provider() const { return "ilwis"; } ConnectorInterface *CatalogConnector::create(const Ilwis::Resource &resource, bool load,const IOOptions& options) { return new CatalogConnector(resource, load); } bool CatalogConnector::loadMetaData(IlwisObject *data,const IOOptions &) { return loadExplorers(); } bool CatalogConnector::loadData(IlwisObject *obj, const IOOptions& ){ Catalog *cat = static_cast<Catalog *>(obj); for(const auto& explorer : _dataProviders){ std::vector<Resource> items = explorer->loadItems(); cat->addItemsPrivate(items); } return true; } Ilwis::IlwisObject *CatalogConnector::create() const { if ( source().hasProperty("domain")) return new DataSet(source()); return new Catalog(source()); } bool CatalogConnector::loadExplorers() { if ( _dataProviders.size() > 0) // already done return true; const Ilwis::ConnectorFactory *factory = kernel()->factory<Ilwis::ConnectorFactory>("ilwis::ConnectorFactory"); std::vector<CatalogExplorer*> explorers = factory->explorersForResource(source()); if ( explorers.size() == 0) { return ERROR2(ERR_COULDNT_CREATE_OBJECT_FOR_2,"Catalog connector", source().toLocalFile()); } _dataProviders.resize(explorers.size()); int i =0; for(CatalogExplorer *explorer : explorers) { _dataProviders[i++].reset(explorer); } return true; } <|endoftext|>